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