pw_user.c revision 242916
120253Sjoerg/*-
220302Sjoerg * Copyright (C) 1996
320302Sjoerg *	David L. Nugent.  All rights reserved.
420253Sjoerg *
520253Sjoerg * Redistribution and use in source and binary forms, with or without
620253Sjoerg * modification, are permitted provided that the following conditions
720253Sjoerg * are met:
820253Sjoerg * 1. Redistributions of source code must retain the above copyright
920302Sjoerg *    notice, this list of conditions and the following disclaimer.
1020253Sjoerg * 2. Redistributions in binary form must reproduce the above copyright
1120253Sjoerg *    notice, this list of conditions and the following disclaimer in the
1220253Sjoerg *    documentation and/or other materials provided with the distribution.
1320253Sjoerg *
1420302Sjoerg * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
1520253Sjoerg * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1620253Sjoerg * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1720302Sjoerg * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
1820253Sjoerg * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1920253Sjoerg * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2020253Sjoerg * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2120253Sjoerg * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2220253Sjoerg * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2320253Sjoerg * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2420253Sjoerg * SUCH DAMAGE.
2544229Sdavidn *
2620253Sjoerg */
2720253Sjoerg
2830259Scharnier#ifndef lint
2930259Scharnierstatic const char rcsid[] =
3050479Speter  "$FreeBSD: stable/9/usr.sbin/pw/pw_user.c 242916 2012-11-12 14:13:49Z bapt $";
3130259Scharnier#endif /* not lint */
3230259Scharnier
3330259Scharnier#include <ctype.h>
3430259Scharnier#include <err.h>
3520253Sjoerg#include <fcntl.h>
3620253Sjoerg#include <sys/param.h>
3720253Sjoerg#include <dirent.h>
3830259Scharnier#include <paths.h>
3920253Sjoerg#include <termios.h>
4020555Sdavidn#include <sys/types.h>
4120555Sdavidn#include <sys/time.h>
4220555Sdavidn#include <sys/resource.h>
4330259Scharnier#include <unistd.h>
4464918Sgreen#include <login_cap.h>
4520253Sjoerg#include "pw.h"
4620253Sjoerg#include "bitmap.h"
4720253Sjoerg
4823318Sache#define LOGNAMESIZE (MAXLOGNAME-1)
4922394Sdavidn
5052512Sdavidnstatic		char locked_str[] = "*LOCKED*";
5124214Sache
5244386Sdavidnstatic int      print_user(struct passwd * pwd, int pretty, int v7);
5320253Sjoergstatic uid_t    pw_uidpolicy(struct userconf * cnf, struct cargs * args);
5420253Sjoergstatic uid_t    pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer);
5520253Sjoergstatic time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
5620253Sjoergstatic time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
5720253Sjoergstatic char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
5820253Sjoergstatic char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
5920253Sjoergstatic char    *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
6020253Sjoergstatic char    *shell_path(char const * path, char *shells[], char *sh);
6120253Sjoergstatic void     rmat(uid_t uid);
6285145Sachestatic void     rmopie(char const * name);
6320253Sjoerg
6420253Sjoerg/*-
6520253Sjoerg * -C config      configuration file
6620253Sjoerg * -q             quiet operation
6720253Sjoerg * -n name        login name
6820253Sjoerg * -u uid         user id
6920253Sjoerg * -c comment     user name/comment
7020253Sjoerg * -d directory   home directory
7120253Sjoerg * -e date        account expiry date
7220253Sjoerg * -p date        password expiry date
7320253Sjoerg * -g grp         primary group
7420253Sjoerg * -G grp1,grp2   additional groups
7520253Sjoerg * -m [ -k dir ]  create and set up home
7620253Sjoerg * -s shell       name of login shell
7720253Sjoerg * -o             duplicate uid ok
7820253Sjoerg * -L class       user class
7920253Sjoerg * -l name        new login name
8020253Sjoerg * -h fd          password filehandle
81124382Siedowse * -H fd          encrypted password filehandle
8220253Sjoerg * -F             force print or add
8320253Sjoerg *   Setting defaults:
8420253Sjoerg * -D             set user defaults
8520253Sjoerg * -b dir         default home root dir
8620253Sjoerg * -e period      default expiry period
8720253Sjoerg * -p period      default password change period
8820253Sjoerg * -g group       default group
8920253Sjoerg * -G             grp1,grp2.. default additional groups
9020253Sjoerg * -L class       default login class
9120253Sjoerg * -k dir         default home skeleton
9220253Sjoerg * -s shell       default shell
9320253Sjoerg * -w method      default password method
9420253Sjoerg */
9520253Sjoerg
9620253Sjoergint
9720253Sjoergpw_user(struct userconf * cnf, int mode, struct cargs * args)
9820253Sjoerg{
9952527Sdavidn	int	        rc, edited = 0;
10020253Sjoerg	char           *p = NULL;
10152512Sdavidn	char					 *passtmp;
10220253Sjoerg	struct carg    *a_name;
10320253Sjoerg	struct carg    *a_uid;
10420253Sjoerg	struct carg    *arg;
10520253Sjoerg	struct passwd  *pwd = NULL;
10620253Sjoerg	struct group   *grp;
10720253Sjoerg	struct stat     st;
10820747Sdavidn	char            line[_PASSWORD_LEN+1];
10982868Sdd	FILE	       *fp;
110167919Sle	char *dmode_c;
111167919Sle	void *set = NULL;
11220253Sjoerg
11320253Sjoerg	static struct passwd fakeuser =
11420253Sjoerg	{
11520253Sjoerg		NULL,
11620253Sjoerg		"*",
11720253Sjoerg		-1,
11820253Sjoerg		-1,
11920253Sjoerg		0,
12020253Sjoerg		"",
12120253Sjoerg		"User &",
12256000Sdavidn		"/nonexistent",
12320253Sjoerg		"/bin/sh",
12420253Sjoerg		0
12556000Sdavidn#if defined(__FreeBSD__)
12656000Sdavidn		,0
12756000Sdavidn#endif
12820253Sjoerg	};
12920253Sjoerg
13052512Sdavidn
13120253Sjoerg	/*
13220267Sjoerg	 * With M_NEXT, we only need to return the
13320267Sjoerg	 * next uid to stdout
13420267Sjoerg	 */
13520267Sjoerg	if (mode == M_NEXT)
13620267Sjoerg	{
13720267Sjoerg		uid_t next = pw_uidpolicy(cnf, args);
13820267Sjoerg		if (getarg(args, 'q'))
13920267Sjoerg			return next;
14020267Sjoerg		printf("%ld:", (long)next);
14120267Sjoerg		pw_group(cnf, mode, args);
14220267Sjoerg		return EXIT_SUCCESS;
14320267Sjoerg	}
14420267Sjoerg
14520267Sjoerg	/*
14620253Sjoerg	 * We can do all of the common legwork here
14720253Sjoerg	 */
14820253Sjoerg
14920253Sjoerg	if ((arg = getarg(args, 'b')) != NULL) {
15020267Sjoerg		cnf->home = arg->val;
15120253Sjoerg	}
15221052Sdavidn
153167919Sle	if ((arg = getarg(args, 'M')) != NULL) {
154167919Sle		dmode_c = arg->val;
155167919Sle		if ((set = setmode(dmode_c)) == NULL)
156167919Sle			errx(EX_DATAERR, "invalid directory creation mode '%s'",
157167919Sle			    dmode_c);
158219408Sjkim		cnf->homemode = getmode(set, _DEF_DIRMODE);
159167919Sle		free(set);
160168044Sle	}
161167919Sle
16221052Sdavidn	/*
16321052Sdavidn	 * If we'll need to use it or we're updating it,
16421052Sdavidn	 * then create the base home directory if necessary
16521052Sdavidn	 */
166224535Sdelphij	if (arg != NULL || getarg(args, 'm') != NULL) {
16721052Sdavidn		int	l = strlen(cnf->home);
16821052Sdavidn
16921052Sdavidn		if (l > 1 && cnf->home[l-1] == '/')	/* Shave off any trailing path delimiter */
17021052Sdavidn			cnf->home[--l] = '\0';
17121052Sdavidn
17221052Sdavidn		if (l < 2 || *cnf->home != '/')		/* Check for absolute path name */
17330259Scharnier			errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
17421052Sdavidn
17521052Sdavidn		if (stat(cnf->home, &st) == -1) {
17621052Sdavidn			char	dbuf[MAXPATHLEN];
17721052Sdavidn
17821242Sdavidn			/*
17921242Sdavidn			 * This is a kludge especially for Joerg :)
18021242Sdavidn			 * If the home directory would be created in the root partition, then
18121242Sdavidn			 * we really create it under /usr which is likely to have more space.
18221242Sdavidn			 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
18321242Sdavidn			 */
18421242Sdavidn			if (strchr(cnf->home+1, '/') == NULL) {
18521242Sdavidn				strcpy(dbuf, "/usr");
18621242Sdavidn				strncat(dbuf, cnf->home, MAXPATHLEN-5);
187219408Sjkim				if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
18821242Sdavidn					chown(dbuf, 0, 0);
189148584Spjd					/*
190148584Spjd					 * Skip first "/" and create symlink:
191148584Spjd					 * /home -> usr/home
192148584Spjd					 */
193148584Spjd					symlink(dbuf+1, cnf->home);
19421242Sdavidn				}
19521242Sdavidn				/* If this falls, fall back to old method */
19621242Sdavidn			}
197130633Srobert			strlcpy(dbuf, cnf->home, sizeof(dbuf));
198130633Srobert			p = dbuf;
19921242Sdavidn			if (stat(dbuf, &st) == -1) {
20021242Sdavidn				while ((p = strchr(++p, '/')) != NULL) {
20121242Sdavidn					*p = '\0';
20221242Sdavidn					if (stat(dbuf, &st) == -1) {
203219408Sjkim						if (mkdir(dbuf, _DEF_DIRMODE) == -1)
20421242Sdavidn							goto direrr;
20521242Sdavidn						chown(dbuf, 0, 0);
20621242Sdavidn					} else if (!S_ISDIR(st.st_mode))
20730259Scharnier						errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
20821242Sdavidn					*p = '/';
20921242Sdavidn				}
21021052Sdavidn			}
21121242Sdavidn			if (stat(dbuf, &st) == -1) {
212219408Sjkim				if (mkdir(dbuf, _DEF_DIRMODE) == -1) {
21330259Scharnier				direrr:	err(EX_OSFILE, "mkdir '%s'", dbuf);
21421052Sdavidn				}
21521052Sdavidn				chown(dbuf, 0, 0);
21621052Sdavidn			}
21721052Sdavidn		} else if (!S_ISDIR(st.st_mode))
21830259Scharnier			errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
21921052Sdavidn	}
22021052Sdavidn
22120253Sjoerg	if ((arg = getarg(args, 'e')) != NULL)
22220253Sjoerg		cnf->expire_days = atoi(arg->val);
22320253Sjoerg
22421330Sdavidn	if ((arg = getarg(args, 'y')) != NULL)
22521330Sdavidn		cnf->nispasswd = arg->val;
22621330Sdavidn
22720253Sjoerg	if ((arg = getarg(args, 'p')) != NULL && arg->val)
22820253Sjoerg		cnf->password_days = atoi(arg->val);
22920253Sjoerg
23020253Sjoerg	if ((arg = getarg(args, 'g')) != NULL) {
23163596Sdavidn		if (!*(p = arg->val))	/* Handle empty group list specially */
23263596Sdavidn			cnf->default_group = "";
23363596Sdavidn		else {
23463596Sdavidn			if ((grp = GETGRNAM(p)) == NULL) {
23563596Sdavidn				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
23663596Sdavidn					errx(EX_NOUSER, "group `%s' does not exist", p);
23763596Sdavidn			}
23863596Sdavidn			cnf->default_group = newstr(grp->gr_name);
23920253Sjoerg		}
24020253Sjoerg	}
24120253Sjoerg	if ((arg = getarg(args, 'L')) != NULL)
24220679Sdavidn		cnf->default_class = pw_checkname((u_char *)arg->val, 0);
24320253Sjoerg
24420253Sjoerg	if ((arg = getarg(args, 'G')) != NULL && arg->val) {
24552527Sdavidn		int i = 0;
24620253Sjoerg
24720747Sdavidn		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
24844229Sdavidn			if ((grp = GETGRNAM(p)) == NULL) {
24961957Sache				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
25030259Scharnier					errx(EX_NOUSER, "group `%s' does not exist", p);
25120253Sjoerg			}
25220747Sdavidn			if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
25320747Sdavidn				cnf->groups[i++] = newstr(grp->gr_name);
25420253Sjoerg		}
25520747Sdavidn		while (i < cnf->numgroups)
25620253Sjoerg			cnf->groups[i++] = NULL;
25720253Sjoerg	}
25852527Sdavidn
25920253Sjoerg	if ((arg = getarg(args, 'k')) != NULL) {
26026088Sdavidn		if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
26130259Scharnier			errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
26220253Sjoerg	}
26352527Sdavidn
26420253Sjoerg	if ((arg = getarg(args, 's')) != NULL)
26520253Sjoerg		cnf->shell_default = arg->val;
26620253Sjoerg
26763600Sdavidn	if ((arg = getarg(args, 'w')) != NULL)
26863600Sdavidn		cnf->default_password = boolean_val(arg->val, cnf->default_password);
26920253Sjoerg	if (mode == M_ADD && getarg(args, 'D')) {
27020253Sjoerg		if (getarg(args, 'n') != NULL)
27130259Scharnier			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
27220253Sjoerg		if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
27320253Sjoerg			if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
27420253Sjoerg				cnf->min_uid = 1000;
27520253Sjoerg			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
27620253Sjoerg				cnf->max_uid = 32000;
27720253Sjoerg		}
27820253Sjoerg		if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
27920253Sjoerg			if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
28020253Sjoerg				cnf->min_gid = 1000;
28120253Sjoerg			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
28220253Sjoerg				cnf->max_gid = 32000;
28320253Sjoerg		}
28420253Sjoerg
28520253Sjoerg		arg = getarg(args, 'C');
28620253Sjoerg		if (write_userconfig(arg ? arg->val : NULL))
28720267Sjoerg			return EXIT_SUCCESS;
28830259Scharnier		warn("config update");
28920267Sjoerg		return EX_IOERR;
29020253Sjoerg	}
29152527Sdavidn
29220253Sjoerg	if (mode == M_PRINT && getarg(args, 'a')) {
29320267Sjoerg		int             pretty = getarg(args, 'P') != NULL;
29444386Sdavidn		int		v7 = getarg(args, '7') != NULL;
29520253Sjoerg
29644229Sdavidn		SETPWENT();
29744229Sdavidn		while ((pwd = GETPWENT()) != NULL)
29844386Sdavidn			print_user(pwd, pretty, v7);
29944229Sdavidn		ENDPWENT();
30020267Sjoerg		return EXIT_SUCCESS;
30120253Sjoerg	}
30252527Sdavidn
30320253Sjoerg	if ((a_name = getarg(args, 'n')) != NULL)
30444229Sdavidn		pwd = GETPWNAM(pw_checkname((u_char *)a_name->val, 0));
30520253Sjoerg	a_uid = getarg(args, 'u');
30620253Sjoerg
30720253Sjoerg	if (a_uid == NULL) {
30820253Sjoerg		if (a_name == NULL)
30930259Scharnier			errx(EX_DATAERR, "user name or id required");
31020253Sjoerg
31120253Sjoerg		/*
31220253Sjoerg		 * Determine whether 'n' switch is name or uid - we don't
31320253Sjoerg		 * really don't really care which we have, but we need to
31420253Sjoerg		 * know.
31520253Sjoerg		 */
31643780Sdes		if (mode != M_ADD && pwd == NULL
31743780Sdes		    && strspn(a_name->val, "0123456789") == strlen(a_name->val)
318242916Sbapt		    && *a_name->val) {
31920253Sjoerg			(a_uid = a_name)->ch = 'u';
32020253Sjoerg			a_name = NULL;
32120253Sjoerg		}
32220253Sjoerg	}
32352527Sdavidn
32420253Sjoerg	/*
32520253Sjoerg	 * Update, delete & print require that the user exists
32620253Sjoerg	 */
32752512Sdavidn	if (mode == M_UPDATE || mode == M_DELETE ||
32852512Sdavidn	    mode == M_PRINT  || mode == M_LOCK   || mode == M_UNLOCK) {
32952527Sdavidn
33020253Sjoerg		if (a_name == NULL && pwd == NULL)	/* Try harder */
33144229Sdavidn			pwd = GETPWUID(atoi(a_uid->val));
33220253Sjoerg
33320253Sjoerg		if (pwd == NULL) {
33420253Sjoerg			if (mode == M_PRINT && getarg(args, 'F')) {
33520253Sjoerg				fakeuser.pw_name = a_name ? a_name->val : "nouser";
33620253Sjoerg				fakeuser.pw_uid = a_uid ? (uid_t) atol(a_uid->val) : -1;
33744386Sdavidn				return print_user(&fakeuser,
33844386Sdavidn						  getarg(args, 'P') != NULL,
33944386Sdavidn						  getarg(args, '7') != NULL);
34020253Sjoerg			}
34120253Sjoerg			if (a_name == NULL)
34230259Scharnier				errx(EX_NOUSER, "no such uid `%s'", a_uid->val);
34330259Scharnier			errx(EX_NOUSER, "no such user `%s'", a_name->val);
34420253Sjoerg		}
34552527Sdavidn
34620253Sjoerg		if (a_name == NULL)	/* May be needed later */
34720253Sjoerg			a_name = addarg(args, 'n', newstr(pwd->pw_name));
34820253Sjoerg
34920253Sjoerg		/*
35052512Sdavidn		 * The M_LOCK and M_UNLOCK functions simply add or remove
35152512Sdavidn		 * a "*LOCKED*" prefix from in front of the password to
35252512Sdavidn		 * prevent it decoding correctly, and therefore prevents
35352512Sdavidn		 * access. Of course, this only prevents access via
35452512Sdavidn		 * password authentication (not ssh, kerberos or any
35552512Sdavidn		 * other method that does not use the UNIX password) but
35652512Sdavidn		 * that is a known limitation.
35752512Sdavidn		 */
35852512Sdavidn
35952512Sdavidn		if (mode == M_LOCK) {
36052512Sdavidn			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
36152512Sdavidn				errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
36252512Sdavidn			passtmp = malloc(strlen(pwd->pw_passwd) + sizeof(locked_str));
36352512Sdavidn			if (passtmp == NULL)	/* disaster */
36452512Sdavidn				errx(EX_UNAVAILABLE, "out of memory");
36552512Sdavidn			strcpy(passtmp, locked_str);
36652512Sdavidn			strcat(passtmp, pwd->pw_passwd);
36752512Sdavidn			pwd->pw_passwd = passtmp;
36852527Sdavidn			edited = 1;
36952512Sdavidn		} else if (mode == M_UNLOCK) {
37052512Sdavidn			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
37152512Sdavidn				errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
37252512Sdavidn			pwd->pw_passwd += sizeof(locked_str)-1;
37352527Sdavidn			edited = 1;
37452527Sdavidn		} else if (mode == M_DELETE) {
37552527Sdavidn			/*
37652527Sdavidn			 * Handle deletions now
37752527Sdavidn			 */
37820253Sjoerg			char            file[MAXPATHLEN];
37920253Sjoerg			char            home[MAXPATHLEN];
38020253Sjoerg			uid_t           uid = pwd->pw_uid;
38120253Sjoerg
38220253Sjoerg			if (strcmp(pwd->pw_name, "root") == 0)
38330259Scharnier				errx(EX_DATAERR, "cannot remove user 'root'");
38420253Sjoerg
38544229Sdavidn			if (!PWALTDIR()) {
38644229Sdavidn				/*
38785145Sache				 * Remove opie record from /etc/opiekeys
38844229Sdavidn		        	 */
38920747Sdavidn
39085145Sache				rmopie(pwd->pw_name);
39120747Sdavidn
39244229Sdavidn				/*
39344229Sdavidn				 * Remove crontabs
39444229Sdavidn				 */
39544229Sdavidn				sprintf(file, "/var/cron/tabs/%s", pwd->pw_name);
39644229Sdavidn				if (access(file, F_OK) == 0) {
39744229Sdavidn					sprintf(file, "crontab -u %s -r", pwd->pw_name);
39844229Sdavidn					system(file);
39944229Sdavidn				}
40020253Sjoerg			}
40120253Sjoerg			/*
40220253Sjoerg			 * Save these for later, since contents of pwd may be
40320253Sjoerg			 * invalidated by deletion
40420253Sjoerg			 */
40520253Sjoerg			sprintf(file, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
406130633Srobert			strlcpy(home, pwd->pw_dir, sizeof(home));
40720253Sjoerg
40852502Sdavidn			rc = delpwent(pwd);
40952502Sdavidn			if (rc == -1)
41052502Sdavidn				err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
41152502Sdavidn			else if (rc != 0) {
41256000Sdavidn				warn("passwd update");
41352502Sdavidn				return EX_IOERR;
41452502Sdavidn			}
41521330Sdavidn
41652502Sdavidn			if (cnf->nispasswd && *cnf->nispasswd=='/') {
41752502Sdavidn				rc = delnispwent(cnf->nispasswd, a_name->val);
41852502Sdavidn				if (rc == -1)
41952502Sdavidn					warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
42052502Sdavidn				else if (rc != 0)
42156000Sdavidn					warn("WARNING: NIS passwd update");
42252502Sdavidn				/* non-fatal */
42352502Sdavidn			}
42452502Sdavidn
42520253Sjoerg			editgroups(a_name->val, NULL);
42620253Sjoerg
42720253Sjoerg			pw_log(cnf, mode, W_USER, "%s(%ld) account removed", a_name->val, (long) uid);
42820253Sjoerg
42944229Sdavidn			if (!PWALTDIR()) {
43044229Sdavidn				/*
43144229Sdavidn				 * Remove mail file
43244229Sdavidn				 */
43344229Sdavidn				remove(file);
43420253Sjoerg
43544229Sdavidn				/*
43644229Sdavidn				 * Remove at jobs
43744229Sdavidn				 */
43844229Sdavidn				if (getpwuid(uid) == NULL)
43944229Sdavidn					rmat(uid);
44020253Sjoerg
44144229Sdavidn				/*
44244229Sdavidn				 * Remove home directory and contents
44344229Sdavidn				 */
44444229Sdavidn				if (getarg(args, 'r') != NULL && *home == '/' && getpwuid(uid) == NULL) {
44544229Sdavidn					if (stat(home, &st) != -1) {
44644229Sdavidn						rm_r(home, uid);
44744229Sdavidn						pw_log(cnf, mode, W_USER, "%s(%ld) home '%s' %sremoved",
44844229Sdavidn						       a_name->val, (long) uid, home,
44944229Sdavidn						       stat(home, &st) == -1 ? "" : "not completely ");
45044229Sdavidn					}
45120253Sjoerg				}
45220253Sjoerg			}
45320267Sjoerg			return EXIT_SUCCESS;
45420253Sjoerg		} else if (mode == M_PRINT)
45544386Sdavidn			return print_user(pwd,
45644386Sdavidn					  getarg(args, 'P') != NULL,
45744386Sdavidn					  getarg(args, '7') != NULL);
45820253Sjoerg
45920253Sjoerg		/*
46020253Sjoerg		 * The rest is edit code
46120253Sjoerg		 */
46220253Sjoerg		if ((arg = getarg(args, 'l')) != NULL) {
46320253Sjoerg			if (strcmp(pwd->pw_name, "root") == 0)
46430259Scharnier				errx(EX_DATAERR, "can't rename `root' account");
46520679Sdavidn			pwd->pw_name = pw_checkname((u_char *)arg->val, 0);
46652527Sdavidn			edited = 1;
46720253Sjoerg		}
46852527Sdavidn
46961957Sache		if ((arg = getarg(args, 'u')) != NULL && isdigit((unsigned char)*arg->val)) {
47020253Sjoerg			pwd->pw_uid = (uid_t) atol(arg->val);
47152527Sdavidn			edited = 1;
47220253Sjoerg			if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
47330259Scharnier				errx(EX_DATAERR, "can't change uid of `root' account");
47420253Sjoerg			if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
47530259Scharnier				warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
47620253Sjoerg		}
47720253Sjoerg
47852527Sdavidn		if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {	/* Already checked this */
47952527Sdavidn			gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
48052527Sdavidn			if (newgid != pwd->pw_gid) {
48152527Sdavidn				edited = 1;
48261762Sdavidn				pwd->pw_gid = newgid;
48352527Sdavidn			}
48452527Sdavidn		}
48552527Sdavidn
48620253Sjoerg		if ((arg = getarg(args, 'p')) != NULL) {
48752527Sdavidn			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
48852527Sdavidn				if (pwd->pw_change != 0) {
48952527Sdavidn					pwd->pw_change = 0;
49052527Sdavidn					edited = 1;
49152527Sdavidn				}
49252527Sdavidn			}
49320253Sjoerg			else {
49420253Sjoerg				time_t          now = time(NULL);
49520253Sjoerg				time_t          expire = parse_date(now, arg->val);
49620253Sjoerg
49720253Sjoerg				if (now == expire)
49830259Scharnier					errx(EX_DATAERR, "invalid password change date `%s'", arg->val);
49952527Sdavidn				if (pwd->pw_change != expire) {
50052527Sdavidn					pwd->pw_change = expire;
50152527Sdavidn					edited = 1;
50252527Sdavidn				}
50320253Sjoerg			}
50420253Sjoerg		}
50552527Sdavidn
50620267Sjoerg		if ((arg = getarg(args, 'e')) != NULL) {
50752527Sdavidn			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
50852527Sdavidn				if (pwd->pw_expire != 0) {
50952527Sdavidn					pwd->pw_expire = 0;
51052527Sdavidn					edited = 1;
51152527Sdavidn				}
51252527Sdavidn			}
51320253Sjoerg			else {
51420253Sjoerg				time_t          now = time(NULL);
51520253Sjoerg				time_t          expire = parse_date(now, arg->val);
51620253Sjoerg
51720253Sjoerg				if (now == expire)
51830259Scharnier					errx(EX_DATAERR, "invalid account expiry date `%s'", arg->val);
51952527Sdavidn				if (pwd->pw_expire != expire) {
52052527Sdavidn					pwd->pw_expire = expire;
52152527Sdavidn					edited = 1;
52252527Sdavidn				}
52320253Sjoerg			}
52420253Sjoerg		}
52520253Sjoerg
52652527Sdavidn		if ((arg = getarg(args, 's')) != NULL) {
52752527Sdavidn			char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
52852527Sdavidn			if (shell == NULL)
52952527Sdavidn				shell = "";
53052527Sdavidn			if (strcmp(shell, pwd->pw_shell) != 0) {
53152527Sdavidn				pwd->pw_shell = shell;
53252527Sdavidn				edited = 1;
53352527Sdavidn			}
53452527Sdavidn		}
53520253Sjoerg
53652527Sdavidn		if (getarg(args, 'L')) {
53752527Sdavidn			if (cnf->default_class == NULL)
53852527Sdavidn				cnf->default_class = "";
53952527Sdavidn			if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
54052527Sdavidn				pwd->pw_class = cnf->default_class;
54152527Sdavidn				edited = 1;
54252527Sdavidn			}
54352527Sdavidn		}
54452527Sdavidn
54520747Sdavidn		if ((arg  = getarg(args, 'd')) != NULL) {
546130629Srobert			if (strcmp(pwd->pw_dir, arg->val))
547130629Srobert				edited = 1;
54820747Sdavidn			if (stat(pwd->pw_dir = arg->val, &st) == -1) {
54920747Sdavidn				if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
55030259Scharnier				  warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
55120747Sdavidn			} else if (!S_ISDIR(st.st_mode))
55230259Scharnier				warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
55320747Sdavidn		}
55420747Sdavidn
555124382Siedowse		if ((arg = getarg(args, 'w')) != NULL &&
556124382Siedowse		    getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
55764918Sgreen			login_cap_t *lc;
55864918Sgreen
55964918Sgreen			lc = login_getpwclass(pwd);
56064918Sgreen			if (lc == NULL ||
56164918Sgreen			    login_setcryptfmt(lc, "md5", NULL) == NULL)
56264918Sgreen				warn("setting crypt(3) format");
56364918Sgreen			login_close(lc);
56420267Sjoerg			pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
56552527Sdavidn			edited = 1;
56652527Sdavidn		}
56720267Sjoerg
56820253Sjoerg	} else {
56964918Sgreen		login_cap_t *lc;
57052527Sdavidn
57152527Sdavidn		/*
57252527Sdavidn		 * Add code
57352527Sdavidn		 */
57452527Sdavidn
57520253Sjoerg		if (a_name == NULL)	/* Required */
57630259Scharnier			errx(EX_DATAERR, "login name required");
57744229Sdavidn		else if ((pwd = GETPWNAM(a_name->val)) != NULL)	/* Exists */
57830259Scharnier			errx(EX_DATAERR, "login name `%s' already exists", a_name->val);
57920253Sjoerg
58020253Sjoerg		/*
58120253Sjoerg		 * Now, set up defaults for a new user
58220253Sjoerg		 */
58320253Sjoerg		pwd = &fakeuser;
58420253Sjoerg		pwd->pw_name = a_name->val;
58520253Sjoerg		pwd->pw_class = cnf->default_class ? cnf->default_class : "";
58620253Sjoerg		pwd->pw_uid = pw_uidpolicy(cnf, args);
58720253Sjoerg		pwd->pw_gid = pw_gidpolicy(cnf, args, pwd->pw_name, (gid_t) pwd->pw_uid);
58820253Sjoerg		pwd->pw_change = pw_pwdpolicy(cnf, args);
58920253Sjoerg		pwd->pw_expire = pw_exppolicy(cnf, args);
59020253Sjoerg		pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
59120253Sjoerg		pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
59264918Sgreen		lc = login_getpwclass(pwd);
59364918Sgreen		if (lc == NULL || login_setcryptfmt(lc, "md5", NULL) == NULL)
59464918Sgreen			warn("setting crypt(3) format");
59564918Sgreen		login_close(lc);
59664918Sgreen		pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
59752527Sdavidn		edited = 1;
59820253Sjoerg
59920253Sjoerg		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
60030259Scharnier			warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
60120253Sjoerg	}
60220253Sjoerg
60320253Sjoerg	/*
60420253Sjoerg	 * Shared add/edit code
60520253Sjoerg	 */
60652527Sdavidn	if ((arg = getarg(args, 'c')) != NULL) {
60752527Sdavidn		char	*gecos = pw_checkname((u_char *)arg->val, 1);
60852527Sdavidn		if (strcmp(pwd->pw_gecos, gecos) != 0) {
60952527Sdavidn			pwd->pw_gecos = gecos;
61052527Sdavidn			edited = 1;
61152527Sdavidn		}
61252527Sdavidn	}
61320253Sjoerg
614124382Siedowse	if ((arg = getarg(args, 'h')) != NULL ||
615124382Siedowse	    (arg = getarg(args, 'H')) != NULL) {
61663572Sdavidn		if (strcmp(arg->val, "-") == 0) {
61763572Sdavidn			if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
61863572Sdavidn				pwd->pw_passwd = "*";	/* No access */
61963572Sdavidn				edited = 1;
62063572Sdavidn			}
62163572Sdavidn		} else {
62220253Sjoerg			int             fd = atoi(arg->val);
623124382Siedowse			int		precrypt = (arg->ch == 'H');
62420253Sjoerg			int             b;
62520253Sjoerg			int             istty = isatty(fd);
62620253Sjoerg			struct termios  t;
62764918Sgreen			login_cap_t	*lc;
62820253Sjoerg
62920253Sjoerg			if (istty) {
63020253Sjoerg				if (tcgetattr(fd, &t) == -1)
63120253Sjoerg					istty = 0;
63220253Sjoerg				else {
63320253Sjoerg					struct termios  n = t;
63420253Sjoerg
63520253Sjoerg					/* Disable echo */
63620253Sjoerg					n.c_lflag &= ~(ECHO);
63720253Sjoerg					tcsetattr(fd, TCSANOW, &n);
638124382Siedowse					printf("%s%spassword for user %s:",
639124382Siedowse					     (mode == M_UPDATE) ? "new " : "",
640124382Siedowse					     precrypt ? "encrypted " : "",
641124382Siedowse					     pwd->pw_name);
64220253Sjoerg					fflush(stdout);
64320253Sjoerg				}
64420253Sjoerg			}
64520253Sjoerg			b = read(fd, line, sizeof(line) - 1);
64620253Sjoerg			if (istty) {	/* Restore state */
64720253Sjoerg				tcsetattr(fd, TCSANOW, &t);
64820253Sjoerg				fputc('\n', stdout);
64920253Sjoerg				fflush(stdout);
65020253Sjoerg			}
65120253Sjoerg			if (b < 0) {
652124382Siedowse				warn("-%c file descriptor", precrypt ? 'H' :
653124382Siedowse				    'h');
65420267Sjoerg				return EX_IOERR;
65520253Sjoerg			}
65620253Sjoerg			line[b] = '\0';
657168045Sle			if ((p = strpbrk(line, "\r\n")) != NULL)
65820253Sjoerg				*p = '\0';
65920253Sjoerg			if (!*line)
66030259Scharnier				errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
661124382Siedowse			if (precrypt) {
662124382Siedowse				if (strchr(line, ':') != NULL)
663124382Siedowse					return EX_DATAERR;
664124382Siedowse				pwd->pw_passwd = line;
665124382Siedowse			} else {
666124382Siedowse				lc = login_getpwclass(pwd);
667124382Siedowse				if (lc == NULL ||
668124382Siedowse				    login_setcryptfmt(lc, "md5", NULL) == NULL)
669124382Siedowse					warn("setting crypt(3) format");
670124382Siedowse				login_close(lc);
671124382Siedowse				pwd->pw_passwd = pw_pwcrypt(line);
672124382Siedowse			}
67352527Sdavidn			edited = 1;
67420253Sjoerg		}
67520253Sjoerg	}
67620267Sjoerg
67720267Sjoerg	/*
67820267Sjoerg	 * Special case: -N only displays & exits
67920267Sjoerg	 */
68020267Sjoerg	if (getarg(args, 'N') != NULL)
68144386Sdavidn		return print_user(pwd,
68244386Sdavidn				  getarg(args, 'P') != NULL,
68344386Sdavidn				  getarg(args, '7') != NULL);
68420267Sjoerg
68521330Sdavidn	if (mode == M_ADD) {
68652527Sdavidn		edited = 1;	/* Always */
68752502Sdavidn		rc = addpwent(pwd);
68852502Sdavidn		if (rc == -1) {
68952502Sdavidn			warnx("user '%s' already exists", pwd->pw_name);
69052502Sdavidn			return EX_IOERR;
69152502Sdavidn		} else if (rc != 0) {
69256000Sdavidn			warn("passwd file update");
69352502Sdavidn			return EX_IOERR;
69452502Sdavidn		}
69552502Sdavidn		if (cnf->nispasswd && *cnf->nispasswd=='/') {
69652502Sdavidn			rc = addnispwent(cnf->nispasswd, pwd);
69752502Sdavidn			if (rc == -1)
69852502Sdavidn				warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
69952502Sdavidn			else
70056000Sdavidn				warn("NIS passwd update");
70152502Sdavidn			/* NOTE: we treat NIS-only update errors as non-fatal */
70252502Sdavidn		}
70352512Sdavidn	} else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
70452527Sdavidn		if (edited) {	/* Only updated this if required */
70552527Sdavidn			rc = chgpwent(a_name->val, pwd);
70652527Sdavidn			if (rc == -1) {
70752527Sdavidn				warnx("user '%s' does not exist (NIS?)", pwd->pw_name);
70852527Sdavidn				return EX_IOERR;
70952527Sdavidn			} else if (rc != 0) {
71056000Sdavidn				warn("passwd file update");
71152527Sdavidn				return EX_IOERR;
71252527Sdavidn			}
71352527Sdavidn			if ( cnf->nispasswd && *cnf->nispasswd=='/') {
71452527Sdavidn				rc = chgnispwent(cnf->nispasswd, a_name->val, pwd);
71552527Sdavidn				if (rc == -1)
71652527Sdavidn					warn("User '%s' not found in NIS passwd", pwd->pw_name);
71752527Sdavidn				else
71856000Sdavidn					warn("NIS passwd update");
71952527Sdavidn				/* NOTE: NIS-only update errors are not fatal */
72052527Sdavidn			}
72152502Sdavidn		}
72221330Sdavidn	}
72321330Sdavidn
72420253Sjoerg	/*
72520253Sjoerg	 * Ok, user is created or changed - now edit group file
72620253Sjoerg	 */
72720253Sjoerg
72820253Sjoerg	if (mode == M_ADD || getarg(args, 'G') != NULL)
72920253Sjoerg		editgroups(pwd->pw_name, cnf->groups);
73020253Sjoerg
73161759Sdavidn	/* go get a current version of pwd */
73261759Sdavidn	pwd = GETPWNAM(a_name->val);
73361759Sdavidn	if (pwd == NULL) {
73461759Sdavidn		/* This will fail when we rename, so special case that */
73561759Sdavidn		if (mode == M_UPDATE && (arg = getarg(args, 'l')) != NULL) {
73661759Sdavidn			a_name->val = arg->val;		/* update new name */
73761759Sdavidn			pwd = GETPWNAM(a_name->val);	/* refetch renamed rec */
73861759Sdavidn		}
73961759Sdavidn	}
74061759Sdavidn	if (pwd == NULL)	/* can't go on without this */
74130259Scharnier		errx(EX_NOUSER, "user '%s' disappeared during update", a_name->val);
74220253Sjoerg
74344229Sdavidn	grp = GETGRGID(pwd->pw_gid);
74498744Sdwmalone	pw_log(cnf, mode, W_USER, "%s(%ld):%s(%ld):%s:%s:%s",
74520253Sjoerg	       pwd->pw_name, (long) pwd->pw_uid,
74620253Sjoerg	    grp ? grp->gr_name : "unknown", (long) (grp ? grp->gr_gid : -1),
74720253Sjoerg	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
74820253Sjoerg
74920253Sjoerg	/*
75020253Sjoerg	 * If adding, let's touch and chown the user's mail file. This is not
75120253Sjoerg	 * strictly necessary under BSD with a 0755 maildir but it also
75220253Sjoerg	 * doesn't hurt anything to create the empty mailfile
75320253Sjoerg	 */
75420253Sjoerg	if (mode == M_ADD) {
75544229Sdavidn		if (!PWALTDIR()) {
75644229Sdavidn			sprintf(line, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
75744229Sdavidn			close(open(line, O_RDWR | O_CREAT, 0600));	/* Preserve contents &
75844229Sdavidn									 * mtime */
75944229Sdavidn			chown(line, pwd->pw_uid, pwd->pw_gid);
76020253Sjoerg		}
76120253Sjoerg	}
76252527Sdavidn
76320253Sjoerg	/*
76482868Sdd	 * Let's create and populate the user's home directory. Note
76520253Sjoerg	 * that this also `works' for editing users if -m is used, but
76620253Sjoerg	 * existing files will *not* be overwritten.
76720253Sjoerg	 */
76844229Sdavidn	if (!PWALTDIR() && getarg(args, 'm') != NULL && pwd->pw_dir && *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
769168044Sle		copymkdir(pwd->pw_dir, cnf->dotdir, cnf->homemode, pwd->pw_uid, pwd->pw_gid);
77020253Sjoerg		pw_log(cnf, mode, W_USER, "%s(%ld) home %s made",
77120253Sjoerg		       pwd->pw_name, (long) pwd->pw_uid, pwd->pw_dir);
77220253Sjoerg	}
77352527Sdavidn
77482868Sdd
77582868Sdd	/*
77682868Sdd	 * Finally, send mail to the new user as well, if we are asked to
77782868Sdd	 */
77882868Sdd	if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
77982868Sdd		FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
78082868Sdd
78182868Sdd		if (pfp == NULL)
78282868Sdd			warn("sendmail");
78382868Sdd		else {
78482868Sdd			fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
78582868Sdd			while (fgets(line, sizeof(line), fp) != NULL) {
78682868Sdd				/* Do substitutions? */
78782868Sdd				fputs(line, pfp);
78882868Sdd			}
78982868Sdd			pclose(pfp);
79082868Sdd			pw_log(cnf, mode, W_USER, "%s(%ld) new user mail sent",
79182868Sdd			    pwd->pw_name, (long) pwd->pw_uid);
79282868Sdd		}
79382868Sdd		fclose(fp);
79482868Sdd	}
79582868Sdd
79620267Sjoerg	return EXIT_SUCCESS;
79720253Sjoerg}
79820253Sjoerg
79920253Sjoerg
80020253Sjoergstatic          uid_t
80120253Sjoergpw_uidpolicy(struct userconf * cnf, struct cargs * args)
80220253Sjoerg{
80320253Sjoerg	struct passwd  *pwd;
80420253Sjoerg	uid_t           uid = (uid_t) - 1;
80520253Sjoerg	struct carg    *a_uid = getarg(args, 'u');
80620253Sjoerg
80720253Sjoerg	/*
80820253Sjoerg	 * Check the given uid, if any
80920253Sjoerg	 */
81020253Sjoerg	if (a_uid != NULL) {
81120253Sjoerg		uid = (uid_t) atol(a_uid->val);
81220253Sjoerg
81344229Sdavidn		if ((pwd = GETPWUID(uid)) != NULL && getarg(args, 'o') == NULL)
81430259Scharnier			errx(EX_DATAERR, "uid `%ld' has already been allocated", (long) pwd->pw_uid);
81520253Sjoerg	} else {
81620253Sjoerg		struct bitmap   bm;
81720253Sjoerg
81820253Sjoerg		/*
81920253Sjoerg		 * We need to allocate the next available uid under one of
82020253Sjoerg		 * two policies a) Grab the first unused uid b) Grab the
82120253Sjoerg		 * highest possible unused uid
82220253Sjoerg		 */
82320253Sjoerg		if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
82420253Sjoerg							 * claus^H^H^H^Hheck */
82520253Sjoerg			cnf->min_uid = 1000;
82620253Sjoerg			cnf->max_uid = 32000;
82720253Sjoerg		}
82820253Sjoerg		bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
82920253Sjoerg
83020253Sjoerg		/*
83120253Sjoerg		 * Now, let's fill the bitmap from the password file
83220253Sjoerg		 */
83344229Sdavidn		SETPWENT();
83444229Sdavidn		while ((pwd = GETPWENT()) != NULL)
83544229Sdavidn			if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
83620253Sjoerg				bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
83744229Sdavidn		ENDPWENT();
83820253Sjoerg
83920253Sjoerg		/*
84020253Sjoerg		 * Then apply the policy, with fallback to reuse if necessary
84120253Sjoerg		 */
84220253Sjoerg		if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
84320253Sjoerg			uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
84420253Sjoerg
84520253Sjoerg		/*
84620253Sjoerg		 * Another sanity check
84720253Sjoerg		 */
84820253Sjoerg		if (uid < cnf->min_uid || uid > cnf->max_uid)
84930259Scharnier			errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
85020253Sjoerg		bm_dealloc(&bm);
85120253Sjoerg	}
85220253Sjoerg	return uid;
85320253Sjoerg}
85420253Sjoerg
85520253Sjoerg
85620253Sjoergstatic          uid_t
85720253Sjoergpw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer)
85820253Sjoerg{
85920253Sjoerg	struct group   *grp;
86020253Sjoerg	gid_t           gid = (uid_t) - 1;
86120253Sjoerg	struct carg    *a_gid = getarg(args, 'g');
86220253Sjoerg
86320253Sjoerg	/*
86420253Sjoerg	 * If no arg given, see if default can help out
86520253Sjoerg	 */
86620253Sjoerg	if (a_gid == NULL && cnf->default_group && *cnf->default_group)
86720253Sjoerg		a_gid = addarg(args, 'g', cnf->default_group);
86820253Sjoerg
86920253Sjoerg	/*
87020253Sjoerg	 * Check the given gid, if any
87120253Sjoerg	 */
87244229Sdavidn	SETGRENT();
87320253Sjoerg	if (a_gid != NULL) {
87444229Sdavidn		if ((grp = GETGRNAM(a_gid->val)) == NULL) {
87520253Sjoerg			gid = (gid_t) atol(a_gid->val);
87661957Sache			if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
87730259Scharnier				errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
87820253Sjoerg		}
87920253Sjoerg		gid = grp->gr_gid;
88044229Sdavidn	} else if ((grp = GETGRNAM(nam)) != NULL && grp->gr_mem[0] == NULL) {
88120267Sjoerg		gid = grp->gr_gid;  /* Already created? Use it anyway... */
88220253Sjoerg	} else {
88320253Sjoerg		struct cargs    grpargs;
88420253Sjoerg		char            tmp[32];
88520253Sjoerg
88620253Sjoerg		LIST_INIT(&grpargs);
88720253Sjoerg		addarg(&grpargs, 'n', nam);
88820253Sjoerg
88920253Sjoerg		/*
89020253Sjoerg		 * We need to auto-create a group with the user's name. We
89120253Sjoerg		 * can send all the appropriate output to our sister routine
89220253Sjoerg		 * bit first see if we can create a group with gid==uid so we
89320253Sjoerg		 * can keep the user and group ids in sync. We purposely do
89420253Sjoerg		 * NOT check the gid range if we can force the sync. If the
89520253Sjoerg		 * user's name dups an existing group, then the group add
89620253Sjoerg		 * function will happily handle that case for us and exit.
89720253Sjoerg		 */
89844229Sdavidn		if (GETGRGID(prefer) == NULL) {
89920253Sjoerg			sprintf(tmp, "%lu", (unsigned long) prefer);
90020253Sjoerg			addarg(&grpargs, 'g', tmp);
90120253Sjoerg		}
90220267Sjoerg		if (getarg(args, 'N'))
90320267Sjoerg		{
90420267Sjoerg			addarg(&grpargs, 'N', NULL);
90520267Sjoerg			addarg(&grpargs, 'q', NULL);
90620267Sjoerg			gid = pw_group(cnf, M_NEXT, &grpargs);
90720267Sjoerg		}
90820267Sjoerg		else
90920267Sjoerg		{
91020267Sjoerg			pw_group(cnf, M_ADD, &grpargs);
91144229Sdavidn			if ((grp = GETGRNAM(nam)) != NULL)
91220267Sjoerg				gid = grp->gr_gid;
91320267Sjoerg		}
91470486Sben		a_gid = LIST_FIRST(&grpargs);
91520253Sjoerg		while (a_gid != NULL) {
91670486Sben			struct carg    *t = LIST_NEXT(a_gid, list);
91720253Sjoerg			LIST_REMOVE(a_gid, list);
91820253Sjoerg			a_gid = t;
91920253Sjoerg		}
92020253Sjoerg	}
92144229Sdavidn	ENDGRENT();
92220253Sjoerg	return gid;
92320253Sjoerg}
92420253Sjoerg
92520253Sjoerg
92620253Sjoergstatic          time_t
92720253Sjoergpw_pwdpolicy(struct userconf * cnf, struct cargs * args)
92820253Sjoerg{
92920253Sjoerg	time_t          result = 0;
93020253Sjoerg	time_t          now = time(NULL);
93127831Sdavidn	struct carg    *arg = getarg(args, 'p');
93220253Sjoerg
93320253Sjoerg	if (arg != NULL) {
93420253Sjoerg		if ((result = parse_date(now, arg->val)) == now)
93530259Scharnier			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
93620253Sjoerg	} else if (cnf->password_days > 0)
93720253Sjoerg		result = now + ((long) cnf->password_days * 86400L);
93820253Sjoerg	return result;
93920253Sjoerg}
94020253Sjoerg
94120253Sjoerg
94220253Sjoergstatic          time_t
94320253Sjoergpw_exppolicy(struct userconf * cnf, struct cargs * args)
94420253Sjoerg{
94520253Sjoerg	time_t          result = 0;
94620253Sjoerg	time_t          now = time(NULL);
94720253Sjoerg	struct carg    *arg = getarg(args, 'e');
94820253Sjoerg
94920253Sjoerg	if (arg != NULL) {
95020253Sjoerg		if ((result = parse_date(now, arg->val)) == now)
95130259Scharnier			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
95220253Sjoerg	} else if (cnf->expire_days > 0)
95320253Sjoerg		result = now + ((long) cnf->expire_days * 86400L);
95420253Sjoerg	return result;
95520253Sjoerg}
95620253Sjoerg
95720253Sjoerg
95820253Sjoergstatic char    *
95920253Sjoergpw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
96020253Sjoerg{
96120253Sjoerg	struct carg    *arg = getarg(args, 'd');
96220253Sjoerg
96320253Sjoerg	if (arg)
96420253Sjoerg		return arg->val;
96520253Sjoerg	else {
96620253Sjoerg		static char     home[128];
96720253Sjoerg
96820253Sjoerg		if (cnf->home == NULL || *cnf->home == '\0')
96930259Scharnier			errx(EX_CONFIG, "no base home directory set");
97020253Sjoerg		sprintf(home, "%s/%s", cnf->home, user);
97120253Sjoerg		return home;
97220253Sjoerg	}
97320253Sjoerg}
97420253Sjoerg
97520253Sjoergstatic char    *
97620253Sjoergshell_path(char const * path, char *shells[], char *sh)
97720253Sjoerg{
97820253Sjoerg	if (sh != NULL && (*sh == '/' || *sh == '\0'))
97920253Sjoerg		return sh;	/* specified full path or forced none */
98020253Sjoerg	else {
98120253Sjoerg		char           *p;
98220253Sjoerg		char            paths[_UC_MAXLINE];
98320253Sjoerg
98420253Sjoerg		/*
98520253Sjoerg		 * We need to search paths
98620253Sjoerg		 */
987130633Srobert		strlcpy(paths, path, sizeof(paths));
98820253Sjoerg		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
98920253Sjoerg			int             i;
99020253Sjoerg			static char     shellpath[256];
99120253Sjoerg
99220253Sjoerg			if (sh != NULL) {
99320253Sjoerg				sprintf(shellpath, "%s/%s", p, sh);
99420253Sjoerg				if (access(shellpath, X_OK) == 0)
99520253Sjoerg					return shellpath;
99620253Sjoerg			} else
99720253Sjoerg				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
99820253Sjoerg					sprintf(shellpath, "%s/%s", p, shells[i]);
99920253Sjoerg					if (access(shellpath, X_OK) == 0)
100020253Sjoerg						return shellpath;
100120253Sjoerg				}
100220253Sjoerg		}
100320253Sjoerg		if (sh == NULL)
100430259Scharnier			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
100530259Scharnier		errx(EX_CONFIG, "no default shell available or defined");
100620253Sjoerg		return NULL;
100720253Sjoerg	}
100820253Sjoerg}
100920253Sjoerg
101020253Sjoerg
101120253Sjoergstatic char    *
101220253Sjoergpw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
101320253Sjoerg{
101420253Sjoerg	char           *sh = newshell;
101520253Sjoerg	struct carg    *arg = getarg(args, 's');
101620253Sjoerg
101720253Sjoerg	if (newshell == NULL && arg != NULL)
101820253Sjoerg		sh = arg->val;
101920253Sjoerg	return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
102020253Sjoerg}
102120253Sjoerg
1022179365Santoine#define	SALTSIZE	32
102320253Sjoerg
1024179365Santoinestatic char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1025179365Santoine
102620253Sjoergchar           *
102720253Sjoergpw_pwcrypt(char *password)
102820253Sjoerg{
102920253Sjoerg	int             i;
1030179365Santoine	char            salt[SALTSIZE + 1];
103120253Sjoerg
103220253Sjoerg	static char     buf[256];
103320253Sjoerg
103420253Sjoerg	/*
103520253Sjoerg	 * Calculate a salt value
103620253Sjoerg	 */
1037179365Santoine	for (i = 0; i < SALTSIZE; i++)
1038181785Sache		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1039179365Santoine	salt[SALTSIZE] = '\0';
104020253Sjoerg
104120253Sjoerg	return strcpy(buf, crypt(password, salt));
104220253Sjoerg}
104320253Sjoerg
104420590Sdavidn
104520253Sjoergstatic char    *
104620253Sjoergpw_password(struct userconf * cnf, struct cargs * args, char const * user)
104720253Sjoerg{
104820253Sjoerg	int             i, l;
104920253Sjoerg	char            pwbuf[32];
105020253Sjoerg
105120253Sjoerg	switch (cnf->default_password) {
105220253Sjoerg	case -1:		/* Random password */
105373563Skris		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
105420253Sjoerg		for (i = 0; i < l; i++)
1055181785Sache			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
105620253Sjoerg		pwbuf[i] = '\0';
105720253Sjoerg
105820253Sjoerg		/*
105920253Sjoerg		 * We give this information back to the user
106020253Sjoerg		 */
1061124382Siedowse		if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
1062124382Siedowse		    getarg(args, 'N') == NULL) {
106361957Sache			if (isatty(STDOUT_FILENO))
106420712Sdavidn				printf("Password for '%s' is: ", user);
106520253Sjoerg			printf("%s\n", pwbuf);
106620253Sjoerg			fflush(stdout);
106720253Sjoerg		}
106820253Sjoerg		break;
106920253Sjoerg
107020253Sjoerg	case -2:		/* No password at all! */
107120253Sjoerg		return "";
107220253Sjoerg
107320253Sjoerg	case 0:		/* No login - default */
107420253Sjoerg	default:
107520253Sjoerg		return "*";
107620253Sjoerg
107720253Sjoerg	case 1:		/* user's name */
1078130633Srobert		strlcpy(pwbuf, user, sizeof(pwbuf));
107920253Sjoerg		break;
108020253Sjoerg	}
108120253Sjoerg	return pw_pwcrypt(pwbuf);
108220253Sjoerg}
108320253Sjoerg
108420253Sjoerg
108520253Sjoergstatic int
108644386Sdavidnprint_user(struct passwd * pwd, int pretty, int v7)
108720253Sjoerg{
108820253Sjoerg	if (!pretty) {
108920253Sjoerg		char            buf[_UC_MAXLINE];
109020253Sjoerg
109144386Sdavidn		fmtpwentry(buf, pwd, v7 ? PWF_PASSWD : PWF_STANDARD);
109220253Sjoerg		fputs(buf, stdout);
109320253Sjoerg	} else {
109420267Sjoerg		int		j;
109520253Sjoerg		char           *p;
109644229Sdavidn		struct group   *grp = GETGRGID(pwd->pw_gid);
109720253Sjoerg		char            uname[60] = "User &", office[60] = "[None]",
109820253Sjoerg		                wphone[60] = "[None]", hphone[60] = "[None]";
109920590Sdavidn		char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
110020590Sdavidn		struct tm *    tptr;
110120253Sjoerg
110220253Sjoerg		if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1103130633Srobert			strlcpy(uname, p, sizeof(uname));
110420253Sjoerg			if ((p = strtok(NULL, ",")) != NULL) {
1105130633Srobert				strlcpy(office, p, sizeof(office));
110620253Sjoerg				if ((p = strtok(NULL, ",")) != NULL) {
1107130633Srobert					strlcpy(wphone, p, sizeof(wphone));
110820253Sjoerg					if ((p = strtok(NULL, "")) != NULL) {
1109130633Srobert						strlcpy(hphone, p,
1110130633Srobert						    sizeof(hphone));
111120253Sjoerg					}
111220253Sjoerg				}
111320253Sjoerg			}
111420253Sjoerg		}
111520253Sjoerg		/*
111620253Sjoerg		 * Handle '&' in gecos field
111720253Sjoerg		 */
111820253Sjoerg		if ((p = strchr(uname, '&')) != NULL) {
111920253Sjoerg			int             l = strlen(pwd->pw_name);
112020253Sjoerg			int             m = strlen(p);
112120253Sjoerg
112220253Sjoerg			memmove(p + l, p + 1, m);
112320253Sjoerg			memmove(p, pwd->pw_name, l);
112461957Sache			*p = (char) toupper((unsigned char)*p);
112520253Sjoerg		}
112620590Sdavidn		if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
112774569Sache			strftime(acexpire, sizeof acexpire, "%c", tptr);
112861957Sache		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
112974569Sache			strftime(pwexpire, sizeof pwexpire, "%c", tptr);
113022394Sdavidn		printf("Login Name: %-15s   #%-12ld Group: %-15s   #%ld\n"
113120747Sdavidn		       " Full Name: %s\n"
113220747Sdavidn		       "      Home: %-26.26s      Class: %s\n"
113320747Sdavidn		       "     Shell: %-26.26s     Office: %s\n"
113420747Sdavidn		       "Work Phone: %-26.26s Home Phone: %s\n"
113520747Sdavidn		       "Acc Expire: %-26.26s Pwd Expire: %s\n",
113620253Sjoerg		       pwd->pw_name, (long) pwd->pw_uid,
113720253Sjoerg		       grp ? grp->gr_name : "(invalid)", (long) pwd->pw_gid,
113820253Sjoerg		       uname, pwd->pw_dir, pwd->pw_class,
113920590Sdavidn		       pwd->pw_shell, office, wphone, hphone,
114020590Sdavidn		       acexpire, pwexpire);
114144229Sdavidn	        SETGRENT();
114220267Sjoerg		j = 0;
114344229Sdavidn		while ((grp=GETGRENT()) != NULL)
114420267Sjoerg		{
114520267Sjoerg			int     i = 0;
114620747Sdavidn			while (grp->gr_mem[i] != NULL)
114720267Sjoerg			{
114820267Sjoerg				if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
114920267Sjoerg				{
115020747Sdavidn					printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
115120267Sjoerg					break;
115220267Sjoerg				}
115320267Sjoerg				++i;
115420267Sjoerg			}
115520267Sjoerg		}
115644229Sdavidn		ENDGRENT();
115761957Sache		printf("%s", j ? "\n" : "");
115820253Sjoerg	}
115920267Sjoerg	return EXIT_SUCCESS;
116020253Sjoerg}
116120253Sjoerg
116220679Sdavidnchar    *
116320679Sdavidnpw_checkname(u_char *name, int gecos)
116420253Sjoerg{
1165109961Sgad	char showch[8];
1166109961Sgad	u_char const *badchars, *ch, *showtype;
1167109961Sgad	int reject;
116820253Sjoerg
1169109961Sgad	ch = name;
1170109961Sgad	reject = 0;
1171109961Sgad	if (gecos) {
1172109961Sgad		/* See if the name is valid as a gecos (comment) field. */
1173109961Sgad		badchars = ":!@";
1174109961Sgad		showtype = "gecos field";
1175109961Sgad	} else {
1176109961Sgad		/* See if the name is valid as a userid or group. */
1177109961Sgad		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1178109961Sgad		showtype = "userid/group name";
1179109961Sgad		/* Userids and groups can not have a leading '-'. */
1180109961Sgad		if (*ch == '-')
1181109961Sgad			reject = 1;
118220253Sjoerg	}
1183109961Sgad	if (!reject) {
1184109961Sgad		while (*ch) {
1185109961Sgad			if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1186109961Sgad			    *ch == 127) {
1187109961Sgad				reject = 1;
1188109961Sgad				break;
1189109961Sgad			}
1190109961Sgad			/* 8-bit characters are only allowed in GECOS fields */
1191109961Sgad			if (!gecos && (*ch & 0x80)) {
1192109961Sgad				reject = 1;
1193109961Sgad				break;
1194109961Sgad			}
1195109961Sgad			ch++;
1196109961Sgad		}
1197109961Sgad	}
1198109961Sgad	/*
1199109961Sgad	 * A `$' is allowed as the final character for userids and groups,
1200109961Sgad	 * mainly for the benefit of samba.
1201109961Sgad	 */
1202109961Sgad	if (reject && !gecos) {
1203109961Sgad		if (*ch == '$' && *(ch + 1) == '\0') {
1204109961Sgad			reject = 0;
1205109961Sgad			ch++;
1206109961Sgad		}
1207109961Sgad	}
1208109961Sgad	if (reject) {
1209109961Sgad		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1210109961Sgad		    ? "`%c'" : "0x%02x", *ch);
1211229237Sdim		errx(EX_DATAERR, "invalid character %s at position %td in %s",
1212109961Sgad		    showch, (ch - name), showtype);
1213109961Sgad	}
1214109961Sgad	if (!gecos && (ch - name) > LOGNAMESIZE)
1215109961Sgad		errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1216109961Sgad		    LOGNAMESIZE);
121720679Sdavidn	return (char *)name;
121820253Sjoerg}
121920253Sjoerg
122020253Sjoerg
122120253Sjoergstatic void
122220253Sjoergrmat(uid_t uid)
122320253Sjoerg{
122420253Sjoerg	DIR            *d = opendir("/var/at/jobs");
122520253Sjoerg
122620253Sjoerg	if (d != NULL) {
122720253Sjoerg		struct dirent  *e;
122820253Sjoerg
122920253Sjoerg		while ((e = readdir(d)) != NULL) {
123020253Sjoerg			struct stat     st;
123120253Sjoerg
123220253Sjoerg			if (strncmp(e->d_name, ".lock", 5) != 0 &&
123320253Sjoerg			    stat(e->d_name, &st) == 0 &&
123420253Sjoerg			    !S_ISDIR(st.st_mode) &&
123520253Sjoerg			    st.st_uid == uid) {
123620253Sjoerg				char            tmp[MAXPATHLEN];
123720253Sjoerg
123820253Sjoerg				sprintf(tmp, "/usr/bin/atrm %s", e->d_name);
123920253Sjoerg				system(tmp);
124020253Sjoerg			}
124120253Sjoerg		}
124220253Sjoerg		closedir(d);
124320253Sjoerg	}
124420253Sjoerg}
124520747Sdavidn
124620747Sdavidnstatic void
124785145Sachermopie(char const * name)
124820747Sdavidn{
124985145Sache	static const char etcopie[] = "/etc/opiekeys";
125085145Sache	FILE   *fp = fopen(etcopie, "r+");
125120747Sdavidn
125221052Sdavidn	if (fp != NULL) {
125321052Sdavidn		char	tmp[1024];
125421052Sdavidn		off_t	atofs = 0;
125521052Sdavidn		int	length = strlen(name);
125620747Sdavidn
125721052Sdavidn		while (fgets(tmp, sizeof tmp, fp) != NULL) {
125821052Sdavidn			if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
125921052Sdavidn				if (fseek(fp, atofs, SEEK_SET) == 0) {
126021052Sdavidn					fwrite("#", 1, 1, fp);	/* Comment username out */
126121052Sdavidn				}
126221052Sdavidn				break;
126320747Sdavidn			}
126421052Sdavidn			atofs = ftell(fp);
126520747Sdavidn		}
126621052Sdavidn		/*
126721052Sdavidn		 * If we got an error of any sort, don't update!
126821052Sdavidn		 */
126921052Sdavidn		fclose(fp);
127020747Sdavidn	}
127120747Sdavidn}
127220747Sdavidn
1273