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