xref: /freebsd/lib/libutil/pw_util.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*--
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 2002 Networks Associates Technology, Inc.
7  * All rights reserved.
8  *
9  * Portions of this software were developed for the FreeBSD Project by
10  * ThinkSec AS and NAI Labs, the Security Research Division of Network
11  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
12  * ("CBOSS"), as part of the DARPA CHATS research program.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 __SCCSID("@(#)pw_util.c	8.3 (Berkeley) 4/2/94");
41 
42 /*
43  * This file is used by all the "password" programs; vipw(8), chpass(1),
44  * and passwd(1).
45  */
46 
47 #include <sys/param.h>
48 #include <sys/errno.h>
49 #include <sys/time.h>
50 #include <sys/resource.h>
51 #include <sys/stat.h>
52 #include <sys/wait.h>
53 
54 #include <ctype.h>
55 #include <err.h>
56 #include <fcntl.h>
57 #include <inttypes.h>
58 #include <paths.h>
59 #include <pwd.h>
60 #include <signal.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 
66 #include "libutil.h"
67 
68 static pid_t editpid = -1;
69 static int lockfd = -1;
70 static char masterpasswd[PATH_MAX];
71 static char passwd_dir[PATH_MAX];
72 static char tempname[PATH_MAX];
73 static int initialized;
74 
75 #if 0
76 void
77 pw_cont(int sig)
78 {
79 
80 	if (editpid != -1)
81 		kill(editpid, sig);
82 }
83 #endif
84 
85 /*
86  * Initialize statics and set limits, signals & umask to try to avoid
87  * interruptions, crashes etc. that might expose passord data.
88  */
89 int
90 pw_init(const char *dir, const char *master)
91 {
92 #if 0
93 	struct rlimit rlim;
94 #endif
95 
96 	if (dir == NULL) {
97 		strcpy(passwd_dir, _PATH_ETC);
98 	} else {
99 		if (strlen(dir) >= sizeof(passwd_dir)) {
100 			errno = ENAMETOOLONG;
101 			return (-1);
102 		}
103 		strcpy(passwd_dir, dir);
104 	}
105 
106 	if (master == NULL) {
107 		if (dir == NULL) {
108 			strcpy(masterpasswd, _PATH_MASTERPASSWD);
109 		} else if (snprintf(masterpasswd, sizeof(masterpasswd), "%s/%s",
110 		    passwd_dir, _MASTERPASSWD) > (int)sizeof(masterpasswd)) {
111 			errno = ENAMETOOLONG;
112 			return (-1);
113 		}
114 	} else {
115 		if (strlen(master) >= sizeof(masterpasswd)) {
116 			errno = ENAMETOOLONG;
117 			return (-1);
118 		}
119 		strcpy(masterpasswd, master);
120 	}
121 
122 	/*
123 	 * The code that follows is extremely disruptive to the calling
124 	 * process, and is therefore disabled until someone can conceive
125 	 * of a realistic scenario where it would fend off a compromise.
126 	 * Race conditions concerning the temporary files can be guarded
127 	 * against in other ways than masking signals (by checking stat(2)
128 	 * results after creation).
129 	 */
130 #if 0
131 	/* Unlimited resource limits. */
132 	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
133 	(void)setrlimit(RLIMIT_CPU, &rlim);
134 	(void)setrlimit(RLIMIT_FSIZE, &rlim);
135 	(void)setrlimit(RLIMIT_STACK, &rlim);
136 	(void)setrlimit(RLIMIT_DATA, &rlim);
137 	(void)setrlimit(RLIMIT_RSS, &rlim);
138 
139 	/* Don't drop core (not really necessary, but GP's). */
140 	rlim.rlim_cur = rlim.rlim_max = 0;
141 	(void)setrlimit(RLIMIT_CORE, &rlim);
142 
143 	/* Turn off signals. */
144 	(void)signal(SIGALRM, SIG_IGN);
145 	(void)signal(SIGHUP, SIG_IGN);
146 	(void)signal(SIGINT, SIG_IGN);
147 	(void)signal(SIGPIPE, SIG_IGN);
148 	(void)signal(SIGQUIT, SIG_IGN);
149 	(void)signal(SIGTERM, SIG_IGN);
150 	(void)signal(SIGCONT, pw_cont);
151 
152 	/* Create with exact permissions. */
153 	(void)umask(0);
154 #endif
155 	initialized = 1;
156 	return (0);
157 }
158 
159 /*
160  * Lock the master password file.
161  */
162 int
163 pw_lock(void)
164 {
165 
166 	if (*masterpasswd == '\0')
167 		return (-1);
168 
169 	/*
170 	 * If the master password file doesn't exist, the system is hosed.
171 	 * Might as well try to build one.  Set the close-on-exec bit so
172 	 * that users can't get at the encrypted passwords while editing.
173 	 * Open should allow flock'ing the file; see 4.4BSD.	XXX
174 	 */
175 	for (;;) {
176 		struct stat st;
177 
178 		lockfd = flopen(masterpasswd, O_RDONLY|O_NONBLOCK|O_CLOEXEC, 0);
179 		if (lockfd == -1) {
180 			if (errno == EWOULDBLOCK) {
181 				errx(1, "the password db file is busy");
182 			} else {
183 				err(1, "could not lock the passwd file");
184 			}
185 		}
186 
187 		/*
188 		 * If the password file was replaced while we were trying to
189 		 * get the lock, our hardlink count will be 0 and we have to
190 		 * close and retry.
191 		 */
192 		if (fstat(lockfd, &st) == -1)
193 			err(1, "fstat() failed");
194 		if (st.st_nlink != 0)
195 			break;
196 		close(lockfd);
197 		lockfd = -1;
198 	}
199 	return (lockfd);
200 }
201 
202 /*
203  * Create and open a presumably safe temp file for editing the password
204  * data, and copy the master password file into it.
205  */
206 int
207 pw_tmp(int mfd)
208 {
209 	char buf[8192];
210 	ssize_t nr;
211 	const char *p;
212 	int tfd;
213 
214 	if (*masterpasswd == '\0')
215 		return (-1);
216 	if ((p = strrchr(masterpasswd, '/')))
217 		++p;
218 	else
219 		p = masterpasswd;
220 	if (snprintf(tempname, sizeof(tempname), "%.*spw.XXXXXX",
221 		(int)(p - masterpasswd), masterpasswd) >= (int)sizeof(tempname)) {
222 		errno = ENAMETOOLONG;
223 		return (-1);
224 	}
225 	if ((tfd = mkostemp(tempname, 0)) == -1)
226 		return (-1);
227 	if (mfd != -1) {
228 		while ((nr = read(mfd, buf, sizeof(buf))) > 0)
229 			if (write(tfd, buf, (size_t)nr) != nr)
230 				break;
231 		if (nr != 0) {
232 			unlink(tempname);
233 			*tempname = '\0';
234 			close(tfd);
235 			return (-1);
236 		}
237 	}
238 	return (tfd);
239 }
240 
241 /*
242  * Regenerate the password database.
243  */
244 int
245 pw_mkdb(const char *user)
246 {
247 	int pstat;
248 	pid_t pid;
249 
250 	(void)fflush(stderr);
251 	switch ((pid = fork())) {
252 	case -1:
253 		return (-1);
254 	case 0:
255 		/* child */
256 		if (user == NULL)
257 			execl(_PATH_PWD_MKDB, "pwd_mkdb", "-p",
258 			    "-d", passwd_dir, tempname, (char *)NULL);
259 		else
260 			execl(_PATH_PWD_MKDB, "pwd_mkdb", "-p",
261 			    "-d", passwd_dir, "-u", user, tempname,
262 			    (char *)NULL);
263 		_exit(1);
264 		/* NOTREACHED */
265 	default:
266 		/* parent */
267 		break;
268 	}
269 	if (waitpid(pid, &pstat, 0) == -1)
270 		return (-1);
271 	if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0)
272 		return (0);
273 	errno = 0;
274 	return (-1);
275 }
276 
277 /*
278  * Edit the temp file.  Return -1 on error, >0 if the file was modified, 0
279  * if it was not.
280  */
281 int
282 pw_edit(int notsetuid)
283 {
284 	struct sigaction sa, sa_int, sa_quit;
285 	sigset_t oldsigset, nsigset;
286 	struct stat st1, st2;
287 	const char *editor;
288 	int pstat;
289 
290 	if ((editor = getenv("EDITOR")) == NULL)
291 		editor = _PATH_VI;
292 	if (stat(tempname, &st1) == -1)
293 		return (-1);
294 	sa.sa_handler = SIG_IGN;
295 	sigemptyset(&sa.sa_mask);
296 	sa.sa_flags = 0;
297 	sigaction(SIGINT, &sa, &sa_int);
298 	sigaction(SIGQUIT, &sa, &sa_quit);
299 	sigemptyset(&nsigset);
300 	sigaddset(&nsigset, SIGCHLD);
301 	sigprocmask(SIG_BLOCK, &nsigset, &oldsigset);
302 	switch ((editpid = fork())) {
303 	case -1:
304 		return (-1);
305 	case 0:
306 		sigaction(SIGINT, &sa_int, NULL);
307 		sigaction(SIGQUIT, &sa_quit, NULL);
308 		sigprocmask(SIG_SETMASK, &oldsigset, NULL);
309 		if (notsetuid) {
310 			if (setgid(getgid()) == -1)
311 				err(1, "setgid");
312 			if (setuid(getuid()) == -1)
313 				err(1, "setuid");
314 		}
315 		execlp(editor, editor, tempname, (char *)NULL);
316 		err(1, "%s", editor);
317 	default:
318 		/* parent */
319 		break;
320 	}
321 	for (;;) {
322 		if (waitpid(editpid, &pstat, WUNTRACED) == -1) {
323 			if (errno == EINTR)
324 				continue;
325 			unlink(tempname);
326 			editpid = -1;
327 			break;
328 		} else if (WIFSTOPPED(pstat)) {
329 			raise(WSTOPSIG(pstat));
330 		} else if (WIFEXITED(pstat)) {
331 			if (WEXITSTATUS(pstat) != 0)
332 				errx(1, "\"%s\" exited with status %d", editor, WEXITSTATUS(pstat));
333 			editpid = -1;
334 			break;
335 		} else {
336 			unlink(tempname);
337 			editpid = -1;
338 			break;
339 		}
340 	}
341 	sigaction(SIGINT, &sa_int, NULL);
342 	sigaction(SIGQUIT, &sa_quit, NULL);
343 	sigprocmask(SIG_SETMASK, &oldsigset, NULL);
344 	if (stat(tempname, &st2) == -1)
345 		return (-1);
346 	return (st1.st_mtim.tv_sec != st2.st_mtim.tv_sec ||
347 	    st1.st_mtim.tv_nsec != st2.st_mtim.tv_nsec);
348 }
349 
350 /*
351  * Clean up.  Preserve errno for the caller's convenience.
352  */
353 void
354 pw_fini(void)
355 {
356 	int serrno, status;
357 
358 	if (!initialized)
359 		return;
360 	initialized = 0;
361 	serrno = errno;
362 	if (editpid != -1) {
363 		kill(editpid, SIGTERM);
364 		kill(editpid, SIGCONT);
365 		waitpid(editpid, &status, 0);
366 		editpid = -1;
367 	}
368 	if (*tempname != '\0') {
369 		unlink(tempname);
370 		*tempname = '\0';
371 	}
372 	if (lockfd != -1)
373 		close(lockfd);
374 	errno = serrno;
375 }
376 
377 /*
378  * Compares two struct pwds.
379  */
380 int
381 pw_equal(const struct passwd *pw1, const struct passwd *pw2)
382 {
383 	return (strcmp(pw1->pw_name, pw2->pw_name) == 0 &&
384 	    pw1->pw_uid == pw2->pw_uid &&
385 	    pw1->pw_gid == pw2->pw_gid &&
386 	    strcmp(pw1->pw_class, pw2->pw_class) == 0 &&
387 	    pw1->pw_change == pw2->pw_change &&
388 	    pw1->pw_expire == pw2->pw_expire &&
389 	    strcmp(pw1->pw_gecos, pw2->pw_gecos) == 0 &&
390 	    strcmp(pw1->pw_dir, pw2->pw_dir) == 0 &&
391 	    strcmp(pw1->pw_shell, pw2->pw_shell) == 0);
392 }
393 
394 /*
395  * Make a passwd line out of a struct passwd.
396  */
397 char *
398 pw_make(const struct passwd *pw)
399 {
400 	char *line;
401 
402 	asprintf(&line, "%s:%s:%ju:%ju:%s:%ju:%ju:%s:%s:%s", pw->pw_name,
403 	    pw->pw_passwd, (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid,
404 	    pw->pw_class, (uintmax_t)pw->pw_change, (uintmax_t)pw->pw_expire,
405 	    pw->pw_gecos, pw->pw_dir, pw->pw_shell);
406 	return (line);
407 }
408 
409 /*
410  * Make a passwd line (in v7 format) out of a struct passwd
411  */
412 char *
413 pw_make_v7(const struct passwd *pw)
414 {
415 	char *line;
416 
417 	asprintf(&line, "%s:*:%ju:%ju:%s:%s:%s", pw->pw_name,
418 	    (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid,
419 	    pw->pw_gecos, pw->pw_dir, pw->pw_shell);
420 	return (line);
421 }
422 
423 /*
424  * Copy password file from one descriptor to another, replacing, deleting
425  * or adding a single record on the way.
426  */
427 int
428 pw_copy(int ffd, int tfd, const struct passwd *pw, struct passwd *old_pw)
429 {
430 	char *buf, *end, *line, *p, *q, *r, *tmp;
431 	struct passwd *fpw;
432 	const struct passwd *spw;
433 	size_t len, size;
434 	int eof, readlen;
435 	char t;
436 
437 	if (old_pw == NULL && pw == NULL)
438 			return (-1);
439 
440 	spw = old_pw;
441 	/* deleting a user */
442 	if (pw == NULL) {
443 		line = NULL;
444 	} else {
445 		if ((line = pw_make(pw)) == NULL)
446 			return (-1);
447 	}
448 
449 	/* adding a user */
450 	if (spw == NULL)
451 		spw = pw;
452 
453 	/* initialize the buffer */
454 	if ((buf = malloc(size = 1024)) == NULL)
455 		goto err;
456 
457 	eof = 0;
458 	len = 0;
459 	p = q = end = buf;
460 	for (;;) {
461 		/* find the end of the current line */
462 		for (p = q; q < end && *q != '\0'; ++q)
463 			if (*q == '\n')
464 				break;
465 
466 		/* if we don't have a complete line, fill up the buffer */
467 		if (q >= end) {
468 			if (eof)
469 				break;
470 			while ((size_t)(q - p) >= size) {
471 				if ((tmp = reallocarray(buf, 2, size)) == NULL) {
472 					warnx("passwd line too long");
473 					goto err;
474 				}
475 				p = tmp + (p - buf);
476 				q = tmp + (q - buf);
477 				end = tmp + (end - buf);
478 				buf = tmp;
479 				size = size * 2;
480 			}
481 			if (p < end) {
482 				q = memmove(buf, p, end - p);
483 				end -= p - buf;
484 			} else {
485 				p = q = end = buf;
486 			}
487 			readlen = read(ffd, end, size - (end - buf));
488 			if (readlen == -1)
489 				goto err;
490 			else
491 				len = (size_t)readlen;
492 			if (len == 0 && p == buf)
493 				break;
494 			end += len;
495 			len = end - buf;
496 			if (len < size) {
497 				eof = 1;
498 				if (len > 0 && buf[len - 1] != '\n')
499 					++len, *end++ = '\n';
500 			}
501 			continue;
502 		}
503 
504 		/* is it a blank line or a comment? */
505 		for (r = p; r < q && isspace(*r); ++r)
506 			/* nothing */ ;
507 		if (r == q || *r == '#') {
508 			/* yep */
509 			if (write(tfd, p, q - p + 1) != q - p + 1)
510 				goto err;
511 			++q;
512 			continue;
513 		}
514 
515 		/* is it the one we're looking for? */
516 
517 		t = *q;
518 		*q = '\0';
519 
520 		fpw = pw_scan(r, PWSCAN_MASTER);
521 
522 		/*
523 		 * fpw is either the struct passwd for the current line,
524 		 * or NULL if the line is malformed.
525 		 */
526 
527 		*q = t;
528 		if (fpw == NULL || strcmp(fpw->pw_name, spw->pw_name) != 0) {
529 			/* nope */
530 			if (fpw != NULL)
531 				free(fpw);
532 			if (write(tfd, p, q - p + 1) != q - p + 1)
533 				goto err;
534 			++q;
535 			continue;
536 		}
537 		if (old_pw && !pw_equal(fpw, old_pw)) {
538 			warnx("entry inconsistent");
539 			free(fpw);
540 			errno = EINVAL; /* hack */
541 			goto err;
542 		}
543 		free(fpw);
544 
545 		/* it is, replace or remove it */
546 		if (line != NULL) {
547 			len = strlen(line);
548 			if (write(tfd, line, len) != (int)len)
549 				goto err;
550 		} else {
551 			/* when removed, avoid the \n */
552 			q++;
553 		}
554 		/* we're done, just copy the rest over */
555 		for (;;) {
556 			if (write(tfd, q, end - q) != end - q)
557 				goto err;
558 			q = buf;
559 			readlen = read(ffd, buf, size);
560 			if (readlen == 0)
561 				break;
562 			else
563 				len = (size_t)readlen;
564 			if (readlen == -1)
565 				goto err;
566 			end = buf + len;
567 		}
568 		goto done;
569 	}
570 
571 	/* if we got here, we didn't find the old entry */
572 	if (line == NULL) {
573 		errno = ENOENT;
574 		goto err;
575 	}
576 	len = strlen(line);
577 	if ((size_t)write(tfd, line, len) != len ||
578 	    write(tfd, "\n", 1) != 1)
579 		goto err;
580  done:
581 	free(line);
582 	free(buf);
583 	return (0);
584  err:
585 	free(line);
586 	free(buf);
587 	return (-1);
588 }
589 
590 /*
591  * Return the current value of tempname.
592  */
593 const char *
594 pw_tempname(void)
595 {
596 
597 	return (tempname);
598 }
599 
600 /*
601  * Duplicate a struct passwd.
602  */
603 struct passwd *
604 pw_dup(const struct passwd *pw)
605 {
606 	char *dst;
607 	struct passwd *npw;
608 	ssize_t len;
609 
610 	len = sizeof(*npw);
611 	if (pw->pw_name != NULL)
612 		len += strlen(pw->pw_name) + 1;
613 	if (pw->pw_passwd != NULL)
614 		len += strlen(pw->pw_passwd) + 1;
615 	if (pw->pw_class != NULL)
616 		len += strlen(pw->pw_class) + 1;
617 	if (pw->pw_gecos != NULL)
618 		len += strlen(pw->pw_gecos) + 1;
619 	if (pw->pw_dir != NULL)
620 		len += strlen(pw->pw_dir) + 1;
621 	if (pw->pw_shell != NULL)
622 		len += strlen(pw->pw_shell) + 1;
623 	if ((npw = malloc((size_t)len)) == NULL)
624 		return (NULL);
625 	memcpy(npw, pw, sizeof(*npw));
626 	dst = (char *)npw + sizeof(*npw);
627 	if (pw->pw_name != NULL) {
628 		npw->pw_name = dst;
629 		dst = stpcpy(npw->pw_name, pw->pw_name) + 1;
630 	}
631 	if (pw->pw_passwd != NULL) {
632 		npw->pw_passwd = dst;
633 		dst = stpcpy(npw->pw_passwd, pw->pw_passwd) + 1;
634 	}
635 	if (pw->pw_class != NULL) {
636 		npw->pw_class = dst;
637 		dst = stpcpy(npw->pw_class, pw->pw_class) + 1;
638 	}
639 	if (pw->pw_gecos != NULL) {
640 		npw->pw_gecos = dst;
641 		dst = stpcpy(npw->pw_gecos, pw->pw_gecos) + 1;
642 	}
643 	if (pw->pw_dir != NULL) {
644 		npw->pw_dir = dst;
645 		dst = stpcpy(npw->pw_dir, pw->pw_dir) + 1;
646 	}
647 	if (pw->pw_shell != NULL) {
648 		npw->pw_shell = dst;
649 		dst = stpcpy(npw->pw_shell, pw->pw_shell) + 1;
650 	}
651 	return (npw);
652 }
653 
654 #include "pw_scan.h"
655 
656 /*
657  * Wrapper around some internal libc functions.
658  */
659 
660 void
661 pw_initpwd(struct passwd *pw)
662 {
663 
664 	__pw_initpwd(pw);
665 }
666 
667 struct passwd *
668 pw_scan(const char *line, int flags)
669 {
670 	struct passwd pw, *ret;
671 	char *bp;
672 
673 	if ((bp = strdup(line)) == NULL)
674 		return (NULL);
675 	__pw_initpwd(&pw);
676 	if (!__pw_scan(bp, &pw, flags)) {
677 		free(bp);
678 		return (NULL);
679 	}
680 	ret = pw_dup(&pw);
681 	free(bp);
682 	return (ret);
683 }
684