2 * SPDX-License-Identifier: BSD-2-Clause
5 * David L. Nugent. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 static const char rcsid[] =
35 #include <sys/param.h>
36 #include <sys/types.h>
47 #include <login_cap.h>
59 #define LOGNAMESIZE (MAXLOGNAME-1)
61 extern char **environ;
62 static char locked_str[] = "*LOCKED*";
64 static struct passwd fakeuser = {
78 static int print_user(struct passwd *pwd, bool pretty, bool v7);
79 static uid_t pw_uidpolicy(struct userconf *cnf, intmax_t id);
80 static uid_t pw_gidpolicy(struct userconf *cnf, char *grname, char *nam,
81 gid_t prefer, bool dryrun);
82 static char *pw_homepolicy(struct userconf * cnf, char *homedir,
84 static char *pw_shellpolicy(struct userconf * cnf);
85 static char *pw_password(struct userconf * cnf, char const * user);
86 static char *shell_path(char const * path, char *shells[], char *sh);
87 static void rmat(uid_t uid);
90 mkdir_home_parents(int dfd, const char *dir)
96 errx(EX_DATAERR, "invalid base directory for home '%s'", dir);
100 if (fstatat(dfd, dir, &st, 0) != -1) {
101 if (S_ISDIR(st.st_mode))
103 errx(EX_OSFILE, "root home `/%s' is not a directory", dir);
108 errx(EX_UNAVAILABLE, "out of memory");
110 tmp = strrchr(dirs, '/');
118 if (fstatat(dfd, dirs, &st, 0) == -1) {
119 while ((tmp = strchr(tmp + 1, '/')) != NULL) {
121 if (fstatat(dfd, dirs, &st, 0) == -1) {
122 if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
123 err(EX_OSFILE, "'%s' (home parent) is not a directory", dirs);
128 if (fstatat(dfd, dirs, &st, 0) == -1) {
129 if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
130 err(EX_OSFILE, "'%s' (home parent) is not a directory", dirs);
131 fchownat(dfd, dirs, 0, 0, 0);
138 create_and_populate_homedir(struct userconf *cnf, struct passwd *pwd,
139 const char *skeldir, mode_t homemode, bool update)
143 /* Create home parents directories */
144 mkdir_home_parents(conf.rootfd, pwd->pw_dir);
146 if (skeldir != NULL && *skeldir != '\0') {
149 skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
152 copymkdir(conf.rootfd, pwd->pw_dir, skelfd, homemode, pwd->pw_uid,
154 pw_log(cnf, update ? M_UPDATE : M_ADD, W_USER, "%s(%ju) home %s made",
155 pwd->pw_name, (uintmax_t)pwd->pw_uid, pwd->pw_dir);
159 pw_set_passwd(struct passwd *pwd, int fd, bool precrypted, bool update)
164 char line[_PASSWORD_LEN+1];
168 if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
169 pwd->pw_passwd = "*"; /* No access */
175 if ((istty = isatty(fd))) {
176 if (tcgetattr(fd, &t) == -1)
180 n.c_lflag &= ~(ECHO);
181 tcsetattr(fd, TCSANOW, &n);
182 printf("%s%spassword for user %s:",
183 update ? "new " : "",
184 precrypted ? "encrypted " : "",
189 b = read(fd, line, sizeof(line) - 1);
190 if (istty) { /* Restore state */
191 tcsetattr(fd, TCSANOW, &t);
197 err(EX_IOERR, "-%c file descriptor",
198 precrypted ? 'H' : 'h');
200 if ((p = strpbrk(line, "\r\n")) != NULL)
203 errx(EX_DATAERR, "empty password read on file descriptor %d",
206 if (strchr(line, ':') != NULL)
207 errx(EX_DATAERR, "bad encrypted password");
208 pwd->pw_passwd = strdup(line);
210 lc = login_getpwclass(pwd);
212 login_setcryptfmt(lc, "sha512", NULL) == NULL)
213 warn("setting crypt(3) format");
215 pwd->pw_passwd = pw_pwcrypt(line);
221 perform_chgpwent(const char *name, struct passwd *pwd, char *nispasswd)
224 struct passwd *nispwd;
226 /* duplicate for nis so that chgpwent is not modifying before NIS */
227 if (nispasswd && *nispasswd == '/')
228 nispwd = pw_dup(pwd);
230 rc = chgpwent(name, pwd);
232 errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
234 err(EX_IOERR, "passwd file update");
236 if (nispasswd && *nispasswd == '/') {
237 rc = chgnispwent(nispasswd, name, nispwd);
239 warn("User '%s' not found in NIS passwd", pwd->pw_name);
241 warn("NIS passwd update");
242 /* NOTE: NIS-only update errors are not fatal */
247 * The M_LOCK and M_UNLOCK functions simply add or remove
248 * a "*LOCKED*" prefix from in front of the password to
249 * prevent it decoding correctly, and therefore prevents
250 * access. Of course, this only prevents access via
251 * password authentication (not ssh, kerberos or any
252 * other method that does not use the UNIX password) but
253 * that is a known limitation.
256 pw_userlock(char *arg1, int mode)
258 struct passwd *pwd = NULL;
259 char *passtmp = NULL;
262 uid_t id = (uid_t)-1;
265 errx(EX_NOPERM, "you must be root");
268 errx(EX_DATAERR, "username or id required");
271 if (arg1[strspn(name, "0123456789")] == '\0')
272 id = pw_checkid(name, UID_MAX);
274 pwd = GETPWNAM(pw_checkname(name, 0));
275 if (pwd == NULL && id != (uid_t)-1) {
282 errx(EX_NOUSER, "no such name or uid `%ju'", (uintmax_t) id);
283 errx(EX_NOUSER, "no such user `%s'", name);
289 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
291 if (mode == M_LOCK && locked)
292 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
293 if (mode == M_UNLOCK && !locked)
294 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
296 if (mode == M_LOCK) {
297 asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
298 if (passtmp == NULL) /* disaster */
299 errx(EX_UNAVAILABLE, "out of memory");
300 pwd->pw_passwd = passtmp;
302 pwd->pw_passwd += sizeof(locked_str)-1;
305 perform_chgpwent(name, pwd, NULL);
308 return (EXIT_SUCCESS);
312 pw_uidpolicy(struct userconf * cnf, intmax_t id)
316 uid_t uid = (uid_t) - 1;
319 * Check the given uid, if any
324 if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
325 errx(EX_DATAERR, "uid `%ju' has already been allocated",
326 (uintmax_t)pwd->pw_uid);
330 * We need to allocate the next available uid under one of
331 * two policies a) Grab the first unused uid b) Grab the
332 * highest possible unused uid
334 if (cnf->min_uid >= cnf->max_uid) { /* Sanity
335 * claus^H^H^H^Hheck */
337 cnf->max_uid = 32000;
339 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
342 * Now, let's fill the bitmap from the password file
345 while ((pwd = GETPWENT()) != NULL)
346 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
347 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
351 * Then apply the policy, with fallback to reuse if necessary
353 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
354 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
357 * Another sanity check
359 if (uid < cnf->min_uid || uid > cnf->max_uid)
360 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
366 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam, gid_t prefer, bool dryrun)
369 gid_t gid = (uid_t) - 1;
372 * Check the given gid, if any
376 if ((grp = GETGRNAM(grname)) == NULL) {
377 gid = pw_checkid(grname, GID_MAX);
381 } else if ((grp = GETGRNAM(nam)) != NULL &&
382 (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
383 gid = grp->gr_gid; /* Already created? Use it anyway... */
388 * We need to auto-create a group with the user's name. We
389 * can send all the appropriate output to our sister routine
390 * bit first see if we can create a group with gid==uid so we
391 * can keep the user and group ids in sync. We purposely do
392 * NOT check the gid range if we can force the sync. If the
393 * user's name dups an existing group, then the group add
394 * function will happily handle that case for us and exit.
396 if (GETGRGID(prefer) == NULL)
399 gid = pw_groupnext(cnf, true);
402 grid = pw_groupnext(cnf, true);
403 groupadd(cnf, nam, grid, NULL, -1, false, false, false);
404 if ((grp = GETGRNAM(nam)) != NULL)
413 pw_homepolicy(struct userconf * cnf, char *homedir, const char *user)
415 static char home[128];
420 if (cnf->home == NULL || *cnf->home == '\0')
421 errx(EX_CONFIG, "no base home directory set");
422 snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
428 shell_path(char const * path, char *shells[], char *sh)
430 if (sh != NULL && (*sh == '/' || *sh == '\0'))
431 return sh; /* specified full path or forced none */
434 char paths[_UC_MAXLINE];
437 * We need to search paths
439 strlcpy(paths, path, sizeof(paths));
440 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
442 static char shellpath[256];
445 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
446 if (access(shellpath, X_OK) == 0)
449 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
450 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
451 if (access(shellpath, X_OK) == 0)
456 errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
457 errx(EX_CONFIG, "no default shell available or defined");
463 pw_shellpolicy(struct userconf * cnf)
466 return shell_path(cnf->shelldir, cnf->shells, cnf->shell_default);
471 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
474 pw_pwcrypt(char *password)
477 char salt[SALTSIZE + 1];
479 static char buf[256];
483 * Calculate a salt value
485 for (i = 0; i < SALTSIZE; i++)
486 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
487 salt[SALTSIZE] = '\0';
489 cryptpw = crypt(password, salt);
491 errx(EX_CONFIG, "crypt(3) failure");
492 pwlen = strlcpy(buf, cryptpw, sizeof(buf));
493 assert(pwlen < sizeof(buf));
498 pw_password(struct userconf * cnf, char const * user)
503 switch (cnf->default_password) {
504 case P_NONE: /* No password at all! */
506 case P_RANDOM: /* Random password */
507 l = (arc4random() % 8 + 8); /* 8 - 16 chars */
508 for (i = 0; i < l; i++)
509 pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
513 * We give this information back to the user
516 if (isatty(STDOUT_FILENO))
517 printf("Password for '%s' is: ", user);
518 printf("%s\n", pwbuf);
522 case P_YES: /* user's name */
523 strlcpy(pwbuf, user, sizeof(pwbuf));
525 case P_NO: /* No login - default */
530 return pw_pwcrypt(pwbuf);
534 print_user(struct passwd * pwd, bool pretty, bool v7)
538 struct group *grp = GETGRGID(pwd->pw_gid);
539 char uname[60] = "User &", office[60] = "[None]",
540 wphone[60] = "[None]", hphone[60] = "[None]";
541 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
545 p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
548 return (EXIT_SUCCESS);
551 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
552 strlcpy(uname, p, sizeof(uname));
553 if ((p = strtok(NULL, ",")) != NULL) {
554 strlcpy(office, p, sizeof(office));
555 if ((p = strtok(NULL, ",")) != NULL) {
556 strlcpy(wphone, p, sizeof(wphone));
557 if ((p = strtok(NULL, "")) != NULL) {
558 strlcpy(hphone, p, sizeof(hphone));
564 * Handle '&' in gecos field
566 if ((p = strchr(uname, '&')) != NULL) {
567 int l = strlen(pwd->pw_name);
570 memmove(p + l, p + 1, m);
571 memmove(p, pwd->pw_name, l);
572 *p = (char) toupper((unsigned char)*p);
574 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
575 strftime(acexpire, sizeof acexpire, "%c", tptr);
576 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
577 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
578 printf("Login Name: %-15s #%-12ju Group: %-15s #%ju\n"
580 " Home: %-26.26s Class: %s\n"
581 " Shell: %-26.26s Office: %s\n"
582 "Work Phone: %-26.26s Home Phone: %s\n"
583 "Acc Expire: %-26.26s Pwd Expire: %s\n",
584 pwd->pw_name, (uintmax_t)pwd->pw_uid,
585 grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
586 uname, pwd->pw_dir, pwd->pw_class,
587 pwd->pw_shell, office, wphone, hphone,
591 while ((grp=GETGRENT()) != NULL) {
593 if (grp->gr_mem != NULL) {
594 while (grp->gr_mem[i] != NULL) {
595 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
596 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
604 printf("%s", j ? "\n" : "");
605 return (EXIT_SUCCESS);
609 pw_checkname(char *name, int gecos)
612 const char *badchars, *ch, *showtype;
618 /* See if the name is valid as a gecos (comment) field. */
620 showtype = "gecos field";
622 /* See if the name is valid as a userid or group. */
623 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\";";
624 showtype = "userid/group name";
625 /* Userids and groups can not have a leading '-'. */
631 if (strchr(badchars, *ch) != NULL ||
632 (!gecos && *ch < ' ') ||
637 /* 8-bit characters are only allowed in GECOS fields */
638 if (!gecos && (*ch & 0x80)) {
646 * A `$' is allowed as the final character for userids and groups,
647 * mainly for the benefit of samba.
649 if (reject && !gecos) {
650 if (*ch == '$' && *(ch + 1) == '\0') {
656 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
657 ? "`%c'" : "0x%02x", *ch);
658 errx(EX_DATAERR, "invalid character %s at position %td in %s",
659 showch, (ch - name), showtype);
661 if (!gecos && (ch - name) > LOGNAMESIZE)
662 errx(EX_USAGE, "name too long `%s' (max is %d)", name,
671 DIR *d = opendir("/var/at/jobs");
676 while ((e = readdir(d)) != NULL) {
679 if (strncmp(e->d_name, ".lock", 5) != 0 &&
680 stat(e->d_name, &st) == 0 &&
681 !S_ISDIR(st.st_mode) &&
683 const char *argv[] = {
688 if (posix_spawn(NULL, argv[0], NULL, NULL,
689 (char *const *) argv, environ)) {
690 warn("Failed to execute '%s %s'",
700 pw_user_next(int argc, char **argv, char *name __unused)
702 struct userconf *cnf = NULL;
703 const char *cfg = NULL;
708 while ((ch = getopt(argc, argv, "C:q")) != -1) {
722 freopen(_PATH_DEVNULL, "w", stderr);
724 cnf = get_userconfig(cfg);
726 next = pw_uidpolicy(cnf, -1);
728 printf("%ju:", (uintmax_t)next);
729 pw_groupnext(cnf, quiet);
731 return (EXIT_SUCCESS);
735 pw_user_show(int argc, char **argv, char *arg1)
737 struct passwd *pwd = NULL;
748 if (arg1[strspn(arg1, "0123456789")] == '\0')
749 id = pw_checkid(arg1, UID_MAX);
754 while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
757 /* ignore compatibility */
766 id = pw_checkid(optarg, UID_MAX);
786 freopen(_PATH_DEVNULL, "w", stderr);
790 while ((pwd = GETPWENT()) != NULL)
791 print_user(pwd, pretty, v7);
793 return (EXIT_SUCCESS);
796 if (id < 0 && name == NULL)
797 errx(EX_DATAERR, "username or id required");
799 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
805 errx(EX_NOUSER, "no such uid `%ju'",
807 errx(EX_NOUSER, "no such user `%s'", name);
811 return (print_user(pwd, pretty, v7));
815 pw_user_del(int argc, char **argv, char *arg1)
817 struct userconf *cnf = NULL;
818 struct passwd *pwd = NULL;
819 struct group *gr, *grp;
821 char grname[MAXLOGNAME];
822 char *nispasswd = NULL;
823 char file[MAXPATHLEN];
824 char home[MAXPATHLEN];
825 const char *cfg = NULL;
830 bool deletehome = false;
834 if (arg1[strspn(arg1, "0123456789")] == '\0')
835 id = pw_checkid(arg1, UID_MAX);
840 while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
852 id = pw_checkid(optarg, UID_MAX);
869 freopen(_PATH_DEVNULL, "w", stderr);
871 if (id < 0 && name == NULL)
872 errx(EX_DATAERR, "username or id required");
874 cnf = get_userconfig(cfg);
876 if (nispasswd == NULL)
877 nispasswd = cnf->nispasswd;
879 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
882 errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
883 errx(EX_NOUSER, "no such user `%s'", name);
886 if (PWF._altdir == PWF_REGULAR &&
887 ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
888 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
889 if (!nis && nispasswd && *nispasswd != '/')
890 errx(EX_NOUSER, "Cannot remove NIS user `%s'",
893 errx(EX_NOUSER, "Cannot remove non local user `%s'",
902 if (strcmp(pwd->pw_name, "root") == 0)
903 errx(EX_DATAERR, "cannot remove user 'root'");
906 /* Remove crontabs */
907 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
908 if (access(file, F_OK) == 0) {
909 const char *argv[] = {
916 if (posix_spawnp(NULL, argv[0], NULL, NULL,
917 (char *const *) argv, environ)) {
918 warn("Failed to execute '%s %s'",
925 * Save these for later, since contents of pwd may be
926 * invalidated by deletion
928 snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
929 strlcpy(home, pwd->pw_dir, sizeof(home));
930 gr = GETGRGID(pwd->pw_gid);
932 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
938 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
940 err(EX_IOERR, "passwd update");
942 if (nis && nispasswd && *nispasswd=='/') {
943 rc = delnispwent(nispasswd, name);
945 warnx("WARNING: user '%s' does not exist in NIS passwd",
948 warn("WARNING: NIS passwd update");
951 grp = GETGRNAM(name);
953 (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
954 strcmp(name, grname) == 0)
955 delgrent(GETGRNAM(name));
957 while ((grp = GETGRENT()) != NULL) {
959 char group[MAXLOGNAME];
960 if (grp->gr_mem == NULL)
963 for (i = 0; grp->gr_mem[i] != NULL; i++) {
964 if (strcmp(grp->gr_mem[i], name) != 0)
967 for (j = i; grp->gr_mem[j] != NULL; j++)
968 grp->gr_mem[j] = grp->gr_mem[j+1];
969 strlcpy(group, grp->gr_name, MAXLOGNAME);
970 chggrent(group, grp);
975 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
978 /* Remove mail file */
979 if (PWALTDIR() != PWF_ALT)
980 unlinkat(conf.rootfd, file + 1, 0);
983 if (!PWALTDIR() && getpwuid(id) == NULL)
986 /* Remove home directory and contents */
987 if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
988 GETPWUID(id) == NULL &&
989 fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
990 rm_r(conf.rootfd, home, id);
991 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
992 "removed", name, (uintmax_t)id, home,
993 fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
997 return (EXIT_SUCCESS);
1001 pw_user_lock(int argc, char **argv, char *arg1)
1005 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1016 return (pw_userlock(arg1, M_LOCK));
1020 pw_user_unlock(int argc, char **argv, char *arg1)
1024 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1035 return (pw_userlock(arg1, M_UNLOCK));
1038 static struct group *
1039 group_from_name_or_id(char *name)
1041 const char *errstr = NULL;
1045 if ((grp = GETGRNAM(name)) == NULL) {
1046 id = strtounum(name, 0, GID_MAX, &errstr);
1048 errx(EX_NOUSER, "group `%s' does not exist", name);
1051 errx(EX_NOUSER, "group `%s' does not exist", name);
1058 split_groups(StringList **groups, char *groupsstr)
1062 char tok[] = ", \t";
1064 if (*groups == NULL)
1065 *groups = sl_init();
1066 for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1067 grp = group_from_name_or_id(p);
1068 sl_add(*groups, newstr(grp->gr_name));
1073 validate_grname(struct userconf *cnf, char *group)
1077 if (group == NULL || *group == '\0') {
1078 cnf->default_group = "";
1081 grp = group_from_name_or_id(group);
1082 cnf->default_group = newstr(grp->gr_name);
1086 validate_mode(char *mode)
1091 if ((set = setmode(mode)) == NULL)
1092 errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1094 m = getmode(set, _DEF_DIRMODE);
1100 validate_expire(char *str, int opt)
1103 errx(EX_DATAERR, "-%c argument must be numeric "
1104 "when setting defaults: %s", (char)opt, str);
1105 return strtol(str, NULL, 0);
1109 mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1112 if (cmdcnf->default_password < 0)
1113 cmdcnf->default_password = cfg->default_password;
1114 if (cmdcnf->reuse_uids == 0)
1115 cmdcnf->reuse_uids = cfg->reuse_uids;
1116 if (cmdcnf->reuse_gids == 0)
1117 cmdcnf->reuse_gids = cfg->reuse_gids;
1118 if (cmdcnf->nispasswd == NULL)
1119 cmdcnf->nispasswd = cfg->nispasswd;
1120 if (cmdcnf->dotdir == NULL)
1121 cmdcnf->dotdir = cfg->dotdir;
1122 if (cmdcnf->newmail == NULL)
1123 cmdcnf->newmail = cfg->newmail;
1124 if (cmdcnf->logfile == NULL)
1125 cmdcnf->logfile = cfg->logfile;
1126 if (cmdcnf->home == NULL)
1127 cmdcnf->home = cfg->home;
1128 if (cmdcnf->homemode == 0)
1129 cmdcnf->homemode = cfg->homemode;
1130 if (cmdcnf->shelldir == NULL)
1131 cmdcnf->shelldir = cfg->shelldir;
1132 if (cmdcnf->shells == NULL)
1133 cmdcnf->shells = cfg->shells;
1134 if (cmdcnf->shell_default == NULL)
1135 cmdcnf->shell_default = cfg->shell_default;
1136 if (cmdcnf->default_group == NULL)
1137 cmdcnf->default_group = cfg->default_group;
1138 if (cmdcnf->groups == NULL)
1139 cmdcnf->groups = cfg->groups;
1140 if (cmdcnf->default_class == NULL)
1141 cmdcnf->default_class = cfg->default_class;
1142 if (cmdcnf->min_uid == 0)
1143 cmdcnf->min_uid = cfg->min_uid;
1144 if (cmdcnf->max_uid == 0)
1145 cmdcnf->max_uid = cfg->max_uid;
1146 if (cmdcnf->min_gid == 0)
1147 cmdcnf->min_gid = cfg->min_gid;
1148 if (cmdcnf->max_gid == 0)
1149 cmdcnf->max_gid = cfg->max_gid;
1150 if (cmdcnf->expire_days < 0)
1151 cmdcnf->expire_days = cfg->expire_days;
1152 if (cmdcnf->password_days < 0)
1153 cmdcnf->password_days = cfg->password_days;
1157 pw_user_add(int argc, char **argv, char *arg1)
1159 struct userconf *cnf, *cmdcnf;
1163 char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1164 char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1165 char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1166 char *default_passwd, *name, *p;
1167 const char *cfg = NULL;
1172 int rc, ch, fd = -1;
1174 bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1176 dryrun = nis = pretty = quiet = createhome = precrypted = false;
1178 gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1179 grname = name = NULL;
1181 if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1182 err(EXIT_FAILURE, "calloc()");
1184 cmdcnf->default_password = cmdcnf->expire_days = cmdcnf->password_days = -1;
1188 if (arg1[strspn(arg1, "0123456789")] == '\0')
1189 id = pw_checkid(arg1, UID_MAX);
1191 name = pw_checkname(arg1, 0);
1194 while ((ch = getopt(argc, argv, args)) != -1) {
1203 name = pw_checkname(optarg, 0);
1209 gecos = pw_checkname(optarg, 1);
1216 cmdcnf->expire_days = validate_expire(optarg, ch);
1218 cmdcnf->expire_days = parse_date(now, optarg);
1222 cmdcnf->password_days = validate_expire(optarg, ch);
1224 cmdcnf->password_days = parse_date(now, optarg);
1227 validate_grname(cmdcnf, optarg);
1231 split_groups(&cmdcnf->groups, optarg);
1237 cmdcnf->homemode = validate_mode(optarg);
1240 walk = skel = optarg;
1243 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1244 errx(EX_OSFILE, "skeleton `%s' does not "
1246 if (!S_ISDIR(st.st_mode))
1247 errx(EX_OSFILE, "skeleton `%s' is not a "
1249 cmdcnf->dotdir = skel;
1252 cmdcnf->shell_default = optarg;
1255 conf.checkduplicate = false;
1258 cmdcnf->default_class = pw_checkname(optarg, 0);
1264 default_passwd = optarg;
1268 errx(EX_USAGE, "'-h' and '-H' are mutually "
1269 "exclusive options");
1270 fd = pw_checkfd(optarg);
1273 errx(EX_USAGE, "-H expects a file descriptor");
1277 errx(EX_USAGE, "'-h' and '-H' are mutually "
1278 "exclusive options");
1279 fd = pw_checkfd(optarg);
1285 cmdcnf->home = optarg;
1294 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 = passwd_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 grname = cmdcnf->default_group;
1359 pwd->pw_name = name;
1360 pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1361 pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1362 pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1363 (gid_t) pwd->pw_uid, dryrun);
1365 /* cmdcnf->password_days and cmdcnf->expire_days hold unixtime here */
1366 if (cmdcnf->password_days > 0)
1367 pwd->pw_change = cmdcnf->password_days;
1368 if (cmdcnf->expire_days > 0)
1369 pwd->pw_expire = cmdcnf->expire_days;
1371 pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1372 pwd->pw_shell = pw_shellpolicy(cmdcnf);
1373 lc = login_getpwclass(pwd);
1374 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1375 warn("setting crypt(3) format");
1377 pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name);
1378 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1379 warnx("WARNING: new account `%s' has a uid of 0 "
1380 "(superuser access!)", pwd->pw_name);
1382 pwd->pw_gecos = gecos;
1385 pw_set_passwd(pwd, fd, precrypted, false);
1388 return (print_user(pwd, pretty, false));
1390 if ((rc = addpwent(pwd)) != 0) {
1392 errx(EX_IOERR, "user '%s' already exists",
1395 err(EX_IOERR, "passwd file update");
1397 if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1398 printf("%s\n", cmdcnf->nispasswd);
1399 rc = addnispwent(cmdcnf->nispasswd, pwd);
1401 warnx("User '%s' already exists in NIS passwd",
1404 warn("NIS passwd update");
1405 /* NOTE: we treat NIS-only update errors as non-fatal */
1408 if (cmdcnf->groups != NULL) {
1409 for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1410 grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1411 grp = gr_add(grp, pwd->pw_name);
1413 * grp can only be NULL in 2 cases:
1414 * - the new member is already a member
1415 * - a problem with memory occurs
1416 * in both cases we want to skip now.
1420 chggrent(grp->gr_name, grp);
1425 pwd = GETPWNAM(name);
1427 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1429 grp = GETGRGID(pwd->pw_gid);
1430 pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1431 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1432 grp ? grp->gr_name : "unknown",
1433 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1434 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1437 * let's touch and chown the user's mail file. This is not
1438 * strictly necessary under BSD with a 0755 maildir but it also
1439 * doesn't hurt anything to create the empty mailfile
1441 if (PWALTDIR() != PWF_ALT) {
1442 snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1444 /* Preserve contents & mtime */
1445 close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1446 fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1447 AT_SYMLINK_NOFOLLOW);
1451 * Let's create and populate the user's home directory. Note
1452 * that this also `works' for editing users if -m is used, but
1453 * existing files will *not* be overwritten.
1455 if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1456 *pwd->pw_dir == '/' && pwd->pw_dir[1])
1457 create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1458 cmdcnf->homemode, false);
1460 if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1461 (fp = fopen(cnf->newmail, "r")) != NULL) {
1462 if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1465 fprintf(pfp, "From: root\n" "To: %s\n"
1466 "Subject: Welcome!\n\n", pwd->pw_name);
1467 while (fgets(line, sizeof(line), fp) != NULL) {
1468 /* Do substitutions? */
1472 pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1473 pwd->pw_name, (uintmax_t)pwd->pw_uid);
1478 if (nis && nis_update() == 0)
1479 pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1481 return (EXIT_SUCCESS);
1485 pw_user_mod(int argc, char **argv, char *arg1)
1487 struct userconf *cnf;
1490 StringList *groups = NULL;
1491 char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1492 const char *cfg = NULL;
1493 char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1494 char *passwd, *class, *nispasswd;
1500 bool quiet, createhome, pretty, dryrun, nis, edited;
1502 mode_t homemode = 0;
1503 time_t expire_time, password_time, now;
1505 expire_time = password_time = -1;
1506 gecos = homedir = grname = name = newname = skel = shell =NULL;
1508 class = nispasswd = NULL;
1509 quiet = createhome = pretty = dryrun = nis = precrypted = false;
1514 if (arg1[strspn(arg1, "0123456789")] == '\0')
1515 id = pw_checkid(arg1, UID_MAX);
1520 while ((ch = getopt(argc, argv, args)) != -1) {
1532 id = pw_checkid(optarg, UID_MAX);
1535 gecos = pw_checkname(optarg, 1);
1541 expire_time = parse_date(now, optarg);
1544 password_time = parse_date(now, optarg);
1547 group_from_name_or_id(optarg);
1551 split_groups(&groups, optarg);
1557 homemode = validate_mode(optarg);
1563 walk = skel = optarg;
1566 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1567 errx(EX_OSFILE, "skeleton `%s' does not "
1569 if (!S_ISDIR(st.st_mode))
1570 errx(EX_OSFILE, "skeleton `%s' is not a "
1580 class = pw_checkname(optarg, 0);
1584 errx(EX_USAGE, "'-h' and '-H' are mutually "
1585 "exclusive options");
1586 fd = pw_checkfd(optarg);
1589 errx(EX_USAGE, "-H expects a file descriptor");
1593 errx(EX_USAGE, "'-h' and '-H' are mutually "
1594 "exclusive options");
1595 fd = pw_checkfd(optarg);
1614 if (geteuid() != 0 && ! dryrun)
1615 errx(EX_NOPERM, "you must be root");
1618 freopen(_PATH_DEVNULL, "w", stderr);
1620 cnf = get_userconfig(cfg);
1622 if (id < 0 && name == NULL)
1623 errx(EX_DATAERR, "username or id required");
1625 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1628 errx(EX_NOUSER, "no such uid `%ju'",
1630 errx(EX_NOUSER, "no such user `%s'", name);
1634 name = pwd->pw_name;
1636 if (nis && nispasswd == NULL)
1637 nispasswd = cnf->nispasswd;
1639 if (PWF._altdir == PWF_REGULAR &&
1640 ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
1641 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
1642 if (!nis && nispasswd && *nispasswd != '/')
1643 errx(EX_NOUSER, "Cannot modify NIS user `%s'",
1646 errx(EX_NOUSER, "Cannot modify non local user `%s'",
1652 if (strcmp(pwd->pw_name, "root") == 0)
1653 errx(EX_DATAERR, "can't rename `root' account");
1654 if (strcmp(pwd->pw_name, newname) != 0) {
1655 pwd->pw_name = pw_checkname(newname, 0);
1660 if (id >= 0 && pwd->pw_uid != id) {
1663 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
1664 errx(EX_DATAERR, "can't change uid of `root' account");
1665 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1666 warnx("WARNING: account `%s' will have a uid of 0 "
1667 "(superuser access!)", pwd->pw_name);
1670 if (grname && pwd->pw_uid != 0) {
1671 grp = GETGRNAM(grname);
1673 grp = GETGRGID(pw_checkid(grname, GID_MAX));
1674 if (grp->gr_gid != pwd->pw_gid) {
1675 pwd->pw_gid = grp->gr_gid;
1681 if (password_time >= 0 && pwd->pw_change != password_time) {
1682 pwd->pw_change = password_time;
1686 if (expire_time >= 0 && pwd->pw_expire != expire_time) {
1687 pwd->pw_expire = expire_time;
1692 shell = shell_path(cnf->shelldir, cnf->shells, shell);
1695 if (strcmp(shell, pwd->pw_shell) != 0) {
1696 pwd->pw_shell = shell;
1701 if (class && strcmp(pwd->pw_class, class) != 0) {
1702 pwd->pw_class = class;
1706 if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1707 pwd->pw_dir = homedir;
1709 if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1711 warnx("WARNING: home `%s' does not exist",
1713 } else if (!S_ISDIR(st.st_mode)) {
1714 warnx("WARNING: home `%s' is not a directory",
1719 if (passwd && conf.fd == -1) {
1720 lc = login_getpwclass(pwd);
1721 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1722 warn("setting crypt(3) format");
1724 cnf->default_password = passwd_val(passwd,
1725 cnf->default_password);
1726 pwd->pw_passwd = pw_password(cnf, pwd->pw_name);
1730 if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1731 pwd->pw_gecos = gecos;
1736 edited = pw_set_passwd(pwd, fd, precrypted, true);
1739 return (print_user(pwd, pretty, false));
1741 if (edited) /* Only updated this if required */
1742 perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1743 /* Now perform the needed changes concern groups */
1744 if (groups != NULL) {
1745 /* Delete User from groups using old name */
1747 while ((grp = GETGRENT()) != NULL) {
1748 if (grp->gr_mem == NULL)
1750 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1751 if (strcmp(grp->gr_mem[i] , name) != 0)
1753 for (j = i; grp->gr_mem[j] != NULL ; j++)
1754 grp->gr_mem[j] = grp->gr_mem[j+1];
1755 chggrent(grp->gr_name, grp);
1760 /* Add the user to the needed groups */
1761 for (i = 0; i < groups->sl_cur; i++) {
1762 grp = GETGRNAM(groups->sl_str[i]);
1763 grp = gr_add(grp, pwd->pw_name);
1766 chggrent(grp->gr_name, grp);
1770 /* In case of rename we need to walk over the different groups */
1773 while ((grp = GETGRENT()) != NULL) {
1774 if (grp->gr_mem == NULL)
1776 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1777 if (strcmp(grp->gr_mem[i], name) != 0)
1779 grp->gr_mem[i] = newname;
1780 chggrent(grp->gr_name, grp);
1786 /* go get a current version of pwd */
1789 pwd = GETPWNAM(name);
1791 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1792 grp = GETGRGID(pwd->pw_gid);
1793 pw_log(cnf, M_UPDATE, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1794 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1795 grp ? grp->gr_name : "unknown",
1796 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1797 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1800 * Let's create and populate the user's home directory. Note
1801 * that this also `works' for editing users if -m is used, but
1802 * existing files will *not* be overwritten.
1804 if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1805 *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1809 homemode = cnf->homemode;
1810 create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1813 if (nis && nis_update() == 0)
1814 pw_log(cnf, M_UPDATE, W_USER, "NIS maps updated");
1816 return (EXIT_SUCCESS);