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
26 * $FreeBSD: src/usr.sbin/pw/pw_user.c,v 1.72 2012/02/22 06:27:20 kevlo Exp $
32 #include <sys/param.h>
36 #include <sys/types.h>
38 #include <sys/resource.h>
40 #include <login_cap.h>
44 #define LOGNAMESIZE (MAXLOGNAME-1)
46 static char locked_str[] = "*LOCKED*";
48 static int print_user(struct passwd * pwd, int pretty, int v7);
49 static uid_t pw_uidpolicy(struct userconf * cnf, struct cargs * args);
50 static uid_t pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer);
51 static time_t pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
52 static time_t pw_exppolicy(struct userconf * cnf, struct cargs * args);
53 static char *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
54 static char *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
55 static char *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
56 static char *shell_path(char const * path, char *shells[], char *sh);
57 static void rmat(uid_t uid);
60 * -C config configuration file
64 * -c comment user name/comment
65 * -d directory home directory
66 * -e date account expiry date
67 * -p date password expiry date
68 * -g grp primary group
69 * -G grp1,grp2 additional groups
70 * -m [ -k dir ] create and set up home
71 * -s shell name of login shell
74 * -l name new login name
75 * -h fd password filehandle
76 * -H fd encrypted password filehandle
77 * -F force print or add
79 * -D set user defaults
80 * -b dir default home root dir
81 * -e period default expiry period
82 * -p period default password change period
83 * -g group default group
84 * -G grp1,grp2.. default additional groups
85 * -L class default login class
86 * -k dir default home skeleton
87 * -s shell default shell
88 * -w method default password method
92 pw_user(struct userconf * cnf, int mode, struct cargs * args)
100 struct passwd *pwd = NULL;
103 char line[_PASSWORD_LEN+1];
108 static struct passwd fakeuser =
125 * With M_NEXT, we only need to return the
130 uid_t next = pw_uidpolicy(cnf, args);
131 if (getarg(args, 'q'))
133 printf("%ld:", (long)next);
134 pw_group(cnf, mode, args);
139 * We can do all of the common legwork here
142 if ((arg = getarg(args, 'b')) != NULL) {
143 cnf->home = arg->val;
146 if ((arg = getarg(args, 'M')) != NULL) {
148 if ((set = setmode(dmode_c)) == NULL)
149 errx(EX_DATAERR, "invalid directory creation mode '%s'",
151 cnf->homemode = getmode(set, _DEF_DIRMODE);
156 * If we'll need to use it or we're updating it,
157 * then create the base home directory if necessary
159 if (arg != NULL || getarg(args, 'm') != NULL) {
160 int l = strlen(cnf->home);
162 if (l > 1 && cnf->home[l-1] == '/') /* Shave off any trailing path delimiter */
163 cnf->home[--l] = '\0';
165 if (l < 2 || *cnf->home != '/') /* Check for absolute path name */
166 errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
168 if (stat(cnf->home, &st) == -1) {
169 char dbuf[MAXPATHLEN];
172 * This is a kludge especially for Joerg :)
173 * If the home directory would be created in the root partition, then
174 * we really create it under /usr which is likely to have more space.
175 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
177 if (strchr(cnf->home+1, '/') == NULL) {
178 strcpy(dbuf, "/usr");
179 strncat(dbuf, cnf->home, MAXPATHLEN-5);
180 if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
183 * Skip first "/" and create symlink:
186 symlink(dbuf+1, cnf->home);
188 /* If this falls, fall back to old method */
190 strlcpy(dbuf, cnf->home, sizeof(dbuf));
192 if (stat(dbuf, &st) == -1) {
193 while ((p = strchr(++p, '/')) != NULL) {
195 if (stat(dbuf, &st) == -1) {
196 if (mkdir(dbuf, _DEF_DIRMODE) == -1)
199 } else if (!S_ISDIR(st.st_mode))
200 errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
204 if (stat(dbuf, &st) == -1) {
205 if (mkdir(dbuf, _DEF_DIRMODE) == -1) {
206 direrr: err(EX_OSFILE, "mkdir '%s'", dbuf);
210 } else if (!S_ISDIR(st.st_mode))
211 errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
214 if ((arg = getarg(args, 'e')) != NULL)
215 cnf->expire_days = atoi(arg->val);
217 if ((arg = getarg(args, 'y')) != NULL)
218 cnf->nispasswd = arg->val;
220 if ((arg = getarg(args, 'p')) != NULL && arg->val)
221 cnf->password_days = atoi(arg->val);
223 if ((arg = getarg(args, 'g')) != NULL) {
224 if (!*(p = arg->val)) /* Handle empty group list specially */
225 cnf->default_group = "";
227 if ((grp = GETGRNAM(p)) == NULL) {
228 if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
229 errx(EX_NOUSER, "group `%s' does not exist", p);
231 cnf->default_group = newstr(grp->gr_name);
234 if ((arg = getarg(args, 'L')) != NULL)
235 cnf->default_class = pw_checkname((u_char *)arg->val, 0);
237 if ((arg = getarg(args, 'G')) != NULL && arg->val) {
240 for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
241 if ((grp = GETGRNAM(p)) == NULL) {
242 if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
243 errx(EX_NOUSER, "group `%s' does not exist", p);
245 if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
246 cnf->groups[i++] = newstr(grp->gr_name);
248 while (i < cnf->numgroups)
249 cnf->groups[i++] = NULL;
252 if ((arg = getarg(args, 'k')) != NULL) {
253 if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
254 errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
257 if ((arg = getarg(args, 's')) != NULL)
258 cnf->shell_default = arg->val;
260 if ((arg = getarg(args, 'w')) != NULL)
261 cnf->default_password = boolean_val(arg->val, cnf->default_password);
262 if (mode == M_ADD && getarg(args, 'D')) {
263 if (getarg(args, 'n') != NULL)
264 errx(EX_DATAERR, "can't combine `-D' with `-n name'");
265 if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
266 if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
268 if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
269 cnf->max_uid = 32000;
271 if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
272 if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
274 if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
275 cnf->max_gid = 32000;
278 arg = getarg(args, 'C');
279 if (write_userconfig(arg ? arg->val : NULL))
281 warn("config update");
285 if (mode == M_PRINT && getarg(args, 'a')) {
286 int pretty = getarg(args, 'P') != NULL;
287 int v7 = getarg(args, '7') != NULL;
290 while ((pwd = GETPWENT()) != NULL)
291 print_user(pwd, pretty, v7);
296 if ((a_name = getarg(args, 'n')) != NULL)
297 pwd = GETPWNAM(pw_checkname((u_char *)a_name->val, 0));
298 a_uid = getarg(args, 'u');
302 errx(EX_DATAERR, "user name or id required");
305 * Determine whether 'n' switch is name or uid - we don't
306 * really don't really care which we have, but we need to
309 if (mode != M_ADD && pwd == NULL
310 && strspn(a_name->val, "0123456789") == strlen(a_name->val)
311 && atoi(a_name->val) > 0) { /* Assume uid */
312 (a_uid = a_name)->ch = 'u';
318 * Update, delete & print require that the user exists
320 if (mode == M_UPDATE || mode == M_DELETE ||
321 mode == M_PRINT || mode == M_LOCK || mode == M_UNLOCK) {
323 if (a_name == NULL && pwd == NULL) /* Try harder */
324 pwd = GETPWUID(atoi(a_uid->val));
327 if (mode == M_PRINT && getarg(args, 'F')) {
328 fakeuser.pw_name = a_name ? a_name->val : "nouser";
329 fakeuser.pw_uid = a_uid ? (uid_t) atol(a_uid->val) : -1;
330 return print_user(&fakeuser,
331 getarg(args, 'P') != NULL,
332 getarg(args, '7') != NULL);
335 errx(EX_NOUSER, "no such uid `%s'", a_uid->val);
336 errx(EX_NOUSER, "no such user `%s'", a_name->val);
339 if (a_name == NULL) /* May be needed later */
340 a_name = addarg(args, 'n', newstr(pwd->pw_name));
343 * The M_LOCK and M_UNLOCK functions simply add or remove
344 * a "*LOCKED*" prefix from in front of the password to
345 * prevent it decoding correctly, and therefore prevents
346 * access. Of course, this only prevents access via
347 * password authentication (not ssh, kerberos or any
348 * other method that does not use the UNIX password) but
349 * that is a known limitation.
352 if (mode == M_LOCK) {
353 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
354 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
355 passtmp = malloc(strlen(pwd->pw_passwd) + sizeof(locked_str));
356 if (passtmp == NULL) /* disaster */
357 errx(EX_UNAVAILABLE, "out of memory");
358 strcpy(passtmp, locked_str);
359 strcat(passtmp, pwd->pw_passwd);
360 pwd->pw_passwd = passtmp;
362 } else if (mode == M_UNLOCK) {
363 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
364 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
365 pwd->pw_passwd += sizeof(locked_str)-1;
367 } else if (mode == M_DELETE) {
369 * Handle deletions now
371 char file[MAXPATHLEN];
372 char home[MAXPATHLEN];
373 uid_t uid = pwd->pw_uid;
375 if (strcmp(pwd->pw_name, "root") == 0)
376 errx(EX_DATAERR, "cannot remove user 'root'");
382 sprintf(file, "/var/cron/tabs/%s", pwd->pw_name);
383 if (access(file, F_OK) == 0) {
384 sprintf(file, "crontab -u %s -r", pwd->pw_name);
389 * Save these for later, since contents of pwd may be
390 * invalidated by deletion
392 sprintf(file, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
393 strlcpy(home, pwd->pw_dir, sizeof(home));
397 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
399 warn("passwd update");
403 if (cnf->nispasswd && *cnf->nispasswd=='/') {
404 rc = delnispwent(cnf->nispasswd, a_name->val);
406 warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
408 warn("WARNING: NIS passwd update");
412 editgroups(a_name->val, NULL);
414 pw_log(cnf, mode, W_USER, "%s(%ld) account removed", a_name->val, (long) uid);
425 if (getpwuid(uid) == NULL)
429 * Remove home directory and contents
431 if (getarg(args, 'r') != NULL && *home == '/' && getpwuid(uid) == NULL) {
432 if (stat(home, &st) != -1) {
434 pw_log(cnf, mode, W_USER, "%s(%ld) home '%s' %sremoved",
435 a_name->val, (long) uid, home,
436 stat(home, &st) == -1 ? "" : "not completely ");
441 } else if (mode == M_PRINT)
442 return print_user(pwd,
443 getarg(args, 'P') != NULL,
444 getarg(args, '7') != NULL);
447 * The rest is edit code
449 if ((arg = getarg(args, 'l')) != NULL) {
450 if (strcmp(pwd->pw_name, "root") == 0)
451 errx(EX_DATAERR, "can't rename `root' account");
452 pwd->pw_name = pw_checkname((u_char *)arg->val, 0);
456 if ((arg = getarg(args, 'u')) != NULL && isdigit((unsigned char)*arg->val)) {
457 pwd->pw_uid = (uid_t) atol(arg->val);
459 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
460 errx(EX_DATAERR, "can't change uid of `root' account");
461 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
462 warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
465 if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) { /* Already checked this */
466 gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
467 if (newgid != pwd->pw_gid) {
469 pwd->pw_gid = newgid;
473 if ((arg = getarg(args, 'p')) != NULL) {
474 if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
475 if (pwd->pw_change != 0) {
481 time_t now = time(NULL);
482 time_t expire = parse_date(now, arg->val);
485 errx(EX_DATAERR, "invalid password change date `%s'", arg->val);
486 if (pwd->pw_change != expire) {
487 pwd->pw_change = expire;
493 if ((arg = getarg(args, 'e')) != NULL) {
494 if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
495 if (pwd->pw_expire != 0) {
501 time_t now = time(NULL);
502 time_t expire = parse_date(now, arg->val);
505 errx(EX_DATAERR, "invalid account expiry date `%s'", arg->val);
506 if (pwd->pw_expire != expire) {
507 pwd->pw_expire = expire;
513 if ((arg = getarg(args, 's')) != NULL) {
514 char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
517 if (strcmp(shell, pwd->pw_shell) != 0) {
518 pwd->pw_shell = shell;
523 if (getarg(args, 'L')) {
524 if (cnf->default_class == NULL)
525 cnf->default_class = "";
526 if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
527 pwd->pw_class = cnf->default_class;
532 if ((arg = getarg(args, 'd')) != NULL) {
533 if (strcmp(pwd->pw_dir, arg->val))
535 if (stat(pwd->pw_dir = arg->val, &st) == -1) {
536 if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
537 warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
538 } else if (!S_ISDIR(st.st_mode))
539 warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
542 if ((arg = getarg(args, 'w')) != NULL &&
543 getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
546 lc = login_getpwclass(pwd);
548 login_setcryptfmt(lc, "md5", NULL) == NULL)
549 warn("setting crypt(3) format");
551 pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
562 if (a_name == NULL) /* Required */
563 errx(EX_DATAERR, "login name required");
564 else if ((pwd = GETPWNAM(a_name->val)) != NULL) /* Exists */
565 errx(EX_DATAERR, "login name `%s' already exists", a_name->val);
568 * Now, set up defaults for a new user
571 pwd->pw_name = a_name->val;
572 pwd->pw_class = cnf->default_class ? cnf->default_class : "";
573 pwd->pw_uid = pw_uidpolicy(cnf, args);
574 pwd->pw_gid = pw_gidpolicy(cnf, args, pwd->pw_name, (gid_t) pwd->pw_uid);
575 pwd->pw_change = pw_pwdpolicy(cnf, args);
576 pwd->pw_expire = pw_exppolicy(cnf, args);
577 pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
578 pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
579 lc = login_getpwclass(pwd);
580 if (lc == NULL || login_setcryptfmt(lc, "md5", NULL) == NULL)
581 warn("setting crypt(3) format");
583 pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
586 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
587 warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
591 * Shared add/edit code
593 if ((arg = getarg(args, 'c')) != NULL) {
594 char *gecos = pw_checkname((u_char *)arg->val, 1);
595 if (strcmp(pwd->pw_gecos, gecos) != 0) {
596 pwd->pw_gecos = gecos;
601 if ((arg = getarg(args, 'h')) != NULL ||
602 (arg = getarg(args, 'H')) != NULL) {
603 if (strcmp(arg->val, "-") == 0) {
604 if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
605 pwd->pw_passwd = "*"; /* No access */
609 int fd = atoi(arg->val);
610 int precrypt = (arg->ch == 'H');
612 int istty = isatty(fd);
617 if (tcgetattr(fd, &t) == -1)
620 struct termios n = t;
623 n.c_lflag &= ~(ECHO);
624 tcsetattr(fd, TCSANOW, &n);
625 printf("%s%spassword for user %s:",
626 (mode == M_UPDATE) ? "new " : "",
627 precrypt ? "encrypted " : "",
632 b = read(fd, line, sizeof(line) - 1);
633 if (istty) { /* Restore state */
634 tcsetattr(fd, TCSANOW, &t);
639 warn("-%c file descriptor", precrypt ? 'H' :
644 if ((p = strpbrk(line, "\r\n")) != NULL)
647 errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
649 if (strchr(line, ':') != NULL)
651 pwd->pw_passwd = line;
653 lc = login_getpwclass(pwd);
655 login_setcryptfmt(lc, "md5", NULL) == NULL)
656 warn("setting crypt(3) format");
658 pwd->pw_passwd = pw_pwcrypt(line);
665 * Special case: -N only displays & exits
667 if (getarg(args, 'N') != NULL)
668 return print_user(pwd,
669 getarg(args, 'P') != NULL,
670 getarg(args, '7') != NULL);
673 edited = 1; /* Always */
676 warnx("user '%s' already exists", pwd->pw_name);
678 } else if (rc != 0) {
679 warn("passwd file update");
682 if (cnf->nispasswd && *cnf->nispasswd=='/') {
683 rc = addnispwent(cnf->nispasswd, pwd);
685 warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
687 warn("NIS passwd update");
688 /* NOTE: we treat NIS-only update errors as non-fatal */
690 } else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
691 if (edited) { /* Only updated this if required */
692 rc = chgpwent(a_name->val, pwd);
694 warnx("user '%s' does not exist (NIS?)", pwd->pw_name);
696 } else if (rc != 0) {
697 warn("passwd file update");
700 if ( cnf->nispasswd && *cnf->nispasswd=='/') {
701 rc = chgnispwent(cnf->nispasswd, a_name->val, pwd);
703 warn("User '%s' not found in NIS passwd", pwd->pw_name);
705 warn("NIS passwd update");
706 /* NOTE: NIS-only update errors are not fatal */
712 * Ok, user is created or changed - now edit group file
715 if (mode == M_ADD || getarg(args, 'G') != NULL)
716 editgroups(pwd->pw_name, cnf->groups);
718 /* go get a current version of pwd */
719 pwd = GETPWNAM(a_name->val);
721 /* This will fail when we rename, so special case that */
722 if (mode == M_UPDATE && (arg = getarg(args, 'l')) != NULL) {
723 a_name->val = arg->val; /* update new name */
724 pwd = GETPWNAM(a_name->val); /* refetch renamed rec */
727 if (pwd == NULL) /* can't go on without this */
728 errx(EX_NOUSER, "user '%s' disappeared during update", a_name->val);
730 grp = GETGRGID(pwd->pw_gid);
731 pw_log(cnf, mode, W_USER, "%s(%ld):%s(%ld):%s:%s:%s",
732 pwd->pw_name, (long) pwd->pw_uid,
733 grp ? grp->gr_name : "unknown", (long) (grp ? grp->gr_gid : -1),
734 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
737 * If adding, let's touch and chown the user's mail file. This is not
738 * strictly necessary under BSD with a 0755 maildir but it also
739 * doesn't hurt anything to create the empty mailfile
743 sprintf(line, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
744 close(open(line, O_RDWR | O_CREAT, 0600)); /* Preserve contents &
746 chown(line, pwd->pw_uid, pwd->pw_gid);
751 * Let's create and populate the user's home directory. Note
752 * that this also `works' for editing users if -m is used, but
753 * existing files will *not* be overwritten.
755 if (!PWALTDIR() && getarg(args, 'm') != NULL && pwd->pw_dir && *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
756 copymkdir(pwd->pw_dir, cnf->dotdir, cnf->homemode, pwd->pw_uid, pwd->pw_gid);
757 pw_log(cnf, mode, W_USER, "%s(%ld) home %s made",
758 pwd->pw_name, (long) pwd->pw_uid, pwd->pw_dir);
763 * Finally, send mail to the new user as well, if we are asked to
765 if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
766 FILE *pfp = popen(_PATH_SENDMAIL " -t", "w");
771 fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
772 while (fgets(line, sizeof(line), fp) != NULL) {
773 /* Do substitutions? */
777 pw_log(cnf, mode, W_USER, "%s(%ld) new user mail sent",
778 pwd->pw_name, (long) pwd->pw_uid);
788 pw_uidpolicy(struct userconf * cnf, struct cargs * args)
791 uid_t uid = (uid_t) - 1;
792 struct carg *a_uid = getarg(args, 'u');
795 * Check the given uid, if any
798 uid = (uid_t) atol(a_uid->val);
800 if ((pwd = GETPWUID(uid)) != NULL && getarg(args, 'o') == NULL)
801 errx(EX_DATAERR, "uid `%ld' has already been allocated", (long) pwd->pw_uid);
806 * We need to allocate the next available uid under one of
807 * two policies a) Grab the first unused uid b) Grab the
808 * highest possible unused uid
810 if (cnf->min_uid >= cnf->max_uid) { /* Sanity
811 * claus^H^H^H^Hheck */
813 cnf->max_uid = 32000;
815 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
818 * Now, let's fill the bitmap from the password file
821 while ((pwd = GETPWENT()) != NULL)
822 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
823 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
827 * Then apply the policy, with fallback to reuse if necessary
829 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
830 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
833 * Another sanity check
835 if (uid < cnf->min_uid || uid > cnf->max_uid)
836 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
844 pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer)
847 gid_t gid = (uid_t) - 1;
848 struct carg *a_gid = getarg(args, 'g');
851 * If no arg given, see if default can help out
853 if (a_gid == NULL && cnf->default_group && *cnf->default_group)
854 a_gid = addarg(args, 'g', cnf->default_group);
857 * Check the given gid, if any
861 if ((grp = GETGRNAM(a_gid->val)) == NULL) {
862 gid = (gid_t) atol(a_gid->val);
863 if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
864 errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
867 } else if ((grp = GETGRNAM(nam)) != NULL && grp->gr_mem[0] == NULL) {
868 gid = grp->gr_gid; /* Already created? Use it anyway... */
870 struct cargs grpargs;
874 addarg(&grpargs, 'n', nam);
877 * We need to auto-create a group with the user's name. We
878 * can send all the appropriate output to our sister routine
879 * bit first see if we can create a group with gid==uid so we
880 * can keep the user and group ids in sync. We purposely do
881 * NOT check the gid range if we can force the sync. If the
882 * user's name dups an existing group, then the group add
883 * function will happily handle that case for us and exit.
885 if (GETGRGID(prefer) == NULL) {
886 sprintf(tmp, "%lu", (unsigned long) prefer);
887 addarg(&grpargs, 'g', tmp);
889 if (getarg(args, 'N'))
891 addarg(&grpargs, 'N', NULL);
892 addarg(&grpargs, 'q', NULL);
893 gid = pw_group(cnf, M_NEXT, &grpargs);
897 pw_group(cnf, M_ADD, &grpargs);
898 if ((grp = GETGRNAM(nam)) != NULL)
901 a_gid = LIST_FIRST(&grpargs);
902 while (a_gid != NULL) {
903 struct carg *t = LIST_NEXT(a_gid, list);
904 LIST_REMOVE(a_gid, list);
914 pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
917 time_t now = time(NULL);
918 struct carg *arg = getarg(args, 'p');
921 if ((result = parse_date(now, arg->val)) == now)
922 errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
923 } else if (cnf->password_days > 0)
924 result = now + ((long) cnf->password_days * 86400L);
930 pw_exppolicy(struct userconf * cnf, struct cargs * args)
933 time_t now = time(NULL);
934 struct carg *arg = getarg(args, 'e');
937 if ((result = parse_date(now, arg->val)) == now)
938 errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
939 } else if (cnf->expire_days > 0)
940 result = now + ((long) cnf->expire_days * 86400L);
946 pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
948 struct carg *arg = getarg(args, 'd');
953 static char home[128];
955 if (cnf->home == NULL || *cnf->home == '\0')
956 errx(EX_CONFIG, "no base home directory set");
957 sprintf(home, "%s/%s", cnf->home, user);
963 shell_path(char const * path, char *shells[], char *sh)
965 if (sh != NULL && (*sh == '/' || *sh == '\0'))
966 return sh; /* specified full path or forced none */
969 char paths[_UC_MAXLINE];
972 * We need to search paths
974 strlcpy(paths, path, sizeof(paths));
975 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
977 static char shellpath[256];
980 sprintf(shellpath, "%s/%s", p, sh);
981 if (access(shellpath, X_OK) == 0)
984 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
985 sprintf(shellpath, "%s/%s", p, shells[i]);
986 if (access(shellpath, X_OK) == 0)
991 errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
992 errx(EX_CONFIG, "no default shell available or defined");
999 pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
1001 char *sh = newshell;
1002 struct carg *arg = getarg(args, 's');
1004 if (newshell == NULL && arg != NULL)
1006 return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
1011 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1014 pw_pwcrypt(char *password)
1017 char salt[SALTSIZE + 1];
1020 static char buf[256];
1023 * Calculate a salt value
1025 for (i = 0; i < SALTSIZE; i++)
1026 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1027 salt[SALTSIZE] = '\0';
1029 cryptpw = crypt(password, salt);
1030 if (cryptpw == NULL)
1031 errx(EX_CONFIG, "crypt(3) failure");
1032 return strcpy(buf, cryptpw);
1037 pw_password(struct userconf * cnf, struct cargs * args, char const * user)
1042 switch (cnf->default_password) {
1043 case -1: /* Random password */
1044 l = (arc4random() % 8 + 8); /* 8 - 16 chars */
1045 for (i = 0; i < l; i++)
1046 pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
1050 * We give this information back to the user
1052 if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
1053 getarg(args, 'N') == NULL) {
1054 if (isatty(STDOUT_FILENO))
1055 printf("Password for '%s' is: ", user);
1056 printf("%s\n", pwbuf);
1061 case -2: /* No password at all! */
1064 case 0: /* No login - default */
1068 case 1: /* user's name */
1069 strlcpy(pwbuf, user, sizeof(pwbuf));
1072 return pw_pwcrypt(pwbuf);
1077 print_user(struct passwd * pwd, int pretty, int v7)
1080 char buf[_UC_MAXLINE];
1082 fmtpwentry(buf, pwd, v7 ? PWF_PASSWD : PWF_STANDARD);
1087 struct group *grp = GETGRGID(pwd->pw_gid);
1088 char uname[60] = "User &", office[60] = "[None]",
1089 wphone[60] = "[None]", hphone[60] = "[None]";
1090 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
1093 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1094 strlcpy(uname, p, sizeof(uname));
1095 if ((p = strtok(NULL, ",")) != NULL) {
1096 strlcpy(office, p, sizeof(office));
1097 if ((p = strtok(NULL, ",")) != NULL) {
1098 strlcpy(wphone, p, sizeof(wphone));
1099 if ((p = strtok(NULL, "")) != NULL) {
1107 * Handle '&' in gecos field
1109 if ((p = strchr(uname, '&')) != NULL) {
1110 int l = strlen(pwd->pw_name);
1113 memmove(p + l, p + 1, m);
1114 memmove(p, pwd->pw_name, l);
1115 *p = (char) toupper((unsigned char)*p);
1117 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1118 strftime(acexpire, sizeof acexpire, "%c", tptr);
1119 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1120 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1121 printf("Login Name: %-15s #%-12ld Group: %-15s #%ld\n"
1123 " Home: %-26.26s Class: %s\n"
1124 " Shell: %-26.26s Office: %s\n"
1125 "Work Phone: %-26.26s Home Phone: %s\n"
1126 "Acc Expire: %-26.26s Pwd Expire: %s\n",
1127 pwd->pw_name, (long) pwd->pw_uid,
1128 grp ? grp->gr_name : "(invalid)", (long) pwd->pw_gid,
1129 uname, pwd->pw_dir, pwd->pw_class,
1130 pwd->pw_shell, office, wphone, hphone,
1131 acexpire, pwexpire);
1134 while ((grp=GETGRENT()) != NULL)
1137 while (grp->gr_mem[i] != NULL)
1139 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1141 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
1148 printf("%s", j ? "\n" : "");
1150 return EXIT_SUCCESS;
1154 pw_checkname(u_char *name, int gecos)
1157 u_char const *badchars, *ch, *showtype;
1163 /* See if the name is valid as a gecos (comment) field. */
1165 showtype = "gecos field";
1167 /* See if the name is valid as a userid or group. */
1168 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1169 showtype = "userid/group name";
1170 /* Userids and groups can not have a leading '-'. */
1176 if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1181 /* 8-bit characters are only allowed in GECOS fields */
1182 if (!gecos && (*ch & 0x80)) {
1190 * A `$' is allowed as the final character for userids and groups,
1191 * mainly for the benefit of samba.
1193 if (reject && !gecos) {
1194 if (*ch == '$' && *(ch + 1) == '\0') {
1200 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1201 ? "`%c'" : "0x%02x", *ch);
1202 errx(EX_DATAERR, "invalid character %s at position %td in %s",
1203 showch, (ch - name), showtype);
1205 if (!gecos && (ch - name) > LOGNAMESIZE)
1206 errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1208 return (char *)name;
1215 DIR *d = opendir("/var/at/jobs");
1220 while ((e = readdir(d)) != NULL) {
1223 if (strncmp(e->d_name, ".lock", 5) != 0 &&
1224 stat(e->d_name, &st) == 0 &&
1225 !S_ISDIR(st.st_mode) &&
1227 char tmp[MAXPATHLEN];
1229 sprintf(tmp, "/usr/bin/atrm %s", e->d_name);