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[] =
36 #include <sys/param.h>
40 #include <sys/types.h>
42 #include <sys/resource.h>
44 #include <login_cap.h>
51 #define LOGNAMESIZE (MAXLOGNAME-1)
53 static char locked_str[] = "*LOCKED*";
55 static int print_user(struct passwd * pwd, int pretty, int v7);
56 static uid_t pw_uidpolicy(struct userconf * cnf, struct cargs * args);
57 static uid_t pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer);
58 static time_t pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
59 static time_t pw_exppolicy(struct userconf * cnf, struct cargs * args);
60 static char *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
61 static char *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
62 static char *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
63 static char *shell_path(char const * path, char *shells[], char *sh);
64 static void rmat(uid_t uid);
65 static void rmopie(char const * name);
68 * -C config configuration file
72 * -c comment user name/comment
73 * -d directory home directory
74 * -e date account expiry date
75 * -p date password expiry date
76 * -g grp primary group
77 * -G grp1,grp2 additional groups
78 * -m [ -k dir ] create and set up home
79 * -s shell name of login shell
82 * -l name new login name
83 * -h fd password filehandle
84 * -H fd encrypted password filehandle
85 * -F force print or add
87 * -D set user defaults
88 * -b dir default home root dir
89 * -e period default expiry period
90 * -p period default password change period
91 * -g group default group
92 * -G grp1,grp2.. default additional groups
93 * -L class default login class
94 * -k dir default home skeleton
95 * -s shell default shell
96 * -w method default password method
100 pw_user(struct userconf * cnf, int mode, struct cargs * args)
108 struct passwd *pwd = NULL;
111 char line[_PASSWORD_LEN+1];
116 static struct passwd fakeuser =
128 #if defined(__FreeBSD__)
135 * With M_NEXT, we only need to return the
140 uid_t next = pw_uidpolicy(cnf, args);
141 if (getarg(args, 'q'))
143 printf("%ld:", (long)next);
144 pw_group(cnf, mode, args);
149 * We can do all of the common legwork here
152 if ((arg = getarg(args, 'b')) != NULL) {
153 cnf->home = arg->val;
156 if ((arg = getarg(args, 'M')) != NULL) {
158 if ((set = setmode(dmode_c)) == NULL)
159 errx(EX_DATAERR, "invalid directory creation mode '%s'",
161 cnf->homemode = getmode(set, _DEF_DIRMODE);
166 * If we'll need to use it or we're updating it,
167 * then create the base home directory if necessary
169 if (arg != NULL || getarg(args, 'm') != NULL) {
170 int l = strlen(cnf->home);
172 if (l > 1 && cnf->home[l-1] == '/') /* Shave off any trailing path delimiter */
173 cnf->home[--l] = '\0';
175 if (l < 2 || *cnf->home != '/') /* Check for absolute path name */
176 errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
178 if (stat(cnf->home, &st) == -1) {
179 char dbuf[MAXPATHLEN];
182 * This is a kludge especially for Joerg :)
183 * If the home directory would be created in the root partition, then
184 * we really create it under /usr which is likely to have more space.
185 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
187 if (strchr(cnf->home+1, '/') == NULL) {
188 strcpy(dbuf, "/usr");
189 strncat(dbuf, cnf->home, MAXPATHLEN-5);
190 if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
193 * Skip first "/" and create symlink:
196 symlink(dbuf+1, cnf->home);
198 /* If this falls, fall back to old method */
200 strlcpy(dbuf, cnf->home, sizeof(dbuf));
202 if (stat(dbuf, &st) == -1) {
203 while ((p = strchr(p + 1, '/')) != NULL) {
205 if (stat(dbuf, &st) == -1) {
206 if (mkdir(dbuf, _DEF_DIRMODE) == -1)
209 } else if (!S_ISDIR(st.st_mode))
210 errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
214 if (stat(dbuf, &st) == -1) {
215 if (mkdir(dbuf, _DEF_DIRMODE) == -1) {
216 direrr: err(EX_OSFILE, "mkdir '%s'", dbuf);
220 } else if (!S_ISDIR(st.st_mode))
221 errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
224 if ((arg = getarg(args, 'e')) != NULL)
225 cnf->expire_days = atoi(arg->val);
227 if ((arg = getarg(args, 'y')) != NULL)
228 cnf->nispasswd = arg->val;
230 if ((arg = getarg(args, 'p')) != NULL && arg->val)
231 cnf->password_days = atoi(arg->val);
233 if ((arg = getarg(args, 'g')) != NULL) {
234 if (!*(p = arg->val)) /* Handle empty group list specially */
235 cnf->default_group = "";
237 if ((grp = GETGRNAM(p)) == NULL) {
238 if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
239 errx(EX_NOUSER, "group `%s' does not exist", p);
241 cnf->default_group = newstr(grp->gr_name);
244 if ((arg = getarg(args, 'L')) != NULL)
245 cnf->default_class = pw_checkname((u_char *)arg->val, 0);
247 if ((arg = getarg(args, 'G')) != NULL && arg->val) {
250 for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
251 if ((grp = GETGRNAM(p)) == NULL) {
252 if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
253 errx(EX_NOUSER, "group `%s' does not exist", p);
255 if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
256 cnf->groups[i++] = newstr(grp->gr_name);
258 while (i < cnf->numgroups)
259 cnf->groups[i++] = NULL;
262 if ((arg = getarg(args, 'k')) != NULL) {
263 if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
264 errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
267 if ((arg = getarg(args, 's')) != NULL)
268 cnf->shell_default = arg->val;
270 if ((arg = getarg(args, 'w')) != NULL)
271 cnf->default_password = boolean_val(arg->val, cnf->default_password);
272 if (mode == M_ADD && getarg(args, 'D')) {
273 if (getarg(args, 'n') != NULL)
274 errx(EX_DATAERR, "can't combine `-D' with `-n name'");
275 if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
276 if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
278 if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
279 cnf->max_uid = 32000;
281 if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
282 if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
284 if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
285 cnf->max_gid = 32000;
288 arg = getarg(args, 'C');
289 if (write_userconfig(arg ? arg->val : NULL))
291 warn("config update");
295 if (mode == M_PRINT && getarg(args, 'a')) {
296 int pretty = getarg(args, 'P') != NULL;
297 int v7 = getarg(args, '7') != NULL;
299 while ((pwd = GETPWENT()) != NULL)
300 print_user(pwd, pretty, v7);
305 if ((a_name = getarg(args, 'n')) != NULL)
306 pwd = GETPWNAM(pw_checkname((u_char *)a_name->val, 0));
307 a_uid = getarg(args, 'u');
311 errx(EX_DATAERR, "user name or id required");
314 * Determine whether 'n' switch is name or uid - we don't
315 * really don't really care which we have, but we need to
318 if (mode != M_ADD && pwd == NULL
319 && strspn(a_name->val, "0123456789") == strlen(a_name->val)
321 (a_uid = a_name)->ch = 'u';
327 * Update, delete & print require that the user exists
329 if (mode == M_UPDATE || mode == M_DELETE ||
330 mode == M_PRINT || mode == M_LOCK || mode == M_UNLOCK) {
332 if (a_name == NULL && pwd == NULL) /* Try harder */
333 pwd = GETPWUID(atoi(a_uid->val));
336 if (mode == M_PRINT && getarg(args, 'F')) {
337 fakeuser.pw_name = a_name ? a_name->val : "nouser";
338 fakeuser.pw_uid = a_uid ? (uid_t) atol(a_uid->val) : -1;
339 return print_user(&fakeuser,
340 getarg(args, 'P') != NULL,
341 getarg(args, '7') != NULL);
344 errx(EX_NOUSER, "no such uid `%s'", a_uid->val);
345 errx(EX_NOUSER, "no such user `%s'", a_name->val);
348 if (a_name == NULL) /* May be needed later */
349 a_name = addarg(args, 'n', newstr(pwd->pw_name));
352 * The M_LOCK and M_UNLOCK functions simply add or remove
353 * a "*LOCKED*" prefix from in front of the password to
354 * prevent it decoding correctly, and therefore prevents
355 * access. Of course, this only prevents access via
356 * password authentication (not ssh, kerberos or any
357 * other method that does not use the UNIX password) but
358 * that is a known limitation.
361 if (mode == M_LOCK) {
362 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
363 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
364 passtmp = malloc(strlen(pwd->pw_passwd) + sizeof(locked_str));
365 if (passtmp == NULL) /* disaster */
366 errx(EX_UNAVAILABLE, "out of memory");
367 strcpy(passtmp, locked_str);
368 strcat(passtmp, pwd->pw_passwd);
369 pwd->pw_passwd = passtmp;
371 } else if (mode == M_UNLOCK) {
372 if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
373 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
374 pwd->pw_passwd += sizeof(locked_str)-1;
376 } else if (mode == M_DELETE) {
378 * Handle deletions now
380 char file[MAXPATHLEN];
381 char home[MAXPATHLEN];
382 uid_t uid = pwd->pw_uid;
384 char grname[LOGNAMESIZE];
386 if (strcmp(pwd->pw_name, "root") == 0)
387 errx(EX_DATAERR, "cannot remove user 'root'");
391 * Remove opie record from /etc/opiekeys
394 rmopie(pwd->pw_name);
399 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
400 if (access(file, F_OK) == 0) {
401 sprintf(file, "crontab -u %s -r", pwd->pw_name);
406 * Save these for later, since contents of pwd may be
407 * invalidated by deletion
409 sprintf(file, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
410 strlcpy(home, pwd->pw_dir, sizeof(home));
411 gr = GETGRGID(pwd->pw_gid);
413 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
419 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
421 warn("passwd update");
425 if (cnf->nispasswd && *cnf->nispasswd=='/') {
426 rc = delnispwent(cnf->nispasswd, a_name->val);
428 warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
430 warn("WARNING: NIS passwd update");
434 grp = GETGRNAM(a_name->val);
436 (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
437 strcmp(a_name->val, grname) == 0)
438 delgrent(GETGRNAM(a_name->val));
440 while ((grp = GETGRENT()) != NULL) {
442 char group[MAXLOGNAME];
443 if (grp->gr_mem != NULL) {
444 for (i = 0; grp->gr_mem[i] != NULL; i++) {
445 if (!strcmp(grp->gr_mem[i], a_name->val)) {
446 while (grp->gr_mem[i] != NULL) {
447 grp->gr_mem[i] = grp->gr_mem[i+1];
449 strlcpy(group, grp->gr_name, MAXLOGNAME);
450 chggrent(group, grp);
457 pw_log(cnf, mode, W_USER, "%s(%ld) account removed", a_name->val, (long) uid);
468 if (getpwuid(uid) == NULL)
472 * Remove home directory and contents
474 if (getarg(args, 'r') != NULL && *home == '/' && getpwuid(uid) == NULL) {
475 if (stat(home, &st) != -1) {
477 pw_log(cnf, mode, W_USER, "%s(%ld) home '%s' %sremoved",
478 a_name->val, (long) uid, home,
479 stat(home, &st) == -1 ? "" : "not completely ");
484 } else if (mode == M_PRINT)
485 return print_user(pwd,
486 getarg(args, 'P') != NULL,
487 getarg(args, '7') != NULL);
490 * The rest is edit code
492 if ((arg = getarg(args, 'l')) != NULL) {
493 if (strcmp(pwd->pw_name, "root") == 0)
494 errx(EX_DATAERR, "can't rename `root' account");
495 pwd->pw_name = pw_checkname((u_char *)arg->val, 0);
499 if ((arg = getarg(args, 'u')) != NULL && isdigit((unsigned char)*arg->val)) {
500 pwd->pw_uid = (uid_t) atol(arg->val);
502 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
503 errx(EX_DATAERR, "can't change uid of `root' account");
504 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
505 warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
508 if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) { /* Already checked this */
509 gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
510 if (newgid != pwd->pw_gid) {
512 pwd->pw_gid = newgid;
516 if ((arg = getarg(args, 'p')) != NULL) {
517 if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
518 if (pwd->pw_change != 0) {
524 time_t now = time(NULL);
525 time_t expire = parse_date(now, arg->val);
527 if (pwd->pw_change != expire) {
528 pwd->pw_change = expire;
534 if ((arg = getarg(args, 'e')) != NULL) {
535 if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
536 if (pwd->pw_expire != 0) {
542 time_t now = time(NULL);
543 time_t expire = parse_date(now, arg->val);
545 if (pwd->pw_expire != expire) {
546 pwd->pw_expire = expire;
552 if ((arg = getarg(args, 's')) != NULL) {
553 char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
556 if (strcmp(shell, pwd->pw_shell) != 0) {
557 pwd->pw_shell = shell;
562 if (getarg(args, 'L')) {
563 if (cnf->default_class == NULL)
564 cnf->default_class = "";
565 if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
566 pwd->pw_class = cnf->default_class;
571 if ((arg = getarg(args, 'd')) != NULL) {
572 if (strcmp(pwd->pw_dir, arg->val))
574 if (stat(pwd->pw_dir = arg->val, &st) == -1) {
575 if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
576 warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
577 } else if (!S_ISDIR(st.st_mode))
578 warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
581 if ((arg = getarg(args, 'w')) != NULL &&
582 getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
585 lc = login_getpwclass(pwd);
587 login_setcryptfmt(lc, "sha512", NULL) == NULL)
588 warn("setting crypt(3) format");
590 pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
601 if (a_name == NULL) /* Required */
602 errx(EX_DATAERR, "login name required");
603 else if ((pwd = GETPWNAM(a_name->val)) != NULL) /* Exists */
604 errx(EX_DATAERR, "login name `%s' already exists", a_name->val);
607 * Now, set up defaults for a new user
610 pwd->pw_name = a_name->val;
611 pwd->pw_class = cnf->default_class ? cnf->default_class : "";
612 pwd->pw_uid = pw_uidpolicy(cnf, args);
613 pwd->pw_gid = pw_gidpolicy(cnf, args, pwd->pw_name, (gid_t) pwd->pw_uid);
614 pwd->pw_change = pw_pwdpolicy(cnf, args);
615 pwd->pw_expire = pw_exppolicy(cnf, args);
616 pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
617 pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
618 lc = login_getpwclass(pwd);
619 if (lc == NULL || login_setcryptfmt(lc, "md5", NULL) == NULL)
620 warn("setting crypt(3) format");
622 pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
625 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
626 warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
630 * Shared add/edit code
632 if ((arg = getarg(args, 'c')) != NULL) {
633 char *gecos = pw_checkname((u_char *)arg->val, 1);
634 if (strcmp(pwd->pw_gecos, gecos) != 0) {
635 pwd->pw_gecos = gecos;
640 if ((arg = getarg(args, 'h')) != NULL ||
641 (arg = getarg(args, 'H')) != NULL) {
642 if (strcmp(arg->val, "-") == 0) {
643 if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
644 pwd->pw_passwd = "*"; /* No access */
648 int fd = atoi(arg->val);
649 int precrypt = (arg->ch == 'H');
651 int istty = isatty(fd);
656 if (tcgetattr(fd, &t) == -1)
659 struct termios n = t;
662 n.c_lflag &= ~(ECHO);
663 tcsetattr(fd, TCSANOW, &n);
664 printf("%s%spassword for user %s:",
665 (mode == M_UPDATE) ? "new " : "",
666 precrypt ? "encrypted " : "",
671 b = read(fd, line, sizeof(line) - 1);
672 if (istty) { /* Restore state */
673 tcsetattr(fd, TCSANOW, &t);
678 warn("-%c file descriptor", precrypt ? 'H' :
683 if ((p = strpbrk(line, "\r\n")) != NULL)
686 errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
688 if (strchr(line, ':') != NULL)
690 pwd->pw_passwd = line;
692 lc = login_getpwclass(pwd);
694 login_setcryptfmt(lc, "md5", NULL) == NULL)
695 warn("setting crypt(3) format");
697 pwd->pw_passwd = pw_pwcrypt(line);
704 * Special case: -N only displays & exits
706 if (getarg(args, 'N') != NULL)
707 return print_user(pwd,
708 getarg(args, 'P') != NULL,
709 getarg(args, '7') != NULL);
712 edited = 1; /* Always */
715 warnx("user '%s' already exists", pwd->pw_name);
717 } else if (rc != 0) {
718 warn("passwd file update");
721 if (cnf->nispasswd && *cnf->nispasswd=='/') {
722 rc = addnispwent(cnf->nispasswd, pwd);
724 warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
726 warn("NIS passwd update");
727 /* NOTE: we treat NIS-only update errors as non-fatal */
729 } else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
730 if (edited) { /* Only updated this if required */
731 rc = chgpwent(a_name->val, pwd);
733 warnx("user '%s' does not exist (NIS?)", pwd->pw_name);
735 } else if (rc != 0) {
736 warn("passwd file update");
739 if ( cnf->nispasswd && *cnf->nispasswd=='/') {
740 rc = chgnispwent(cnf->nispasswd, a_name->val, pwd);
742 warn("User '%s' not found in NIS passwd", pwd->pw_name);
744 warn("NIS passwd update");
745 /* NOTE: NIS-only update errors are not fatal */
751 * Ok, user is created or changed - now edit group file
754 if (mode == M_ADD || getarg(args, 'G') != NULL) {
756 for (i = 0; cnf->groups[i] != NULL; i++) {
757 grp = GETGRNAM(cnf->groups[i]);
758 grp = gr_add(grp, pwd->pw_name);
760 * grp can only be NULL in 2 cases:
761 * - the new member is already a member
762 * - a problem with memory occurs
763 * in both cases we want to skip now.
767 chggrent(cnf->groups[i], grp);
773 /* go get a current version of pwd */
774 pwd = GETPWNAM(a_name->val);
776 /* This will fail when we rename, so special case that */
777 if (mode == M_UPDATE && (arg = getarg(args, 'l')) != NULL) {
778 a_name->val = arg->val; /* update new name */
779 pwd = GETPWNAM(a_name->val); /* refetch renamed rec */
782 if (pwd == NULL) /* can't go on without this */
783 errx(EX_NOUSER, "user '%s' disappeared during update", a_name->val);
785 grp = GETGRGID(pwd->pw_gid);
786 pw_log(cnf, mode, W_USER, "%s(%ld):%s(%ld):%s:%s:%s",
787 pwd->pw_name, (long) pwd->pw_uid,
788 grp ? grp->gr_name : "unknown", (long) (grp ? grp->gr_gid : -1),
789 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
792 * If adding, let's touch and chown the user's mail file. This is not
793 * strictly necessary under BSD with a 0755 maildir but it also
794 * doesn't hurt anything to create the empty mailfile
798 sprintf(line, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
799 close(open(line, O_RDWR | O_CREAT, 0600)); /* Preserve contents &
801 chown(line, pwd->pw_uid, pwd->pw_gid);
806 * Let's create and populate the user's home directory. Note
807 * that this also `works' for editing users if -m is used, but
808 * existing files will *not* be overwritten.
810 if (!PWALTDIR() && getarg(args, 'm') != NULL && pwd->pw_dir && *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
811 copymkdir(pwd->pw_dir, cnf->dotdir, cnf->homemode, pwd->pw_uid, pwd->pw_gid);
812 pw_log(cnf, mode, W_USER, "%s(%ld) home %s made",
813 pwd->pw_name, (long) pwd->pw_uid, pwd->pw_dir);
818 * Finally, send mail to the new user as well, if we are asked to
820 if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
821 FILE *pfp = popen(_PATH_SENDMAIL " -t", "w");
826 fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
827 while (fgets(line, sizeof(line), fp) != NULL) {
828 /* Do substitutions? */
832 pw_log(cnf, mode, W_USER, "%s(%ld) new user mail sent",
833 pwd->pw_name, (long) pwd->pw_uid);
843 pw_uidpolicy(struct userconf * cnf, struct cargs * args)
846 uid_t uid = (uid_t) - 1;
847 struct carg *a_uid = getarg(args, 'u');
850 * Check the given uid, if any
853 uid = (uid_t) atol(a_uid->val);
855 if ((pwd = GETPWUID(uid)) != NULL && getarg(args, 'o') == NULL)
856 errx(EX_DATAERR, "uid `%ld' has already been allocated", (long) pwd->pw_uid);
861 * We need to allocate the next available uid under one of
862 * two policies a) Grab the first unused uid b) Grab the
863 * highest possible unused uid
865 if (cnf->min_uid >= cnf->max_uid) { /* Sanity
866 * claus^H^H^H^Hheck */
868 cnf->max_uid = 32000;
870 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
873 * Now, let's fill the bitmap from the password file
876 while ((pwd = GETPWENT()) != NULL)
877 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
878 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
882 * Then apply the policy, with fallback to reuse if necessary
884 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
885 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
888 * Another sanity check
890 if (uid < cnf->min_uid || uid > cnf->max_uid)
891 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
899 pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer)
902 gid_t gid = (uid_t) - 1;
903 struct carg *a_gid = getarg(args, 'g');
906 * If no arg given, see if default can help out
908 if (a_gid == NULL && cnf->default_group && *cnf->default_group)
909 a_gid = addarg(args, 'g', cnf->default_group);
912 * Check the given gid, if any
916 if ((grp = GETGRNAM(a_gid->val)) == NULL) {
917 gid = (gid_t) atol(a_gid->val);
918 if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
919 errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
922 } else if ((grp = GETGRNAM(nam)) != NULL &&
923 (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
924 gid = grp->gr_gid; /* Already created? Use it anyway... */
926 struct cargs grpargs;
930 addarg(&grpargs, 'n', nam);
933 * We need to auto-create a group with the user's name. We
934 * can send all the appropriate output to our sister routine
935 * bit first see if we can create a group with gid==uid so we
936 * can keep the user and group ids in sync. We purposely do
937 * NOT check the gid range if we can force the sync. If the
938 * user's name dups an existing group, then the group add
939 * function will happily handle that case for us and exit.
941 if (GETGRGID(prefer) == NULL) {
942 sprintf(tmp, "%lu", (unsigned long) prefer);
943 addarg(&grpargs, 'g', tmp);
945 if (getarg(args, 'N'))
947 addarg(&grpargs, 'N', NULL);
948 addarg(&grpargs, 'q', NULL);
949 gid = pw_group(cnf, M_NEXT, &grpargs);
953 pw_group(cnf, M_ADD, &grpargs);
954 if ((grp = GETGRNAM(nam)) != NULL)
957 a_gid = LIST_FIRST(&grpargs);
958 while (a_gid != NULL) {
959 struct carg *t = LIST_NEXT(a_gid, list);
960 LIST_REMOVE(a_gid, list);
970 pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
973 time_t now = time(NULL);
974 struct carg *arg = getarg(args, 'p');
977 if ((result = parse_date(now, arg->val)) == now)
978 errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
979 } else if (cnf->password_days > 0)
980 result = now + ((long) cnf->password_days * 86400L);
986 pw_exppolicy(struct userconf * cnf, struct cargs * args)
989 time_t now = time(NULL);
990 struct carg *arg = getarg(args, 'e');
993 if ((result = parse_date(now, arg->val)) == now)
994 errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
995 } else if (cnf->expire_days > 0)
996 result = now + ((long) cnf->expire_days * 86400L);
1002 pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
1004 struct carg *arg = getarg(args, 'd');
1009 static char home[128];
1011 if (cnf->home == NULL || *cnf->home == '\0')
1012 errx(EX_CONFIG, "no base home directory set");
1013 sprintf(home, "%s/%s", cnf->home, user);
1019 shell_path(char const * path, char *shells[], char *sh)
1021 if (sh != NULL && (*sh == '/' || *sh == '\0'))
1022 return sh; /* specified full path or forced none */
1025 char paths[_UC_MAXLINE];
1028 * We need to search paths
1030 strlcpy(paths, path, sizeof(paths));
1031 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
1033 static char shellpath[256];
1036 sprintf(shellpath, "%s/%s", p, sh);
1037 if (access(shellpath, X_OK) == 0)
1040 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
1041 sprintf(shellpath, "%s/%s", p, shells[i]);
1042 if (access(shellpath, X_OK) == 0)
1047 errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
1048 errx(EX_CONFIG, "no default shell available or defined");
1055 pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
1057 char *sh = newshell;
1058 struct carg *arg = getarg(args, 's');
1060 if (newshell == NULL && arg != NULL)
1062 return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
1067 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1070 pw_pwcrypt(char *password)
1073 char salt[SALTSIZE + 1];
1076 static char buf[256];
1079 * Calculate a salt value
1081 for (i = 0; i < SALTSIZE; i++)
1082 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1083 salt[SALTSIZE] = '\0';
1085 cryptpw = crypt(password, salt);
1086 if (cryptpw == NULL)
1087 errx(EX_CONFIG, "crypt(3) failure");
1088 return strcpy(buf, cryptpw);
1093 pw_password(struct userconf * cnf, struct cargs * args, char const * user)
1098 switch (cnf->default_password) {
1099 case -1: /* Random password */
1100 l = (arc4random() % 8 + 8); /* 8 - 16 chars */
1101 for (i = 0; i < l; i++)
1102 pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
1106 * We give this information back to the user
1108 if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
1109 getarg(args, 'N') == NULL) {
1110 if (isatty(STDOUT_FILENO))
1111 printf("Password for '%s' is: ", user);
1112 printf("%s\n", pwbuf);
1117 case -2: /* No password at all! */
1120 case 0: /* No login - default */
1124 case 1: /* user's name */
1125 strlcpy(pwbuf, user, sizeof(pwbuf));
1128 return pw_pwcrypt(pwbuf);
1133 print_user(struct passwd * pwd, int pretty, int v7)
1139 pwd->pw_passwd = (pwd->pw_passwd == NULL) ? "" : "*";
1141 buf = v7 ? pw_make_v7(pwd) : pw_make(pwd);
1142 printf("%s\n", buf);
1147 struct group *grp = GETGRGID(pwd->pw_gid);
1148 char uname[60] = "User &", office[60] = "[None]",
1149 wphone[60] = "[None]", hphone[60] = "[None]";
1150 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
1153 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1154 strlcpy(uname, p, sizeof(uname));
1155 if ((p = strtok(NULL, ",")) != NULL) {
1156 strlcpy(office, p, sizeof(office));
1157 if ((p = strtok(NULL, ",")) != NULL) {
1158 strlcpy(wphone, p, sizeof(wphone));
1159 if ((p = strtok(NULL, "")) != NULL) {
1167 * Handle '&' in gecos field
1169 if ((p = strchr(uname, '&')) != NULL) {
1170 int l = strlen(pwd->pw_name);
1173 memmove(p + l, p + 1, m);
1174 memmove(p, pwd->pw_name, l);
1175 *p = (char) toupper((unsigned char)*p);
1177 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1178 strftime(acexpire, sizeof acexpire, "%c", tptr);
1179 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1180 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1181 printf("Login Name: %-15s #%-12ld Group: %-15s #%ld\n"
1183 " Home: %-26.26s Class: %s\n"
1184 " Shell: %-26.26s Office: %s\n"
1185 "Work Phone: %-26.26s Home Phone: %s\n"
1186 "Acc Expire: %-26.26s Pwd Expire: %s\n",
1187 pwd->pw_name, (long) pwd->pw_uid,
1188 grp ? grp->gr_name : "(invalid)", (long) pwd->pw_gid,
1189 uname, pwd->pw_dir, pwd->pw_class,
1190 pwd->pw_shell, office, wphone, hphone,
1191 acexpire, pwexpire);
1194 while ((grp=GETGRENT()) != NULL)
1197 if (grp->gr_mem != NULL) {
1198 while (grp->gr_mem[i] != NULL)
1200 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1202 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
1210 printf("%s", j ? "\n" : "");
1212 return EXIT_SUCCESS;
1216 pw_checkname(u_char *name, int gecos)
1219 u_char const *badchars, *ch, *showtype;
1225 /* See if the name is valid as a gecos (comment) field. */
1227 showtype = "gecos field";
1229 /* See if the name is valid as a userid or group. */
1230 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1231 showtype = "userid/group name";
1232 /* Userids and groups can not have a leading '-'. */
1238 if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1243 /* 8-bit characters are only allowed in GECOS fields */
1244 if (!gecos && (*ch & 0x80)) {
1252 * A `$' is allowed as the final character for userids and groups,
1253 * mainly for the benefit of samba.
1255 if (reject && !gecos) {
1256 if (*ch == '$' && *(ch + 1) == '\0') {
1262 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1263 ? "`%c'" : "0x%02x", *ch);
1264 errx(EX_DATAERR, "invalid character %s at position %td in %s",
1265 showch, (ch - name), showtype);
1267 if (!gecos && (ch - name) > LOGNAMESIZE)
1268 errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1270 return (char *)name;
1277 DIR *d = opendir("/var/at/jobs");
1282 while ((e = readdir(d)) != NULL) {
1285 if (strncmp(e->d_name, ".lock", 5) != 0 &&
1286 stat(e->d_name, &st) == 0 &&
1287 !S_ISDIR(st.st_mode) &&
1289 char tmp[MAXPATHLEN];
1291 sprintf(tmp, "/usr/bin/atrm %s", e->d_name);
1300 rmopie(char const * name)
1302 static const char etcopie[] = "/etc/opiekeys";
1303 FILE *fp = fopen(etcopie, "r+");
1308 int length = strlen(name);
1310 while (fgets(tmp, sizeof tmp, fp) != NULL) {
1311 if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
1312 if (fseek(fp, atofs, SEEK_SET) == 0) {
1313 fwrite("#", 1, 1, fp); /* Comment username out */
1320 * If we got an error of any sort, don't update!