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