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