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);
288 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
291 errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
292 errx(EX_NOUSER, "no such user `%s'", name);
298 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
300 if (mode == M_LOCK && locked)
301 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
302 if (mode == M_UNLOCK && !locked)
303 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
305 if (mode == M_LOCK) {
306 asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
307 if (passtmp == NULL) /* disaster */
308 errx(EX_UNAVAILABLE, "out of memory");
309 pwd->pw_passwd = passtmp;
311 pwd->pw_passwd += sizeof(locked_str)-1;
314 perform_chgpwent(name, pwd, NULL);
317 return (EXIT_SUCCESS);
321 pw_uidpolicy(struct userconf * cnf, intmax_t id)
325 uid_t uid = (uid_t) - 1;
328 * Check the given uid, if any
333 if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
334 errx(EX_DATAERR, "uid `%ju' has already been allocated",
335 (uintmax_t)pwd->pw_uid);
339 * We need to allocate the next available uid under one of
340 * two policies a) Grab the first unused uid b) Grab the
341 * highest possible unused uid
343 if (cnf->min_uid >= cnf->max_uid) { /* Sanity
344 * claus^H^H^H^Hheck */
346 cnf->max_uid = 32000;
348 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
351 * Now, let's fill the bitmap from the password file
354 while ((pwd = GETPWENT()) != NULL)
355 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
356 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
360 * Then apply the policy, with fallback to reuse if necessary
362 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
363 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
366 * Another sanity check
368 if (uid < cnf->min_uid || uid > cnf->max_uid)
369 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
375 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam, gid_t prefer, bool dryrun)
378 gid_t gid = (uid_t) - 1;
381 * Check the given gid, if any
385 if ((grp = GETGRNAM(grname)) == NULL) {
386 gid = pw_checkid(grname, GID_MAX);
390 } else if ((grp = GETGRNAM(nam)) != NULL &&
391 (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
392 gid = grp->gr_gid; /* Already created? Use it anyway... */
397 * We need to auto-create a group with the user's name. We
398 * can send all the appropriate output to our sister routine
399 * bit first see if we can create a group with gid==uid so we
400 * can keep the user and group ids in sync. We purposely do
401 * NOT check the gid range if we can force the sync. If the
402 * user's name dups an existing group, then the group add
403 * function will happily handle that case for us and exit.
405 if (GETGRGID(prefer) == NULL)
408 gid = pw_groupnext(cnf, true);
411 grid = pw_groupnext(cnf, true);
412 groupadd(cnf, nam, grid, NULL, -1, false, false, false);
413 if ((grp = GETGRNAM(nam)) != NULL)
422 pw_homepolicy(struct userconf * cnf, char *homedir, const char *user)
424 static char home[128];
429 if (cnf->home == NULL || *cnf->home == '\0')
430 errx(EX_CONFIG, "no base home directory set");
431 snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
437 shell_path(char const * path, char *shells[], char *sh)
439 if (sh != NULL && (*sh == '/' || *sh == '\0'))
440 return sh; /* specified full path or forced none */
443 char paths[_UC_MAXLINE];
446 * We need to search paths
448 strlcpy(paths, path, sizeof(paths));
449 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
451 static char shellpath[256];
454 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
455 if (access(shellpath, X_OK) == 0)
458 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
459 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
460 if (access(shellpath, X_OK) == 0)
465 errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
466 errx(EX_CONFIG, "no default shell available or defined");
472 pw_shellpolicy(struct userconf * cnf)
475 return shell_path(cnf->shelldir, cnf->shells, cnf->shell_default);
480 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
483 pw_pwcrypt(char *password)
486 char salt[SALTSIZE + 1];
488 static char buf[256];
491 * Calculate a salt value
493 for (i = 0; i < SALTSIZE; i++)
494 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
495 salt[SALTSIZE] = '\0';
497 cryptpw = crypt(password, salt);
499 errx(EX_CONFIG, "crypt(3) failure");
500 return strcpy(buf, cryptpw);
504 pw_password(struct userconf * cnf, char const * user, bool dryrun)
509 switch (cnf->default_password) {
510 case -1: /* Random password */
511 l = (arc4random() % 8 + 8); /* 8 - 16 chars */
512 for (i = 0; i < l; i++)
513 pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
517 * We give this information back to the user
519 if (conf.fd == -1 && !dryrun) {
520 if (isatty(STDOUT_FILENO))
521 printf("Password for '%s' is: ", user);
522 printf("%s\n", pwbuf);
527 case -2: /* No password at all! */
530 case 0: /* No login - default */
534 case 1: /* user's name */
535 strlcpy(pwbuf, user, sizeof(pwbuf));
538 return pw_pwcrypt(pwbuf);
542 print_user(struct passwd * pwd, bool pretty, bool v7)
546 struct group *grp = GETGRGID(pwd->pw_gid);
547 char uname[60] = "User &", office[60] = "[None]",
548 wphone[60] = "[None]", hphone[60] = "[None]";
549 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
553 p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
556 return (EXIT_SUCCESS);
559 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
560 strlcpy(uname, p, sizeof(uname));
561 if ((p = strtok(NULL, ",")) != NULL) {
562 strlcpy(office, p, sizeof(office));
563 if ((p = strtok(NULL, ",")) != NULL) {
564 strlcpy(wphone, p, sizeof(wphone));
565 if ((p = strtok(NULL, "")) != NULL) {
566 strlcpy(hphone, p, sizeof(hphone));
572 * Handle '&' in gecos field
574 if ((p = strchr(uname, '&')) != NULL) {
575 int l = strlen(pwd->pw_name);
578 memmove(p + l, p + 1, m);
579 memmove(p, pwd->pw_name, l);
580 *p = (char) toupper((unsigned char)*p);
582 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
583 strftime(acexpire, sizeof acexpire, "%c", tptr);
584 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
585 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
586 printf("Login Name: %-15s #%-12ju Group: %-15s #%ju\n"
588 " Home: %-26.26s Class: %s\n"
589 " Shell: %-26.26s Office: %s\n"
590 "Work Phone: %-26.26s Home Phone: %s\n"
591 "Acc Expire: %-26.26s Pwd Expire: %s\n",
592 pwd->pw_name, (uintmax_t)pwd->pw_uid,
593 grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
594 uname, pwd->pw_dir, pwd->pw_class,
595 pwd->pw_shell, office, wphone, hphone,
599 while ((grp=GETGRENT()) != NULL) {
601 if (grp->gr_mem != NULL) {
602 while (grp->gr_mem[i] != NULL) {
603 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
604 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
612 printf("%s", j ? "\n" : "");
613 return (EXIT_SUCCESS);
617 pw_checkname(char *name, int gecos)
620 const char *badchars, *ch, *showtype;
626 /* See if the name is valid as a gecos (comment) field. */
628 showtype = "gecos field";
630 /* See if the name is valid as a userid or group. */
631 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
632 showtype = "userid/group name";
633 /* Userids and groups can not have a leading '-'. */
639 if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
644 /* 8-bit characters are only allowed in GECOS fields */
645 if (!gecos && (*ch & 0x80)) {
653 * A `$' is allowed as the final character for userids and groups,
654 * mainly for the benefit of samba.
656 if (reject && !gecos) {
657 if (*ch == '$' && *(ch + 1) == '\0') {
663 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
664 ? "`%c'" : "0x%02x", *ch);
665 errx(EX_DATAERR, "invalid character %s at position %td in %s",
666 showch, (ch - name), showtype);
668 if (!gecos && (ch - name) > LOGNAMESIZE)
669 errx(EX_USAGE, "name too long `%s' (max is %d)", name,
678 DIR *d = opendir("/var/at/jobs");
683 while ((e = readdir(d)) != NULL) {
686 if (strncmp(e->d_name, ".lock", 5) != 0 &&
687 stat(e->d_name, &st) == 0 &&
688 !S_ISDIR(st.st_mode) &&
690 char tmp[MAXPATHLEN];
692 snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s",
702 rmopie(char const * name)
710 if ((fd = openat(conf.rootfd, "etc/opiekeys", O_RDWR)) == -1)
713 fp = fdopen(fd, "r+");
716 while (fgets(tmp, sizeof(tmp), fp) != NULL) {
717 if (strncmp(name, tmp, len) == 0 && tmp[len]==' ') {
718 /* Comment username out */
719 if (fseek(fp, atofs, SEEK_SET) == 0)
720 fwrite("#", 1, 1, fp);
726 * If we got an error of any sort, don't update!
732 pw_user_next(int argc, char **argv, char *name __unused)
734 struct userconf *cnf = NULL;
735 const char *cfg = NULL;
740 while ((ch = getopt(argc, argv, "Cq")) != -1) {
752 freopen(_PATH_DEVNULL, "w", stderr);
754 cnf = get_userconfig(cfg);
756 next = pw_uidpolicy(cnf, -1);
758 printf("%ju:", (uintmax_t)next);
759 pw_groupnext(cnf, quiet);
761 return (EXIT_SUCCESS);
765 pw_user_show(int argc, char **argv, char *arg1)
767 struct passwd *pwd = NULL;
778 if (arg1[strspn(arg1, "0123456789")] == '\0')
779 id = pw_checkid(arg1, UID_MAX);
784 while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
787 /* ignore compatibility */
796 id = pw_checkid(optarg, UID_MAX);
814 freopen(_PATH_DEVNULL, "w", stderr);
818 while ((pwd = GETPWENT()) != NULL)
819 print_user(pwd, pretty, v7);
821 return (EXIT_SUCCESS);
824 if (id < 0 && name == NULL)
825 errx(EX_DATAERR, "username or id required");
827 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
833 errx(EX_NOUSER, "no such uid `%ju'",
835 errx(EX_NOUSER, "no such user `%s'", name);
839 return (print_user(pwd, pretty, v7));
843 pw_user_del(int argc, char **argv, char *arg1)
845 struct userconf *cnf = NULL;
846 struct passwd *pwd = NULL;
847 struct group *gr, *grp;
849 char grname[MAXLOGNAME];
850 char *nispasswd = NULL;
851 char file[MAXPATHLEN];
852 char home[MAXPATHLEN];
853 const char *cfg = NULL;
858 bool deletehome = false;
862 if (arg1[strspn(arg1, "0123456789")] == '\0')
863 id = pw_checkid(arg1, UID_MAX);
868 while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
880 id = pw_checkid(optarg, UID_MAX);
895 freopen(_PATH_DEVNULL, "w", stderr);
897 if (id < 0 && name == NULL)
898 errx(EX_DATAERR, "username or id required");
900 cnf = get_userconfig(cfg);
902 if (nispasswd == NULL)
903 nispasswd = cnf->nispasswd;
905 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
908 errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
909 errx(EX_NOUSER, "no such user `%s'", name);
912 if (PWF._altdir == PWF_REGULAR &&
913 ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
914 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
915 if (!nis && nispasswd && *nispasswd != '/')
916 errx(EX_NOUSER, "Cannot remove NIS user `%s'",
919 errx(EX_NOUSER, "Cannot remove non local user `%s'",
928 if (strcmp(pwd->pw_name, "root") == 0)
929 errx(EX_DATAERR, "cannot remove user 'root'");
931 /* Remove opie record from /etc/opiekeys */
932 if (PWALTDIR() != PWF_ALT)
933 rmopie(pwd->pw_name);
936 /* Remove crontabs */
937 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
938 if (access(file, F_OK) == 0) {
939 snprintf(file, sizeof(file), "crontab -u %s -r",
946 * Save these for later, since contents of pwd may be
947 * invalidated by deletion
949 snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
950 strlcpy(home, pwd->pw_dir, sizeof(home));
951 gr = GETGRGID(pwd->pw_gid);
953 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
959 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
961 err(EX_IOERR, "passwd update");
963 if (nis && nispasswd && *nispasswd=='/') {
964 rc = delnispwent(nispasswd, name);
966 warnx("WARNING: user '%s' does not exist in NIS passwd",
969 warn("WARNING: NIS passwd update");
972 grp = GETGRNAM(name);
974 (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
975 strcmp(name, grname) == 0)
976 delgrent(GETGRNAM(name));
978 while ((grp = GETGRENT()) != NULL) {
980 char group[MAXLOGNAME];
981 if (grp->gr_mem == NULL)
984 for (i = 0; grp->gr_mem[i] != NULL; i++) {
985 if (strcmp(grp->gr_mem[i], name) != 0)
988 for (j = i; grp->gr_mem[j] != NULL; j++)
989 grp->gr_mem[j] = grp->gr_mem[j+1];
990 strlcpy(group, grp->gr_name, MAXLOGNAME);
991 chggrent(group, grp);
996 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
999 /* Remove mail file */
1000 if (PWALTDIR() != PWF_ALT)
1001 unlinkat(conf.rootfd, file + 1, 0);
1003 /* Remove at jobs */
1004 if (!PWALTDIR() && getpwuid(id) == NULL)
1007 /* Remove home directory and contents */
1008 if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
1009 GETPWUID(id) == NULL &&
1010 fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1011 rm_r(conf.rootfd, home, id);
1012 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
1013 "removed", name, (uintmax_t)id, home,
1014 fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1018 return (EXIT_SUCCESS);
1022 pw_user_lock(int argc, char **argv, char *arg1)
1026 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1035 return (pw_userlock(arg1, M_LOCK));
1039 pw_user_unlock(int argc, char **argv, char *arg1)
1043 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1052 return (pw_userlock(arg1, M_UNLOCK));
1055 static struct group *
1056 group_from_name_or_id(char *name)
1058 const char *errstr = NULL;
1062 if ((grp = GETGRNAM(name)) == NULL) {
1063 id = strtounum(name, 0, GID_MAX, &errstr);
1065 errx(EX_NOUSER, "group `%s' does not exist", name);
1068 errx(EX_NOUSER, "group `%s' does not exist", name);
1075 split_groups(StringList **groups, char *groupsstr)
1079 char tok[] = ", \t";
1081 for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1082 grp = group_from_name_or_id(p);
1083 if (*groups == NULL)
1084 *groups = sl_init();
1085 sl_add(*groups, newstr(grp->gr_name));
1090 validate_grname(struct userconf *cnf, char *group)
1094 if (group == NULL || *group == '\0') {
1095 cnf->default_group = "";
1098 grp = group_from_name_or_id(group);
1099 cnf->default_group = newstr(grp->gr_name);
1103 validate_mode(char *mode)
1108 if ((set = setmode(mode)) == NULL)
1109 errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1111 m = getmode(set, _DEF_DIRMODE);
1117 mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1120 if (cmdcnf->default_password == 0)
1121 cmdcnf->default_password = cfg->default_password;
1122 if (cmdcnf->reuse_uids == 0)
1123 cmdcnf->reuse_uids = cfg->reuse_uids;
1124 if (cmdcnf->reuse_gids == 0)
1125 cmdcnf->reuse_gids = cfg->reuse_gids;
1126 if (cmdcnf->nispasswd == NULL)
1127 cmdcnf->nispasswd = cfg->nispasswd;
1128 if (cmdcnf->dotdir == NULL)
1129 cmdcnf->dotdir = cfg->dotdir;
1130 if (cmdcnf->newmail == NULL)
1131 cmdcnf->newmail = cfg->newmail;
1132 if (cmdcnf->logfile == NULL)
1133 cmdcnf->logfile = cfg->logfile;
1134 if (cmdcnf->home == NULL)
1135 cmdcnf->home = cfg->home;
1136 if (cmdcnf->homemode == 0)
1137 cmdcnf->homemode = cfg->homemode;
1138 if (cmdcnf->shelldir == NULL)
1139 cmdcnf->shelldir = cfg->shelldir;
1140 if (cmdcnf->shells == NULL)
1141 cmdcnf->shells = cfg->shells;
1142 if (cmdcnf->shell_default == NULL)
1143 cmdcnf->shell_default = cfg->shell_default;
1144 if (cmdcnf->default_group == NULL)
1145 cmdcnf->default_group = cfg->default_group;
1146 if (cmdcnf->groups == NULL)
1147 cmdcnf->groups = cfg->groups;
1148 if (cmdcnf->default_class == NULL)
1149 cmdcnf->default_class = cfg->default_class;
1150 if (cmdcnf->min_uid == 0)
1151 cmdcnf->min_uid = cfg->min_uid;
1152 if (cmdcnf->max_uid == 0)
1153 cmdcnf->max_uid = cfg->max_uid;
1154 if (cmdcnf->min_gid == 0)
1155 cmdcnf->min_gid = cfg->min_gid;
1156 if (cmdcnf->max_gid == 0)
1157 cmdcnf->max_gid = cfg->max_gid;
1158 if (cmdcnf->expire_days == 0)
1159 cmdcnf->expire_days = cfg->expire_days;
1160 if (cmdcnf->password_days == 0)
1161 cmdcnf->password_days = cfg->password_days;
1165 pw_user_add(int argc, char **argv, char *arg1)
1167 struct userconf *cnf, *cmdcnf;
1171 char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1172 char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1173 char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1174 char *default_passwd, *name, *p;
1180 int rc, ch, fd = -1;
1182 bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1184 dryrun = nis = pretty = quiet = createhome = precrypted = false;
1186 gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1187 grname = name = NULL;
1189 if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1190 err(EXIT_FAILURE, "calloc()");
1193 if (arg1[strspn(arg1, "0123456789")] == '\0')
1194 id = pw_checkid(arg1, UID_MAX);
1199 while ((ch = getopt(argc, argv, args)) != -1) {
1214 gecos = pw_checkname(optarg, 1);
1221 cmdcnf->expire_days = parse_date(now, optarg);
1225 cmdcnf->password_days = parse_date(now, optarg);
1228 validate_grname(cmdcnf, optarg);
1232 split_groups(&cmdcnf->groups, optarg);
1238 cmdcnf->homemode = validate_mode(optarg);
1241 walk = skel = optarg;
1244 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1245 errx(EX_OSFILE, "skeleton `%s' does not "
1247 if (!S_ISDIR(st.st_mode))
1248 errx(EX_OSFILE, "skeleton `%s' is not a "
1250 cmdcnf->dotdir = skel;
1253 cmdcnf->shell_default = optarg;
1256 conf.checkduplicate = false;
1259 cmdcnf->default_class = pw_checkname(optarg, 0);
1265 default_passwd = optarg;
1269 errx(EX_USAGE, "'-h' and '-H' are mutually "
1270 "exclusive options");
1271 fd = pw_checkfd(optarg);
1274 errx(EX_USAGE, "-H expects a file descriptor");
1278 errx(EX_USAGE, "'-h' and '-H' are mutually "
1279 "exclusive options");
1280 fd = pw_checkfd(optarg);
1286 cmdcnf->home = optarg;
1295 cmdcnf->nispasswd = optarg;
1303 if (geteuid() != 0 && ! dryrun)
1304 errx(EX_NOPERM, "you must be root");
1307 freopen(_PATH_DEVNULL, "w", stderr);
1309 cnf = get_userconfig(cfg);
1311 mix_config(cmdcnf, cnf);
1313 cmdcnf->default_password = boolean_val(default_passwd,
1314 cnf->default_password);
1317 errx(EX_DATAERR, "can't combine `-D' with `-n name'");
1318 if (userid != NULL) {
1319 if ((p = strtok(userid, ", \t")) != NULL)
1320 cmdcnf->min_uid = pw_checkid(p, UID_MAX);
1321 if (cmdcnf->min_uid == 0)
1322 cmdcnf->min_uid = 1000;
1323 if ((p = strtok(NULL, " ,\t")) != NULL)
1324 cmdcnf->max_uid = pw_checkid(p, UID_MAX);
1325 if (cmdcnf->max_uid == 0)
1326 cmdcnf->max_uid = 32000;
1328 if (groupid != NULL) {
1329 if ((p = strtok(groupid, ", \t")) != NULL)
1330 cmdcnf->min_gid = pw_checkid(p, GID_MAX);
1331 if (cmdcnf->min_gid == 0)
1332 cmdcnf->min_gid = 1000;
1333 if ((p = strtok(NULL, " ,\t")) != NULL)
1334 cmdcnf->max_gid = pw_checkid(p, GID_MAX);
1335 if (cmdcnf->max_gid == 0)
1336 cmdcnf->max_gid = 32000;
1338 if (write_userconfig(cmdcnf, cfg))
1339 return (EXIT_SUCCESS);
1340 err(EX_IOERR, "config update");
1344 id = pw_checkid(userid, UID_MAX);
1345 if (id < 0 && name == NULL)
1346 errx(EX_DATAERR, "user name or id required");
1349 errx(EX_DATAERR, "login name required");
1351 if (GETPWNAM(name) != NULL)
1352 errx(EX_DATAERR, "login name `%s' already exists", name);
1355 pwd->pw_name = name;
1356 pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1357 pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1358 pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1359 (gid_t) pwd->pw_uid, dryrun);
1360 pwd->pw_change = cmdcnf->password_days;
1361 pwd->pw_expire = cmdcnf->expire_days;
1362 pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1363 pwd->pw_shell = pw_shellpolicy(cmdcnf);
1364 lc = login_getpwclass(pwd);
1365 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1366 warn("setting crypt(3) format");
1368 pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name, dryrun);
1369 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1370 warnx("WARNING: new account `%s' has a uid of 0 "
1371 "(superuser access!)", pwd->pw_name);
1373 pwd->pw_gecos = gecos;
1376 pw_set_passwd(pwd, fd, precrypted, false);
1379 return (print_user(pwd, pretty, false));
1381 if ((rc = addpwent(pwd)) != 0) {
1383 errx(EX_IOERR, "user '%s' already exists",
1386 err(EX_IOERR, "passwd file update");
1388 if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1389 printf("%s\n", cmdcnf->nispasswd);
1390 rc = addnispwent(cmdcnf->nispasswd, pwd);
1392 warnx("User '%s' already exists in NIS passwd",
1395 warn("NIS passwd update");
1396 /* NOTE: we treat NIS-only update errors as non-fatal */
1399 if (cmdcnf->groups != NULL) {
1400 for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1401 grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1402 grp = gr_add(grp, pwd->pw_name);
1404 * grp can only be NULL in 2 cases:
1405 * - the new member is already a member
1406 * - a problem with memory occurs
1407 * in both cases we want to skip now.
1411 chggrent(grp->gr_name, grp);
1416 pwd = GETPWNAM(name);
1418 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1420 grp = GETGRGID(pwd->pw_gid);
1421 pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1422 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1423 grp ? grp->gr_name : "unknown",
1424 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1425 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1428 * let's touch and chown the user's mail file. This is not
1429 * strictly necessary under BSD with a 0755 maildir but it also
1430 * doesn't hurt anything to create the empty mailfile
1432 if (PWALTDIR() != PWF_ALT) {
1433 snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1435 /* Preserve contents & mtime */
1436 close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1437 fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1438 AT_SYMLINK_NOFOLLOW);
1442 * Let's create and populate the user's home directory. Note
1443 * that this also `works' for editing users if -m is used, but
1444 * existing files will *not* be overwritten.
1446 if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1447 *pwd->pw_dir == '/' && pwd->pw_dir[1])
1448 create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1449 cmdcnf->homemode, false);
1451 if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1452 (fp = fopen(cnf->newmail, "r")) != NULL) {
1453 if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1456 fprintf(pfp, "From: root\n" "To: %s\n"
1457 "Subject: Welcome!\n\n", pwd->pw_name);
1458 while (fgets(line, sizeof(line), fp) != NULL) {
1459 /* Do substitutions? */
1463 pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1464 pwd->pw_name, (uintmax_t)pwd->pw_uid);
1469 if (nis && nis_update() == 0)
1470 pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1472 return (EXIT_SUCCESS);
1476 pw_user_mod(int argc, char **argv, char *arg1)
1478 struct userconf *cnf;
1481 StringList *groups = NULL;
1482 char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1484 char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1485 char *passwd, *class, *nispasswd;
1491 bool quiet, createhome, pretty, dryrun, nis, edited, docreatehome;
1493 mode_t homemode = 0;
1494 time_t expire_days, password_days, now;
1496 expire_days = password_days = -1;
1497 gecos = homedir = grname = name = newname = skel = shell =NULL;
1499 class = nispasswd = NULL;
1500 quiet = createhome = pretty = dryrun = nis = precrypted = false;
1501 edited = docreatehome = false;
1504 if (arg1[strspn(arg1, "0123456789")] == '\0')
1505 id = pw_checkid(arg1, UID_MAX);
1510 while ((ch = getopt(argc, argv, args)) != -1) {
1522 id = pw_checkid(optarg, UID_MAX);
1525 gecos = pw_checkname(optarg, 1);
1532 expire_days = parse_date(now, optarg);
1536 password_days = parse_date(now, optarg);
1539 group_from_name_or_id(optarg);
1543 split_groups(&groups, optarg);
1549 homemode = validate_mode(optarg);
1555 walk = skel = optarg;
1558 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1559 errx(EX_OSFILE, "skeleton `%s' does not "
1561 if (!S_ISDIR(st.st_mode))
1562 errx(EX_OSFILE, "skeleton `%s' is not a "
1572 class = pw_checkname(optarg, 0);
1576 errx(EX_USAGE, "'-h' and '-H' are mutually "
1577 "exclusive options");
1578 fd = pw_checkfd(optarg);
1581 errx(EX_USAGE, "-H expects a file descriptor");
1585 errx(EX_USAGE, "'-h' and '-H' are mutually "
1586 "exclusive options");
1587 fd = pw_checkfd(optarg);
1604 if (geteuid() != 0 && ! dryrun)
1605 errx(EX_NOPERM, "you must be root");
1608 freopen(_PATH_DEVNULL, "w", stderr);
1610 cnf = get_userconfig(cfg);
1612 if (id < 0 && name == NULL)
1613 errx(EX_DATAERR, "username or id required");
1615 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1618 errx(EX_NOUSER, "no such uid `%ju'",
1620 errx(EX_NOUSER, "no such user `%s'", name);
1624 name = pwd->pw_name;
1626 if (nis && nispasswd == NULL)
1627 nispasswd = cnf->nispasswd;
1629 if (PWF._altdir == PWF_REGULAR &&
1630 ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
1631 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
1632 if (!nis && nispasswd && *nispasswd != '/')
1633 errx(EX_NOUSER, "Cannot modify NIS user `%s'",
1636 errx(EX_NOUSER, "Cannot modify non local user `%s'",
1642 if (strcmp(pwd->pw_name, "root") == 0)
1643 errx(EX_DATAERR, "can't rename `root' account");
1644 if (strcmp(pwd->pw_name, newname) != 0) {
1645 pwd->pw_name = pw_checkname(newname, 0);
1650 if (id > 0 && pwd->pw_uid != id) {
1653 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
1654 errx(EX_DATAERR, "can't change uid of `root' account");
1655 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1656 warnx("WARNING: account `%s' will have a uid of 0 "
1657 "(superuser access!)", pwd->pw_name);
1660 if (grname && pwd->pw_uid != 0) {
1661 grp = GETGRNAM(grname);
1663 grp = GETGRGID(pw_checkid(grname, GID_MAX));
1664 if (grp->gr_gid != pwd->pw_gid) {
1665 pwd->pw_gid = grp->gr_gid;
1670 if (password_days >= 0 && pwd->pw_change != password_days) {
1671 pwd->pw_change = password_days;
1675 if (expire_days >= 0 && pwd->pw_expire != expire_days) {
1676 pwd->pw_expire = expire_days;
1681 shell = shell_path(cnf->shelldir, cnf->shells, shell);
1684 if (strcmp(shell, pwd->pw_shell) != 0) {
1685 pwd->pw_shell = shell;
1690 if (class && strcmp(pwd->pw_class, class) != 0) {
1691 pwd->pw_class = class;
1695 if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1696 pwd->pw_dir = homedir;
1698 if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1700 warnx("WARNING: home `%s' does not exist",
1703 docreatehome = true;
1704 } else if (!S_ISDIR(st.st_mode)) {
1705 warnx("WARNING: home `%s' is not a directory",
1710 if (passwd && conf.fd == -1) {
1711 lc = login_getpwclass(pwd);
1712 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1713 warn("setting crypt(3) format");
1715 cnf->default_password = boolean_val(passwd,
1716 cnf->default_password);
1717 pwd->pw_passwd = pw_password(cnf, pwd->pw_name, dryrun);
1721 if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1722 pwd->pw_gecos = gecos;
1727 edited = pw_set_passwd(pwd, fd, precrypted, true);
1730 return (print_user(pwd, pretty, false));
1732 if (edited) /* Only updated this if required */
1733 perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1734 /* Now perform the needed changes concern groups */
1735 if (groups != NULL) {
1736 /* Delete User from groups using old name */
1738 while ((grp = GETGRENT()) != NULL) {
1739 if (grp->gr_mem == NULL)
1741 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1742 if (strcmp(grp->gr_mem[i] , name) != 0)
1744 for (j = i; grp->gr_mem[j] != NULL ; j++)
1745 grp->gr_mem[j] = grp->gr_mem[j+1];
1746 chggrent(grp->gr_name, grp);
1751 /* Add the user to the needed groups */
1752 for (i = 0; i < groups->sl_cur; i++) {
1753 grp = GETGRNAM(groups->sl_str[i]);
1754 grp = gr_add(grp, pwd->pw_name);
1757 chggrent(grp->gr_name, grp);
1761 /* In case of rename we need to walk over the different groups */
1764 while ((grp = GETGRENT()) != NULL) {
1765 if (grp->gr_mem == NULL)
1767 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1768 if (strcmp(grp->gr_mem[i], name) != 0)
1770 grp->gr_mem[i] = newname;
1771 chggrent(grp->gr_name, grp);
1777 /* go get a current version of pwd */
1780 pwd = GETPWNAM(name);
1782 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1783 grp = GETGRGID(pwd->pw_gid);
1784 pw_log(cnf, M_UPDATE, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1785 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1786 grp ? grp->gr_name : "unknown",
1787 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1788 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1791 * Let's create and populate the user's home directory. Note
1792 * that this also `works' for editing users if -m is used, but
1793 * existing files will *not* be overwritten.
1795 if (PWALTDIR() != PWF_ALT && docreatehome && pwd->pw_dir &&
1796 *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1800 homemode = cnf->homemode;
1801 create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1804 if (nis && nis_update() == 0)
1805 pw_log(cnf, M_UPDATE, W_USER, "NIS maps updated");
1807 return (EXIT_SUCCESS);