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