xref: /dragonfly/lib/libutil/pw_util.c (revision 36a3d1d6)
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  * @(#)pw_util.c	8.3 (Berkeley) 4/2/94
37  * $FreeBSD: src/lib/libutil/pw_util.c,v 1.38 2007/01/09 01:02:05 imp Exp $
38  * $DragonFly: src/lib/libutil/pw_util.c,v 1.2 2007/12/30 13:44:33 matthias Exp $
39  */
40 
41 /*
42  * This file is used by all the "password" programs; vipw(8), chpass(1),
43  * and passwd(1).
44  */
45 
46 #include <sys/param.h>
47 #include <sys/errno.h>
48 #include <sys/time.h>
49 #include <sys/resource.h>
50 #include <sys/stat.h>
51 #include <sys/wait.h>
52 
53 #include <ctype.h>
54 #include <err.h>
55 #include <fcntl.h>
56 #include <inttypes.h>
57 #include <libgen.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 = open(masterpasswd, O_RDONLY, 0);
179 		if (lockfd < 0 || fcntl(lockfd, F_SETFD, 1) == -1)
180 			err(1, "%s", masterpasswd);
181 		/* XXX vulnerable to race conditions */
182 		if (flock(lockfd, LOCK_EX|LOCK_NB) == -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 = mkstemp(tempname)) == -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, NULL);
262 		else
263 			execl(_PATH_PWD_MKDB, "pwd_mkdb", "-p",
264 			    "-d", passwd_dir, "-u", user, tempname,
265 			    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, sigset;
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(&sigset);
303 	sigaddset(&sigset, SIGCHLD);
304 	sigprocmask(SIG_BLOCK, &sigset, &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 			setgid(getgid());
314 			setuid(getuid());
315 		}
316 		errno = 0;
317 		execlp(editor, basename(editor), tempname, 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_mtime != st2.st_mtime);
347 }
348 
349 /*
350  * Clean up.  Preserve errno for the caller's convenience.
351  */
352 void
353 pw_fini(void)
354 {
355 	int serrno, status;
356 
357 	if (!initialized)
358 		return;
359 	initialized = 0;
360 	serrno = errno;
361 	if (editpid != -1) {
362 		kill(editpid, SIGTERM);
363 		kill(editpid, SIGCONT);
364 		waitpid(editpid, &status, 0);
365 		editpid = -1;
366 	}
367 	if (*tempname != '\0') {
368 		unlink(tempname);
369 		*tempname = '\0';
370 	}
371 	if (lockfd != -1)
372 		close(lockfd);
373 	errno = serrno;
374 }
375 
376 /*
377  * Compares two struct pwds.
378  */
379 int
380 pw_equal(const struct passwd *pw1, const struct passwd *pw2)
381 {
382 	return (strcmp(pw1->pw_name, pw2->pw_name) == 0 &&
383 	    pw1->pw_uid == pw2->pw_uid &&
384 	    pw1->pw_gid == pw2->pw_gid &&
385 	    strcmp(pw1->pw_class, pw2->pw_class) == 0 &&
386 	    pw1->pw_change == pw2->pw_change &&
387 	    pw1->pw_expire == pw2->pw_expire &&
388 	    strcmp(pw1->pw_gecos, pw2->pw_gecos) == 0 &&
389 	    strcmp(pw1->pw_dir, pw2->pw_dir) == 0 &&
390 	    strcmp(pw1->pw_shell, pw2->pw_shell) == 0);
391 }
392 
393 /*
394  * Make a passwd line out of a struct passwd.
395  */
396 char *
397 pw_make(const struct passwd *pw)
398 {
399 	char *line;
400 
401 	asprintf(&line, "%s:%s:%ju:%ju:%s:%ju:%ju:%s:%s:%s", pw->pw_name,
402 	    pw->pw_passwd, (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid,
403 	    pw->pw_class, (uintmax_t)pw->pw_change, (uintmax_t)pw->pw_expire,
404 	    pw->pw_gecos, pw->pw_dir, pw->pw_shell);
405 	return line;
406 }
407 
408 /*
409  * Copy password file from one descriptor to another, replacing or adding
410  * a single record on the way.
411  */
412 int
413 pw_copy(int ffd, int tfd, const struct passwd *pw, struct passwd *old_pw)
414 {
415 	char buf[8192], *end, *line, *p, *q, *r, t;
416 	struct passwd *fpw;
417 	size_t len;
418 	int eof, readlen;
419 
420 	if ((line = pw_make(pw)) == NULL)
421 		return (-1);
422 
423 	eof = 0;
424 	q = end = buf;
425 	for (;;) {
426 		/* find the end of the current line */
427 		for (p = q; q < end && *q != '\0'; ++q)
428 			if (*q == '\n')
429 				break;
430 
431 		/* if we don't have a complete line, fill up the buffer */
432 		if (q >= end) {
433 			if (eof)
434 				break;
435 			if ((size_t)(q - p) >= sizeof(buf)) {
436 				warnx("passwd line too long");
437 				errno = EINVAL; /* hack */
438 				goto err;
439 			}
440 			if (p < end) {
441 				q = memmove(buf, p, end - p);
442 				end -= p - buf;
443 			} else {
444 				p = q = end = buf;
445 			}
446 			readlen = read(ffd, end, sizeof(buf) - (end - buf));
447 			if (readlen == -1)
448 				goto err;
449 			else
450 				len = (size_t)readlen;
451 			if (len == 0 && p == buf)
452 				break;
453 			end += len;
454 			len = end - buf;
455 			if (len < (ssize_t)sizeof(buf)) {
456 				eof = 1;
457 				if (len > 0 && buf[len - 1] != '\n')
458 					*end++ = '\n';
459 			}
460 			continue;
461 		}
462 
463 		/* is it a blank line or a comment? */
464 		for (r = p; r < q && isspace(*r); ++r)
465 			/* nothing */ ;
466 		if (r == q || *r == '#') {
467 			/* yep */
468 			if (write(tfd, p, q - p + 1) != q - p + 1)
469 				goto err;
470 			++q;
471 			continue;
472 		}
473 
474 		/* is it the one we're looking for? */
475 
476 		t = *q;
477 		*q = '\0';
478 
479 		fpw = pw_scan(r, PWSCAN_MASTER);
480 
481 		/*
482 		 * fpw is either the struct passwd for the current line,
483 		 * or NULL if the line is malformed.
484 		 */
485 
486 		*q = t;
487 		if (fpw == NULL || strcmp(fpw->pw_name, pw->pw_name) != 0) {
488 			/* nope */
489 			if (fpw != NULL)
490 				free(fpw);
491 			if (write(tfd, p, q - p + 1) != q - p + 1)
492 				goto err;
493 			++q;
494 			continue;
495 		}
496 		if (old_pw && !pw_equal(fpw, old_pw)) {
497 			warnx("entry inconsistent");
498 			free(fpw);
499 			errno = EINVAL; /* hack */
500 			goto err;
501 		}
502 		free(fpw);
503 
504 		/* it is, replace it */
505 		len = strlen(line);
506 		if (write(tfd, line, len) != (int)len)
507 			goto err;
508 
509 		/* we're done, just copy the rest over */
510 		for (;;) {
511 			if (write(tfd, q, end - q) != end - q)
512 				goto err;
513 			q = buf;
514 			readlen = read(ffd, buf, sizeof(buf));
515 			if (readlen == 0)
516 				break;
517 			else
518 				len = (size_t)readlen;
519 			if (readlen == -1)
520 				goto err;
521 			end = buf + len;
522 		}
523 		goto done;
524 	}
525 
526 	/* if we got here, we have a new entry */
527 	len = strlen(line);
528 	if ((size_t)write(tfd, line, len) != len ||
529 	    write(tfd, "\n", 1) != 1)
530 		goto err;
531  done:
532 	free(line);
533 	return (0);
534  err:
535 	free(line);
536 	return (-1);
537 }
538 
539 /*
540  * Return the current value of tempname.
541  */
542 const char *
543 pw_tempname(void)
544 {
545 
546 	return (tempname);
547 }
548 
549 /*
550  * Duplicate a struct passwd.
551  */
552 struct passwd *
553 pw_dup(const struct passwd *pw)
554 {
555 	struct passwd *npw;
556 	ssize_t len;
557 
558 	len = sizeof(*npw) +
559 	    (pw->pw_name ? strlen(pw->pw_name) + 1 : 0) +
560 	    (pw->pw_passwd ? strlen(pw->pw_passwd) + 1 : 0) +
561 	    (pw->pw_class ? strlen(pw->pw_class) + 1 : 0) +
562 	    (pw->pw_gecos ? strlen(pw->pw_gecos) + 1 : 0) +
563 	    (pw->pw_dir ? strlen(pw->pw_dir) + 1 : 0) +
564 	    (pw->pw_shell ? strlen(pw->pw_shell) + 1 : 0);
565 	if ((npw = malloc((size_t)len)) == NULL)
566 		return (NULL);
567 	memcpy(npw, pw, sizeof(*npw));
568 	len = sizeof(*npw);
569 	if (pw->pw_name) {
570 		npw->pw_name = ((char *)npw) + len;
571 		len += sprintf(npw->pw_name, "%s", pw->pw_name) + 1;
572 	}
573 	if (pw->pw_passwd) {
574 		npw->pw_passwd = ((char *)npw) + len;
575 		len += sprintf(npw->pw_passwd, "%s", pw->pw_passwd) + 1;
576 	}
577 	if (pw->pw_class) {
578 		npw->pw_class = ((char *)npw) + len;
579 		len += sprintf(npw->pw_class, "%s", pw->pw_class) + 1;
580 	}
581 	if (pw->pw_gecos) {
582 		npw->pw_gecos = ((char *)npw) + len;
583 		len += sprintf(npw->pw_gecos, "%s", pw->pw_gecos) + 1;
584 	}
585 	if (pw->pw_dir) {
586 		npw->pw_dir = ((char *)npw) + len;
587 		len += sprintf(npw->pw_dir, "%s", pw->pw_dir) + 1;
588 	}
589 	if (pw->pw_shell) {
590 		npw->pw_shell = ((char *)npw) + len;
591 		len += sprintf(npw->pw_shell, "%s", pw->pw_shell) + 1;
592 	}
593 	return (npw);
594 }
595 
596 #include "pw_scan.h"
597 
598 /*
599  * Wrapper around an internal libc function
600  */
601 struct passwd *
602 pw_scan(const char *line, int flags)
603 {
604 	struct passwd pw, *ret;
605 	char *bp;
606 
607 	if ((bp = strdup(line)) == NULL)
608 		return (NULL);
609 	if (!__pw_scan(bp, &pw, flags)) {
610 		free(bp);
611 		return (NULL);
612 	}
613 	ret = pw_dup(&pw);
614 	free(bp);
615 	return (ret);
616 }
617