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