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