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