xref: /freebsd/usr.sbin/pwd_mkdb/pwd_mkdb.c (revision 0640d357f29fb1c0daaaffadd0416c5981413afd)
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
35 static 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
42 static char sccsid[] = "@(#)pwd_mkdb.c	8.5 (Berkeley) 4/20/94";
43 #endif
44 static const char rcsid[] =
45 	"$Id: pwd_mkdb.c,v 1.26 1998/06/09 20:19:59 ache 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 
70 HASHINFO openinfo = {
71 	4096,		/* bsize */
72 	32,		/* ffactor */
73 	256,		/* nelem */
74 	2048 * 1024,	/* cachesize */
75 	NULL,		/* hash() */
76 	0		/* lorder */
77 };
78 
79 static enum state { FILE_INSECURE, FILE_SECURE, FILE_ORIG } clean;
80 static struct passwd pwd;			/* password structure */
81 static char *pname;				/* password file name */
82 static char prefix[MAXPATHLEN];
83 
84 static int is_comment;	/* flag for comments */
85 static char line[LINE_MAX];
86 
87 void	cleanup __P((void));
88 void	error __P((char *));
89 void	cp __P((char *, char *, mode_t mode));
90 void	mv __P((char *, char *));
91 int	scan __P((FILE *, struct passwd *));
92 static void	usage __P((void));
93 
94 int
95 main(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:ps:u: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 's':			/* change default cachesize */
129 			openinfo.cachesize = atoi(optarg) * 1024 * 1024;
130 			break;
131 		case 'u':			/* only update this record */
132 			username = optarg;
133 			break;
134 		case 'v':                       /* backward compatible */
135 			break;
136 		default:
137 			usage();
138 		}
139 	argc -= optind;
140 	argv += optind;
141 
142 	if (argc != 1 || (username && (*username == '+' || *username == '-')))
143 		usage();
144 
145 	/*
146 	 * This could be changed to allow the user to interrupt.
147 	 * Probably not worth the effort.
148 	 */
149 	sigemptyset(&set);
150 	sigaddset(&set, SIGTSTP);
151 	sigaddset(&set, SIGHUP);
152 	sigaddset(&set, SIGINT);
153 	sigaddset(&set, SIGQUIT);
154 	sigaddset(&set, SIGTERM);
155 	(void)sigprocmask(SIG_BLOCK, &set, (sigset_t *)NULL);
156 
157 	/* We don't care what the user wants. */
158 	(void)umask(0);
159 
160 	pname = *argv;
161 	/* Open the original password file */
162 	if (!(fp = fopen(pname, "r")))
163 		error(pname);
164 
165 	/* check only if password database is valid */
166 	if (Cflag) {
167 		for (cnt = 1; scan(fp, &pwd); ++cnt);
168 		exit(0);
169 	}
170 
171 	/* Open the temporary insecure password database. */
172 	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
173 	(void)snprintf(sbuf, sizeof(sbuf), "%s/%s.tmp", prefix, _SMP_DB);
174 	if (username) {
175 		(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _MP_DB);
176 		(void)snprintf(sbuf2, sizeof(sbuf2), "%s/%s", prefix, _SMP_DB);
177 
178 		clean = FILE_INSECURE;
179 		cp(buf2, buf, PERM_INSECURE);
180 		dp = dbopen(buf,
181 		    O_RDWR|O_EXCL, PERM_INSECURE, DB_HASH, &openinfo);
182 		if (dp == NULL)
183 			error(buf);
184 
185 		clean = FILE_SECURE;
186 		cp(sbuf2, sbuf, PERM_SECURE);
187 		sdp = dbopen(sbuf,
188 		    O_RDWR|O_EXCL, PERM_SECURE, DB_HASH, &openinfo);
189 		if (sdp == NULL)
190 			error(sbuf);
191 
192 		/*
193 		 * Do some trouble to check if we should store this users
194 		 * uid. Don't use getpwnam/getpwuid as that interferes
195 		 * with NIS.
196 		 */
197 		pw_db = dbopen(_PATH_MP_DB, O_RDONLY, 0, DB_HASH, NULL);
198 		if (!pw_db)
199 			error(_MP_DB);
200 		buf[0] = _PW_KEYBYNAME;
201 		len = strlen(username);
202 
203 		/* Only check that username fits in buffer */
204 		memmove(buf + 1, username, MIN(len, sizeof(buf) - 1));
205 		key.data = (u_char *)buf;
206 		key.size = len + 1;
207 		if ((pw_db->get)(pw_db, &key, &data, 0) == 0) {
208 			p = (char *)data.data;
209 
210 			/* jump over pw_name and pw_passwd, to get to pw_uid */
211 			while (*p++)
212 				;
213 			while (*p++)
214 				;
215 
216 			buf[0] = _PW_KEYBYUID;
217 			memmove(buf + 1, p, sizeof(int));
218 			key.data = (u_char *)buf;
219 			key.size = sizeof(int) + 1;
220 
221 			if ((pw_db->get)(pw_db, &key, &data, 0) == 0) {
222 				/* First field of data.data holds pw_pwname */
223 				if (!strcmp(data.data, username))
224 					methoduid = 0;
225 				else
226 					methoduid = R_NOOVERWRITE;
227 			} else {
228 				methoduid = R_NOOVERWRITE;
229 			}
230 		} else {
231 			methoduid = R_NOOVERWRITE;
232 		}
233 		if ((pw_db->close)(pw_db))
234 			error("close pw_db");
235 		method = 0;
236 	} else {
237 		dp = dbopen(buf,
238 		    O_RDWR|O_CREAT|O_EXCL, PERM_INSECURE, DB_HASH, &openinfo);
239 		if (dp == NULL)
240 			error(buf);
241 		clean = FILE_INSECURE;
242 
243 		sdp = dbopen(sbuf,
244 		    O_RDWR|O_CREAT|O_EXCL, PERM_SECURE, DB_HASH, &openinfo);
245 		if (sdp == NULL)
246 			error(sbuf);
247 		clean = FILE_SECURE;
248 
249 		method = R_NOOVERWRITE;
250 		methoduid = R_NOOVERWRITE;
251 	}
252 
253 	/*
254 	 * Open file for old password file.  Minor trickiness -- don't want to
255 	 * chance the file already existing, since someone (stupidly) might
256 	 * still be using this for permission checking.  So, open it first and
257 	 * fdopen the resulting fd.  The resulting file should be readable by
258 	 * everyone.
259 	 */
260 	if (makeold) {
261 		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
262 		if ((tfd = open(buf,
263 		    O_WRONLY|O_CREAT|O_EXCL, PERM_INSECURE)) < 0)
264 			error(buf);
265 		if ((oldfp = fdopen(tfd, "w")) == NULL)
266 			error(buf);
267 		clean = FILE_ORIG;
268 	}
269 
270 	/*
271 	 * The databases actually contain three copies of the original data.
272 	 * Each password file entry is converted into a rough approximation
273 	 * of a ``struct passwd'', with the strings placed inline.  This
274 	 * object is then stored as the data for three separate keys.  The
275 	 * first key * is the pw_name field prepended by the _PW_KEYBYNAME
276 	 * character.  The second key is the pw_uid field prepended by the
277 	 * _PW_KEYBYUID character.  The third key is the line number in the
278 	 * original file prepended by the _PW_KEYBYNUM character.  (The special
279 	 * characters are prepended to ensure that the keys do not collide.)
280 	 */
281 	ypcnt = 1;
282 	data.data = (u_char *)buf;
283 	sdata.data = (u_char *)sbuf;
284 	key.data = (u_char *)tbuf;
285 	for (cnt = 1; scan(fp, &pwd); ++cnt) {
286 		if (!is_comment &&
287 		    (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-'))
288 			yp_enabled = 1;
289 #define	COMPACT(e)	t = e; while ((*p++ = *t++));
290 		if (!is_comment &&
291 		    (!username || (strcmp(username, pwd.pw_name) == 0))) {
292 			/* Create insecure data. */
293 			p = buf;
294 			COMPACT(pwd.pw_name);
295 			COMPACT("*");
296 			memmove(p, &pwd.pw_uid, sizeof(int));
297 			p += sizeof(int);
298 			memmove(p, &pwd.pw_gid, sizeof(int));
299 			p += sizeof(int);
300 			memmove(p, &pwd.pw_change, sizeof(time_t));
301 			p += sizeof(time_t);
302 			COMPACT(pwd.pw_class);
303 			COMPACT(pwd.pw_gecos);
304 			COMPACT(pwd.pw_dir);
305 			COMPACT(pwd.pw_shell);
306 			memmove(p, &pwd.pw_expire, sizeof(time_t));
307 			p += sizeof(time_t);
308 			memmove(p, &pwd.pw_fields, sizeof pwd.pw_fields);
309 			p += sizeof pwd.pw_fields;
310 			data.size = p - buf;
311 
312 			/* Create secure data. */
313 			p = sbuf;
314 			COMPACT(pwd.pw_name);
315 			COMPACT(pwd.pw_passwd);
316 			memmove(p, &pwd.pw_uid, sizeof(int));
317 			p += sizeof(int);
318 			memmove(p, &pwd.pw_gid, sizeof(int));
319 			p += sizeof(int);
320 			memmove(p, &pwd.pw_change, sizeof(time_t));
321 			p += sizeof(time_t);
322 			COMPACT(pwd.pw_class);
323 			COMPACT(pwd.pw_gecos);
324 			COMPACT(pwd.pw_dir);
325 			COMPACT(pwd.pw_shell);
326 			memmove(p, &pwd.pw_expire, sizeof(time_t));
327 			p += sizeof(time_t);
328 			memmove(p, &pwd.pw_fields, sizeof pwd.pw_fields);
329 			p += sizeof pwd.pw_fields;
330 			sdata.size = p - sbuf;
331 
332 			/* Store insecure by name. */
333 			tbuf[0] = _PW_KEYBYNAME;
334 			len = strlen(pwd.pw_name);
335 			memmove(tbuf + 1, pwd.pw_name, len);
336 			key.size = len + 1;
337 			if ((dp->put)(dp, &key, &data, method) == -1)
338 				error("put");
339 
340 			/* Store insecure by number. */
341 			tbuf[0] = _PW_KEYBYNUM;
342 			memmove(tbuf + 1, &cnt, sizeof(cnt));
343 			key.size = sizeof(cnt) + 1;
344 			if ((dp->put)(dp, &key, &data, method) == -1)
345 				error("put");
346 
347 			/* Store insecure by uid. */
348 			tbuf[0] = _PW_KEYBYUID;
349 			memmove(tbuf + 1, &pwd.pw_uid, sizeof(pwd.pw_uid));
350 			key.size = sizeof(pwd.pw_uid) + 1;
351 			if ((dp->put)(dp, &key, &data, methoduid) == -1)
352 				error("put");
353 
354 			/* Store secure by name. */
355 			tbuf[0] = _PW_KEYBYNAME;
356 			len = strlen(pwd.pw_name);
357 			memmove(tbuf + 1, pwd.pw_name, len);
358 			key.size = len + 1;
359 			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
360 				error("put");
361 
362 			/* Store secure by number. */
363 			tbuf[0] = _PW_KEYBYNUM;
364 			memmove(tbuf + 1, &cnt, sizeof(cnt));
365 			key.size = sizeof(cnt) + 1;
366 			if ((sdp->put)(sdp, &key, &sdata, method) == -1)
367 				error("put");
368 
369 			/* Store secure by uid. */
370 			tbuf[0] = _PW_KEYBYUID;
371 			memmove(tbuf + 1, &pwd.pw_uid, sizeof(pwd.pw_uid));
372 			key.size = sizeof(pwd.pw_uid) + 1;
373 			if ((sdp->put)(sdp, &key, &sdata, methoduid) == -1)
374 				error("put");
375 
376 			/* Store insecure and secure special plus and special minus */
377 			if (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-') {
378 				tbuf[0] = _PW_KEYYPBYNUM;
379 				memmove(tbuf + 1, &ypcnt, sizeof(cnt));
380 				ypcnt++;
381 				key.size = sizeof(cnt) + 1;
382 				if ((dp->put)(dp, &key, &data, method) == -1)
383 					error("put");
384 				if ((sdp->put)(sdp, &key, &sdata, method) == -1)
385 					error("put");
386 			}
387 		}
388 		/* Create original format password file entry */
389 		if (is_comment && makeold){	/* copy comments */
390 			if (fprintf(oldfp, "%s\n", line) < 0)
391 				error("write old");
392 		} else if (makeold) {
393 			char uidstr[20];
394 			char gidstr[20];
395 
396 			snprintf(uidstr, sizeof(uidstr), "%d", pwd.pw_uid);
397 			snprintf(gidstr, sizeof(gidstr), "%d", pwd.pw_gid);
398 
399 			if (fprintf(oldfp, "%s:*:%s:%s:%s:%s:%s\n",
400 			    pwd.pw_name, pwd.pw_fields & _PWF_UID ? uidstr : "",
401 			    pwd.pw_fields & _PWF_GID ? gidstr : "",
402 			    pwd.pw_gecos, pwd.pw_dir, pwd.pw_shell) < 0)
403 				error("write old");
404 		}
405 	}
406 	/* If YP enabled, set flag. */
407 	if (yp_enabled) {
408 		buf[0] = yp_enabled + 2;
409 		data.size = 1;
410 		tbuf[0] = _PW_KEYYPENABLED;
411 		key.size = 1;
412 		if ((dp->put)(dp, &key, &data, method) == -1)
413 			error("put");
414 		if ((sdp->put)(sdp, &key, &data, method) == -1)
415 			error("put");
416 	}
417 
418 	if ((dp->close)(dp) == -1)
419 		error("close");
420 	if ((sdp->close)(sdp) == -1)
421 		error("close");
422 	if (makeold) {
423 		(void)fflush(oldfp);
424 		if (fclose(oldfp) == EOF)
425 			error("close old");
426 	}
427 
428 	/* Set master.passwd permissions, in case caller forgot. */
429 	(void)fchmod(fileno(fp), S_IRUSR|S_IWUSR);
430 	if (fclose(fp) == EOF)
431 		error("close fp");
432 
433 	/* Install as the real password files. */
434 	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
435 	(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _MP_DB);
436 	mv(buf, buf2);
437 	(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _SMP_DB);
438 	(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _SMP_DB);
439 	mv(buf, buf2);
440 	if (makeold) {
441 		(void)snprintf(buf2, sizeof(buf2), "%s/%s", prefix, _PASSWD);
442 		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
443 		mv(buf, buf2);
444 	}
445 	/*
446 	 * Move the master password LAST -- chpass(1), passwd(1) and vipw(8)
447 	 * all use flock(2) on it to block other incarnations of themselves.
448 	 * The rename means that everything is unlocked, as the original file
449 	 * can no longer be accessed.
450 	 */
451 	(void)snprintf(buf, sizeof(buf), "%s/%s", prefix, _MASTERPASSWD);
452 	mv(pname, buf);
453 	exit(0);
454 }
455 
456 int
457 scan(fp, pw)
458 	FILE *fp;
459 	struct passwd *pw;
460 {
461 	static int lcnt;
462 	char *p;
463 
464 	if (!fgets(line, sizeof(line), fp))
465 		return (0);
466 	++lcnt;
467 	/*
468 	 * ``... if I swallow anything evil, put your fingers down my
469 	 * throat...''
470 	 *	-- The Who
471 	 */
472 	if (!(p = strchr(line, '\n'))) {
473 		warnx("line too long");
474 		goto fmt;
475 
476 	}
477 	*p = '\0';
478 
479 #ifdef PASSWD_IGNORE_COMMENTS
480 	/*
481 	 * Ignore comments: ^[ \t]*#
482 	 */
483 	for (p = line; *p != '\0'; p++)
484 		if (*p != ' ' && *p != '\t')
485 			break;
486 	if (*p == '#' || *p == '\0') {
487 		is_comment = 1;
488 		return(1);
489 	} else
490 		is_comment = 0;
491 #endif
492 
493 	if (!pw_scan(line, pw)) {
494 		warnx("at line #%d", lcnt);
495 fmt:		errno = EFTYPE;	/* XXX */
496 		error(pname);
497 	}
498 
499 	return (1);
500 }
501 
502 void
503 cp(from, to, mode)
504 	char *from, *to;
505 	mode_t mode;
506 {
507 	static char buf[MAXBSIZE];
508 	int from_fd, rcount, to_fd, wcount;
509 
510 	if ((from_fd = open(from, O_RDONLY, 0)) < 0)
511 		error(from);
512 	if ((to_fd = open(to, O_WRONLY|O_CREAT|O_EXCL, mode)) < 0)
513 		error(to);
514 	while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
515 		wcount = write(to_fd, buf, rcount);
516 		if (rcount != wcount || wcount == -1) {
517 			int sverrno = errno;
518 
519 			(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
520 			errno = sverrno;
521 			error(buf);
522 		}
523 	}
524 	if (rcount < 0) {
525 		int sverrno = errno;
526 
527 		(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
528 		errno = sverrno;
529 		error(buf);
530 	}
531 }
532 
533 
534 void
535 mv(from, to)
536 	char *from, *to;
537 {
538 	char buf[MAXPATHLEN];
539 
540 	if (rename(from, to)) {
541 		int sverrno = errno;
542 		(void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
543 		errno = sverrno;
544 		error(buf);
545 	}
546 }
547 
548 void
549 error(name)
550 	char *name;
551 {
552 
553 	warn("%s", name);
554 	cleanup();
555 	exit(1);
556 }
557 
558 void
559 cleanup()
560 {
561 	char buf[MAXPATHLEN];
562 
563 	switch(clean) {
564 	case FILE_ORIG:
565 		(void)snprintf(buf, sizeof(buf), "%s.orig", pname);
566 		(void)unlink(buf);
567 		/* FALLTHROUGH */
568 	case FILE_SECURE:
569 		(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _SMP_DB);
570 		(void)unlink(buf);
571 		/* FALLTHROUGH */
572 	case FILE_INSECURE:
573 		(void)snprintf(buf, sizeof(buf), "%s/%s.tmp", prefix, _MP_DB);
574 		(void)unlink(buf);
575 	}
576 }
577 
578 static void
579 usage()
580 {
581 
582 	(void)fprintf(stderr,
583 "usage: pwd_mkdb [-C] [-p] [-d <dest dir>] [-s <cachesize>] [-u <local username>] file\n");
584 	exit(1);
585 }
586