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