pw_util.c revision 112328
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 112328 2003-03-17 02:12:55Z das $";
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 stat st1, st2;
291	const char *editor;
292	char *editcmd;
293	int editcmdlen;
294	int pstat;
295
296	if ((editor = getenv("EDITOR")) == NULL)
297		editor = _PATH_VI;
298	if (stat(tempname, &st1) == -1)
299		return (-1);
300	switch ((editpid = fork())) {
301	case -1:
302		return (-1);
303	case 0:
304		/* child */
305		if (notsetuid) {
306			(void)setgid(getgid());
307			(void)setuid(getuid());
308		}
309		if ((editcmdlen = sysconf(_SC_ARG_MAX) - 6) <= 0 ||
310		    (editcmd = malloc(editcmdlen)) == NULL)
311			_exit(EXIT_FAILURE);
312		if (snprintf(editcmd, editcmdlen, "%s %s",
313		    editor, tempname) >= editcmdlen) {
314			free(editcmd);	/* pedantry */
315			_exit(EXIT_FAILURE);
316		}
317		errno = 0;
318		execl(_PATH_BSHELL, "sh", "-c", editcmd, NULL);
319		free(editcmd);
320		_exit(errno);
321	default:
322		/* parent */
323		break;
324	}
325	for (;;) {
326		editpid = waitpid(editpid, &pstat, WUNTRACED);
327		if (editpid == -1) {
328			unlink(tempname);
329			return (-1);
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			*tempname = '\0';
338			editpid = -1;
339			return (-1);
340		}
341	}
342	if (stat(tempname, &st2) == -1)
343		return (-1);
344	return (st1.st_mtime != st2.st_mtime);
345}
346
347/*
348 * Clean up.  Preserve errno for the caller's convenience.
349 */
350void
351pw_fini(void)
352{
353	int serrno, status;
354
355	if (!initialized)
356		return;
357	initialized = 0;
358	serrno = errno;
359	if (editpid != -1) {
360		kill(editpid, SIGTERM);
361		kill(editpid, SIGCONT);
362		waitpid(editpid, &status, 0);
363		editpid = -1;
364	}
365	if (*tempname != '\0') {
366		unlink(tempname);
367		*tempname = '\0';
368	}
369	if (lockfd != -1)
370		close(lockfd);
371	errno = serrno;
372}
373
374/*
375 * Compares two struct pwds.
376 */
377int
378pw_equal(struct passwd *pw1, struct passwd *pw2)
379{
380	return (strcmp(pw1->pw_name, pw2->pw_name) == 0 &&
381	    pw1->pw_uid == pw2->pw_uid &&
382	    pw1->pw_gid == pw2->pw_gid &&
383	    strcmp(pw1->pw_class, pw2->pw_class) == 0 &&
384	    pw1->pw_change == pw2->pw_change &&
385	    pw1->pw_expire == pw2->pw_expire &&
386	    strcmp(pw1->pw_gecos, pw2->pw_gecos) == 0 &&
387	    strcmp(pw1->pw_dir, pw2->pw_dir) == 0 &&
388	    strcmp(pw1->pw_shell, pw2->pw_shell) == 0);
389}
390
391/*
392 * Make a passwd line out of a struct passwd.
393 */
394char *
395pw_make(struct passwd *pw)
396{
397	char *line;
398
399	asprintf(&line, "%s:%s:%ju:%ju:%s:%ju:%ju:%s:%s:%s", pw->pw_name,
400	    pw->pw_passwd, (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid,
401	    pw->pw_class, (uintmax_t)pw->pw_change, (uintmax_t)pw->pw_expire,
402	    pw->pw_gecos, pw->pw_dir, pw->pw_shell);
403	return line;
404}
405
406/*
407 * Copy password file from one descriptor to another, replacing or adding
408 * a single record on the way.
409 */
410int
411pw_copy(int ffd, int tfd, struct passwd *pw, struct passwd *old_pw)
412{
413	char buf[8192], *end, *line, *p, *q, *r, t;
414	struct passwd *fpw;
415	ssize_t len;
416	int eof;
417
418	if ((line = pw_make(pw)) == NULL)
419		return (-1);
420
421	eof = 0;
422	len = 0;
423	p = q = end = buf;
424	for (;;) {
425		/* find the end of the current line */
426		for (p = q; q < end && *q != '\0'; ++q)
427			if (*q == '\n')
428				break;
429
430		/* if we don't have a complete line, fill up the buffer */
431		if (q >= end) {
432			if (eof)
433				break;
434			if (q - p >= sizeof buf) {
435				warnx("passwd line too long");
436				errno = EINVAL; /* hack */
437				goto err;
438			}
439			if (p < end) {
440				q = memmove(buf, p, end - p);
441				end -= p - buf;
442			} else {
443				p = q = end = buf;
444			}
445			len = read(ffd, end, sizeof buf - (end - buf));
446			if (len == -1)
447				goto err;
448			if (len == 0 && p == buf)
449				break;
450			end += len;
451			len = end - buf;
452			if (len < sizeof buf) {
453				eof = 1;
454				if (len > 0 && buf[len - 1] != '\n')
455					++len, *end++ = '\n';
456			}
457			continue;
458		}
459
460		/* is it a blank line or a comment? */
461		for (r = p; r < q && isspace(*r); ++r)
462			/* nothing */ ;
463		if (r == q || *r == '#') {
464			/* yep */
465			if (write(tfd, p, q - p + 1) != q - p + 1)
466				goto err;
467			++q;
468			continue;
469		}
470
471		/* is it the one we're looking for? */
472		t = *q;
473		*q = '\0';
474		fpw = pw_scan(r, PWSCAN_MASTER);
475		*q = t;
476		if ((old_pw && !pw_equal(fpw, old_pw)) ||
477		    (!old_pw && strcmp(fpw->pw_name, pw->pw_name))) {
478			/* nope */
479			free(fpw);
480			if (write(tfd, p, q - p + 1) != q - p + 1)
481				goto err;
482			++q;
483			continue;
484		}
485		free(fpw);
486
487		/* it is, replace it */
488		len = strlen(line);
489		if (write(tfd, line, len) != len)
490			goto err;
491
492		/* we're done, just copy the rest over */
493		for (;;) {
494			if (write(tfd, q, end - q) != end - q)
495				goto err;
496			q = buf;
497			len = read(ffd, buf, sizeof buf);
498			if (len == 0)
499				break;
500			if (len == -1)
501				goto err;
502			end = buf + len;
503		}
504		goto done;
505	}
506
507	/* if we got here, we have a new entry */
508	len = strlen(line);
509	if (write(tfd, line, len) != len ||
510	    write(tfd, "\n", 1) != 1)
511		goto err;
512 done:
513	free(line);
514	return (0);
515 err:
516	free(line);
517	return (-1);
518}
519
520/*
521 * Return the current value of tempname.
522 */
523const char *
524pw_tempname(void)
525{
526
527	return (tempname);
528}
529
530/*
531 * Duplicate a struct passwd.
532 */
533struct passwd *
534pw_dup(struct passwd *pw)
535{
536	struct passwd *npw;
537	size_t len;
538
539	len = sizeof *npw +
540	    (pw->pw_name ? strlen(pw->pw_name) + 1 : 0) +
541	    (pw->pw_passwd ? strlen(pw->pw_passwd) + 1 : 0) +
542	    (pw->pw_class ? strlen(pw->pw_class) + 1 : 0) +
543	    (pw->pw_gecos ? strlen(pw->pw_gecos) + 1 : 0) +
544	    (pw->pw_dir ? strlen(pw->pw_dir) + 1 : 0) +
545	    (pw->pw_shell ? strlen(pw->pw_shell) + 1 : 0);
546	if ((npw = malloc(len)) == NULL)
547		return (NULL);
548	memcpy(npw, pw, sizeof *npw);
549	len = sizeof *npw;
550	if (pw->pw_name) {
551		npw->pw_name = ((char *)npw) + len;
552		len += sprintf(npw->pw_name, "%s", pw->pw_name) + 1;
553	}
554	if (pw->pw_passwd) {
555		npw->pw_passwd = ((char *)npw) + len;
556		len += sprintf(npw->pw_passwd, "%s", pw->pw_passwd) + 1;
557	}
558	if (pw->pw_class) {
559		npw->pw_class = ((char *)npw) + len;
560		len += sprintf(npw->pw_class, "%s", pw->pw_class) + 1;
561	}
562	if (pw->pw_gecos) {
563		npw->pw_gecos = ((char *)npw) + len;
564		len += sprintf(npw->pw_gecos, "%s", pw->pw_gecos) + 1;
565	}
566	if (pw->pw_dir) {
567		npw->pw_dir = ((char *)npw) + len;
568		len += sprintf(npw->pw_dir, "%s", pw->pw_dir) + 1;
569	}
570	if (pw->pw_shell) {
571		npw->pw_shell = ((char *)npw) + len;
572		len += sprintf(npw->pw_shell, "%s", pw->pw_shell) + 1;
573	}
574	return (npw);
575}
576
577#include "pw_scan.h"
578
579/*
580 * Wrapper around an internal libc function
581 */
582struct passwd *
583pw_scan(const char *line, int flags)
584{
585	struct passwd pw, *ret;
586	char *bp;
587
588	if ((bp = strdup(line)) == NULL)
589		return (NULL);
590	if (!__pw_scan(bp, &pw, flags)) {
591		free(bp);
592		return (NULL);
593	}
594	ret = pw_dup(&pw);
595	free(bp);
596	return (ret);
597}
598