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