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