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[] =
37 #include <sys/param.h>
41 #include <sys/types.h>
43 #include <sys/resource.h>
44 #include <login_cap.h>
51 #define LOGNAMESIZE (MAXLOGNAME-1)
53 static char locked_str[] = "*LOCKED*";
55 static int pw_userdel(char *name, long id);
56 static int print_user(struct passwd * pwd);
57 static uid_t pw_uidpolicy(struct userconf * cnf, long id);
58 static uid_t pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer);
59 static time_t pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
60 static time_t pw_exppolicy(struct userconf * cnf, struct cargs * args);
61 static char *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
62 static char *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
63 static char *pw_password(struct userconf * cnf, char const * user);
64 static char *shell_path(char const * path, char *shells[], char *sh);
65 static void rmat(uid_t uid);
66 static void rmopie(char const * name);
69 create_and_populate_homedir(struct passwd *pwd)
71 struct userconf *cnf = conf.userconf;
75 skeldir = cnf->dotdir;
77 if (skeldir != NULL && *skeldir != '\0') {
80 skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
83 copymkdir(conf.rootfd, pwd->pw_dir, skelfd, cnf->homemode, pwd->pw_uid,
85 pw_log(cnf, M_ADD, W_USER, "%s(%ju) home %s made", pwd->pw_name,
86 (uintmax_t)pwd->pw_uid, pwd->pw_dir);
90 set_passwd(struct passwd *pwd, bool update)
95 char line[_PASSWORD_LEN+1];
99 if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
100 pwd->pw_passwd = "*"; /* No access */
106 if ((istty = isatty(conf.fd))) {
107 if (tcgetattr(conf.fd, &t) == -1)
111 n.c_lflag &= ~(ECHO);
112 tcsetattr(conf.fd, TCSANOW, &n);
113 printf("%s%spassword for user %s:",
114 update ? "new " : "",
115 conf.precrypted ? "encrypted " : "",
120 b = read(conf.fd, line, sizeof(line) - 1);
121 if (istty) { /* Restore state */
122 tcsetattr(conf.fd, TCSANOW, &t);
128 err(EX_IOERR, "-%c file descriptor",
129 conf.precrypted ? 'H' : 'h');
131 if ((p = strpbrk(line, "\r\n")) != NULL)
134 errx(EX_DATAERR, "empty password read on file descriptor %d",
136 if (conf.precrypted) {
137 if (strchr(line, ':') != NULL)
138 errx(EX_DATAERR, "bad encrypted password");
139 pwd->pw_passwd = line;
141 lc = login_getpwclass(pwd);
143 login_setcryptfmt(lc, "sha512", NULL) == NULL)
144 warn("setting crypt(3) format");
146 pwd->pw_passwd = pw_pwcrypt(line);
152 pw_usernext(struct userconf *cnf, bool quiet)
154 uid_t next = pw_uidpolicy(cnf, -1);
159 printf("%ju:", (uintmax_t)next);
160 pw_groupnext(cnf, quiet);
162 return (EXIT_SUCCESS);
166 pw_usershow(char *name, long id, struct passwd *fakeuser)
168 struct passwd *pwd = NULL;
170 if (id < 0 && name == NULL && !conf.all)
171 errx(EX_DATAERR, "username or id or '-a' required");
175 while ((pwd = GETPWENT()) != NULL)
178 return (EXIT_SUCCESS);
181 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
187 errx(EX_NOUSER, "no such uid `%ld'", id);
188 errx(EX_NOUSER, "no such user `%s'", name);
192 return (print_user(pwd));
196 perform_chgpwent(const char *name, struct passwd *pwd)
200 rc = chgpwent(name, pwd);
202 errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
204 err(EX_IOERR, "passwd file update");
206 if (conf.userconf->nispasswd && *conf.userconf->nispasswd == '/') {
207 rc = chgnispwent(conf.userconf->nispasswd, name, pwd);
209 warn("User '%s' not found in NIS passwd", pwd->pw_name);
211 warn("NIS passwd update");
212 /* NOTE: NIS-only update errors are not fatal */
217 * The M_LOCK and M_UNLOCK functions simply add or remove
218 * a "*LOCKED*" prefix from in front of the password to
219 * prevent it decoding correctly, and therefore prevents
220 * access. Of course, this only prevents access via
221 * password authentication (not ssh, kerberos or any
222 * other method that does not use the UNIX password) but
223 * that is a known limitation.
226 pw_userlock(char *name, long id, int mode)
228 struct passwd *pwd = NULL;
229 char *passtmp = NULL;
232 if (id < 0 && name == NULL)
233 errx(EX_DATAERR, "username or id required");
235 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
238 errx(EX_NOUSER, "no such uid `%ld'", id);
239 errx(EX_NOUSER, "no such user `%s'", name);
245 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
247 if (mode == M_LOCK && locked)
248 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
249 if (mode == M_UNLOCK && !locked)
250 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
252 if (mode == M_LOCK) {
253 asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
254 if (passtmp == NULL) /* disaster */
255 errx(EX_UNAVAILABLE, "out of memory");
256 pwd->pw_passwd = passtmp;
258 pwd->pw_passwd += sizeof(locked_str)-1;
261 perform_chgpwent(name, pwd);
264 return (EXIT_SUCCESS);
268 * -C config configuration file
272 * -c comment user name/comment
273 * -d directory home directory
274 * -e date account expiry date
275 * -p date password expiry date
276 * -g grp primary group
277 * -G grp1,grp2 additional groups
278 * -m [ -k dir ] create and set up home
279 * -s shell name of login shell
280 * -o duplicate uid ok
281 * -L class user class
282 * -l name new login name
283 * -h fd password filehandle
284 * -H fd encrypted password filehandle
285 * -F force print or add
287 * -D set user defaults
288 * -b dir default home root dir
289 * -e period default expiry period
290 * -p period default password change period
291 * -g group default group
292 * -G grp1,grp2.. default additional groups
293 * -L class default login class
294 * -k dir default home skeleton
295 * -s shell default shell
296 * -w method default password method
300 pw_user(int mode, char *name, long id, struct cargs * args)
305 struct passwd *pwd = NULL;
308 struct userconf *cnf;
309 char line[_PASSWORD_LEN+1];
310 char path[MAXPATHLEN];
314 int valid_type = _PWF_FILES;
316 static struct passwd fakeuser =
328 #if defined(__FreeBSD__)
336 return (pw_usernext(cnf, conf.quiet));
339 return (pw_usershow(name, id, &fakeuser));
341 if (mode == M_DELETE)
342 return (pw_userdel(name, id));
344 if (mode == M_LOCK || mode == M_UNLOCK)
345 return (pw_userlock(name, id, mode));
348 * We can do all of the common legwork here
351 if ((arg = getarg(args, 'b')) != NULL) {
352 cnf->home = arg->val;
355 if ((arg = getarg(args, 'M')) != NULL) {
357 if ((set = setmode(dmode_c)) == NULL)
358 errx(EX_DATAERR, "invalid directory creation mode '%s'",
360 cnf->homemode = getmode(set, _DEF_DIRMODE);
365 * If we'll need to use it or we're updating it,
366 * then create the base home directory if necessary
368 if (arg != NULL || getarg(args, 'm') != NULL) {
369 int l = strlen(cnf->home);
371 if (l > 1 && cnf->home[l-1] == '/') /* Shave off any trailing path delimiter */
372 cnf->home[--l] = '\0';
374 if (l < 2 || *cnf->home != '/') /* Check for absolute path name */
375 errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
377 if (stat(cnf->home, &st) == -1) {
378 char dbuf[MAXPATHLEN];
381 * This is a kludge especially for Joerg :)
382 * If the home directory would be created in the root partition, then
383 * we really create it under /usr which is likely to have more space.
384 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
386 if (strchr(cnf->home+1, '/') == NULL) {
387 snprintf(dbuf, MAXPATHLEN, "/usr%s", cnf->home);
388 if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
391 * Skip first "/" and create symlink:
394 symlink(dbuf+1, cnf->home);
396 /* If this falls, fall back to old method */
398 strlcpy(dbuf, cnf->home, sizeof(dbuf));
400 if (stat(dbuf, &st) == -1) {
401 while ((p = strchr(p + 1, '/')) != NULL) {
403 if (stat(dbuf, &st) == -1) {
404 if (mkdir(dbuf, _DEF_DIRMODE) == -1)
405 err(EX_OSFILE, "mkdir '%s'", dbuf);
407 } else if (!S_ISDIR(st.st_mode))
408 errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
412 if (stat(dbuf, &st) == -1) {
413 if (mkdir(dbuf, _DEF_DIRMODE) == -1)
414 err(EX_OSFILE, "mkdir '%s'", dbuf);
417 } else if (!S_ISDIR(st.st_mode))
418 errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
421 if ((arg = getarg(args, 'e')) != NULL)
422 cnf->expire_days = atoi(arg->val);
424 if ((arg = getarg(args, 'y')) != NULL)
425 cnf->nispasswd = arg->val;
427 if ((arg = getarg(args, 'p')) != NULL && arg->val)
428 cnf->password_days = atoi(arg->val);
430 if ((arg = getarg(args, 'g')) != NULL) {
431 if (!*(p = arg->val)) /* Handle empty group list specially */
432 cnf->default_group = "";
434 if ((grp = GETGRNAM(p)) == NULL) {
435 if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
436 errx(EX_NOUSER, "group `%s' does not exist", p);
438 cnf->default_group = newstr(grp->gr_name);
441 if ((arg = getarg(args, 'L')) != NULL)
442 cnf->default_class = pw_checkname(arg->val, 0);
444 if ((arg = getarg(args, 'G')) != NULL && arg->val) {
445 for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
446 if ((grp = GETGRNAM(p)) == NULL) {
447 if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
448 errx(EX_NOUSER, "group `%s' does not exist", p);
450 sl_add(cnf->groups, newstr(grp->gr_name));
454 if ((arg = getarg(args, 'k')) != NULL) {
455 char *tmp = cnf->dotdir = arg->val;
458 if ((fstatat(conf.rootfd, tmp, &st, 0) == -1) ||
459 !S_ISDIR(st.st_mode))
460 errx(EX_OSFILE, "skeleton `%s' is not a directory or "
461 "does not exist", cnf->dotdir);
464 if ((arg = getarg(args, 's')) != NULL)
465 cnf->shell_default = arg->val;
467 if ((arg = getarg(args, 'w')) != NULL)
468 cnf->default_password = boolean_val(arg->val, cnf->default_password);
469 if (mode == M_ADD && getarg(args, 'D')) {
471 errx(EX_DATAERR, "can't combine `-D' with `-n name'");
472 if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
473 if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
475 if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
476 cnf->max_uid = 32000;
478 if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
479 if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
481 if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
482 cnf->max_gid = 32000;
485 if (write_userconfig(conf.config))
486 return (EXIT_SUCCESS);
487 err(EX_IOERR, "config udpate");
491 pwd = GETPWNAM(pw_checkname(name, 0));
493 if (id < 0 && name == NULL)
494 errx(EX_DATAERR, "user name or id required");
497 * Update require that the user exists
499 if (mode == M_UPDATE) {
501 if (name == NULL && pwd == NULL) /* Try harder */
506 errx(EX_NOUSER, "no such uid `%ld'", id);
507 errx(EX_NOUSER, "no such user `%s'", name);
510 if (conf.userconf->nispasswd && *conf.userconf->nispasswd == '/')
511 valid_type = _PWF_NIS;
513 if (PWF._altdir == PWF_REGULAR &&
514 ((pwd->pw_fields & _PWF_SOURCE) != valid_type))
515 errx(EX_NOUSER, "no such %s user `%s'",
516 valid_type == _PWF_FILES ? "local" : "NIS" , name);
522 * The rest is edit code
524 if (conf.newname != NULL) {
525 if (strcmp(pwd->pw_name, "root") == 0)
526 errx(EX_DATAERR, "can't rename `root' account");
527 pwd->pw_name = pw_checkname(conf.newname, 0);
531 if (id > 0 && isdigit((unsigned char)*arg->val)) {
532 pwd->pw_uid = (uid_t)id;
534 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
535 errx(EX_DATAERR, "can't change uid of `root' account");
536 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
537 warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
540 if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) { /* Already checked this */
541 gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
542 if (newgid != pwd->pw_gid) {
544 pwd->pw_gid = newgid;
548 if ((arg = getarg(args, 'p')) != NULL) {
549 if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
550 if (pwd->pw_change != 0) {
556 time_t now = time(NULL);
557 time_t expire = parse_date(now, arg->val);
559 if (pwd->pw_change != expire) {
560 pwd->pw_change = expire;
566 if ((arg = getarg(args, 'e')) != NULL) {
567 if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
568 if (pwd->pw_expire != 0) {
574 time_t now = time(NULL);
575 time_t expire = parse_date(now, arg->val);
577 if (pwd->pw_expire != expire) {
578 pwd->pw_expire = expire;
584 if ((arg = getarg(args, 's')) != NULL) {
585 char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
588 if (strcmp(shell, pwd->pw_shell) != 0) {
589 pwd->pw_shell = shell;
594 if (getarg(args, 'L')) {
595 if (cnf->default_class == NULL)
596 cnf->default_class = "";
597 if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
598 pwd->pw_class = cnf->default_class;
603 if ((arg = getarg(args, 'd')) != NULL) {
604 if (strcmp(pwd->pw_dir, arg->val))
606 if (stat(pwd->pw_dir = arg->val, &st) == -1) {
607 if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
608 warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
609 } else if (!S_ISDIR(st.st_mode))
610 warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
613 if ((arg = getarg(args, 'w')) != NULL && conf.fd == -1) {
616 lc = login_getpwclass(pwd);
618 login_setcryptfmt(lc, "sha512", NULL) == NULL)
619 warn("setting crypt(3) format");
621 pwd->pw_passwd = pw_password(cnf, pwd->pw_name);
632 if (name == NULL) /* Required */
633 errx(EX_DATAERR, "login name required");
634 else if ((pwd = GETPWNAM(name)) != NULL) /* Exists */
635 errx(EX_DATAERR, "login name `%s' already exists", name);
638 * Now, set up defaults for a new user
642 pwd->pw_class = cnf->default_class ? cnf->default_class : "";
643 pwd->pw_uid = pw_uidpolicy(cnf, id);
644 pwd->pw_gid = pw_gidpolicy(args, pwd->pw_name, (gid_t) pwd->pw_uid);
645 pwd->pw_change = pw_pwdpolicy(cnf, args);
646 pwd->pw_expire = pw_exppolicy(cnf, args);
647 pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
648 pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
649 lc = login_getpwclass(pwd);
650 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
651 warn("setting crypt(3) format");
653 pwd->pw_passwd = pw_password(cnf, pwd->pw_name);
656 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
657 warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
661 * Shared add/edit code
663 if (conf.gecos != NULL) {
664 if (strcmp(pwd->pw_gecos, conf.gecos) != 0) {
665 pwd->pw_gecos = conf.gecos;
671 edited = set_passwd(pwd, mode == M_UPDATE);
674 * Special case: -N only displays & exits
677 return print_user(pwd);
680 edited = 1; /* Always */
683 errx(EX_IOERR, "user '%s' already exists",
686 err(EX_IOERR, "passwd file update");
687 if (cnf->nispasswd && *cnf->nispasswd=='/') {
688 rc = addnispwent(cnf->nispasswd, pwd);
690 warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
692 warn("NIS passwd update");
693 /* NOTE: we treat NIS-only update errors as non-fatal */
695 } else if (mode == M_UPDATE && edited) /* Only updated this if required */
696 perform_chgpwent(name, pwd);
699 * Ok, user is created or changed - now edit group file
702 if (mode == M_ADD || getarg(args, 'G') != NULL) {
705 /* First remove the user from all group */
707 while ((grp = GETGRENT()) != NULL) {
708 char group[MAXLOGNAME];
709 if (grp->gr_mem == NULL)
711 for (i = 0; grp->gr_mem[i] != NULL; i++) {
712 if (strcmp(grp->gr_mem[i] , pwd->pw_name) != 0)
714 for (j = i; grp->gr_mem[j] != NULL ; j++)
715 grp->gr_mem[j] = grp->gr_mem[j+1];
716 strlcpy(group, grp->gr_name, MAXLOGNAME);
717 chggrent(group, grp);
722 /* now add to group where needed */
723 for (i = 0; i < cnf->groups->sl_cur; i++) {
724 grp = GETGRNAM(cnf->groups->sl_str[i]);
725 grp = gr_add(grp, pwd->pw_name);
727 * grp can only be NULL in 2 cases:
728 * - the new member is already a member
729 * - a problem with memory occurs
730 * in both cases we want to skip now.
734 chggrent(grp->gr_name, grp);
740 /* go get a current version of pwd */
741 pwd = GETPWNAM(name);
743 /* This will fail when we rename, so special case that */
744 if (mode == M_UPDATE && conf.newname != NULL) {
745 name = conf.newname; /* update new name */
746 pwd = GETPWNAM(name); /* refetch renamed rec */
749 if (pwd == NULL) /* can't go on without this */
750 errx(EX_NOUSER, "user '%s' disappeared during update", name);
752 grp = GETGRGID(pwd->pw_gid);
753 pw_log(cnf, mode, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
754 pwd->pw_name, (uintmax_t)pwd->pw_uid,
755 grp ? grp->gr_name : "unknown", (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
756 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
759 * If adding, let's touch and chown the user's mail file. This is not
760 * strictly necessary under BSD with a 0755 maildir but it also
761 * doesn't hurt anything to create the empty mailfile
764 if (PWALTDIR() != PWF_ALT) {
765 snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
767 close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT,
768 0600)); /* Preserve contents & mtime */
769 fchownat(conf.rootfd, path + 1, pwd->pw_uid,
770 pwd->pw_gid, AT_SYMLINK_NOFOLLOW);
775 * Let's create and populate the user's home directory. Note
776 * that this also `works' for editing users if -m is used, but
777 * existing files will *not* be overwritten.
779 if (PWALTDIR() != PWF_ALT && getarg(args, 'm') != NULL && pwd->pw_dir &&
780 *pwd->pw_dir == '/' && pwd->pw_dir[1])
781 create_and_populate_homedir(pwd);
784 * Finally, send mail to the new user as well, if we are asked to
786 if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
787 FILE *pfp = popen(_PATH_SENDMAIL " -t", "w");
792 fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
793 while (fgets(line, sizeof(line), fp) != NULL) {
794 /* Do substitutions? */
798 pw_log(cnf, mode, W_USER, "%s(%ju) new user mail sent",
799 pwd->pw_name, (uintmax_t)pwd->pw_uid);
809 pw_uidpolicy(struct userconf * cnf, long id)
812 uid_t uid = (uid_t) - 1;
815 * Check the given uid, if any
820 if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
821 errx(EX_DATAERR, "uid `%ju' has already been allocated",
822 (uintmax_t)pwd->pw_uid);
827 * We need to allocate the next available uid under one of
828 * two policies a) Grab the first unused uid b) Grab the
829 * highest possible unused uid
831 if (cnf->min_uid >= cnf->max_uid) { /* Sanity
832 * claus^H^H^H^Hheck */
834 cnf->max_uid = 32000;
836 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
839 * Now, let's fill the bitmap from the password file
842 while ((pwd = GETPWENT()) != NULL)
843 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
844 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
848 * Then apply the policy, with fallback to reuse if necessary
850 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
851 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
854 * Another sanity check
856 if (uid < cnf->min_uid || uid > cnf->max_uid)
857 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
865 pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer)
868 gid_t gid = (uid_t) - 1;
869 struct carg *a_gid = getarg(args, 'g');
870 struct userconf *cnf = conf.userconf;
873 * If no arg given, see if default can help out
875 if (a_gid == NULL && cnf->default_group && *cnf->default_group)
876 a_gid = addarg(args, 'g', cnf->default_group);
879 * Check the given gid, if any
883 if ((grp = GETGRNAM(a_gid->val)) == NULL) {
884 gid = (gid_t) atol(a_gid->val);
885 if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
886 errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
889 } else if ((grp = GETGRNAM(nam)) != NULL &&
890 (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
891 gid = grp->gr_gid; /* Already created? Use it anyway... */
896 * We need to auto-create a group with the user's name. We
897 * can send all the appropriate output to our sister routine
898 * bit first see if we can create a group with gid==uid so we
899 * can keep the user and group ids in sync. We purposely do
900 * NOT check the gid range if we can force the sync. If the
901 * user's name dups an existing group, then the group add
902 * function will happily handle that case for us and exit.
904 if (GETGRGID(prefer) == NULL)
907 gid = pw_groupnext(cnf, true);
909 pw_group(M_ADD, nam, grid, NULL);
910 if ((grp = GETGRNAM(nam)) != NULL)
920 pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
923 time_t now = time(NULL);
924 struct carg *arg = getarg(args, 'p');
927 if ((result = parse_date(now, arg->val)) == now)
928 errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
929 } else if (cnf->password_days > 0)
930 result = now + ((long) cnf->password_days * 86400L);
936 pw_exppolicy(struct userconf * cnf, struct cargs * args)
939 time_t now = time(NULL);
940 struct carg *arg = getarg(args, 'e');
943 if ((result = parse_date(now, arg->val)) == now)
944 errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
945 } else if (cnf->expire_days > 0)
946 result = now + ((long) cnf->expire_days * 86400L);
952 pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
954 struct carg *arg = getarg(args, 'd');
955 static char home[128];
960 if (cnf->home == NULL || *cnf->home == '\0')
961 errx(EX_CONFIG, "no base home directory set");
962 snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
968 shell_path(char const * path, char *shells[], char *sh)
970 if (sh != NULL && (*sh == '/' || *sh == '\0'))
971 return sh; /* specified full path or forced none */
974 char paths[_UC_MAXLINE];
977 * We need to search paths
979 strlcpy(paths, path, sizeof(paths));
980 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
982 static char shellpath[256];
985 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
986 if (access(shellpath, X_OK) == 0)
989 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
990 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
991 if (access(shellpath, X_OK) == 0)
996 errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
997 errx(EX_CONFIG, "no default shell available or defined");
1004 pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
1006 char *sh = newshell;
1007 struct carg *arg = getarg(args, 's');
1009 if (newshell == NULL && arg != NULL)
1011 return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
1016 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1019 pw_pwcrypt(char *password)
1022 char salt[SALTSIZE + 1];
1025 static char buf[256];
1028 * Calculate a salt value
1030 for (i = 0; i < SALTSIZE; i++)
1031 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1032 salt[SALTSIZE] = '\0';
1034 cryptpw = crypt(password, salt);
1035 if (cryptpw == NULL)
1036 errx(EX_CONFIG, "crypt(3) failure");
1037 return strcpy(buf, cryptpw);
1042 pw_password(struct userconf * cnf, char const * user)
1047 switch (cnf->default_password) {
1048 case -1: /* Random password */
1049 l = (arc4random() % 8 + 8); /* 8 - 16 chars */
1050 for (i = 0; i < l; i++)
1051 pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
1055 * We give this information back to the user
1057 if (conf.fd == -1 && !conf.dryrun) {
1058 if (isatty(STDOUT_FILENO))
1059 printf("Password for '%s' is: ", user);
1060 printf("%s\n", pwbuf);
1065 case -2: /* No password at all! */
1068 case 0: /* No login - default */
1072 case 1: /* user's name */
1073 strlcpy(pwbuf, user, sizeof(pwbuf));
1076 return pw_pwcrypt(pwbuf);
1080 pw_userdel(char *name, long id)
1082 struct passwd *pwd = NULL;
1083 char file[MAXPATHLEN];
1084 char home[MAXPATHLEN];
1086 struct group *gr, *grp;
1087 char grname[LOGNAMESIZE];
1090 int valid_type = _PWF_FILES;
1092 if (id < 0 && name == NULL)
1093 errx(EX_DATAERR, "username or id required");
1095 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1098 errx(EX_NOUSER, "no such uid `%ld'", id);
1099 errx(EX_NOUSER, "no such user `%s'", name);
1102 if (conf.userconf->nispasswd && *conf.userconf->nispasswd == '/')
1103 valid_type = _PWF_NIS;
1105 if (PWF._altdir == PWF_REGULAR &&
1106 ((pwd->pw_fields & _PWF_SOURCE) != valid_type))
1107 errx(EX_NOUSER, "no such %s user `%s'",
1108 valid_type == _PWF_FILES ? "local" : "NIS" , name);
1112 name = pwd->pw_name;
1114 if (strcmp(pwd->pw_name, "root") == 0)
1115 errx(EX_DATAERR, "cannot remove user 'root'");
1117 /* Remove opie record from /etc/opiekeys */
1119 if (PWALTDIR() != PWF_ALT)
1120 rmopie(pwd->pw_name);
1123 /* Remove crontabs */
1124 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
1125 if (access(file, F_OK) == 0) {
1126 snprintf(file, sizeof(file), "crontab -u %s -r", pwd->pw_name);
1131 * Save these for later, since contents of pwd may be
1132 * invalidated by deletion
1134 snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
1135 strlcpy(home, pwd->pw_dir, sizeof(home));
1136 gr = GETGRGID(pwd->pw_gid);
1138 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
1144 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
1146 err(EX_IOERR, "passwd update");
1148 if (conf.userconf->nispasswd && *conf.userconf->nispasswd=='/') {
1149 rc = delnispwent(conf.userconf->nispasswd, name);
1151 warnx("WARNING: user '%s' does not exist in NIS passwd",
1154 warn("WARNING: NIS passwd update");
1158 grp = GETGRNAM(name);
1160 (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
1161 strcmp(name, grname) == 0)
1162 delgrent(GETGRNAM(name));
1164 while ((grp = GETGRENT()) != NULL) {
1166 char group[MAXLOGNAME];
1167 if (grp->gr_mem == NULL)
1170 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1171 if (strcmp(grp->gr_mem[i], name) != 0)
1174 for (j = i; grp->gr_mem[j] != NULL; j++)
1175 grp->gr_mem[j] = grp->gr_mem[j+1];
1176 strlcpy(group, grp->gr_name, MAXLOGNAME);
1177 chggrent(group, grp);
1182 pw_log(conf.userconf, M_DELETE, W_USER, "%s(%ju) account removed", name,
1185 /* Remove mail file */
1186 if (PWALTDIR() != PWF_ALT)
1187 unlinkat(conf.rootfd, file + 1, 0);
1189 /* Remove at jobs */
1190 if (!PWALTDIR() && getpwuid(uid) == NULL)
1193 /* Remove home directory and contents */
1194 if (PWALTDIR() != PWF_ALT && conf.deletehome && *home == '/' &&
1195 getpwuid(uid) == NULL &&
1196 fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1197 rm_r(conf.rootfd, home, uid);
1198 pw_log(conf.userconf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
1199 "removed", name, (uintmax_t)uid, home,
1200 fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1204 return (EXIT_SUCCESS);
1208 print_user(struct passwd * pwd)
1213 buf = conf.v7 ? pw_make_v7(pwd) : pw_make(pwd);
1214 printf("%s\n", buf);
1219 struct group *grp = GETGRGID(pwd->pw_gid);
1220 char uname[60] = "User &", office[60] = "[None]",
1221 wphone[60] = "[None]", hphone[60] = "[None]";
1222 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
1225 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1226 strlcpy(uname, p, sizeof(uname));
1227 if ((p = strtok(NULL, ",")) != NULL) {
1228 strlcpy(office, p, sizeof(office));
1229 if ((p = strtok(NULL, ",")) != NULL) {
1230 strlcpy(wphone, p, sizeof(wphone));
1231 if ((p = strtok(NULL, "")) != NULL) {
1239 * Handle '&' in gecos field
1241 if ((p = strchr(uname, '&')) != NULL) {
1242 int l = strlen(pwd->pw_name);
1245 memmove(p + l, p + 1, m);
1246 memmove(p, pwd->pw_name, l);
1247 *p = (char) toupper((unsigned char)*p);
1249 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1250 strftime(acexpire, sizeof acexpire, "%c", tptr);
1251 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1252 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1253 printf("Login Name: %-15s #%-12ju Group: %-15s #%ju\n"
1255 " Home: %-26.26s Class: %s\n"
1256 " Shell: %-26.26s Office: %s\n"
1257 "Work Phone: %-26.26s Home Phone: %s\n"
1258 "Acc Expire: %-26.26s Pwd Expire: %s\n",
1259 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1260 grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
1261 uname, pwd->pw_dir, pwd->pw_class,
1262 pwd->pw_shell, office, wphone, hphone,
1263 acexpire, pwexpire);
1266 while ((grp=GETGRENT()) != NULL)
1269 if (grp->gr_mem != NULL) {
1270 while (grp->gr_mem[i] != NULL)
1272 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1274 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
1282 printf("%s", j ? "\n" : "");
1284 return EXIT_SUCCESS;
1288 pw_checkname(char *name, int gecos)
1291 const char *badchars, *ch, *showtype;
1297 /* See if the name is valid as a gecos (comment) field. */
1299 showtype = "gecos field";
1301 /* See if the name is valid as a userid or group. */
1302 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1303 showtype = "userid/group name";
1304 /* Userids and groups can not have a leading '-'. */
1310 if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1315 /* 8-bit characters are only allowed in GECOS fields */
1316 if (!gecos && (*ch & 0x80)) {
1324 * A `$' is allowed as the final character for userids and groups,
1325 * mainly for the benefit of samba.
1327 if (reject && !gecos) {
1328 if (*ch == '$' && *(ch + 1) == '\0') {
1334 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1335 ? "`%c'" : "0x%02x", *ch);
1336 errx(EX_DATAERR, "invalid character %s at position %td in %s",
1337 showch, (ch - name), showtype);
1339 if (!gecos && (ch - name) > LOGNAMESIZE)
1340 errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1350 DIR *d = opendir("/var/at/jobs");
1355 while ((e = readdir(d)) != NULL) {
1358 if (strncmp(e->d_name, ".lock", 5) != 0 &&
1359 stat(e->d_name, &st) == 0 &&
1360 !S_ISDIR(st.st_mode) &&
1362 char tmp[MAXPATHLEN];
1364 snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s", e->d_name);
1373 rmopie(char const * name)
1381 if ((fd = openat(conf.rootfd, "etc/opiekeys", O_RDWR)) == -1)
1384 fp = fdopen(fd, "r+");
1387 while (fgets(tmp, sizeof(tmp), fp) != NULL) {
1388 if (strncmp(name, tmp, len) == 0 && tmp[len]==' ') {
1389 /* Comment username out */
1390 if (fseek(fp, atofs, SEEK_SET) == 0)
1391 fwrite("#", 1, 1, fp);
1397 * If we got an error of any sort, don't update!