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