pwd_mkdb.c revision 33413
1/*-
2 * Copyright (c) 1991, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1991, 1993, 1994\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)pwd_mkdb.c	8.5 (Berkeley) 4/20/94";
43#endif
44static const char rcsid[] =
45	"$Id: pwd_mkdb.c,v 1.21 1998/01/10 17:27:28 wosch Exp $";
46#endif /* not lint */
47
48#include <sys/param.h>
49#include <sys/stat.h>
50
51#include <db.h>
52#include <err.h>
53#include <errno.h>
54#include <fcntl.h>
55#include <limits.h>
56#include <pwd.h>
57#include <signal.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61#include <unistd.h>
62
63#include "pw_scan.h"
64
65#define	INSECURE	1
66#define	SECURE		2
67#define	PERM_INSECURE	(S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)
68#define	PERM_SECURE	(S_IRUSR|S_IWUSR)
69
70HASHINFO openinfo = {
71	4096,		/* bsize */
72	32,		/* ffactor */
73	256,		/* nelem */
74	2048 * 1024,	/* cachesize */
75	NULL,		/* hash() */
76	0		/* lorder */
77};
78
79static enum state { FILE_INSECURE, FILE_SECURE, FILE_ORIG } clean;
80static struct passwd pwd;			/* password structure */
81static char *pname;				/* password file name */
82static char prefix[MAXPATHLEN];
83
84static int Cflag;	/* flag for comments */
85static char line[LINE_MAX];
86
87void	cleanup __P((void));
88void	error __P((char *));
89void	cp __P((char *, char *, mode_t mode));
90void	mv __P((char *, char *));
91int	scan __P((FILE *, struct passwd *));
92static void	usage __P((void));
93
94int
95main(argc, argv)
96	int argc;
97	char *argv[];
98{
99	DB *dp, *sdp, *pw_db;
100	DBT data, sdata, key;
101	FILE *fp, *oldfp;
102	sigset_t set;
103	int ch, cnt, ypcnt, len, makeold, tfd, yp_enabled = 0;
104	char *p, *t;
105	char buf[MAX(MAXPATHLEN, LINE_MAX * 2)], tbuf[1024];
106	char sbuf[MAX(MAXPATHLEN, LINE_MAX * 2)];
107	char buf2[MAXPATHLEN];
108	char sbuf2[MAXPATHLEN];
109	char *username;
110	u_int method, methoduid;
111	int Cflag;
112
113	Cflag = 0;
114	strcpy(prefix, _PATH_PWD);
115	makeold = 0;
116	username = NULL;
117	while ((ch = getopt(argc, argv, "Cd:pu:v")) != -1)
118		switch(ch) {
119		case 'C':                       /* verify only */
120			Cflag = 1;
121			break;
122		case 'd':
123			strncpy(prefix, optarg, sizeof prefix - 1);
124			break;
125		case 'p':			/* create V7 "file.orig" */
126			makeold = 1;
127			break;
128		case 'u':			/* only update this record */
129			username = optarg;
130			break;
131		case 'v':                       /* backward compatible */
132			break;
133		default:
134			usage();
135		}
136	argc -= optind;
137	argv += optind;
138
139	if (argc != 1 || (username && (*username == '+' || *username == '-')))
140		usage();
141
142	/*
143	 * This could be changed to allow the user to interrupt.
144	 * Probably not worth the effort.
145	 */
146	sigemptyset(&set);
147	sigaddset(&set, SIGTSTP);
148	sigaddset(&set, SIGHUP);
149	sigaddset(&set, SIGINT);
150	sigaddset(&set, SIGQUIT);
151	sigaddset(&set, SIGTERM);
152	(void)sigprocmask(SIG_BLOCK, &set, (sigset_t *)NULL);
153
154	/* We don't care what the user wants. */
155	(void)umask(0);
156
157	pname = *argv;
158	/* Open the original password file */
159	if (!(fp = fopen(pname, "r")))
160		error(pname);
161
162	/* check only if password database is valid */
163	if (Cflag) {
164		for (cnt = 1; scan(fp, &pwd); ++cnt);
165		exit(0);
166	}
167
168	/* Open the temporary insecure password database. */
169	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
170	(void)snprintf(sbuf, sizeof(sbuf), "%s/%s.tmp", prefix, _SMP_DB);
171	if (username) {
172		(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _MP_DB);
173		(void)snprintf(sbuf2, sizeof(sbuf2), "%s/%s", prefix, _SMP_DB);
174
175		clean = FILE_INSECURE;
176		cp(buf2, buf, PERM_INSECURE);
177		dp = dbopen(buf,
178		    O_RDWR|O_EXCL, PERM_INSECURE, DB_HASH, &openinfo);
179		if (dp == NULL)
180			error(buf);
181
182		clean = FILE_SECURE;
183		cp(sbuf2, sbuf, PERM_SECURE);
184		sdp = dbopen(sbuf,
185		    O_RDWR|O_EXCL, PERM_SECURE, DB_HASH, &openinfo);
186		if (sdp == NULL)
187			error(sbuf);
188
189		/*
190		 * Do some trouble to check if we should store this users
191		 * uid. Don't use getpwnam/getpwuid as that interferes
192		 * with NIS.
193		 */
194		pw_db = dbopen(_PATH_MP_DB, O_RDONLY, 0, DB_HASH, NULL);
195		if (!pw_db)
196			error(_MP_DB);
197		buf[0] = _PW_KEYBYNAME;
198		len = strlen(username);
199
200		/* Only check that username fits in buffer */
201		memmove(buf + 1, username, MIN(len, sizeof(buf) - 1));
202		key.data = (u_char *)buf;
203		key.size = len + 1;
204		if ((pw_db->get)(pw_db, &key, &data, 0) == 0) {
205			p = (char *)data.data;
206
207			/* jump over pw_name and pw_passwd, to get to pw_uid */
208			while (*p++)
209				;
210			while (*p++)
211				;
212
213			buf[0] = _PW_KEYBYUID;
214			memmove(buf + 1, p, sizeof(int));
215			key.data = (u_char *)buf;
216			key.size = sizeof(int) + 1;
217
218			if ((pw_db->get)(pw_db, &key, &data, 0) == 0) {
219				/* First field of data.data holds pw_pwname */
220				if (!strcmp(data.data, username))
221					methoduid = 0;
222				else
223					methoduid = R_NOOVERWRITE;
224			} else {
225				methoduid = R_NOOVERWRITE;
226			}
227		} else {
228			methoduid = R_NOOVERWRITE;
229		}
230		if ((pw_db->close)(pw_db))
231			error("close pw_db");
232		method = 0;
233	} else {
234		dp = dbopen(buf,
235		    O_RDWR|O_CREAT|O_EXCL, PERM_INSECURE, DB_HASH, &openinfo);
236		if (dp == NULL)
237			error(buf);
238		clean = FILE_INSECURE;
239
240		sdp = dbopen(sbuf,
241		    O_RDWR|O_CREAT|O_EXCL, PERM_SECURE, DB_HASH, &openinfo);
242		if (sdp == NULL)
243			error(sbuf);
244		clean = FILE_SECURE;
245
246		method = R_NOOVERWRITE;
247		methoduid = R_NOOVERWRITE;
248	}
249
250	/*
251	 * Open file for old password file.  Minor trickiness -- don't want to
252	 * chance the file already existing, since someone (stupidly) might
253	 * still be using this for permission checking.  So, open it first and
254	 * fdopen the resulting fd.  The resulting file should be readable by
255	 * everyone.
256	 */
257	if (makeold) {
258		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
259		if ((tfd = open(buf,
260		    O_WRONLY|O_CREAT|O_EXCL, PERM_INSECURE)) < 0)
261			error(buf);
262		if ((oldfp = fdopen(tfd, "w")) == NULL)
263			error(buf);
264		clean = FILE_ORIG;
265	}
266
267	/*
268	 * The databases actually contain three copies of the original data.
269	 * Each password file entry is converted into a rough approximation
270	 * of a ``struct passwd'', with the strings placed inline.  This
271	 * object is then stored as the data for three separate keys.  The
272	 * first key * is the pw_name field prepended by the _PW_KEYBYNAME
273	 * character.  The second key is the pw_uid field prepended by the
274	 * _PW_KEYBYUID character.  The third key is the line number in the
275	 * original file prepended by the _PW_KEYBYNUM character.  (The special
276	 * characters are prepended to ensure that the keys do not collide.)
277	 */
278	ypcnt = 1;
279	data.data = (u_char *)buf;
280	sdata.data = (u_char *)sbuf;
281	key.data = (u_char *)tbuf;
282	for (cnt = 1; scan(fp, &pwd); ++cnt) {
283		if (!Cflag &&
284		    (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-'))
285			yp_enabled = 1;
286#define	COMPACT(e)	t = e; while ((*p++ = *t++));
287		if (!Cflag &&
288		    (!username || (strcmp(username, pwd.pw_name) == 0))) {
289			/* Create insecure data. */
290			p = buf;
291			COMPACT(pwd.pw_name);
292			COMPACT("*");
293			memmove(p, &pwd.pw_uid, sizeof(int));
294			p += sizeof(int);
295			memmove(p, &pwd.pw_gid, sizeof(int));
296			p += sizeof(int);
297			memmove(p, &pwd.pw_change, sizeof(time_t));
298			p += sizeof(time_t);
299			COMPACT(pwd.pw_class);
300			COMPACT(pwd.pw_gecos);
301			COMPACT(pwd.pw_dir);
302			COMPACT(pwd.pw_shell);
303			memmove(p, &pwd.pw_expire, sizeof(time_t));
304			p += sizeof(time_t);
305			memmove(p, &pwd.pw_fields, sizeof pwd.pw_fields);
306			p += sizeof pwd.pw_fields;
307			data.size = p - buf;
308
309			/* Create secure data. */
310			p = sbuf;
311			COMPACT(pwd.pw_name);
312			COMPACT(pwd.pw_passwd);
313			memmove(p, &pwd.pw_uid, sizeof(int));
314			p += sizeof(int);
315			memmove(p, &pwd.pw_gid, sizeof(int));
316			p += sizeof(int);
317			memmove(p, &pwd.pw_change, sizeof(time_t));
318			p += sizeof(time_t);
319			COMPACT(pwd.pw_class);
320			COMPACT(pwd.pw_gecos);
321			COMPACT(pwd.pw_dir);
322			COMPACT(pwd.pw_shell);
323			memmove(p, &pwd.pw_expire, sizeof(time_t));
324			p += sizeof(time_t);
325			memmove(p, &pwd.pw_fields, sizeof pwd.pw_fields);
326			p += sizeof pwd.pw_fields;
327			sdata.size = p - sbuf;
328
329			/* Store insecure by name. */
330			tbuf[0] = _PW_KEYBYNAME;
331			len = strlen(pwd.pw_name);
332			memmove(tbuf + 1, pwd.pw_name, len);
333			key.size = len + 1;
334			if ((dp->put)(dp, &key, &data, method) == -1)
335				error("put");
336
337			/* Store insecure by number. */
338			tbuf[0] = _PW_KEYBYNUM;
339			memmove(tbuf + 1, &cnt, sizeof(cnt));
340			key.size = sizeof(cnt) + 1;
341			if ((dp->put)(dp, &key, &data, method) == -1)
342				error("put");
343
344			/* Store insecure by uid. */
345			tbuf[0] = _PW_KEYBYUID;
346			memmove(tbuf + 1, &pwd.pw_uid, sizeof(pwd.pw_uid));
347			key.size = sizeof(pwd.pw_uid) + 1;
348			if ((dp->put)(dp, &key, &data, methoduid) == -1)
349				error("put");
350
351			/* Store secure by name. */
352			tbuf[0] = _PW_KEYBYNAME;
353			len = strlen(pwd.pw_name);
354			memmove(tbuf + 1, pwd.pw_name, len);
355			key.size = len + 1;
356			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
357				error("put");
358
359			/* Store secure by number. */
360			tbuf[0] = _PW_KEYBYNUM;
361			memmove(tbuf + 1, &cnt, sizeof(cnt));
362			key.size = sizeof(cnt) + 1;
363			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
364				error("put");
365
366			/* Store secure by uid. */
367			tbuf[0] = _PW_KEYBYUID;
368			memmove(tbuf + 1, &pwd.pw_uid, sizeof(pwd.pw_uid));
369			key.size = sizeof(pwd.pw_uid) + 1;
370			if ((sdp->put)(sdp, &key, &sdata, methoduid) == -1)
371				error("put");
372
373			/* Store insecure and secure special plus and special minus */
374			if (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-') {
375				tbuf[0] = _PW_KEYYPBYNUM;
376				memmove(tbuf + 1, &ypcnt, sizeof(cnt));
377				ypcnt++;
378				key.size = sizeof(cnt) + 1;
379				if ((dp->put)(dp, &key, &data, method) == -1)
380					error("put");
381				if ((sdp->put)(sdp, &key, &sdata, method) == -1)
382					error("put");
383			}
384		}
385		/* Create original format password file entry */
386		if (Cflag && makeold)	/* copy comments */
387			if (fprintf(oldfp, "%s\n", line) == EOF)
388				error("write old");
389		else if (makeold) {
390			char uidstr[20];
391			char gidstr[20];
392
393			snprintf(uidstr, sizeof(uidstr), "%d", pwd.pw_uid);
394			snprintf(gidstr, sizeof(gidstr), "%d", pwd.pw_gid);
395
396			if (fprintf(oldfp, "%s:*:%s:%s:%s:%s:%s\n",
397			    pwd.pw_name, pwd.pw_fields & _PWF_UID ? uidstr : "",
398			    pwd.pw_fields & _PWF_GID ? gidstr : "",
399			    pwd.pw_gecos, pwd.pw_dir, pwd.pw_shell) == EOF)
400				error("write old");
401		}
402	}
403	/* If YP enabled, set flag. */
404	if (yp_enabled) {
405		buf[0] = yp_enabled + 2;
406		data.size = 1;
407		tbuf[0] = _PW_KEYYPENABLED;
408		key.size = 1;
409		if ((dp->put)(dp, &key, &data, method) == -1)
410			error("put");
411		if ((sdp->put)(sdp, &key, &data, method) == -1)
412			error("put");
413	}
414
415	if ((dp->close)(dp) == -1)
416		error("close");
417	if ((sdp->close)(sdp) == -1)
418		error("close");
419	if (makeold) {
420		(void)fflush(oldfp);
421		if (fclose(oldfp) == EOF)
422			error("close old");
423	}
424
425	/* Set master.passwd permissions, in case caller forgot. */
426	(void)fchmod(fileno(fp), S_IRUSR|S_IWUSR);
427	if (fclose(fp) == EOF)
428		error("close fp");
429
430	/* Install as the real password files. */
431	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
432	(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _MP_DB);
433	mv(buf, buf2);
434	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _SMP_DB);
435	(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _SMP_DB);
436	mv(buf, buf2);
437	if (makeold) {
438		(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _PASSWD);
439		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
440		mv(buf, buf2);
441	}
442	/*
443	 * Move the master password LAST -- chpass(1), passwd(1) and vipw(8)
444	 * all use flock(2) on it to block other incarnations of themselves.
445	 * The rename means that everything is unlocked, as the original file
446	 * can no longer be accessed.
447	 */
448	(void)snprintf(buf, sizeof(buf), "%s/%s", prefix, _MASTERPASSWD);
449	mv(pname, buf);
450	exit(0);
451}
452
453int
454scan(fp, pw)
455	FILE *fp;
456	struct passwd *pw;
457{
458	static int lcnt;
459	char *p;
460
461	if (!fgets(line, sizeof(line), fp))
462		return (0);
463	++lcnt;
464	/*
465	 * ``... if I swallow anything evil, put your fingers down my
466	 * throat...''
467	 *	-- The Who
468	 */
469	if (!(p = strchr(line, '\n'))) {
470		warnx("line too long");
471		goto fmt;
472
473	}
474	*p = '\0';
475
476#ifdef PASSWD_IGNORE_COMMENTS
477	/*
478	 * Ignore comments: ^[ \t]*#
479	 */
480	for (p = line; *p != '\0'; p++)
481		if (*p != ' ' && *p != '\t')
482			break;
483	if (*p == '#' || *p == '\0') {
484		Cflag = 1;
485		return(1);
486	} else
487		Cflag = 0;
488#endif
489
490	if (!pw_scan(line, pw)) {
491		warnx("at line #%d", lcnt);
492fmt:		errno = EFTYPE;	/* XXX */
493		error(pname);
494	}
495
496	return (1);
497}
498
499void
500cp(from, to, mode)
501	char *from, *to;
502	mode_t mode;
503{
504	static char buf[MAXBSIZE];
505	int from_fd, rcount, to_fd, wcount;
506
507	if ((from_fd = open(from, O_RDONLY, 0)) < 0)
508		error(from);
509	if ((to_fd = open(to, O_WRONLY|O_CREAT|O_EXCL, mode)) < 0)
510		error(to);
511	while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
512		wcount = write(to_fd, buf, rcount);
513		if (rcount != wcount || wcount == -1) {
514			int sverrno = errno;
515
516			(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
517			errno = sverrno;
518			error(buf);
519		}
520	}
521	if (rcount < 0) {
522		int sverrno = errno;
523
524		(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
525		errno = sverrno;
526		error(buf);
527	}
528}
529
530
531void
532mv(from, to)
533	char *from, *to;
534{
535	char buf[MAXPATHLEN];
536
537	if (rename(from, to)) {
538		int sverrno = errno;
539		(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
540		errno = sverrno;
541		error(buf);
542	}
543}
544
545void
546error(name)
547	char *name;
548{
549
550	warn("%s", name);
551	cleanup();
552	exit(1);
553}
554
555void
556cleanup()
557{
558	char buf[MAXPATHLEN];
559
560	switch(clean) {
561	case FILE_ORIG:
562		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
563		(void)unlink(buf);
564		/* FALLTHROUGH */
565	case FILE_SECURE:
566		(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _SMP_DB);
567		(void)unlink(buf);
568		/* FALLTHROUGH */
569	case FILE_INSECURE:
570		(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
571		(void)unlink(buf);
572	}
573}
574
575static void
576usage()
577{
578
579	(void)fprintf(stderr,
580"usage: pwd_mkdb [-c] [-p] [-d <dest dir>] [-u <local username>] file\n");
581	exit(1);
582}
583