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