pw_user.c revision 148584
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 148584 2005-07-31 08:25:53Z pjd $";
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>
4422394Sdavidn#include <utmp.h>
4564918Sgreen#include <login_cap.h>
4622394Sdavidn#if defined(USE_MD5RAND)
4720555Sdavidn#include <md5.h>
4822394Sdavidn#endif
4920253Sjoerg#include "pw.h"
5020253Sjoerg#include "bitmap.h"
5120253Sjoerg
5223318Sache#if (MAXLOGNAME-1) > UT_NAMESIZE
5322394Sdavidn#define LOGNAMESIZE UT_NAMESIZE
5422394Sdavidn#else
5523318Sache#define LOGNAMESIZE (MAXLOGNAME-1)
5622394Sdavidn#endif
5722394Sdavidn
5852512Sdavidnstatic		char locked_str[] = "*LOCKED*";
5924214Sache
6044386Sdavidnstatic int      print_user(struct passwd * pwd, int pretty, int v7);
6120253Sjoergstatic uid_t    pw_uidpolicy(struct userconf * cnf, struct cargs * args);
6220253Sjoergstatic uid_t    pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer);
6320253Sjoergstatic time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
6420253Sjoergstatic time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
6520253Sjoergstatic char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
6620253Sjoergstatic char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
6720253Sjoergstatic char    *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
6820253Sjoergstatic char    *shell_path(char const * path, char *shells[], char *sh);
6920253Sjoergstatic void     rmat(uid_t uid);
7085145Sachestatic void     rmopie(char const * name);
7120253Sjoerg
7220253Sjoerg/*-
7320253Sjoerg * -C config      configuration file
7420253Sjoerg * -q             quiet operation
7520253Sjoerg * -n name        login name
7620253Sjoerg * -u uid         user id
7720253Sjoerg * -c comment     user name/comment
7820253Sjoerg * -d directory   home directory
7920253Sjoerg * -e date        account expiry date
8020253Sjoerg * -p date        password expiry date
8120253Sjoerg * -g grp         primary group
8220253Sjoerg * -G grp1,grp2   additional groups
8320253Sjoerg * -m [ -k dir ]  create and set up home
8420253Sjoerg * -s shell       name of login shell
8520253Sjoerg * -o             duplicate uid ok
8620253Sjoerg * -L class       user class
8720253Sjoerg * -l name        new login name
8820253Sjoerg * -h fd          password filehandle
89124382Siedowse * -H fd          encrypted password filehandle
9020253Sjoerg * -F             force print or add
9120253Sjoerg *   Setting defaults:
9220253Sjoerg * -D             set user defaults
9320253Sjoerg * -b dir         default home root dir
9420253Sjoerg * -e period      default expiry period
9520253Sjoerg * -p period      default password change period
9620253Sjoerg * -g group       default group
9720253Sjoerg * -G             grp1,grp2.. default additional groups
9820253Sjoerg * -L class       default login class
9920253Sjoerg * -k dir         default home skeleton
10020253Sjoerg * -s shell       default shell
10120253Sjoerg * -w method      default password method
10220253Sjoerg */
10320253Sjoerg
10420253Sjoergint
10520253Sjoergpw_user(struct userconf * cnf, int mode, struct cargs * args)
10620253Sjoerg{
10752527Sdavidn	int	        rc, edited = 0;
10820253Sjoerg	char           *p = NULL;
10952512Sdavidn	char					 *passtmp;
11020253Sjoerg	struct carg    *a_name;
11120253Sjoerg	struct carg    *a_uid;
11220253Sjoerg	struct carg    *arg;
11320253Sjoerg	struct passwd  *pwd = NULL;
11420253Sjoerg	struct group   *grp;
11520253Sjoerg	struct stat     st;
11620747Sdavidn	char            line[_PASSWORD_LEN+1];
11782868Sdd	FILE	       *fp;
11820253Sjoerg
11920253Sjoerg	static struct passwd fakeuser =
12020253Sjoerg	{
12120253Sjoerg		NULL,
12220253Sjoerg		"*",
12320253Sjoerg		-1,
12420253Sjoerg		-1,
12520253Sjoerg		0,
12620253Sjoerg		"",
12720253Sjoerg		"User &",
12856000Sdavidn		"/nonexistent",
12920253Sjoerg		"/bin/sh",
13020253Sjoerg		0
13156000Sdavidn#if defined(__FreeBSD__)
13256000Sdavidn		,0
13356000Sdavidn#endif
13420253Sjoerg	};
13520253Sjoerg
13652512Sdavidn
13720253Sjoerg	/*
13820267Sjoerg	 * With M_NEXT, we only need to return the
13920267Sjoerg	 * next uid to stdout
14020267Sjoerg	 */
14120267Sjoerg	if (mode == M_NEXT)
14220267Sjoerg	{
14320267Sjoerg		uid_t next = pw_uidpolicy(cnf, args);
14420267Sjoerg		if (getarg(args, 'q'))
14520267Sjoerg			return next;
14620267Sjoerg		printf("%ld:", (long)next);
14720267Sjoerg		pw_group(cnf, mode, args);
14820267Sjoerg		return EXIT_SUCCESS;
14920267Sjoerg	}
15020267Sjoerg
15120267Sjoerg	/*
15220253Sjoerg	 * We can do all of the common legwork here
15320253Sjoerg	 */
15420253Sjoerg
15520253Sjoerg	if ((arg = getarg(args, 'b')) != NULL) {
15620267Sjoerg		cnf->home = arg->val;
15720253Sjoerg	}
15821052Sdavidn
15921052Sdavidn	/*
16021052Sdavidn	 * If we'll need to use it or we're updating it,
16121052Sdavidn	 * then create the base home directory if necessary
16221052Sdavidn	 */
16321052Sdavidn	if (arg != NULL || getarg(args, 'm') != NULL) {
16421052Sdavidn		int	l = strlen(cnf->home);
16521052Sdavidn
16621052Sdavidn		if (l > 1 && cnf->home[l-1] == '/')	/* Shave off any trailing path delimiter */
16721052Sdavidn			cnf->home[--l] = '\0';
16821052Sdavidn
16921052Sdavidn		if (l < 2 || *cnf->home != '/')		/* Check for absolute path name */
17030259Scharnier			errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
17121052Sdavidn
17221052Sdavidn		if (stat(cnf->home, &st) == -1) {
17321052Sdavidn			char	dbuf[MAXPATHLEN];
17421052Sdavidn
17521242Sdavidn			/*
17621242Sdavidn			 * This is a kludge especially for Joerg :)
17721242Sdavidn			 * If the home directory would be created in the root partition, then
17821242Sdavidn			 * we really create it under /usr which is likely to have more space.
17921242Sdavidn			 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
18021242Sdavidn			 */
18121242Sdavidn			if (strchr(cnf->home+1, '/') == NULL) {
18221242Sdavidn				strcpy(dbuf, "/usr");
18321242Sdavidn				strncat(dbuf, cnf->home, MAXPATHLEN-5);
18421242Sdavidn				if (mkdir(dbuf, 0755) != -1 || errno == EEXIST) {
18521242Sdavidn					chown(dbuf, 0, 0);
186148584Spjd					/*
187148584Spjd					 * Skip first "/" and create symlink:
188148584Spjd					 * /home -> usr/home
189148584Spjd					 */
190148584Spjd					symlink(dbuf+1, cnf->home);
19121242Sdavidn				}
19221242Sdavidn				/* If this falls, fall back to old method */
19321242Sdavidn			}
194130633Srobert			strlcpy(dbuf, cnf->home, sizeof(dbuf));
195130633Srobert			p = dbuf;
19621242Sdavidn			if (stat(dbuf, &st) == -1) {
19721242Sdavidn				while ((p = strchr(++p, '/')) != NULL) {
19821242Sdavidn					*p = '\0';
19921242Sdavidn					if (stat(dbuf, &st) == -1) {
20021242Sdavidn						if (mkdir(dbuf, 0755) == -1)
20121242Sdavidn							goto direrr;
20221242Sdavidn						chown(dbuf, 0, 0);
20321242Sdavidn					} else if (!S_ISDIR(st.st_mode))
20430259Scharnier						errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
20521242Sdavidn					*p = '/';
20621242Sdavidn				}
20721052Sdavidn			}
20821242Sdavidn			if (stat(dbuf, &st) == -1) {
20921052Sdavidn				if (mkdir(dbuf, 0755) == -1) {
21030259Scharnier				direrr:	err(EX_OSFILE, "mkdir '%s'", dbuf);
21121052Sdavidn				}
21221052Sdavidn				chown(dbuf, 0, 0);
21321052Sdavidn			}
21421052Sdavidn		} else if (!S_ISDIR(st.st_mode))
21530259Scharnier			errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
21621052Sdavidn	}
21721052Sdavidn
21820253Sjoerg	if ((arg = getarg(args, 'e')) != NULL)
21920253Sjoerg		cnf->expire_days = atoi(arg->val);
22020253Sjoerg
22121330Sdavidn	if ((arg = getarg(args, 'y')) != NULL)
22221330Sdavidn		cnf->nispasswd = arg->val;
22321330Sdavidn
22420253Sjoerg	if ((arg = getarg(args, 'p')) != NULL && arg->val)
22520253Sjoerg		cnf->password_days = atoi(arg->val);
22620253Sjoerg
22720253Sjoerg	if ((arg = getarg(args, 'g')) != NULL) {
22863596Sdavidn		if (!*(p = arg->val))	/* Handle empty group list specially */
22963596Sdavidn			cnf->default_group = "";
23063596Sdavidn		else {
23163596Sdavidn			if ((grp = GETGRNAM(p)) == NULL) {
23263596Sdavidn				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
23363596Sdavidn					errx(EX_NOUSER, "group `%s' does not exist", p);
23463596Sdavidn			}
23563596Sdavidn			cnf->default_group = newstr(grp->gr_name);
23620253Sjoerg		}
23720253Sjoerg	}
23820253Sjoerg	if ((arg = getarg(args, 'L')) != NULL)
23920679Sdavidn		cnf->default_class = pw_checkname((u_char *)arg->val, 0);
24020253Sjoerg
24120253Sjoerg	if ((arg = getarg(args, 'G')) != NULL && arg->val) {
24252527Sdavidn		int i = 0;
24320253Sjoerg
24420747Sdavidn		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
24544229Sdavidn			if ((grp = GETGRNAM(p)) == NULL) {
24661957Sache				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
24730259Scharnier					errx(EX_NOUSER, "group `%s' does not exist", p);
24820253Sjoerg			}
24920747Sdavidn			if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
25020747Sdavidn				cnf->groups[i++] = newstr(grp->gr_name);
25120253Sjoerg		}
25220747Sdavidn		while (i < cnf->numgroups)
25320253Sjoerg			cnf->groups[i++] = NULL;
25420253Sjoerg	}
25552527Sdavidn
25620253Sjoerg	if ((arg = getarg(args, 'k')) != NULL) {
25726088Sdavidn		if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
25830259Scharnier			errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
25920253Sjoerg	}
26052527Sdavidn
26120253Sjoerg	if ((arg = getarg(args, 's')) != NULL)
26220253Sjoerg		cnf->shell_default = arg->val;
26320253Sjoerg
26463600Sdavidn	if ((arg = getarg(args, 'w')) != NULL)
26563600Sdavidn		cnf->default_password = boolean_val(arg->val, cnf->default_password);
26620253Sjoerg	if (mode == M_ADD && getarg(args, 'D')) {
26720253Sjoerg		if (getarg(args, 'n') != NULL)
26830259Scharnier			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
26920253Sjoerg		if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
27020253Sjoerg			if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
27120253Sjoerg				cnf->min_uid = 1000;
27220253Sjoerg			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
27320253Sjoerg				cnf->max_uid = 32000;
27420253Sjoerg		}
27520253Sjoerg		if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
27620253Sjoerg			if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
27720253Sjoerg				cnf->min_gid = 1000;
27820253Sjoerg			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
27920253Sjoerg				cnf->max_gid = 32000;
28020253Sjoerg		}
28120253Sjoerg
28220253Sjoerg		arg = getarg(args, 'C');
28320253Sjoerg		if (write_userconfig(arg ? arg->val : NULL))
28420267Sjoerg			return EXIT_SUCCESS;
28530259Scharnier		warn("config update");
28620267Sjoerg		return EX_IOERR;
28720253Sjoerg	}
28852527Sdavidn
28920253Sjoerg	if (mode == M_PRINT && getarg(args, 'a')) {
29020267Sjoerg		int             pretty = getarg(args, 'P') != NULL;
29144386Sdavidn		int		v7 = getarg(args, '7') != NULL;
29220253Sjoerg
29344229Sdavidn		SETPWENT();
29444229Sdavidn		while ((pwd = GETPWENT()) != NULL)
29544386Sdavidn			print_user(pwd, pretty, v7);
29644229Sdavidn		ENDPWENT();
29720267Sjoerg		return EXIT_SUCCESS;
29820253Sjoerg	}
29952527Sdavidn
30020253Sjoerg	if ((a_name = getarg(args, 'n')) != NULL)
30144229Sdavidn		pwd = GETPWNAM(pw_checkname((u_char *)a_name->val, 0));
30220253Sjoerg	a_uid = getarg(args, 'u');
30320253Sjoerg
30420253Sjoerg	if (a_uid == NULL) {
30520253Sjoerg		if (a_name == NULL)
30630259Scharnier			errx(EX_DATAERR, "user name or id required");
30720253Sjoerg
30820253Sjoerg		/*
30920253Sjoerg		 * Determine whether 'n' switch is name or uid - we don't
31020253Sjoerg		 * really don't really care which we have, but we need to
31120253Sjoerg		 * know.
31220253Sjoerg		 */
31343780Sdes		if (mode != M_ADD && pwd == NULL
31443780Sdes		    && strspn(a_name->val, "0123456789") == strlen(a_name->val)
31543780Sdes		    && atoi(a_name->val) > 0) {	/* Assume uid */
31620253Sjoerg			(a_uid = a_name)->ch = 'u';
31720253Sjoerg			a_name = NULL;
31820253Sjoerg		}
31920253Sjoerg	}
32052527Sdavidn
32120253Sjoerg	/*
32220253Sjoerg	 * Update, delete & print require that the user exists
32320253Sjoerg	 */
32452512Sdavidn	if (mode == M_UPDATE || mode == M_DELETE ||
32552512Sdavidn	    mode == M_PRINT  || mode == M_LOCK   || mode == M_UNLOCK) {
32652527Sdavidn
32720253Sjoerg		if (a_name == NULL && pwd == NULL)	/* Try harder */
32844229Sdavidn			pwd = GETPWUID(atoi(a_uid->val));
32920253Sjoerg
33020253Sjoerg		if (pwd == NULL) {
33120253Sjoerg			if (mode == M_PRINT && getarg(args, 'F')) {
33220253Sjoerg				fakeuser.pw_name = a_name ? a_name->val : "nouser";
33320253Sjoerg				fakeuser.pw_uid = a_uid ? (uid_t) atol(a_uid->val) : -1;
33444386Sdavidn				return print_user(&fakeuser,
33544386Sdavidn						  getarg(args, 'P') != NULL,
33644386Sdavidn						  getarg(args, '7') != NULL);
33720253Sjoerg			}
33820253Sjoerg			if (a_name == NULL)
33930259Scharnier				errx(EX_NOUSER, "no such uid `%s'", a_uid->val);
34030259Scharnier			errx(EX_NOUSER, "no such user `%s'", a_name->val);
34120253Sjoerg		}
34252527Sdavidn
34320253Sjoerg		if (a_name == NULL)	/* May be needed later */
34420253Sjoerg			a_name = addarg(args, 'n', newstr(pwd->pw_name));
34520253Sjoerg
34620253Sjoerg		/*
34752512Sdavidn		 * The M_LOCK and M_UNLOCK functions simply add or remove
34852512Sdavidn		 * a "*LOCKED*" prefix from in front of the password to
34952512Sdavidn		 * prevent it decoding correctly, and therefore prevents
35052512Sdavidn		 * access. Of course, this only prevents access via
35152512Sdavidn		 * password authentication (not ssh, kerberos or any
35252512Sdavidn		 * other method that does not use the UNIX password) but
35352512Sdavidn		 * that is a known limitation.
35452512Sdavidn		 */
35552512Sdavidn
35652512Sdavidn		if (mode == M_LOCK) {
35752512Sdavidn			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
35852512Sdavidn				errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
35952512Sdavidn			passtmp = malloc(strlen(pwd->pw_passwd) + sizeof(locked_str));
36052512Sdavidn			if (passtmp == NULL)	/* disaster */
36152512Sdavidn				errx(EX_UNAVAILABLE, "out of memory");
36252512Sdavidn			strcpy(passtmp, locked_str);
36352512Sdavidn			strcat(passtmp, pwd->pw_passwd);
36452512Sdavidn			pwd->pw_passwd = passtmp;
36552527Sdavidn			edited = 1;
36652512Sdavidn		} else if (mode == M_UNLOCK) {
36752512Sdavidn			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
36852512Sdavidn				errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
36952512Sdavidn			pwd->pw_passwd += sizeof(locked_str)-1;
37052527Sdavidn			edited = 1;
37152527Sdavidn		} else if (mode == M_DELETE) {
37252527Sdavidn			/*
37352527Sdavidn			 * Handle deletions now
37452527Sdavidn			 */
37520253Sjoerg			char            file[MAXPATHLEN];
37620253Sjoerg			char            home[MAXPATHLEN];
37720253Sjoerg			uid_t           uid = pwd->pw_uid;
37820253Sjoerg
37920253Sjoerg			if (strcmp(pwd->pw_name, "root") == 0)
38030259Scharnier				errx(EX_DATAERR, "cannot remove user 'root'");
38120253Sjoerg
38244229Sdavidn			if (!PWALTDIR()) {
38344229Sdavidn				/*
38485145Sache				 * Remove opie record from /etc/opiekeys
38544229Sdavidn		        	 */
38620747Sdavidn
38785145Sache				rmopie(pwd->pw_name);
38820747Sdavidn
38944229Sdavidn				/*
39044229Sdavidn				 * Remove crontabs
39144229Sdavidn				 */
39244229Sdavidn				sprintf(file, "/var/cron/tabs/%s", pwd->pw_name);
39344229Sdavidn				if (access(file, F_OK) == 0) {
39444229Sdavidn					sprintf(file, "crontab -u %s -r", pwd->pw_name);
39544229Sdavidn					system(file);
39644229Sdavidn				}
39720253Sjoerg			}
39820253Sjoerg			/*
39920253Sjoerg			 * Save these for later, since contents of pwd may be
40020253Sjoerg			 * invalidated by deletion
40120253Sjoerg			 */
40220253Sjoerg			sprintf(file, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
403130633Srobert			strlcpy(home, pwd->pw_dir, sizeof(home));
40420253Sjoerg
40552502Sdavidn			rc = delpwent(pwd);
40652502Sdavidn			if (rc == -1)
40752502Sdavidn				err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
40852502Sdavidn			else if (rc != 0) {
40956000Sdavidn				warn("passwd update");
41052502Sdavidn				return EX_IOERR;
41152502Sdavidn			}
41221330Sdavidn
41352502Sdavidn			if (cnf->nispasswd && *cnf->nispasswd=='/') {
41452502Sdavidn				rc = delnispwent(cnf->nispasswd, a_name->val);
41552502Sdavidn				if (rc == -1)
41652502Sdavidn					warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
41752502Sdavidn				else if (rc != 0)
41856000Sdavidn					warn("WARNING: NIS passwd update");
41952502Sdavidn				/* non-fatal */
42052502Sdavidn			}
42152502Sdavidn
42220253Sjoerg			editgroups(a_name->val, NULL);
42320253Sjoerg
42420253Sjoerg			pw_log(cnf, mode, W_USER, "%s(%ld) account removed", a_name->val, (long) uid);
42520253Sjoerg
42644229Sdavidn			if (!PWALTDIR()) {
42744229Sdavidn				/*
42844229Sdavidn				 * Remove mail file
42944229Sdavidn				 */
43044229Sdavidn				remove(file);
43120253Sjoerg
43244229Sdavidn				/*
43344229Sdavidn				 * Remove at jobs
43444229Sdavidn				 */
43544229Sdavidn				if (getpwuid(uid) == NULL)
43644229Sdavidn					rmat(uid);
43720253Sjoerg
43844229Sdavidn				/*
43944229Sdavidn				 * Remove home directory and contents
44044229Sdavidn				 */
44144229Sdavidn				if (getarg(args, 'r') != NULL && *home == '/' && getpwuid(uid) == NULL) {
44244229Sdavidn					if (stat(home, &st) != -1) {
44344229Sdavidn						rm_r(home, uid);
44444229Sdavidn						pw_log(cnf, mode, W_USER, "%s(%ld) home '%s' %sremoved",
44544229Sdavidn						       a_name->val, (long) uid, home,
44644229Sdavidn						       stat(home, &st) == -1 ? "" : "not completely ");
44744229Sdavidn					}
44820253Sjoerg				}
44920253Sjoerg			}
45020267Sjoerg			return EXIT_SUCCESS;
45120253Sjoerg		} else if (mode == M_PRINT)
45244386Sdavidn			return print_user(pwd,
45344386Sdavidn					  getarg(args, 'P') != NULL,
45444386Sdavidn					  getarg(args, '7') != NULL);
45520253Sjoerg
45620253Sjoerg		/*
45720253Sjoerg		 * The rest is edit code
45820253Sjoerg		 */
45920253Sjoerg		if ((arg = getarg(args, 'l')) != NULL) {
46020253Sjoerg			if (strcmp(pwd->pw_name, "root") == 0)
46130259Scharnier				errx(EX_DATAERR, "can't rename `root' account");
46220679Sdavidn			pwd->pw_name = pw_checkname((u_char *)arg->val, 0);
46352527Sdavidn			edited = 1;
46420253Sjoerg		}
46552527Sdavidn
46661957Sache		if ((arg = getarg(args, 'u')) != NULL && isdigit((unsigned char)*arg->val)) {
46720253Sjoerg			pwd->pw_uid = (uid_t) atol(arg->val);
46852527Sdavidn			edited = 1;
46920253Sjoerg			if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
47030259Scharnier				errx(EX_DATAERR, "can't change uid of `root' account");
47120253Sjoerg			if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
47230259Scharnier				warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
47320253Sjoerg		}
47420253Sjoerg
47552527Sdavidn		if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {	/* Already checked this */
47652527Sdavidn			gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
47752527Sdavidn			if (newgid != pwd->pw_gid) {
47852527Sdavidn				edited = 1;
47961762Sdavidn				pwd->pw_gid = newgid;
48052527Sdavidn			}
48152527Sdavidn		}
48252527Sdavidn
48320253Sjoerg		if ((arg = getarg(args, 'p')) != NULL) {
48452527Sdavidn			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
48552527Sdavidn				if (pwd->pw_change != 0) {
48652527Sdavidn					pwd->pw_change = 0;
48752527Sdavidn					edited = 1;
48852527Sdavidn				}
48952527Sdavidn			}
49020253Sjoerg			else {
49120253Sjoerg				time_t          now = time(NULL);
49220253Sjoerg				time_t          expire = parse_date(now, arg->val);
49320253Sjoerg
49420253Sjoerg				if (now == expire)
49530259Scharnier					errx(EX_DATAERR, "invalid password change date `%s'", arg->val);
49652527Sdavidn				if (pwd->pw_change != expire) {
49752527Sdavidn					pwd->pw_change = expire;
49852527Sdavidn					edited = 1;
49952527Sdavidn				}
50020253Sjoerg			}
50120253Sjoerg		}
50252527Sdavidn
50320267Sjoerg		if ((arg = getarg(args, 'e')) != NULL) {
50452527Sdavidn			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
50552527Sdavidn				if (pwd->pw_expire != 0) {
50652527Sdavidn					pwd->pw_expire = 0;
50752527Sdavidn					edited = 1;
50852527Sdavidn				}
50952527Sdavidn			}
51020253Sjoerg			else {
51120253Sjoerg				time_t          now = time(NULL);
51220253Sjoerg				time_t          expire = parse_date(now, arg->val);
51320253Sjoerg
51420253Sjoerg				if (now == expire)
51530259Scharnier					errx(EX_DATAERR, "invalid account expiry date `%s'", arg->val);
51652527Sdavidn				if (pwd->pw_expire != expire) {
51752527Sdavidn					pwd->pw_expire = expire;
51852527Sdavidn					edited = 1;
51952527Sdavidn				}
52020253Sjoerg			}
52120253Sjoerg		}
52220253Sjoerg
52352527Sdavidn		if ((arg = getarg(args, 's')) != NULL) {
52452527Sdavidn			char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
52552527Sdavidn			if (shell == NULL)
52652527Sdavidn				shell = "";
52752527Sdavidn			if (strcmp(shell, pwd->pw_shell) != 0) {
52852527Sdavidn				pwd->pw_shell = shell;
52952527Sdavidn				edited = 1;
53052527Sdavidn			}
53152527Sdavidn		}
53220253Sjoerg
53352527Sdavidn		if (getarg(args, 'L')) {
53452527Sdavidn			if (cnf->default_class == NULL)
53552527Sdavidn				cnf->default_class = "";
53652527Sdavidn			if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
53752527Sdavidn				pwd->pw_class = cnf->default_class;
53852527Sdavidn				edited = 1;
53952527Sdavidn			}
54052527Sdavidn		}
54152527Sdavidn
54220747Sdavidn		if ((arg  = getarg(args, 'd')) != NULL) {
543130629Srobert			if (strcmp(pwd->pw_dir, arg->val))
544130629Srobert				edited = 1;
54520747Sdavidn			if (stat(pwd->pw_dir = arg->val, &st) == -1) {
54620747Sdavidn				if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
54730259Scharnier				  warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
54820747Sdavidn			} else if (!S_ISDIR(st.st_mode))
54930259Scharnier				warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
55020747Sdavidn		}
55120747Sdavidn
552124382Siedowse		if ((arg = getarg(args, 'w')) != NULL &&
553124382Siedowse		    getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
55464918Sgreen			login_cap_t *lc;
55564918Sgreen
55664918Sgreen			lc = login_getpwclass(pwd);
55764918Sgreen			if (lc == NULL ||
55864918Sgreen			    login_setcryptfmt(lc, "md5", NULL) == NULL)
55964918Sgreen				warn("setting crypt(3) format");
56064918Sgreen			login_close(lc);
56120267Sjoerg			pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
56252527Sdavidn			edited = 1;
56352527Sdavidn		}
56420267Sjoerg
56520253Sjoerg	} else {
56664918Sgreen		login_cap_t *lc;
56752527Sdavidn
56852527Sdavidn		/*
56952527Sdavidn		 * Add code
57052527Sdavidn		 */
57152527Sdavidn
57220253Sjoerg		if (a_name == NULL)	/* Required */
57330259Scharnier			errx(EX_DATAERR, "login name required");
57444229Sdavidn		else if ((pwd = GETPWNAM(a_name->val)) != NULL)	/* Exists */
57530259Scharnier			errx(EX_DATAERR, "login name `%s' already exists", a_name->val);
57620253Sjoerg
57720253Sjoerg		/*
57820253Sjoerg		 * Now, set up defaults for a new user
57920253Sjoerg		 */
58020253Sjoerg		pwd = &fakeuser;
58120253Sjoerg		pwd->pw_name = a_name->val;
58220253Sjoerg		pwd->pw_class = cnf->default_class ? cnf->default_class : "";
58320253Sjoerg		pwd->pw_uid = pw_uidpolicy(cnf, args);
58420253Sjoerg		pwd->pw_gid = pw_gidpolicy(cnf, args, pwd->pw_name, (gid_t) pwd->pw_uid);
58520253Sjoerg		pwd->pw_change = pw_pwdpolicy(cnf, args);
58620253Sjoerg		pwd->pw_expire = pw_exppolicy(cnf, args);
58720253Sjoerg		pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
58820253Sjoerg		pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
58964918Sgreen		lc = login_getpwclass(pwd);
59064918Sgreen		if (lc == NULL || login_setcryptfmt(lc, "md5", NULL) == NULL)
59164918Sgreen			warn("setting crypt(3) format");
59264918Sgreen		login_close(lc);
59364918Sgreen		pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
59452527Sdavidn		edited = 1;
59520253Sjoerg
59620253Sjoerg		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
59730259Scharnier			warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
59820253Sjoerg	}
59920253Sjoerg
60020253Sjoerg	/*
60120253Sjoerg	 * Shared add/edit code
60220253Sjoerg	 */
60352527Sdavidn	if ((arg = getarg(args, 'c')) != NULL) {
60452527Sdavidn		char	*gecos = pw_checkname((u_char *)arg->val, 1);
60552527Sdavidn		if (strcmp(pwd->pw_gecos, gecos) != 0) {
60652527Sdavidn			pwd->pw_gecos = gecos;
60752527Sdavidn			edited = 1;
60852527Sdavidn		}
60952527Sdavidn	}
61020253Sjoerg
611124382Siedowse	if ((arg = getarg(args, 'h')) != NULL ||
612124382Siedowse	    (arg = getarg(args, 'H')) != NULL) {
61363572Sdavidn		if (strcmp(arg->val, "-") == 0) {
61463572Sdavidn			if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
61563572Sdavidn				pwd->pw_passwd = "*";	/* No access */
61663572Sdavidn				edited = 1;
61763572Sdavidn			}
61863572Sdavidn		} else {
61920253Sjoerg			int             fd = atoi(arg->val);
620124382Siedowse			int		precrypt = (arg->ch == 'H');
62120253Sjoerg			int             b;
62220253Sjoerg			int             istty = isatty(fd);
62320253Sjoerg			struct termios  t;
62464918Sgreen			login_cap_t	*lc;
62520253Sjoerg
62620253Sjoerg			if (istty) {
62720253Sjoerg				if (tcgetattr(fd, &t) == -1)
62820253Sjoerg					istty = 0;
62920253Sjoerg				else {
63020253Sjoerg					struct termios  n = t;
63120253Sjoerg
63220253Sjoerg					/* Disable echo */
63320253Sjoerg					n.c_lflag &= ~(ECHO);
63420253Sjoerg					tcsetattr(fd, TCSANOW, &n);
635124382Siedowse					printf("%s%spassword for user %s:",
636124382Siedowse					     (mode == M_UPDATE) ? "new " : "",
637124382Siedowse					     precrypt ? "encrypted " : "",
638124382Siedowse					     pwd->pw_name);
63920253Sjoerg					fflush(stdout);
64020253Sjoerg				}
64120253Sjoerg			}
64220253Sjoerg			b = read(fd, line, sizeof(line) - 1);
64320253Sjoerg			if (istty) {	/* Restore state */
64420253Sjoerg				tcsetattr(fd, TCSANOW, &t);
64520253Sjoerg				fputc('\n', stdout);
64620253Sjoerg				fflush(stdout);
64720253Sjoerg			}
64820253Sjoerg			if (b < 0) {
649124382Siedowse				warn("-%c file descriptor", precrypt ? 'H' :
650124382Siedowse				    'h');
65120267Sjoerg				return EX_IOERR;
65220253Sjoerg			}
65320253Sjoerg			line[b] = '\0';
65420253Sjoerg			if ((p = strpbrk(line, " \t\r\n")) != NULL)
65520253Sjoerg				*p = '\0';
65620253Sjoerg			if (!*line)
65730259Scharnier				errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
658124382Siedowse			if (precrypt) {
659124382Siedowse				if (strchr(line, ':') != NULL)
660124382Siedowse					return EX_DATAERR;
661124382Siedowse				pwd->pw_passwd = line;
662124382Siedowse			} else {
663124382Siedowse				lc = login_getpwclass(pwd);
664124382Siedowse				if (lc == NULL ||
665124382Siedowse				    login_setcryptfmt(lc, "md5", NULL) == NULL)
666124382Siedowse					warn("setting crypt(3) format");
667124382Siedowse				login_close(lc);
668124382Siedowse				pwd->pw_passwd = pw_pwcrypt(line);
669124382Siedowse			}
67052527Sdavidn			edited = 1;
67120253Sjoerg		}
67220253Sjoerg	}
67320267Sjoerg
67420267Sjoerg	/*
67520267Sjoerg	 * Special case: -N only displays & exits
67620267Sjoerg	 */
67720267Sjoerg	if (getarg(args, 'N') != NULL)
67844386Sdavidn		return print_user(pwd,
67944386Sdavidn				  getarg(args, 'P') != NULL,
68044386Sdavidn				  getarg(args, '7') != NULL);
68120267Sjoerg
68221330Sdavidn	if (mode == M_ADD) {
68352527Sdavidn		edited = 1;	/* Always */
68452502Sdavidn		rc = addpwent(pwd);
68552502Sdavidn		if (rc == -1) {
68652502Sdavidn			warnx("user '%s' already exists", pwd->pw_name);
68752502Sdavidn			return EX_IOERR;
68852502Sdavidn		} else if (rc != 0) {
68956000Sdavidn			warn("passwd file update");
69052502Sdavidn			return EX_IOERR;
69152502Sdavidn		}
69252502Sdavidn		if (cnf->nispasswd && *cnf->nispasswd=='/') {
69352502Sdavidn			rc = addnispwent(cnf->nispasswd, pwd);
69452502Sdavidn			if (rc == -1)
69552502Sdavidn				warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
69652502Sdavidn			else
69756000Sdavidn				warn("NIS passwd update");
69852502Sdavidn			/* NOTE: we treat NIS-only update errors as non-fatal */
69952502Sdavidn		}
70052512Sdavidn	} else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
70152527Sdavidn		if (edited) {	/* Only updated this if required */
70252527Sdavidn			rc = chgpwent(a_name->val, pwd);
70352527Sdavidn			if (rc == -1) {
70452527Sdavidn				warnx("user '%s' does not exist (NIS?)", pwd->pw_name);
70552527Sdavidn				return EX_IOERR;
70652527Sdavidn			} else if (rc != 0) {
70756000Sdavidn				warn("passwd file update");
70852527Sdavidn				return EX_IOERR;
70952527Sdavidn			}
71052527Sdavidn			if ( cnf->nispasswd && *cnf->nispasswd=='/') {
71152527Sdavidn				rc = chgnispwent(cnf->nispasswd, a_name->val, pwd);
71252527Sdavidn				if (rc == -1)
71352527Sdavidn					warn("User '%s' not found in NIS passwd", pwd->pw_name);
71452527Sdavidn				else
71556000Sdavidn					warn("NIS passwd update");
71652527Sdavidn				/* NOTE: NIS-only update errors are not fatal */
71752527Sdavidn			}
71852502Sdavidn		}
71921330Sdavidn	}
72021330Sdavidn
72120253Sjoerg	/*
72220253Sjoerg	 * Ok, user is created or changed - now edit group file
72320253Sjoerg	 */
72420253Sjoerg
72520253Sjoerg	if (mode == M_ADD || getarg(args, 'G') != NULL)
72620253Sjoerg		editgroups(pwd->pw_name, cnf->groups);
72720253Sjoerg
72861759Sdavidn	/* go get a current version of pwd */
72961759Sdavidn	pwd = GETPWNAM(a_name->val);
73061759Sdavidn	if (pwd == NULL) {
73161759Sdavidn		/* This will fail when we rename, so special case that */
73261759Sdavidn		if (mode == M_UPDATE && (arg = getarg(args, 'l')) != NULL) {
73361759Sdavidn			a_name->val = arg->val;		/* update new name */
73461759Sdavidn			pwd = GETPWNAM(a_name->val);	/* refetch renamed rec */
73561759Sdavidn		}
73661759Sdavidn	}
73761759Sdavidn	if (pwd == NULL)	/* can't go on without this */
73830259Scharnier		errx(EX_NOUSER, "user '%s' disappeared during update", a_name->val);
73920253Sjoerg
74044229Sdavidn	grp = GETGRGID(pwd->pw_gid);
74198744Sdwmalone	pw_log(cnf, mode, W_USER, "%s(%ld):%s(%ld):%s:%s:%s",
74220253Sjoerg	       pwd->pw_name, (long) pwd->pw_uid,
74320253Sjoerg	    grp ? grp->gr_name : "unknown", (long) (grp ? grp->gr_gid : -1),
74420253Sjoerg	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
74520253Sjoerg
74620253Sjoerg	/*
74720253Sjoerg	 * If adding, let's touch and chown the user's mail file. This is not
74820253Sjoerg	 * strictly necessary under BSD with a 0755 maildir but it also
74920253Sjoerg	 * doesn't hurt anything to create the empty mailfile
75020253Sjoerg	 */
75120253Sjoerg	if (mode == M_ADD) {
75244229Sdavidn		if (!PWALTDIR()) {
75344229Sdavidn			sprintf(line, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
75444229Sdavidn			close(open(line, O_RDWR | O_CREAT, 0600));	/* Preserve contents &
75544229Sdavidn									 * mtime */
75644229Sdavidn			chown(line, pwd->pw_uid, pwd->pw_gid);
75720253Sjoerg		}
75820253Sjoerg	}
75952527Sdavidn
76020253Sjoerg	/*
76182868Sdd	 * Let's create and populate the user's home directory. Note
76220253Sjoerg	 * that this also `works' for editing users if -m is used, but
76320253Sjoerg	 * existing files will *not* be overwritten.
76420253Sjoerg	 */
76544229Sdavidn	if (!PWALTDIR() && getarg(args, 'm') != NULL && pwd->pw_dir && *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
76620253Sjoerg		copymkdir(pwd->pw_dir, cnf->dotdir, 0755, pwd->pw_uid, pwd->pw_gid);
76720253Sjoerg		pw_log(cnf, mode, W_USER, "%s(%ld) home %s made",
76820253Sjoerg		       pwd->pw_name, (long) pwd->pw_uid, pwd->pw_dir);
76920253Sjoerg	}
77052527Sdavidn
77182868Sdd
77282868Sdd	/*
77382868Sdd	 * Finally, send mail to the new user as well, if we are asked to
77482868Sdd	 */
77582868Sdd	if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
77682868Sdd		FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
77782868Sdd
77882868Sdd		if (pfp == NULL)
77982868Sdd			warn("sendmail");
78082868Sdd		else {
78182868Sdd			fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
78282868Sdd			while (fgets(line, sizeof(line), fp) != NULL) {
78382868Sdd				/* Do substitutions? */
78482868Sdd				fputs(line, pfp);
78582868Sdd			}
78682868Sdd			pclose(pfp);
78782868Sdd			pw_log(cnf, mode, W_USER, "%s(%ld) new user mail sent",
78882868Sdd			    pwd->pw_name, (long) pwd->pw_uid);
78982868Sdd		}
79082868Sdd		fclose(fp);
79182868Sdd	}
79282868Sdd
79320267Sjoerg	return EXIT_SUCCESS;
79420253Sjoerg}
79520253Sjoerg
79620253Sjoerg
79720253Sjoergstatic          uid_t
79820253Sjoergpw_uidpolicy(struct userconf * cnf, struct cargs * args)
79920253Sjoerg{
80020253Sjoerg	struct passwd  *pwd;
80120253Sjoerg	uid_t           uid = (uid_t) - 1;
80220253Sjoerg	struct carg    *a_uid = getarg(args, 'u');
80320253Sjoerg
80420253Sjoerg	/*
80520253Sjoerg	 * Check the given uid, if any
80620253Sjoerg	 */
80720253Sjoerg	if (a_uid != NULL) {
80820253Sjoerg		uid = (uid_t) atol(a_uid->val);
80920253Sjoerg
81044229Sdavidn		if ((pwd = GETPWUID(uid)) != NULL && getarg(args, 'o') == NULL)
81130259Scharnier			errx(EX_DATAERR, "uid `%ld' has already been allocated", (long) pwd->pw_uid);
81220253Sjoerg	} else {
81320253Sjoerg		struct bitmap   bm;
81420253Sjoerg
81520253Sjoerg		/*
81620253Sjoerg		 * We need to allocate the next available uid under one of
81720253Sjoerg		 * two policies a) Grab the first unused uid b) Grab the
81820253Sjoerg		 * highest possible unused uid
81920253Sjoerg		 */
82020253Sjoerg		if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
82120253Sjoerg							 * claus^H^H^H^Hheck */
82220253Sjoerg			cnf->min_uid = 1000;
82320253Sjoerg			cnf->max_uid = 32000;
82420253Sjoerg		}
82520253Sjoerg		bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
82620253Sjoerg
82720253Sjoerg		/*
82820253Sjoerg		 * Now, let's fill the bitmap from the password file
82920253Sjoerg		 */
83044229Sdavidn		SETPWENT();
83144229Sdavidn		while ((pwd = GETPWENT()) != NULL)
83244229Sdavidn			if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
83320253Sjoerg				bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
83444229Sdavidn		ENDPWENT();
83520253Sjoerg
83620253Sjoerg		/*
83720253Sjoerg		 * Then apply the policy, with fallback to reuse if necessary
83820253Sjoerg		 */
83920253Sjoerg		if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
84020253Sjoerg			uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
84120253Sjoerg
84220253Sjoerg		/*
84320253Sjoerg		 * Another sanity check
84420253Sjoerg		 */
84520253Sjoerg		if (uid < cnf->min_uid || uid > cnf->max_uid)
84630259Scharnier			errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
84720253Sjoerg		bm_dealloc(&bm);
84820253Sjoerg	}
84920253Sjoerg	return uid;
85020253Sjoerg}
85120253Sjoerg
85220253Sjoerg
85320253Sjoergstatic          uid_t
85420253Sjoergpw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer)
85520253Sjoerg{
85620253Sjoerg	struct group   *grp;
85720253Sjoerg	gid_t           gid = (uid_t) - 1;
85820253Sjoerg	struct carg    *a_gid = getarg(args, 'g');
85920253Sjoerg
86020253Sjoerg	/*
86120253Sjoerg	 * If no arg given, see if default can help out
86220253Sjoerg	 */
86320253Sjoerg	if (a_gid == NULL && cnf->default_group && *cnf->default_group)
86420253Sjoerg		a_gid = addarg(args, 'g', cnf->default_group);
86520253Sjoerg
86620253Sjoerg	/*
86720253Sjoerg	 * Check the given gid, if any
86820253Sjoerg	 */
86944229Sdavidn	SETGRENT();
87020253Sjoerg	if (a_gid != NULL) {
87144229Sdavidn		if ((grp = GETGRNAM(a_gid->val)) == NULL) {
87220253Sjoerg			gid = (gid_t) atol(a_gid->val);
87361957Sache			if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
87430259Scharnier				errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
87520253Sjoerg		}
87620253Sjoerg		gid = grp->gr_gid;
87744229Sdavidn	} else if ((grp = GETGRNAM(nam)) != NULL && grp->gr_mem[0] == NULL) {
87820267Sjoerg		gid = grp->gr_gid;  /* Already created? Use it anyway... */
87920253Sjoerg	} else {
88020253Sjoerg		struct cargs    grpargs;
88120253Sjoerg		char            tmp[32];
88220253Sjoerg
88320253Sjoerg		LIST_INIT(&grpargs);
88420253Sjoerg		addarg(&grpargs, 'n', nam);
88520253Sjoerg
88620253Sjoerg		/*
88720253Sjoerg		 * We need to auto-create a group with the user's name. We
88820253Sjoerg		 * can send all the appropriate output to our sister routine
88920253Sjoerg		 * bit first see if we can create a group with gid==uid so we
89020253Sjoerg		 * can keep the user and group ids in sync. We purposely do
89120253Sjoerg		 * NOT check the gid range if we can force the sync. If the
89220253Sjoerg		 * user's name dups an existing group, then the group add
89320253Sjoerg		 * function will happily handle that case for us and exit.
89420253Sjoerg		 */
89544229Sdavidn		if (GETGRGID(prefer) == NULL) {
89620253Sjoerg			sprintf(tmp, "%lu", (unsigned long) prefer);
89720253Sjoerg			addarg(&grpargs, 'g', tmp);
89820253Sjoerg		}
89920267Sjoerg		if (getarg(args, 'N'))
90020267Sjoerg		{
90120267Sjoerg			addarg(&grpargs, 'N', NULL);
90220267Sjoerg			addarg(&grpargs, 'q', NULL);
90320267Sjoerg			gid = pw_group(cnf, M_NEXT, &grpargs);
90420267Sjoerg		}
90520267Sjoerg		else
90620267Sjoerg		{
90720267Sjoerg			pw_group(cnf, M_ADD, &grpargs);
90844229Sdavidn			if ((grp = GETGRNAM(nam)) != NULL)
90920267Sjoerg				gid = grp->gr_gid;
91020267Sjoerg		}
91170486Sben		a_gid = LIST_FIRST(&grpargs);
91220253Sjoerg		while (a_gid != NULL) {
91370486Sben			struct carg    *t = LIST_NEXT(a_gid, list);
91420253Sjoerg			LIST_REMOVE(a_gid, list);
91520253Sjoerg			a_gid = t;
91620253Sjoerg		}
91720253Sjoerg	}
91844229Sdavidn	ENDGRENT();
91920253Sjoerg	return gid;
92020253Sjoerg}
92120253Sjoerg
92220253Sjoerg
92320253Sjoergstatic          time_t
92420253Sjoergpw_pwdpolicy(struct userconf * cnf, struct cargs * args)
92520253Sjoerg{
92620253Sjoerg	time_t          result = 0;
92720253Sjoerg	time_t          now = time(NULL);
92827831Sdavidn	struct carg    *arg = getarg(args, 'p');
92920253Sjoerg
93020253Sjoerg	if (arg != NULL) {
93120253Sjoerg		if ((result = parse_date(now, arg->val)) == now)
93230259Scharnier			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
93320253Sjoerg	} else if (cnf->password_days > 0)
93420253Sjoerg		result = now + ((long) cnf->password_days * 86400L);
93520253Sjoerg	return result;
93620253Sjoerg}
93720253Sjoerg
93820253Sjoerg
93920253Sjoergstatic          time_t
94020253Sjoergpw_exppolicy(struct userconf * cnf, struct cargs * args)
94120253Sjoerg{
94220253Sjoerg	time_t          result = 0;
94320253Sjoerg	time_t          now = time(NULL);
94420253Sjoerg	struct carg    *arg = getarg(args, 'e');
94520253Sjoerg
94620253Sjoerg	if (arg != NULL) {
94720253Sjoerg		if ((result = parse_date(now, arg->val)) == now)
94830259Scharnier			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
94920253Sjoerg	} else if (cnf->expire_days > 0)
95020253Sjoerg		result = now + ((long) cnf->expire_days * 86400L);
95120253Sjoerg	return result;
95220253Sjoerg}
95320253Sjoerg
95420253Sjoerg
95520253Sjoergstatic char    *
95620253Sjoergpw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
95720253Sjoerg{
95820253Sjoerg	struct carg    *arg = getarg(args, 'd');
95920253Sjoerg
96020253Sjoerg	if (arg)
96120253Sjoerg		return arg->val;
96220253Sjoerg	else {
96320253Sjoerg		static char     home[128];
96420253Sjoerg
96520253Sjoerg		if (cnf->home == NULL || *cnf->home == '\0')
96630259Scharnier			errx(EX_CONFIG, "no base home directory set");
96720253Sjoerg		sprintf(home, "%s/%s", cnf->home, user);
96820253Sjoerg		return home;
96920253Sjoerg	}
97020253Sjoerg}
97120253Sjoerg
97220253Sjoergstatic char    *
97320253Sjoergshell_path(char const * path, char *shells[], char *sh)
97420253Sjoerg{
97520253Sjoerg	if (sh != NULL && (*sh == '/' || *sh == '\0'))
97620253Sjoerg		return sh;	/* specified full path or forced none */
97720253Sjoerg	else {
97820253Sjoerg		char           *p;
97920253Sjoerg		char            paths[_UC_MAXLINE];
98020253Sjoerg
98120253Sjoerg		/*
98220253Sjoerg		 * We need to search paths
98320253Sjoerg		 */
984130633Srobert		strlcpy(paths, path, sizeof(paths));
98520253Sjoerg		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
98620253Sjoerg			int             i;
98720253Sjoerg			static char     shellpath[256];
98820253Sjoerg
98920253Sjoerg			if (sh != NULL) {
99020253Sjoerg				sprintf(shellpath, "%s/%s", p, sh);
99120253Sjoerg				if (access(shellpath, X_OK) == 0)
99220253Sjoerg					return shellpath;
99320253Sjoerg			} else
99420253Sjoerg				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
99520253Sjoerg					sprintf(shellpath, "%s/%s", p, shells[i]);
99620253Sjoerg					if (access(shellpath, X_OK) == 0)
99720253Sjoerg						return shellpath;
99820253Sjoerg				}
99920253Sjoerg		}
100020253Sjoerg		if (sh == NULL)
100130259Scharnier			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
100230259Scharnier		errx(EX_CONFIG, "no default shell available or defined");
100320253Sjoerg		return NULL;
100420253Sjoerg	}
100520253Sjoerg}
100620253Sjoerg
100720253Sjoerg
100820253Sjoergstatic char    *
100920253Sjoergpw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
101020253Sjoerg{
101120253Sjoerg	char           *sh = newshell;
101220253Sjoerg	struct carg    *arg = getarg(args, 's');
101320253Sjoerg
101420253Sjoerg	if (newshell == NULL && arg != NULL)
101520253Sjoerg		sh = arg->val;
101620253Sjoerg	return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
101720253Sjoerg}
101820253Sjoerg
101920253Sjoergstatic char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.";
102020253Sjoerg
102120253Sjoergchar           *
102220253Sjoergpw_pwcrypt(char *password)
102320253Sjoerg{
102420253Sjoerg	int             i;
102520253Sjoerg	char            salt[12];
102620253Sjoerg
102720253Sjoerg	static char     buf[256];
102820253Sjoerg
102920253Sjoerg	/*
103020253Sjoerg	 * Calculate a salt value
103120253Sjoerg	 */
103220253Sjoerg	for (i = 0; i < 8; i++)
103373563Skris		salt[i] = chars[arc4random() % 63];
103420253Sjoerg	salt[i] = '\0';
103520253Sjoerg
103620253Sjoerg	return strcpy(buf, crypt(password, salt));
103720253Sjoerg}
103820253Sjoerg
103920590Sdavidn#if defined(USE_MD5RAND)
104020555Sdavidnu_char *
104120590Sdavidnpw_getrand(u_char *buf, int len)	/* cryptographically secure rng */
104220555Sdavidn{
104320590Sdavidn	int i;
104420590Sdavidn	for (i=0;i<len;i+=16) {
104520590Sdavidn		u_char ubuf[16];
104620590Sdavidn
104720590Sdavidn		MD5_CTX md5_ctx;
104820590Sdavidn		struct timeval tv, tvo;
104920590Sdavidn		struct rusage ru;
105020590Sdavidn		int n=0;
105120590Sdavidn		int t;
105220590Sdavidn
105320590Sdavidn		MD5Init (&md5_ctx);
105420590Sdavidn		t=getpid();
105520590Sdavidn		MD5Update (&md5_ctx, (u_char*)&t, sizeof t);
105620590Sdavidn		t=getppid();
105720590Sdavidn		MD5Update (&md5_ctx, (u_char*)&t, sizeof t);
105820590Sdavidn		gettimeofday (&tvo, NULL);
105920590Sdavidn		do {
106020590Sdavidn			getrusage (RUSAGE_SELF, &ru);
106120590Sdavidn			MD5Update (&md5_ctx, (u_char*)&ru, sizeof ru);
106220590Sdavidn			gettimeofday (&tv, NULL);
106320590Sdavidn			MD5Update (&md5_ctx, (u_char*)&tv, sizeof tv);
106420590Sdavidn		} while (n++<20 || tv.tv_usec-tvo.tv_usec<100*1000);
106520590Sdavidn		MD5Final (ubuf, &md5_ctx);
106682047Sjoerg		memcpy(buf+i, ubuf, MIN(16, len-i));
106720590Sdavidn	}
106820590Sdavidn	return buf;
106920555Sdavidn}
107020253Sjoerg
107120590Sdavidn#else	/* Portable version */
107220590Sdavidn
107320590Sdavidnstatic u_char *
107420590Sdavidnpw_getrand(u_char *buf, int len)
107520590Sdavidn{
107620590Sdavidn	int i;
107720590Sdavidn
107820590Sdavidn	for (i = 0; i < len; i++) {
1079110667Sache		unsigned long val = arc4random();
108020590Sdavidn		/* Use all bits in the random value */
108120590Sdavidn		buf[i]=(u_char)((val >> 24) ^ (val >> 16) ^ (val >> 8) ^ val);
108220590Sdavidn	}
108320590Sdavidn	return buf;
108420590Sdavidn}
108520590Sdavidn
108620590Sdavidn#endif
108720590Sdavidn
108820253Sjoergstatic char    *
108920253Sjoergpw_password(struct userconf * cnf, struct cargs * args, char const * user)
109020253Sjoerg{
109120253Sjoerg	int             i, l;
109220253Sjoerg	char            pwbuf[32];
109320555Sdavidn	u_char		rndbuf[sizeof pwbuf];
109420253Sjoerg
109520253Sjoerg	switch (cnf->default_password) {
109620253Sjoerg	case -1:		/* Random password */
109773563Skris		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
109820555Sdavidn		pw_getrand(rndbuf, l);
109920253Sjoerg		for (i = 0; i < l; i++)
110042245Sbillf			pwbuf[i] = chars[rndbuf[i] % (sizeof(chars)-1)];
110120253Sjoerg		pwbuf[i] = '\0';
110220253Sjoerg
110320253Sjoerg		/*
110420253Sjoerg		 * We give this information back to the user
110520253Sjoerg		 */
1106124382Siedowse		if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
1107124382Siedowse		    getarg(args, 'N') == NULL) {
110861957Sache			if (isatty(STDOUT_FILENO))
110920712Sdavidn				printf("Password for '%s' is: ", user);
111020253Sjoerg			printf("%s\n", pwbuf);
111120253Sjoerg			fflush(stdout);
111220253Sjoerg		}
111320253Sjoerg		break;
111420253Sjoerg
111520253Sjoerg	case -2:		/* No password at all! */
111620253Sjoerg		return "";
111720253Sjoerg
111820253Sjoerg	case 0:		/* No login - default */
111920253Sjoerg	default:
112020253Sjoerg		return "*";
112120253Sjoerg
112220253Sjoerg	case 1:		/* user's name */
1123130633Srobert		strlcpy(pwbuf, user, sizeof(pwbuf));
112420253Sjoerg		break;
112520253Sjoerg	}
112620253Sjoerg	return pw_pwcrypt(pwbuf);
112720253Sjoerg}
112820253Sjoerg
112920253Sjoerg
113020253Sjoergstatic int
113144386Sdavidnprint_user(struct passwd * pwd, int pretty, int v7)
113220253Sjoerg{
113320253Sjoerg	if (!pretty) {
113420253Sjoerg		char            buf[_UC_MAXLINE];
113520253Sjoerg
113644386Sdavidn		fmtpwentry(buf, pwd, v7 ? PWF_PASSWD : PWF_STANDARD);
113720253Sjoerg		fputs(buf, stdout);
113820253Sjoerg	} else {
113920267Sjoerg		int		j;
114020253Sjoerg		char           *p;
114144229Sdavidn		struct group   *grp = GETGRGID(pwd->pw_gid);
114220253Sjoerg		char            uname[60] = "User &", office[60] = "[None]",
114320253Sjoerg		                wphone[60] = "[None]", hphone[60] = "[None]";
114420590Sdavidn		char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
114520590Sdavidn		struct tm *    tptr;
114620253Sjoerg
114720253Sjoerg		if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1148130633Srobert			strlcpy(uname, p, sizeof(uname));
114920253Sjoerg			if ((p = strtok(NULL, ",")) != NULL) {
1150130633Srobert				strlcpy(office, p, sizeof(office));
115120253Sjoerg				if ((p = strtok(NULL, ",")) != NULL) {
1152130633Srobert					strlcpy(wphone, p, sizeof(wphone));
115320253Sjoerg					if ((p = strtok(NULL, "")) != NULL) {
1154130633Srobert						strlcpy(hphone, p,
1155130633Srobert						    sizeof(hphone));
115620253Sjoerg					}
115720253Sjoerg				}
115820253Sjoerg			}
115920253Sjoerg		}
116020253Sjoerg		/*
116120253Sjoerg		 * Handle '&' in gecos field
116220253Sjoerg		 */
116320253Sjoerg		if ((p = strchr(uname, '&')) != NULL) {
116420253Sjoerg			int             l = strlen(pwd->pw_name);
116520253Sjoerg			int             m = strlen(p);
116620253Sjoerg
116720253Sjoerg			memmove(p + l, p + 1, m);
116820253Sjoerg			memmove(p, pwd->pw_name, l);
116961957Sache			*p = (char) toupper((unsigned char)*p);
117020253Sjoerg		}
117120590Sdavidn		if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
117274569Sache			strftime(acexpire, sizeof acexpire, "%c", tptr);
117361957Sache		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
117474569Sache			strftime(pwexpire, sizeof pwexpire, "%c", tptr);
117522394Sdavidn		printf("Login Name: %-15s   #%-12ld Group: %-15s   #%ld\n"
117620747Sdavidn		       " Full Name: %s\n"
117720747Sdavidn		       "      Home: %-26.26s      Class: %s\n"
117820747Sdavidn		       "     Shell: %-26.26s     Office: %s\n"
117920747Sdavidn		       "Work Phone: %-26.26s Home Phone: %s\n"
118020747Sdavidn		       "Acc Expire: %-26.26s Pwd Expire: %s\n",
118120253Sjoerg		       pwd->pw_name, (long) pwd->pw_uid,
118220253Sjoerg		       grp ? grp->gr_name : "(invalid)", (long) pwd->pw_gid,
118320253Sjoerg		       uname, pwd->pw_dir, pwd->pw_class,
118420590Sdavidn		       pwd->pw_shell, office, wphone, hphone,
118520590Sdavidn		       acexpire, pwexpire);
118644229Sdavidn	        SETGRENT();
118720267Sjoerg		j = 0;
118844229Sdavidn		while ((grp=GETGRENT()) != NULL)
118920267Sjoerg		{
119020267Sjoerg			int     i = 0;
119120747Sdavidn			while (grp->gr_mem[i] != NULL)
119220267Sjoerg			{
119320267Sjoerg				if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
119420267Sjoerg				{
119520747Sdavidn					printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
119620267Sjoerg					break;
119720267Sjoerg				}
119820267Sjoerg				++i;
119920267Sjoerg			}
120020267Sjoerg		}
120144229Sdavidn		ENDGRENT();
120261957Sache		printf("%s", j ? "\n" : "");
120320253Sjoerg	}
120420267Sjoerg	return EXIT_SUCCESS;
120520253Sjoerg}
120620253Sjoerg
120720679Sdavidnchar    *
120820679Sdavidnpw_checkname(u_char *name, int gecos)
120920253Sjoerg{
1210109961Sgad	char showch[8];
1211109961Sgad	u_char const *badchars, *ch, *showtype;
1212109961Sgad	int reject;
121320253Sjoerg
1214109961Sgad	ch = name;
1215109961Sgad	reject = 0;
1216109961Sgad	if (gecos) {
1217109961Sgad		/* See if the name is valid as a gecos (comment) field. */
1218109961Sgad		badchars = ":!@";
1219109961Sgad		showtype = "gecos field";
1220109961Sgad	} else {
1221109961Sgad		/* See if the name is valid as a userid or group. */
1222109961Sgad		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1223109961Sgad		showtype = "userid/group name";
1224109961Sgad		/* Userids and groups can not have a leading '-'. */
1225109961Sgad		if (*ch == '-')
1226109961Sgad			reject = 1;
122720253Sjoerg	}
1228109961Sgad	if (!reject) {
1229109961Sgad		while (*ch) {
1230109961Sgad			if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1231109961Sgad			    *ch == 127) {
1232109961Sgad				reject = 1;
1233109961Sgad				break;
1234109961Sgad			}
1235109961Sgad			/* 8-bit characters are only allowed in GECOS fields */
1236109961Sgad			if (!gecos && (*ch & 0x80)) {
1237109961Sgad				reject = 1;
1238109961Sgad				break;
1239109961Sgad			}
1240109961Sgad			ch++;
1241109961Sgad		}
1242109961Sgad	}
1243109961Sgad	/*
1244109961Sgad	 * A `$' is allowed as the final character for userids and groups,
1245109961Sgad	 * mainly for the benefit of samba.
1246109961Sgad	 */
1247109961Sgad	if (reject && !gecos) {
1248109961Sgad		if (*ch == '$' && *(ch + 1) == '\0') {
1249109961Sgad			reject = 0;
1250109961Sgad			ch++;
1251109961Sgad		}
1252109961Sgad	}
1253109961Sgad	if (reject) {
1254109961Sgad		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1255109961Sgad		    ? "`%c'" : "0x%02x", *ch);
1256109961Sgad		errx(EX_DATAERR, "invalid character %s at position %d in %s",
1257109961Sgad		    showch, (ch - name), showtype);
1258109961Sgad	}
1259109961Sgad	if (!gecos && (ch - name) > LOGNAMESIZE)
1260109961Sgad		errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1261109961Sgad		    LOGNAMESIZE);
126220679Sdavidn	return (char *)name;
126320253Sjoerg}
126420253Sjoerg
126520253Sjoerg
126620253Sjoergstatic void
126720253Sjoergrmat(uid_t uid)
126820253Sjoerg{
126920253Sjoerg	DIR            *d = opendir("/var/at/jobs");
127020253Sjoerg
127120253Sjoerg	if (d != NULL) {
127220253Sjoerg		struct dirent  *e;
127320253Sjoerg
127420253Sjoerg		while ((e = readdir(d)) != NULL) {
127520253Sjoerg			struct stat     st;
127620253Sjoerg
127720253Sjoerg			if (strncmp(e->d_name, ".lock", 5) != 0 &&
127820253Sjoerg			    stat(e->d_name, &st) == 0 &&
127920253Sjoerg			    !S_ISDIR(st.st_mode) &&
128020253Sjoerg			    st.st_uid == uid) {
128120253Sjoerg				char            tmp[MAXPATHLEN];
128220253Sjoerg
128320253Sjoerg				sprintf(tmp, "/usr/bin/atrm %s", e->d_name);
128420253Sjoerg				system(tmp);
128520253Sjoerg			}
128620253Sjoerg		}
128720253Sjoerg		closedir(d);
128820253Sjoerg	}
128920253Sjoerg}
129020747Sdavidn
129120747Sdavidnstatic void
129285145Sachermopie(char const * name)
129320747Sdavidn{
129485145Sache	static const char etcopie[] = "/etc/opiekeys";
129585145Sache	FILE   *fp = fopen(etcopie, "r+");
129620747Sdavidn
129721052Sdavidn	if (fp != NULL) {
129821052Sdavidn		char	tmp[1024];
129921052Sdavidn		off_t	atofs = 0;
130021052Sdavidn		int	length = strlen(name);
130120747Sdavidn
130221052Sdavidn		while (fgets(tmp, sizeof tmp, fp) != NULL) {
130321052Sdavidn			if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
130421052Sdavidn				if (fseek(fp, atofs, SEEK_SET) == 0) {
130521052Sdavidn					fwrite("#", 1, 1, fp);	/* Comment username out */
130621052Sdavidn				}
130721052Sdavidn				break;
130820747Sdavidn			}
130921052Sdavidn			atofs = ftell(fp);
131020747Sdavidn		}
131121052Sdavidn		/*
131221052Sdavidn		 * If we got an error of any sort, don't update!
131321052Sdavidn		 */
131421052Sdavidn		fclose(fp);
131520747Sdavidn	}
131620747Sdavidn}
131720747Sdavidn
1318