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, '/');
117 * This is a kludge especially for Joerg :)
118 * If the home directory would be created in the root partition, then
119 * we really create it under /usr which is likely to have more space.
120 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
122 if (strchr(dirs, '/') == NULL) {
123 asprintf(&tmp, "usr/%s", dirs);
125 errx(EX_UNAVAILABLE, "out of memory");
126 if (mkdirat(dfd, tmp, _DEF_DIRMODE) != -1 || errno == EEXIST) {
127 fchownat(dfd, tmp, 0, 0, 0);
128 symlinkat(tmp, dfd, dirs);
133 if (fstatat(dfd, dirs, &st, 0) == -1) {
134 while ((tmp = strchr(tmp + 1, '/')) != NULL) {
136 if (fstatat(dfd, dirs, &st, 0) == -1) {
137 if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
138 err(EX_OSFILE, "'%s' (root home parent) is not a directory", dirs);
143 if (fstatat(dfd, dirs, &st, 0) == -1) {
144 if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
145 err(EX_OSFILE, "'%s' (root home parent) is not a directory", dirs);
146 fchownat(dfd, dirs, 0, 0, 0);
153 create_and_populate_homedir(struct userconf *cnf, struct passwd *pwd,
154 const char *skeldir, mode_t homemode, bool update)
158 /* Create home parents directories */
159 mkdir_home_parents(conf.rootfd, pwd->pw_dir);
161 if (skeldir != NULL && *skeldir != '\0') {
164 skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
167 copymkdir(conf.rootfd, pwd->pw_dir, skelfd, homemode, pwd->pw_uid,
169 pw_log(cnf, update ? M_UPDATE : M_ADD, W_USER, "%s(%ju) home %s made",
170 pwd->pw_name, (uintmax_t)pwd->pw_uid, pwd->pw_dir);
174 pw_set_passwd(struct passwd *pwd, int fd, bool precrypted, bool update)
179 char line[_PASSWORD_LEN+1];
183 if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
184 pwd->pw_passwd = "*"; /* No access */
190 if ((istty = isatty(fd))) {
191 if (tcgetattr(fd, &t) == -1)
195 n.c_lflag &= ~(ECHO);
196 tcsetattr(fd, TCSANOW, &n);
197 printf("%s%spassword for user %s:",
198 update ? "new " : "",
199 precrypted ? "encrypted " : "",
204 b = read(fd, line, sizeof(line) - 1);
205 if (istty) { /* Restore state */
206 tcsetattr(fd, TCSANOW, &t);
212 err(EX_IOERR, "-%c file descriptor",
213 precrypted ? 'H' : 'h');
215 if ((p = strpbrk(line, "\r\n")) != NULL)
218 errx(EX_DATAERR, "empty password read on file descriptor %d",
221 if (strchr(line, ':') != NULL)
222 errx(EX_DATAERR, "bad encrypted password");
223 pwd->pw_passwd = strdup(line);
225 lc = login_getpwclass(pwd);
227 login_setcryptfmt(lc, "sha512", NULL) == NULL)
228 warn("setting crypt(3) format");
230 pwd->pw_passwd = pw_pwcrypt(line);
236 perform_chgpwent(const char *name, struct passwd *pwd, char *nispasswd)
239 struct passwd *nispwd;
241 /* duplicate for nis so that chgpwent is not modifying before NIS */
242 if (nispasswd && *nispasswd == '/')
243 nispwd = pw_dup(pwd);
245 rc = chgpwent(name, pwd);
247 errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
249 err(EX_IOERR, "passwd file update");
251 if (nispasswd && *nispasswd == '/') {
252 rc = chgnispwent(nispasswd, name, nispwd);
254 warn("User '%s' not found in NIS passwd", pwd->pw_name);
256 warn("NIS passwd update");
257 /* NOTE: NIS-only update errors are not fatal */
262 * The M_LOCK and M_UNLOCK functions simply add or remove
263 * a "*LOCKED*" prefix from in front of the password to
264 * prevent it decoding correctly, and therefore prevents
265 * access. Of course, this only prevents access via
266 * password authentication (not ssh, kerberos or any
267 * other method that does not use the UNIX password) but
268 * that is a known limitation.
271 pw_userlock(char *arg1, int mode)
273 struct passwd *pwd = NULL;
274 char *passtmp = NULL;
277 uid_t id = (uid_t)-1;
280 errx(EX_NOPERM, "you must be root");
283 errx(EX_DATAERR, "username or id required");
286 if (arg1[strspn(name, "0123456789")] == '\0')
287 id = pw_checkid(name, UID_MAX);
289 pwd = GETPWNAM(pw_checkname(name, 0));
290 if (pwd == NULL && id != (uid_t)-1) {
297 errx(EX_NOUSER, "no such name or uid `%ju'", (uintmax_t) id);
298 errx(EX_NOUSER, "no such user `%s'", name);
304 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
306 if (mode == M_LOCK && locked)
307 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
308 if (mode == M_UNLOCK && !locked)
309 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
311 if (mode == M_LOCK) {
312 asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
313 if (passtmp == NULL) /* disaster */
314 errx(EX_UNAVAILABLE, "out of memory");
315 pwd->pw_passwd = passtmp;
317 pwd->pw_passwd += sizeof(locked_str)-1;
320 perform_chgpwent(name, pwd, NULL);
323 return (EXIT_SUCCESS);
327 pw_uidpolicy(struct userconf * cnf, intmax_t id)
331 uid_t uid = (uid_t) - 1;
334 * Check the given uid, if any
339 if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
340 errx(EX_DATAERR, "uid `%ju' has already been allocated",
341 (uintmax_t)pwd->pw_uid);
345 * We need to allocate the next available uid under one of
346 * two policies a) Grab the first unused uid b) Grab the
347 * highest possible unused uid
349 if (cnf->min_uid >= cnf->max_uid) { /* Sanity
350 * claus^H^H^H^Hheck */
352 cnf->max_uid = 32000;
354 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
357 * Now, let's fill the bitmap from the password file
360 while ((pwd = GETPWENT()) != NULL)
361 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
362 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
366 * Then apply the policy, with fallback to reuse if necessary
368 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
369 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
372 * Another sanity check
374 if (uid < cnf->min_uid || uid > cnf->max_uid)
375 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
381 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam, gid_t prefer, bool dryrun)
384 gid_t gid = (uid_t) - 1;
387 * Check the given gid, if any
391 if ((grp = GETGRNAM(grname)) == NULL) {
392 gid = pw_checkid(grname, GID_MAX);
396 } else if ((grp = GETGRNAM(nam)) != NULL &&
397 (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
398 gid = grp->gr_gid; /* Already created? Use it anyway... */
403 * We need to auto-create a group with the user's name. We
404 * can send all the appropriate output to our sister routine
405 * bit first see if we can create a group with gid==uid so we
406 * can keep the user and group ids in sync. We purposely do
407 * NOT check the gid range if we can force the sync. If the
408 * user's name dups an existing group, then the group add
409 * function will happily handle that case for us and exit.
411 if (GETGRGID(prefer) == NULL)
414 gid = pw_groupnext(cnf, true);
417 grid = pw_groupnext(cnf, true);
418 groupadd(cnf, nam, grid, NULL, -1, false, false, false);
419 if ((grp = GETGRNAM(nam)) != NULL)
428 pw_homepolicy(struct userconf * cnf, char *homedir, const char *user)
430 static char home[128];
435 if (cnf->home == NULL || *cnf->home == '\0')
436 errx(EX_CONFIG, "no base home directory set");
437 snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
443 shell_path(char const * path, char *shells[], char *sh)
445 if (sh != NULL && (*sh == '/' || *sh == '\0'))
446 return sh; /* specified full path or forced none */
449 char paths[_UC_MAXLINE];
452 * We need to search paths
454 strlcpy(paths, path, sizeof(paths));
455 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
457 static char shellpath[256];
460 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
461 if (access(shellpath, X_OK) == 0)
464 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
465 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
466 if (access(shellpath, X_OK) == 0)
471 errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
472 errx(EX_CONFIG, "no default shell available or defined");
478 pw_shellpolicy(struct userconf * cnf)
481 return shell_path(cnf->shelldir, cnf->shells, cnf->shell_default);
486 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
489 pw_pwcrypt(char *password)
492 char salt[SALTSIZE + 1];
494 static char buf[256];
497 * Calculate a salt value
499 for (i = 0; i < SALTSIZE; i++)
500 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
501 salt[SALTSIZE] = '\0';
503 cryptpw = crypt(password, salt);
505 errx(EX_CONFIG, "crypt(3) failure");
506 return strcpy(buf, cryptpw);
510 pw_password(struct userconf * cnf, char const * user, bool dryrun)
515 switch (cnf->default_password) {
516 case -1: /* Random password */
517 l = (arc4random() % 8 + 8); /* 8 - 16 chars */
518 for (i = 0; i < l; i++)
519 pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
523 * We give this information back to the user
525 if (conf.fd == -1 && !dryrun) {
526 if (isatty(STDOUT_FILENO))
527 printf("Password for '%s' is: ", user);
528 printf("%s\n", pwbuf);
533 case -2: /* No password at all! */
536 case 0: /* No login - default */
540 case 1: /* user's name */
541 strlcpy(pwbuf, user, sizeof(pwbuf));
544 return pw_pwcrypt(pwbuf);
548 print_user(struct passwd * pwd, bool pretty, bool v7)
552 struct group *grp = GETGRGID(pwd->pw_gid);
553 char uname[60] = "User &", office[60] = "[None]",
554 wphone[60] = "[None]", hphone[60] = "[None]";
555 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
559 p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
562 return (EXIT_SUCCESS);
565 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
566 strlcpy(uname, p, sizeof(uname));
567 if ((p = strtok(NULL, ",")) != NULL) {
568 strlcpy(office, p, sizeof(office));
569 if ((p = strtok(NULL, ",")) != NULL) {
570 strlcpy(wphone, p, sizeof(wphone));
571 if ((p = strtok(NULL, "")) != NULL) {
572 strlcpy(hphone, p, sizeof(hphone));
578 * Handle '&' in gecos field
580 if ((p = strchr(uname, '&')) != NULL) {
581 int l = strlen(pwd->pw_name);
584 memmove(p + l, p + 1, m);
585 memmove(p, pwd->pw_name, l);
586 *p = (char) toupper((unsigned char)*p);
588 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
589 strftime(acexpire, sizeof acexpire, "%c", tptr);
590 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
591 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
592 printf("Login Name: %-15s #%-12ju Group: %-15s #%ju\n"
594 " Home: %-26.26s Class: %s\n"
595 " Shell: %-26.26s Office: %s\n"
596 "Work Phone: %-26.26s Home Phone: %s\n"
597 "Acc Expire: %-26.26s Pwd Expire: %s\n",
598 pwd->pw_name, (uintmax_t)pwd->pw_uid,
599 grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
600 uname, pwd->pw_dir, pwd->pw_class,
601 pwd->pw_shell, office, wphone, hphone,
605 while ((grp=GETGRENT()) != NULL) {
607 if (grp->gr_mem != NULL) {
608 while (grp->gr_mem[i] != NULL) {
609 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
610 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
618 printf("%s", j ? "\n" : "");
619 return (EXIT_SUCCESS);
623 pw_checkname(char *name, int gecos)
626 const char *badchars, *ch, *showtype;
632 /* See if the name is valid as a gecos (comment) field. */
634 showtype = "gecos field";
636 /* See if the name is valid as a userid or group. */
637 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
638 showtype = "userid/group name";
639 /* Userids and groups can not have a leading '-'. */
645 if (strchr(badchars, *ch) != NULL ||
646 (!gecos && *ch < ' ') ||
651 /* 8-bit characters are only allowed in GECOS fields */
652 if (!gecos && (*ch & 0x80)) {
660 * A `$' is allowed as the final character for userids and groups,
661 * mainly for the benefit of samba.
663 if (reject && !gecos) {
664 if (*ch == '$' && *(ch + 1) == '\0') {
670 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
671 ? "`%c'" : "0x%02x", *ch);
672 errx(EX_DATAERR, "invalid character %s at position %td in %s",
673 showch, (ch - name), showtype);
675 if (!gecos && (ch - name) > LOGNAMESIZE)
676 errx(EX_USAGE, "name too long `%s' (max is %d)", name,
685 DIR *d = opendir("/var/at/jobs");
690 while ((e = readdir(d)) != NULL) {
693 if (strncmp(e->d_name, ".lock", 5) != 0 &&
694 stat(e->d_name, &st) == 0 &&
695 !S_ISDIR(st.st_mode) &&
697 char tmp[MAXPATHLEN];
699 snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s",
709 rmopie(char const * name)
717 if ((fd = openat(conf.rootfd, "etc/opiekeys", O_RDWR)) == -1)
720 fp = fdopen(fd, "r+");
723 while (fgets(tmp, sizeof(tmp), fp) != NULL) {
724 if (strncmp(name, tmp, len) == 0 && tmp[len]==' ') {
725 /* Comment username out */
726 if (fseek(fp, atofs, SEEK_SET) == 0)
727 fwrite("#", 1, 1, fp);
733 * If we got an error of any sort, don't update!
739 pw_user_next(int argc, char **argv, char *name __unused)
741 struct userconf *cnf = NULL;
742 const char *cfg = NULL;
747 while ((ch = getopt(argc, argv, "Cq")) != -1) {
759 freopen(_PATH_DEVNULL, "w", stderr);
761 cnf = get_userconfig(cfg);
763 next = pw_uidpolicy(cnf, -1);
765 printf("%ju:", (uintmax_t)next);
766 pw_groupnext(cnf, quiet);
768 return (EXIT_SUCCESS);
772 pw_user_show(int argc, char **argv, char *arg1)
774 struct passwd *pwd = NULL;
785 if (arg1[strspn(arg1, "0123456789")] == '\0')
786 id = pw_checkid(arg1, UID_MAX);
791 while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
794 /* ignore compatibility */
803 id = pw_checkid(optarg, UID_MAX);
821 freopen(_PATH_DEVNULL, "w", stderr);
825 while ((pwd = GETPWENT()) != NULL)
826 print_user(pwd, pretty, v7);
828 return (EXIT_SUCCESS);
831 if (id < 0 && name == NULL)
832 errx(EX_DATAERR, "username or id required");
834 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
840 errx(EX_NOUSER, "no such uid `%ju'",
842 errx(EX_NOUSER, "no such user `%s'", name);
846 return (print_user(pwd, pretty, v7));
850 pw_user_del(int argc, char **argv, char *arg1)
852 struct userconf *cnf = NULL;
853 struct passwd *pwd = NULL;
854 struct group *gr, *grp;
856 char grname[MAXLOGNAME];
857 char *nispasswd = NULL;
858 char file[MAXPATHLEN];
859 char home[MAXPATHLEN];
860 const char *cfg = NULL;
865 bool deletehome = false;
869 if (arg1[strspn(arg1, "0123456789")] == '\0')
870 id = pw_checkid(arg1, UID_MAX);
875 while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
887 id = pw_checkid(optarg, UID_MAX);
902 freopen(_PATH_DEVNULL, "w", stderr);
904 if (id < 0 && name == NULL)
905 errx(EX_DATAERR, "username or id required");
907 cnf = get_userconfig(cfg);
909 if (nispasswd == NULL)
910 nispasswd = cnf->nispasswd;
912 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
915 errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
916 errx(EX_NOUSER, "no such user `%s'", name);
919 if (PWF._altdir == PWF_REGULAR &&
920 ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
921 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
922 if (!nis && nispasswd && *nispasswd != '/')
923 errx(EX_NOUSER, "Cannot remove NIS user `%s'",
926 errx(EX_NOUSER, "Cannot remove non local user `%s'",
935 if (strcmp(pwd->pw_name, "root") == 0)
936 errx(EX_DATAERR, "cannot remove user 'root'");
938 /* Remove opie record from /etc/opiekeys */
939 if (PWALTDIR() != PWF_ALT)
940 rmopie(pwd->pw_name);
943 /* Remove crontabs */
944 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
945 if (access(file, F_OK) == 0) {
946 snprintf(file, sizeof(file), "crontab -u %s -r",
953 * Save these for later, since contents of pwd may be
954 * invalidated by deletion
956 snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
957 strlcpy(home, pwd->pw_dir, sizeof(home));
958 gr = GETGRGID(pwd->pw_gid);
960 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
966 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
968 err(EX_IOERR, "passwd update");
970 if (nis && nispasswd && *nispasswd=='/') {
971 rc = delnispwent(nispasswd, name);
973 warnx("WARNING: user '%s' does not exist in NIS passwd",
976 warn("WARNING: NIS passwd update");
979 grp = GETGRNAM(name);
981 (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
982 strcmp(name, grname) == 0)
983 delgrent(GETGRNAM(name));
985 while ((grp = GETGRENT()) != NULL) {
987 char group[MAXLOGNAME];
988 if (grp->gr_mem == NULL)
991 for (i = 0; grp->gr_mem[i] != NULL; i++) {
992 if (strcmp(grp->gr_mem[i], name) != 0)
995 for (j = i; grp->gr_mem[j] != NULL; j++)
996 grp->gr_mem[j] = grp->gr_mem[j+1];
997 strlcpy(group, grp->gr_name, MAXLOGNAME);
998 chggrent(group, grp);
1003 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
1006 /* Remove mail file */
1007 if (PWALTDIR() != PWF_ALT)
1008 unlinkat(conf.rootfd, file + 1, 0);
1010 /* Remove at jobs */
1011 if (!PWALTDIR() && getpwuid(id) == NULL)
1014 /* Remove home directory and contents */
1015 if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
1016 GETPWUID(id) == NULL &&
1017 fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1018 rm_r(conf.rootfd, home, id);
1019 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
1020 "removed", name, (uintmax_t)id, home,
1021 fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1025 return (EXIT_SUCCESS);
1029 pw_user_lock(int argc, char **argv, char *arg1)
1033 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1042 return (pw_userlock(arg1, M_LOCK));
1046 pw_user_unlock(int argc, char **argv, char *arg1)
1050 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1059 return (pw_userlock(arg1, M_UNLOCK));
1062 static struct group *
1063 group_from_name_or_id(char *name)
1065 const char *errstr = NULL;
1069 if ((grp = GETGRNAM(name)) == NULL) {
1070 id = strtounum(name, 0, GID_MAX, &errstr);
1072 errx(EX_NOUSER, "group `%s' does not exist", name);
1075 errx(EX_NOUSER, "group `%s' does not exist", name);
1082 split_groups(StringList **groups, char *groupsstr)
1086 char tok[] = ", \t";
1088 for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1089 grp = group_from_name_or_id(p);
1090 if (*groups == NULL)
1091 *groups = sl_init();
1092 sl_add(*groups, newstr(grp->gr_name));
1097 validate_grname(struct userconf *cnf, char *group)
1101 if (group == NULL || *group == '\0') {
1102 cnf->default_group = "";
1105 grp = group_from_name_or_id(group);
1106 cnf->default_group = newstr(grp->gr_name);
1110 validate_mode(char *mode)
1115 if ((set = setmode(mode)) == NULL)
1116 errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1118 m = getmode(set, _DEF_DIRMODE);
1124 mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1127 if (cmdcnf->default_password == 0)
1128 cmdcnf->default_password = cfg->default_password;
1129 if (cmdcnf->reuse_uids == 0)
1130 cmdcnf->reuse_uids = cfg->reuse_uids;
1131 if (cmdcnf->reuse_gids == 0)
1132 cmdcnf->reuse_gids = cfg->reuse_gids;
1133 if (cmdcnf->nispasswd == NULL)
1134 cmdcnf->nispasswd = cfg->nispasswd;
1135 if (cmdcnf->dotdir == NULL)
1136 cmdcnf->dotdir = cfg->dotdir;
1137 if (cmdcnf->newmail == NULL)
1138 cmdcnf->newmail = cfg->newmail;
1139 if (cmdcnf->logfile == NULL)
1140 cmdcnf->logfile = cfg->logfile;
1141 if (cmdcnf->home == NULL)
1142 cmdcnf->home = cfg->home;
1143 if (cmdcnf->homemode == 0)
1144 cmdcnf->homemode = cfg->homemode;
1145 if (cmdcnf->shelldir == NULL)
1146 cmdcnf->shelldir = cfg->shelldir;
1147 if (cmdcnf->shells == NULL)
1148 cmdcnf->shells = cfg->shells;
1149 if (cmdcnf->shell_default == NULL)
1150 cmdcnf->shell_default = cfg->shell_default;
1151 if (cmdcnf->default_group == NULL)
1152 cmdcnf->default_group = cfg->default_group;
1153 if (cmdcnf->groups == NULL)
1154 cmdcnf->groups = cfg->groups;
1155 if (cmdcnf->default_class == NULL)
1156 cmdcnf->default_class = cfg->default_class;
1157 if (cmdcnf->min_uid == 0)
1158 cmdcnf->min_uid = cfg->min_uid;
1159 if (cmdcnf->max_uid == 0)
1160 cmdcnf->max_uid = cfg->max_uid;
1161 if (cmdcnf->min_gid == 0)
1162 cmdcnf->min_gid = cfg->min_gid;
1163 if (cmdcnf->max_gid == 0)
1164 cmdcnf->max_gid = cfg->max_gid;
1165 if (cmdcnf->expire_days == 0)
1166 cmdcnf->expire_days = cfg->expire_days;
1167 if (cmdcnf->password_days == 0)
1168 cmdcnf->password_days = cfg->password_days;
1172 pw_user_add(int argc, char **argv, char *arg1)
1174 struct userconf *cnf, *cmdcnf;
1178 char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1179 char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1180 char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1181 char *default_passwd, *name, *p;
1182 const char *cfg = NULL;
1187 int rc, ch, fd = -1;
1189 bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1191 dryrun = nis = pretty = quiet = createhome = precrypted = false;
1193 gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1194 grname = name = NULL;
1196 if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1197 err(EXIT_FAILURE, "calloc()");
1200 if (arg1[strspn(arg1, "0123456789")] == '\0')
1201 id = pw_checkid(arg1, UID_MAX);
1206 while ((ch = getopt(argc, argv, args)) != -1) {
1221 gecos = pw_checkname(optarg, 1);
1228 cmdcnf->expire_days = parse_date(now, optarg);
1232 cmdcnf->password_days = parse_date(now, optarg);
1235 validate_grname(cmdcnf, optarg);
1239 split_groups(&cmdcnf->groups, optarg);
1245 cmdcnf->homemode = validate_mode(optarg);
1248 walk = skel = optarg;
1251 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1252 errx(EX_OSFILE, "skeleton `%s' does not "
1254 if (!S_ISDIR(st.st_mode))
1255 errx(EX_OSFILE, "skeleton `%s' is not a "
1257 cmdcnf->dotdir = skel;
1260 cmdcnf->shell_default = optarg;
1263 conf.checkduplicate = false;
1266 cmdcnf->default_class = pw_checkname(optarg, 0);
1272 default_passwd = optarg;
1276 errx(EX_USAGE, "'-h' and '-H' are mutually "
1277 "exclusive options");
1278 fd = pw_checkfd(optarg);
1281 errx(EX_USAGE, "-H expects a file descriptor");
1285 errx(EX_USAGE, "'-h' and '-H' are mutually "
1286 "exclusive options");
1287 fd = pw_checkfd(optarg);
1293 cmdcnf->home = optarg;
1302 cmdcnf->nispasswd = optarg;
1310 if (geteuid() != 0 && ! dryrun)
1311 errx(EX_NOPERM, "you must be root");
1314 freopen(_PATH_DEVNULL, "w", stderr);
1316 cnf = get_userconfig(cfg);
1318 mix_config(cmdcnf, cnf);
1320 cmdcnf->default_password = passwd_val(default_passwd,
1321 cnf->default_password);
1324 errx(EX_DATAERR, "can't combine `-D' with `-n name'");
1325 if (userid != NULL) {
1326 if ((p = strtok(userid, ", \t")) != NULL)
1327 cmdcnf->min_uid = pw_checkid(p, UID_MAX);
1328 if (cmdcnf->min_uid == 0)
1329 cmdcnf->min_uid = 1000;
1330 if ((p = strtok(NULL, " ,\t")) != NULL)
1331 cmdcnf->max_uid = pw_checkid(p, UID_MAX);
1332 if (cmdcnf->max_uid == 0)
1333 cmdcnf->max_uid = 32000;
1335 if (groupid != NULL) {
1336 if ((p = strtok(groupid, ", \t")) != NULL)
1337 cmdcnf->min_gid = pw_checkid(p, GID_MAX);
1338 if (cmdcnf->min_gid == 0)
1339 cmdcnf->min_gid = 1000;
1340 if ((p = strtok(NULL, " ,\t")) != NULL)
1341 cmdcnf->max_gid = pw_checkid(p, GID_MAX);
1342 if (cmdcnf->max_gid == 0)
1343 cmdcnf->max_gid = 32000;
1345 if (write_userconfig(cmdcnf, cfg))
1346 return (EXIT_SUCCESS);
1347 err(EX_IOERR, "config update");
1351 id = pw_checkid(userid, UID_MAX);
1352 if (id < 0 && name == NULL)
1353 errx(EX_DATAERR, "user name or id required");
1356 errx(EX_DATAERR, "login name required");
1358 if (GETPWNAM(name) != NULL)
1359 errx(EX_DATAERR, "login name `%s' already exists", name);
1362 grname = cmdcnf->default_group;
1365 pwd->pw_name = name;
1366 pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1367 pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1368 pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1369 (gid_t) pwd->pw_uid, dryrun);
1370 pwd->pw_change = cmdcnf->password_days;
1371 pwd->pw_expire = cmdcnf->expire_days;
1372 pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1373 pwd->pw_shell = pw_shellpolicy(cmdcnf);
1374 lc = login_getpwclass(pwd);
1375 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1376 warn("setting crypt(3) format");
1378 pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name, dryrun);
1379 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1380 warnx("WARNING: new account `%s' has a uid of 0 "
1381 "(superuser access!)", pwd->pw_name);
1383 pwd->pw_gecos = gecos;
1386 pw_set_passwd(pwd, fd, precrypted, false);
1389 return (print_user(pwd, pretty, false));
1391 if ((rc = addpwent(pwd)) != 0) {
1393 errx(EX_IOERR, "user '%s' already exists",
1396 err(EX_IOERR, "passwd file update");
1398 if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1399 printf("%s\n", cmdcnf->nispasswd);
1400 rc = addnispwent(cmdcnf->nispasswd, pwd);
1402 warnx("User '%s' already exists in NIS passwd",
1405 warn("NIS passwd update");
1406 /* NOTE: we treat NIS-only update errors as non-fatal */
1409 if (cmdcnf->groups != NULL) {
1410 for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1411 grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1412 grp = gr_add(grp, pwd->pw_name);
1414 * grp can only be NULL in 2 cases:
1415 * - the new member is already a member
1416 * - a problem with memory occurs
1417 * in both cases we want to skip now.
1421 chggrent(grp->gr_name, grp);
1426 pwd = GETPWNAM(name);
1428 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1430 grp = GETGRGID(pwd->pw_gid);
1431 pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1432 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1433 grp ? grp->gr_name : "unknown",
1434 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1435 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1438 * let's touch and chown the user's mail file. This is not
1439 * strictly necessary under BSD with a 0755 maildir but it also
1440 * doesn't hurt anything to create the empty mailfile
1442 if (PWALTDIR() != PWF_ALT) {
1443 snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1445 /* Preserve contents & mtime */
1446 close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1447 fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1448 AT_SYMLINK_NOFOLLOW);
1452 * Let's create and populate the user's home directory. Note
1453 * that this also `works' for editing users if -m is used, but
1454 * existing files will *not* be overwritten.
1456 if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1457 *pwd->pw_dir == '/' && pwd->pw_dir[1])
1458 create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1459 cmdcnf->homemode, false);
1461 if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1462 (fp = fopen(cnf->newmail, "r")) != NULL) {
1463 if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1466 fprintf(pfp, "From: root\n" "To: %s\n"
1467 "Subject: Welcome!\n\n", pwd->pw_name);
1468 while (fgets(line, sizeof(line), fp) != NULL) {
1469 /* Do substitutions? */
1473 pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1474 pwd->pw_name, (uintmax_t)pwd->pw_uid);
1479 if (nis && nis_update() == 0)
1480 pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1482 return (EXIT_SUCCESS);
1486 pw_user_mod(int argc, char **argv, char *arg1)
1488 struct userconf *cnf;
1491 StringList *groups = NULL;
1492 char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1493 const char *cfg = NULL;
1494 char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1495 char *passwd, *class, *nispasswd;
1501 bool quiet, createhome, pretty, dryrun, nis, edited;
1503 mode_t homemode = 0;
1504 time_t expire_days, password_days, now;
1506 expire_days = password_days = -1;
1507 gecos = homedir = grname = name = newname = skel = shell =NULL;
1509 class = nispasswd = NULL;
1510 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);
1542 expire_days = parse_date(now, optarg);
1546 password_days = parse_date(now, optarg);
1549 group_from_name_or_id(optarg);
1553 split_groups(&groups, optarg);
1559 homemode = validate_mode(optarg);
1565 walk = skel = optarg;
1568 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1569 errx(EX_OSFILE, "skeleton `%s' does not "
1571 if (!S_ISDIR(st.st_mode))
1572 errx(EX_OSFILE, "skeleton `%s' is not a "
1582 class = pw_checkname(optarg, 0);
1586 errx(EX_USAGE, "'-h' and '-H' are mutually "
1587 "exclusive options");
1588 fd = pw_checkfd(optarg);
1591 errx(EX_USAGE, "-H expects a file descriptor");
1595 errx(EX_USAGE, "'-h' and '-H' are mutually "
1596 "exclusive options");
1597 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;
1680 if (password_days >= 0 && pwd->pw_change != password_days) {
1681 pwd->pw_change = password_days;
1685 if (expire_days >= 0 && pwd->pw_expire != expire_days) {
1686 pwd->pw_expire = expire_days;
1691 shell = shell_path(cnf->shelldir, cnf->shells, shell);
1694 if (strcmp(shell, pwd->pw_shell) != 0) {
1695 pwd->pw_shell = shell;
1700 if (class && strcmp(pwd->pw_class, class) != 0) {
1701 pwd->pw_class = class;
1705 if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1706 pwd->pw_dir = homedir;
1708 if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1710 warnx("WARNING: home `%s' does not exist",
1712 } else if (!S_ISDIR(st.st_mode)) {
1713 warnx("WARNING: home `%s' is not a directory",
1718 if (passwd && conf.fd == -1) {
1719 lc = login_getpwclass(pwd);
1720 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1721 warn("setting crypt(3) format");
1723 cnf->default_password = passwd_val(passwd,
1724 cnf->default_password);
1725 pwd->pw_passwd = pw_password(cnf, pwd->pw_name, dryrun);
1729 if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1730 pwd->pw_gecos = gecos;
1735 edited = pw_set_passwd(pwd, fd, precrypted, true);
1738 return (print_user(pwd, pretty, false));
1740 if (edited) /* Only updated this if required */
1741 perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1742 /* Now perform the needed changes concern groups */
1743 if (groups != NULL) {
1744 /* Delete User from groups using old name */
1746 while ((grp = GETGRENT()) != NULL) {
1747 if (grp->gr_mem == NULL)
1749 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1750 if (strcmp(grp->gr_mem[i] , name) != 0)
1752 for (j = i; grp->gr_mem[j] != NULL ; j++)
1753 grp->gr_mem[j] = grp->gr_mem[j+1];
1754 chggrent(grp->gr_name, grp);
1759 /* Add the user to the needed groups */
1760 for (i = 0; i < groups->sl_cur; i++) {
1761 grp = GETGRNAM(groups->sl_str[i]);
1762 grp = gr_add(grp, pwd->pw_name);
1765 chggrent(grp->gr_name, grp);
1769 /* In case of rename we need to walk over the different groups */
1772 while ((grp = GETGRENT()) != NULL) {
1773 if (grp->gr_mem == NULL)
1775 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1776 if (strcmp(grp->gr_mem[i], name) != 0)
1778 grp->gr_mem[i] = newname;
1779 chggrent(grp->gr_name, grp);
1785 /* go get a current version of pwd */
1788 pwd = GETPWNAM(name);
1790 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1791 grp = GETGRGID(pwd->pw_gid);
1792 pw_log(cnf, M_UPDATE, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1793 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1794 grp ? grp->gr_name : "unknown",
1795 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1796 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1799 * Let's create and populate the user's home directory. Note
1800 * that this also `works' for editing users if -m is used, but
1801 * existing files will *not* be overwritten.
1803 if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1804 *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1808 homemode = cnf->homemode;
1809 create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1812 if (nis && nis_update() == 0)
1813 pw_log(cnf, M_UPDATE, W_USER, "NIS maps updated");
1815 return (EXIT_SUCCESS);