3 * David L. Nugent. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 static const char rcsid[] =
33 #include <sys/param.h>
34 #include <sys/resource.h>
36 #include <sys/types.h>
46 #include <login_cap.h>
57 #define LOGNAMESIZE (MAXLOGNAME-1)
59 static char locked_str[] = "*LOCKED*";
61 static struct passwd fakeuser = {
75 static int print_user(struct passwd *pwd, bool pretty, bool v7);
76 static uid_t pw_uidpolicy(struct userconf *cnf, intmax_t id);
77 static uid_t pw_gidpolicy(struct userconf *cnf, char *grname, char *nam,
78 gid_t prefer, bool dryrun);
79 static char *pw_homepolicy(struct userconf * cnf, char *homedir,
81 static char *pw_shellpolicy(struct userconf * cnf);
82 static char *pw_password(struct userconf * cnf, char const * user,
84 static char *shell_path(char const * path, char *shells[], char *sh);
85 static void rmat(uid_t uid);
86 static void rmopie(char const * name);
89 mkdir_home_parents(int dfd, const char *dir)
95 errx(EX_DATAERR, "invalid base directory for home '%s'", dir);
99 if (fstatat(dfd, dir, &st, 0) != -1) {
100 if (S_ISDIR(st.st_mode))
102 errx(EX_OSFILE, "root home `/%s' is not a directory", dir);
107 errx(EX_UNAVAILABLE, "out of memory");
109 tmp = strrchr(dirs, '/');
115 * This is a kludge especially for Joerg :)
116 * If the home directory would be created in the root partition, then
117 * we really create it under /usr which is likely to have more space.
118 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
120 if (strchr(dirs, '/') == NULL) {
121 asprintf(&tmp, "usr/%s", dirs);
123 errx(EX_UNAVAILABLE, "out of memory");
124 if (mkdirat(dfd, tmp, _DEF_DIRMODE) != -1 || errno == EEXIST) {
125 fchownat(dfd, tmp, 0, 0, 0);
126 symlinkat(tmp, dfd, dirs);
131 if (fstatat(dfd, dirs, &st, 0) == -1) {
132 while ((tmp = strchr(tmp + 1, '/')) != NULL) {
134 if (fstatat(dfd, dirs, &st, 0) == -1) {
135 if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
136 err(EX_OSFILE, "'%s' (root home parent) is not a directory", dirs);
141 if (fstatat(dfd, dirs, &st, 0) == -1) {
142 if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
143 err(EX_OSFILE, "'%s' (root home parent) is not a directory", dirs);
144 fchownat(dfd, dirs, 0, 0, 0);
151 create_and_populate_homedir(struct userconf *cnf, struct passwd *pwd,
152 const char *skeldir, mode_t homemode, bool update)
156 /* Create home parents directories */
157 mkdir_home_parents(conf.rootfd, pwd->pw_dir);
159 if (skeldir != NULL && *skeldir != '\0') {
162 skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
165 copymkdir(conf.rootfd, pwd->pw_dir, skelfd, homemode, pwd->pw_uid,
167 pw_log(cnf, update ? M_UPDATE : M_ADD, W_USER, "%s(%ju) home %s made",
168 pwd->pw_name, (uintmax_t)pwd->pw_uid, pwd->pw_dir);
172 pw_set_passwd(struct passwd *pwd, int fd, bool precrypted, bool update)
177 char line[_PASSWORD_LEN+1];
181 if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
182 pwd->pw_passwd = "*"; /* No access */
188 if ((istty = isatty(fd))) {
189 if (tcgetattr(fd, &t) == -1)
193 n.c_lflag &= ~(ECHO);
194 tcsetattr(fd, TCSANOW, &n);
195 printf("%s%spassword for user %s:",
196 update ? "new " : "",
197 precrypted ? "encrypted " : "",
202 b = read(fd, line, sizeof(line) - 1);
203 if (istty) { /* Restore state */
204 tcsetattr(fd, TCSANOW, &t);
210 err(EX_IOERR, "-%c file descriptor",
211 precrypted ? 'H' : 'h');
213 if ((p = strpbrk(line, "\r\n")) != NULL)
216 errx(EX_DATAERR, "empty password read on file descriptor %d",
219 if (strchr(line, ':') != NULL)
220 errx(EX_DATAERR, "bad encrypted password");
221 pwd->pw_passwd = strdup(line);
223 lc = login_getpwclass(pwd);
225 login_setcryptfmt(lc, "sha512", NULL) == NULL)
226 warn("setting crypt(3) format");
228 pwd->pw_passwd = pw_pwcrypt(line);
234 perform_chgpwent(const char *name, struct passwd *pwd, char *nispasswd)
237 struct passwd *nispwd;
239 /* duplicate for nis so that chgpwent is not modifying before NIS */
240 if (nispasswd && *nispasswd == '/')
241 nispwd = pw_dup(pwd);
243 rc = chgpwent(name, pwd);
245 errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
247 err(EX_IOERR, "passwd file update");
249 if (nispasswd && *nispasswd == '/') {
250 rc = chgnispwent(nispasswd, name, nispwd);
252 warn("User '%s' not found in NIS passwd", pwd->pw_name);
254 warn("NIS passwd update");
255 /* NOTE: NIS-only update errors are not fatal */
260 * The M_LOCK and M_UNLOCK functions simply add or remove
261 * a "*LOCKED*" prefix from in front of the password to
262 * prevent it decoding correctly, and therefore prevents
263 * access. Of course, this only prevents access via
264 * password authentication (not ssh, kerberos or any
265 * other method that does not use the UNIX password) but
266 * that is a known limitation.
269 pw_userlock(char *arg1, int mode)
271 struct passwd *pwd = NULL;
272 char *passtmp = NULL;
278 errx(EX_NOPERM, "you must be root");
281 errx(EX_DATAERR, "username or id required");
283 if (arg1[strspn(arg1, "0123456789")] == '\0') {
284 id = pw_checkid(arg1, UID_MAX);
289 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
292 errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
293 errx(EX_NOUSER, "no such user `%s'", name);
299 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
301 if (mode == M_LOCK && locked)
302 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
303 if (mode == M_UNLOCK && !locked)
304 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
306 if (mode == M_LOCK) {
307 asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
308 if (passtmp == NULL) /* disaster */
309 errx(EX_UNAVAILABLE, "out of memory");
310 pwd->pw_passwd = passtmp;
312 pwd->pw_passwd += sizeof(locked_str)-1;
315 perform_chgpwent(name, pwd, NULL);
318 return (EXIT_SUCCESS);
322 pw_uidpolicy(struct userconf * cnf, intmax_t id)
326 uid_t uid = (uid_t) - 1;
329 * Check the given uid, if any
334 if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
335 errx(EX_DATAERR, "uid `%ju' has already been allocated",
336 (uintmax_t)pwd->pw_uid);
340 * We need to allocate the next available uid under one of
341 * two policies a) Grab the first unused uid b) Grab the
342 * highest possible unused uid
344 if (cnf->min_uid >= cnf->max_uid) { /* Sanity
345 * claus^H^H^H^Hheck */
347 cnf->max_uid = 32000;
349 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
352 * Now, let's fill the bitmap from the password file
355 while ((pwd = GETPWENT()) != NULL)
356 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
357 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
361 * Then apply the policy, with fallback to reuse if necessary
363 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
364 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
367 * Another sanity check
369 if (uid < cnf->min_uid || uid > cnf->max_uid)
370 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
376 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam, gid_t prefer, bool dryrun)
379 gid_t gid = (uid_t) - 1;
382 * Check the given gid, if any
386 if ((grp = GETGRNAM(grname)) == NULL) {
387 gid = pw_checkid(grname, GID_MAX);
391 } else if ((grp = GETGRNAM(nam)) != NULL &&
392 (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
393 gid = grp->gr_gid; /* Already created? Use it anyway... */
398 * We need to auto-create a group with the user's name. We
399 * can send all the appropriate output to our sister routine
400 * bit first see if we can create a group with gid==uid so we
401 * can keep the user and group ids in sync. We purposely do
402 * NOT check the gid range if we can force the sync. If the
403 * user's name dups an existing group, then the group add
404 * function will happily handle that case for us and exit.
406 if (GETGRGID(prefer) == NULL)
409 gid = pw_groupnext(cnf, true);
412 grid = pw_groupnext(cnf, true);
413 groupadd(cnf, nam, grid, NULL, -1, false, false, false);
414 if ((grp = GETGRNAM(nam)) != NULL)
423 pw_homepolicy(struct userconf * cnf, char *homedir, const char *user)
425 static char home[128];
430 if (cnf->home == NULL || *cnf->home == '\0')
431 errx(EX_CONFIG, "no base home directory set");
432 snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
438 shell_path(char const * path, char *shells[], char *sh)
440 if (sh != NULL && (*sh == '/' || *sh == '\0'))
441 return sh; /* specified full path or forced none */
444 char paths[_UC_MAXLINE];
447 * We need to search paths
449 strlcpy(paths, path, sizeof(paths));
450 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
452 static char shellpath[256];
455 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
456 if (access(shellpath, X_OK) == 0)
459 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
460 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
461 if (access(shellpath, X_OK) == 0)
466 errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
467 errx(EX_CONFIG, "no default shell available or defined");
473 pw_shellpolicy(struct userconf * cnf)
476 return shell_path(cnf->shelldir, cnf->shells, cnf->shell_default);
481 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
484 pw_pwcrypt(char *password)
487 char salt[SALTSIZE + 1];
489 static char buf[256];
492 * Calculate a salt value
494 for (i = 0; i < SALTSIZE; i++)
495 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
496 salt[SALTSIZE] = '\0';
498 cryptpw = crypt(password, salt);
500 errx(EX_CONFIG, "crypt(3) failure");
501 return strcpy(buf, cryptpw);
505 pw_password(struct userconf * cnf, char const * user, bool dryrun)
510 switch (cnf->default_password) {
511 case -1: /* Random password */
512 l = (arc4random() % 8 + 8); /* 8 - 16 chars */
513 for (i = 0; i < l; i++)
514 pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
518 * We give this information back to the user
520 if (conf.fd == -1 && !dryrun) {
521 if (isatty(STDOUT_FILENO))
522 printf("Password for '%s' is: ", user);
523 printf("%s\n", pwbuf);
528 case -2: /* No password at all! */
531 case 0: /* No login - default */
535 case 1: /* user's name */
536 strlcpy(pwbuf, user, sizeof(pwbuf));
539 return pw_pwcrypt(pwbuf);
543 print_user(struct passwd * pwd, bool pretty, bool v7)
547 struct group *grp = GETGRGID(pwd->pw_gid);
548 char uname[60] = "User &", office[60] = "[None]",
549 wphone[60] = "[None]", hphone[60] = "[None]";
550 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
554 p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
557 return (EXIT_SUCCESS);
560 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
561 strlcpy(uname, p, sizeof(uname));
562 if ((p = strtok(NULL, ",")) != NULL) {
563 strlcpy(office, p, sizeof(office));
564 if ((p = strtok(NULL, ",")) != NULL) {
565 strlcpy(wphone, p, sizeof(wphone));
566 if ((p = strtok(NULL, "")) != NULL) {
567 strlcpy(hphone, p, sizeof(hphone));
573 * Handle '&' in gecos field
575 if ((p = strchr(uname, '&')) != NULL) {
576 int l = strlen(pwd->pw_name);
579 memmove(p + l, p + 1, m);
580 memmove(p, pwd->pw_name, l);
581 *p = (char) toupper((unsigned char)*p);
583 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
584 strftime(acexpire, sizeof acexpire, "%c", tptr);
585 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
586 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
587 printf("Login Name: %-15s #%-12ju Group: %-15s #%ju\n"
589 " Home: %-26.26s Class: %s\n"
590 " Shell: %-26.26s Office: %s\n"
591 "Work Phone: %-26.26s Home Phone: %s\n"
592 "Acc Expire: %-26.26s Pwd Expire: %s\n",
593 pwd->pw_name, (uintmax_t)pwd->pw_uid,
594 grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
595 uname, pwd->pw_dir, pwd->pw_class,
596 pwd->pw_shell, office, wphone, hphone,
600 while ((grp=GETGRENT()) != NULL) {
602 if (grp->gr_mem != NULL) {
603 while (grp->gr_mem[i] != NULL) {
604 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
605 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
613 printf("%s", j ? "\n" : "");
614 return (EXIT_SUCCESS);
618 pw_checkname(char *name, int gecos)
621 const char *badchars, *ch, *showtype;
627 /* See if the name is valid as a gecos (comment) field. */
629 showtype = "gecos field";
631 /* See if the name is valid as a userid or group. */
632 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
633 showtype = "userid/group name";
634 /* Userids and groups can not have a leading '-'. */
640 if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
645 /* 8-bit characters are only allowed in GECOS fields */
646 if (!gecos && (*ch & 0x80)) {
654 * A `$' is allowed as the final character for userids and groups,
655 * mainly for the benefit of samba.
657 if (reject && !gecos) {
658 if (*ch == '$' && *(ch + 1) == '\0') {
664 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
665 ? "`%c'" : "0x%02x", *ch);
666 errx(EX_DATAERR, "invalid character %s at position %td in %s",
667 showch, (ch - name), showtype);
669 if (!gecos && (ch - name) > LOGNAMESIZE)
670 errx(EX_USAGE, "name too long `%s' (max is %d)", name,
679 DIR *d = opendir("/var/at/jobs");
684 while ((e = readdir(d)) != NULL) {
687 if (strncmp(e->d_name, ".lock", 5) != 0 &&
688 stat(e->d_name, &st) == 0 &&
689 !S_ISDIR(st.st_mode) &&
691 char tmp[MAXPATHLEN];
693 snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s",
703 rmopie(char const * name)
711 if ((fd = openat(conf.rootfd, "etc/opiekeys", O_RDWR)) == -1)
714 fp = fdopen(fd, "r+");
717 while (fgets(tmp, sizeof(tmp), fp) != NULL) {
718 if (strncmp(name, tmp, len) == 0 && tmp[len]==' ') {
719 /* Comment username out */
720 if (fseek(fp, atofs, SEEK_SET) == 0)
721 fwrite("#", 1, 1, fp);
727 * If we got an error of any sort, don't update!
733 pw_user_next(int argc, char **argv, char *name __unused)
735 struct userconf *cnf = NULL;
736 const char *cfg = NULL;
741 while ((ch = getopt(argc, argv, "Cq")) != -1) {
753 freopen(_PATH_DEVNULL, "w", stderr);
755 cnf = get_userconfig(cfg);
757 next = pw_uidpolicy(cnf, -1);
759 printf("%ju:", (uintmax_t)next);
760 pw_groupnext(cnf, quiet);
762 return (EXIT_SUCCESS);
766 pw_user_show(int argc, char **argv, char *arg1)
768 struct passwd *pwd = NULL;
779 if (arg1[strspn(arg1, "0123456789")] == '\0')
780 id = pw_checkid(arg1, UID_MAX);
785 while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
788 /* ignore compatibility */
797 id = pw_checkid(optarg, UID_MAX);
815 freopen(_PATH_DEVNULL, "w", stderr);
819 while ((pwd = GETPWENT()) != NULL)
820 print_user(pwd, pretty, v7);
822 return (EXIT_SUCCESS);
825 if (id < 0 && name == NULL)
826 errx(EX_DATAERR, "username or id required");
828 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
834 errx(EX_NOUSER, "no such uid `%ju'",
836 errx(EX_NOUSER, "no such user `%s'", name);
840 return (print_user(pwd, pretty, v7));
844 pw_user_del(int argc, char **argv, char *arg1)
846 struct userconf *cnf = NULL;
847 struct passwd *pwd = NULL;
848 struct group *gr, *grp;
850 char grname[MAXLOGNAME];
851 char *nispasswd = NULL;
852 char file[MAXPATHLEN];
853 char home[MAXPATHLEN];
854 const char *cfg = NULL;
859 bool deletehome = false;
863 if (arg1[strspn(arg1, "0123456789")] == '\0')
864 id = pw_checkid(arg1, UID_MAX);
869 while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
881 id = pw_checkid(optarg, UID_MAX);
896 freopen(_PATH_DEVNULL, "w", stderr);
898 if (id < 0 && name == NULL)
899 errx(EX_DATAERR, "username or id required");
901 cnf = get_userconfig(cfg);
903 if (nispasswd == NULL)
904 nispasswd = cnf->nispasswd;
906 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
909 errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
910 errx(EX_NOUSER, "no such user `%s'", name);
913 if (PWF._altdir == PWF_REGULAR &&
914 ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
915 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
916 if (!nis && nispasswd && *nispasswd != '/')
917 errx(EX_NOUSER, "Cannot remove NIS user `%s'",
920 errx(EX_NOUSER, "Cannot remove non local user `%s'",
929 if (strcmp(pwd->pw_name, "root") == 0)
930 errx(EX_DATAERR, "cannot remove user 'root'");
932 /* Remove opie record from /etc/opiekeys */
933 if (PWALTDIR() != PWF_ALT)
934 rmopie(pwd->pw_name);
937 /* Remove crontabs */
938 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
939 if (access(file, F_OK) == 0) {
940 snprintf(file, sizeof(file), "crontab -u %s -r",
947 * Save these for later, since contents of pwd may be
948 * invalidated by deletion
950 snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
951 strlcpy(home, pwd->pw_dir, sizeof(home));
952 gr = GETGRGID(pwd->pw_gid);
954 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
960 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
962 err(EX_IOERR, "passwd update");
964 if (nis && nispasswd && *nispasswd=='/') {
965 rc = delnispwent(nispasswd, name);
967 warnx("WARNING: user '%s' does not exist in NIS passwd",
970 warn("WARNING: NIS passwd update");
973 grp = GETGRNAM(name);
975 (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
976 strcmp(name, grname) == 0)
977 delgrent(GETGRNAM(name));
979 while ((grp = GETGRENT()) != NULL) {
981 char group[MAXLOGNAME];
982 if (grp->gr_mem == NULL)
985 for (i = 0; grp->gr_mem[i] != NULL; i++) {
986 if (strcmp(grp->gr_mem[i], name) != 0)
989 for (j = i; grp->gr_mem[j] != NULL; j++)
990 grp->gr_mem[j] = grp->gr_mem[j+1];
991 strlcpy(group, grp->gr_name, MAXLOGNAME);
992 chggrent(group, grp);
997 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
1000 /* Remove mail file */
1001 if (PWALTDIR() != PWF_ALT)
1002 unlinkat(conf.rootfd, file + 1, 0);
1004 /* Remove at jobs */
1005 if (!PWALTDIR() && getpwuid(id) == NULL)
1008 /* Remove home directory and contents */
1009 if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
1010 GETPWUID(id) == NULL &&
1011 fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1012 rm_r(conf.rootfd, home, id);
1013 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
1014 "removed", name, (uintmax_t)id, home,
1015 fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1019 return (EXIT_SUCCESS);
1023 pw_user_lock(int argc, char **argv, char *arg1)
1027 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1036 return (pw_userlock(arg1, M_LOCK));
1040 pw_user_unlock(int argc, char **argv, char *arg1)
1044 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1053 return (pw_userlock(arg1, M_UNLOCK));
1056 static struct group *
1057 group_from_name_or_id(char *name)
1059 const char *errstr = NULL;
1063 if ((grp = GETGRNAM(name)) == NULL) {
1064 id = strtounum(name, 0, GID_MAX, &errstr);
1066 errx(EX_NOUSER, "group `%s' does not exist", name);
1069 errx(EX_NOUSER, "group `%s' does not exist", name);
1076 split_groups(StringList **groups, char *groupsstr)
1080 char tok[] = ", \t";
1082 for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1083 grp = group_from_name_or_id(p);
1084 if (*groups == NULL)
1085 *groups = sl_init();
1086 sl_add(*groups, newstr(grp->gr_name));
1091 validate_grname(struct userconf *cnf, char *group)
1095 if (group == NULL || *group == '\0') {
1096 cnf->default_group = "";
1099 grp = group_from_name_or_id(group);
1100 cnf->default_group = newstr(grp->gr_name);
1104 validate_mode(char *mode)
1109 if ((set = setmode(mode)) == NULL)
1110 errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1112 m = getmode(set, _DEF_DIRMODE);
1118 mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1121 if (cmdcnf->default_password == 0)
1122 cmdcnf->default_password = cfg->default_password;
1123 if (cmdcnf->reuse_uids == 0)
1124 cmdcnf->reuse_uids = cfg->reuse_uids;
1125 if (cmdcnf->reuse_gids == 0)
1126 cmdcnf->reuse_gids = cfg->reuse_gids;
1127 if (cmdcnf->nispasswd == NULL)
1128 cmdcnf->nispasswd = cfg->nispasswd;
1129 if (cmdcnf->dotdir == NULL)
1130 cmdcnf->dotdir = cfg->dotdir;
1131 if (cmdcnf->newmail == NULL)
1132 cmdcnf->newmail = cfg->newmail;
1133 if (cmdcnf->logfile == NULL)
1134 cmdcnf->logfile = cfg->logfile;
1135 if (cmdcnf->home == NULL)
1136 cmdcnf->home = cfg->home;
1137 if (cmdcnf->homemode == 0)
1138 cmdcnf->homemode = cfg->homemode;
1139 if (cmdcnf->shelldir == NULL)
1140 cmdcnf->shelldir = cfg->shelldir;
1141 if (cmdcnf->shells == NULL)
1142 cmdcnf->shells = cfg->shells;
1143 if (cmdcnf->shell_default == NULL)
1144 cmdcnf->shell_default = cfg->shell_default;
1145 if (cmdcnf->default_group == NULL)
1146 cmdcnf->default_group = cfg->default_group;
1147 if (cmdcnf->groups == NULL)
1148 cmdcnf->groups = cfg->groups;
1149 if (cmdcnf->default_class == NULL)
1150 cmdcnf->default_class = cfg->default_class;
1151 if (cmdcnf->min_uid == 0)
1152 cmdcnf->min_uid = cfg->min_uid;
1153 if (cmdcnf->max_uid == 0)
1154 cmdcnf->max_uid = cfg->max_uid;
1155 if (cmdcnf->min_gid == 0)
1156 cmdcnf->min_gid = cfg->min_gid;
1157 if (cmdcnf->max_gid == 0)
1158 cmdcnf->max_gid = cfg->max_gid;
1159 if (cmdcnf->expire_days == 0)
1160 cmdcnf->expire_days = cfg->expire_days;
1161 if (cmdcnf->password_days == 0)
1162 cmdcnf->password_days = cfg->password_days;
1166 pw_user_add(int argc, char **argv, char *arg1)
1168 struct userconf *cnf, *cmdcnf;
1172 char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1173 char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1174 char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1175 char *default_passwd, *name, *p;
1181 int rc, ch, fd = -1;
1183 bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1185 dryrun = nis = pretty = quiet = createhome = precrypted = false;
1187 gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1188 grname = name = NULL;
1190 if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1191 err(EXIT_FAILURE, "calloc()");
1194 if (arg1[strspn(arg1, "0123456789")] == '\0')
1195 id = pw_checkid(arg1, UID_MAX);
1200 while ((ch = getopt(argc, argv, args)) != -1) {
1215 gecos = pw_checkname(optarg, 1);
1222 cmdcnf->expire_days = parse_date(now, optarg);
1226 cmdcnf->password_days = parse_date(now, optarg);
1229 validate_grname(cmdcnf, optarg);
1233 split_groups(&cmdcnf->groups, optarg);
1239 cmdcnf->homemode = validate_mode(optarg);
1242 walk = skel = optarg;
1245 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1246 errx(EX_OSFILE, "skeleton `%s' does not "
1248 if (!S_ISDIR(st.st_mode))
1249 errx(EX_OSFILE, "skeleton `%s' is not a "
1251 cmdcnf->dotdir = skel;
1254 cmdcnf->shell_default = optarg;
1257 conf.checkduplicate = false;
1260 cmdcnf->default_class = pw_checkname(optarg, 0);
1266 default_passwd = optarg;
1270 errx(EX_USAGE, "'-h' and '-H' are mutually "
1271 "exclusive options");
1272 fd = pw_checkfd(optarg);
1275 errx(EX_USAGE, "-H expects a file descriptor");
1279 errx(EX_USAGE, "'-h' and '-H' are mutually "
1280 "exclusive options");
1281 fd = pw_checkfd(optarg);
1287 cmdcnf->home = optarg;
1296 cmdcnf->nispasswd = optarg;
1304 if (geteuid() != 0 && ! dryrun)
1305 errx(EX_NOPERM, "you must be root");
1308 freopen(_PATH_DEVNULL, "w", stderr);
1310 cnf = get_userconfig(cfg);
1312 mix_config(cmdcnf, cnf);
1314 cmdcnf->default_password = boolean_val(default_passwd,
1315 cnf->default_password);
1318 errx(EX_DATAERR, "can't combine `-D' with `-n name'");
1319 if (userid != NULL) {
1320 if ((p = strtok(userid, ", \t")) != NULL)
1321 cmdcnf->min_uid = pw_checkid(p, UID_MAX);
1322 if (cmdcnf->min_uid == 0)
1323 cmdcnf->min_uid = 1000;
1324 if ((p = strtok(NULL, " ,\t")) != NULL)
1325 cmdcnf->max_uid = pw_checkid(p, UID_MAX);
1326 if (cmdcnf->max_uid == 0)
1327 cmdcnf->max_uid = 32000;
1329 if (groupid != NULL) {
1330 if ((p = strtok(groupid, ", \t")) != NULL)
1331 cmdcnf->min_gid = pw_checkid(p, GID_MAX);
1332 if (cmdcnf->min_gid == 0)
1333 cmdcnf->min_gid = 1000;
1334 if ((p = strtok(NULL, " ,\t")) != NULL)
1335 cmdcnf->max_gid = pw_checkid(p, GID_MAX);
1336 if (cmdcnf->max_gid == 0)
1337 cmdcnf->max_gid = 32000;
1339 if (write_userconfig(cmdcnf, cfg))
1340 return (EXIT_SUCCESS);
1341 err(EX_IOERR, "config update");
1345 id = pw_checkid(userid, UID_MAX);
1346 if (id < 0 && name == NULL)
1347 errx(EX_DATAERR, "user name or id required");
1350 errx(EX_DATAERR, "login name required");
1352 if (GETPWNAM(name) != NULL)
1353 errx(EX_DATAERR, "login name `%s' already exists", name);
1356 pwd->pw_name = name;
1357 pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1358 pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1359 pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1360 (gid_t) pwd->pw_uid, dryrun);
1361 pwd->pw_change = cmdcnf->password_days;
1362 pwd->pw_expire = cmdcnf->expire_days;
1363 pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1364 pwd->pw_shell = pw_shellpolicy(cmdcnf);
1365 lc = login_getpwclass(pwd);
1366 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1367 warn("setting crypt(3) format");
1369 pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name, dryrun);
1370 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1371 warnx("WARNING: new account `%s' has a uid of 0 "
1372 "(superuser access!)", pwd->pw_name);
1374 pwd->pw_gecos = gecos;
1377 pw_set_passwd(pwd, fd, precrypted, false);
1380 return (print_user(pwd, pretty, false));
1382 if ((rc = addpwent(pwd)) != 0) {
1384 errx(EX_IOERR, "user '%s' already exists",
1387 err(EX_IOERR, "passwd file update");
1389 if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1390 printf("%s\n", cmdcnf->nispasswd);
1391 rc = addnispwent(cmdcnf->nispasswd, pwd);
1393 warnx("User '%s' already exists in NIS passwd",
1396 warn("NIS passwd update");
1397 /* NOTE: we treat NIS-only update errors as non-fatal */
1400 if (cmdcnf->groups != NULL) {
1401 for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1402 grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1403 grp = gr_add(grp, pwd->pw_name);
1405 * grp can only be NULL in 2 cases:
1406 * - the new member is already a member
1407 * - a problem with memory occurs
1408 * in both cases we want to skip now.
1412 chggrent(grp->gr_name, grp);
1417 pwd = GETPWNAM(name);
1419 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1421 grp = GETGRGID(pwd->pw_gid);
1422 pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1423 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1424 grp ? grp->gr_name : "unknown",
1425 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1426 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1429 * let's touch and chown the user's mail file. This is not
1430 * strictly necessary under BSD with a 0755 maildir but it also
1431 * doesn't hurt anything to create the empty mailfile
1433 if (PWALTDIR() != PWF_ALT) {
1434 snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1436 /* Preserve contents & mtime */
1437 close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1438 fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1439 AT_SYMLINK_NOFOLLOW);
1443 * Let's create and populate the user's home directory. Note
1444 * that this also `works' for editing users if -m is used, but
1445 * existing files will *not* be overwritten.
1447 if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1448 *pwd->pw_dir == '/' && pwd->pw_dir[1])
1449 create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1450 cmdcnf->homemode, false);
1452 if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1453 (fp = fopen(cnf->newmail, "r")) != NULL) {
1454 if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1457 fprintf(pfp, "From: root\n" "To: %s\n"
1458 "Subject: Welcome!\n\n", pwd->pw_name);
1459 while (fgets(line, sizeof(line), fp) != NULL) {
1460 /* Do substitutions? */
1464 pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1465 pwd->pw_name, (uintmax_t)pwd->pw_uid);
1470 if (nis && nis_update() == 0)
1471 pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1473 return (EXIT_SUCCESS);
1477 pw_user_mod(int argc, char **argv, char *arg1)
1479 struct userconf *cnf;
1482 StringList *groups = NULL;
1483 char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1485 char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1486 char *passwd, *class, *nispasswd;
1492 bool quiet, createhome, pretty, dryrun, nis, edited, docreatehome;
1494 mode_t homemode = 0;
1495 time_t expire_days, password_days, now;
1497 expire_days = password_days = -1;
1498 gecos = homedir = grname = name = newname = skel = shell =NULL;
1500 class = nispasswd = NULL;
1501 quiet = createhome = pretty = dryrun = nis = precrypted = false;
1502 edited = docreatehome = false;
1505 if (arg1[strspn(arg1, "0123456789")] == '\0')
1506 id = pw_checkid(arg1, UID_MAX);
1511 while ((ch = getopt(argc, argv, args)) != -1) {
1523 id = pw_checkid(optarg, UID_MAX);
1526 gecos = pw_checkname(optarg, 1);
1533 expire_days = parse_date(now, optarg);
1537 password_days = parse_date(now, optarg);
1540 group_from_name_or_id(optarg);
1544 split_groups(&groups, optarg);
1550 homemode = validate_mode(optarg);
1556 walk = skel = optarg;
1559 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1560 errx(EX_OSFILE, "skeleton `%s' does not "
1562 if (!S_ISDIR(st.st_mode))
1563 errx(EX_OSFILE, "skeleton `%s' is not a "
1573 class = pw_checkname(optarg, 0);
1577 errx(EX_USAGE, "'-h' and '-H' are mutually "
1578 "exclusive options");
1579 fd = pw_checkfd(optarg);
1582 errx(EX_USAGE, "-H expects a file descriptor");
1586 errx(EX_USAGE, "'-h' and '-H' are mutually "
1587 "exclusive options");
1588 fd = pw_checkfd(optarg);
1605 if (geteuid() != 0 && ! dryrun)
1606 errx(EX_NOPERM, "you must be root");
1609 freopen(_PATH_DEVNULL, "w", stderr);
1611 cnf = get_userconfig(cfg);
1613 if (id < 0 && name == NULL)
1614 errx(EX_DATAERR, "username or id required");
1616 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1619 errx(EX_NOUSER, "no such uid `%ju'",
1621 errx(EX_NOUSER, "no such user `%s'", name);
1625 name = pwd->pw_name;
1627 if (nis && nispasswd == NULL)
1628 nispasswd = cnf->nispasswd;
1630 if (PWF._altdir == PWF_REGULAR &&
1631 ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
1632 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
1633 if (!nis && nispasswd && *nispasswd != '/')
1634 errx(EX_NOUSER, "Cannot modify NIS user `%s'",
1637 errx(EX_NOUSER, "Cannot modify non local user `%s'",
1643 if (strcmp(pwd->pw_name, "root") == 0)
1644 errx(EX_DATAERR, "can't rename `root' account");
1645 if (strcmp(pwd->pw_name, newname) != 0) {
1646 pwd->pw_name = pw_checkname(newname, 0);
1651 if (id > 0 && pwd->pw_uid != id) {
1654 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
1655 errx(EX_DATAERR, "can't change uid of `root' account");
1656 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1657 warnx("WARNING: account `%s' will have a uid of 0 "
1658 "(superuser access!)", pwd->pw_name);
1661 if (grname && pwd->pw_uid != 0) {
1662 grp = GETGRNAM(grname);
1664 grp = GETGRGID(pw_checkid(grname, GID_MAX));
1665 if (grp->gr_gid != pwd->pw_gid) {
1666 pwd->pw_gid = grp->gr_gid;
1671 if (password_days >= 0 && pwd->pw_change != password_days) {
1672 pwd->pw_change = password_days;
1676 if (expire_days >= 0 && pwd->pw_expire != expire_days) {
1677 pwd->pw_expire = expire_days;
1682 shell = shell_path(cnf->shelldir, cnf->shells, shell);
1685 if (strcmp(shell, pwd->pw_shell) != 0) {
1686 pwd->pw_shell = shell;
1691 if (class && strcmp(pwd->pw_class, class) != 0) {
1692 pwd->pw_class = class;
1696 if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1697 pwd->pw_dir = homedir;
1699 if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1701 warnx("WARNING: home `%s' does not exist",
1704 docreatehome = true;
1705 } else if (!S_ISDIR(st.st_mode)) {
1706 warnx("WARNING: home `%s' is not a directory",
1711 if (passwd && conf.fd == -1) {
1712 lc = login_getpwclass(pwd);
1713 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1714 warn("setting crypt(3) format");
1716 cnf->default_password = boolean_val(passwd,
1717 cnf->default_password);
1718 pwd->pw_passwd = pw_password(cnf, pwd->pw_name, dryrun);
1722 if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1723 pwd->pw_gecos = gecos;
1728 edited = pw_set_passwd(pwd, fd, precrypted, true);
1731 return (print_user(pwd, pretty, false));
1733 if (edited) /* Only updated this if required */
1734 perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1735 /* Now perform the needed changes concern groups */
1736 if (groups != NULL) {
1737 /* Delete User from groups using old name */
1739 while ((grp = GETGRENT()) != NULL) {
1740 if (grp->gr_mem == NULL)
1742 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1743 if (strcmp(grp->gr_mem[i] , name) != 0)
1745 for (j = i; grp->gr_mem[j] != NULL ; j++)
1746 grp->gr_mem[j] = grp->gr_mem[j+1];
1747 chggrent(grp->gr_name, grp);
1752 /* Add the user to the needed groups */
1753 for (i = 0; i < groups->sl_cur; i++) {
1754 grp = GETGRNAM(groups->sl_str[i]);
1755 grp = gr_add(grp, pwd->pw_name);
1758 chggrent(grp->gr_name, grp);
1762 /* In case of rename we need to walk over the different groups */
1765 while ((grp = GETGRENT()) != NULL) {
1766 if (grp->gr_mem == NULL)
1768 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1769 if (strcmp(grp->gr_mem[i], name) != 0)
1771 grp->gr_mem[i] = newname;
1772 chggrent(grp->gr_name, grp);
1778 /* go get a current version of pwd */
1781 pwd = GETPWNAM(name);
1783 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1784 grp = GETGRGID(pwd->pw_gid);
1785 pw_log(cnf, M_UPDATE, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1786 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1787 grp ? grp->gr_name : "unknown",
1788 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1789 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1792 * Let's create and populate the user's home directory. Note
1793 * that this also `works' for editing users if -m is used, but
1794 * existing files will *not* be overwritten.
1796 if (PWALTDIR() != PWF_ALT && docreatehome && pwd->pw_dir &&
1797 *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1801 homemode = cnf->homemode;
1802 create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1805 if (nis && nis_update() == 0)
1806 pw_log(cnf, M_UPDATE, W_USER, "NIS maps updated");
1808 return (EXIT_SUCCESS);