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