pw_user.c revision 284149
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: head/usr.sbin/pw/pw_user.c 284149 2015-06-08 05:27:34Z 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>
4364918Sgreen#include <login_cap.h>
44242349Sbapt#include <pwd.h>
45242349Sbapt#include <grp.h>
46242349Sbapt#include <libutil.h>
4720253Sjoerg#include "pw.h"
4820253Sjoerg#include "bitmap.h"
4920253Sjoerg
5023318Sache#define LOGNAMESIZE (MAXLOGNAME-1)
5122394Sdavidn
5252512Sdavidnstatic		char locked_str[] = "*LOCKED*";
5324214Sache
54284111Sbaptstatic int	delete_user(struct userconf *cnf, struct passwd *pwd,
55284128Sbapt		    char *name, int delete, int mode);
56284124Sbaptstatic int	print_user(struct passwd * pwd);
57284133Sbaptstatic uid_t    pw_uidpolicy(struct userconf * cnf, long id);
58284118Sbaptstatic uid_t    pw_gidpolicy(struct cargs * args, char *nam, gid_t prefer);
5920253Sjoergstatic time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
6020253Sjoergstatic time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
6120253Sjoergstatic char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
6220253Sjoergstatic char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
6320253Sjoergstatic char    *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
6420253Sjoergstatic char    *shell_path(char const * path, char *shells[], char *sh);
6520253Sjoergstatic void     rmat(uid_t uid);
6685145Sachestatic void     rmopie(char const * name);
6720253Sjoerg
68283961Sbaptstatic void
69284118Sbaptcreate_and_populate_homedir(int mode, struct passwd *pwd)
70283961Sbapt{
71283961Sbapt	char *homedir, *dotdir;
72284118Sbapt	struct userconf *cnf = conf.userconf;
73283961Sbapt
74283961Sbapt	homedir = dotdir = NULL;
75283961Sbapt
76284118Sbapt	if (conf.rootdir[0] != '\0') {
77284118Sbapt		asprintf(&homedir, "%s/%s", conf.rootdir, pwd->pw_dir);
78283961Sbapt		if (homedir == NULL)
79283961Sbapt			errx(EX_OSERR, "out of memory");
80284118Sbapt		asprintf(&dotdir, "%s/%s", conf.rootdir, cnf->dotdir);
81283961Sbapt	}
82283961Sbapt
83283961Sbapt	copymkdir(homedir ? homedir : pwd->pw_dir, dotdir ? dotdir: cnf->dotdir,
84283961Sbapt	    cnf->homemode, pwd->pw_uid, pwd->pw_gid);
85283961Sbapt	pw_log(cnf, mode, W_USER, "%s(%u) home %s made", pwd->pw_name,
86283961Sbapt	    pwd->pw_uid, pwd->pw_dir);
87283961Sbapt}
88283961Sbapt
8920253Sjoerg/*-
9020253Sjoerg * -C config      configuration file
9120253Sjoerg * -q             quiet operation
9220253Sjoerg * -n name        login name
9320253Sjoerg * -u uid         user id
9420253Sjoerg * -c comment     user name/comment
9520253Sjoerg * -d directory   home directory
9620253Sjoerg * -e date        account expiry date
9720253Sjoerg * -p date        password expiry date
9820253Sjoerg * -g grp         primary group
9920253Sjoerg * -G grp1,grp2   additional groups
10020253Sjoerg * -m [ -k dir ]  create and set up home
10120253Sjoerg * -s shell       name of login shell
10220253Sjoerg * -o             duplicate uid ok
10320253Sjoerg * -L class       user class
10420253Sjoerg * -l name        new login name
10520253Sjoerg * -h fd          password filehandle
106124382Siedowse * -H fd          encrypted password filehandle
10720253Sjoerg * -F             force print or add
10820253Sjoerg *   Setting defaults:
10920253Sjoerg * -D             set user defaults
11020253Sjoerg * -b dir         default home root dir
11120253Sjoerg * -e period      default expiry period
11220253Sjoerg * -p period      default password change period
11320253Sjoerg * -g group       default group
11420253Sjoerg * -G             grp1,grp2.. default additional groups
11520253Sjoerg * -L class       default login class
11620253Sjoerg * -k dir         default home skeleton
11720253Sjoerg * -s shell       default shell
11820253Sjoerg * -w method      default password method
11920253Sjoerg */
12020253Sjoerg
12120253Sjoergint
122284128Sbaptpw_user(int mode, char *name, long id, struct cargs * args)
12320253Sjoerg{
12452527Sdavidn	int	        rc, edited = 0;
12520253Sjoerg	char           *p = NULL;
12652512Sdavidn	char					 *passtmp;
12720253Sjoerg	struct carg    *arg;
12820253Sjoerg	struct passwd  *pwd = NULL;
12920253Sjoerg	struct group   *grp;
13020253Sjoerg	struct stat     st;
131284118Sbapt	struct userconf	*cnf;
13220747Sdavidn	char            line[_PASSWORD_LEN+1];
133283961Sbapt	char		path[MAXPATHLEN];
13482868Sdd	FILE	       *fp;
135167919Sle	char *dmode_c;
136167919Sle	void *set = NULL;
13720253Sjoerg
13820253Sjoerg	static struct passwd fakeuser =
13920253Sjoerg	{
14020253Sjoerg		NULL,
14120253Sjoerg		"*",
14220253Sjoerg		-1,
14320253Sjoerg		-1,
14420253Sjoerg		0,
14520253Sjoerg		"",
14620253Sjoerg		"User &",
14756000Sdavidn		"/nonexistent",
14820253Sjoerg		"/bin/sh",
14920253Sjoerg		0
15056000Sdavidn#if defined(__FreeBSD__)
15156000Sdavidn		,0
15256000Sdavidn#endif
15320253Sjoerg	};
15420253Sjoerg
155284118Sbapt	cnf = conf.userconf;
15652512Sdavidn
15720253Sjoerg	/*
15820267Sjoerg	 * With M_NEXT, we only need to return the
15920267Sjoerg	 * next uid to stdout
16020267Sjoerg	 */
161284149Sbapt	if (mode == M_NEXT)
162284149Sbapt	{
163284149Sbapt		uid_t next = pw_uidpolicy(cnf, id);
164284149Sbapt		if (getarg(args, 'q'))
165284149Sbapt			return next;
166284149Sbapt		printf("%u:", next);
167284128Sbapt		pw_group(mode, name, -1, args);
168284149Sbapt		return EXIT_SUCCESS;
16920267Sjoerg	}
17020267Sjoerg
17120267Sjoerg	/*
17220253Sjoerg	 * We can do all of the common legwork here
17320253Sjoerg	 */
17420253Sjoerg
17520253Sjoerg	if ((arg = getarg(args, 'b')) != NULL) {
17620267Sjoerg		cnf->home = arg->val;
17720253Sjoerg	}
17821052Sdavidn
179167919Sle	if ((arg = getarg(args, 'M')) != NULL) {
180167919Sle		dmode_c = arg->val;
181167919Sle		if ((set = setmode(dmode_c)) == NULL)
182167919Sle			errx(EX_DATAERR, "invalid directory creation mode '%s'",
183167919Sle			    dmode_c);
184219408Sjkim		cnf->homemode = getmode(set, _DEF_DIRMODE);
185167919Sle		free(set);
186168044Sle	}
187167919Sle
18821052Sdavidn	/*
18921052Sdavidn	 * If we'll need to use it or we're updating it,
19021052Sdavidn	 * then create the base home directory if necessary
19121052Sdavidn	 */
192224535Sdelphij	if (arg != NULL || getarg(args, 'm') != NULL) {
19321052Sdavidn		int	l = strlen(cnf->home);
19421052Sdavidn
19521052Sdavidn		if (l > 1 && cnf->home[l-1] == '/')	/* Shave off any trailing path delimiter */
19621052Sdavidn			cnf->home[--l] = '\0';
19721052Sdavidn
19821052Sdavidn		if (l < 2 || *cnf->home != '/')		/* Check for absolute path name */
19930259Scharnier			errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
20021052Sdavidn
20121052Sdavidn		if (stat(cnf->home, &st) == -1) {
20221052Sdavidn			char	dbuf[MAXPATHLEN];
20321052Sdavidn
20421242Sdavidn			/*
20521242Sdavidn			 * This is a kludge especially for Joerg :)
20621242Sdavidn			 * If the home directory would be created in the root partition, then
20721242Sdavidn			 * we really create it under /usr which is likely to have more space.
20821242Sdavidn			 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
20921242Sdavidn			 */
21021242Sdavidn			if (strchr(cnf->home+1, '/') == NULL) {
211282683Sbapt				snprintf(dbuf, MAXPATHLEN, "/usr%s", cnf->home);
212219408Sjkim				if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
21321242Sdavidn					chown(dbuf, 0, 0);
214148584Spjd					/*
215148584Spjd					 * Skip first "/" and create symlink:
216148584Spjd					 * /home -> usr/home
217148584Spjd					 */
218148584Spjd					symlink(dbuf+1, cnf->home);
21921242Sdavidn				}
22021242Sdavidn				/* If this falls, fall back to old method */
22121242Sdavidn			}
222130633Srobert			strlcpy(dbuf, cnf->home, sizeof(dbuf));
223130633Srobert			p = dbuf;
22421242Sdavidn			if (stat(dbuf, &st) == -1) {
225252377Skientzle				while ((p = strchr(p + 1, '/')) != NULL) {
22621242Sdavidn					*p = '\0';
22721242Sdavidn					if (stat(dbuf, &st) == -1) {
228219408Sjkim						if (mkdir(dbuf, _DEF_DIRMODE) == -1)
22921242Sdavidn							goto direrr;
23021242Sdavidn						chown(dbuf, 0, 0);
23121242Sdavidn					} else if (!S_ISDIR(st.st_mode))
23230259Scharnier						errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
23321242Sdavidn					*p = '/';
23421242Sdavidn				}
23521052Sdavidn			}
23621242Sdavidn			if (stat(dbuf, &st) == -1) {
237219408Sjkim				if (mkdir(dbuf, _DEF_DIRMODE) == -1) {
23830259Scharnier				direrr:	err(EX_OSFILE, "mkdir '%s'", dbuf);
23921052Sdavidn				}
24021052Sdavidn				chown(dbuf, 0, 0);
24121052Sdavidn			}
24221052Sdavidn		} else if (!S_ISDIR(st.st_mode))
24330259Scharnier			errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
24421052Sdavidn	}
24521052Sdavidn
24620253Sjoerg	if ((arg = getarg(args, 'e')) != NULL)
24720253Sjoerg		cnf->expire_days = atoi(arg->val);
24820253Sjoerg
24921330Sdavidn	if ((arg = getarg(args, 'y')) != NULL)
25021330Sdavidn		cnf->nispasswd = arg->val;
25121330Sdavidn
25220253Sjoerg	if ((arg = getarg(args, 'p')) != NULL && arg->val)
25320253Sjoerg		cnf->password_days = atoi(arg->val);
25420253Sjoerg
25520253Sjoerg	if ((arg = getarg(args, 'g')) != NULL) {
25663596Sdavidn		if (!*(p = arg->val))	/* Handle empty group list specially */
25763596Sdavidn			cnf->default_group = "";
25863596Sdavidn		else {
25963596Sdavidn			if ((grp = GETGRNAM(p)) == NULL) {
26063596Sdavidn				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
26163596Sdavidn					errx(EX_NOUSER, "group `%s' does not exist", p);
26263596Sdavidn			}
26363596Sdavidn			cnf->default_group = newstr(grp->gr_name);
26420253Sjoerg		}
26520253Sjoerg	}
26620253Sjoerg	if ((arg = getarg(args, 'L')) != NULL)
267284110Sbapt		cnf->default_class = pw_checkname(arg->val, 0);
26820253Sjoerg
26920253Sjoerg	if ((arg = getarg(args, 'G')) != NULL && arg->val) {
27052527Sdavidn		int i = 0;
27120253Sjoerg
27220747Sdavidn		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
27344229Sdavidn			if ((grp = GETGRNAM(p)) == NULL) {
27461957Sache				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
27530259Scharnier					errx(EX_NOUSER, "group `%s' does not exist", p);
27620253Sjoerg			}
27720747Sdavidn			if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
27820747Sdavidn				cnf->groups[i++] = newstr(grp->gr_name);
27920253Sjoerg		}
28020747Sdavidn		while (i < cnf->numgroups)
28120253Sjoerg			cnf->groups[i++] = NULL;
28220253Sjoerg	}
28352527Sdavidn
28420253Sjoerg	if ((arg = getarg(args, 'k')) != NULL) {
28526088Sdavidn		if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
28630259Scharnier			errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
28720253Sjoerg	}
28852527Sdavidn
28920253Sjoerg	if ((arg = getarg(args, 's')) != NULL)
29020253Sjoerg		cnf->shell_default = arg->val;
29120253Sjoerg
29263600Sdavidn	if ((arg = getarg(args, 'w')) != NULL)
29363600Sdavidn		cnf->default_password = boolean_val(arg->val, cnf->default_password);
29420253Sjoerg	if (mode == M_ADD && getarg(args, 'D')) {
295284135Sbapt		if (name != NULL)
29630259Scharnier			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
29720253Sjoerg		if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
29820253Sjoerg			if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
29920253Sjoerg				cnf->min_uid = 1000;
30020253Sjoerg			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
30120253Sjoerg				cnf->max_uid = 32000;
30220253Sjoerg		}
30320253Sjoerg		if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
30420253Sjoerg			if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
30520253Sjoerg				cnf->min_gid = 1000;
30620253Sjoerg			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
30720253Sjoerg				cnf->max_gid = 32000;
30820253Sjoerg		}
30920253Sjoerg
310284135Sbapt		if (write_userconfig(conf.config))
311284135Sbapt			return (EXIT_SUCCESS);
312283814Sbapt		err(EX_IOERR, "config udpate");
31320253Sjoerg	}
31452527Sdavidn
31520253Sjoerg	if (mode == M_PRINT && getarg(args, 'a')) {
31644229Sdavidn		SETPWENT();
31744229Sdavidn		while ((pwd = GETPWENT()) != NULL)
318284124Sbapt			print_user(pwd);
31944229Sdavidn		ENDPWENT();
32020267Sjoerg		return EXIT_SUCCESS;
32120253Sjoerg	}
32252527Sdavidn
323284128Sbapt	if (name != NULL)
324284128Sbapt		pwd = GETPWNAM(pw_checkname(name, 0));
32520253Sjoerg
326284128Sbapt	if (id < 0 && name == NULL)
327284128Sbapt		errx(EX_DATAERR, "user name or id required");
32820253Sjoerg
32920253Sjoerg	/*
33020253Sjoerg	 * Update, delete & print require that the user exists
33120253Sjoerg	 */
33252512Sdavidn	if (mode == M_UPDATE || mode == M_DELETE ||
33352512Sdavidn	    mode == M_PRINT  || mode == M_LOCK   || mode == M_UNLOCK) {
33452527Sdavidn
335284128Sbapt		if (name == NULL && pwd == NULL)	/* Try harder */
336284128Sbapt			pwd = GETPWUID(id);
33720253Sjoerg
33820253Sjoerg		if (pwd == NULL) {
33920253Sjoerg			if (mode == M_PRINT && getarg(args, 'F')) {
340284128Sbapt				fakeuser.pw_name = name ? name : "nouser";
341284128Sbapt				fakeuser.pw_uid = (uid_t) id;
342284126Sbapt				return print_user(&fakeuser);
34320253Sjoerg			}
344284128Sbapt			if (name == NULL)
345284128Sbapt				errx(EX_NOUSER, "no such uid `%ld'", id);
346284128Sbapt			errx(EX_NOUSER, "no such user `%s'", name);
34720253Sjoerg		}
34852527Sdavidn
349284128Sbapt		if (name == NULL)
350284128Sbapt			name = pwd->pw_name;
35120253Sjoerg
35220253Sjoerg		/*
35352512Sdavidn		 * The M_LOCK and M_UNLOCK functions simply add or remove
35452512Sdavidn		 * a "*LOCKED*" prefix from in front of the password to
35552512Sdavidn		 * prevent it decoding correctly, and therefore prevents
35652512Sdavidn		 * access. Of course, this only prevents access via
35752512Sdavidn		 * password authentication (not ssh, kerberos or any
35852512Sdavidn		 * other method that does not use the UNIX password) but
35952512Sdavidn		 * that is a known limitation.
36052512Sdavidn		 */
36152512Sdavidn
36252512Sdavidn		if (mode == M_LOCK) {
36352512Sdavidn			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
36452512Sdavidn				errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
365282685Sbapt			asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
36652512Sdavidn			if (passtmp == NULL)	/* disaster */
36752512Sdavidn				errx(EX_UNAVAILABLE, "out of memory");
36852512Sdavidn			pwd->pw_passwd = passtmp;
36952527Sdavidn			edited = 1;
37052512Sdavidn		} else if (mode == M_UNLOCK) {
37152512Sdavidn			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
37252512Sdavidn				errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
37352512Sdavidn			pwd->pw_passwd += sizeof(locked_str)-1;
37452527Sdavidn			edited = 1;
375284111Sbapt		} else if (mode == M_DELETE)
376284128Sbapt			return (delete_user(cnf, pwd, name,
377284111Sbapt				    getarg(args, 'r') != NULL, mode));
378284111Sbapt		else if (mode == M_PRINT)
379284126Sbapt			return print_user(pwd);
38020253Sjoerg
38120253Sjoerg		/*
38220253Sjoerg		 * The rest is edit code
38320253Sjoerg		 */
384284129Sbapt		if (conf.newname != NULL) {
38520253Sjoerg			if (strcmp(pwd->pw_name, "root") == 0)
38630259Scharnier				errx(EX_DATAERR, "can't rename `root' account");
387284129Sbapt			pwd->pw_name = pw_checkname(conf.newname, 0);
38852527Sdavidn			edited = 1;
38920253Sjoerg		}
39052527Sdavidn
391284133Sbapt		if (id > 0 && isdigit((unsigned char)*arg->val)) {
392284133Sbapt			pwd->pw_uid = (uid_t)id;
39352527Sdavidn			edited = 1;
39420253Sjoerg			if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
39530259Scharnier				errx(EX_DATAERR, "can't change uid of `root' account");
39620253Sjoerg			if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
39730259Scharnier				warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
39820253Sjoerg		}
39920253Sjoerg
40052527Sdavidn		if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {	/* Already checked this */
40152527Sdavidn			gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
40252527Sdavidn			if (newgid != pwd->pw_gid) {
40352527Sdavidn				edited = 1;
40461762Sdavidn				pwd->pw_gid = newgid;
40552527Sdavidn			}
40652527Sdavidn		}
40752527Sdavidn
40820253Sjoerg		if ((arg = getarg(args, 'p')) != NULL) {
40952527Sdavidn			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
41052527Sdavidn				if (pwd->pw_change != 0) {
41152527Sdavidn					pwd->pw_change = 0;
41252527Sdavidn					edited = 1;
41352527Sdavidn				}
41452527Sdavidn			}
41520253Sjoerg			else {
41620253Sjoerg				time_t          now = time(NULL);
41720253Sjoerg				time_t          expire = parse_date(now, arg->val);
41820253Sjoerg
41952527Sdavidn				if (pwd->pw_change != expire) {
42052527Sdavidn					pwd->pw_change = expire;
42152527Sdavidn					edited = 1;
42252527Sdavidn				}
42320253Sjoerg			}
42420253Sjoerg		}
42552527Sdavidn
42620267Sjoerg		if ((arg = getarg(args, 'e')) != NULL) {
42752527Sdavidn			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
42852527Sdavidn				if (pwd->pw_expire != 0) {
42952527Sdavidn					pwd->pw_expire = 0;
43052527Sdavidn					edited = 1;
43152527Sdavidn				}
43252527Sdavidn			}
43320253Sjoerg			else {
43420253Sjoerg				time_t          now = time(NULL);
43520253Sjoerg				time_t          expire = parse_date(now, arg->val);
43620253Sjoerg
43752527Sdavidn				if (pwd->pw_expire != expire) {
43852527Sdavidn					pwd->pw_expire = expire;
43952527Sdavidn					edited = 1;
44052527Sdavidn				}
44120253Sjoerg			}
44220253Sjoerg		}
44320253Sjoerg
44452527Sdavidn		if ((arg = getarg(args, 's')) != NULL) {
44552527Sdavidn			char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
44652527Sdavidn			if (shell == NULL)
44752527Sdavidn				shell = "";
44852527Sdavidn			if (strcmp(shell, pwd->pw_shell) != 0) {
44952527Sdavidn				pwd->pw_shell = shell;
45052527Sdavidn				edited = 1;
45152527Sdavidn			}
45252527Sdavidn		}
45320253Sjoerg
45452527Sdavidn		if (getarg(args, 'L')) {
45552527Sdavidn			if (cnf->default_class == NULL)
45652527Sdavidn				cnf->default_class = "";
45752527Sdavidn			if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
45852527Sdavidn				pwd->pw_class = cnf->default_class;
45952527Sdavidn				edited = 1;
46052527Sdavidn			}
46152527Sdavidn		}
46252527Sdavidn
46320747Sdavidn		if ((arg  = getarg(args, 'd')) != NULL) {
464130629Srobert			if (strcmp(pwd->pw_dir, arg->val))
465130629Srobert				edited = 1;
46620747Sdavidn			if (stat(pwd->pw_dir = arg->val, &st) == -1) {
46720747Sdavidn				if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
46830259Scharnier				  warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
46920747Sdavidn			} else if (!S_ISDIR(st.st_mode))
47030259Scharnier				warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
47120747Sdavidn		}
47220747Sdavidn
473124382Siedowse		if ((arg = getarg(args, 'w')) != NULL &&
474124382Siedowse		    getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
47564918Sgreen			login_cap_t *lc;
47664918Sgreen
47764918Sgreen			lc = login_getpwclass(pwd);
47864918Sgreen			if (lc == NULL ||
479252688Sdes			    login_setcryptfmt(lc, "sha512", NULL) == NULL)
48064918Sgreen				warn("setting crypt(3) format");
48164918Sgreen			login_close(lc);
48220267Sjoerg			pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
48352527Sdavidn			edited = 1;
48452527Sdavidn		}
48520267Sjoerg
48620253Sjoerg	} else {
48764918Sgreen		login_cap_t *lc;
48852527Sdavidn
48952527Sdavidn		/*
49052527Sdavidn		 * Add code
49152527Sdavidn		 */
49252527Sdavidn
493284128Sbapt		if (name == NULL)	/* Required */
49430259Scharnier			errx(EX_DATAERR, "login name required");
495284128Sbapt		else if ((pwd = GETPWNAM(name)) != NULL)	/* Exists */
496284128Sbapt			errx(EX_DATAERR, "login name `%s' already exists", name);
49720253Sjoerg
49820253Sjoerg		/*
49920253Sjoerg		 * Now, set up defaults for a new user
50020253Sjoerg		 */
50120253Sjoerg		pwd = &fakeuser;
502284128Sbapt		pwd->pw_name = name;
50320253Sjoerg		pwd->pw_class = cnf->default_class ? cnf->default_class : "";
504284133Sbapt		pwd->pw_uid = pw_uidpolicy(cnf, id);
505284118Sbapt		pwd->pw_gid = pw_gidpolicy(args, pwd->pw_name, (gid_t) pwd->pw_uid);
50620253Sjoerg		pwd->pw_change = pw_pwdpolicy(cnf, args);
50720253Sjoerg		pwd->pw_expire = pw_exppolicy(cnf, args);
50820253Sjoerg		pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
50920253Sjoerg		pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
51064918Sgreen		lc = login_getpwclass(pwd);
511272833Sdes		if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
51264918Sgreen			warn("setting crypt(3) format");
51364918Sgreen		login_close(lc);
51464918Sgreen		pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
51552527Sdavidn		edited = 1;
51620253Sjoerg
51720253Sjoerg		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
51830259Scharnier			warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
51920253Sjoerg	}
52020253Sjoerg
52120253Sjoerg	/*
52220253Sjoerg	 * Shared add/edit code
52320253Sjoerg	 */
52452527Sdavidn	if ((arg = getarg(args, 'c')) != NULL) {
525284110Sbapt		char	*gecos = pw_checkname(arg->val, 1);
52652527Sdavidn		if (strcmp(pwd->pw_gecos, gecos) != 0) {
52752527Sdavidn			pwd->pw_gecos = gecos;
52852527Sdavidn			edited = 1;
52952527Sdavidn		}
53052527Sdavidn	}
53120253Sjoerg
532124382Siedowse	if ((arg = getarg(args, 'h')) != NULL ||
533124382Siedowse	    (arg = getarg(args, 'H')) != NULL) {
53463572Sdavidn		if (strcmp(arg->val, "-") == 0) {
53563572Sdavidn			if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
53663572Sdavidn				pwd->pw_passwd = "*";	/* No access */
53763572Sdavidn				edited = 1;
53863572Sdavidn			}
53963572Sdavidn		} else {
54020253Sjoerg			int             fd = atoi(arg->val);
541124382Siedowse			int		precrypt = (arg->ch == 'H');
54220253Sjoerg			int             b;
54320253Sjoerg			int             istty = isatty(fd);
54420253Sjoerg			struct termios  t;
54564918Sgreen			login_cap_t	*lc;
54620253Sjoerg
54720253Sjoerg			if (istty) {
54820253Sjoerg				if (tcgetattr(fd, &t) == -1)
54920253Sjoerg					istty = 0;
55020253Sjoerg				else {
55120253Sjoerg					struct termios  n = t;
55220253Sjoerg
55320253Sjoerg					/* Disable echo */
55420253Sjoerg					n.c_lflag &= ~(ECHO);
55520253Sjoerg					tcsetattr(fd, TCSANOW, &n);
556124382Siedowse					printf("%s%spassword for user %s:",
557124382Siedowse					     (mode == M_UPDATE) ? "new " : "",
558124382Siedowse					     precrypt ? "encrypted " : "",
559124382Siedowse					     pwd->pw_name);
56020253Sjoerg					fflush(stdout);
56120253Sjoerg				}
56220253Sjoerg			}
56320253Sjoerg			b = read(fd, line, sizeof(line) - 1);
56420253Sjoerg			if (istty) {	/* Restore state */
56520253Sjoerg				tcsetattr(fd, TCSANOW, &t);
56620253Sjoerg				fputc('\n', stdout);
56720253Sjoerg				fflush(stdout);
56820253Sjoerg			}
569283814Sbapt			if (b < 0)
570283814Sbapt				err(EX_IOERR, "-%c file descriptor",
571283814Sbapt				    precrypt ? 'H' : 'h');
57220253Sjoerg			line[b] = '\0';
573168045Sle			if ((p = strpbrk(line, "\r\n")) != NULL)
57420253Sjoerg				*p = '\0';
57520253Sjoerg			if (!*line)
57630259Scharnier				errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
577124382Siedowse			if (precrypt) {
578124382Siedowse				if (strchr(line, ':') != NULL)
579124382Siedowse					return EX_DATAERR;
580124382Siedowse				pwd->pw_passwd = line;
581124382Siedowse			} else {
582124382Siedowse				lc = login_getpwclass(pwd);
583124382Siedowse				if (lc == NULL ||
584272833Sdes				    login_setcryptfmt(lc, "sha512", NULL) == NULL)
585124382Siedowse					warn("setting crypt(3) format");
586124382Siedowse				login_close(lc);
587124382Siedowse				pwd->pw_passwd = pw_pwcrypt(line);
588124382Siedowse			}
58952527Sdavidn			edited = 1;
59020253Sjoerg		}
59120253Sjoerg	}
59220267Sjoerg
59320267Sjoerg	/*
59420267Sjoerg	 * Special case: -N only displays & exits
59520267Sjoerg	 */
596284121Sbapt	if (conf.dryrun)
597284126Sbapt		return print_user(pwd);
59820267Sjoerg
59921330Sdavidn	if (mode == M_ADD) {
60052527Sdavidn		edited = 1;	/* Always */
60152502Sdavidn		rc = addpwent(pwd);
602283814Sbapt		if (rc == -1)
603283814Sbapt			errx(EX_IOERR, "user '%s' already exists",
604283814Sbapt			    pwd->pw_name);
605283814Sbapt		else if (rc != 0)
606283814Sbapt			err(EX_IOERR, "passwd file update");
60752502Sdavidn		if (cnf->nispasswd && *cnf->nispasswd=='/') {
60852502Sdavidn			rc = addnispwent(cnf->nispasswd, pwd);
60952502Sdavidn			if (rc == -1)
61052502Sdavidn				warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
61152502Sdavidn			else
61256000Sdavidn				warn("NIS passwd update");
61352502Sdavidn			/* NOTE: we treat NIS-only update errors as non-fatal */
61452502Sdavidn		}
61552512Sdavidn	} else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
61652527Sdavidn		if (edited) {	/* Only updated this if required */
617284128Sbapt			rc = chgpwent(name, pwd);
618283814Sbapt			if (rc == -1)
619283814Sbapt				errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
620283814Sbapt			else if (rc != 0)
621283814Sbapt				err(EX_IOERR, "passwd file update");
62252527Sdavidn			if ( cnf->nispasswd && *cnf->nispasswd=='/') {
623284128Sbapt				rc = chgnispwent(cnf->nispasswd, name, pwd);
62452527Sdavidn				if (rc == -1)
62552527Sdavidn					warn("User '%s' not found in NIS passwd", pwd->pw_name);
62652527Sdavidn				else
62756000Sdavidn					warn("NIS passwd update");
62852527Sdavidn				/* NOTE: NIS-only update errors are not fatal */
62952527Sdavidn			}
63052502Sdavidn		}
63121330Sdavidn	}
63221330Sdavidn
63320253Sjoerg	/*
63420253Sjoerg	 * Ok, user is created or changed - now edit group file
63520253Sjoerg	 */
63620253Sjoerg
637242349Sbapt	if (mode == M_ADD || getarg(args, 'G') != NULL) {
638273779Sbapt		int i, j;
639273779Sbapt		/* First remove the user from all group */
640273779Sbapt		SETGRENT();
641273779Sbapt		while ((grp = GETGRENT()) != NULL) {
642273779Sbapt			char group[MAXLOGNAME];
643273779Sbapt			if (grp->gr_mem == NULL)
644273779Sbapt				continue;
645273779Sbapt			for (i = 0; grp->gr_mem[i] != NULL; i++) {
646273779Sbapt				if (strcmp(grp->gr_mem[i] , pwd->pw_name) != 0)
647273779Sbapt					continue;
648273779Sbapt				for (j = i; grp->gr_mem[j] != NULL ; j++)
649273779Sbapt					grp->gr_mem[j] = grp->gr_mem[j+1];
650273779Sbapt				strlcpy(group, grp->gr_name, MAXLOGNAME);
651273779Sbapt				chggrent(group, grp);
652273779Sbapt			}
653273779Sbapt		}
654273779Sbapt		ENDGRENT();
655273779Sbapt
656273779Sbapt		/* now add to group where needed */
657242349Sbapt		for (i = 0; cnf->groups[i] != NULL; i++) {
658242349Sbapt			grp = GETGRNAM(cnf->groups[i]);
659244737Sbapt			grp = gr_add(grp, pwd->pw_name);
660244737Sbapt			/*
661244737Sbapt			 * grp can only be NULL in 2 cases:
662244737Sbapt			 * - the new member is already a member
663244737Sbapt			 * - a problem with memory occurs
664244737Sbapt			 * in both cases we want to skip now.
665244737Sbapt			 */
666244737Sbapt			if (grp == NULL)
667242349Sbapt				continue;
668242349Sbapt			chggrent(cnf->groups[i], grp);
669245114Smjg			free(grp);
670242349Sbapt		}
671242349Sbapt	}
672242349Sbapt
673242349Sbapt
67461759Sdavidn	/* go get a current version of pwd */
675284128Sbapt	pwd = GETPWNAM(name);
67661759Sdavidn	if (pwd == NULL) {
67761759Sdavidn		/* This will fail when we rename, so special case that */
678284129Sbapt		if (mode == M_UPDATE && conf.newname != NULL) {
679284129Sbapt			name = conf.newname;		/* update new name */
680284128Sbapt			pwd = GETPWNAM(name);	/* refetch renamed rec */
68161759Sdavidn		}
68261759Sdavidn	}
68361759Sdavidn	if (pwd == NULL)	/* can't go on without this */
684284128Sbapt		errx(EX_NOUSER, "user '%s' disappeared during update", name);
68520253Sjoerg
68644229Sdavidn	grp = GETGRGID(pwd->pw_gid);
687283842Sbapt	pw_log(cnf, mode, W_USER, "%s(%u):%s(%u):%s:%s:%s",
688283842Sbapt	       pwd->pw_name, pwd->pw_uid,
689283842Sbapt	    grp ? grp->gr_name : "unknown", (grp ? grp->gr_gid : (uid_t)-1),
69020253Sjoerg	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
69120253Sjoerg
69220253Sjoerg	/*
69320253Sjoerg	 * If adding, let's touch and chown the user's mail file. This is not
69420253Sjoerg	 * strictly necessary under BSD with a 0755 maildir but it also
69520253Sjoerg	 * doesn't hurt anything to create the empty mailfile
69620253Sjoerg	 */
69720253Sjoerg	if (mode == M_ADD) {
698283961Sbapt		if (PWALTDIR() != PWF_ALT) {
699283961Sbapt			arg = getarg(args, 'R');
700283961Sbapt			snprintf(path, sizeof(path), "%s%s/%s",
701283961Sbapt			    arg ? arg->val : "", _PATH_MAILDIR, pwd->pw_name);
702283961Sbapt			close(open(path, O_RDWR | O_CREAT, 0600));	/* Preserve contents &
70344229Sdavidn									 * mtime */
704283961Sbapt			chown(path, pwd->pw_uid, pwd->pw_gid);
70520253Sjoerg		}
70620253Sjoerg	}
70752527Sdavidn
70820253Sjoerg	/*
70982868Sdd	 * Let's create and populate the user's home directory. Note
71020253Sjoerg	 * that this also `works' for editing users if -m is used, but
71120253Sjoerg	 * existing files will *not* be overwritten.
71220253Sjoerg	 */
713283961Sbapt	if (PWALTDIR() != PWF_ALT && getarg(args, 'm') != NULL && pwd->pw_dir &&
714283961Sbapt	    *pwd->pw_dir == '/' && pwd->pw_dir[1])
715284118Sbapt		create_and_populate_homedir(mode, pwd);
71652527Sdavidn
71782868Sdd	/*
71882868Sdd	 * Finally, send mail to the new user as well, if we are asked to
71982868Sdd	 */
72082868Sdd	if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
72182868Sdd		FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
72282868Sdd
72382868Sdd		if (pfp == NULL)
72482868Sdd			warn("sendmail");
72582868Sdd		else {
72682868Sdd			fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
72782868Sdd			while (fgets(line, sizeof(line), fp) != NULL) {
72882868Sdd				/* Do substitutions? */
72982868Sdd				fputs(line, pfp);
73082868Sdd			}
73182868Sdd			pclose(pfp);
732283842Sbapt			pw_log(cnf, mode, W_USER, "%s(%u) new user mail sent",
733283842Sbapt			    pwd->pw_name, pwd->pw_uid);
73482868Sdd		}
73582868Sdd		fclose(fp);
73682868Sdd	}
73782868Sdd
73820267Sjoerg	return EXIT_SUCCESS;
73920253Sjoerg}
74020253Sjoerg
74120253Sjoerg
74220253Sjoergstatic          uid_t
743284133Sbaptpw_uidpolicy(struct userconf * cnf, long id)
74420253Sjoerg{
74520253Sjoerg	struct passwd  *pwd;
74620253Sjoerg	uid_t           uid = (uid_t) - 1;
74720253Sjoerg
74820253Sjoerg	/*
74920253Sjoerg	 * Check the given uid, if any
75020253Sjoerg	 */
751284133Sbapt	if (id > 0) {
752284133Sbapt		uid = (uid_t) id;
75320253Sjoerg
754284133Sbapt		if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
755283842Sbapt			errx(EX_DATAERR, "uid `%u' has already been allocated", pwd->pw_uid);
75620253Sjoerg	} else {
75720253Sjoerg		struct bitmap   bm;
75820253Sjoerg
75920253Sjoerg		/*
76020253Sjoerg		 * We need to allocate the next available uid under one of
76120253Sjoerg		 * two policies a) Grab the first unused uid b) Grab the
76220253Sjoerg		 * highest possible unused uid
76320253Sjoerg		 */
76420253Sjoerg		if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
76520253Sjoerg							 * claus^H^H^H^Hheck */
76620253Sjoerg			cnf->min_uid = 1000;
76720253Sjoerg			cnf->max_uid = 32000;
76820253Sjoerg		}
76920253Sjoerg		bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
77020253Sjoerg
77120253Sjoerg		/*
77220253Sjoerg		 * Now, let's fill the bitmap from the password file
77320253Sjoerg		 */
77444229Sdavidn		SETPWENT();
77544229Sdavidn		while ((pwd = GETPWENT()) != NULL)
77644229Sdavidn			if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
77720253Sjoerg				bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
77844229Sdavidn		ENDPWENT();
77920253Sjoerg
78020253Sjoerg		/*
78120253Sjoerg		 * Then apply the policy, with fallback to reuse if necessary
78220253Sjoerg		 */
78320253Sjoerg		if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
78420253Sjoerg			uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
78520253Sjoerg
78620253Sjoerg		/*
78720253Sjoerg		 * Another sanity check
78820253Sjoerg		 */
78920253Sjoerg		if (uid < cnf->min_uid || uid > cnf->max_uid)
79030259Scharnier			errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
79120253Sjoerg		bm_dealloc(&bm);
79220253Sjoerg	}
79320253Sjoerg	return uid;
79420253Sjoerg}
79520253Sjoerg
79620253Sjoerg
79720253Sjoergstatic          uid_t
798284118Sbaptpw_gidpolicy(struct cargs * args, char *nam, gid_t prefer)
79920253Sjoerg{
80020253Sjoerg	struct group   *grp;
80120253Sjoerg	gid_t           gid = (uid_t) - 1;
80220253Sjoerg	struct carg    *a_gid = getarg(args, 'g');
803284118Sbapt	struct userconf	*cnf = conf.userconf;
80420253Sjoerg
80520253Sjoerg	/*
80620253Sjoerg	 * If no arg given, see if default can help out
80720253Sjoerg	 */
80820253Sjoerg	if (a_gid == NULL && cnf->default_group && *cnf->default_group)
80920253Sjoerg		a_gid = addarg(args, 'g', cnf->default_group);
81020253Sjoerg
81120253Sjoerg	/*
81220253Sjoerg	 * Check the given gid, if any
81320253Sjoerg	 */
81444229Sdavidn	SETGRENT();
81520253Sjoerg	if (a_gid != NULL) {
81644229Sdavidn		if ((grp = GETGRNAM(a_gid->val)) == NULL) {
81720253Sjoerg			gid = (gid_t) atol(a_gid->val);
81861957Sache			if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
81930259Scharnier				errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
82020253Sjoerg		}
82120253Sjoerg		gid = grp->gr_gid;
822262865Sjulian	} else if ((grp = GETGRNAM(nam)) != NULL &&
823262865Sjulian	    (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
82420267Sjoerg		gid = grp->gr_gid;  /* Already created? Use it anyway... */
82520253Sjoerg	} else {
82620253Sjoerg		struct cargs    grpargs;
82720253Sjoerg		char            tmp[32];
82820253Sjoerg
82920253Sjoerg		LIST_INIT(&grpargs);
83020253Sjoerg
83120253Sjoerg		/*
83220253Sjoerg		 * We need to auto-create a group with the user's name. We
83320253Sjoerg		 * can send all the appropriate output to our sister routine
83420253Sjoerg		 * bit first see if we can create a group with gid==uid so we
83520253Sjoerg		 * can keep the user and group ids in sync. We purposely do
83620253Sjoerg		 * NOT check the gid range if we can force the sync. If the
83720253Sjoerg		 * user's name dups an existing group, then the group add
83820253Sjoerg		 * function will happily handle that case for us and exit.
83920253Sjoerg		 */
84044229Sdavidn		if (GETGRGID(prefer) == NULL) {
841282700Sbapt			snprintf(tmp, sizeof(tmp), "%u", prefer);
84220253Sjoerg			addarg(&grpargs, 'g', tmp);
84320253Sjoerg		}
844284121Sbapt		if (conf.dryrun) {
84520267Sjoerg			addarg(&grpargs, 'q', NULL);
846284128Sbapt			gid = pw_group(M_NEXT, nam, -1, &grpargs);
84720267Sjoerg		}
84820267Sjoerg		else
84920267Sjoerg		{
850284128Sbapt			pw_group(M_ADD, nam, -1, &grpargs);
85144229Sdavidn			if ((grp = GETGRNAM(nam)) != NULL)
85220267Sjoerg				gid = grp->gr_gid;
85320267Sjoerg		}
85470486Sben		a_gid = LIST_FIRST(&grpargs);
85520253Sjoerg		while (a_gid != NULL) {
85670486Sben			struct carg    *t = LIST_NEXT(a_gid, list);
85720253Sjoerg			LIST_REMOVE(a_gid, list);
85820253Sjoerg			a_gid = t;
85920253Sjoerg		}
86020253Sjoerg	}
86144229Sdavidn	ENDGRENT();
86220253Sjoerg	return gid;
86320253Sjoerg}
86420253Sjoerg
86520253Sjoerg
86620253Sjoergstatic          time_t
86720253Sjoergpw_pwdpolicy(struct userconf * cnf, struct cargs * args)
86820253Sjoerg{
86920253Sjoerg	time_t          result = 0;
87020253Sjoerg	time_t          now = time(NULL);
87127831Sdavidn	struct carg    *arg = getarg(args, 'p');
87220253Sjoerg
87320253Sjoerg	if (arg != NULL) {
87420253Sjoerg		if ((result = parse_date(now, arg->val)) == now)
87530259Scharnier			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
87620253Sjoerg	} else if (cnf->password_days > 0)
87720253Sjoerg		result = now + ((long) cnf->password_days * 86400L);
87820253Sjoerg	return result;
87920253Sjoerg}
88020253Sjoerg
88120253Sjoerg
88220253Sjoergstatic          time_t
88320253Sjoergpw_exppolicy(struct userconf * cnf, struct cargs * args)
88420253Sjoerg{
88520253Sjoerg	time_t          result = 0;
88620253Sjoerg	time_t          now = time(NULL);
88720253Sjoerg	struct carg    *arg = getarg(args, 'e');
88820253Sjoerg
88920253Sjoerg	if (arg != NULL) {
89020253Sjoerg		if ((result = parse_date(now, arg->val)) == now)
89130259Scharnier			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
89220253Sjoerg	} else if (cnf->expire_days > 0)
89320253Sjoerg		result = now + ((long) cnf->expire_days * 86400L);
89420253Sjoerg	return result;
89520253Sjoerg}
89620253Sjoerg
89720253Sjoerg
89820253Sjoergstatic char    *
89920253Sjoergpw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
90020253Sjoerg{
90120253Sjoerg	struct carg    *arg = getarg(args, 'd');
902282699Sbapt	static char     home[128];
90320253Sjoerg
90420253Sjoerg	if (arg)
905282699Sbapt		return (arg->val);
90620253Sjoerg
907282699Sbapt	if (cnf->home == NULL || *cnf->home == '\0')
908282699Sbapt		errx(EX_CONFIG, "no base home directory set");
909282699Sbapt	snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
910282699Sbapt
911282699Sbapt	return (home);
91220253Sjoerg}
91320253Sjoerg
91420253Sjoergstatic char    *
91520253Sjoergshell_path(char const * path, char *shells[], char *sh)
91620253Sjoerg{
91720253Sjoerg	if (sh != NULL && (*sh == '/' || *sh == '\0'))
91820253Sjoerg		return sh;	/* specified full path or forced none */
91920253Sjoerg	else {
92020253Sjoerg		char           *p;
92120253Sjoerg		char            paths[_UC_MAXLINE];
92220253Sjoerg
92320253Sjoerg		/*
92420253Sjoerg		 * We need to search paths
92520253Sjoerg		 */
926130633Srobert		strlcpy(paths, path, sizeof(paths));
92720253Sjoerg		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
92820253Sjoerg			int             i;
92920253Sjoerg			static char     shellpath[256];
93020253Sjoerg
93120253Sjoerg			if (sh != NULL) {
932282700Sbapt				snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
93320253Sjoerg				if (access(shellpath, X_OK) == 0)
93420253Sjoerg					return shellpath;
93520253Sjoerg			} else
93620253Sjoerg				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
937282700Sbapt					snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
93820253Sjoerg					if (access(shellpath, X_OK) == 0)
93920253Sjoerg						return shellpath;
94020253Sjoerg				}
94120253Sjoerg		}
94220253Sjoerg		if (sh == NULL)
94330259Scharnier			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
94430259Scharnier		errx(EX_CONFIG, "no default shell available or defined");
94520253Sjoerg		return NULL;
94620253Sjoerg	}
94720253Sjoerg}
94820253Sjoerg
94920253Sjoerg
95020253Sjoergstatic char    *
95120253Sjoergpw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
95220253Sjoerg{
95320253Sjoerg	char           *sh = newshell;
95420253Sjoerg	struct carg    *arg = getarg(args, 's');
95520253Sjoerg
95620253Sjoerg	if (newshell == NULL && arg != NULL)
95720253Sjoerg		sh = arg->val;
95820253Sjoerg	return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
95920253Sjoerg}
96020253Sjoerg
961179365Santoine#define	SALTSIZE	32
96220253Sjoerg
963179365Santoinestatic char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
964179365Santoine
96520253Sjoergchar           *
96620253Sjoergpw_pwcrypt(char *password)
96720253Sjoerg{
96820253Sjoerg	int             i;
969179365Santoine	char            salt[SALTSIZE + 1];
970231994Skevlo	char		*cryptpw;
97120253Sjoerg
97220253Sjoerg	static char     buf[256];
97320253Sjoerg
97420253Sjoerg	/*
97520253Sjoerg	 * Calculate a salt value
97620253Sjoerg	 */
977179365Santoine	for (i = 0; i < SALTSIZE; i++)
978181785Sache		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
979179365Santoine	salt[SALTSIZE] = '\0';
98020253Sjoerg
981231994Skevlo	cryptpw = crypt(password, salt);
982231994Skevlo	if (cryptpw == NULL)
983231994Skevlo		errx(EX_CONFIG, "crypt(3) failure");
984231994Skevlo	return strcpy(buf, cryptpw);
98520253Sjoerg}
98620253Sjoerg
98720590Sdavidn
98820253Sjoergstatic char    *
98920253Sjoergpw_password(struct userconf * cnf, struct cargs * args, char const * user)
99020253Sjoerg{
99120253Sjoerg	int             i, l;
99220253Sjoerg	char            pwbuf[32];
99320253Sjoerg
99420253Sjoerg	switch (cnf->default_password) {
99520253Sjoerg	case -1:		/* Random password */
99673563Skris		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
99720253Sjoerg		for (i = 0; i < l; i++)
998181785Sache			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
99920253Sjoerg		pwbuf[i] = '\0';
100020253Sjoerg
100120253Sjoerg		/*
100220253Sjoerg		 * We give this information back to the user
100320253Sjoerg		 */
1004124382Siedowse		if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
1005284121Sbapt		    !conf.dryrun) {
100661957Sache			if (isatty(STDOUT_FILENO))
100720712Sdavidn				printf("Password for '%s' is: ", user);
100820253Sjoerg			printf("%s\n", pwbuf);
100920253Sjoerg			fflush(stdout);
101020253Sjoerg		}
101120253Sjoerg		break;
101220253Sjoerg
101320253Sjoerg	case -2:		/* No password at all! */
101420253Sjoerg		return "";
101520253Sjoerg
101620253Sjoerg	case 0:		/* No login - default */
101720253Sjoerg	default:
101820253Sjoerg		return "*";
101920253Sjoerg
102020253Sjoerg	case 1:		/* user's name */
1021130633Srobert		strlcpy(pwbuf, user, sizeof(pwbuf));
102220253Sjoerg		break;
102320253Sjoerg	}
102420253Sjoerg	return pw_pwcrypt(pwbuf);
102520253Sjoerg}
102620253Sjoerg
1027284111Sbaptstatic int
1028284128Sbaptdelete_user(struct userconf *cnf, struct passwd *pwd, char *name,
1029284111Sbapt    int delete, int mode)
1030284111Sbapt{
1031284111Sbapt	char		 file[MAXPATHLEN];
1032284111Sbapt	char		 home[MAXPATHLEN];
1033284111Sbapt	uid_t		 uid = pwd->pw_uid;
1034284111Sbapt	struct group	*gr, *grp;
1035284111Sbapt	char		 grname[LOGNAMESIZE];
1036284111Sbapt	int		 rc;
1037284111Sbapt	struct stat	 st;
103820253Sjoerg
1039284111Sbapt	if (strcmp(pwd->pw_name, "root") == 0)
1040284111Sbapt		errx(EX_DATAERR, "cannot remove user 'root'");
1041284111Sbapt
1042284111Sbapt	if (!PWALTDIR()) {
1043284111Sbapt		/*
1044284111Sbapt		 * Remove opie record from /etc/opiekeys
1045284111Sbapt		*/
1046284111Sbapt
1047284111Sbapt		rmopie(pwd->pw_name);
1048284111Sbapt
1049284111Sbapt		/*
1050284111Sbapt		 * Remove crontabs
1051284111Sbapt		 */
1052284111Sbapt		snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
1053284111Sbapt		if (access(file, F_OK) == 0) {
1054284111Sbapt			snprintf(file, sizeof(file), "crontab -u %s -r", pwd->pw_name);
1055284111Sbapt			system(file);
1056284111Sbapt		}
1057284111Sbapt	}
1058284111Sbapt	/*
1059284111Sbapt	 * Save these for later, since contents of pwd may be
1060284111Sbapt	 * invalidated by deletion
1061284111Sbapt	 */
1062284111Sbapt	snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
1063284111Sbapt	strlcpy(home, pwd->pw_dir, sizeof(home));
1064284111Sbapt	gr = GETGRGID(pwd->pw_gid);
1065284111Sbapt	if (gr != NULL)
1066284111Sbapt		strlcpy(grname, gr->gr_name, LOGNAMESIZE);
1067284111Sbapt	else
1068284111Sbapt		grname[0] = '\0';
1069284111Sbapt
1070284111Sbapt	rc = delpwent(pwd);
1071284111Sbapt	if (rc == -1)
1072284111Sbapt		err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
1073284111Sbapt	else if (rc != 0)
1074284111Sbapt		err(EX_IOERR, "passwd update");
1075284111Sbapt
1076284111Sbapt	if (cnf->nispasswd && *cnf->nispasswd=='/') {
1077284128Sbapt		rc = delnispwent(cnf->nispasswd, name);
1078284111Sbapt		if (rc == -1)
1079284111Sbapt			warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
1080284111Sbapt		else if (rc != 0)
1081284111Sbapt			warn("WARNING: NIS passwd update");
1082284111Sbapt		/* non-fatal */
1083284111Sbapt	}
1084284111Sbapt
1085284128Sbapt	grp = GETGRNAM(name);
1086284111Sbapt	if (grp != NULL &&
1087284111Sbapt	    (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
1088284128Sbapt	    strcmp(name, grname) == 0)
1089284128Sbapt		delgrent(GETGRNAM(name));
1090284111Sbapt	SETGRENT();
1091284111Sbapt	while ((grp = GETGRENT()) != NULL) {
1092284111Sbapt		int i, j;
1093284111Sbapt		char group[MAXLOGNAME];
1094284113Sbapt		if (grp->gr_mem == NULL)
1095284113Sbapt			continue;
1096284113Sbapt
1097284113Sbapt		for (i = 0; grp->gr_mem[i] != NULL; i++) {
1098284128Sbapt			if (strcmp(grp->gr_mem[i], name) != 0)
1099284113Sbapt				continue;
1100284113Sbapt
1101284113Sbapt			for (j = i; grp->gr_mem[j] != NULL; j++)
1102284113Sbapt				grp->gr_mem[j] = grp->gr_mem[j+1];
1103284113Sbapt			strlcpy(group, grp->gr_name, MAXLOGNAME);
1104284113Sbapt			chggrent(group, grp);
1105284111Sbapt		}
1106284111Sbapt	}
1107284111Sbapt	ENDGRENT();
1108284111Sbapt
1109284128Sbapt	pw_log(cnf, mode, W_USER, "%s(%u) account removed", name, uid);
1110284111Sbapt
1111284117Sbapt	if (!PWALTDIR()) {
1112284111Sbapt		/*
1113284111Sbapt		 * Remove mail file
1114284111Sbapt		 */
1115284111Sbapt		remove(file);
1116284111Sbapt
1117284111Sbapt		/*
1118284111Sbapt		 * Remove at jobs
1119284111Sbapt		 */
1120284111Sbapt		if (getpwuid(uid) == NULL)
1121284111Sbapt			rmat(uid);
1122284111Sbapt
1123284111Sbapt		/*
1124284111Sbapt		 * Remove home directory and contents
1125284111Sbapt		 */
1126284112Sbapt		if (delete && *home == '/' && getpwuid(uid) == NULL &&
1127284112Sbapt		    stat(home, &st) != -1) {
1128284112Sbapt			rm_r(home, uid);
1129284112Sbapt			pw_log(cnf, mode, W_USER, "%s(%u) home '%s' %sremoved",
1130284128Sbapt			       name, uid, home,
1131284112Sbapt			       stat(home, &st) == -1 ? "" : "not completely ");
1132284111Sbapt		}
1133284111Sbapt	}
1134284111Sbapt
1135284111Sbapt	return (EXIT_SUCCESS);
1136284111Sbapt}
1137284111Sbapt
113820253Sjoergstatic int
1139284124Sbaptprint_user(struct passwd * pwd)
114020253Sjoerg{
1141284122Sbapt	if (!conf.pretty) {
1142242349Sbapt		char            *buf;
114320253Sjoerg
1144284124Sbapt		buf = conf.v7 ? pw_make_v7(pwd) : pw_make(pwd);
1145242349Sbapt		printf("%s\n", buf);
1146242349Sbapt		free(buf);
114720253Sjoerg	} else {
114820267Sjoerg		int		j;
114920253Sjoerg		char           *p;
115044229Sdavidn		struct group   *grp = GETGRGID(pwd->pw_gid);
115120253Sjoerg		char            uname[60] = "User &", office[60] = "[None]",
115220253Sjoerg		                wphone[60] = "[None]", hphone[60] = "[None]";
115320590Sdavidn		char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
115420590Sdavidn		struct tm *    tptr;
115520253Sjoerg
115620253Sjoerg		if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1157130633Srobert			strlcpy(uname, p, sizeof(uname));
115820253Sjoerg			if ((p = strtok(NULL, ",")) != NULL) {
1159130633Srobert				strlcpy(office, p, sizeof(office));
116020253Sjoerg				if ((p = strtok(NULL, ",")) != NULL) {
1161130633Srobert					strlcpy(wphone, p, sizeof(wphone));
116220253Sjoerg					if ((p = strtok(NULL, "")) != NULL) {
1163130633Srobert						strlcpy(hphone, p,
1164130633Srobert						    sizeof(hphone));
116520253Sjoerg					}
116620253Sjoerg				}
116720253Sjoerg			}
116820253Sjoerg		}
116920253Sjoerg		/*
117020253Sjoerg		 * Handle '&' in gecos field
117120253Sjoerg		 */
117220253Sjoerg		if ((p = strchr(uname, '&')) != NULL) {
117320253Sjoerg			int             l = strlen(pwd->pw_name);
117420253Sjoerg			int             m = strlen(p);
117520253Sjoerg
117620253Sjoerg			memmove(p + l, p + 1, m);
117720253Sjoerg			memmove(p, pwd->pw_name, l);
117861957Sache			*p = (char) toupper((unsigned char)*p);
117920253Sjoerg		}
118020590Sdavidn		if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
118174569Sache			strftime(acexpire, sizeof acexpire, "%c", tptr);
118261957Sache		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
118374569Sache			strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1184283842Sbapt		printf("Login Name: %-15s   #%-12u Group: %-15s   #%u\n"
118520747Sdavidn		       " Full Name: %s\n"
118620747Sdavidn		       "      Home: %-26.26s      Class: %s\n"
118720747Sdavidn		       "     Shell: %-26.26s     Office: %s\n"
118820747Sdavidn		       "Work Phone: %-26.26s Home Phone: %s\n"
118920747Sdavidn		       "Acc Expire: %-26.26s Pwd Expire: %s\n",
1190283842Sbapt		       pwd->pw_name, pwd->pw_uid,
1191283842Sbapt		       grp ? grp->gr_name : "(invalid)", pwd->pw_gid,
119220253Sjoerg		       uname, pwd->pw_dir, pwd->pw_class,
119320590Sdavidn		       pwd->pw_shell, office, wphone, hphone,
119420590Sdavidn		       acexpire, pwexpire);
119544229Sdavidn	        SETGRENT();
119620267Sjoerg		j = 0;
119744229Sdavidn		while ((grp=GETGRENT()) != NULL)
119820267Sjoerg		{
119920267Sjoerg			int     i = 0;
1200262865Sjulian			if (grp->gr_mem != NULL) {
1201262865Sjulian				while (grp->gr_mem[i] != NULL)
120220267Sjoerg				{
1203262865Sjulian					if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1204262865Sjulian					{
1205262865Sjulian						printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
1206262865Sjulian						break;
1207262865Sjulian					}
1208262865Sjulian					++i;
120920267Sjoerg				}
121020267Sjoerg			}
121120267Sjoerg		}
121244229Sdavidn		ENDGRENT();
121361957Sache		printf("%s", j ? "\n" : "");
121420253Sjoerg	}
121520267Sjoerg	return EXIT_SUCCESS;
121620253Sjoerg}
121720253Sjoerg
1218284110Sbaptchar *
1219284110Sbaptpw_checkname(char *name, int gecos)
122020253Sjoerg{
1221109961Sgad	char showch[8];
1222284110Sbapt	const char *badchars, *ch, *showtype;
1223109961Sgad	int reject;
122420253Sjoerg
1225109961Sgad	ch = name;
1226109961Sgad	reject = 0;
1227109961Sgad	if (gecos) {
1228109961Sgad		/* See if the name is valid as a gecos (comment) field. */
1229109961Sgad		badchars = ":!@";
1230109961Sgad		showtype = "gecos field";
1231109961Sgad	} else {
1232109961Sgad		/* See if the name is valid as a userid or group. */
1233109961Sgad		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1234109961Sgad		showtype = "userid/group name";
1235109961Sgad		/* Userids and groups can not have a leading '-'. */
1236109961Sgad		if (*ch == '-')
1237109961Sgad			reject = 1;
123820253Sjoerg	}
1239109961Sgad	if (!reject) {
1240109961Sgad		while (*ch) {
1241109961Sgad			if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1242109961Sgad			    *ch == 127) {
1243109961Sgad				reject = 1;
1244109961Sgad				break;
1245109961Sgad			}
1246109961Sgad			/* 8-bit characters are only allowed in GECOS fields */
1247109961Sgad			if (!gecos && (*ch & 0x80)) {
1248109961Sgad				reject = 1;
1249109961Sgad				break;
1250109961Sgad			}
1251109961Sgad			ch++;
1252109961Sgad		}
1253109961Sgad	}
1254109961Sgad	/*
1255109961Sgad	 * A `$' is allowed as the final character for userids and groups,
1256109961Sgad	 * mainly for the benefit of samba.
1257109961Sgad	 */
1258109961Sgad	if (reject && !gecos) {
1259109961Sgad		if (*ch == '$' && *(ch + 1) == '\0') {
1260109961Sgad			reject = 0;
1261109961Sgad			ch++;
1262109961Sgad		}
1263109961Sgad	}
1264109961Sgad	if (reject) {
1265109961Sgad		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1266109961Sgad		    ? "`%c'" : "0x%02x", *ch);
1267228673Sdim		errx(EX_DATAERR, "invalid character %s at position %td in %s",
1268109961Sgad		    showch, (ch - name), showtype);
1269109961Sgad	}
1270109961Sgad	if (!gecos && (ch - name) > LOGNAMESIZE)
1271109961Sgad		errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1272109961Sgad		    LOGNAMESIZE);
1273284110Sbapt
1274284110Sbapt	return (name);
127520253Sjoerg}
127620253Sjoerg
127720253Sjoerg
127820253Sjoergstatic void
127920253Sjoergrmat(uid_t uid)
128020253Sjoerg{
128120253Sjoerg	DIR            *d = opendir("/var/at/jobs");
128220253Sjoerg
128320253Sjoerg	if (d != NULL) {
128420253Sjoerg		struct dirent  *e;
128520253Sjoerg
128620253Sjoerg		while ((e = readdir(d)) != NULL) {
128720253Sjoerg			struct stat     st;
128820253Sjoerg
128920253Sjoerg			if (strncmp(e->d_name, ".lock", 5) != 0 &&
129020253Sjoerg			    stat(e->d_name, &st) == 0 &&
129120253Sjoerg			    !S_ISDIR(st.st_mode) &&
129220253Sjoerg			    st.st_uid == uid) {
129320253Sjoerg				char            tmp[MAXPATHLEN];
129420253Sjoerg
1295282700Sbapt				snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s", e->d_name);
129620253Sjoerg				system(tmp);
129720253Sjoerg			}
129820253Sjoerg		}
129920253Sjoerg		closedir(d);
130020253Sjoerg	}
130120253Sjoerg}
130220747Sdavidn
130320747Sdavidnstatic void
130485145Sachermopie(char const * name)
130520747Sdavidn{
130685145Sache	static const char etcopie[] = "/etc/opiekeys";
130785145Sache	FILE   *fp = fopen(etcopie, "r+");
130820747Sdavidn
130921052Sdavidn	if (fp != NULL) {
131021052Sdavidn		char	tmp[1024];
131121052Sdavidn		off_t	atofs = 0;
131221052Sdavidn		int	length = strlen(name);
131320747Sdavidn
131421052Sdavidn		while (fgets(tmp, sizeof tmp, fp) != NULL) {
131521052Sdavidn			if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
131621052Sdavidn				if (fseek(fp, atofs, SEEK_SET) == 0) {
131721052Sdavidn					fwrite("#", 1, 1, fp);	/* Comment username out */
131821052Sdavidn				}
131921052Sdavidn				break;
132020747Sdavidn			}
132121052Sdavidn			atofs = ftell(fp);
132220747Sdavidn		}
132321052Sdavidn		/*
132421052Sdavidn		 * If we got an error of any sort, don't update!
132521052Sdavidn		 */
132621052Sdavidn		fclose(fp);
132720747Sdavidn	}
132820747Sdavidn}
132920747Sdavidn
1330