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