xref: /freebsd/usr.sbin/pw/pw_user.c (revision c3a3d1fd6c7007e7088936e14fd9b4944b3a3054)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 1996
5  *	David L. Nugent.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  */
29 
30 #ifndef lint
31 static const char rcsid[] =
32   "$FreeBSD$";
33 #endif /* not lint */
34 
35 #include <sys/param.h>
36 #include <sys/types.h>
37 
38 #include <assert.h>
39 #include <ctype.h>
40 #include <dirent.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <grp.h>
45 #include <pwd.h>
46 #include <libutil.h>
47 #include <login_cap.h>
48 #include <paths.h>
49 #include <string.h>
50 #include <sysexits.h>
51 #include <termios.h>
52 #include <unistd.h>
53 
54 #include "pw.h"
55 #include "bitmap.h"
56 #include "psdate.h"
57 
58 #define LOGNAMESIZE (MAXLOGNAME-1)
59 
60 static		char locked_str[] = "*LOCKED*";
61 
62 static struct passwd fakeuser = {
63 	"nouser",
64 	"*",
65 	-1,
66 	-1,
67 	0,
68 	"",
69 	"User &",
70 	"/nonexistent",
71 	"/bin/sh",
72 	0,
73 	0
74 };
75 
76 static int	 print_user(struct passwd *pwd, bool pretty, bool v7);
77 static uid_t	 pw_uidpolicy(struct userconf *cnf, intmax_t id);
78 static uid_t	 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam,
79     gid_t prefer, bool dryrun);
80 static char	*pw_homepolicy(struct userconf * cnf, char *homedir,
81     const char *user);
82 static char	*pw_shellpolicy(struct userconf * cnf);
83 static char	*pw_password(struct userconf * cnf, char const * user,
84     bool dryrun);
85 static char	*shell_path(char const * path, char *shells[], char *sh);
86 static void	rmat(uid_t uid);
87 
88 static void
89 mkdir_home_parents(int dfd, const char *dir)
90 {
91 	struct stat st;
92 	char *dirs, *tmp;
93 
94 	if (*dir != '/')
95 		errx(EX_DATAERR, "invalid base directory for home '%s'", dir);
96 
97 	dir++;
98 
99 	if (fstatat(dfd, dir, &st, 0) != -1) {
100 		if (S_ISDIR(st.st_mode))
101 			return;
102 		errx(EX_OSFILE, "root home `/%s' is not a directory", dir);
103 	}
104 
105 	dirs = strdup(dir);
106 	if (dirs == NULL)
107 		errx(EX_UNAVAILABLE, "out of memory");
108 
109 	tmp = strrchr(dirs, '/');
110 	if (tmp == NULL) {
111 		free(dirs);
112 		return;
113 	}
114 	tmp[0] = '\0';
115 
116 	/*
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
121 	 */
122 	if (strchr(dirs, '/') == NULL) {
123 		asprintf(&tmp, "usr/%s", dirs);
124 		if (tmp == NULL)
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);
129 		}
130 		free(tmp);
131 	}
132 	tmp = dirs;
133 	if (fstatat(dfd, dirs, &st, 0) == -1) {
134 		while ((tmp = strchr(tmp + 1, '/')) != NULL) {
135 			*tmp = '\0';
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);
139 			}
140 			*tmp = '/';
141 		}
142 	}
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);
147 	}
148 
149 	free(dirs);
150 }
151 
152 static void
153 create_and_populate_homedir(struct userconf *cnf, struct passwd *pwd,
154     const char *skeldir, mode_t homemode, bool update)
155 {
156 	int skelfd = -1;
157 
158 	/* Create home parents directories */
159 	mkdir_home_parents(conf.rootfd, pwd->pw_dir);
160 
161 	if (skeldir != NULL && *skeldir != '\0') {
162 		if (*skeldir == '/')
163 			skeldir++;
164 		skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
165 	}
166 
167 	copymkdir(conf.rootfd, pwd->pw_dir, skelfd, homemode, pwd->pw_uid,
168 	    pwd->pw_gid, 0);
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);
171 }
172 
173 static int
174 pw_set_passwd(struct passwd *pwd, int fd, bool precrypted, bool update)
175 {
176 	int		 b, istty;
177 	struct termios	 t, n;
178 	login_cap_t	*lc;
179 	char		line[_PASSWORD_LEN+1];
180 	char		*p;
181 
182 	if (fd == '-') {
183 		if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
184 			pwd->pw_passwd = "*";	/* No access */
185 			return (1);
186 		}
187 		return (0);
188 	}
189 
190 	if ((istty = isatty(fd))) {
191 		if (tcgetattr(fd, &t) == -1)
192 			istty = 0;
193 		else {
194 			n = t;
195 			n.c_lflag &= ~(ECHO);
196 			tcsetattr(fd, TCSANOW, &n);
197 			printf("%s%spassword for user %s:",
198 			    update ? "new " : "",
199 			    precrypted ? "encrypted " : "",
200 			    pwd->pw_name);
201 			fflush(stdout);
202 		}
203 	}
204 	b = read(fd, line, sizeof(line) - 1);
205 	if (istty) {	/* Restore state */
206 		tcsetattr(fd, TCSANOW, &t);
207 		fputc('\n', stdout);
208 		fflush(stdout);
209 	}
210 
211 	if (b < 0)
212 		err(EX_IOERR, "-%c file descriptor",
213 		    precrypted ? 'H' : 'h');
214 	line[b] = '\0';
215 	if ((p = strpbrk(line, "\r\n")) != NULL)
216 		*p = '\0';
217 	if (!*line)
218 		errx(EX_DATAERR, "empty password read on file descriptor %d",
219 		    fd);
220 	if (precrypted) {
221 		if (strchr(line, ':') != NULL)
222 			errx(EX_DATAERR, "bad encrypted password");
223 		pwd->pw_passwd = strdup(line);
224 	} else {
225 		lc = login_getpwclass(pwd);
226 		if (lc == NULL ||
227 				login_setcryptfmt(lc, "sha512", NULL) == NULL)
228 			warn("setting crypt(3) format");
229 		login_close(lc);
230 		pwd->pw_passwd = pw_pwcrypt(line);
231 	}
232 	return (1);
233 }
234 
235 static void
236 perform_chgpwent(const char *name, struct passwd *pwd, char *nispasswd)
237 {
238 	int rc;
239 	struct passwd *nispwd;
240 
241 	/* duplicate for nis so that chgpwent is not modifying before NIS */
242 	if (nispasswd && *nispasswd == '/')
243 		nispwd = pw_dup(pwd);
244 
245 	rc = chgpwent(name, pwd);
246 	if (rc == -1)
247 		errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
248 	else if (rc != 0)
249 		err(EX_IOERR, "passwd file update");
250 
251 	if (nispasswd && *nispasswd == '/') {
252 		rc = chgnispwent(nispasswd, name, nispwd);
253 		if (rc == -1)
254 			warn("User '%s' not found in NIS passwd", pwd->pw_name);
255 		else if (rc != 0)
256 			warn("NIS passwd update");
257 		/* NOTE: NIS-only update errors are not fatal */
258 	}
259 }
260 
261 /*
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.
269  */
270 static int
271 pw_userlock(char *arg1, int mode)
272 {
273 	struct passwd *pwd = NULL;
274 	char *passtmp = NULL;
275 	char *name;
276 	bool locked = false;
277 	uid_t id = (uid_t)-1;
278 
279 	if (geteuid() != 0)
280 		errx(EX_NOPERM, "you must be root");
281 
282 	if (arg1 == NULL)
283 		errx(EX_DATAERR, "username or id required");
284 
285 	name = arg1;
286 	if (arg1[strspn(name, "0123456789")] == '\0')
287 		id = pw_checkid(name, UID_MAX);
288 
289 	pwd = GETPWNAM(pw_checkname(name, 0));
290 	if (pwd == NULL && id != (uid_t)-1) {
291 		pwd = GETPWUID(id);
292 		if (pwd != NULL)
293 			name = pwd->pw_name;
294 	}
295 	if (pwd == NULL) {
296 		if (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);
299 	}
300 
301 	if (name == NULL)
302 		name = pwd->pw_name;
303 
304 	if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
305 		locked = true;
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);
310 
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;
316 	} else {
317 		pwd->pw_passwd += sizeof(locked_str)-1;
318 	}
319 
320 	perform_chgpwent(name, pwd, NULL);
321 	free(passtmp);
322 
323 	return (EXIT_SUCCESS);
324 }
325 
326 static uid_t
327 pw_uidpolicy(struct userconf * cnf, intmax_t id)
328 {
329 	struct passwd  *pwd;
330 	struct bitmap   bm;
331 	uid_t           uid = (uid_t) - 1;
332 
333 	/*
334 	 * Check the given uid, if any
335 	 */
336 	if (id >= 0) {
337 		uid = (uid_t) id;
338 
339 		if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
340 			errx(EX_DATAERR, "uid `%ju' has already been allocated",
341 			    (uintmax_t)pwd->pw_uid);
342 		return (uid);
343 	}
344 	/*
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
348 	 */
349 	if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
350 						 * claus^H^H^H^Hheck */
351 		cnf->min_uid = 1000;
352 		cnf->max_uid = 32000;
353 	}
354 	bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
355 
356 	/*
357 	 * Now, let's fill the bitmap from the password file
358 	 */
359 	SETPWENT();
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);
363 	ENDPWENT();
364 
365 	/*
366 	 * Then apply the policy, with fallback to reuse if necessary
367 	 */
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);
370 
371 	/*
372 	 * Another sanity check
373 	 */
374 	if (uid < cnf->min_uid || uid > cnf->max_uid)
375 		errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
376 	bm_dealloc(&bm);
377 	return (uid);
378 }
379 
380 static uid_t
381 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam, gid_t prefer, bool dryrun)
382 {
383 	struct group   *grp;
384 	gid_t           gid = (uid_t) - 1;
385 
386 	/*
387 	 * Check the given gid, if any
388 	 */
389 	SETGRENT();
390 	if (grname) {
391 		if ((grp = GETGRNAM(grname)) == NULL) {
392 			gid = pw_checkid(grname, GID_MAX);
393 			grp = GETGRGID(gid);
394 		}
395 		gid = grp->gr_gid;
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... */
399 	} else {
400 		intmax_t		grid = -1;
401 
402 		/*
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.
410 		 */
411 		if (GETGRGID(prefer) == NULL)
412 			grid = prefer;
413 		if (dryrun) {
414 			gid = pw_groupnext(cnf, true);
415 		} else {
416 			if (grid == -1)
417 				grid =  pw_groupnext(cnf, true);
418 			groupadd(cnf, nam, grid, NULL, -1, false, false, false);
419 			if ((grp = GETGRNAM(nam)) != NULL)
420 				gid = grp->gr_gid;
421 		}
422 	}
423 	ENDGRENT();
424 	return (gid);
425 }
426 
427 static char *
428 pw_homepolicy(struct userconf * cnf, char *homedir, const char *user)
429 {
430 	static char     home[128];
431 
432 	if (homedir)
433 		return (homedir);
434 
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);
438 
439 	return (home);
440 }
441 
442 static char *
443 shell_path(char const * path, char *shells[], char *sh)
444 {
445 	if (sh != NULL && (*sh == '/' || *sh == '\0'))
446 		return sh;	/* specified full path or forced none */
447 	else {
448 		char           *p;
449 		char            paths[_UC_MAXLINE];
450 
451 		/*
452 		 * We need to search paths
453 		 */
454 		strlcpy(paths, path, sizeof(paths));
455 		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
456 			int             i;
457 			static char     shellpath[256];
458 
459 			if (sh != NULL) {
460 				snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
461 				if (access(shellpath, X_OK) == 0)
462 					return shellpath;
463 			} else
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)
467 						return shellpath;
468 				}
469 		}
470 		if (sh == NULL)
471 			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
472 		errx(EX_CONFIG, "no default shell available or defined");
473 		return NULL;
474 	}
475 }
476 
477 static char *
478 pw_shellpolicy(struct userconf * cnf)
479 {
480 
481 	return shell_path(cnf->shelldir, cnf->shells, cnf->shell_default);
482 }
483 
484 #define	SALTSIZE	32
485 
486 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
487 
488 char *
489 pw_pwcrypt(char *password)
490 {
491 	int             i;
492 	char            salt[SALTSIZE + 1];
493 	char		*cryptpw;
494 	static char     buf[256];
495 	size_t		pwlen;
496 
497 	/*
498 	 * Calculate a salt value
499 	 */
500 	for (i = 0; i < SALTSIZE; i++)
501 		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
502 	salt[SALTSIZE] = '\0';
503 
504 	cryptpw = crypt(password, salt);
505 	if (cryptpw == NULL)
506 		errx(EX_CONFIG, "crypt(3) failure");
507 	pwlen = strlcpy(buf, cryptpw, sizeof(buf));
508 	assert(pwlen < sizeof(buf));
509 	return (buf);
510 }
511 
512 static char *
513 pw_password(struct userconf * cnf, char const * user, bool dryrun)
514 {
515 	int             i, l;
516 	char            pwbuf[32];
517 
518 	switch (cnf->default_password) {
519 	case P_NONE:		/* No password at all! */
520 		return "";
521 	case P_RANDOM:			/* Random password */
522 		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
523 		for (i = 0; i < l; i++)
524 			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
525 		pwbuf[i] = '\0';
526 
527 		/*
528 		 * We give this information back to the user
529 		 */
530 		if (conf.fd == -1 && !dryrun) {
531 			if (isatty(STDOUT_FILENO))
532 				printf("Password for '%s' is: ", user);
533 			printf("%s\n", pwbuf);
534 			fflush(stdout);
535 		}
536 		break;
537 	case P_YES:		/* user's name */
538 		strlcpy(pwbuf, user, sizeof(pwbuf));
539 		break;
540 	case P_NO:		/* No login - default */
541 				/* FALLTHROUGH */
542 	default:
543 		return "*";
544 	}
545 	return pw_pwcrypt(pwbuf);
546 }
547 
548 static int
549 print_user(struct passwd * pwd, bool pretty, bool v7)
550 {
551 	int		j;
552 	char           *p;
553 	struct group   *grp = GETGRGID(pwd->pw_gid);
554 	char            uname[60] = "User &", office[60] = "[None]",
555 			wphone[60] = "[None]", hphone[60] = "[None]";
556 	char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
557 	struct tm *    tptr;
558 
559 	if (!pretty) {
560 		p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
561 		printf("%s\n", p);
562 		free(p);
563 		return (EXIT_SUCCESS);
564 	}
565 
566 	if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
567 		strlcpy(uname, p, sizeof(uname));
568 		if ((p = strtok(NULL, ",")) != NULL) {
569 			strlcpy(office, p, sizeof(office));
570 			if ((p = strtok(NULL, ",")) != NULL) {
571 				strlcpy(wphone, p, sizeof(wphone));
572 				if ((p = strtok(NULL, "")) != NULL) {
573 					strlcpy(hphone, p, sizeof(hphone));
574 				}
575 			}
576 		}
577 	}
578 	/*
579 	 * Handle '&' in gecos field
580 	 */
581 	if ((p = strchr(uname, '&')) != NULL) {
582 		int             l = strlen(pwd->pw_name);
583 		int             m = strlen(p);
584 
585 		memmove(p + l, p + 1, m);
586 		memmove(p, pwd->pw_name, l);
587 		*p = (char) toupper((unsigned char)*p);
588 	}
589 	if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
590 		strftime(acexpire, sizeof acexpire, "%c", tptr);
591 	if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
592 		strftime(pwexpire, sizeof pwexpire, "%c", tptr);
593 	printf("Login Name: %-15s   #%-12ju Group: %-15s   #%ju\n"
594 	       " Full Name: %s\n"
595 	       "      Home: %-26.26s      Class: %s\n"
596 	       "     Shell: %-26.26s     Office: %s\n"
597 	       "Work Phone: %-26.26s Home Phone: %s\n"
598 	       "Acc Expire: %-26.26s Pwd Expire: %s\n",
599 	       pwd->pw_name, (uintmax_t)pwd->pw_uid,
600 	       grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
601 	       uname, pwd->pw_dir, pwd->pw_class,
602 	       pwd->pw_shell, office, wphone, hphone,
603 	       acexpire, pwexpire);
604         SETGRENT();
605 	j = 0;
606 	while ((grp=GETGRENT()) != NULL) {
607 		int     i = 0;
608 		if (grp->gr_mem != NULL) {
609 			while (grp->gr_mem[i] != NULL) {
610 				if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
611 					printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
612 					break;
613 				}
614 				++i;
615 			}
616 		}
617 	}
618 	ENDGRENT();
619 	printf("%s", j ? "\n" : "");
620 	return (EXIT_SUCCESS);
621 }
622 
623 char *
624 pw_checkname(char *name, int gecos)
625 {
626 	char showch[8];
627 	const char *badchars, *ch, *showtype;
628 	int reject;
629 
630 	ch = name;
631 	reject = 0;
632 	if (gecos) {
633 		/* See if the name is valid as a gecos (comment) field. */
634 		badchars = ":";
635 		showtype = "gecos field";
636 	} else {
637 		/* See if the name is valid as a userid or group. */
638 		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
639 		showtype = "userid/group name";
640 		/* Userids and groups can not have a leading '-'. */
641 		if (*ch == '-')
642 			reject = 1;
643 	}
644 	if (!reject) {
645 		while (*ch) {
646 			if (strchr(badchars, *ch) != NULL ||
647 			    (!gecos && *ch < ' ') ||
648 			    *ch == 127) {
649 				reject = 1;
650 				break;
651 			}
652 			/* 8-bit characters are only allowed in GECOS fields */
653 			if (!gecos && (*ch & 0x80)) {
654 				reject = 1;
655 				break;
656 			}
657 			ch++;
658 		}
659 	}
660 	/*
661 	 * A `$' is allowed as the final character for userids and groups,
662 	 * mainly for the benefit of samba.
663 	 */
664 	if (reject && !gecos) {
665 		if (*ch == '$' && *(ch + 1) == '\0') {
666 			reject = 0;
667 			ch++;
668 		}
669 	}
670 	if (reject) {
671 		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
672 		    ? "`%c'" : "0x%02x", *ch);
673 		errx(EX_DATAERR, "invalid character %s at position %td in %s",
674 		    showch, (ch - name), showtype);
675 	}
676 	if (!gecos && (ch - name) > LOGNAMESIZE)
677 		errx(EX_USAGE, "name too long `%s' (max is %d)", name,
678 		    LOGNAMESIZE);
679 
680 	return (name);
681 }
682 
683 static void
684 rmat(uid_t uid)
685 {
686 	DIR            *d = opendir("/var/at/jobs");
687 
688 	if (d != NULL) {
689 		struct dirent  *e;
690 
691 		while ((e = readdir(d)) != NULL) {
692 			struct stat     st;
693 
694 			if (strncmp(e->d_name, ".lock", 5) != 0 &&
695 			    stat(e->d_name, &st) == 0 &&
696 			    !S_ISDIR(st.st_mode) &&
697 			    st.st_uid == uid) {
698 				char            tmp[MAXPATHLEN];
699 
700 				snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s",
701 				    e->d_name);
702 				system(tmp);
703 			}
704 		}
705 		closedir(d);
706 	}
707 }
708 
709 int
710 pw_user_next(int argc, char **argv, char *name __unused)
711 {
712 	struct userconf *cnf = NULL;
713 	const char *cfg = NULL;
714 	int ch;
715 	bool quiet = false;
716 	uid_t next;
717 
718 	while ((ch = getopt(argc, argv, "C:q")) != -1) {
719 		switch (ch) {
720 		case 'C':
721 			cfg = optarg;
722 			break;
723 		case 'q':
724 			quiet = true;
725 			break;
726 		}
727 	}
728 
729 	if (quiet)
730 		freopen(_PATH_DEVNULL, "w", stderr);
731 
732 	cnf = get_userconfig(cfg);
733 
734 	next = pw_uidpolicy(cnf, -1);
735 
736 	printf("%ju:", (uintmax_t)next);
737 	pw_groupnext(cnf, quiet);
738 
739 	return (EXIT_SUCCESS);
740 }
741 
742 int
743 pw_user_show(int argc, char **argv, char *arg1)
744 {
745 	struct passwd *pwd = NULL;
746 	char *name = NULL;
747 	intmax_t id = -1;
748 	int ch;
749 	bool all = false;
750 	bool pretty = false;
751 	bool force = false;
752 	bool v7 = false;
753 	bool quiet = false;
754 
755 	if (arg1 != NULL) {
756 		if (arg1[strspn(arg1, "0123456789")] == '\0')
757 			id = pw_checkid(arg1, UID_MAX);
758 		else
759 			name = arg1;
760 	}
761 
762 	while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
763 		switch (ch) {
764 		case 'C':
765 			/* ignore compatibility */
766 			break;
767 		case 'q':
768 			quiet = true;
769 			break;
770 		case 'n':
771 			name = optarg;
772 			break;
773 		case 'u':
774 			id = pw_checkid(optarg, UID_MAX);
775 			break;
776 		case 'F':
777 			force = true;
778 			break;
779 		case 'P':
780 			pretty = true;
781 			break;
782 		case 'a':
783 			all = true;
784 			break;
785 		case '7':
786 			v7 = true;
787 			break;
788 		}
789 	}
790 
791 	if (quiet)
792 		freopen(_PATH_DEVNULL, "w", stderr);
793 
794 	if (all) {
795 		SETPWENT();
796 		while ((pwd = GETPWENT()) != NULL)
797 			print_user(pwd, pretty, v7);
798 		ENDPWENT();
799 		return (EXIT_SUCCESS);
800 	}
801 
802 	if (id < 0 && name == NULL)
803 		errx(EX_DATAERR, "username or id required");
804 
805 	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
806 	if (pwd == NULL) {
807 		if (force) {
808 			pwd = &fakeuser;
809 		} else {
810 			if (name == NULL)
811 				errx(EX_NOUSER, "no such uid `%ju'",
812 				    (uintmax_t) id);
813 			errx(EX_NOUSER, "no such user `%s'", name);
814 		}
815 	}
816 
817 	return (print_user(pwd, pretty, v7));
818 }
819 
820 int
821 pw_user_del(int argc, char **argv, char *arg1)
822 {
823 	struct userconf *cnf = NULL;
824 	struct passwd *pwd = NULL;
825 	struct group *gr, *grp;
826 	char *name = NULL;
827 	char grname[MAXLOGNAME];
828 	char *nispasswd = NULL;
829 	char file[MAXPATHLEN];
830 	char home[MAXPATHLEN];
831 	const char *cfg = NULL;
832 	struct stat st;
833 	intmax_t id = -1;
834 	int ch, rc;
835 	bool nis = false;
836 	bool deletehome = false;
837 	bool quiet = false;
838 
839 	if (arg1 != NULL) {
840 		if (arg1[strspn(arg1, "0123456789")] == '\0')
841 			id = pw_checkid(arg1, UID_MAX);
842 		else
843 			name = arg1;
844 	}
845 
846 	while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
847 		switch (ch) {
848 		case 'C':
849 			cfg = optarg;
850 			break;
851 		case 'q':
852 			quiet = true;
853 			break;
854 		case 'n':
855 			name = optarg;
856 			break;
857 		case 'u':
858 			id = pw_checkid(optarg, UID_MAX);
859 			break;
860 		case 'r':
861 			deletehome = true;
862 			break;
863 		case 'y':
864 			nispasswd = optarg;
865 			break;
866 		case 'Y':
867 			nis = true;
868 			break;
869 		}
870 	}
871 
872 	if (quiet)
873 		freopen(_PATH_DEVNULL, "w", stderr);
874 
875 	if (id < 0 && name == NULL)
876 		errx(EX_DATAERR, "username or id required");
877 
878 	cnf = get_userconfig(cfg);
879 
880 	if (nispasswd == NULL)
881 		nispasswd = cnf->nispasswd;
882 
883 	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
884 	if (pwd == NULL) {
885 		if (name == NULL)
886 			errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
887 		errx(EX_NOUSER, "no such user `%s'", name);
888 	}
889 
890 	if (PWF._altdir == PWF_REGULAR &&
891 	    ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
892 		if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
893 			if (!nis && nispasswd && *nispasswd != '/')
894 				errx(EX_NOUSER, "Cannot remove NIS user `%s'",
895 				    name);
896 		} else {
897 			errx(EX_NOUSER, "Cannot remove non local user `%s'",
898 			    name);
899 		}
900 	}
901 
902 	id = pwd->pw_uid;
903 	if (name == NULL)
904 		name = pwd->pw_name;
905 
906 	if (strcmp(pwd->pw_name, "root") == 0)
907 		errx(EX_DATAERR, "cannot remove user 'root'");
908 
909 	if (!PWALTDIR()) {
910 		/* Remove crontabs */
911 		snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
912 		if (access(file, F_OK) == 0) {
913 			snprintf(file, sizeof(file), "crontab -u %s -r",
914 			    pwd->pw_name);
915 			system(file);
916 		}
917 	}
918 
919 	/*
920 	 * Save these for later, since contents of pwd may be
921 	 * invalidated by deletion
922 	 */
923 	snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
924 	strlcpy(home, pwd->pw_dir, sizeof(home));
925 	gr = GETGRGID(pwd->pw_gid);
926 	if (gr != NULL)
927 		strlcpy(grname, gr->gr_name, LOGNAMESIZE);
928 	else
929 		grname[0] = '\0';
930 
931 	rc = delpwent(pwd);
932 	if (rc == -1)
933 		err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
934 	else if (rc != 0)
935 		err(EX_IOERR, "passwd update");
936 
937 	if (nis && nispasswd && *nispasswd=='/') {
938 		rc = delnispwent(nispasswd, name);
939 		if (rc == -1)
940 			warnx("WARNING: user '%s' does not exist in NIS passwd",
941 			    pwd->pw_name);
942 		else if (rc != 0)
943 			warn("WARNING: NIS passwd update");
944 	}
945 
946 	grp = GETGRNAM(name);
947 	if (grp != NULL &&
948 	    (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
949 	    strcmp(name, grname) == 0)
950 		delgrent(GETGRNAM(name));
951 	SETGRENT();
952 	while ((grp = GETGRENT()) != NULL) {
953 		int i, j;
954 		char group[MAXLOGNAME];
955 		if (grp->gr_mem == NULL)
956 			continue;
957 
958 		for (i = 0; grp->gr_mem[i] != NULL; i++) {
959 			if (strcmp(grp->gr_mem[i], name) != 0)
960 				continue;
961 
962 			for (j = i; grp->gr_mem[j] != NULL; j++)
963 				grp->gr_mem[j] = grp->gr_mem[j+1];
964 			strlcpy(group, grp->gr_name, MAXLOGNAME);
965 			chggrent(group, grp);
966 		}
967 	}
968 	ENDGRENT();
969 
970 	pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
971 	    (uintmax_t)id);
972 
973 	/* Remove mail file */
974 	if (PWALTDIR() != PWF_ALT)
975 		unlinkat(conf.rootfd, file + 1, 0);
976 
977 	/* Remove at jobs */
978 	if (!PWALTDIR() && getpwuid(id) == NULL)
979 		rmat(id);
980 
981 	/* Remove home directory and contents */
982 	if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
983 	    GETPWUID(id) == NULL &&
984 	    fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
985 		rm_r(conf.rootfd, home, id);
986 		pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
987 		    "removed", name, (uintmax_t)id, home,
988 		     fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
989 		     "completely ");
990 	}
991 
992 	return (EXIT_SUCCESS);
993 }
994 
995 int
996 pw_user_lock(int argc, char **argv, char *arg1)
997 {
998 	int ch;
999 
1000 	while ((ch = getopt(argc, argv, "Cq")) != -1) {
1001 		switch (ch) {
1002 		case 'C':
1003 		case 'q':
1004 			/* compatibility */
1005 			break;
1006 		}
1007 	}
1008 
1009 	return (pw_userlock(arg1, M_LOCK));
1010 }
1011 
1012 int
1013 pw_user_unlock(int argc, char **argv, char *arg1)
1014 {
1015 	int ch;
1016 
1017 	while ((ch = getopt(argc, argv, "Cq")) != -1) {
1018 		switch (ch) {
1019 		case 'C':
1020 		case 'q':
1021 			/* compatibility */
1022 			break;
1023 		}
1024 	}
1025 
1026 	return (pw_userlock(arg1, M_UNLOCK));
1027 }
1028 
1029 static struct group *
1030 group_from_name_or_id(char *name)
1031 {
1032 	const char *errstr = NULL;
1033 	struct group *grp;
1034 	uintmax_t id;
1035 
1036 	if ((grp = GETGRNAM(name)) == NULL) {
1037 		id = strtounum(name, 0, GID_MAX, &errstr);
1038 		if (errstr)
1039 			errx(EX_NOUSER, "group `%s' does not exist", name);
1040 		grp = GETGRGID(id);
1041 		if (grp == NULL)
1042 			errx(EX_NOUSER, "group `%s' does not exist", name);
1043 	}
1044 
1045 	return (grp);
1046 }
1047 
1048 static void
1049 split_groups(StringList **groups, char *groupsstr)
1050 {
1051 	struct group *grp;
1052 	char *p;
1053 	char tok[] = ", \t";
1054 
1055 	if (*groups == NULL)
1056 		*groups = sl_init();
1057 	for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1058 		grp = group_from_name_or_id(p);
1059 		sl_add(*groups, newstr(grp->gr_name));
1060 	}
1061 }
1062 
1063 static void
1064 validate_grname(struct userconf *cnf, char *group)
1065 {
1066 	struct group *grp;
1067 
1068 	if (group == NULL || *group == '\0') {
1069 		cnf->default_group = "";
1070 		return;
1071 	}
1072 	grp = group_from_name_or_id(group);
1073 	cnf->default_group = newstr(grp->gr_name);
1074 }
1075 
1076 static mode_t
1077 validate_mode(char *mode)
1078 {
1079 	mode_t m;
1080 	void *set;
1081 
1082 	if ((set = setmode(mode)) == NULL)
1083 		errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1084 
1085 	m = getmode(set, _DEF_DIRMODE);
1086 	free(set);
1087 	return (m);
1088 }
1089 
1090 static long
1091 validate_expire(char *str, int opt)
1092 {
1093 	if (!numerics(str))
1094 		errx(EX_DATAERR, "-%c argument must be numeric "
1095 		     "when setting defaults: %s", (char)opt, str);
1096 	return strtol(str, NULL, 0);
1097 }
1098 
1099 static void
1100 mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1101 {
1102 
1103 	if (cmdcnf->default_password < 0)
1104 		cmdcnf->default_password = cfg->default_password;
1105 	if (cmdcnf->reuse_uids == 0)
1106 		cmdcnf->reuse_uids = cfg->reuse_uids;
1107 	if (cmdcnf->reuse_gids == 0)
1108 		cmdcnf->reuse_gids = cfg->reuse_gids;
1109 	if (cmdcnf->nispasswd == NULL)
1110 		cmdcnf->nispasswd = cfg->nispasswd;
1111 	if (cmdcnf->dotdir == NULL)
1112 		cmdcnf->dotdir = cfg->dotdir;
1113 	if (cmdcnf->newmail == NULL)
1114 		cmdcnf->newmail = cfg->newmail;
1115 	if (cmdcnf->logfile == NULL)
1116 		cmdcnf->logfile = cfg->logfile;
1117 	if (cmdcnf->home == NULL)
1118 		cmdcnf->home = cfg->home;
1119 	if (cmdcnf->homemode == 0)
1120 		cmdcnf->homemode = cfg->homemode;
1121 	if (cmdcnf->shelldir == NULL)
1122 		cmdcnf->shelldir = cfg->shelldir;
1123 	if (cmdcnf->shells == NULL)
1124 		cmdcnf->shells = cfg->shells;
1125 	if (cmdcnf->shell_default == NULL)
1126 		cmdcnf->shell_default = cfg->shell_default;
1127 	if (cmdcnf->default_group == NULL)
1128 		cmdcnf->default_group = cfg->default_group;
1129 	if (cmdcnf->groups == NULL)
1130 		cmdcnf->groups = cfg->groups;
1131 	if (cmdcnf->default_class == NULL)
1132 		cmdcnf->default_class = cfg->default_class;
1133 	if (cmdcnf->min_uid == 0)
1134 		cmdcnf->min_uid = cfg->min_uid;
1135 	if (cmdcnf->max_uid == 0)
1136 		cmdcnf->max_uid = cfg->max_uid;
1137 	if (cmdcnf->min_gid == 0)
1138 		cmdcnf->min_gid = cfg->min_gid;
1139 	if (cmdcnf->max_gid == 0)
1140 		cmdcnf->max_gid = cfg->max_gid;
1141 	if (cmdcnf->expire_days < 0)
1142 		cmdcnf->expire_days = cfg->expire_days;
1143 	if (cmdcnf->password_days < 0)
1144 		cmdcnf->password_days = cfg->password_days;
1145 }
1146 
1147 int
1148 pw_user_add(int argc, char **argv, char *arg1)
1149 {
1150 	struct userconf *cnf, *cmdcnf;
1151 	struct passwd *pwd;
1152 	struct group *grp;
1153 	struct stat st;
1154 	char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1155 	char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1156 	char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1157 	char *default_passwd, *name, *p;
1158 	const char *cfg = NULL;
1159 	login_cap_t *lc;
1160 	FILE *pfp, *fp;
1161 	intmax_t id = -1;
1162 	time_t now;
1163 	int rc, ch, fd = -1;
1164 	size_t i;
1165 	bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1166 
1167 	dryrun = nis = pretty = quiet = createhome = precrypted = false;
1168 	genconf = false;
1169 	gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1170 	grname = name = NULL;
1171 
1172 	if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1173 		err(EXIT_FAILURE, "calloc()");
1174 
1175 	cmdcnf->default_password = cmdcnf->expire_days = cmdcnf->password_days = -1;
1176 	now = time(NULL);
1177 
1178 	if (arg1 != NULL) {
1179 		if (arg1[strspn(arg1, "0123456789")] == '\0')
1180 			id = pw_checkid(arg1, UID_MAX);
1181 		else
1182 			name = pw_checkname(arg1, 0);
1183 	}
1184 
1185 	while ((ch = getopt(argc, argv, args)) != -1) {
1186 		switch (ch) {
1187 		case 'C':
1188 			cfg = optarg;
1189 			break;
1190 		case 'q':
1191 			quiet = true;
1192 			break;
1193 		case 'n':
1194 			name = pw_checkname(optarg, 0);
1195 			break;
1196 		case 'u':
1197 			userid = optarg;
1198 			break;
1199 		case 'c':
1200 			gecos = pw_checkname(optarg, 1);
1201 			break;
1202 		case 'd':
1203 			homedir = optarg;
1204 			break;
1205 		case 'e':
1206 			if (genconf)
1207 			    cmdcnf->expire_days = validate_expire(optarg, ch);
1208 			else
1209 			    cmdcnf->expire_days = parse_date(now, optarg);
1210 			break;
1211 		case 'p':
1212 			if (genconf)
1213 			    cmdcnf->password_days = validate_expire(optarg, ch);
1214 			else
1215 			    cmdcnf->password_days = parse_date(now, optarg);
1216 			break;
1217 		case 'g':
1218 			validate_grname(cmdcnf, optarg);
1219 			grname = optarg;
1220 			break;
1221 		case 'G':
1222 			split_groups(&cmdcnf->groups, optarg);
1223 			break;
1224 		case 'm':
1225 			createhome = true;
1226 			break;
1227 		case 'M':
1228 			cmdcnf->homemode = validate_mode(optarg);
1229 			break;
1230 		case 'k':
1231 			walk = skel = optarg;
1232 			if (*walk == '/')
1233 				walk++;
1234 			if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1235 				errx(EX_OSFILE, "skeleton `%s' does not "
1236 				    "exists", skel);
1237 			if (!S_ISDIR(st.st_mode))
1238 				errx(EX_OSFILE, "skeleton `%s' is not a "
1239 				    "directory", skel);
1240 			cmdcnf->dotdir = skel;
1241 			break;
1242 		case 's':
1243 			cmdcnf->shell_default = optarg;
1244 			break;
1245 		case 'o':
1246 			conf.checkduplicate = false;
1247 			break;
1248 		case 'L':
1249 			cmdcnf->default_class = pw_checkname(optarg, 0);
1250 			break;
1251 		case 'i':
1252 			groupid = optarg;
1253 			break;
1254 		case 'w':
1255 			default_passwd = optarg;
1256 			break;
1257 		case 'H':
1258 			if (fd != -1)
1259 				errx(EX_USAGE, "'-h' and '-H' are mutually "
1260 				    "exclusive options");
1261 			fd = pw_checkfd(optarg);
1262 			precrypted = true;
1263 			if (fd == '-')
1264 				errx(EX_USAGE, "-H expects a file descriptor");
1265 			break;
1266 		case 'h':
1267 			if (fd != -1)
1268 				errx(EX_USAGE, "'-h' and '-H' are mutually "
1269 				    "exclusive options");
1270 			fd = pw_checkfd(optarg);
1271 			break;
1272 		case 'D':
1273 			genconf = true;
1274 			break;
1275 		case 'b':
1276 			cmdcnf->home = optarg;
1277 			break;
1278 		case 'N':
1279 			dryrun = true;
1280 			break;
1281 		case 'P':
1282 			pretty = true;
1283 			break;
1284 		case 'y':
1285 			cmdcnf->nispasswd = optarg;
1286 			break;
1287 		case 'Y':
1288 			nis = true;
1289 			break;
1290 		}
1291 	}
1292 
1293 	if (geteuid() != 0 && ! dryrun)
1294 		errx(EX_NOPERM, "you must be root");
1295 
1296 	if (quiet)
1297 		freopen(_PATH_DEVNULL, "w", stderr);
1298 
1299 	cnf = get_userconfig(cfg);
1300 
1301 	mix_config(cmdcnf, cnf);
1302 	if (default_passwd)
1303 		cmdcnf->default_password = passwd_val(default_passwd,
1304 		    cnf->default_password);
1305 	if (genconf) {
1306 		if (name != NULL)
1307 			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
1308 		if (userid != NULL) {
1309 			if ((p = strtok(userid, ", \t")) != NULL)
1310 				cmdcnf->min_uid = pw_checkid(p, UID_MAX);
1311 			if (cmdcnf->min_uid == 0)
1312 				cmdcnf->min_uid = 1000;
1313 			if ((p = strtok(NULL, " ,\t")) != NULL)
1314 				cmdcnf->max_uid = pw_checkid(p, UID_MAX);
1315 			if (cmdcnf->max_uid == 0)
1316 				cmdcnf->max_uid = 32000;
1317 		}
1318 		if (groupid != NULL) {
1319 			if ((p = strtok(groupid, ", \t")) != NULL)
1320 				cmdcnf->min_gid = pw_checkid(p, GID_MAX);
1321 			if (cmdcnf->min_gid == 0)
1322 				cmdcnf->min_gid = 1000;
1323 			if ((p = strtok(NULL, " ,\t")) != NULL)
1324 				cmdcnf->max_gid = pw_checkid(p, GID_MAX);
1325 			if (cmdcnf->max_gid == 0)
1326 				cmdcnf->max_gid = 32000;
1327 		}
1328 		if (write_userconfig(cmdcnf, cfg))
1329 			return (EXIT_SUCCESS);
1330 		err(EX_IOERR, "config update");
1331 	}
1332 
1333 	if (userid)
1334 		id = pw_checkid(userid, UID_MAX);
1335 	if (id < 0 && name == NULL)
1336 		errx(EX_DATAERR, "user name or id required");
1337 
1338 	if (name == NULL)
1339 		errx(EX_DATAERR, "login name required");
1340 
1341 	if (GETPWNAM(name) != NULL)
1342 		errx(EX_DATAERR, "login name `%s' already exists", name);
1343 
1344 	if (!grname)
1345 		grname = cmdcnf->default_group;
1346 
1347 	pwd = &fakeuser;
1348 	pwd->pw_name = name;
1349 	pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1350 	pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1351 	pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1352 	    (gid_t) pwd->pw_uid, dryrun);
1353 
1354 	/* cmdcnf->password_days and cmdcnf->expire_days hold unixtime here */
1355 	if (cmdcnf->password_days > 0)
1356 		pwd->pw_change = cmdcnf->password_days;
1357 	if (cmdcnf->expire_days > 0)
1358 		pwd->pw_expire = cmdcnf->expire_days;
1359 
1360 	pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1361 	pwd->pw_shell = pw_shellpolicy(cmdcnf);
1362 	lc = login_getpwclass(pwd);
1363 	if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1364 		warn("setting crypt(3) format");
1365 	login_close(lc);
1366 	pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name, dryrun);
1367 	if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1368 		warnx("WARNING: new account `%s' has a uid of 0 "
1369 		    "(superuser access!)", pwd->pw_name);
1370 	if (gecos)
1371 		pwd->pw_gecos = gecos;
1372 
1373 	if (fd != -1)
1374 		pw_set_passwd(pwd, fd, precrypted, false);
1375 
1376 	if (dryrun)
1377 		return (print_user(pwd, pretty, false));
1378 
1379 	if ((rc = addpwent(pwd)) != 0) {
1380 		if (rc == -1)
1381 			errx(EX_IOERR, "user '%s' already exists",
1382 			    pwd->pw_name);
1383 		else if (rc != 0)
1384 			err(EX_IOERR, "passwd file update");
1385 	}
1386 	if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1387 		printf("%s\n", cmdcnf->nispasswd);
1388 		rc = addnispwent(cmdcnf->nispasswd, pwd);
1389 		if (rc == -1)
1390 			warnx("User '%s' already exists in NIS passwd",
1391 			    pwd->pw_name);
1392 		else if (rc != 0)
1393 			warn("NIS passwd update");
1394 		/* NOTE: we treat NIS-only update errors as non-fatal */
1395 	}
1396 
1397 	if (cmdcnf->groups != NULL) {
1398 		for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1399 			grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1400 			grp = gr_add(grp, pwd->pw_name);
1401 			/*
1402 			 * grp can only be NULL in 2 cases:
1403 			 * - the new member is already a member
1404 			 * - a problem with memory occurs
1405 			 * in both cases we want to skip now.
1406 			 */
1407 			if (grp == NULL)
1408 				continue;
1409 			chggrent(grp->gr_name, grp);
1410 			free(grp);
1411 		}
1412 	}
1413 
1414 	pwd = GETPWNAM(name);
1415 	if (pwd == NULL)
1416 		errx(EX_NOUSER, "user '%s' disappeared during update", name);
1417 
1418 	grp = GETGRGID(pwd->pw_gid);
1419 	pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1420 	       pwd->pw_name, (uintmax_t)pwd->pw_uid,
1421 	    grp ? grp->gr_name : "unknown",
1422 	       (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1423 	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1424 
1425 	/*
1426 	 * let's touch and chown the user's mail file. This is not
1427 	 * strictly necessary under BSD with a 0755 maildir but it also
1428 	 * doesn't hurt anything to create the empty mailfile
1429 	 */
1430 	if (PWALTDIR() != PWF_ALT) {
1431 		snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1432 		    pwd->pw_name);
1433 		/* Preserve contents & mtime */
1434 		close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1435 		fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1436 		    AT_SYMLINK_NOFOLLOW);
1437 	}
1438 
1439 	/*
1440 	 * Let's create and populate the user's home directory. Note
1441 	 * that this also `works' for editing users if -m is used, but
1442 	 * existing files will *not* be overwritten.
1443 	 */
1444 	if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1445 	    *pwd->pw_dir == '/' && pwd->pw_dir[1])
1446 		create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1447 		    cmdcnf->homemode, false);
1448 
1449 	if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1450 	    (fp = fopen(cnf->newmail, "r")) != NULL) {
1451 		if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1452 			warn("sendmail");
1453 		else {
1454 			fprintf(pfp, "From: root\n" "To: %s\n"
1455 			    "Subject: Welcome!\n\n", pwd->pw_name);
1456 			while (fgets(line, sizeof(line), fp) != NULL) {
1457 				/* Do substitutions? */
1458 				fputs(line, pfp);
1459 			}
1460 			pclose(pfp);
1461 			pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1462 			    pwd->pw_name, (uintmax_t)pwd->pw_uid);
1463 		}
1464 		fclose(fp);
1465 	}
1466 
1467 	if (nis && nis_update() == 0)
1468 		pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1469 
1470 	return (EXIT_SUCCESS);
1471 }
1472 
1473 int
1474 pw_user_mod(int argc, char **argv, char *arg1)
1475 {
1476 	struct userconf *cnf;
1477 	struct passwd *pwd;
1478 	struct group *grp;
1479 	StringList *groups = NULL;
1480 	char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1481 	const char *cfg = NULL;
1482 	char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1483 	char *passwd, *class, *nispasswd;
1484 	login_cap_t *lc;
1485 	struct stat st;
1486 	intmax_t id = -1;
1487 	int ch, fd = -1;
1488 	size_t i, j;
1489 	bool quiet, createhome, pretty, dryrun, nis, edited;
1490 	bool precrypted;
1491 	mode_t homemode = 0;
1492 	time_t expire_time, password_time, now;
1493 
1494 	expire_time = password_time = -1;
1495 	gecos = homedir = grname = name = newname = skel = shell =NULL;
1496 	passwd = NULL;
1497 	class = nispasswd = NULL;
1498 	quiet = createhome = pretty = dryrun = nis = precrypted = false;
1499 	edited = false;
1500 	now = time(NULL);
1501 
1502 	if (arg1 != NULL) {
1503 		if (arg1[strspn(arg1, "0123456789")] == '\0')
1504 			id = pw_checkid(arg1, UID_MAX);
1505 		else
1506 			name = arg1;
1507 	}
1508 
1509 	while ((ch = getopt(argc, argv, args)) != -1) {
1510 		switch (ch) {
1511 		case 'C':
1512 			cfg = optarg;
1513 			break;
1514 		case 'q':
1515 			quiet = true;
1516 			break;
1517 		case 'n':
1518 			name = optarg;
1519 			break;
1520 		case 'u':
1521 			id = pw_checkid(optarg, UID_MAX);
1522 			break;
1523 		case 'c':
1524 			gecos = pw_checkname(optarg, 1);
1525 			break;
1526 		case 'd':
1527 			homedir = optarg;
1528 			break;
1529 		case 'e':
1530 			expire_time = parse_date(now, optarg);
1531 			break;
1532 		case 'p':
1533 			password_time = parse_date(now, optarg);
1534 			break;
1535 		case 'g':
1536 			group_from_name_or_id(optarg);
1537 			grname = optarg;
1538 			break;
1539 		case 'G':
1540 			split_groups(&groups, optarg);
1541 			break;
1542 		case 'm':
1543 			createhome = true;
1544 			break;
1545 		case 'M':
1546 			homemode = validate_mode(optarg);
1547 			break;
1548 		case 'l':
1549 			newname = optarg;
1550 			break;
1551 		case 'k':
1552 			walk = skel = optarg;
1553 			if (*walk == '/')
1554 				walk++;
1555 			if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1556 				errx(EX_OSFILE, "skeleton `%s' does not "
1557 				    "exists", skel);
1558 			if (!S_ISDIR(st.st_mode))
1559 				errx(EX_OSFILE, "skeleton `%s' is not a "
1560 				    "directory", skel);
1561 			break;
1562 		case 's':
1563 			shell = optarg;
1564 			break;
1565 		case 'w':
1566 			passwd = optarg;
1567 			break;
1568 		case 'L':
1569 			class = pw_checkname(optarg, 0);
1570 			break;
1571 		case 'H':
1572 			if (fd != -1)
1573 				errx(EX_USAGE, "'-h' and '-H' are mutually "
1574 				    "exclusive options");
1575 			fd = pw_checkfd(optarg);
1576 			precrypted = true;
1577 			if (fd == '-')
1578 				errx(EX_USAGE, "-H expects a file descriptor");
1579 			break;
1580 		case 'h':
1581 			if (fd != -1)
1582 				errx(EX_USAGE, "'-h' and '-H' are mutually "
1583 				    "exclusive options");
1584 			fd = pw_checkfd(optarg);
1585 			break;
1586 		case 'N':
1587 			dryrun = true;
1588 			break;
1589 		case 'P':
1590 			pretty = true;
1591 			break;
1592 		case 'y':
1593 			nispasswd = optarg;
1594 			break;
1595 		case 'Y':
1596 			nis = true;
1597 			break;
1598 		}
1599 	}
1600 
1601 	if (geteuid() != 0 && ! dryrun)
1602 		errx(EX_NOPERM, "you must be root");
1603 
1604 	if (quiet)
1605 		freopen(_PATH_DEVNULL, "w", stderr);
1606 
1607 	cnf = get_userconfig(cfg);
1608 
1609 	if (id < 0 && name == NULL)
1610 		errx(EX_DATAERR, "username or id required");
1611 
1612 	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1613 	if (pwd == NULL) {
1614 		if (name == NULL)
1615 			errx(EX_NOUSER, "no such uid `%ju'",
1616 			    (uintmax_t) id);
1617 		errx(EX_NOUSER, "no such user `%s'", name);
1618 	}
1619 
1620 	if (name == NULL)
1621 		name = pwd->pw_name;
1622 
1623 	if (nis && nispasswd == NULL)
1624 		nispasswd = cnf->nispasswd;
1625 
1626 	if (PWF._altdir == PWF_REGULAR &&
1627 	    ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
1628 		if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
1629 			if (!nis && nispasswd && *nispasswd != '/')
1630 				errx(EX_NOUSER, "Cannot modify NIS user `%s'",
1631 				    name);
1632 		} else {
1633 			errx(EX_NOUSER, "Cannot modify non local user `%s'",
1634 			    name);
1635 		}
1636 	}
1637 
1638 	if (newname) {
1639 		if (strcmp(pwd->pw_name, "root") == 0)
1640 			errx(EX_DATAERR, "can't rename `root' account");
1641 		if (strcmp(pwd->pw_name, newname) != 0) {
1642 			pwd->pw_name = pw_checkname(newname, 0);
1643 			edited = true;
1644 		}
1645 	}
1646 
1647 	if (id >= 0 && pwd->pw_uid != id) {
1648 		pwd->pw_uid = id;
1649 		edited = true;
1650 		if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
1651 			errx(EX_DATAERR, "can't change uid of `root' account");
1652 		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1653 			warnx("WARNING: account `%s' will have a uid of 0 "
1654 			    "(superuser access!)", pwd->pw_name);
1655 	}
1656 
1657 	if (grname && pwd->pw_uid != 0) {
1658 		grp = GETGRNAM(grname);
1659 		if (grp == NULL)
1660 			grp = GETGRGID(pw_checkid(grname, GID_MAX));
1661 		if (grp->gr_gid != pwd->pw_gid) {
1662 			pwd->pw_gid = grp->gr_gid;
1663 			edited = true;
1664 		}
1665 	}
1666 
1667 
1668 	if (password_time >= 0 && pwd->pw_change != password_time) {
1669 		pwd->pw_change = password_time;
1670 		edited = true;
1671 	}
1672 
1673 	if (expire_time >= 0 && pwd->pw_expire != expire_time) {
1674 		pwd->pw_expire = expire_time;
1675 		edited = true;
1676 	}
1677 
1678 	if (shell) {
1679 		shell = shell_path(cnf->shelldir, cnf->shells, shell);
1680 		if (shell == NULL)
1681 			shell = "";
1682 		if (strcmp(shell, pwd->pw_shell) != 0) {
1683 			pwd->pw_shell = shell;
1684 			edited = true;
1685 		}
1686 	}
1687 
1688 	if (class && strcmp(pwd->pw_class, class) != 0) {
1689 		pwd->pw_class = class;
1690 		edited = true;
1691 	}
1692 
1693 	if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1694 		pwd->pw_dir = homedir;
1695 		edited = true;
1696 		if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1697 			if (!createhome)
1698 				warnx("WARNING: home `%s' does not exist",
1699 				    pwd->pw_dir);
1700 		} else if (!S_ISDIR(st.st_mode)) {
1701 			warnx("WARNING: home `%s' is not a directory",
1702 			    pwd->pw_dir);
1703 		}
1704 	}
1705 
1706 	if (passwd && conf.fd == -1) {
1707 		lc = login_getpwclass(pwd);
1708 		if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1709 			warn("setting crypt(3) format");
1710 		login_close(lc);
1711 		cnf->default_password = passwd_val(passwd,
1712 		    cnf->default_password);
1713 		pwd->pw_passwd = pw_password(cnf, pwd->pw_name, dryrun);
1714 		edited = true;
1715 	}
1716 
1717 	if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1718 		pwd->pw_gecos = gecos;
1719 		edited = true;
1720 	}
1721 
1722 	if (fd != -1)
1723 		edited = pw_set_passwd(pwd, fd, precrypted, true);
1724 
1725 	if (dryrun)
1726 		return (print_user(pwd, pretty, false));
1727 
1728 	if (edited) /* Only updated this if required */
1729 		perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1730 	/* Now perform the needed changes concern groups */
1731 	if (groups != NULL) {
1732 		/* Delete User from groups using old name */
1733 		SETGRENT();
1734 		while ((grp = GETGRENT()) != NULL) {
1735 			if (grp->gr_mem == NULL)
1736 				continue;
1737 			for (i = 0; grp->gr_mem[i] != NULL; i++) {
1738 				if (strcmp(grp->gr_mem[i] , name) != 0)
1739 					continue;
1740 				for (j = i; grp->gr_mem[j] != NULL ; j++)
1741 					grp->gr_mem[j] = grp->gr_mem[j+1];
1742 				chggrent(grp->gr_name, grp);
1743 				break;
1744 			}
1745 		}
1746 		ENDGRENT();
1747 		/* Add the user to the needed groups */
1748 		for (i = 0; i < groups->sl_cur; i++) {
1749 			grp = GETGRNAM(groups->sl_str[i]);
1750 			grp = gr_add(grp, pwd->pw_name);
1751 			if (grp == NULL)
1752 				continue;
1753 			chggrent(grp->gr_name, grp);
1754 			free(grp);
1755 		}
1756 	}
1757 	/* In case of rename we need to walk over the different groups */
1758 	if (newname) {
1759 		SETGRENT();
1760 		while ((grp = GETGRENT()) != NULL) {
1761 			if (grp->gr_mem == NULL)
1762 				continue;
1763 			for (i = 0; grp->gr_mem[i] != NULL; i++) {
1764 				if (strcmp(grp->gr_mem[i], name) != 0)
1765 					continue;
1766 				grp->gr_mem[i] = newname;
1767 				chggrent(grp->gr_name, grp);
1768 				break;
1769 			}
1770 		}
1771 	}
1772 
1773 	/* go get a current version of pwd */
1774 	if (newname)
1775 		name = newname;
1776 	pwd = GETPWNAM(name);
1777 	if (pwd == NULL)
1778 		errx(EX_NOUSER, "user '%s' disappeared during update", name);
1779 	grp = GETGRGID(pwd->pw_gid);
1780 	pw_log(cnf, M_UPDATE, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1781 	    pwd->pw_name, (uintmax_t)pwd->pw_uid,
1782 	    grp ? grp->gr_name : "unknown",
1783 	    (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1784 	    pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1785 
1786 	/*
1787 	 * Let's create and populate the user's home directory. Note
1788 	 * that this also `works' for editing users if -m is used, but
1789 	 * existing files will *not* be overwritten.
1790 	 */
1791 	if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1792 	    *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1793 		if (!skel)
1794 			skel = cnf->dotdir;
1795 		if (homemode == 0)
1796 			homemode = cnf->homemode;
1797 		create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1798 	}
1799 
1800 	if (nis && nis_update() == 0)
1801 		pw_log(cnf, M_UPDATE, W_USER, "NIS maps updated");
1802 
1803 	return (EXIT_SUCCESS);
1804 }
1805