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