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