pw_user.c revision 327091
1/*-
2 * Copyright (C) 1996
3 *	David L. Nugent.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 */
27
28#ifndef lint
29static const char rcsid[] =
30  "$FreeBSD: stable/10/usr.sbin/pw/pw_user.c 327091 2017-12-22 18:15:34Z eugen $";
31#endif /* not lint */
32
33#include <sys/param.h>
34#include <sys/resource.h>
35#include <sys/time.h>
36#include <sys/types.h>
37
38#include <assert.h>
39#include <ctype.h>
40#include <dirent.h>
41#include <err.h>
42#include <errno.h>
43#include <fcntl.h>
44#include <grp.h>
45#include <pwd.h>
46#include <libutil.h>
47#include <login_cap.h>
48#include <paths.h>
49#include <string.h>
50#include <sysexits.h>
51#include <termios.h>
52#include <unistd.h>
53
54#include "pw.h"
55#include "bitmap.h"
56#include "psdate.h"
57
58#define LOGNAMESIZE (MAXLOGNAME-1)
59
60static		char locked_str[] = "*LOCKED*";
61
62static struct passwd fakeuser = {
63	"nouser",
64	"*",
65	-1,
66	-1,
67	0,
68	"",
69	"User &",
70	"/nonexistent",
71	"/bin/sh",
72	0,
73	0
74};
75
76static int	 print_user(struct passwd *pwd, bool pretty, bool v7);
77static uid_t	 pw_uidpolicy(struct userconf *cnf, intmax_t id);
78static uid_t	 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam,
79    gid_t prefer, bool dryrun);
80static char	*pw_homepolicy(struct userconf * cnf, char *homedir,
81    const char *user);
82static char	*pw_shellpolicy(struct userconf * cnf);
83static char	*pw_password(struct userconf * cnf, char const * user,
84    bool dryrun);
85static char	*shell_path(char const * path, char *shells[], char *sh);
86static void	rmat(uid_t uid);
87static void	rmopie(char const * name);
88
89static void
90mkdir_home_parents(int dfd, const char *dir)
91{
92	struct stat st;
93	char *dirs, *tmp;
94
95	if (*dir != '/')
96		errx(EX_DATAERR, "invalid base directory for home '%s'", dir);
97
98	dir++;
99
100	if (fstatat(dfd, dir, &st, 0) != -1) {
101		if (S_ISDIR(st.st_mode))
102			return;
103		errx(EX_OSFILE, "root home `/%s' is not a directory", dir);
104	}
105
106	dirs = strdup(dir);
107	if (dirs == NULL)
108		errx(EX_UNAVAILABLE, "out of memory");
109
110	tmp = strrchr(dirs, '/');
111	if (tmp == NULL) {
112		free(dirs);
113		return;
114	}
115	tmp[0] = '\0';
116
117	/*
118	 * This is a kludge especially for Joerg :)
119	 * If the home directory would be created in the root partition, then
120	 * we really create it under /usr which is likely to have more space.
121	 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
122	 */
123	if (strchr(dirs, '/') == NULL) {
124		asprintf(&tmp, "usr/%s", dirs);
125		if (tmp == NULL)
126			errx(EX_UNAVAILABLE, "out of memory");
127		if (mkdirat(dfd, tmp, _DEF_DIRMODE) != -1 || errno == EEXIST) {
128			fchownat(dfd, tmp, 0, 0, 0);
129			symlinkat(tmp, dfd, dirs);
130		}
131		free(tmp);
132	}
133	tmp = dirs;
134	if (fstatat(dfd, dirs, &st, 0) == -1) {
135		while ((tmp = strchr(tmp + 1, '/')) != NULL) {
136			*tmp = '\0';
137			if (fstatat(dfd, dirs, &st, 0) == -1) {
138				if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
139					err(EX_OSFILE,  "'%s' (root home parent) is not a directory", dirs);
140			}
141			*tmp = '/';
142		}
143	}
144	if (fstatat(dfd, dirs, &st, 0) == -1) {
145		if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
146			err(EX_OSFILE,  "'%s' (root home parent) is not a directory", dirs);
147		fchownat(dfd, dirs, 0, 0, 0);
148	}
149
150	free(dirs);
151}
152
153static void
154create_and_populate_homedir(struct userconf *cnf, struct passwd *pwd,
155    const char *skeldir, mode_t homemode, bool update)
156{
157	int skelfd = -1;
158
159	/* Create home parents directories */
160	mkdir_home_parents(conf.rootfd, pwd->pw_dir);
161
162	if (skeldir != NULL && *skeldir != '\0') {
163		if (*skeldir == '/')
164			skeldir++;
165		skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
166	}
167
168	copymkdir(conf.rootfd, pwd->pw_dir, skelfd, homemode, pwd->pw_uid,
169	    pwd->pw_gid, 0);
170	pw_log(cnf, update ? M_UPDATE : M_ADD, W_USER, "%s(%ju) home %s made",
171	    pwd->pw_name, (uintmax_t)pwd->pw_uid, pwd->pw_dir);
172}
173
174static int
175pw_set_passwd(struct passwd *pwd, int fd, bool precrypted, bool update)
176{
177	int		 b, istty;
178	struct termios	 t, n;
179	login_cap_t	*lc;
180	char		line[_PASSWORD_LEN+1];
181	char		*p;
182
183	if (fd == '-') {
184		if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
185			pwd->pw_passwd = "*";	/* No access */
186			return (1);
187		}
188		return (0);
189	}
190
191	if ((istty = isatty(fd))) {
192		if (tcgetattr(fd, &t) == -1)
193			istty = 0;
194		else {
195			n = t;
196			n.c_lflag &= ~(ECHO);
197			tcsetattr(fd, TCSANOW, &n);
198			printf("%s%spassword for user %s:",
199			    update ? "new " : "",
200			    precrypted ? "encrypted " : "",
201			    pwd->pw_name);
202			fflush(stdout);
203		}
204	}
205	b = read(fd, line, sizeof(line) - 1);
206	if (istty) {	/* Restore state */
207		tcsetattr(fd, TCSANOW, &t);
208		fputc('\n', stdout);
209		fflush(stdout);
210	}
211
212	if (b < 0)
213		err(EX_IOERR, "-%c file descriptor",
214		    precrypted ? 'H' : 'h');
215	line[b] = '\0';
216	if ((p = strpbrk(line, "\r\n")) != NULL)
217		*p = '\0';
218	if (!*line)
219		errx(EX_DATAERR, "empty password read on file descriptor %d",
220		    fd);
221	if (precrypted) {
222		if (strchr(line, ':') != NULL)
223			errx(EX_DATAERR, "bad encrypted password");
224		pwd->pw_passwd = strdup(line);
225	} else {
226		lc = login_getpwclass(pwd);
227		if (lc == NULL ||
228				login_setcryptfmt(lc, "sha512", NULL) == NULL)
229			warn("setting crypt(3) format");
230		login_close(lc);
231		pwd->pw_passwd = pw_pwcrypt(line);
232	}
233	return (1);
234}
235
236static void
237perform_chgpwent(const char *name, struct passwd *pwd, char *nispasswd)
238{
239	int rc;
240	struct passwd *nispwd;
241
242	/* duplicate for nis so that chgpwent is not modifying before NIS */
243	if (nispasswd && *nispasswd == '/')
244		nispwd = pw_dup(pwd);
245
246	rc = chgpwent(name, pwd);
247	if (rc == -1)
248		errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
249	else if (rc != 0)
250		err(EX_IOERR, "passwd file update");
251
252	if (nispasswd && *nispasswd == '/') {
253		rc = chgnispwent(nispasswd, name, nispwd);
254		if (rc == -1)
255			warn("User '%s' not found in NIS passwd", pwd->pw_name);
256		else if (rc != 0)
257			warn("NIS passwd update");
258		/* NOTE: NIS-only update errors are not fatal */
259	}
260}
261
262/*
263 * The M_LOCK and M_UNLOCK functions simply add or remove
264 * a "*LOCKED*" prefix from in front of the password to
265 * prevent it decoding correctly, and therefore prevents
266 * access. Of course, this only prevents access via
267 * password authentication (not ssh, kerberos or any
268 * other method that does not use the UNIX password) but
269 * that is a known limitation.
270 */
271static int
272pw_userlock(char *arg1, int mode)
273{
274	struct passwd *pwd = NULL;
275	char *passtmp = NULL;
276	char *name;
277	bool locked = false;
278	uid_t id = (uid_t)-1;
279
280	if (geteuid() != 0)
281		errx(EX_NOPERM, "you must be root");
282
283	if (arg1 == NULL)
284		errx(EX_DATAERR, "username or id required");
285
286	name = arg1;
287	if (arg1[strspn(name, "0123456789")] == '\0')
288		id = pw_checkid(name, UID_MAX);
289
290	pwd = GETPWNAM(pw_checkname(name, 0));
291	if (pwd == NULL && id != (uid_t)-1) {
292		pwd = GETPWUID(id);
293		if (pwd != NULL)
294			name = pwd->pw_name;
295	}
296	if (pwd == NULL) {
297		if (id == (uid_t)-1)
298			errx(EX_NOUSER, "no such name or uid `%ju'", (uintmax_t) id);
299		errx(EX_NOUSER, "no such user `%s'", name);
300	}
301
302	if (name == NULL)
303		name = pwd->pw_name;
304
305	if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
306		locked = true;
307	if (mode == M_LOCK && locked)
308		errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
309	if (mode == M_UNLOCK && !locked)
310		errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
311
312	if (mode == M_LOCK) {
313		asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
314		if (passtmp == NULL)	/* disaster */
315			errx(EX_UNAVAILABLE, "out of memory");
316		pwd->pw_passwd = passtmp;
317	} else {
318		pwd->pw_passwd += sizeof(locked_str)-1;
319	}
320
321	perform_chgpwent(name, pwd, NULL);
322	free(passtmp);
323
324	return (EXIT_SUCCESS);
325}
326
327static uid_t
328pw_uidpolicy(struct userconf * cnf, intmax_t id)
329{
330	struct passwd  *pwd;
331	struct bitmap   bm;
332	uid_t           uid = (uid_t) - 1;
333
334	/*
335	 * Check the given uid, if any
336	 */
337	if (id >= 0) {
338		uid = (uid_t) id;
339
340		if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
341			errx(EX_DATAERR, "uid `%ju' has already been allocated",
342			    (uintmax_t)pwd->pw_uid);
343		return (uid);
344	}
345	/*
346	 * We need to allocate the next available uid under one of
347	 * two policies a) Grab the first unused uid b) Grab the
348	 * highest possible unused uid
349	 */
350	if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
351						 * claus^H^H^H^Hheck */
352		cnf->min_uid = 1000;
353		cnf->max_uid = 32000;
354	}
355	bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
356
357	/*
358	 * Now, let's fill the bitmap from the password file
359	 */
360	SETPWENT();
361	while ((pwd = GETPWENT()) != NULL)
362		if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
363			bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
364	ENDPWENT();
365
366	/*
367	 * Then apply the policy, with fallback to reuse if necessary
368	 */
369	if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
370		uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
371
372	/*
373	 * Another sanity check
374	 */
375	if (uid < cnf->min_uid || uid > cnf->max_uid)
376		errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
377	bm_dealloc(&bm);
378	return (uid);
379}
380
381static uid_t
382pw_gidpolicy(struct userconf *cnf, char *grname, char *nam, gid_t prefer, bool dryrun)
383{
384	struct group   *grp;
385	gid_t           gid = (uid_t) - 1;
386
387	/*
388	 * Check the given gid, if any
389	 */
390	SETGRENT();
391	if (grname) {
392		if ((grp = GETGRNAM(grname)) == NULL) {
393			gid = pw_checkid(grname, GID_MAX);
394			grp = GETGRGID(gid);
395		}
396		gid = grp->gr_gid;
397	} else if ((grp = GETGRNAM(nam)) != NULL &&
398	    (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
399		gid = grp->gr_gid;  /* Already created? Use it anyway... */
400	} else {
401		intmax_t		grid = -1;
402
403		/*
404		 * We need to auto-create a group with the user's name. We
405		 * can send all the appropriate output to our sister routine
406		 * bit first see if we can create a group with gid==uid so we
407		 * can keep the user and group ids in sync. We purposely do
408		 * NOT check the gid range if we can force the sync. If the
409		 * user's name dups an existing group, then the group add
410		 * function will happily handle that case for us and exit.
411		 */
412		if (GETGRGID(prefer) == NULL)
413			grid = prefer;
414		if (dryrun) {
415			gid = pw_groupnext(cnf, true);
416		} else {
417			if (grid == -1)
418				grid =  pw_groupnext(cnf, true);
419			groupadd(cnf, nam, grid, NULL, -1, false, false, false);
420			if ((grp = GETGRNAM(nam)) != NULL)
421				gid = grp->gr_gid;
422		}
423	}
424	ENDGRENT();
425	return (gid);
426}
427
428static char *
429pw_homepolicy(struct userconf * cnf, char *homedir, const char *user)
430{
431	static char     home[128];
432
433	if (homedir)
434		return (homedir);
435
436	if (cnf->home == NULL || *cnf->home == '\0')
437		errx(EX_CONFIG, "no base home directory set");
438	snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
439
440	return (home);
441}
442
443static char *
444shell_path(char const * path, char *shells[], char *sh)
445{
446	if (sh != NULL && (*sh == '/' || *sh == '\0'))
447		return sh;	/* specified full path or forced none */
448	else {
449		char           *p;
450		char            paths[_UC_MAXLINE];
451
452		/*
453		 * We need to search paths
454		 */
455		strlcpy(paths, path, sizeof(paths));
456		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
457			int             i;
458			static char     shellpath[256];
459
460			if (sh != NULL) {
461				snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
462				if (access(shellpath, X_OK) == 0)
463					return shellpath;
464			} else
465				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
466					snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
467					if (access(shellpath, X_OK) == 0)
468						return shellpath;
469				}
470		}
471		if (sh == NULL)
472			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
473		errx(EX_CONFIG, "no default shell available or defined");
474		return NULL;
475	}
476}
477
478static char *
479pw_shellpolicy(struct userconf * cnf)
480{
481
482	return shell_path(cnf->shelldir, cnf->shells, cnf->shell_default);
483}
484
485#define	SALTSIZE	32
486
487static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
488
489char *
490pw_pwcrypt(char *password)
491{
492	int             i;
493	char            salt[SALTSIZE + 1];
494	char		*cryptpw;
495	static char     buf[256];
496	size_t		pwlen;
497
498	/*
499	 * Calculate a salt value
500	 */
501	for (i = 0; i < SALTSIZE; i++)
502		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
503	salt[SALTSIZE] = '\0';
504
505	cryptpw = crypt(password, salt);
506	if (cryptpw == NULL)
507		errx(EX_CONFIG, "crypt(3) failure");
508	pwlen = strlcpy(buf, cryptpw, sizeof(buf));
509	assert(pwlen < sizeof(buf));
510	return (buf);
511}
512
513static char *
514pw_password(struct userconf * cnf, char const * user, bool dryrun)
515{
516	int             i, l;
517	char            pwbuf[32];
518
519	switch (cnf->default_password) {
520	case P_NONE:		/* No password at all! */
521		return "";
522	case P_RANDOM:			/* Random password */
523		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
524		for (i = 0; i < l; i++)
525			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
526		pwbuf[i] = '\0';
527
528		/*
529		 * We give this information back to the user
530		 */
531		if (conf.fd == -1 && !dryrun) {
532			if (isatty(STDOUT_FILENO))
533				printf("Password for '%s' is: ", user);
534			printf("%s\n", pwbuf);
535			fflush(stdout);
536		}
537		break;
538	case P_YES:		/* user's name */
539		strlcpy(pwbuf, user, sizeof(pwbuf));
540		break;
541	case P_NO:		/* No login - default */
542				/* FALLTHROUGH */
543	default:
544		return "*";
545	}
546	return pw_pwcrypt(pwbuf);
547}
548
549static int
550print_user(struct passwd * pwd, bool pretty, bool v7)
551{
552	int		j;
553	char           *p;
554	struct group   *grp = GETGRGID(pwd->pw_gid);
555	char            uname[60] = "User &", office[60] = "[None]",
556			wphone[60] = "[None]", hphone[60] = "[None]";
557	char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
558	struct tm *    tptr;
559
560	if (!pretty) {
561		p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
562		printf("%s\n", p);
563		free(p);
564		return (EXIT_SUCCESS);
565	}
566
567	if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
568		strlcpy(uname, p, sizeof(uname));
569		if ((p = strtok(NULL, ",")) != NULL) {
570			strlcpy(office, p, sizeof(office));
571			if ((p = strtok(NULL, ",")) != NULL) {
572				strlcpy(wphone, p, sizeof(wphone));
573				if ((p = strtok(NULL, "")) != NULL) {
574					strlcpy(hphone, p, sizeof(hphone));
575				}
576			}
577		}
578	}
579	/*
580	 * Handle '&' in gecos field
581	 */
582	if ((p = strchr(uname, '&')) != NULL) {
583		int             l = strlen(pwd->pw_name);
584		int             m = strlen(p);
585
586		memmove(p + l, p + 1, m);
587		memmove(p, pwd->pw_name, l);
588		*p = (char) toupper((unsigned char)*p);
589	}
590	if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
591		strftime(acexpire, sizeof acexpire, "%c", tptr);
592		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
593		strftime(pwexpire, sizeof pwexpire, "%c", tptr);
594	printf("Login Name: %-15s   #%-12ju Group: %-15s   #%ju\n"
595	       " Full Name: %s\n"
596	       "      Home: %-26.26s      Class: %s\n"
597	       "     Shell: %-26.26s     Office: %s\n"
598	       "Work Phone: %-26.26s Home Phone: %s\n"
599	       "Acc Expire: %-26.26s Pwd Expire: %s\n",
600	       pwd->pw_name, (uintmax_t)pwd->pw_uid,
601	       grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
602	       uname, pwd->pw_dir, pwd->pw_class,
603	       pwd->pw_shell, office, wphone, hphone,
604	       acexpire, pwexpire);
605        SETGRENT();
606	j = 0;
607	while ((grp=GETGRENT()) != NULL) {
608		int     i = 0;
609		if (grp->gr_mem != NULL) {
610			while (grp->gr_mem[i] != NULL) {
611				if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
612					printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
613					break;
614				}
615				++i;
616			}
617		}
618	}
619	ENDGRENT();
620	printf("%s", j ? "\n" : "");
621	return (EXIT_SUCCESS);
622}
623
624char *
625pw_checkname(char *name, int gecos)
626{
627	char showch[8];
628	const char *badchars, *ch, *showtype;
629	int reject;
630
631	ch = name;
632	reject = 0;
633	if (gecos) {
634		/* See if the name is valid as a gecos (comment) field. */
635		badchars = ":!@";
636		showtype = "gecos field";
637	} else {
638		/* See if the name is valid as a userid or group. */
639		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
640		showtype = "userid/group name";
641		/* Userids and groups can not have a leading '-'. */
642		if (*ch == '-')
643			reject = 1;
644	}
645	if (!reject) {
646		while (*ch) {
647			if (strchr(badchars, *ch) != NULL ||
648			    (!gecos && *ch < ' ') ||
649			    *ch == 127) {
650				reject = 1;
651				break;
652			}
653			/* 8-bit characters are only allowed in GECOS fields */
654			if (!gecos && (*ch & 0x80)) {
655				reject = 1;
656				break;
657			}
658			ch++;
659		}
660	}
661	/*
662	 * A `$' is allowed as the final character for userids and groups,
663	 * mainly for the benefit of samba.
664	 */
665	if (reject && !gecos) {
666		if (*ch == '$' && *(ch + 1) == '\0') {
667			reject = 0;
668			ch++;
669		}
670	}
671	if (reject) {
672		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
673		    ? "`%c'" : "0x%02x", *ch);
674		errx(EX_DATAERR, "invalid character %s at position %td in %s",
675		    showch, (ch - name), showtype);
676	}
677	if (!gecos && (ch - name) > LOGNAMESIZE)
678		errx(EX_USAGE, "name too long `%s' (max is %d)", name,
679		    LOGNAMESIZE);
680
681	return (name);
682}
683
684static void
685rmat(uid_t uid)
686{
687	DIR            *d = opendir("/var/at/jobs");
688
689	if (d != NULL) {
690		struct dirent  *e;
691
692		while ((e = readdir(d)) != NULL) {
693			struct stat     st;
694
695			if (strncmp(e->d_name, ".lock", 5) != 0 &&
696			    stat(e->d_name, &st) == 0 &&
697			    !S_ISDIR(st.st_mode) &&
698			    st.st_uid == uid) {
699				char            tmp[MAXPATHLEN];
700
701				snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s",
702				    e->d_name);
703				system(tmp);
704			}
705		}
706		closedir(d);
707	}
708}
709
710static void
711rmopie(char const * name)
712{
713	char tmp[1014];
714	FILE *fp;
715	int fd;
716	size_t len;
717	off_t	atofs = 0;
718
719	if ((fd = openat(conf.rootfd, "etc/opiekeys", O_RDWR)) == -1)
720		return;
721
722	fp = fdopen(fd, "r+");
723	len = strlen(name);
724
725	while (fgets(tmp, sizeof(tmp), fp) != NULL) {
726		if (strncmp(name, tmp, len) == 0 && tmp[len]==' ') {
727			/* Comment username out */
728			if (fseek(fp, atofs, SEEK_SET) == 0)
729				fwrite("#", 1, 1, fp);
730			break;
731		}
732		atofs = ftell(fp);
733	}
734	/*
735	 * If we got an error of any sort, don't update!
736	 */
737	fclose(fp);
738}
739
740int
741pw_user_next(int argc, char **argv, char *name __unused)
742{
743	struct userconf *cnf = NULL;
744	const char *cfg = NULL;
745	int ch;
746	bool quiet = false;
747	uid_t next;
748
749	while ((ch = getopt(argc, argv, "Cq")) != -1) {
750		switch (ch) {
751		case 'C':
752			cfg = optarg;
753			break;
754		case 'q':
755			quiet = true;
756			break;
757		}
758	}
759
760	if (quiet)
761		freopen(_PATH_DEVNULL, "w", stderr);
762
763	cnf = get_userconfig(cfg);
764
765	next = pw_uidpolicy(cnf, -1);
766
767	printf("%ju:", (uintmax_t)next);
768	pw_groupnext(cnf, quiet);
769
770	return (EXIT_SUCCESS);
771}
772
773int
774pw_user_show(int argc, char **argv, char *arg1)
775{
776	struct passwd *pwd = NULL;
777	char *name = NULL;
778	intmax_t id = -1;
779	int ch;
780	bool all = false;
781	bool pretty = false;
782	bool force = false;
783	bool v7 = false;
784	bool quiet = false;
785
786	if (arg1 != NULL) {
787		if (arg1[strspn(arg1, "0123456789")] == '\0')
788			id = pw_checkid(arg1, UID_MAX);
789		else
790			name = arg1;
791	}
792
793	while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
794		switch (ch) {
795		case 'C':
796			/* ignore compatibility */
797			break;
798		case 'q':
799			quiet = true;
800			break;
801		case 'n':
802			name = optarg;
803			break;
804		case 'u':
805			id = pw_checkid(optarg, UID_MAX);
806			break;
807		case 'F':
808			force = true;
809			break;
810		case 'P':
811			pretty = true;
812			break;
813		case 'a':
814			all = true;
815			break;
816		case '7':
817			v7 = true;
818			break;
819		}
820	}
821
822	if (quiet)
823		freopen(_PATH_DEVNULL, "w", stderr);
824
825	if (all) {
826		SETPWENT();
827		while ((pwd = GETPWENT()) != NULL)
828			print_user(pwd, pretty, v7);
829		ENDPWENT();
830		return (EXIT_SUCCESS);
831	}
832
833	if (id < 0 && name == NULL)
834		errx(EX_DATAERR, "username or id required");
835
836	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
837	if (pwd == NULL) {
838		if (force) {
839			pwd = &fakeuser;
840		} else {
841			if (name == NULL)
842				errx(EX_NOUSER, "no such uid `%ju'",
843				    (uintmax_t) id);
844			errx(EX_NOUSER, "no such user `%s'", name);
845		}
846	}
847
848	return (print_user(pwd, pretty, v7));
849}
850
851int
852pw_user_del(int argc, char **argv, char *arg1)
853{
854	struct userconf *cnf = NULL;
855	struct passwd *pwd = NULL;
856	struct group *gr, *grp;
857	char *name = NULL;
858	char grname[MAXLOGNAME];
859	char *nispasswd = NULL;
860	char file[MAXPATHLEN];
861	char home[MAXPATHLEN];
862	const char *cfg = NULL;
863	struct stat st;
864	intmax_t id = -1;
865	int ch, rc;
866	bool nis = false;
867	bool deletehome = false;
868	bool quiet = false;
869
870	if (arg1 != NULL) {
871		if (arg1[strspn(arg1, "0123456789")] == '\0')
872			id = pw_checkid(arg1, UID_MAX);
873		else
874			name = arg1;
875	}
876
877	while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
878		switch (ch) {
879		case 'C':
880			cfg = optarg;
881			break;
882		case 'q':
883			quiet = true;
884			break;
885		case 'n':
886			name = optarg;
887			break;
888		case 'u':
889			id = pw_checkid(optarg, UID_MAX);
890			break;
891		case 'r':
892			deletehome = true;
893			break;
894		case 'y':
895			nispasswd = optarg;
896			break;
897		case 'Y':
898			nis = true;
899			break;
900		}
901	}
902
903	if (quiet)
904		freopen(_PATH_DEVNULL, "w", stderr);
905
906	if (id < 0 && name == NULL)
907		errx(EX_DATAERR, "username or id required");
908
909	cnf = get_userconfig(cfg);
910
911	if (nispasswd == NULL)
912		nispasswd = cnf->nispasswd;
913
914	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
915	if (pwd == NULL) {
916		if (name == NULL)
917			errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
918		errx(EX_NOUSER, "no such user `%s'", name);
919	}
920
921	if (PWF._altdir == PWF_REGULAR &&
922	    ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
923		if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
924			if (!nis && nispasswd && *nispasswd != '/')
925				errx(EX_NOUSER, "Cannot remove NIS user `%s'",
926				    name);
927		} else {
928			errx(EX_NOUSER, "Cannot remove non local user `%s'",
929			    name);
930		}
931	}
932
933	id = pwd->pw_uid;
934	if (name == NULL)
935		name = pwd->pw_name;
936
937	if (strcmp(pwd->pw_name, "root") == 0)
938		errx(EX_DATAERR, "cannot remove user 'root'");
939
940	/* Remove opie record from /etc/opiekeys */
941	if (PWALTDIR() != PWF_ALT)
942		rmopie(pwd->pw_name);
943
944	if (!PWALTDIR()) {
945		/* Remove crontabs */
946		snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
947		if (access(file, F_OK) == 0) {
948			snprintf(file, sizeof(file), "crontab -u %s -r",
949			    pwd->pw_name);
950			system(file);
951		}
952	}
953
954	/*
955	 * Save these for later, since contents of pwd may be
956	 * invalidated by deletion
957	 */
958	snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
959	strlcpy(home, pwd->pw_dir, sizeof(home));
960	gr = GETGRGID(pwd->pw_gid);
961	if (gr != NULL)
962		strlcpy(grname, gr->gr_name, LOGNAMESIZE);
963	else
964		grname[0] = '\0';
965
966	rc = delpwent(pwd);
967	if (rc == -1)
968		err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
969	else if (rc != 0)
970		err(EX_IOERR, "passwd update");
971
972	if (nis && nispasswd && *nispasswd=='/') {
973		rc = delnispwent(nispasswd, name);
974		if (rc == -1)
975			warnx("WARNING: user '%s' does not exist in NIS passwd",
976			    pwd->pw_name);
977		else if (rc != 0)
978			warn("WARNING: NIS passwd update");
979	}
980
981	grp = GETGRNAM(name);
982	if (grp != NULL &&
983	    (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
984	    strcmp(name, grname) == 0)
985		delgrent(GETGRNAM(name));
986	SETGRENT();
987	while ((grp = GETGRENT()) != NULL) {
988		int i, j;
989		char group[MAXLOGNAME];
990		if (grp->gr_mem == NULL)
991			continue;
992
993		for (i = 0; grp->gr_mem[i] != NULL; i++) {
994			if (strcmp(grp->gr_mem[i], name) != 0)
995				continue;
996
997			for (j = i; grp->gr_mem[j] != NULL; j++)
998				grp->gr_mem[j] = grp->gr_mem[j+1];
999			strlcpy(group, grp->gr_name, MAXLOGNAME);
1000			chggrent(group, grp);
1001		}
1002	}
1003	ENDGRENT();
1004
1005	pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
1006	    (uintmax_t)id);
1007
1008	/* Remove mail file */
1009	if (PWALTDIR() != PWF_ALT)
1010		unlinkat(conf.rootfd, file + 1, 0);
1011
1012	/* Remove at jobs */
1013	if (!PWALTDIR() && getpwuid(id) == NULL)
1014		rmat(id);
1015
1016	/* Remove home directory and contents */
1017	if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
1018	    GETPWUID(id) == NULL &&
1019	    fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1020		rm_r(conf.rootfd, home, id);
1021		pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
1022		    "removed", name, (uintmax_t)id, home,
1023		     fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1024		     "completely ");
1025	}
1026
1027	return (EXIT_SUCCESS);
1028}
1029
1030int
1031pw_user_lock(int argc, char **argv, char *arg1)
1032{
1033	int ch;
1034
1035	while ((ch = getopt(argc, argv, "Cq")) != -1) {
1036		switch (ch) {
1037		case 'C':
1038		case 'q':
1039			/* compatibility */
1040			break;
1041		}
1042	}
1043
1044	return (pw_userlock(arg1, M_LOCK));
1045}
1046
1047int
1048pw_user_unlock(int argc, char **argv, char *arg1)
1049{
1050	int ch;
1051
1052	while ((ch = getopt(argc, argv, "Cq")) != -1) {
1053		switch (ch) {
1054		case 'C':
1055		case 'q':
1056			/* compatibility */
1057			break;
1058		}
1059	}
1060
1061	return (pw_userlock(arg1, M_UNLOCK));
1062}
1063
1064static struct group *
1065group_from_name_or_id(char *name)
1066{
1067	const char *errstr = NULL;
1068	struct group *grp;
1069	uintmax_t id;
1070
1071	if ((grp = GETGRNAM(name)) == NULL) {
1072		id = strtounum(name, 0, GID_MAX, &errstr);
1073		if (errstr)
1074			errx(EX_NOUSER, "group `%s' does not exist", name);
1075		grp = GETGRGID(id);
1076		if (grp == NULL)
1077			errx(EX_NOUSER, "group `%s' does not exist", name);
1078	}
1079
1080	return (grp);
1081}
1082
1083static void
1084split_groups(StringList **groups, char *groupsstr)
1085{
1086	struct group *grp;
1087	char *p;
1088	char tok[] = ", \t";
1089
1090	if (*groups == NULL)
1091		*groups = sl_init();
1092	for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1093		grp = group_from_name_or_id(p);
1094		sl_add(*groups, newstr(grp->gr_name));
1095	}
1096}
1097
1098static void
1099validate_grname(struct userconf *cnf, char *group)
1100{
1101	struct group *grp;
1102
1103	if (group == NULL || *group == '\0') {
1104		cnf->default_group = "";
1105		return;
1106	}
1107	grp = group_from_name_or_id(group);
1108	cnf->default_group = newstr(grp->gr_name);
1109}
1110
1111static mode_t
1112validate_mode(char *mode)
1113{
1114	mode_t m;
1115	void *set;
1116
1117	if ((set = setmode(mode)) == NULL)
1118		errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1119
1120	m = getmode(set, _DEF_DIRMODE);
1121	free(set);
1122	return (m);
1123}
1124
1125static long
1126validate_expire(char *str, int opt)
1127{
1128	if (!numerics(str))
1129		errx(EX_DATAERR, "-%c argument must be numeric "
1130		     "when setting defaults: %s", (char)opt, str);
1131	return strtol(str, NULL, 0);
1132}
1133
1134static void
1135mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1136{
1137
1138	if (cmdcnf->default_password < 0)
1139		cmdcnf->default_password = cfg->default_password;
1140	if (cmdcnf->reuse_uids == 0)
1141		cmdcnf->reuse_uids = cfg->reuse_uids;
1142	if (cmdcnf->reuse_gids == 0)
1143		cmdcnf->reuse_gids = cfg->reuse_gids;
1144	if (cmdcnf->nispasswd == NULL)
1145		cmdcnf->nispasswd = cfg->nispasswd;
1146	if (cmdcnf->dotdir == NULL)
1147		cmdcnf->dotdir = cfg->dotdir;
1148	if (cmdcnf->newmail == NULL)
1149		cmdcnf->newmail = cfg->newmail;
1150	if (cmdcnf->logfile == NULL)
1151		cmdcnf->logfile = cfg->logfile;
1152	if (cmdcnf->home == NULL)
1153		cmdcnf->home = cfg->home;
1154	if (cmdcnf->homemode == 0)
1155		cmdcnf->homemode = cfg->homemode;
1156	if (cmdcnf->shelldir == NULL)
1157		cmdcnf->shelldir = cfg->shelldir;
1158	if (cmdcnf->shells == NULL)
1159		cmdcnf->shells = cfg->shells;
1160	if (cmdcnf->shell_default == NULL)
1161		cmdcnf->shell_default = cfg->shell_default;
1162	if (cmdcnf->default_group == NULL)
1163		cmdcnf->default_group = cfg->default_group;
1164	if (cmdcnf->groups == NULL)
1165		cmdcnf->groups = cfg->groups;
1166	if (cmdcnf->default_class == NULL)
1167		cmdcnf->default_class = cfg->default_class;
1168	if (cmdcnf->min_uid == 0)
1169		cmdcnf->min_uid = cfg->min_uid;
1170	if (cmdcnf->max_uid == 0)
1171		cmdcnf->max_uid = cfg->max_uid;
1172	if (cmdcnf->min_gid == 0)
1173		cmdcnf->min_gid = cfg->min_gid;
1174	if (cmdcnf->max_gid == 0)
1175		cmdcnf->max_gid = cfg->max_gid;
1176	if (cmdcnf->expire_days < 0)
1177		cmdcnf->expire_days = cfg->expire_days;
1178	if (cmdcnf->password_days < 0)
1179		cmdcnf->password_days = cfg->password_days;
1180}
1181
1182int
1183pw_user_add(int argc, char **argv, char *arg1)
1184{
1185	struct userconf *cnf, *cmdcnf;
1186	struct passwd *pwd;
1187	struct group *grp;
1188	struct stat st;
1189	char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1190	char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1191	char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1192	char *default_passwd, *name, *p;
1193	const char *cfg = NULL;
1194	login_cap_t *lc;
1195	FILE *pfp, *fp;
1196	intmax_t id = -1;
1197	time_t now;
1198	int rc, ch, fd = -1;
1199	size_t i;
1200	bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1201
1202	dryrun = nis = pretty = quiet = createhome = precrypted = false;
1203	genconf = false;
1204	gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1205	grname = name = NULL;
1206
1207	if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1208		err(EXIT_FAILURE, "calloc()");
1209
1210	cmdcnf->default_password = cmdcnf->expire_days = cmdcnf->password_days = -1;
1211	now = time(NULL);
1212
1213	if (arg1 != NULL) {
1214		if (arg1[strspn(arg1, "0123456789")] == '\0')
1215			id = pw_checkid(arg1, UID_MAX);
1216		else
1217			name = pw_checkname(arg1, 0);
1218	}
1219
1220	while ((ch = getopt(argc, argv, args)) != -1) {
1221		switch (ch) {
1222		case 'C':
1223			cfg = optarg;
1224			break;
1225		case 'q':
1226			quiet = true;
1227			break;
1228		case 'n':
1229			name = pw_checkname(optarg, 0);
1230			break;
1231		case 'u':
1232			userid = optarg;
1233			break;
1234		case 'c':
1235			gecos = pw_checkname(optarg, 1);
1236			break;
1237		case 'd':
1238			homedir = optarg;
1239			break;
1240		case 'e':
1241			if (genconf)
1242			    cmdcnf->expire_days = validate_expire(optarg, ch);
1243			else
1244			    cmdcnf->expire_days = parse_date(now, optarg);
1245			break;
1246		case 'p':
1247			if (genconf)
1248			    cmdcnf->password_days = validate_expire(optarg, ch);
1249			else
1250			    cmdcnf->password_days = parse_date(now, optarg);
1251			break;
1252		case 'g':
1253			validate_grname(cmdcnf, optarg);
1254			grname = optarg;
1255			break;
1256		case 'G':
1257			split_groups(&cmdcnf->groups, optarg);
1258			break;
1259		case 'm':
1260			createhome = true;
1261			break;
1262		case 'M':
1263			cmdcnf->homemode = validate_mode(optarg);
1264			break;
1265		case 'k':
1266			walk = skel = optarg;
1267			if (*walk == '/')
1268				walk++;
1269			if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1270				errx(EX_OSFILE, "skeleton `%s' does not "
1271				    "exists", skel);
1272			if (!S_ISDIR(st.st_mode))
1273				errx(EX_OSFILE, "skeleton `%s' is not a "
1274				    "directory", skel);
1275			cmdcnf->dotdir = skel;
1276			break;
1277		case 's':
1278			cmdcnf->shell_default = optarg;
1279			break;
1280		case 'o':
1281			conf.checkduplicate = false;
1282			break;
1283		case 'L':
1284			cmdcnf->default_class = pw_checkname(optarg, 0);
1285			break;
1286		case 'i':
1287			groupid = optarg;
1288			break;
1289		case 'w':
1290			default_passwd = optarg;
1291			break;
1292		case 'H':
1293			if (fd != -1)
1294				errx(EX_USAGE, "'-h' and '-H' are mutually "
1295				    "exclusive options");
1296			fd = pw_checkfd(optarg);
1297			precrypted = true;
1298			if (fd == '-')
1299				errx(EX_USAGE, "-H expects a file descriptor");
1300			break;
1301		case 'h':
1302			if (fd != -1)
1303				errx(EX_USAGE, "'-h' and '-H' are mutually "
1304				    "exclusive options");
1305			fd = pw_checkfd(optarg);
1306			break;
1307		case 'D':
1308			genconf = true;
1309			break;
1310		case 'b':
1311			cmdcnf->home = optarg;
1312			break;
1313		case 'N':
1314			dryrun = true;
1315			break;
1316		case 'P':
1317			pretty = true;
1318			break;
1319		case 'y':
1320			cmdcnf->nispasswd = optarg;
1321			break;
1322		case 'Y':
1323			nis = true;
1324			break;
1325		}
1326	}
1327
1328	if (geteuid() != 0 && ! dryrun)
1329		errx(EX_NOPERM, "you must be root");
1330
1331	if (quiet)
1332		freopen(_PATH_DEVNULL, "w", stderr);
1333
1334	cnf = get_userconfig(cfg);
1335
1336	mix_config(cmdcnf, cnf);
1337	if (default_passwd)
1338		cmdcnf->default_password = passwd_val(default_passwd,
1339		    cnf->default_password);
1340	if (genconf) {
1341		if (name != NULL)
1342			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
1343		if (userid != NULL) {
1344			if ((p = strtok(userid, ", \t")) != NULL)
1345				cmdcnf->min_uid = pw_checkid(p, UID_MAX);
1346			if (cmdcnf->min_uid == 0)
1347				cmdcnf->min_uid = 1000;
1348			if ((p = strtok(NULL, " ,\t")) != NULL)
1349				cmdcnf->max_uid = pw_checkid(p, UID_MAX);
1350			if (cmdcnf->max_uid == 0)
1351				cmdcnf->max_uid = 32000;
1352		}
1353		if (groupid != NULL) {
1354			if ((p = strtok(groupid, ", \t")) != NULL)
1355				cmdcnf->min_gid = pw_checkid(p, GID_MAX);
1356			if (cmdcnf->min_gid == 0)
1357				cmdcnf->min_gid = 1000;
1358			if ((p = strtok(NULL, " ,\t")) != NULL)
1359				cmdcnf->max_gid = pw_checkid(p, GID_MAX);
1360			if (cmdcnf->max_gid == 0)
1361				cmdcnf->max_gid = 32000;
1362		}
1363		if (write_userconfig(cmdcnf, cfg))
1364			return (EXIT_SUCCESS);
1365		err(EX_IOERR, "config update");
1366	}
1367
1368	if (userid)
1369		id = pw_checkid(userid, UID_MAX);
1370	if (id < 0 && name == NULL)
1371		errx(EX_DATAERR, "user name or id required");
1372
1373	if (name == NULL)
1374		errx(EX_DATAERR, "login name required");
1375
1376	if (GETPWNAM(name) != NULL)
1377		errx(EX_DATAERR, "login name `%s' already exists", name);
1378
1379	if (!grname)
1380		grname = cmdcnf->default_group;
1381
1382	pwd = &fakeuser;
1383	pwd->pw_name = name;
1384	pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1385	pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1386	pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1387	    (gid_t) pwd->pw_uid, dryrun);
1388
1389	/* cmdcnf->password_days and cmdcnf->expire_days hold unixtime here */
1390	if (cmdcnf->password_days > 0)
1391		pwd->pw_change = cmdcnf->password_days;
1392	if (cmdcnf->expire_days > 0)
1393		pwd->pw_expire = cmdcnf->expire_days;
1394
1395	pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1396	pwd->pw_shell = pw_shellpolicy(cmdcnf);
1397	lc = login_getpwclass(pwd);
1398	if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1399		warn("setting crypt(3) format");
1400	login_close(lc);
1401	pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name, dryrun);
1402	if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1403		warnx("WARNING: new account `%s' has a uid of 0 "
1404		    "(superuser access!)", pwd->pw_name);
1405	if (gecos)
1406		pwd->pw_gecos = gecos;
1407
1408	if (fd != -1)
1409		pw_set_passwd(pwd, fd, precrypted, false);
1410
1411	if (dryrun)
1412		return (print_user(pwd, pretty, false));
1413
1414	if ((rc = addpwent(pwd)) != 0) {
1415		if (rc == -1)
1416			errx(EX_IOERR, "user '%s' already exists",
1417			    pwd->pw_name);
1418		else if (rc != 0)
1419			err(EX_IOERR, "passwd file update");
1420	}
1421	if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1422		printf("%s\n", cmdcnf->nispasswd);
1423		rc = addnispwent(cmdcnf->nispasswd, pwd);
1424		if (rc == -1)
1425			warnx("User '%s' already exists in NIS passwd",
1426			    pwd->pw_name);
1427		else if (rc != 0)
1428			warn("NIS passwd update");
1429		/* NOTE: we treat NIS-only update errors as non-fatal */
1430	}
1431
1432	if (cmdcnf->groups != NULL) {
1433		for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1434			grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1435			grp = gr_add(grp, pwd->pw_name);
1436			/*
1437			 * grp can only be NULL in 2 cases:
1438			 * - the new member is already a member
1439			 * - a problem with memory occurs
1440			 * in both cases we want to skip now.
1441			 */
1442			if (grp == NULL)
1443				continue;
1444			chggrent(grp->gr_name, grp);
1445			free(grp);
1446		}
1447	}
1448
1449	pwd = GETPWNAM(name);
1450	if (pwd == NULL)
1451		errx(EX_NOUSER, "user '%s' disappeared during update", name);
1452
1453	grp = GETGRGID(pwd->pw_gid);
1454	pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1455	       pwd->pw_name, (uintmax_t)pwd->pw_uid,
1456	    grp ? grp->gr_name : "unknown",
1457	       (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1458	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1459
1460	/*
1461	 * let's touch and chown the user's mail file. This is not
1462	 * strictly necessary under BSD with a 0755 maildir but it also
1463	 * doesn't hurt anything to create the empty mailfile
1464	 */
1465	if (PWALTDIR() != PWF_ALT) {
1466		snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1467		    pwd->pw_name);
1468		/* Preserve contents & mtime */
1469		close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1470		fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1471		    AT_SYMLINK_NOFOLLOW);
1472	}
1473
1474	/*
1475	 * Let's create and populate the user's home directory. Note
1476	 * that this also `works' for editing users if -m is used, but
1477	 * existing files will *not* be overwritten.
1478	 */
1479	if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1480	    *pwd->pw_dir == '/' && pwd->pw_dir[1])
1481		create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1482		    cmdcnf->homemode, false);
1483
1484	if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1485	    (fp = fopen(cnf->newmail, "r")) != NULL) {
1486		if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1487			warn("sendmail");
1488		else {
1489			fprintf(pfp, "From: root\n" "To: %s\n"
1490			    "Subject: Welcome!\n\n", pwd->pw_name);
1491			while (fgets(line, sizeof(line), fp) != NULL) {
1492				/* Do substitutions? */
1493				fputs(line, pfp);
1494			}
1495			pclose(pfp);
1496			pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1497			    pwd->pw_name, (uintmax_t)pwd->pw_uid);
1498		}
1499		fclose(fp);
1500	}
1501
1502	if (nis && nis_update() == 0)
1503		pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1504
1505	return (EXIT_SUCCESS);
1506}
1507
1508int
1509pw_user_mod(int argc, char **argv, char *arg1)
1510{
1511	struct userconf *cnf;
1512	struct passwd *pwd;
1513	struct group *grp;
1514	StringList *groups = NULL;
1515	char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1516	const char *cfg = NULL;
1517	char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1518	char *passwd, *class, *nispasswd;
1519	login_cap_t *lc;
1520	struct stat st;
1521	intmax_t id = -1;
1522	int ch, fd = -1;
1523	size_t i, j;
1524	bool quiet, createhome, pretty, dryrun, nis, edited;
1525	bool precrypted;
1526	mode_t homemode = 0;
1527	time_t expire_time, password_time, now;
1528
1529	expire_time = password_time = -1;
1530	gecos = homedir = grname = name = newname = skel = shell =NULL;
1531	passwd = NULL;
1532	class = nispasswd = NULL;
1533	quiet = createhome = pretty = dryrun = nis = precrypted = false;
1534	edited = false;
1535	now = time(NULL);
1536
1537	if (arg1 != NULL) {
1538		if (arg1[strspn(arg1, "0123456789")] == '\0')
1539			id = pw_checkid(arg1, UID_MAX);
1540		else
1541			name = arg1;
1542	}
1543
1544	while ((ch = getopt(argc, argv, args)) != -1) {
1545		switch (ch) {
1546		case 'C':
1547			cfg = optarg;
1548			break;
1549		case 'q':
1550			quiet = true;
1551			break;
1552		case 'n':
1553			name = optarg;
1554			break;
1555		case 'u':
1556			id = pw_checkid(optarg, UID_MAX);
1557			break;
1558		case 'c':
1559			gecos = pw_checkname(optarg, 1);
1560			break;
1561		case 'd':
1562			homedir = optarg;
1563			break;
1564		case 'e':
1565			expire_time = parse_date(now, optarg);
1566			break;
1567		case 'p':
1568			password_time = parse_date(now, optarg);
1569			break;
1570		case 'g':
1571			group_from_name_or_id(optarg);
1572			grname = optarg;
1573			break;
1574		case 'G':
1575			split_groups(&groups, optarg);
1576			break;
1577		case 'm':
1578			createhome = true;
1579			break;
1580		case 'M':
1581			homemode = validate_mode(optarg);
1582			break;
1583		case 'l':
1584			newname = optarg;
1585			break;
1586		case 'k':
1587			walk = skel = optarg;
1588			if (*walk == '/')
1589				walk++;
1590			if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1591				errx(EX_OSFILE, "skeleton `%s' does not "
1592				    "exists", skel);
1593			if (!S_ISDIR(st.st_mode))
1594				errx(EX_OSFILE, "skeleton `%s' is not a "
1595				    "directory", skel);
1596			break;
1597		case 's':
1598			shell = optarg;
1599			break;
1600		case 'w':
1601			passwd = optarg;
1602			break;
1603		case 'L':
1604			class = pw_checkname(optarg, 0);
1605			break;
1606		case 'H':
1607			if (fd != -1)
1608				errx(EX_USAGE, "'-h' and '-H' are mutually "
1609				    "exclusive options");
1610			fd = pw_checkfd(optarg);
1611			precrypted = true;
1612			if (fd == '-')
1613				errx(EX_USAGE, "-H expects a file descriptor");
1614			break;
1615		case 'h':
1616			if (fd != -1)
1617				errx(EX_USAGE, "'-h' and '-H' are mutually "
1618				    "exclusive options");
1619			fd = pw_checkfd(optarg);
1620			break;
1621		case 'N':
1622			dryrun = true;
1623			break;
1624		case 'P':
1625			pretty = true;
1626			break;
1627		case 'y':
1628			nispasswd = optarg;
1629			break;
1630		case 'Y':
1631			nis = true;
1632			break;
1633		}
1634	}
1635
1636	if (geteuid() != 0 && ! dryrun)
1637		errx(EX_NOPERM, "you must be root");
1638
1639	if (quiet)
1640		freopen(_PATH_DEVNULL, "w", stderr);
1641
1642	cnf = get_userconfig(cfg);
1643
1644	if (id < 0 && name == NULL)
1645		errx(EX_DATAERR, "username or id required");
1646
1647	pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1648	if (pwd == NULL) {
1649		if (name == NULL)
1650			errx(EX_NOUSER, "no such uid `%ju'",
1651			    (uintmax_t) id);
1652		errx(EX_NOUSER, "no such user `%s'", name);
1653	}
1654
1655	if (name == NULL)
1656		name = pwd->pw_name;
1657
1658	if (nis && nispasswd == NULL)
1659		nispasswd = cnf->nispasswd;
1660
1661	if (PWF._altdir == PWF_REGULAR &&
1662	    ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
1663		if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
1664			if (!nis && nispasswd && *nispasswd != '/')
1665				errx(EX_NOUSER, "Cannot modify NIS user `%s'",
1666				    name);
1667		} else {
1668			errx(EX_NOUSER, "Cannot modify non local user `%s'",
1669			    name);
1670		}
1671	}
1672
1673	if (newname) {
1674		if (strcmp(pwd->pw_name, "root") == 0)
1675			errx(EX_DATAERR, "can't rename `root' account");
1676		if (strcmp(pwd->pw_name, newname) != 0) {
1677			pwd->pw_name = pw_checkname(newname, 0);
1678			edited = true;
1679		}
1680	}
1681
1682	if (id >= 0 && pwd->pw_uid != id) {
1683		pwd->pw_uid = id;
1684		edited = true;
1685		if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
1686			errx(EX_DATAERR, "can't change uid of `root' account");
1687		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1688			warnx("WARNING: account `%s' will have a uid of 0 "
1689			    "(superuser access!)", pwd->pw_name);
1690	}
1691
1692	if (grname && pwd->pw_uid != 0) {
1693		grp = GETGRNAM(grname);
1694		if (grp == NULL)
1695			grp = GETGRGID(pw_checkid(grname, GID_MAX));
1696		if (grp->gr_gid != pwd->pw_gid) {
1697			pwd->pw_gid = grp->gr_gid;
1698			edited = true;
1699		}
1700	}
1701
1702
1703	if (password_time >= 0 && pwd->pw_change != password_time) {
1704		pwd->pw_change = password_time;
1705		edited = true;
1706	}
1707
1708	if (expire_time >= 0 && pwd->pw_expire != expire_time) {
1709		pwd->pw_expire = expire_time;
1710		edited = true;
1711	}
1712
1713	if (shell) {
1714		shell = shell_path(cnf->shelldir, cnf->shells, shell);
1715		if (shell == NULL)
1716			shell = "";
1717		if (strcmp(shell, pwd->pw_shell) != 0) {
1718			pwd->pw_shell = shell;
1719			edited = true;
1720		}
1721	}
1722
1723	if (class && strcmp(pwd->pw_class, class) != 0) {
1724		pwd->pw_class = class;
1725		edited = true;
1726	}
1727
1728	if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1729		pwd->pw_dir = homedir;
1730		edited = true;
1731		if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1732			if (!createhome)
1733				warnx("WARNING: home `%s' does not exist",
1734				    pwd->pw_dir);
1735		} else if (!S_ISDIR(st.st_mode)) {
1736			warnx("WARNING: home `%s' is not a directory",
1737			    pwd->pw_dir);
1738		}
1739	}
1740
1741	if (passwd && conf.fd == -1) {
1742		lc = login_getpwclass(pwd);
1743		if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1744			warn("setting crypt(3) format");
1745		login_close(lc);
1746		cnf->default_password = passwd_val(passwd,
1747		    cnf->default_password);
1748		pwd->pw_passwd = pw_password(cnf, pwd->pw_name, dryrun);
1749		edited = true;
1750	}
1751
1752	if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1753		pwd->pw_gecos = gecos;
1754		edited = true;
1755	}
1756
1757	if (fd != -1)
1758		edited = pw_set_passwd(pwd, fd, precrypted, true);
1759
1760	if (dryrun)
1761		return (print_user(pwd, pretty, false));
1762
1763	if (edited) /* Only updated this if required */
1764		perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1765	/* Now perform the needed changes concern groups */
1766	if (groups != NULL) {
1767		/* Delete User from groups using old name */
1768		SETGRENT();
1769		while ((grp = GETGRENT()) != NULL) {
1770			if (grp->gr_mem == NULL)
1771				continue;
1772			for (i = 0; grp->gr_mem[i] != NULL; i++) {
1773				if (strcmp(grp->gr_mem[i] , name) != 0)
1774					continue;
1775				for (j = i; grp->gr_mem[j] != NULL ; j++)
1776					grp->gr_mem[j] = grp->gr_mem[j+1];
1777				chggrent(grp->gr_name, grp);
1778				break;
1779			}
1780		}
1781		ENDGRENT();
1782		/* Add the user to the needed groups */
1783		for (i = 0; i < groups->sl_cur; i++) {
1784			grp = GETGRNAM(groups->sl_str[i]);
1785			grp = gr_add(grp, pwd->pw_name);
1786			if (grp == NULL)
1787				continue;
1788			chggrent(grp->gr_name, grp);
1789			free(grp);
1790		}
1791	}
1792	/* In case of rename we need to walk over the different groups */
1793	if (newname) {
1794		SETGRENT();
1795		while ((grp = GETGRENT()) != NULL) {
1796			if (grp->gr_mem == NULL)
1797				continue;
1798			for (i = 0; grp->gr_mem[i] != NULL; i++) {
1799				if (strcmp(grp->gr_mem[i], name) != 0)
1800					continue;
1801				grp->gr_mem[i] = newname;
1802				chggrent(grp->gr_name, grp);
1803				break;
1804			}
1805		}
1806	}
1807
1808	/* go get a current version of pwd */
1809	if (newname)
1810		name = newname;
1811	pwd = GETPWNAM(name);
1812	if (pwd == NULL)
1813		errx(EX_NOUSER, "user '%s' disappeared during update", name);
1814	grp = GETGRGID(pwd->pw_gid);
1815	pw_log(cnf, M_UPDATE, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1816	    pwd->pw_name, (uintmax_t)pwd->pw_uid,
1817	    grp ? grp->gr_name : "unknown",
1818	    (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1819	    pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1820
1821	/*
1822	 * Let's create and populate the user's home directory. Note
1823	 * that this also `works' for editing users if -m is used, but
1824	 * existing files will *not* be overwritten.
1825	 */
1826	if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1827	    *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1828		if (!skel)
1829			skel = cnf->dotdir;
1830		if (homemode == 0)
1831			homemode = cnf->homemode;
1832		create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1833	}
1834
1835	if (nis && nis_update() == 0)
1836		pw_log(cnf, M_UPDATE, W_USER, "NIS maps updated");
1837
1838	return (EXIT_SUCCESS);
1839}
1840