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