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