1169689Skan/*-
2169689Skan * SPDX-License-Identifier: BSD-2-Clause
3169689Skan *
4169689Skan * Copyright (C) 1996
5169689Skan *	David L. Nugent.  All rights reserved.
6169689Skan *
7169689Skan * Redistribution and use in source and binary forms, with or without
8169689Skan * modification, are permitted provided that the following conditions
9169689Skan * are met:
10169689Skan * 1. Redistributions of source code must retain the above copyright
11169689Skan *    notice, this list of conditions and the following disclaimer.
12169689Skan * 2. Redistributions in binary form must reproduce the above copyright
13169689Skan *    notice, this list of conditions and the following disclaimer in the
14169689Skan *    documentation and/or other materials provided with the distribution.
15169689Skan *
16169689Skan * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
17169689Skan * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18169689Skan * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19169689Skan * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
20169689Skan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21169689Skan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22169689Skan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23169689Skan * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24169689Skan * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25169689Skan * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26169689Skan * SUCH DAMAGE.
27169689Skan *
28169689Skan */
29169689Skan
30169689Skan#include <sys/param.h>
31169689Skan#include <sys/wait.h>
32169689Skan
33169689Skan#include <assert.h>
34169689Skan#include <ctype.h>
35169689Skan#include <dirent.h>
36169689Skan#include <err.h>
37169689Skan#include <errno.h>
38169689Skan#include <fcntl.h>
39169689Skan#include <grp.h>
40169689Skan#include <pwd.h>
41169689Skan#include <libutil.h>
42169689Skan#include <login_cap.h>
43169689Skan#include <paths.h>
44169689Skan#include <string.h>
45169689Skan#include <sysexits.h>
46169689Skan#include <termios.h>
47169689Skan#include <unistd.h>
48169689Skan#include <spawn.h>
49169689Skan
50169689Skan#include "pw.h"
51169689Skan#include "bitmap.h"
52169689Skan#include "psdate.h"
53169689Skan
54169689Skan#define LOGNAMESIZE (MAXLOGNAME-1)
55169689Skan
56169689Skanextern char **environ;
57169689Skanstatic		char locked_str[] = "*LOCKED*";
58169689Skan
59169689Skanstatic struct passwd fakeuser = {
60169689Skan	"nouser",
61169689Skan	"*",
62169689Skan	-1,
63169689Skan	-1,
64169689Skan	0,
65169689Skan	"",
66169689Skan	"User &",
67169689Skan	"/nonexistent",
68169689Skan	"/bin/sh",
69169689Skan	0,
70169689Skan	0
71169689Skan};
72169689Skan
73169689Skanstatic int	 print_user(struct passwd *pwd, bool pretty, bool v7);
74169689Skanstatic uid_t	 pw_uidpolicy(struct userconf *cnf, intmax_t id);
75169689Skanstatic uid_t	 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam,
76169689Skan    gid_t prefer, bool dryrun);
77169689Skanstatic char	*pw_homepolicy(struct userconf * cnf, char *homedir,
78169689Skan    const char *user);
79169689Skanstatic char	*pw_shellpolicy(struct userconf * cnf);
80169689Skanstatic char	*pw_password(struct userconf * cnf, char const * user);
81169689Skanstatic char	*shell_path(char const * path, char *shells[], char *sh);
82169689Skanstatic void	rmat(uid_t uid);
83169689Skan
84169689Skanstatic void
85169689Skanmkdir_home_parents(int dfd, const char *dir)
86169689Skan{
87169689Skan	struct stat st;
88169689Skan	char *dirs, *tmp;
89169689Skan
90169689Skan	if (*dir != '/')
91169689Skan		errx(EX_DATAERR, "invalid base directory for home '%s'", dir);
92169689Skan
93169689Skan	dir++;
94169689Skan
95169689Skan	if (fstatat(dfd, dir, &st, 0) != -1) {
96169689Skan		if (S_ISDIR(st.st_mode))
97169689Skan			return;
98169689Skan		errx(EX_OSFILE, "root home `/%s' is not a directory", dir);
99169689Skan	}
100169689Skan
101169689Skan	dirs = strdup(dir);
102169689Skan	if (dirs == NULL)
103169689Skan		errx(EX_UNAVAILABLE, "out of memory");
104169689Skan
105169689Skan	tmp = strrchr(dirs, '/');
106169689Skan	if (tmp == NULL) {
107169689Skan		free(dirs);
108169689Skan		return;
109169689Skan	}
110169689Skan	tmp[0] = '\0';
111169689Skan
112169689Skan	tmp = dirs;
113169689Skan	if (fstatat(dfd, dirs, &st, 0) == -1) {
114169689Skan		while ((tmp = strchr(tmp + 1, '/')) != NULL) {
115169689Skan			*tmp = '\0';
116169689Skan			if (fstatat(dfd, dirs, &st, 0) == -1) {
117169689Skan				if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
118169689Skan					err(EX_OSFILE,  "'%s' (home parent) is not a directory", dirs);
119169689Skan			}
120169689Skan			*tmp = '/';
121169689Skan		}
122169689Skan	}
123169689Skan	if (fstatat(dfd, dirs, &st, 0) == -1) {
124169689Skan		if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
125169689Skan			err(EX_OSFILE,  "'%s' (home parent) is not a directory", dirs);
126169689Skan		fchownat(dfd, dirs, 0, 0, 0);
127169689Skan	}
128169689Skan
129169689Skan	free(dirs);
130169689Skan}
131169689Skan
132169689Skanstatic void
133169689Skancreate_and_populate_homedir(struct userconf *cnf, struct passwd *pwd,
134169689Skan    const char *skeldir, mode_t homemode, bool update)
135169689Skan{
136169689Skan	int skelfd = -1;
137169689Skan
138169689Skan	/* Create home parents directories */
139169689Skan	mkdir_home_parents(conf.rootfd, pwd->pw_dir);
140169689Skan
141169689Skan	if (skeldir != NULL && *skeldir != '\0') {
142169689Skan		if (*skeldir == '/')
143169689Skan			skeldir++;
144169689Skan		skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
145169689Skan	}
146169689Skan
147169689Skan	copymkdir(conf.rootfd, pwd->pw_dir, skelfd, homemode, pwd->pw_uid,
148169689Skan	    pwd->pw_gid, 0);
149169689Skan	pw_log(cnf, update ? M_MODIFY : M_ADD, W_USER, "%s(%ju) home %s made",
150169689Skan	    pwd->pw_name, (uintmax_t)pwd->pw_uid, pwd->pw_dir);
151169689Skan}
152169689Skan
153169689Skanstatic int
154169689Skanpw_set_passwd(struct passwd *pwd, int fd, bool precrypted, bool update)
155169689Skan{
156169689Skan	int		 b, istty;
157169689Skan	struct termios	 t, n;
158169689Skan	login_cap_t	*lc;
159169689Skan	char		line[_PASSWORD_LEN+1];
160169689Skan	char		*p;
161169689Skan
162169689Skan	if (fd == '-') {
163169689Skan		if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
164169689Skan			pwd->pw_passwd = "*";	/* No access */
165169689Skan			return (1);
166169689Skan		}
167169689Skan		return (0);
168169689Skan	}
169169689Skan
170169689Skan	if ((istty = isatty(fd))) {
171169689Skan		if (tcgetattr(fd, &t) == -1)
172169689Skan			istty = 0;
173169689Skan		else {
174169689Skan			n = t;
175169689Skan			n.c_lflag &= ~(ECHO);
176169689Skan			tcsetattr(fd, TCSANOW, &n);
177169689Skan			printf("%s%spassword for user %s:",
178169689Skan			    update ? "new " : "",
179169689Skan			    precrypted ? "encrypted " : "",
180169689Skan			    pwd->pw_name);
181169689Skan			fflush(stdout);
182169689Skan		}
183169689Skan	}
184169689Skan	b = read(fd, line, sizeof(line) - 1);
185169689Skan	if (istty) {	/* Restore state */
186169689Skan		tcsetattr(fd, TCSANOW, &t);
187169689Skan		fputc('\n', stdout);
188169689Skan		fflush(stdout);
189169689Skan	}
190169689Skan
191169689Skan	if (b < 0)
192169689Skan		err(EX_IOERR, "-%c file descriptor",
193169689Skan		    precrypted ? 'H' : 'h');
194169689Skan	line[b] = '\0';
195169689Skan	if ((p = strpbrk(line, "\r\n")) != NULL)
196169689Skan		*p = '\0';
197169689Skan	if (!*line)
198169689Skan		errx(EX_DATAERR, "empty password read on file descriptor %d",
199169689Skan		    fd);
200169689Skan	if (precrypted) {
201169689Skan		if (strchr(line, ':') != NULL)
202169689Skan			errx(EX_DATAERR, "bad encrypted password");
203169689Skan		pwd->pw_passwd = strdup(line);
204169689Skan	} else {
205169689Skan		lc = login_getpwclass(pwd);
206169689Skan		if (lc == NULL ||
207169689Skan				login_setcryptfmt(lc, "sha512", NULL) == NULL)
208169689Skan			warn("setting crypt(3) format");
209169689Skan		login_close(lc);
210169689Skan		pwd->pw_passwd = pw_pwcrypt(line);
211169689Skan	}
212169689Skan	return (1);
213169689Skan}
214169689Skan
215169689Skanstatic void
216169689Skanperform_chgpwent(const char *name, struct passwd *pwd, char *nispasswd)
217169689Skan{
218169689Skan	int rc;
219169689Skan	struct passwd *nispwd;
220169689Skan
221169689Skan	/* duplicate for nis so that chgpwent is not modifying before NIS */
222169689Skan	if (nispasswd && *nispasswd == '/')
223169689Skan		nispwd = pw_dup(pwd);
224169689Skan
225169689Skan	rc = chgpwent(name, pwd);
226169689Skan	if (rc == -1)
227169689Skan		errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
228169689Skan	else if (rc != 0)
229169689Skan		err(EX_IOERR, "passwd file update");
230169689Skan
231169689Skan	if (nispasswd && *nispasswd == '/') {
232169689Skan		rc = chgnispwent(nispasswd, name, nispwd);
233169689Skan		if (rc == -1)
234169689Skan			warn("User '%s' not found in NIS passwd", pwd->pw_name);
235169689Skan		else if (rc != 0)
236169689Skan			warn("NIS passwd update");
237169689Skan		/* NOTE: NIS-only update errors are not fatal */
238169689Skan	}
239169689Skan}
240169689Skan
241169689Skan/*
242169689Skan * The M_LOCK and M_UNLOCK functions simply add or remove
243169689Skan * a "*LOCKED*" prefix from in front of the password to
244169689Skan * prevent it decoding correctly, and therefore prevents
245169689Skan * access. Of course, this only prevents access via
246169689Skan * password authentication (not ssh, kerberos or any
247169689Skan * other method that does not use the UNIX password) but
248169689Skan * that is a known limitation.
249169689Skan */
250169689Skanstatic int
251169689Skanpw_userlock(char *arg1, int mode)
252169689Skan{
253169689Skan	struct passwd *pwd = NULL;
254169689Skan	char *passtmp = NULL;
255169689Skan	char *name;
256169689Skan	bool locked = false;
257169689Skan	uid_t id = (uid_t)-1;
258169689Skan
259169689Skan	if (geteuid() != 0)
260169689Skan		errx(EX_NOPERM, "you must be root");
261169689Skan
262169689Skan	if (arg1 == NULL)
263169689Skan		errx(EX_DATAERR, "username or id required");
264169689Skan
265169689Skan	name = arg1;
266169689Skan	if (arg1[strspn(name, "0123456789")] == '\0')
267169689Skan		id = pw_checkid(name, UID_MAX);
268169689Skan
269169689Skan	pwd = GETPWNAM(pw_checkname(name, 0));
270169689Skan	if (pwd == NULL && id != (uid_t)-1) {
271169689Skan		pwd = GETPWUID(id);
272169689Skan		if (pwd != NULL)
273169689Skan			name = pwd->pw_name;
274169689Skan	}
275169689Skan	if (pwd == NULL) {
276169689Skan		if (id == (uid_t)-1)
277169689Skan			errx(EX_NOUSER, "no such name or uid `%ju'", (uintmax_t) id);
278169689Skan		errx(EX_NOUSER, "no such user `%s'", name);
279169689Skan	}
280169689Skan
281169689Skan	if (name == NULL)
282169689Skan		name = pwd->pw_name;
283169689Skan
284169689Skan	if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
285169689Skan		locked = true;
286169689Skan	if (mode == M_LOCK && locked)
287169689Skan		errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
288169689Skan	if (mode == M_UNLOCK && !locked)
289169689Skan		errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
290169689Skan
291169689Skan	if (mode == M_LOCK) {
292169689Skan		asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
293169689Skan		if (passtmp == NULL)	/* disaster */
294169689Skan			errx(EX_UNAVAILABLE, "out of memory");
295169689Skan		pwd->pw_passwd = passtmp;
296169689Skan	} else {
297169689Skan		pwd->pw_passwd += sizeof(locked_str)-1;
298169689Skan	}
299169689Skan
300169689Skan	perform_chgpwent(name, pwd, NULL);
301169689Skan	free(passtmp);
302169689Skan
303169689Skan	return (EXIT_SUCCESS);
304169689Skan}
305169689Skan
306169689Skanstatic uid_t
307169689Skanpw_uidpolicy(struct userconf * cnf, intmax_t id)
308169689Skan{
309169689Skan	struct passwd  *pwd;
310169689Skan	struct bitmap   bm;
311169689Skan	uid_t           uid = (uid_t) - 1;
312169689Skan
313169689Skan	/*
314169689Skan	 * Check the given uid, if any
315169689Skan	 */
316169689Skan	if (id >= 0) {
317169689Skan		uid = (uid_t) id;
318169689Skan
319169689Skan		if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
320169689Skan			errx(EX_DATAERR, "uid `%ju' has already been allocated",
321169689Skan			    (uintmax_t)pwd->pw_uid);
322169689Skan		return (uid);
323169689Skan	}
324169689Skan	/*
325169689Skan	 * We need to allocate the next available uid under one of
326169689Skan	 * two policies a) Grab the first unused uid b) Grab the
327169689Skan	 * highest possible unused uid
328169689Skan	 */
329169689Skan	if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
330169689Skan						 * claus^H^H^H^Hheck */
331169689Skan		cnf->min_uid = 1000;
332169689Skan		cnf->max_uid = 32000;
333169689Skan	}
334169689Skan	bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
335169689Skan
336169689Skan	/*
337169689Skan	 * Now, let's fill the bitmap from the password file
338169689Skan	 */
339169689Skan	SETPWENT();
340169689Skan	while ((pwd = GETPWENT()) != NULL)
341169689Skan		if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
342169689Skan			bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
343169689Skan	ENDPWENT();
344169689Skan
345169689Skan	/*
346169689Skan	 * Then apply the policy, with fallback to reuse if necessary
347169689Skan	 */
348169689Skan	if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
349169689Skan		uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
350169689Skan
351169689Skan	/*
352169689Skan	 * Another sanity check
353169689Skan	 */
354169689Skan	if (uid < cnf->min_uid || uid > cnf->max_uid)
355169689Skan		errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
356169689Skan	bm_dealloc(&bm);
357169689Skan	return (uid);
358169689Skan}
359169689Skan
360169689Skanstatic uid_t
361169689Skanpw_gidpolicy(struct userconf *cnf, char *grname, char *nam, gid_t prefer, bool dryrun)
362169689Skan{
363169689Skan	struct group   *grp;
364169689Skan	gid_t           gid = (uid_t) - 1;
365169689Skan
366169689Skan	/*
367169689Skan	 * Check the given gid, if any
368169689Skan	 */
369169689Skan	SETGRENT();
370169689Skan	if (grname) {
371169689Skan		if ((grp = GETGRNAM(grname)) == NULL) {
372169689Skan			gid = pw_checkid(grname, GID_MAX);
373169689Skan			grp = GETGRGID(gid);
374169689Skan		}
375169689Skan		gid = grp->gr_gid;
376169689Skan	} else if ((grp = GETGRNAM(nam)) != NULL) {
377169689Skan		gid = grp->gr_gid;  /* Already created? Use it anyway... */
378169689Skan	} else {
379169689Skan		intmax_t		grid = -1;
380169689Skan
381169689Skan		/*
382169689Skan		 * We need to auto-create a group with the user's name. We
383169689Skan		 * can send all the appropriate output to our sister routine
384169689Skan		 * bit first see if we can create a group with gid==uid so we
385169689Skan		 * can keep the user and group ids in sync. We purposely do
386169689Skan		 * NOT check the gid range if we can force the sync. If the
387169689Skan		 * user's name dups an existing group, then the group add
388169689Skan		 * function will happily handle that case for us and exit.
389169689Skan		 */
390169689Skan		if (GETGRGID(prefer) == NULL)
391169689Skan			grid = prefer;
392169689Skan		if (dryrun) {
393169689Skan			gid = pw_groupnext(cnf, true);
394169689Skan		} else {
395169689Skan			if (grid == -1)
396169689Skan				grid =  pw_groupnext(cnf, true);
397169689Skan			groupadd(cnf, nam, grid, NULL, -1, false, false, false);
398169689Skan			if ((grp = GETGRNAM(nam)) != NULL)
399169689Skan				gid = grp->gr_gid;
400169689Skan		}
401169689Skan	}
402169689Skan	ENDGRENT();
403169689Skan	return (gid);
404169689Skan}
405169689Skan
406169689Skanstatic char *
407169689Skanpw_homepolicy(struct userconf * cnf, char *homedir, const char *user)
408169689Skan{
409169689Skan	static char     home[128];
410169689Skan
411169689Skan	if (homedir)
412169689Skan		return (homedir);
413169689Skan
414169689Skan	if (cnf->home == NULL || *cnf->home == '\0')
415169689Skan		errx(EX_CONFIG, "no base home directory set");
416169689Skan	snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
417169689Skan
418169689Skan	return (home);
419169689Skan}
420169689Skan
421169689Skanstatic char *
422169689Skanshell_path(char const * path, char *shells[], char *sh)
423169689Skan{
424169689Skan	if (sh != NULL && (*sh == '/' || *sh == '\0'))
425169689Skan		return sh;	/* specified full path or forced none */
426169689Skan	else {
427169689Skan		char           *p;
428169689Skan		char            paths[_UC_MAXLINE];
429169689Skan
430169689Skan		/*
431169689Skan		 * We need to search paths
432169689Skan		 */
433169689Skan		strlcpy(paths, path, sizeof(paths));
434169689Skan		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
435169689Skan			int             i;
436169689Skan			static char     shellpath[256];
437169689Skan
438169689Skan			if (sh != NULL) {
439169689Skan				snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
440169689Skan				if (access(shellpath, X_OK) == 0)
441169689Skan					return shellpath;
442169689Skan			} else
443169689Skan				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
444169689Skan					snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
445169689Skan					if (access(shellpath, X_OK) == 0)
446169689Skan						return shellpath;
447169689Skan				}
448169689Skan		}
449169689Skan		if (sh == NULL)
450169689Skan			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
451169689Skan		errx(EX_CONFIG, "no default shell available or defined");
452169689Skan		return NULL;
453169689Skan	}
454169689Skan}
455169689Skan
456169689Skanstatic char *
457169689Skanpw_shellpolicy(struct userconf * cnf)
458169689Skan{
459169689Skan
460169689Skan	return shell_path(cnf->shelldir, cnf->shells, cnf->shell_default);
461169689Skan}
462169689Skan
463169689Skan#define	SALTSIZE	32
464169689Skan
465169689Skanstatic char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
466169689Skan
467169689Skanchar *
468169689Skanpw_pwcrypt(char *password)
469169689Skan{
470169689Skan	int             i;
471169689Skan	char            salt[SALTSIZE + 1];
472169689Skan	char		*cryptpw;
473169689Skan	static char     buf[256];
474169689Skan	size_t		pwlen;
475169689Skan
476169689Skan	/*
477169689Skan	 * Calculate a salt value
478169689Skan	 */
479169689Skan	for (i = 0; i < SALTSIZE; i++)
480169689Skan		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
481169689Skan	salt[SALTSIZE] = '\0';
482169689Skan
483169689Skan	cryptpw = crypt(password, salt);
484169689Skan	if (cryptpw == NULL)
485169689Skan		errx(EX_CONFIG, "crypt(3) failure");
486169689Skan	pwlen = strlcpy(buf, cryptpw, sizeof(buf));
487169689Skan	assert(pwlen < sizeof(buf));
488169689Skan	return (buf);
489169689Skan}
490169689Skan
491169689Skanstatic char *
492169689Skanpw_password(struct userconf * cnf, char const * user)
493169689Skan{
494169689Skan	int             i, l;
495169689Skan	char            pwbuf[32];
496169689Skan
497169689Skan	switch (cnf->default_password) {
498169689Skan	case P_NONE:		/* No password at all! */
499169689Skan		return "";
500169689Skan	case P_RANDOM:			/* Random password */
501169689Skan		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
502169689Skan		for (i = 0; i < l; i++)
503169689Skan			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
504169689Skan		pwbuf[i] = '\0';
505169689Skan
506169689Skan		/*
507169689Skan		 * We give this information back to the user
508169689Skan		 */
509169689Skan		if (conf.fd == -1) {
510169689Skan			if (isatty(STDOUT_FILENO))
511169689Skan				printf("Password for '%s' is: ", user);
512169689Skan			printf("%s\n", pwbuf);
513169689Skan			fflush(stdout);
514169689Skan		}
515169689Skan		break;
516169689Skan	case P_YES:		/* user's name */
517169689Skan		strlcpy(pwbuf, user, sizeof(pwbuf));
518169689Skan		break;
519169689Skan	case P_NO:		/* No login - default */
520169689Skan				/* FALLTHROUGH */
521169689Skan	default:
522169689Skan		return "*";
523169689Skan	}
524169689Skan	return pw_pwcrypt(pwbuf);
525169689Skan}
526169689Skan
527169689Skanstatic int
528169689Skanprint_user(struct passwd * pwd, bool pretty, bool v7)
529169689Skan{
530169689Skan	int		j;
531169689Skan	char           *p;
532169689Skan	struct group   *grp = GETGRGID(pwd->pw_gid);
533169689Skan	char            uname[60] = "User &", office[60] = "[None]",
534169689Skan			wphone[60] = "[None]", hphone[60] = "[None]";
535169689Skan	char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
536169689Skan	struct tm *    tptr;
537169689Skan
538169689Skan	if (!pretty) {
539169689Skan		p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
540169689Skan		printf("%s\n", p);
541169689Skan		free(p);
542169689Skan		return (EXIT_SUCCESS);
543169689Skan	}
544169689Skan
545169689Skan	if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
546169689Skan		strlcpy(uname, p, sizeof(uname));
547169689Skan		if ((p = strtok(NULL, ",")) != NULL) {
548169689Skan			strlcpy(office, p, sizeof(office));
549169689Skan			if ((p = strtok(NULL, ",")) != NULL) {
550169689Skan				strlcpy(wphone, p, sizeof(wphone));
551169689Skan				if ((p = strtok(NULL, "")) != NULL) {
552169689Skan					strlcpy(hphone, p, sizeof(hphone));
553169689Skan				}
554169689Skan			}
555169689Skan		}
556169689Skan	}
557169689Skan	/*
558169689Skan	 * Handle '&' in gecos field
559169689Skan	 */
560169689Skan	if ((p = strchr(uname, '&')) != NULL) {
561169689Skan		int             l = strlen(pwd->pw_name);
562169689Skan		int             m = strlen(p);
563169689Skan
564169689Skan		memmove(p + l, p + 1, m);
565169689Skan		memmove(p, pwd->pw_name, l);
566169689Skan		*p = (char) toupper((unsigned char)*p);
567169689Skan	}
568169689Skan	if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
569169689Skan		strftime(acexpire, sizeof acexpire, "%c", tptr);
570169689Skan	if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
571169689Skan		strftime(pwexpire, sizeof pwexpire, "%c", tptr);
572169689Skan	printf("Login Name: %-15s   #%-12ju Group: %-15s   #%ju\n"
573169689Skan	       " Full Name: %s\n"
574169689Skan	       "      Home: %-26.26s      Class: %s\n"
575169689Skan	       "     Shell: %-26.26s     Office: %s\n"
576169689Skan	       "Work Phone: %-26.26s Home Phone: %s\n"
577169689Skan	       "Acc Expire: %-26.26s Pwd Expire: %s\n",
578169689Skan	       pwd->pw_name, (uintmax_t)pwd->pw_uid,
579169689Skan	       grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
580169689Skan	       uname, pwd->pw_dir, pwd->pw_class,
581169689Skan	       pwd->pw_shell, office, wphone, hphone,
582169689Skan	       acexpire, pwexpire);
583169689Skan        SETGRENT();
584169689Skan	j = 0;
585169689Skan	while ((grp=GETGRENT()) != NULL) {
586169689Skan		int     i = 0;
587169689Skan		if (grp->gr_mem != NULL) {
588169689Skan			while (grp->gr_mem[i] != NULL) {
589169689Skan				if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
590169689Skan					printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
591169689Skan					break;
592169689Skan				}
593169689Skan				++i;
594169689Skan			}
595169689Skan		}
596169689Skan	}
597169689Skan	ENDGRENT();
598169689Skan	printf("%s", j ? "\n" : "");
599169689Skan	return (EXIT_SUCCESS);
600169689Skan}
601169689Skan
602169689Skanchar *
603169689Skanpw_checkname(char *name, int gecos)
604169689Skan{
605169689Skan	char showch[8];
606169689Skan	const char *badchars, *ch, *showtype;
607169689Skan	int reject;
608169689Skan
609169689Skan	ch = name;
610169689Skan	reject = 0;
611169689Skan	if (gecos) {
612169689Skan		/* See if the name is valid as a gecos (comment) field. */
613169689Skan		badchars = ":";
614169689Skan		showtype = "gecos field";
615169689Skan	} else {
616169689Skan		/* See if the name is valid as a userid or group. */
617169689Skan		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\";";
618169689Skan		showtype = "userid/group name";
619169689Skan		/* Userids and groups can not have a leading '-'. */
620169689Skan		if (*ch == '-')
621169689Skan			reject = 1;
622169689Skan	}
623169689Skan	if (!reject) {
624169689Skan		while (*ch) {
625169689Skan			if (strchr(badchars, *ch) != NULL ||
626169689Skan			    (!gecos && *ch < ' ') ||
627169689Skan			    *ch == 127) {
628169689Skan				reject = 1;
629169689Skan				break;
630169689Skan			}
631169689Skan			/* 8-bit characters are only allowed in GECOS fields */
632169689Skan			if (!gecos && (*ch & 0x80)) {
633169689Skan				reject = 1;
634169689Skan				break;
635169689Skan			}
636169689Skan			ch++;
637169689Skan		}
638169689Skan	}
639169689Skan	/*
640169689Skan	 * A `$' is allowed as the final character for userids and groups,
641169689Skan	 * mainly for the benefit of samba.
642169689Skan	 */
643169689Skan	if (reject && !gecos) {
644169689Skan		if (*ch == '$' && *(ch + 1) == '\0') {
645169689Skan			reject = 0;
646169689Skan			ch++;
647169689Skan		}
648169689Skan	}
649169689Skan	if (reject) {
650169689Skan		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
651169689Skan		    ? "`%c'" : "0x%02x", *ch);
652169689Skan		errx(EX_DATAERR, "invalid character %s at position %td in %s",
653169689Skan		    showch, (ch - name), showtype);
654169689Skan	}
655169689Skan	if (!gecos && (ch - name) > LOGNAMESIZE)
656169689Skan		errx(EX_USAGE, "name too long `%s' (max is %d)", name,
657169689Skan		    LOGNAMESIZE);
658169689Skan
659169689Skan	return (name);
660169689Skan}
661169689Skan
662169689Skanstatic void
663169689Skanrmat(uid_t uid)
664169689Skan{
665169689Skan	DIR            *d = opendir("/var/at/jobs");
666169689Skan
667169689Skan	if (d != NULL) {
668169689Skan		struct dirent  *e;
669169689Skan
670169689Skan		while ((e = readdir(d)) != NULL) {
671169689Skan			struct stat     st;
672169689Skan			pid_t		pid;
673169689Skan
674169689Skan			if (strncmp(e->d_name, ".lock", 5) != 0 &&
675169689Skan			    stat(e->d_name, &st) == 0 &&
676169689Skan			    !S_ISDIR(st.st_mode) &&
677169689Skan			    st.st_uid == uid) {
678169689Skan				const char *argv[] = {
679169689Skan					"/usr/sbin/atrm",
680169689Skan					e->d_name,
681169689Skan					NULL
682169689Skan				};
683169689Skan				if (posix_spawn(&pid, argv[0], NULL, NULL,
684169689Skan				    (char *const *) argv, environ)) {
685169689Skan					warn("Failed to execute '%s %s'",
686169689Skan					    argv[0], argv[1]);
687169689Skan				} else
688169689Skan					(void) waitpid(pid, NULL, 0);
689169689Skan			}
690169689Skan		}
691169689Skan		closedir(d);
692169689Skan	}
693169689Skan}
694169689Skan
695169689Skanint
696169689Skanpw_user_next(int argc, char **argv, char *name __unused)
697169689Skan{
698169689Skan	struct userconf *cnf = NULL;
699169689Skan	const char *cfg = NULL;
700169689Skan	int ch;
701169689Skan	bool quiet = false;
702169689Skan	uid_t next;
703169689Skan
704169689Skan	while ((ch = getopt(argc, argv, "C:q")) != -1) {
705169689Skan		switch (ch) {
706169689Skan		case 'C':
707169689Skan			cfg = optarg;
708169689Skan			break;
709169689Skan		case 'q':
710169689Skan			quiet = true;
711169689Skan			break;
712169689Skan		default:
713169689Skan			usage();
714169689Skan		}
715169689Skan	}
716169689Skan	argc -= optind;
717169689Skan	argv += optind;
718169689Skan	if (argc > 0)
719169689Skan		usage();
720169689Skan
721169689Skan	if (quiet)
722169689Skan		freopen(_PATH_DEVNULL, "w", stderr);
723169689Skan
724169689Skan	cnf = get_userconfig(cfg);
725169689Skan
726169689Skan	next = pw_uidpolicy(cnf, -1);
727169689Skan
728169689Skan	printf("%ju:", (uintmax_t)next);
729169689Skan	pw_groupnext(cnf, quiet);
730169689Skan
731169689Skan	return (EXIT_SUCCESS);
732169689Skan}
733169689Skan
734169689Skanint
735169689Skanpw_user_show(int argc, char **argv, char *arg1)
736169689Skan{
737169689Skan	struct passwd *pwd = NULL;
738169689Skan	char *name = NULL;
739169689Skan	intmax_t id = -1;
740169689Skan	int ch;
741169689Skan	bool all = false;
742169689Skan	bool pretty = false;
743169689Skan	bool force = false;
744169689Skan	bool v7 = false;
745169689Skan	bool quiet = false;
746169689Skan
747169689Skan	if (arg1 != NULL) {
748169689Skan		if (arg1[strspn(arg1, "0123456789")] == '\0')
749169689Skan			id = pw_checkid(arg1, UID_MAX);
750169689Skan		else
751169689Skan			name = arg1;
752169689Skan	}
753169689Skan
754169689Skan	while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
755169689Skan		switch (ch) {
756169689Skan		case 'C':
757169689Skan			/* ignore compatibility */
758169689Skan			break;
759169689Skan		case 'q':
760169689Skan			quiet = true;
761169689Skan			break;
762169689Skan		case 'n':
763169689Skan			name = optarg;
764169689Skan			break;
765169689Skan		case 'u':
766169689Skan			id = pw_checkid(optarg, UID_MAX);
767169689Skan			break;
768169689Skan		case 'F':
769169689Skan			force = true;
770169689Skan			break;
771169689Skan		case 'P':
772169689Skan			pretty = true;
773169689Skan			break;
774169689Skan		case 'a':
775169689Skan			all = true;
776169689Skan			break;
777169689Skan		case '7':
778169689Skan			v7 = true;
779169689Skan			break;
780169689Skan		default:
781169689Skan			usage();
782169689Skan		}
783169689Skan	}
784169689Skan	argc -= optind;
785169689Skan	argv += optind;
786169689Skan	if (argc > 0)
787169689Skan		usage();
788169689Skan
789169689Skan	if (quiet)
790169689Skan		freopen(_PATH_DEVNULL, "w", stderr);
791169689Skan
792169689Skan	if (all) {
793169689Skan		SETPWENT();
794169689Skan		while ((pwd = GETPWENT()) != NULL)
795169689Skan			print_user(pwd, pretty, v7);
796169689Skan		ENDPWENT();
797169689Skan		return (EXIT_SUCCESS);
798169689Skan	}
799169689Skan
800169689Skan	if (id < 0 && name == NULL)
801169689Skan		errx(EX_DATAERR, "username or id required");
802169689Skan
803169689Skan	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
804169689Skan	if (pwd == NULL) {
805169689Skan		if (force) {
806169689Skan			pwd = &fakeuser;
807169689Skan		} else {
808169689Skan			if (name == NULL)
809169689Skan				errx(EX_NOUSER, "no such uid `%ju'",
810169689Skan				    (uintmax_t) id);
811169689Skan			errx(EX_NOUSER, "no such user `%s'", name);
812169689Skan		}
813169689Skan	}
814169689Skan
815169689Skan	return (print_user(pwd, pretty, v7));
816169689Skan}
817169689Skan
818169689Skanint
819169689Skanpw_user_del(int argc, char **argv, char *arg1)
820169689Skan{
821169689Skan	struct userconf *cnf = NULL;
822169689Skan	struct passwd *pwd = NULL;
823169689Skan	struct group *gr, *grp;
824169689Skan	char *name = NULL;
825169689Skan	char grname[MAXLOGNAME];
826169689Skan	char *nispasswd = NULL;
827169689Skan	char file[MAXPATHLEN];
828169689Skan	char home[MAXPATHLEN];
829169689Skan	const char *cfg = NULL;
830169689Skan	struct stat st;
831169689Skan	intmax_t id = -1;
832169689Skan	int ch, rc;
833169689Skan	bool nis = false;
834169689Skan	bool deletehome = false;
835169689Skan	bool quiet = false;
836169689Skan
837169689Skan	if (arg1 != NULL) {
838169689Skan		if (arg1[strspn(arg1, "0123456789")] == '\0')
839169689Skan			id = pw_checkid(arg1, UID_MAX);
840169689Skan		else
841169689Skan			name = arg1;
842169689Skan	}
843169689Skan
844169689Skan	while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
845169689Skan		switch (ch) {
846169689Skan		case 'C':
847169689Skan			cfg = optarg;
848169689Skan			break;
849169689Skan		case 'q':
850169689Skan			quiet = true;
851169689Skan			break;
852169689Skan		case 'n':
853169689Skan			name = optarg;
854169689Skan			break;
855169689Skan		case 'u':
856169689Skan			id = pw_checkid(optarg, UID_MAX);
857169689Skan			break;
858169689Skan		case 'r':
859169689Skan			deletehome = true;
860169689Skan			break;
861169689Skan		case 'y':
862169689Skan			nispasswd = optarg;
863169689Skan			break;
864169689Skan		case 'Y':
865169689Skan			nis = true;
866169689Skan			break;
867169689Skan		default:
868169689Skan			usage();
869169689Skan		}
870169689Skan	}
871169689Skan	argc -= optind;
872169689Skan	argv += optind;
873169689Skan	if (argc > 0)
874169689Skan		usage();
875169689Skan
876169689Skan	if (quiet)
877169689Skan		freopen(_PATH_DEVNULL, "w", stderr);
878169689Skan
879169689Skan	if (id < 0 && name == NULL)
880169689Skan		errx(EX_DATAERR, "username or id required");
881169689Skan
882169689Skan	cnf = get_userconfig(cfg);
883169689Skan
884169689Skan	if (nispasswd == NULL)
885169689Skan		nispasswd = cnf->nispasswd;
886169689Skan
887169689Skan	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
888169689Skan	if (pwd == NULL) {
889169689Skan		if (name == NULL)
890169689Skan			errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
891169689Skan		errx(EX_NOUSER, "no such user `%s'", name);
892169689Skan	}
893169689Skan
894169689Skan	if (PWF._altdir == PWF_REGULAR &&
895169689Skan	    ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
896169689Skan		if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
897169689Skan			if (!nis && nispasswd && *nispasswd != '/')
898169689Skan				errx(EX_NOUSER, "Cannot remove NIS user `%s'",
899169689Skan				    name);
900169689Skan		} else {
901169689Skan			errx(EX_NOUSER, "Cannot remove non local user `%s'",
902169689Skan			    name);
903169689Skan		}
904169689Skan	}
905169689Skan
906169689Skan	id = pwd->pw_uid;
907169689Skan	if (name == NULL)
908169689Skan		name = pwd->pw_name;
909169689Skan
910169689Skan	if (strcmp(pwd->pw_name, "root") == 0)
911169689Skan		errx(EX_DATAERR, "cannot remove user 'root'");
912169689Skan
913169689Skan	if (!PWALTDIR()) {
914169689Skan		/* Remove crontabs */
915169689Skan		snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
916169689Skan		if (access(file, F_OK) == 0) {
917169689Skan			const char *argv[] = {
918169689Skan				"crontab",
919169689Skan				"-u",
920169689Skan				pwd->pw_name,
921169689Skan				"-r",
922169689Skan				NULL
923169689Skan			};
924169689Skan			pid_t pid;
925169689Skan
926169689Skan			if (posix_spawnp(&pid, argv[0], NULL, NULL,
927169689Skan						(char *const *) argv, environ)) {
928169689Skan				warn("Failed to execute '%s %s'",
929169689Skan						argv[0], argv[1]);
930169689Skan			} else
931169689Skan				(void) waitpid(pid, NULL, 0);
932169689Skan		}
933169689Skan	}
934169689Skan
935169689Skan	/*
936169689Skan	 * Save these for later, since contents of pwd may be
937169689Skan	 * invalidated by deletion
938169689Skan	 */
939169689Skan	snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
940169689Skan	strlcpy(home, pwd->pw_dir, sizeof(home));
941169689Skan	gr = GETGRGID(pwd->pw_gid);
942169689Skan	if (gr != NULL)
943169689Skan		strlcpy(grname, gr->gr_name, LOGNAMESIZE);
944169689Skan	else
945169689Skan		grname[0] = '\0';
946169689Skan
947169689Skan	rc = delpwent(pwd);
948169689Skan	if (rc == -1)
949169689Skan		err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
950169689Skan	else if (rc != 0)
951169689Skan		err(EX_IOERR, "passwd update");
952169689Skan
953169689Skan	if (nis && nispasswd && *nispasswd=='/') {
954169689Skan		rc = delnispwent(nispasswd, name);
955169689Skan		if (rc == -1)
956169689Skan			warnx("WARNING: user '%s' does not exist in NIS passwd",
957169689Skan			    pwd->pw_name);
958169689Skan		else if (rc != 0)
959169689Skan			warn("WARNING: NIS passwd update");
960169689Skan	}
961169689Skan
962169689Skan	grp = GETGRNAM(name);
963169689Skan	if (grp != NULL &&
964169689Skan	    (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
965169689Skan	    strcmp(name, grname) == 0)
966169689Skan		delgrent(GETGRNAM(name));
967169689Skan	SETGRENT();
968169689Skan	while ((grp = GETGRENT()) != NULL) {
969169689Skan		int i, j;
970169689Skan		char group[MAXLOGNAME];
971169689Skan		if (grp->gr_mem == NULL)
972169689Skan			continue;
973169689Skan
974169689Skan		for (i = 0; grp->gr_mem[i] != NULL; i++) {
975169689Skan			if (strcmp(grp->gr_mem[i], name) != 0)
976169689Skan				continue;
977169689Skan
978169689Skan			for (j = i; grp->gr_mem[j] != NULL; j++)
979169689Skan				grp->gr_mem[j] = grp->gr_mem[j+1];
980169689Skan			strlcpy(group, grp->gr_name, MAXLOGNAME);
981169689Skan			chggrent(group, grp);
982169689Skan		}
983169689Skan	}
984169689Skan	ENDGRENT();
985169689Skan
986169689Skan	pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
987169689Skan	    (uintmax_t)id);
988169689Skan
989169689Skan	/* Remove mail file */
990169689Skan	if (PWALTDIR() != PWF_ALT)
991169689Skan		unlinkat(conf.rootfd, file + 1, 0);
992169689Skan
993169689Skan	/* Remove at jobs */
994169689Skan	if (!PWALTDIR() && getpwuid(id) == NULL)
995169689Skan		rmat(id);
996169689Skan
997169689Skan	/* Remove home directory and contents */
998169689Skan	if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
999169689Skan	    GETPWUID(id) == NULL &&
1000169689Skan	    fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1001169689Skan		rm_r(conf.rootfd, home, id);
1002169689Skan		pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
1003169689Skan		    "removed", name, (uintmax_t)id, home,
1004169689Skan		     fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1005169689Skan		     "completely ");
1006169689Skan	}
1007169689Skan
1008169689Skan	return (EXIT_SUCCESS);
1009169689Skan}
1010169689Skan
1011169689Skanint
1012169689Skanpw_user_lock(int argc, char **argv, char *arg1)
1013169689Skan{
1014169689Skan	int ch;
1015169689Skan
1016169689Skan	while ((ch = getopt(argc, argv, "Cq")) != -1) {
1017169689Skan		switch (ch) {
1018169689Skan		case 'C':
1019169689Skan		case 'q':
1020169689Skan			/* compatibility */
1021169689Skan			break;
1022169689Skan		default:
1023169689Skan			usage();
1024169689Skan		}
1025169689Skan	}
1026169689Skan	argc -= optind;
1027169689Skan	argv += optind;
1028169689Skan	if (argc > 0)
1029169689Skan		usage();
1030169689Skan
1031169689Skan	return (pw_userlock(arg1, M_LOCK));
1032169689Skan}
1033169689Skan
1034169689Skanint
1035169689Skanpw_user_unlock(int argc, char **argv, char *arg1)
1036169689Skan{
1037169689Skan	int ch;
1038169689Skan
1039169689Skan	while ((ch = getopt(argc, argv, "Cq")) != -1) {
1040169689Skan		switch (ch) {
1041169689Skan		case 'C':
1042169689Skan		case 'q':
1043169689Skan			/* compatibility */
1044169689Skan			break;
1045169689Skan		default:
1046169689Skan			usage();
1047169689Skan		}
1048169689Skan	}
1049169689Skan	argc -= optind;
1050169689Skan	argv += optind;
1051169689Skan	if (argc > 0)
1052169689Skan		usage();
1053169689Skan
1054169689Skan	return (pw_userlock(arg1, M_UNLOCK));
1055169689Skan}
1056169689Skan
1057169689Skanstatic struct group *
1058169689Skangroup_from_name_or_id(char *name)
1059169689Skan{
1060169689Skan	const char *errstr = NULL;
1061169689Skan	struct group *grp;
1062169689Skan	uintmax_t id;
1063169689Skan
1064169689Skan	if ((grp = GETGRNAM(name)) == NULL) {
1065169689Skan		id = strtounum(name, 0, GID_MAX, &errstr);
1066169689Skan		if (errstr)
1067169689Skan			errx(EX_NOUSER, "group `%s' does not exist", name);
1068169689Skan		grp = GETGRGID(id);
1069169689Skan		if (grp == NULL)
1070169689Skan			errx(EX_NOUSER, "group `%s' does not exist", name);
1071169689Skan	}
1072169689Skan
1073169689Skan	return (grp);
1074169689Skan}
1075169689Skan
1076static void
1077split_groups(StringList **groups, char *groupsstr)
1078{
1079	struct group *grp;
1080	char *p;
1081	char tok[] = ", \t";
1082
1083	if (*groups == NULL)
1084		*groups = sl_init();
1085	for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1086		grp = group_from_name_or_id(p);
1087		sl_add(*groups, newstr(grp->gr_name));
1088	}
1089}
1090
1091static void
1092validate_grname(struct userconf *cnf, char *group)
1093{
1094	struct group *grp;
1095
1096	if (group == NULL || *group == '\0') {
1097		cnf->default_group = "";
1098		return;
1099	}
1100	grp = group_from_name_or_id(group);
1101	cnf->default_group = newstr(grp->gr_name);
1102}
1103
1104static mode_t
1105validate_mode(char *mode)
1106{
1107	mode_t m;
1108	void *set;
1109
1110	if ((set = setmode(mode)) == NULL)
1111		errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1112
1113	m = getmode(set, _DEF_DIRMODE);
1114	free(set);
1115	return (m);
1116}
1117
1118static long
1119validate_expire(char *str, int opt)
1120{
1121	if (!numerics(str))
1122		errx(EX_DATAERR, "-%c argument must be numeric "
1123		     "when setting defaults: %s", (char)opt, str);
1124	return strtol(str, NULL, 0);
1125}
1126
1127static void
1128mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1129{
1130
1131	if (cmdcnf->default_password < 0)
1132		cmdcnf->default_password = cfg->default_password;
1133	if (cmdcnf->reuse_uids == 0)
1134		cmdcnf->reuse_uids = cfg->reuse_uids;
1135	if (cmdcnf->reuse_gids == 0)
1136		cmdcnf->reuse_gids = cfg->reuse_gids;
1137	if (cmdcnf->nispasswd == NULL)
1138		cmdcnf->nispasswd = cfg->nispasswd;
1139	if (cmdcnf->dotdir == NULL)
1140		cmdcnf->dotdir = cfg->dotdir;
1141	if (cmdcnf->newmail == NULL)
1142		cmdcnf->newmail = cfg->newmail;
1143	if (cmdcnf->logfile == NULL)
1144		cmdcnf->logfile = cfg->logfile;
1145	if (cmdcnf->home == NULL)
1146		cmdcnf->home = cfg->home;
1147	if (cmdcnf->homemode == 0)
1148		cmdcnf->homemode = cfg->homemode;
1149	if (cmdcnf->shelldir == NULL)
1150		cmdcnf->shelldir = cfg->shelldir;
1151	if (cmdcnf->shells == NULL)
1152		cmdcnf->shells = cfg->shells;
1153	if (cmdcnf->shell_default == NULL)
1154		cmdcnf->shell_default = cfg->shell_default;
1155	if (cmdcnf->default_group == NULL)
1156		cmdcnf->default_group = cfg->default_group;
1157	if (cmdcnf->groups == NULL)
1158		cmdcnf->groups = cfg->groups;
1159	if (cmdcnf->default_class == NULL)
1160		cmdcnf->default_class = cfg->default_class;
1161	if (cmdcnf->min_uid == 0)
1162		cmdcnf->min_uid = cfg->min_uid;
1163	if (cmdcnf->max_uid == 0)
1164		cmdcnf->max_uid = cfg->max_uid;
1165	if (cmdcnf->min_gid == 0)
1166		cmdcnf->min_gid = cfg->min_gid;
1167	if (cmdcnf->max_gid == 0)
1168		cmdcnf->max_gid = cfg->max_gid;
1169	if (cmdcnf->expire_days < 0)
1170		cmdcnf->expire_days = cfg->expire_days;
1171	if (cmdcnf->password_days < 0)
1172		cmdcnf->password_days = cfg->password_days;
1173}
1174
1175int
1176pw_user_add(int argc, char **argv, char *arg1)
1177{
1178	struct userconf *cnf, *cmdcnf;
1179	struct passwd *pwd;
1180	struct group *grp;
1181	struct stat st;
1182	char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1183	char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1184	char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1185	char *default_passwd, *name, *p;
1186	const char *cfg = NULL;
1187	login_cap_t *lc;
1188	FILE *pfp, *fp;
1189	intmax_t id = -1;
1190	time_t now;
1191	int rc, ch, fd = -1;
1192	size_t i;
1193	bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1194
1195	dryrun = nis = pretty = quiet = createhome = precrypted = false;
1196	genconf = false;
1197	gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1198	grname = name = NULL;
1199
1200	if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1201		err(EXIT_FAILURE, "calloc()");
1202
1203	cmdcnf->default_password = cmdcnf->expire_days = cmdcnf->password_days = -1;
1204	now = time(NULL);
1205
1206	if (arg1 != NULL) {
1207		if (arg1[strspn(arg1, "0123456789")] == '\0')
1208			id = pw_checkid(arg1, UID_MAX);
1209		else
1210			name = pw_checkname(arg1, 0);
1211	}
1212
1213	while ((ch = getopt(argc, argv, args)) != -1) {
1214		switch (ch) {
1215		case 'C':
1216			cfg = optarg;
1217			break;
1218		case 'q':
1219			quiet = true;
1220			break;
1221		case 'n':
1222			name = pw_checkname(optarg, 0);
1223			break;
1224		case 'u':
1225			userid = optarg;
1226			break;
1227		case 'c':
1228			gecos = pw_checkname(optarg, 1);
1229			break;
1230		case 'd':
1231			homedir = optarg;
1232			break;
1233		case 'e':
1234			if (genconf)
1235			    cmdcnf->expire_days = validate_expire(optarg, ch);
1236			else
1237			    cmdcnf->expire_days = parse_date(now, optarg);
1238			break;
1239		case 'p':
1240			if (genconf)
1241			    cmdcnf->password_days = validate_expire(optarg, ch);
1242			else
1243			    cmdcnf->password_days = parse_date(now, optarg);
1244			break;
1245		case 'g':
1246			validate_grname(cmdcnf, optarg);
1247			grname = optarg;
1248			break;
1249		case 'G':
1250			split_groups(&cmdcnf->groups, optarg);
1251			break;
1252		case 'm':
1253			createhome = true;
1254			break;
1255		case 'M':
1256			cmdcnf->homemode = validate_mode(optarg);
1257			break;
1258		case 'k':
1259			walk = skel = optarg;
1260			if (*walk == '/')
1261				walk++;
1262			if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1263				errx(EX_OSFILE, "skeleton `%s' does not "
1264				    "exists", skel);
1265			if (!S_ISDIR(st.st_mode))
1266				errx(EX_OSFILE, "skeleton `%s' is not a "
1267				    "directory", skel);
1268			cmdcnf->dotdir = skel;
1269			break;
1270		case 's':
1271			cmdcnf->shell_default = optarg;
1272			break;
1273		case 'o':
1274			conf.checkduplicate = false;
1275			break;
1276		case 'L':
1277			cmdcnf->default_class = pw_checkname(optarg, 0);
1278			break;
1279		case 'i':
1280			groupid = optarg;
1281			break;
1282		case 'w':
1283			default_passwd = optarg;
1284			break;
1285		case 'H':
1286			if (fd != -1)
1287				errx(EX_USAGE, "'-h' and '-H' are mutually "
1288				    "exclusive options");
1289			fd = pw_checkfd(optarg);
1290			precrypted = true;
1291			if (fd == '-')
1292				errx(EX_USAGE, "-H expects a file descriptor");
1293			break;
1294		case 'h':
1295			if (fd != -1)
1296				errx(EX_USAGE, "'-h' and '-H' are mutually "
1297				    "exclusive options");
1298			fd = pw_checkfd(optarg);
1299			break;
1300		case 'D':
1301			genconf = true;
1302			break;
1303		case 'b':
1304			cmdcnf->home = optarg;
1305			break;
1306		case 'N':
1307			dryrun = true;
1308			break;
1309		case 'P':
1310			pretty = true;
1311			break;
1312		case 'y':
1313			cmdcnf->nispasswd = optarg;
1314			break;
1315		case 'Y':
1316			nis = true;
1317			break;
1318		default:
1319			usage();
1320		}
1321	}
1322	argc -= optind;
1323	argv += optind;
1324	if (argc > 0)
1325		usage();
1326
1327	if (geteuid() != 0 && ! dryrun)
1328		errx(EX_NOPERM, "you must be root");
1329
1330	if (quiet)
1331		freopen(_PATH_DEVNULL, "w", stderr);
1332
1333	cnf = get_userconfig(cfg);
1334
1335	mix_config(cmdcnf, cnf);
1336	if (default_passwd)
1337		cmdcnf->default_password = passwd_val(default_passwd,
1338		    cnf->default_password);
1339	if (genconf) {
1340		if (name != NULL)
1341			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
1342		if (userid != NULL) {
1343			if ((p = strtok(userid, ", \t")) != NULL)
1344				cmdcnf->min_uid = pw_checkid(p, UID_MAX);
1345			if (cmdcnf->min_uid == 0)
1346				cmdcnf->min_uid = 1000;
1347			if ((p = strtok(NULL, " ,\t")) != NULL)
1348				cmdcnf->max_uid = pw_checkid(p, UID_MAX);
1349			if (cmdcnf->max_uid == 0)
1350				cmdcnf->max_uid = 32000;
1351		}
1352		if (groupid != NULL) {
1353			if ((p = strtok(groupid, ", \t")) != NULL)
1354				cmdcnf->min_gid = pw_checkid(p, GID_MAX);
1355			if (cmdcnf->min_gid == 0)
1356				cmdcnf->min_gid = 1000;
1357			if ((p = strtok(NULL, " ,\t")) != NULL)
1358				cmdcnf->max_gid = pw_checkid(p, GID_MAX);
1359			if (cmdcnf->max_gid == 0)
1360				cmdcnf->max_gid = 32000;
1361		}
1362		if (write_userconfig(cmdcnf, cfg))
1363			return (EXIT_SUCCESS);
1364		err(EX_IOERR, "config update");
1365	}
1366
1367	if (userid)
1368		id = pw_checkid(userid, UID_MAX);
1369	if (id < 0 && name == NULL)
1370		errx(EX_DATAERR, "user name or id required");
1371
1372	if (name == NULL)
1373		errx(EX_DATAERR, "login name required");
1374
1375	if (GETPWNAM(name) != NULL)
1376		errx(EX_DATAERR, "login name `%s' already exists", name);
1377
1378	if (!grname)
1379		grname = cmdcnf->default_group;
1380
1381	pwd = &fakeuser;
1382	pwd->pw_name = name;
1383	pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1384	pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1385	pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1386	    (gid_t) pwd->pw_uid, dryrun);
1387
1388	/* cmdcnf->password_days and cmdcnf->expire_days hold unixtime here */
1389	if (cmdcnf->password_days > 0)
1390		pwd->pw_change = cmdcnf->password_days;
1391	if (cmdcnf->expire_days > 0)
1392		pwd->pw_expire = cmdcnf->expire_days;
1393
1394	pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1395	pwd->pw_shell = pw_shellpolicy(cmdcnf);
1396	lc = login_getpwclass(pwd);
1397	if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1398		warn("setting crypt(3) format");
1399	login_close(lc);
1400	pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name);
1401	if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1402		warnx("WARNING: new account `%s' has a uid of 0 "
1403		    "(superuser access!)", pwd->pw_name);
1404	if (gecos)
1405		pwd->pw_gecos = gecos;
1406
1407	if (fd != -1)
1408		pw_set_passwd(pwd, fd, precrypted, false);
1409
1410	if (dryrun)
1411		return (print_user(pwd, pretty, false));
1412
1413	if ((rc = addpwent(pwd)) != 0) {
1414		if (rc == -1)
1415			errx(EX_IOERR, "user '%s' already exists",
1416			    pwd->pw_name);
1417		else if (rc != 0)
1418			err(EX_IOERR, "passwd file update");
1419	}
1420	if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1421		printf("%s\n", cmdcnf->nispasswd);
1422		rc = addnispwent(cmdcnf->nispasswd, pwd);
1423		if (rc == -1)
1424			warnx("User '%s' already exists in NIS passwd",
1425			    pwd->pw_name);
1426		else if (rc != 0)
1427			warn("NIS passwd update");
1428		/* NOTE: we treat NIS-only update errors as non-fatal */
1429	}
1430
1431	if (cmdcnf->groups != NULL) {
1432		for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1433			grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1434			/* gr_add doesn't check if new member is already in group */
1435			if (grp_has_member(grp, pwd->pw_name))
1436				continue;
1437			grp = gr_add(grp, pwd->pw_name);
1438			/*
1439			 * grp can only be NULL in 2 cases:
1440			 * - the new member is already a member
1441			 * - a problem with memory occurs
1442			 * in both cases we want to skip now.
1443			 */
1444			if (grp == NULL)
1445				continue;
1446			chggrent(grp->gr_name, grp);
1447			free(grp);
1448		}
1449	}
1450
1451	pwd = GETPWNAM(name);
1452	if (pwd == NULL)
1453		errx(EX_NOUSER, "user '%s' disappeared during update", name);
1454
1455	grp = GETGRGID(pwd->pw_gid);
1456	pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1457	       pwd->pw_name, (uintmax_t)pwd->pw_uid,
1458	    grp ? grp->gr_name : "unknown",
1459	       (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1460	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1461
1462	/*
1463	 * let's touch and chown the user's mail file. This is not
1464	 * strictly necessary under BSD with a 0755 maildir but it also
1465	 * doesn't hurt anything to create the empty mailfile
1466	 */
1467	if (PWALTDIR() != PWF_ALT) {
1468		snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1469		    pwd->pw_name);
1470		/* Preserve contents & mtime */
1471		close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1472		fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1473		    AT_SYMLINK_NOFOLLOW);
1474	}
1475
1476	/*
1477	 * Let's create and populate the user's home directory. Note
1478	 * that this also `works' for editing users if -m is used, but
1479	 * existing files will *not* be overwritten.
1480	 */
1481	if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1482	    *pwd->pw_dir == '/' && pwd->pw_dir[1])
1483		create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1484		    cmdcnf->homemode, false);
1485
1486	if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1487	    (fp = fopen(cnf->newmail, "r")) != NULL) {
1488		if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1489			warn("sendmail");
1490		else {
1491			fprintf(pfp, "From: root\n" "To: %s\n"
1492			    "Subject: Welcome!\n\n", pwd->pw_name);
1493			while (fgets(line, sizeof(line), fp) != NULL) {
1494				/* Do substitutions? */
1495				fputs(line, pfp);
1496			}
1497			pclose(pfp);
1498			pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1499			    pwd->pw_name, (uintmax_t)pwd->pw_uid);
1500		}
1501		fclose(fp);
1502	}
1503
1504	if (nis && nis_update() == 0)
1505		pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1506
1507	return (EXIT_SUCCESS);
1508}
1509
1510int
1511pw_user_mod(int argc, char **argv, char *arg1)
1512{
1513	struct userconf *cnf;
1514	struct passwd *pwd;
1515	struct group *grp;
1516	StringList *groups = NULL;
1517	char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1518	const char *cfg = NULL;
1519	char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1520	char *passwd, *class, *nispasswd;
1521	login_cap_t *lc;
1522	struct stat st;
1523	intmax_t id = -1;
1524	int ch, fd = -1;
1525	size_t i, j;
1526	bool quiet, createhome, pretty, dryrun, nis, edited;
1527	bool precrypted;
1528	mode_t homemode = 0;
1529	time_t expire_time, password_time, now;
1530
1531	expire_time = password_time = -1;
1532	gecos = homedir = grname = name = newname = skel = shell =NULL;
1533	passwd = NULL;
1534	class = nispasswd = NULL;
1535	quiet = createhome = pretty = dryrun = nis = precrypted = false;
1536	edited = false;
1537	now = time(NULL);
1538
1539	if (arg1 != NULL) {
1540		if (arg1[strspn(arg1, "0123456789")] == '\0')
1541			id = pw_checkid(arg1, UID_MAX);
1542		else
1543			name = arg1;
1544	}
1545
1546	while ((ch = getopt(argc, argv, args)) != -1) {
1547		switch (ch) {
1548		case 'C':
1549			cfg = optarg;
1550			break;
1551		case 'q':
1552			quiet = true;
1553			break;
1554		case 'n':
1555			name = optarg;
1556			break;
1557		case 'u':
1558			id = pw_checkid(optarg, UID_MAX);
1559			break;
1560		case 'c':
1561			gecos = pw_checkname(optarg, 1);
1562			break;
1563		case 'd':
1564			homedir = optarg;
1565			break;
1566		case 'e':
1567			expire_time = parse_date(now, optarg);
1568			break;
1569		case 'p':
1570			password_time = parse_date(now, optarg);
1571			break;
1572		case 'g':
1573			group_from_name_or_id(optarg);
1574			grname = optarg;
1575			break;
1576		case 'G':
1577			split_groups(&groups, optarg);
1578			break;
1579		case 'm':
1580			createhome = true;
1581			break;
1582		case 'M':
1583			homemode = validate_mode(optarg);
1584			break;
1585		case 'l':
1586			newname = optarg;
1587			break;
1588		case 'k':
1589			walk = skel = optarg;
1590			if (*walk == '/')
1591				walk++;
1592			if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1593				errx(EX_OSFILE, "skeleton `%s' does not "
1594				    "exists", skel);
1595			if (!S_ISDIR(st.st_mode))
1596				errx(EX_OSFILE, "skeleton `%s' is not a "
1597				    "directory", skel);
1598			break;
1599		case 's':
1600			shell = optarg;
1601			break;
1602		case 'w':
1603			passwd = optarg;
1604			break;
1605		case 'L':
1606			class = pw_checkname(optarg, 0);
1607			break;
1608		case 'H':
1609			if (fd != -1)
1610				errx(EX_USAGE, "'-h' and '-H' are mutually "
1611				    "exclusive options");
1612			fd = pw_checkfd(optarg);
1613			precrypted = true;
1614			if (fd == '-')
1615				errx(EX_USAGE, "-H expects a file descriptor");
1616			break;
1617		case 'h':
1618			if (fd != -1)
1619				errx(EX_USAGE, "'-h' and '-H' are mutually "
1620				    "exclusive options");
1621			fd = pw_checkfd(optarg);
1622			break;
1623		case 'N':
1624			dryrun = true;
1625			break;
1626		case 'P':
1627			pretty = true;
1628			break;
1629		case 'y':
1630			nispasswd = optarg;
1631			break;
1632		case 'Y':
1633			nis = true;
1634			break;
1635		default:
1636			usage();
1637		}
1638	}
1639	argc -= optind;
1640	argv += optind;
1641	if (argc > 0)
1642		usage();
1643
1644	if (geteuid() != 0 && ! dryrun)
1645		errx(EX_NOPERM, "you must be root");
1646
1647	if (quiet)
1648		freopen(_PATH_DEVNULL, "w", stderr);
1649
1650	cnf = get_userconfig(cfg);
1651
1652	if (id < 0 && name == NULL)
1653		errx(EX_DATAERR, "username or id required");
1654
1655	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1656	if (pwd == NULL) {
1657		if (name == NULL)
1658			errx(EX_NOUSER, "no such uid `%ju'",
1659			    (uintmax_t) id);
1660		errx(EX_NOUSER, "no such user `%s'", name);
1661	}
1662
1663	if (name == NULL)
1664		name = pwd->pw_name;
1665
1666	if (nis && nispasswd == NULL)
1667		nispasswd = cnf->nispasswd;
1668
1669	if (PWF._altdir == PWF_REGULAR &&
1670	    ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
1671		if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
1672			if (!nis && nispasswd && *nispasswd != '/')
1673				errx(EX_NOUSER, "Cannot modify NIS user `%s'",
1674				    name);
1675		} else {
1676			errx(EX_NOUSER, "Cannot modify non local user `%s'",
1677			    name);
1678		}
1679	}
1680
1681	if (newname) {
1682		if (strcmp(pwd->pw_name, "root") == 0)
1683			errx(EX_DATAERR, "can't rename `root' account");
1684		if (strcmp(pwd->pw_name, newname) != 0) {
1685			pwd->pw_name = pw_checkname(newname, 0);
1686			edited = true;
1687		}
1688	}
1689
1690	if (id >= 0 && pwd->pw_uid != id) {
1691		pwd->pw_uid = id;
1692		edited = true;
1693		if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
1694			errx(EX_DATAERR, "can't change uid of `root' account");
1695		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1696			warnx("WARNING: account `%s' will have a uid of 0 "
1697			    "(superuser access!)", pwd->pw_name);
1698	}
1699
1700	if (grname && pwd->pw_uid != 0) {
1701		grp = GETGRNAM(grname);
1702		if (grp == NULL)
1703			grp = GETGRGID(pw_checkid(grname, GID_MAX));
1704		if (grp->gr_gid != pwd->pw_gid) {
1705			pwd->pw_gid = grp->gr_gid;
1706			edited = true;
1707		}
1708	}
1709
1710
1711	if (password_time >= 0 && pwd->pw_change != password_time) {
1712		pwd->pw_change = password_time;
1713		edited = true;
1714	}
1715
1716	if (expire_time >= 0 && pwd->pw_expire != expire_time) {
1717		pwd->pw_expire = expire_time;
1718		edited = true;
1719	}
1720
1721	if (shell) {
1722		shell = shell_path(cnf->shelldir, cnf->shells, shell);
1723		if (shell == NULL)
1724			shell = "";
1725		if (strcmp(shell, pwd->pw_shell) != 0) {
1726			pwd->pw_shell = shell;
1727			edited = true;
1728		}
1729	}
1730
1731	if (class && strcmp(pwd->pw_class, class) != 0) {
1732		pwd->pw_class = class;
1733		edited = true;
1734	}
1735
1736	if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1737		pwd->pw_dir = homedir;
1738		edited = true;
1739		if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1740			if (!createhome)
1741				warnx("WARNING: home `%s' does not exist",
1742				    pwd->pw_dir);
1743		} else if (!S_ISDIR(st.st_mode)) {
1744			warnx("WARNING: home `%s' is not a directory",
1745			    pwd->pw_dir);
1746		}
1747	}
1748
1749	if (passwd && conf.fd == -1) {
1750		lc = login_getpwclass(pwd);
1751		if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1752			warn("setting crypt(3) format");
1753		login_close(lc);
1754		cnf->default_password = passwd_val(passwd,
1755		    cnf->default_password);
1756		pwd->pw_passwd = pw_password(cnf, pwd->pw_name);
1757		edited = true;
1758	}
1759
1760	if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1761		pwd->pw_gecos = gecos;
1762		edited = true;
1763	}
1764
1765	if (fd != -1)
1766		edited = pw_set_passwd(pwd, fd, precrypted, true);
1767
1768	if (dryrun)
1769		return (print_user(pwd, pretty, false));
1770
1771	if (edited) /* Only updated this if required */
1772		perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1773	/* Now perform the needed changes concern groups */
1774	if (groups != NULL) {
1775		/* Delete User from groups using old name */
1776		SETGRENT();
1777		while ((grp = GETGRENT()) != NULL) {
1778			if (grp->gr_mem == NULL)
1779				continue;
1780			for (i = 0; grp->gr_mem[i] != NULL; i++) {
1781				if (strcmp(grp->gr_mem[i] , name) != 0)
1782					continue;
1783				for (j = i; grp->gr_mem[j] != NULL ; j++)
1784					grp->gr_mem[j] = grp->gr_mem[j+1];
1785				chggrent(grp->gr_name, grp);
1786				break;
1787			}
1788		}
1789		ENDGRENT();
1790		/* Add the user to the needed groups */
1791		for (i = 0; i < groups->sl_cur; i++) {
1792			grp = GETGRNAM(groups->sl_str[i]);
1793			grp = gr_add(grp, pwd->pw_name);
1794			if (grp == NULL)
1795				continue;
1796			chggrent(grp->gr_name, grp);
1797			free(grp);
1798		}
1799	}
1800	/* In case of rename we need to walk over the different groups */
1801	if (newname) {
1802		SETGRENT();
1803		while ((grp = GETGRENT()) != NULL) {
1804			if (grp->gr_mem == NULL)
1805				continue;
1806			for (i = 0; grp->gr_mem[i] != NULL; i++) {
1807				if (strcmp(grp->gr_mem[i], name) != 0)
1808					continue;
1809				grp->gr_mem[i] = newname;
1810				chggrent(grp->gr_name, grp);
1811				break;
1812			}
1813		}
1814	}
1815
1816	/* go get a current version of pwd */
1817	if (newname)
1818		name = newname;
1819	pwd = GETPWNAM(name);
1820	if (pwd == NULL)
1821		errx(EX_NOUSER, "user '%s' disappeared during update", name);
1822	grp = GETGRGID(pwd->pw_gid);
1823	pw_log(cnf, M_MODIFY, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1824	    pwd->pw_name, (uintmax_t)pwd->pw_uid,
1825	    grp ? grp->gr_name : "unknown",
1826	    (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1827	    pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1828
1829	/*
1830	 * Let's create and populate the user's home directory. Note
1831	 * that this also `works' for editing users if -m is used, but
1832	 * existing files will *not* be overwritten.
1833	 */
1834	if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1835	    *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1836		if (!skel)
1837			skel = cnf->dotdir;
1838		if (homemode == 0)
1839			homemode = cnf->homemode;
1840		create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1841	}
1842
1843	if (nis && nis_update() == 0)
1844		pw_log(cnf, M_MODIFY, W_USER, "NIS maps updated");
1845
1846	return (EXIT_SUCCESS);
1847}
1848