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