xref: /freebsd/usr.sbin/pw/pw_user.c (revision 3fe401a500cdfc73d8c066da3c577c4b9f0aa953)
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 <ctype.h>
34 #include <err.h>
35 #include <fcntl.h>
36 #include <sys/param.h>
37 #include <dirent.h>
38 #include <paths.h>
39 #include <termios.h>
40 #include <sys/types.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <login_cap.h>
44 #include <pwd.h>
45 #include <grp.h>
46 #include <libutil.h>
47 #include "pw.h"
48 #include "bitmap.h"
49 
50 #define LOGNAMESIZE (MAXLOGNAME-1)
51 
52 static		char locked_str[] = "*LOCKED*";
53 
54 static int	pw_userdel(char *name, long id);
55 static int	print_user(struct passwd * pwd);
56 static uid_t    pw_uidpolicy(struct userconf * cnf, long id);
57 static uid_t    pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer);
58 static time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
59 static time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
60 static char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
61 static char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
62 static char    *pw_password(struct userconf * cnf, char const * user);
63 static char    *shell_path(char const * path, char *shells[], char *sh);
64 static void     rmat(uid_t uid);
65 static void     rmopie(char const * name);
66 
67 static void
68 create_and_populate_homedir(struct passwd *pwd)
69 {
70 	struct userconf *cnf = conf.userconf;
71 	const char *skeldir;
72 	int skelfd = -1;
73 
74 	skeldir = cnf->dotdir;
75 
76 	if (skeldir != NULL && *skeldir != '\0') {
77 		if (*skeldir == '/')
78 			skeldir++;
79 		skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
80 	}
81 
82 	copymkdir(conf.rootfd, pwd->pw_dir, skelfd, cnf->homemode, pwd->pw_uid,
83 	    pwd->pw_gid, 0);
84 	pw_log(cnf, M_ADD, W_USER, "%s(%u) home %s made", pwd->pw_name,
85 	    pwd->pw_uid, pwd->pw_dir);
86 }
87 
88 static int
89 set_passwd(struct passwd *pwd, bool update)
90 {
91 	int		 b, istty;
92 	struct termios	 t, n;
93 	login_cap_t	*lc;
94 	char		line[_PASSWORD_LEN+1];
95 	char		*p;
96 
97 	if (conf.fd == '-') {
98 		if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
99 			pwd->pw_passwd = "*";	/* No access */
100 			return (1);
101 		}
102 		return (0);
103 	}
104 
105 	if ((istty = isatty(conf.fd))) {
106 		if (tcgetattr(conf.fd, &t) == -1)
107 			istty = 0;
108 		else {
109 			n = t;
110 			n.c_lflag &= ~(ECHO);
111 			tcsetattr(conf.fd, TCSANOW, &n);
112 			printf("%s%spassword for user %s:",
113 			    update ? "new " : "",
114 			    conf.precrypted ? "encrypted " : "",
115 			    pwd->pw_name);
116 			fflush(stdout);
117 		}
118 	}
119 	b = read(conf.fd, line, sizeof(line) - 1);
120 	if (istty) {	/* Restore state */
121 		tcsetattr(conf.fd, TCSANOW, &t);
122 		fputc('\n', stdout);
123 		fflush(stdout);
124 	}
125 
126 	if (b < 0)
127 		err(EX_IOERR, "-%c file descriptor",
128 		    conf.precrypted ? 'H' : 'h');
129 	line[b] = '\0';
130 	if ((p = strpbrk(line, "\r\n")) != NULL)
131 		*p = '\0';
132 	if (!*line)
133 		errx(EX_DATAERR, "empty password read on file descriptor %d",
134 		    conf.fd);
135 	if (conf.precrypted) {
136 		if (strchr(line, ':') != NULL)
137 			errx(EX_DATAERR, "bad encrypted password");
138 		pwd->pw_passwd = line;
139 	} else {
140 		lc = login_getpwclass(pwd);
141 		if (lc == NULL ||
142 				login_setcryptfmt(lc, "sha512", NULL) == NULL)
143 			warn("setting crypt(3) format");
144 		login_close(lc);
145 		pwd->pw_passwd = pw_pwcrypt(line);
146 	}
147 	return (1);
148 }
149 
150 int
151 pw_usernext(struct userconf *cnf, bool quiet)
152 {
153 	uid_t next = pw_uidpolicy(cnf, -1);
154 
155 	if (quiet)
156 		return (next);
157 
158 	printf("%u:", next);
159 	pw_groupnext(cnf, quiet);
160 
161 	return (EXIT_SUCCESS);
162 }
163 
164 static int
165 pw_usershow(char *name, long id, struct passwd *fakeuser)
166 {
167 	struct passwd *pwd = NULL;
168 
169 	if (id < 0 && name == NULL && !conf.all)
170 		errx(EX_DATAERR, "username or id or '-a' required");
171 
172 	if (conf.all) {
173 		SETPWENT();
174 		while ((pwd = GETPWENT()) != NULL)
175 			print_user(pwd);
176 		ENDPWENT();
177 		return (EXIT_SUCCESS);
178 	}
179 
180 	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
181 	if (pwd == NULL) {
182 		if (conf.force) {
183 			pwd = fakeuser;
184 		} else {
185 			if (name == NULL)
186 				errx(EX_NOUSER, "no such uid `%ld'", id);
187 			errx(EX_NOUSER, "no such user `%s'", name);
188 		}
189 	}
190 
191 	return (print_user(pwd));
192 }
193 
194 static void
195 perform_chgpwent(const char *name, struct passwd *pwd)
196 {
197 	int rc;
198 
199 	rc = chgpwent(name, pwd);
200 	if (rc == -1)
201 		errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
202 	else if (rc != 0)
203 		err(EX_IOERR, "passwd file update");
204 
205 	if (conf.userconf->nispasswd && *conf.userconf->nispasswd == '/') {
206 		rc = chgnispwent(conf.userconf->nispasswd, name, pwd);
207 		if (rc == -1)
208 			warn("User '%s' not found in NIS passwd", pwd->pw_name);
209 		else if (rc != 0)
210 			warn("NIS passwd update");
211 		/* NOTE: NIS-only update errors are not fatal */
212 	}
213 }
214 
215 /*
216  * The M_LOCK and M_UNLOCK functions simply add or remove
217  * a "*LOCKED*" prefix from in front of the password to
218  * prevent it decoding correctly, and therefore prevents
219  * access. Of course, this only prevents access via
220  * password authentication (not ssh, kerberos or any
221  * other method that does not use the UNIX password) but
222  * that is a known limitation.
223  */
224 static int
225 pw_userlock(char *name, long id, int mode)
226 {
227 	struct passwd *pwd = NULL;
228 	char *passtmp = NULL;
229 	bool locked = false;
230 
231 	if (id < 0 && name == NULL)
232 		errx(EX_DATAERR, "username or id required");
233 
234 	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
235 	if (pwd == NULL) {
236 		if (name == NULL)
237 			errx(EX_NOUSER, "no such uid `%ld'", id);
238 		errx(EX_NOUSER, "no such user `%s'", name);
239 	}
240 
241 	if (name == NULL)
242 		name = pwd->pw_name;
243 
244 	if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
245 		locked = true;
246 	if (mode == M_LOCK && locked)
247 		errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
248 	if (mode == M_UNLOCK && !locked)
249 		errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
250 
251 	if (mode == M_LOCK) {
252 		asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
253 		if (passtmp == NULL)	/* disaster */
254 			errx(EX_UNAVAILABLE, "out of memory");
255 		pwd->pw_passwd = passtmp;
256 	} else {
257 		pwd->pw_passwd += sizeof(locked_str)-1;
258 	}
259 
260 	perform_chgpwent(name, pwd);
261 	free(passtmp);
262 
263 	return (EXIT_SUCCESS);
264 }
265 
266 /*-
267  * -C config      configuration file
268  * -q             quiet operation
269  * -n name        login name
270  * -u uid         user id
271  * -c comment     user name/comment
272  * -d directory   home directory
273  * -e date        account expiry date
274  * -p date        password expiry date
275  * -g grp         primary group
276  * -G grp1,grp2   additional groups
277  * -m [ -k dir ]  create and set up home
278  * -s shell       name of login shell
279  * -o             duplicate uid ok
280  * -L class       user class
281  * -l name        new login name
282  * -h fd          password filehandle
283  * -H fd          encrypted password filehandle
284  * -F             force print or add
285  *   Setting defaults:
286  * -D             set user defaults
287  * -b dir         default home root dir
288  * -e period      default expiry period
289  * -p period      default password change period
290  * -g group       default group
291  * -G             grp1,grp2.. default additional groups
292  * -L class       default login class
293  * -k dir         default home skeleton
294  * -s shell       default shell
295  * -w method      default password method
296  */
297 
298 int
299 pw_user(int mode, char *name, long id, struct cargs * args)
300 {
301 	int	        rc, edited = 0;
302 	char           *p = NULL;
303 	struct carg    *arg;
304 	struct passwd  *pwd = NULL;
305 	struct group   *grp;
306 	struct stat     st;
307 	struct userconf	*cnf;
308 	char            line[_PASSWORD_LEN+1];
309 	char		path[MAXPATHLEN];
310 	FILE	       *fp;
311 	char *dmode_c;
312 	void *set = NULL;
313 	int valid_type = _PWF_FILES;
314 
315 	static struct passwd fakeuser =
316 	{
317 		"nouser",
318 		"*",
319 		-1,
320 		-1,
321 		0,
322 		"",
323 		"User &",
324 		"/nonexistent",
325 		"/bin/sh",
326 		0
327 #if defined(__FreeBSD__)
328 		,0
329 #endif
330 	};
331 
332 	cnf = conf.userconf;
333 
334 	if (mode == M_NEXT)
335 		return (pw_usernext(cnf, conf.quiet));
336 
337 	if (mode == M_PRINT)
338 		return (pw_usershow(name, id, &fakeuser));
339 
340 	if (mode == M_DELETE)
341 		return (pw_userdel(name, id));
342 
343 	if (mode == M_LOCK || mode == M_UNLOCK)
344 		return (pw_userlock(name, id, mode));
345 
346 	/*
347 	 * We can do all of the common legwork here
348 	 */
349 
350 	if ((arg = getarg(args, 'b')) != NULL) {
351 		cnf->home = arg->val;
352 	}
353 
354 	if ((arg = getarg(args, 'M')) != NULL) {
355 		dmode_c = arg->val;
356 		if ((set = setmode(dmode_c)) == NULL)
357 			errx(EX_DATAERR, "invalid directory creation mode '%s'",
358 			    dmode_c);
359 		cnf->homemode = getmode(set, _DEF_DIRMODE);
360 		free(set);
361 	}
362 
363 	/*
364 	 * If we'll need to use it or we're updating it,
365 	 * then create the base home directory if necessary
366 	 */
367 	if (arg != NULL || getarg(args, 'm') != NULL) {
368 		int	l = strlen(cnf->home);
369 
370 		if (l > 1 && cnf->home[l-1] == '/')	/* Shave off any trailing path delimiter */
371 			cnf->home[--l] = '\0';
372 
373 		if (l < 2 || *cnf->home != '/')		/* Check for absolute path name */
374 			errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
375 
376 		if (stat(cnf->home, &st) == -1) {
377 			char	dbuf[MAXPATHLEN];
378 
379 			/*
380 			 * This is a kludge especially for Joerg :)
381 			 * If the home directory would be created in the root partition, then
382 			 * we really create it under /usr which is likely to have more space.
383 			 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
384 			 */
385 			if (strchr(cnf->home+1, '/') == NULL) {
386 				snprintf(dbuf, MAXPATHLEN, "/usr%s", cnf->home);
387 				if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
388 					chown(dbuf, 0, 0);
389 					/*
390 					 * Skip first "/" and create symlink:
391 					 * /home -> usr/home
392 					 */
393 					symlink(dbuf+1, cnf->home);
394 				}
395 				/* If this falls, fall back to old method */
396 			}
397 			strlcpy(dbuf, cnf->home, sizeof(dbuf));
398 			p = dbuf;
399 			if (stat(dbuf, &st) == -1) {
400 				while ((p = strchr(p + 1, '/')) != NULL) {
401 					*p = '\0';
402 					if (stat(dbuf, &st) == -1) {
403 						if (mkdir(dbuf, _DEF_DIRMODE) == -1)
404 							err(EX_OSFILE, "mkdir '%s'", dbuf);
405 						chown(dbuf, 0, 0);
406 					} else if (!S_ISDIR(st.st_mode))
407 						errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
408 					*p = '/';
409 				}
410 			}
411 			if (stat(dbuf, &st) == -1) {
412 				if (mkdir(dbuf, _DEF_DIRMODE) == -1)
413 					err(EX_OSFILE, "mkdir '%s'", dbuf);
414 				chown(dbuf, 0, 0);
415 			}
416 		} else if (!S_ISDIR(st.st_mode))
417 			errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
418 	}
419 
420 	if ((arg = getarg(args, 'e')) != NULL)
421 		cnf->expire_days = atoi(arg->val);
422 
423 	if ((arg = getarg(args, 'y')) != NULL)
424 		cnf->nispasswd = arg->val;
425 
426 	if ((arg = getarg(args, 'p')) != NULL && arg->val)
427 		cnf->password_days = atoi(arg->val);
428 
429 	if ((arg = getarg(args, 'g')) != NULL) {
430 		if (!*(p = arg->val))	/* Handle empty group list specially */
431 			cnf->default_group = "";
432 		else {
433 			if ((grp = GETGRNAM(p)) == NULL) {
434 				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
435 					errx(EX_NOUSER, "group `%s' does not exist", p);
436 			}
437 			cnf->default_group = newstr(grp->gr_name);
438 		}
439 	}
440 	if ((arg = getarg(args, 'L')) != NULL)
441 		cnf->default_class = pw_checkname(arg->val, 0);
442 
443 	if ((arg = getarg(args, 'G')) != NULL && arg->val) {
444 		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
445 			if ((grp = GETGRNAM(p)) == NULL) {
446 				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
447 					errx(EX_NOUSER, "group `%s' does not exist", p);
448 			}
449 			sl_add(cnf->groups, newstr(grp->gr_name));
450 		}
451 	}
452 
453 	if ((arg = getarg(args, 'k')) != NULL) {
454 		char *tmp = cnf->dotdir = arg->val;
455 		if (*tmp == '/')
456 			tmp++;
457 		if ((fstatat(conf.rootfd, tmp, &st, 0) == -1) ||
458 		    !S_ISDIR(st.st_mode))
459 			errx(EX_OSFILE, "skeleton `%s' is not a directory or "
460 			    "does not exist", cnf->dotdir);
461 	}
462 
463 	if ((arg = getarg(args, 's')) != NULL)
464 		cnf->shell_default = arg->val;
465 
466 	if ((arg = getarg(args, 'w')) != NULL)
467 		cnf->default_password = boolean_val(arg->val, cnf->default_password);
468 	if (mode == M_ADD && getarg(args, 'D')) {
469 		if (name != NULL)
470 			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
471 		if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
472 			if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
473 				cnf->min_uid = 1000;
474 			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
475 				cnf->max_uid = 32000;
476 		}
477 		if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
478 			if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
479 				cnf->min_gid = 1000;
480 			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
481 				cnf->max_gid = 32000;
482 		}
483 
484 		if (write_userconfig(conf.config))
485 			return (EXIT_SUCCESS);
486 		err(EX_IOERR, "config udpate");
487 	}
488 
489 	if (name != NULL)
490 		pwd = GETPWNAM(pw_checkname(name, 0));
491 
492 	if (id < 0 && name == NULL)
493 		errx(EX_DATAERR, "user name or id required");
494 
495 	/*
496 	 * Update require that the user exists
497 	 */
498 	if (mode == M_UPDATE) {
499 
500 		if (name == NULL && pwd == NULL)	/* Try harder */
501 			pwd = GETPWUID(id);
502 
503 		if (pwd == NULL) {
504 			if (name == NULL)
505 				errx(EX_NOUSER, "no such uid `%ld'", id);
506 			errx(EX_NOUSER, "no such user `%s'", name);
507 		}
508 
509 		if (conf.userconf->nispasswd && *conf.userconf->nispasswd == '/')
510 			valid_type = _PWF_NIS;
511 
512 		if (PWF._altdir == PWF_REGULAR &&
513 		    ((pwd->pw_fields & _PWF_SOURCE) != valid_type))
514 			errx(EX_NOUSER, "no such %s user `%s'",
515 			    valid_type == _PWF_FILES ? "local" : "NIS"  , name);
516 
517 		if (name == NULL)
518 			name = pwd->pw_name;
519 
520 		/*
521 		 * The rest is edit code
522 		 */
523 		if (conf.newname != NULL) {
524 			if (strcmp(pwd->pw_name, "root") == 0)
525 				errx(EX_DATAERR, "can't rename `root' account");
526 			pwd->pw_name = pw_checkname(conf.newname, 0);
527 			edited = 1;
528 		}
529 
530 		if (id > 0 && isdigit((unsigned char)*arg->val)) {
531 			pwd->pw_uid = (uid_t)id;
532 			edited = 1;
533 			if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
534 				errx(EX_DATAERR, "can't change uid of `root' account");
535 			if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
536 				warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
537 		}
538 
539 		if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {	/* Already checked this */
540 			gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
541 			if (newgid != pwd->pw_gid) {
542 				edited = 1;
543 				pwd->pw_gid = newgid;
544 			}
545 		}
546 
547 		if ((arg = getarg(args, 'p')) != NULL) {
548 			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
549 				if (pwd->pw_change != 0) {
550 					pwd->pw_change = 0;
551 					edited = 1;
552 				}
553 			}
554 			else {
555 				time_t          now = time(NULL);
556 				time_t          expire = parse_date(now, arg->val);
557 
558 				if (pwd->pw_change != expire) {
559 					pwd->pw_change = expire;
560 					edited = 1;
561 				}
562 			}
563 		}
564 
565 		if ((arg = getarg(args, 'e')) != NULL) {
566 			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
567 				if (pwd->pw_expire != 0) {
568 					pwd->pw_expire = 0;
569 					edited = 1;
570 				}
571 			}
572 			else {
573 				time_t          now = time(NULL);
574 				time_t          expire = parse_date(now, arg->val);
575 
576 				if (pwd->pw_expire != expire) {
577 					pwd->pw_expire = expire;
578 					edited = 1;
579 				}
580 			}
581 		}
582 
583 		if ((arg = getarg(args, 's')) != NULL) {
584 			char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
585 			if (shell == NULL)
586 				shell = "";
587 			if (strcmp(shell, pwd->pw_shell) != 0) {
588 				pwd->pw_shell = shell;
589 				edited = 1;
590 			}
591 		}
592 
593 		if (getarg(args, 'L')) {
594 			if (cnf->default_class == NULL)
595 				cnf->default_class = "";
596 			if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
597 				pwd->pw_class = cnf->default_class;
598 				edited = 1;
599 			}
600 		}
601 
602 		if ((arg  = getarg(args, 'd')) != NULL) {
603 			if (strcmp(pwd->pw_dir, arg->val))
604 				edited = 1;
605 			if (stat(pwd->pw_dir = arg->val, &st) == -1) {
606 				if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
607 				  warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
608 			} else if (!S_ISDIR(st.st_mode))
609 				warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
610 		}
611 
612 		if ((arg = getarg(args, 'w')) != NULL && conf.fd == -1) {
613 			login_cap_t *lc;
614 
615 			lc = login_getpwclass(pwd);
616 			if (lc == NULL ||
617 			    login_setcryptfmt(lc, "sha512", NULL) == NULL)
618 				warn("setting crypt(3) format");
619 			login_close(lc);
620 			pwd->pw_passwd = pw_password(cnf, pwd->pw_name);
621 			edited = 1;
622 		}
623 
624 	} else {
625 		login_cap_t *lc;
626 
627 		/*
628 		 * Add code
629 		 */
630 
631 		if (name == NULL)	/* Required */
632 			errx(EX_DATAERR, "login name required");
633 		else if ((pwd = GETPWNAM(name)) != NULL)	/* Exists */
634 			errx(EX_DATAERR, "login name `%s' already exists", name);
635 
636 		/*
637 		 * Now, set up defaults for a new user
638 		 */
639 		pwd = &fakeuser;
640 		pwd->pw_name = name;
641 		pwd->pw_class = cnf->default_class ? cnf->default_class : "";
642 		pwd->pw_uid = pw_uidpolicy(cnf, id);
643 		pwd->pw_gid = pw_gidpolicy(args, pwd->pw_name, (gid_t) pwd->pw_uid);
644 		pwd->pw_change = pw_pwdpolicy(cnf, args);
645 		pwd->pw_expire = pw_exppolicy(cnf, args);
646 		pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
647 		pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
648 		lc = login_getpwclass(pwd);
649 		if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
650 			warn("setting crypt(3) format");
651 		login_close(lc);
652 		pwd->pw_passwd = pw_password(cnf, pwd->pw_name);
653 		edited = 1;
654 
655 		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
656 			warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
657 	}
658 
659 	/*
660 	 * Shared add/edit code
661 	 */
662 	if (conf.gecos != NULL) {
663 		if (strcmp(pwd->pw_gecos, conf.gecos) != 0) {
664 			pwd->pw_gecos = conf.gecos;
665 			edited = 1;
666 		}
667 	}
668 
669 	if (conf.fd != -1)
670 		edited = set_passwd(pwd, mode == M_UPDATE);
671 
672 	/*
673 	 * Special case: -N only displays & exits
674 	 */
675 	if (conf.dryrun)
676 		return print_user(pwd);
677 
678 	if (mode == M_ADD) {
679 		edited = 1;	/* Always */
680 		rc = addpwent(pwd);
681 		if (rc == -1)
682 			errx(EX_IOERR, "user '%s' already exists",
683 			    pwd->pw_name);
684 		else if (rc != 0)
685 			err(EX_IOERR, "passwd file update");
686 		if (cnf->nispasswd && *cnf->nispasswd=='/') {
687 			rc = addnispwent(cnf->nispasswd, pwd);
688 			if (rc == -1)
689 				warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
690 			else if (rc != 0)
691 				warn("NIS passwd update");
692 			/* NOTE: we treat NIS-only update errors as non-fatal */
693 		}
694 	} else if (mode == M_UPDATE && edited) /* Only updated this if required */
695 		perform_chgpwent(name, pwd);
696 
697 	/*
698 	 * Ok, user is created or changed - now edit group file
699 	 */
700 
701 	if (mode == M_ADD || getarg(args, 'G') != NULL) {
702 		int j;
703 		size_t i;
704 		/* First remove the user from all group */
705 		SETGRENT();
706 		while ((grp = GETGRENT()) != NULL) {
707 			char group[MAXLOGNAME];
708 			if (grp->gr_mem == NULL)
709 				continue;
710 			for (i = 0; grp->gr_mem[i] != NULL; i++) {
711 				if (strcmp(grp->gr_mem[i] , pwd->pw_name) != 0)
712 					continue;
713 				for (j = i; grp->gr_mem[j] != NULL ; j++)
714 					grp->gr_mem[j] = grp->gr_mem[j+1];
715 				strlcpy(group, grp->gr_name, MAXLOGNAME);
716 				chggrent(group, grp);
717 			}
718 		}
719 		ENDGRENT();
720 
721 		/* now add to group where needed */
722 		for (i = 0; i < cnf->groups->sl_cur; i++) {
723 			grp = GETGRNAM(cnf->groups->sl_str[i]);
724 			grp = gr_add(grp, pwd->pw_name);
725 			/*
726 			 * grp can only be NULL in 2 cases:
727 			 * - the new member is already a member
728 			 * - a problem with memory occurs
729 			 * in both cases we want to skip now.
730 			 */
731 			if (grp == NULL)
732 				continue;
733 			chggrent(grp->gr_name, grp);
734 			free(grp);
735 		}
736 	}
737 
738 
739 	/* go get a current version of pwd */
740 	pwd = GETPWNAM(name);
741 	if (pwd == NULL) {
742 		/* This will fail when we rename, so special case that */
743 		if (mode == M_UPDATE && conf.newname != NULL) {
744 			name = conf.newname;		/* update new name */
745 			pwd = GETPWNAM(name);	/* refetch renamed rec */
746 		}
747 	}
748 	if (pwd == NULL)	/* can't go on without this */
749 		errx(EX_NOUSER, "user '%s' disappeared during update", name);
750 
751 	grp = GETGRGID(pwd->pw_gid);
752 	pw_log(cnf, mode, W_USER, "%s(%u):%s(%u):%s:%s:%s",
753 	       pwd->pw_name, pwd->pw_uid,
754 	    grp ? grp->gr_name : "unknown", (grp ? grp->gr_gid : (uid_t)-1),
755 	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
756 
757 	/*
758 	 * If adding, let's touch and chown the user's mail file. This is not
759 	 * strictly necessary under BSD with a 0755 maildir but it also
760 	 * doesn't hurt anything to create the empty mailfile
761 	 */
762 	if (mode == M_ADD) {
763 		if (PWALTDIR() != PWF_ALT) {
764 			snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
765 			    pwd->pw_name);
766 			close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT,
767 			    0600));	/* Preserve contents & mtime */
768 			fchownat(conf.rootfd, path + 1, pwd->pw_uid,
769 			    pwd->pw_gid, AT_SYMLINK_NOFOLLOW);
770 		}
771 	}
772 
773 	/*
774 	 * Let's create and populate the user's home directory. Note
775 	 * that this also `works' for editing users if -m is used, but
776 	 * existing files will *not* be overwritten.
777 	 */
778 	if (PWALTDIR() != PWF_ALT && getarg(args, 'm') != NULL && pwd->pw_dir &&
779 	    *pwd->pw_dir == '/' && pwd->pw_dir[1])
780 		create_and_populate_homedir(pwd);
781 
782 	/*
783 	 * Finally, send mail to the new user as well, if we are asked to
784 	 */
785 	if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
786 		FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
787 
788 		if (pfp == NULL)
789 			warn("sendmail");
790 		else {
791 			fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
792 			while (fgets(line, sizeof(line), fp) != NULL) {
793 				/* Do substitutions? */
794 				fputs(line, pfp);
795 			}
796 			pclose(pfp);
797 			pw_log(cnf, mode, W_USER, "%s(%u) new user mail sent",
798 			    pwd->pw_name, pwd->pw_uid);
799 		}
800 		fclose(fp);
801 	}
802 
803 	return EXIT_SUCCESS;
804 }
805 
806 
807 static          uid_t
808 pw_uidpolicy(struct userconf * cnf, long id)
809 {
810 	struct passwd  *pwd;
811 	uid_t           uid = (uid_t) - 1;
812 
813 	/*
814 	 * Check the given uid, if any
815 	 */
816 	if (id >= 0) {
817 		uid = (uid_t) id;
818 
819 		if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
820 			errx(EX_DATAERR, "uid `%u' has already been allocated", pwd->pw_uid);
821 	} else {
822 		struct bitmap   bm;
823 
824 		/*
825 		 * We need to allocate the next available uid under one of
826 		 * two policies a) Grab the first unused uid b) Grab the
827 		 * highest possible unused uid
828 		 */
829 		if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
830 							 * claus^H^H^H^Hheck */
831 			cnf->min_uid = 1000;
832 			cnf->max_uid = 32000;
833 		}
834 		bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
835 
836 		/*
837 		 * Now, let's fill the bitmap from the password file
838 		 */
839 		SETPWENT();
840 		while ((pwd = GETPWENT()) != NULL)
841 			if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
842 				bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
843 		ENDPWENT();
844 
845 		/*
846 		 * Then apply the policy, with fallback to reuse if necessary
847 		 */
848 		if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
849 			uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
850 
851 		/*
852 		 * Another sanity check
853 		 */
854 		if (uid < cnf->min_uid || uid > cnf->max_uid)
855 			errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
856 		bm_dealloc(&bm);
857 	}
858 	return uid;
859 }
860 
861 
862 static          uid_t
863 pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer)
864 {
865 	struct group   *grp;
866 	gid_t           gid = (uid_t) - 1;
867 	struct carg    *a_gid = getarg(args, 'g');
868 	struct userconf	*cnf = conf.userconf;
869 
870 	/*
871 	 * If no arg given, see if default can help out
872 	 */
873 	if (a_gid == NULL && cnf->default_group && *cnf->default_group)
874 		a_gid = addarg(args, 'g', cnf->default_group);
875 
876 	/*
877 	 * Check the given gid, if any
878 	 */
879 	SETGRENT();
880 	if (a_gid != NULL) {
881 		if ((grp = GETGRNAM(a_gid->val)) == NULL) {
882 			gid = (gid_t) atol(a_gid->val);
883 			if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
884 				errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
885 		}
886 		gid = grp->gr_gid;
887 	} else if ((grp = GETGRNAM(nam)) != NULL &&
888 	    (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
889 		gid = grp->gr_gid;  /* Already created? Use it anyway... */
890 	} else {
891 		gid_t		grid = -1;
892 
893 		/*
894 		 * We need to auto-create a group with the user's name. We
895 		 * can send all the appropriate output to our sister routine
896 		 * bit first see if we can create a group with gid==uid so we
897 		 * can keep the user and group ids in sync. We purposely do
898 		 * NOT check the gid range if we can force the sync. If the
899 		 * user's name dups an existing group, then the group add
900 		 * function will happily handle that case for us and exit.
901 		 */
902 		if (GETGRGID(prefer) == NULL)
903 			grid = prefer;
904 		if (conf.dryrun) {
905 			gid = pw_groupnext(cnf, true);
906 		} else {
907 			pw_group(M_ADD, nam, grid, NULL);
908 			if ((grp = GETGRNAM(nam)) != NULL)
909 				gid = grp->gr_gid;
910 		}
911 	}
912 	ENDGRENT();
913 	return gid;
914 }
915 
916 
917 static          time_t
918 pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
919 {
920 	time_t          result = 0;
921 	time_t          now = time(NULL);
922 	struct carg    *arg = getarg(args, 'p');
923 
924 	if (arg != NULL) {
925 		if ((result = parse_date(now, arg->val)) == now)
926 			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
927 	} else if (cnf->password_days > 0)
928 		result = now + ((long) cnf->password_days * 86400L);
929 	return result;
930 }
931 
932 
933 static          time_t
934 pw_exppolicy(struct userconf * cnf, struct cargs * args)
935 {
936 	time_t          result = 0;
937 	time_t          now = time(NULL);
938 	struct carg    *arg = getarg(args, 'e');
939 
940 	if (arg != NULL) {
941 		if ((result = parse_date(now, arg->val)) == now)
942 			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
943 	} else if (cnf->expire_days > 0)
944 		result = now + ((long) cnf->expire_days * 86400L);
945 	return result;
946 }
947 
948 
949 static char    *
950 pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
951 {
952 	struct carg    *arg = getarg(args, 'd');
953 	static char     home[128];
954 
955 	if (arg)
956 		return (arg->val);
957 
958 	if (cnf->home == NULL || *cnf->home == '\0')
959 		errx(EX_CONFIG, "no base home directory set");
960 	snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
961 
962 	return (home);
963 }
964 
965 static char    *
966 shell_path(char const * path, char *shells[], char *sh)
967 {
968 	if (sh != NULL && (*sh == '/' || *sh == '\0'))
969 		return sh;	/* specified full path or forced none */
970 	else {
971 		char           *p;
972 		char            paths[_UC_MAXLINE];
973 
974 		/*
975 		 * We need to search paths
976 		 */
977 		strlcpy(paths, path, sizeof(paths));
978 		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
979 			int             i;
980 			static char     shellpath[256];
981 
982 			if (sh != NULL) {
983 				snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
984 				if (access(shellpath, X_OK) == 0)
985 					return shellpath;
986 			} else
987 				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
988 					snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
989 					if (access(shellpath, X_OK) == 0)
990 						return shellpath;
991 				}
992 		}
993 		if (sh == NULL)
994 			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
995 		errx(EX_CONFIG, "no default shell available or defined");
996 		return NULL;
997 	}
998 }
999 
1000 
1001 static char    *
1002 pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
1003 {
1004 	char           *sh = newshell;
1005 	struct carg    *arg = getarg(args, 's');
1006 
1007 	if (newshell == NULL && arg != NULL)
1008 		sh = arg->val;
1009 	return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
1010 }
1011 
1012 #define	SALTSIZE	32
1013 
1014 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1015 
1016 char           *
1017 pw_pwcrypt(char *password)
1018 {
1019 	int             i;
1020 	char            salt[SALTSIZE + 1];
1021 	char		*cryptpw;
1022 
1023 	static char     buf[256];
1024 
1025 	/*
1026 	 * Calculate a salt value
1027 	 */
1028 	for (i = 0; i < SALTSIZE; i++)
1029 		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1030 	salt[SALTSIZE] = '\0';
1031 
1032 	cryptpw = crypt(password, salt);
1033 	if (cryptpw == NULL)
1034 		errx(EX_CONFIG, "crypt(3) failure");
1035 	return strcpy(buf, cryptpw);
1036 }
1037 
1038 
1039 static char    *
1040 pw_password(struct userconf * cnf, char const * user)
1041 {
1042 	int             i, l;
1043 	char            pwbuf[32];
1044 
1045 	switch (cnf->default_password) {
1046 	case -1:		/* Random password */
1047 		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
1048 		for (i = 0; i < l; i++)
1049 			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
1050 		pwbuf[i] = '\0';
1051 
1052 		/*
1053 		 * We give this information back to the user
1054 		 */
1055 		if (conf.fd == -1 && !conf.dryrun) {
1056 			if (isatty(STDOUT_FILENO))
1057 				printf("Password for '%s' is: ", user);
1058 			printf("%s\n", pwbuf);
1059 			fflush(stdout);
1060 		}
1061 		break;
1062 
1063 	case -2:		/* No password at all! */
1064 		return "";
1065 
1066 	case 0:		/* No login - default */
1067 	default:
1068 		return "*";
1069 
1070 	case 1:		/* user's name */
1071 		strlcpy(pwbuf, user, sizeof(pwbuf));
1072 		break;
1073 	}
1074 	return pw_pwcrypt(pwbuf);
1075 }
1076 
1077 static int
1078 pw_userdel(char *name, long id)
1079 {
1080 	struct passwd *pwd = NULL;
1081 	char		 file[MAXPATHLEN];
1082 	char		 home[MAXPATHLEN];
1083 	uid_t		 uid;
1084 	struct group	*gr, *grp;
1085 	char		 grname[LOGNAMESIZE];
1086 	int		 rc;
1087 	struct stat	 st;
1088 	int		 valid_type = _PWF_FILES;
1089 
1090 	if (id < 0 && name == NULL)
1091 		errx(EX_DATAERR, "username or id required");
1092 
1093 	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1094 	if (pwd == NULL) {
1095 		if (name == NULL)
1096 			errx(EX_NOUSER, "no such uid `%ld'", id);
1097 		errx(EX_NOUSER, "no such user `%s'", name);
1098 	}
1099 
1100 	if (conf.userconf->nispasswd && *conf.userconf->nispasswd == '/')
1101 		valid_type = _PWF_NIS;
1102 
1103 	if (PWF._altdir == PWF_REGULAR &&
1104 	    ((pwd->pw_fields & _PWF_SOURCE) != valid_type))
1105 		errx(EX_NOUSER, "no such %s user `%s'",
1106 		    valid_type == _PWF_FILES ? "local" : "NIS"  , name);
1107 
1108 	uid = pwd->pw_uid;
1109 	if (name == NULL)
1110 		name = pwd->pw_name;
1111 
1112 	if (strcmp(pwd->pw_name, "root") == 0)
1113 		errx(EX_DATAERR, "cannot remove user 'root'");
1114 
1115 		/* Remove opie record from /etc/opiekeys */
1116 
1117 	if (PWALTDIR() != PWF_ALT)
1118 		rmopie(pwd->pw_name);
1119 
1120 	if (!PWALTDIR()) {
1121 		/* Remove crontabs */
1122 		snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
1123 		if (access(file, F_OK) == 0) {
1124 			snprintf(file, sizeof(file), "crontab -u %s -r", pwd->pw_name);
1125 			system(file);
1126 		}
1127 	}
1128 	/*
1129 	 * Save these for later, since contents of pwd may be
1130 	 * invalidated by deletion
1131 	 */
1132 	snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
1133 	strlcpy(home, pwd->pw_dir, sizeof(home));
1134 	gr = GETGRGID(pwd->pw_gid);
1135 	if (gr != NULL)
1136 		strlcpy(grname, gr->gr_name, LOGNAMESIZE);
1137 	else
1138 		grname[0] = '\0';
1139 
1140 	rc = delpwent(pwd);
1141 	if (rc == -1)
1142 		err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
1143 	else if (rc != 0)
1144 		err(EX_IOERR, "passwd update");
1145 
1146 	if (conf.userconf->nispasswd && *conf.userconf->nispasswd=='/') {
1147 		rc = delnispwent(conf.userconf->nispasswd, name);
1148 		if (rc == -1)
1149 			warnx("WARNING: user '%s' does not exist in NIS passwd",
1150 			    pwd->pw_name);
1151 		else if (rc != 0)
1152 			warn("WARNING: NIS passwd update");
1153 		/* non-fatal */
1154 	}
1155 
1156 	grp = GETGRNAM(name);
1157 	if (grp != NULL &&
1158 	    (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
1159 	    strcmp(name, grname) == 0)
1160 		delgrent(GETGRNAM(name));
1161 	SETGRENT();
1162 	while ((grp = GETGRENT()) != NULL) {
1163 		int i, j;
1164 		char group[MAXLOGNAME];
1165 		if (grp->gr_mem == NULL)
1166 			continue;
1167 
1168 		for (i = 0; grp->gr_mem[i] != NULL; i++) {
1169 			if (strcmp(grp->gr_mem[i], name) != 0)
1170 				continue;
1171 
1172 			for (j = i; grp->gr_mem[j] != NULL; j++)
1173 				grp->gr_mem[j] = grp->gr_mem[j+1];
1174 			strlcpy(group, grp->gr_name, MAXLOGNAME);
1175 			chggrent(group, grp);
1176 		}
1177 	}
1178 	ENDGRENT();
1179 
1180 	pw_log(conf.userconf, M_DELETE, W_USER, "%s(%u) account removed", name,
1181 	    uid);
1182 
1183 	/* Remove mail file */
1184 	if (PWALTDIR() != PWF_ALT)
1185 		unlinkat(conf.rootfd, file + 1, 0);
1186 
1187 		/* Remove at jobs */
1188 	if (!PWALTDIR() && getpwuid(uid) == NULL)
1189 		rmat(uid);
1190 
1191 	/* Remove home directory and contents */
1192 	if (PWALTDIR() != PWF_ALT && conf.deletehome && *home == '/' &&
1193 	    getpwuid(uid) == NULL &&
1194 	    fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1195 		rm_r(conf.rootfd, home, uid);
1196 		pw_log(conf.userconf, M_DELETE, W_USER, "%s(%u) home '%s' %s"
1197 		    "removed", name, uid, home,
1198 		     fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1199 		     "completely ");
1200 	}
1201 
1202 	return (EXIT_SUCCESS);
1203 }
1204 
1205 static int
1206 print_user(struct passwd * pwd)
1207 {
1208 	if (!conf.pretty) {
1209 		char            *buf;
1210 
1211 		buf = conf.v7 ? pw_make_v7(pwd) : pw_make(pwd);
1212 		printf("%s\n", buf);
1213 		free(buf);
1214 	} else {
1215 		int		j;
1216 		char           *p;
1217 		struct group   *grp = GETGRGID(pwd->pw_gid);
1218 		char            uname[60] = "User &", office[60] = "[None]",
1219 		                wphone[60] = "[None]", hphone[60] = "[None]";
1220 		char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
1221 		struct tm *    tptr;
1222 
1223 		if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1224 			strlcpy(uname, p, sizeof(uname));
1225 			if ((p = strtok(NULL, ",")) != NULL) {
1226 				strlcpy(office, p, sizeof(office));
1227 				if ((p = strtok(NULL, ",")) != NULL) {
1228 					strlcpy(wphone, p, sizeof(wphone));
1229 					if ((p = strtok(NULL, "")) != NULL) {
1230 						strlcpy(hphone, p,
1231 						    sizeof(hphone));
1232 					}
1233 				}
1234 			}
1235 		}
1236 		/*
1237 		 * Handle '&' in gecos field
1238 		 */
1239 		if ((p = strchr(uname, '&')) != NULL) {
1240 			int             l = strlen(pwd->pw_name);
1241 			int             m = strlen(p);
1242 
1243 			memmove(p + l, p + 1, m);
1244 			memmove(p, pwd->pw_name, l);
1245 			*p = (char) toupper((unsigned char)*p);
1246 		}
1247 		if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1248 			strftime(acexpire, sizeof acexpire, "%c", tptr);
1249 		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1250 			strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1251 		printf("Login Name: %-15s   #%-12u Group: %-15s   #%u\n"
1252 		       " Full Name: %s\n"
1253 		       "      Home: %-26.26s      Class: %s\n"
1254 		       "     Shell: %-26.26s     Office: %s\n"
1255 		       "Work Phone: %-26.26s Home Phone: %s\n"
1256 		       "Acc Expire: %-26.26s Pwd Expire: %s\n",
1257 		       pwd->pw_name, pwd->pw_uid,
1258 		       grp ? grp->gr_name : "(invalid)", pwd->pw_gid,
1259 		       uname, pwd->pw_dir, pwd->pw_class,
1260 		       pwd->pw_shell, office, wphone, hphone,
1261 		       acexpire, pwexpire);
1262 	        SETGRENT();
1263 		j = 0;
1264 		while ((grp=GETGRENT()) != NULL)
1265 		{
1266 			int     i = 0;
1267 			if (grp->gr_mem != NULL) {
1268 				while (grp->gr_mem[i] != NULL)
1269 				{
1270 					if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1271 					{
1272 						printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
1273 						break;
1274 					}
1275 					++i;
1276 				}
1277 			}
1278 		}
1279 		ENDGRENT();
1280 		printf("%s", j ? "\n" : "");
1281 	}
1282 	return EXIT_SUCCESS;
1283 }
1284 
1285 char *
1286 pw_checkname(char *name, int gecos)
1287 {
1288 	char showch[8];
1289 	const char *badchars, *ch, *showtype;
1290 	int reject;
1291 
1292 	ch = name;
1293 	reject = 0;
1294 	if (gecos) {
1295 		/* See if the name is valid as a gecos (comment) field. */
1296 		badchars = ":!@";
1297 		showtype = "gecos field";
1298 	} else {
1299 		/* See if the name is valid as a userid or group. */
1300 		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1301 		showtype = "userid/group name";
1302 		/* Userids and groups can not have a leading '-'. */
1303 		if (*ch == '-')
1304 			reject = 1;
1305 	}
1306 	if (!reject) {
1307 		while (*ch) {
1308 			if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1309 			    *ch == 127) {
1310 				reject = 1;
1311 				break;
1312 			}
1313 			/* 8-bit characters are only allowed in GECOS fields */
1314 			if (!gecos && (*ch & 0x80)) {
1315 				reject = 1;
1316 				break;
1317 			}
1318 			ch++;
1319 		}
1320 	}
1321 	/*
1322 	 * A `$' is allowed as the final character for userids and groups,
1323 	 * mainly for the benefit of samba.
1324 	 */
1325 	if (reject && !gecos) {
1326 		if (*ch == '$' && *(ch + 1) == '\0') {
1327 			reject = 0;
1328 			ch++;
1329 		}
1330 	}
1331 	if (reject) {
1332 		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1333 		    ? "`%c'" : "0x%02x", *ch);
1334 		errx(EX_DATAERR, "invalid character %s at position %td in %s",
1335 		    showch, (ch - name), showtype);
1336 	}
1337 	if (!gecos && (ch - name) > LOGNAMESIZE)
1338 		errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1339 		    LOGNAMESIZE);
1340 
1341 	return (name);
1342 }
1343 
1344 
1345 static void
1346 rmat(uid_t uid)
1347 {
1348 	DIR            *d = opendir("/var/at/jobs");
1349 
1350 	if (d != NULL) {
1351 		struct dirent  *e;
1352 
1353 		while ((e = readdir(d)) != NULL) {
1354 			struct stat     st;
1355 
1356 			if (strncmp(e->d_name, ".lock", 5) != 0 &&
1357 			    stat(e->d_name, &st) == 0 &&
1358 			    !S_ISDIR(st.st_mode) &&
1359 			    st.st_uid == uid) {
1360 				char            tmp[MAXPATHLEN];
1361 
1362 				snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s", e->d_name);
1363 				system(tmp);
1364 			}
1365 		}
1366 		closedir(d);
1367 	}
1368 }
1369 
1370 static void
1371 rmopie(char const * name)
1372 {
1373 	char tmp[1014];
1374 	FILE *fp;
1375 	int fd;
1376 	size_t len;
1377 	off_t	atofs = 0;
1378 
1379 	if ((fd = openat(conf.rootfd, "etc/opiekeys", O_RDWR)) == -1)
1380 		return;
1381 
1382 	fp = fdopen(fd, "r+");
1383 	len = strlen(name);
1384 
1385 	while (fgets(tmp, sizeof(tmp), fp) != NULL) {
1386 		if (strncmp(name, tmp, len) == 0 && tmp[len]==' ') {
1387 			/* Comment username out */
1388 			if (fseek(fp, atofs, SEEK_SET) == 0)
1389 				fwrite("#", 1, 1, fp);
1390 			break;
1391 		}
1392 		atofs = ftell(fp);
1393 	}
1394 	/*
1395 	 * If we got an error of any sort, don't update!
1396 	 */
1397 	fclose(fp);
1398 }
1399