xref: /freebsd/lib/libutil/pw_util.c (revision 3ff369fed2a08f32dda232c10470b949bef9489f)
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  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40 
41 #ifndef lint
42 #if 0
43 static const char sccsid[] = "@(#)pw_util.c	8.3 (Berkeley) 4/2/94";
44 #endif
45 static const char rcsid[] =
46   "$FreeBSD$";
47 #endif /* not lint */
48 
49 /*
50  * This file is used by all the "password" programs; vipw(8), chpass(1),
51  * and passwd(1).
52  */
53 
54 #include <sys/param.h>
55 #include <sys/errno.h>
56 #include <sys/time.h>
57 #include <sys/resource.h>
58 #include <sys/stat.h>
59 #include <sys/wait.h>
60 
61 #include <err.h>
62 #include <ctype.h>
63 #include <fcntl.h>
64 #include <inttypes.h>
65 #include <libgen.h>
66 #include <paths.h>
67 #include <pwd.h>
68 #include <signal.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 
74 #include <libutil.h>
75 
76 static pid_t editpid = -1;
77 static int lockfd = -1;
78 static char masterpasswd[PATH_MAX];
79 static char passwd_dir[PATH_MAX];
80 static char tempname[PATH_MAX];
81 static int initialized;
82 
83 void
84 pw_cont(int sig)
85 {
86 
87 	if (editpid != -1)
88 		kill(editpid, sig);
89 }
90 
91 /*
92  * Initialize statics and set limits, signals & umask to try to avoid
93  * interruptions, crashes etc. that might expose passord data.
94  */
95 int
96 pw_init(const char *dir, const char *master)
97 {
98 #if 0
99 	struct rlimit rlim;
100 #endif
101 
102 	if (dir == NULL) {
103 		strcpy(passwd_dir, _PATH_ETC);
104 	} else {
105 		if (strlen(dir) >= sizeof passwd_dir) {
106 			errno = ENAMETOOLONG;
107 			return (-1);
108 		}
109 		strcpy(passwd_dir, dir);
110 	}
111 
112 	if (master == NULL) {
113 		if (dir == NULL) {
114 			strcpy(masterpasswd, _PATH_MASTERPASSWD);
115 		} else if (snprintf(masterpasswd, sizeof masterpasswd, "%s/%s",
116 		    passwd_dir, _MASTERPASSWD) > sizeof masterpasswd) {
117 			errno = ENAMETOOLONG;
118 			return (-1);
119 		}
120 	} else {
121 		if (strlen(master) >= sizeof masterpasswd) {
122 			errno = ENAMETOOLONG;
123 			return (-1);
124 		}
125 		strcpy(masterpasswd, master);
126 	}
127 
128 	/*
129 	 * The code that follows is extremely disruptive to the calling
130 	 * process, and is therefore disabled until someone can conceive
131 	 * of a realistic scenario where it would fend off a compromise.
132 	 * Race conditions concerning the temporary files can be guarded
133 	 * against in other ways than masking signals (by checking stat(2)
134 	 * results after creation).
135 	 */
136 #if 0
137 	/* Unlimited resource limits. */
138 	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
139 	(void)setrlimit(RLIMIT_CPU, &rlim);
140 	(void)setrlimit(RLIMIT_FSIZE, &rlim);
141 	(void)setrlimit(RLIMIT_STACK, &rlim);
142 	(void)setrlimit(RLIMIT_DATA, &rlim);
143 	(void)setrlimit(RLIMIT_RSS, &rlim);
144 
145 	/* Don't drop core (not really necessary, but GP's). */
146 	rlim.rlim_cur = rlim.rlim_max = 0;
147 	(void)setrlimit(RLIMIT_CORE, &rlim);
148 
149 	/* Turn off signals. */
150 	(void)signal(SIGALRM, SIG_IGN);
151 	(void)signal(SIGHUP, SIG_IGN);
152 	(void)signal(SIGINT, SIG_IGN);
153 	(void)signal(SIGPIPE, SIG_IGN);
154 	(void)signal(SIGQUIT, SIG_IGN);
155 	(void)signal(SIGTERM, SIG_IGN);
156 	(void)signal(SIGCONT, pw_cont);
157 
158 	/* Create with exact permissions. */
159 	(void)umask(0);
160 #endif
161 	initialized = 1;
162 	return (0);
163 }
164 
165 /*
166  * Lock the master password file.
167  */
168 int
169 pw_lock(void)
170 {
171 
172 	if (*masterpasswd == '\0')
173 		return (-1);
174 
175 	/*
176 	 * If the master password file doesn't exist, the system is hosed.
177 	 * Might as well try to build one.  Set the close-on-exec bit so
178 	 * that users can't get at the encrypted passwords while editing.
179 	 * Open should allow flock'ing the file; see 4.4BSD.	XXX
180 	 */
181 	for (;;) {
182 		struct stat st;
183 
184 		lockfd = open(masterpasswd, O_RDONLY, 0);
185 		if (lockfd < 0 || fcntl(lockfd, F_SETFD, 1) == -1)
186 			err(1, "%s", masterpasswd);
187 		/* XXX vulnerable to race conditions */
188 		if (flock(lockfd, LOCK_EX|LOCK_NB))
189 			errx(1, "the password db file is busy");
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) < 0)
197 			errx(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, nw;
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) >= sizeof tempname) {
226 		errno = ENAMETOOLONG;
227 		return (-1);
228 	}
229 	if ((tfd = mkstemp(tempname)) == -1)
230 		return (-1);
231 	if (mfd != -1) {
232 		while ((nr = read(mfd, buf, sizeof buf)) > 0)
233 			if ((nw = write(tfd, buf, 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, NULL);
263 		else
264 			execl(_PATH_PWD_MKDB, "pwd_mkdb", "-p",
265 			    "-d", passwd_dir, "-u", user, tempname, NULL);
266 		_exit(1);
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 stat st1, st2;
287 	const char *editor;
288 	int pstat;
289 
290 	if ((editor = getenv("EDITOR")) == NULL)
291 		editor = _PATH_VI;
292 	if (stat(tempname, &st1) == -1)
293 		return (-1);
294 	switch ((editpid = fork())) {
295 	case -1:
296 		return (-1);
297 	case 0:
298 		/* child */
299 		if (notsetuid) {
300 			(void)setgid(getgid());
301 			(void)setuid(getuid());
302 		}
303 		errno = 0;
304 		execlp(editor, basename(editor), tempname, NULL);
305 		_exit(errno);
306 	default:
307 		/* parent */
308 		break;
309 	}
310 	for (;;) {
311 		editpid = waitpid(editpid, &pstat, WUNTRACED);
312 		if (editpid == -1) {
313 			unlink(tempname);
314 			return (-1);
315 		} else if (WIFSTOPPED(pstat)) {
316 			raise(WSTOPSIG(pstat));
317 		} else if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0) {
318 			editpid = -1;
319 			break;
320 		} else {
321 			unlink(tempname);
322 			*tempname = '\0';
323 			editpid = -1;
324 			return (-1);
325 		}
326 	}
327 	if (stat(tempname, &st2) == -1)
328 		return (-1);
329 	return (st1.st_mtime != st2.st_mtime);
330 }
331 
332 /*
333  * Clean up.  Preserve errno for the caller's convenience.
334  */
335 void
336 pw_fini(void)
337 {
338 	int serrno, status;
339 
340 	if (!initialized)
341 		return;
342 	initialized = 0;
343 	serrno = errno;
344 	if (editpid != -1) {
345 		kill(editpid, SIGTERM);
346 		kill(editpid, SIGCONT);
347 		waitpid(editpid, &status, 0);
348 		editpid = -1;
349 	}
350 	if (*tempname != '\0') {
351 		unlink(tempname);
352 		*tempname = '\0';
353 	}
354 	if (lockfd != -1)
355 		close(lockfd);
356 	errno = serrno;
357 }
358 
359 /*
360  * Compares two struct pwds.
361  */
362 int
363 pw_equal(struct passwd *pw1, struct passwd *pw2)
364 {
365 	return (strcmp(pw1->pw_name, pw2->pw_name) == 0 &&
366 	    pw1->pw_uid == pw2->pw_uid &&
367 	    pw1->pw_gid == pw2->pw_gid &&
368 	    strcmp(pw1->pw_class, pw2->pw_class) == 0 &&
369 	    pw1->pw_change == pw2->pw_change &&
370 	    pw1->pw_expire == pw2->pw_expire &&
371 	    strcmp(pw1->pw_gecos, pw2->pw_gecos) == 0 &&
372 	    strcmp(pw1->pw_dir, pw2->pw_dir) == 0 &&
373 	    strcmp(pw1->pw_shell, pw2->pw_shell) == 0);
374 }
375 
376 /*
377  * Make a passwd line out of a struct passwd.
378  */
379 char *
380 pw_make(struct passwd *pw)
381 {
382 	char *line;
383 
384 	asprintf(&line, "%s:%s:%ju:%ju:%s:%ju:%ju:%s:%s:%s", pw->pw_name,
385 	    pw->pw_passwd, (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid,
386 	    pw->pw_class, (uintmax_t)pw->pw_change, (uintmax_t)pw->pw_expire,
387 	    pw->pw_gecos, pw->pw_dir, pw->pw_shell);
388 	return line;
389 }
390 
391 /*
392  * Copy password file from one descriptor to another, replacing or adding
393  * a single record on the way.
394  */
395 int
396 pw_copy(int ffd, int tfd, struct passwd *pw, struct passwd *old_pw)
397 {
398 	char buf[8192], *end, *line, *p, *q, *r, t;
399 	struct passwd *fpw;
400 	ssize_t len;
401 	int eof;
402 
403 	if ((line = pw_make(pw)) == NULL)
404 		return (-1);
405 
406 	eof = 0;
407 	len = 0;
408 	p = q = end = buf;
409 	for (;;) {
410 		/* find the end of the current line */
411 		for (p = q; q < end && *q != '\0'; ++q)
412 			if (*q == '\n')
413 				break;
414 
415 		/* if we don't have a complete line, fill up the buffer */
416 		if (q >= end) {
417 			if (eof)
418 				break;
419 			if (q - p >= sizeof buf) {
420 				warnx("passwd line too long");
421 				errno = EINVAL; /* hack */
422 				goto err;
423 			}
424 			if (p < end) {
425 				q = memmove(buf, p, end - p);
426 				end -= p - buf;
427 			} else {
428 				p = q = end = buf;
429 			}
430 			len = read(ffd, end, sizeof buf - (end - buf));
431 			if (len == -1)
432 				goto err;
433 			if (len == 0 && p == buf)
434 				break;
435 			end += len;
436 			len = end - buf;
437 			if (len < sizeof buf) {
438 				eof = 1;
439 				if (len > 0 && buf[len - 1] != '\n')
440 					++len, *end++ = '\n';
441 			}
442 			continue;
443 		}
444 
445 		/* is it a blank line or a comment? */
446 		for (r = p; r < q && isspace(*r); ++r)
447 			/* nothing */ ;
448 		if (r == q || *r == '#') {
449 			/* yep */
450 			if (write(tfd, p, q - p + 1) != q - p + 1)
451 				goto err;
452 			++q;
453 			continue;
454 		}
455 
456 		/* is it the one we're looking for? */
457 		t = *q;
458 		*q = '\0';
459 		fpw = pw_scan(r, PWSCAN_MASTER);
460 		*q = t;
461 		if ((old_pw && !pw_equal(fpw, old_pw)) ||
462 		    (!old_pw && strcmp(fpw->pw_name, pw->pw_name))) {
463 			/* nope */
464 			free(fpw);
465 			if (write(tfd, p, q - p + 1) != q - p + 1)
466 				goto err;
467 			++q;
468 			continue;
469 		}
470 		free(fpw);
471 
472 		/* it is, replace it */
473 		len = strlen(line);
474 		if (write(tfd, line, len) != len)
475 			goto err;
476 
477 		/* we're done, just copy the rest over */
478 		for (;;) {
479 			if (write(tfd, q, end - q) != end - q)
480 				goto err;
481 			q = buf;
482 			len = read(ffd, buf, sizeof buf);
483 			if (len == 0)
484 				break;
485 			if (len == -1)
486 				goto err;
487 			end = buf + len;
488 		}
489 		goto done;
490 	}
491 
492 	/* if we got here, we have a new entry */
493 	len = strlen(line);
494 	if (write(tfd, line, len) != len)
495 		goto err;
496  done:
497 	free(line);
498 	return (0);
499  err:
500 	free(line);
501 	return (-1);
502 }
503 
504 /*
505  * Return the current value of tempname.
506  */
507 const char *
508 pw_tempname(void)
509 {
510 
511 	return (tempname);
512 }
513 
514 /*
515  * Duplicate a struct passwd.
516  */
517 struct passwd *
518 pw_dup(struct passwd *pw)
519 {
520 	struct passwd *npw;
521 	size_t len;
522 
523 	len = sizeof *npw +
524 	    (pw->pw_name ? strlen(pw->pw_name) + 1 : 0) +
525 	    (pw->pw_passwd ? strlen(pw->pw_passwd) + 1 : 0) +
526 	    (pw->pw_class ? strlen(pw->pw_class) + 1 : 0) +
527 	    (pw->pw_gecos ? strlen(pw->pw_gecos) + 1 : 0) +
528 	    (pw->pw_dir ? strlen(pw->pw_dir) + 1 : 0) +
529 	    (pw->pw_shell ? strlen(pw->pw_shell) + 1 : 0);
530 	if ((npw = malloc(len)) == NULL)
531 		return (NULL);
532 	memcpy(npw, pw, sizeof *npw);
533 	len = sizeof *npw;
534 	if (pw->pw_name) {
535 		npw->pw_name = ((char *)npw) + len;
536 		len += sprintf(npw->pw_name, "%s", pw->pw_name) + 1;
537 	}
538 	if (pw->pw_passwd) {
539 		npw->pw_passwd = ((char *)npw) + len;
540 		len += sprintf(npw->pw_passwd, "%s", pw->pw_passwd) + 1;
541 	}
542 	if (pw->pw_class) {
543 		npw->pw_class = ((char *)npw) + len;
544 		len += sprintf(npw->pw_class, "%s", pw->pw_class) + 1;
545 	}
546 	if (pw->pw_gecos) {
547 		npw->pw_gecos = ((char *)npw) + len;
548 		len += sprintf(npw->pw_gecos, "%s", pw->pw_gecos) + 1;
549 	}
550 	if (pw->pw_dir) {
551 		npw->pw_dir = ((char *)npw) + len;
552 		len += sprintf(npw->pw_dir, "%s", pw->pw_dir) + 1;
553 	}
554 	if (pw->pw_shell) {
555 		npw->pw_shell = ((char *)npw) + len;
556 		len += sprintf(npw->pw_shell, "%s", pw->pw_shell) + 1;
557 	}
558 	return (npw);
559 }
560 
561 #include "pw_scan.h"
562 
563 /*
564  * Wrapper around an internal libc function
565  */
566 struct passwd *
567 pw_scan(const char *line, int flags)
568 {
569 	struct passwd pw, *ret;
570 	char *bp;
571 
572 	if ((bp = strdup(line)) == NULL)
573 		return (NULL);
574 	if (!__pw_scan(bp, &pw, flags)) {
575 		free(bp);
576 		return (NULL);
577 	}
578 	ret = pw_dup(&pw);
579 	free(bp);
580 	return (ret);
581 }
582