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