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