pwd_mkdb.c revision 1.45 1 /* $NetBSD: pwd_mkdb.c,v 1.45 2009/06/19 16:46:52 christos Exp $ */
2
3 /*
4 * Copyright (c) 2000, 2009 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28
29 /*
30 * Copyright (c) 1991, 1993, 1994
31 * The Regents of the University of California. All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. Neither the name of the University nor the names of its contributors
42 * may be used to endorse or promote products derived from this software
43 * without specific prior written permission.
44 *
45 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * SUCH DAMAGE.
56 */
57
58 /*
59 * Portions Copyright(C) 1994, Jason Downs. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
66 * 2. Redistributions in binary form must reproduce the above copyright
67 * notice, this list of conditions and the following disclaimer in the
68 * documentation and/or other materials provided with the distribution.
69 *
70 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS
71 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
72 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
73 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT,
74 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
75 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
76 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
77 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
78 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
79 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
80 * SUCH DAMAGE.
81 */
82
83 #if HAVE_NBTOOL_CONFIG_H
84 #include "nbtool_config.h"
85 #endif
86
87 #include <sys/cdefs.h>
88 #if !defined(lint)
89 __COPYRIGHT("@(#) Copyright (c) 2000, 2009\
90 The NetBSD Foundation, Inc. All rights reserved.\
91 Copyright (c) 1991, 1993, 1994\
92 The Regents of the University of California. All rights reserved.");
93 __SCCSID("from: @(#)pwd_mkdb.c 8.5 (Berkeley) 4/20/94");
94 __RCSID("$NetBSD: pwd_mkdb.c,v 1.45 2009/06/19 16:46:52 christos Exp $");
95 #endif /* not lint */
96
97 #if HAVE_NBTOOL_CONFIG_H
98 #include "compat_pwd.h"
99 #else
100 #include <pwd.h>
101 #endif
102
103 #include <sys/param.h>
104 #include <sys/stat.h>
105 #include <sys/types.h>
106
107 #ifndef HAVE_NBTOOL_CONFIG_H
108 #include <machine/bswap.h>
109 #endif
110
111 #include <db.h>
112 #include <err.h>
113 #include <errno.h>
114 #include <fcntl.h>
115 #include <limits.h>
116 #include <signal.h>
117 #include <stdio.h>
118 #include <stdlib.h>
119 #include <string.h>
120 #include <unistd.h>
121 #include <util.h>
122
123 #define MAX_CACHESIZE 8*1024*1024
124 #define MIN_CACHESIZE 2*1024*1024
125
126 #define PERM_INSECURE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
127 #define PERM_SECURE (S_IRUSR | S_IWUSR)
128
129 #if HAVE_NBTOOL_CONFIG_H
130 static const char __yp_token[] = "__YP!";
131 #else
132 /* Pull this out of the C library. */
133 extern const char __yp_token[];
134 #endif
135
136 static HASHINFO openinfo = {
137 4096, /* bsize */
138 32, /* ffactor */
139 256, /* nelem */
140 0, /* cachesize */
141 NULL, /* hash() */
142 0 /* lorder */
143 };
144
145 #define FILE_INSECURE 0x01
146 #define FILE_SECURE 0x02
147 #define FILE_ORIG 0x04
148
149
150 struct pwddb {
151 DB *db;
152 char dbname[MAX(MAXPATHLEN, LINE_MAX * 2)];
153 const char *fname;
154 uint32_t rversion;
155 uint32_t wversion;
156 };
157
158 static char *pname; /* password file name */
159 static char prefix[MAXPATHLEN];
160 static char oldpwdfile[MAX(MAXPATHLEN, LINE_MAX * 2)];
161 static int lorder = BYTE_ORDER;
162 static int clean;
163 static int verbose;
164 static int warning;
165 static struct pwddb sdb, idb;
166
167
168 void bailout(void) __attribute__((__noreturn__));
169 void cp(const char *, const char *, mode_t);
170 void deldbent(struct pwddb *, int, void *);
171 void error(const char *);
172 int getdbent(struct pwddb *, int, void *, struct passwd **);
173 void inconsistency(void);
174 void install(const char *, const char *);
175 int main(int, char **);
176 void putdbents(struct pwddb *, struct passwd *, const char *, int, int,
177 u_int, u_int);
178 void putyptoken(struct pwddb *);
179 void rm(const char *);
180 int scan(FILE *, struct passwd *, int *, int *);
181 void usage(void) __attribute__((__noreturn__));
182 void wr_error(const char *);
183 uint32_t getversion(const char *);
184 void setversion(struct pwddb *);
185
186 #ifndef __lint__
187 #define SWAP(sw) \
188 ((sizeof(sw) == 2 ? (typeof(sw))bswap16((uint16_t)sw) : \
189 (sizeof(sw) == 4 ? (typeof(sw))bswap32((uint32_t)sw) : \
190 (sizeof(sw) == 8 ? (typeof(sw))bswap64((uint64_t)sw) : (abort(), 0)))))
191 #else
192 #define SWAP(sw) sw
193 #endif
194
195 static void
196 closedb(struct pwddb *db)
197 {
198 if ((*db->db->close)(db->db) < 0)
199 wr_error(db->dbname);
200 }
201
202 static void
203 opendb(struct pwddb *db, const char *dbname, const char *username,
204 uint32_t req_version, int flags, mode_t perm)
205 {
206 char buf[MAXPATHLEN];
207
208 (void)snprintf(db->dbname, sizeof(db->dbname), "%s%s.tmp", prefix,
209 dbname);
210
211 if (username != NULL) {
212 (void)snprintf(buf, sizeof(buf), "%s%s", prefix, dbname);
213 cp(buf, db->dbname, perm);
214 }
215
216 db->db = dbopen(db->dbname, flags, perm, DB_HASH, &openinfo);
217 if (db->db == NULL)
218 error(db->dbname);
219
220 db->fname = dbname;
221 db->rversion = getversion(dbname);
222 if (req_version == ~0U)
223 db->wversion = db->rversion;
224 else
225 db->wversion = req_version;
226
227 if (warning && db->rversion == 0 && db->wversion == 0) {
228 warnx("Database %s is a version %u database.",
229 db->fname, db->rversion);
230 warnx("Use %s -V 1 to upgrade once you've recompiled "
231 "all your binaries.", getprogname());
232 }
233 if (db->wversion != db->rversion) {
234 if (username != NULL) {
235 (void)fprintf(stderr, "%s: you cannot change a single "
236 "record from version %u to version %u\n",
237 getprogname(), db->rversion, db->wversion);
238 bailout();
239 } else if (verbose) {
240 (void)fprintf(stderr, "%s: changing %s from version "
241 "%u to version %u\n",
242 getprogname(), db->fname,
243 db->rversion, db->wversion);
244 }
245 } else {
246 if (verbose)
247 (void)fprintf(stderr, "%s: %s version %u "
248 "requested %u\n", getprogname(), db->fname,
249 db->rversion, db->wversion);
250 }
251
252 setversion(db);
253 }
254
255 int
256 main(int argc, char *argv[])
257 {
258 int ch, makeold, tfd, lineno, found, rv, hasyp, secureonly;
259 struct passwd pwd, *tpwd;
260 char *username;
261 FILE *fp, *oldfp;
262 sigset_t set;
263 u_int dbflg, uid_dbflg;
264 int newuser, olduid, flags;
265 struct stat st;
266 u_int cachesize;
267 uint32_t req_version;
268
269 prefix[0] = '\0';
270 makeold = 0;
271 oldfp = NULL;
272 username = NULL;
273 hasyp = 0;
274 secureonly = 0;
275 found = 0;
276 newuser = 0;
277 cachesize = 0;
278 verbose = 0;
279 warning = 0;
280 req_version = ~0U;
281
282 while ((ch = getopt(argc, argv, "BLc:d:psu:V:vw")) != -1)
283 switch (ch) {
284 case 'B': /* big-endian output */
285 lorder = BIG_ENDIAN;
286 break;
287 case 'L': /* little-endian output */
288 lorder = LITTLE_ENDIAN;
289 break;
290 case 'c':
291 cachesize = atoi(optarg) * 1024 * 1024;
292 break;
293 case 'd': /* set prefix */
294 (void)strlcpy(prefix, optarg, sizeof(prefix));
295 break;
296 case 'p': /* create V7 "file.orig" */
297 makeold = 1;
298 break;
299 case 's': /* modify secure db only */
300 secureonly = 1;
301 break;
302 case 'u': /* modify one user only */
303 username = optarg;
304 break;
305 case 'V':
306 req_version = (uint32_t)atoi(optarg);
307 if (req_version > 1)
308 err(1, "Unknown version %u\n", req_version);
309 break;
310 case 'v':
311 verbose++;
312 break;
313 case 'w':
314 warning++;
315 break;
316 case '?':
317 default:
318 usage();
319 }
320 argc -= optind;
321 argv += optind;
322
323 if (argc != 1)
324 usage();
325 if (username != NULL)
326 if (username[0] == '+' || username[0] == '-')
327 usage();
328 if (secureonly)
329 makeold = 0;
330
331 /*
332 * This could be changed to allow the user to interrupt.
333 * Probably not worth the effort.
334 */
335 (void)sigemptyset(&set);
336 (void)sigaddset(&set, SIGTSTP);
337 (void)sigaddset(&set, SIGHUP);
338 (void)sigaddset(&set, SIGINT);
339 (void)sigaddset(&set, SIGQUIT);
340 (void)sigaddset(&set, SIGTERM);
341 (void)sigprocmask(SIG_BLOCK, &set, (sigset_t *)NULL);
342
343 /* We don't care what the user wants. */
344 (void)umask(0);
345
346 if (username == NULL)
347 flags = O_RDWR | O_CREAT | O_EXCL;
348 else
349 flags = O_RDWR;
350
351 pname = *argv;
352 /* Open the original password file */
353 if ((fp = fopen(pname, "r")) == NULL)
354 error(pname);
355
356 openinfo.lorder = lorder;
357
358 if (fstat(fileno(fp), &st) == -1)
359 error(pname);
360
361 if (cachesize) {
362 openinfo.cachesize = cachesize;
363 } else {
364 /* Tweak openinfo values for large passwd files. */
365 cachesize = (u_int)(st.st_size * 20);
366 if (cachesize > MAX_CACHESIZE)
367 cachesize = MAX_CACHESIZE;
368 else if (cachesize < MIN_CACHESIZE)
369 cachesize = MIN_CACHESIZE;
370 openinfo.cachesize = cachesize;
371 }
372
373 /* Open the temporary insecure password database. */
374 if (!secureonly) {
375 opendb(&idb, _PATH_MP_DB, username, req_version,
376 flags, PERM_INSECURE);
377 clean |= FILE_INSECURE;
378 }
379
380
381 /* Open the temporary encrypted password database. */
382 opendb(&sdb, _PATH_SMP_DB, username, req_version, flags, PERM_SECURE);
383 clean |= FILE_SECURE;
384
385 /*
386 * Open file for old password file. Minor trickiness -- don't want to
387 * chance the file already existing, since someone (stupidly) might
388 * still be using this for permission checking. So, open it first and
389 * fdopen the resulting fd. The resulting file should be readable by
390 * everyone.
391 */
392 if (makeold) {
393 (void)snprintf(oldpwdfile, sizeof(oldpwdfile), "%s.orig",
394 pname);
395 if ((tfd = open(oldpwdfile, O_WRONLY | O_CREAT | O_EXCL,
396 PERM_INSECURE)) < 0)
397 error(oldpwdfile);
398 clean |= FILE_ORIG;
399 if ((oldfp = fdopen(tfd, "w")) == NULL)
400 error(oldpwdfile);
401 }
402
403 if (username != NULL) {
404 uid_dbflg = 0;
405 dbflg = 0;
406
407 /*
408 * Determine if this is a new entry.
409 */
410 if (getdbent(&sdb, _PW_KEYBYNAME, username, &tpwd))
411 newuser = 1;
412 else {
413 newuser = 0;
414 olduid = tpwd->pw_uid;
415 }
416
417 } else {
418 uid_dbflg = R_NOOVERWRITE;
419 dbflg = R_NOOVERWRITE;
420 }
421
422 /*
423 * If we see something go by that looks like YP, we save a special
424 * pointer record, which if YP is enabled in the C lib, will speed
425 * things up.
426 */
427 for (lineno = 0; scan(fp, &pwd, &flags, &lineno);) {
428 /*
429 * Create original format password file entry.
430 */
431 if (makeold) {
432 (void)fprintf(oldfp, "%s:*:%d:%d:%s:%s:%s\n",
433 pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_gecos,
434 pwd.pw_dir, pwd.pw_shell);
435 if (ferror(oldfp))
436 wr_error(oldpwdfile);
437 }
438
439 if (username == NULL) {
440 /* Look like YP? */
441 if (pwd.pw_name[0] == '+' || pwd.pw_name[0] == '-')
442 hasyp++;
443
444 /* Warn about potentially unsafe uid/gid overrides. */
445 if (pwd.pw_name[0] == '+') {
446 if ((flags & _PASSWORD_NOUID) == 0 &&
447 pwd.pw_uid == 0)
448 warnx("line %d: superuser override "
449 "in YP inclusion", lineno);
450 if ((flags & _PASSWORD_NOGID) == 0 &&
451 pwd.pw_gid == 0)
452 warnx("line %d: wheel override "
453 "in YP inclusion", lineno);
454 }
455
456 /* Write the database entry out. */
457 if (!secureonly)
458 putdbents(&idb, &pwd, "*", flags, lineno, dbflg,
459 uid_dbflg);
460 continue;
461 } else if (strcmp(username, pwd.pw_name) != 0)
462 continue;
463
464 if (found) {
465 warnx("user `%s' listed twice in password file",
466 username);
467 bailout();
468 }
469
470 /*
471 * Ensure that the text file and database agree on
472 * which line the record is from.
473 */
474 rv = getdbent(&sdb, _PW_KEYBYNUM, &lineno, &tpwd);
475 if (newuser) {
476 if (rv == 0)
477 inconsistency();
478 } else if (rv == -1 ||
479 strcmp(username, tpwd->pw_name) != 0)
480 inconsistency();
481 else if ((uid_t)olduid != pwd.pw_uid) {
482 /*
483 * If we're changing UID, remove the BYUID
484 * record for the old UID only if it has the
485 * same username.
486 */
487 if (!getdbent(&sdb, _PW_KEYBYUID, &olduid, &tpwd)) {
488 if (strcmp(username, tpwd->pw_name) == 0) {
489 if (!secureonly)
490 deldbent(&idb, _PW_KEYBYUID,
491 &olduid);
492 deldbent(&sdb, _PW_KEYBYUID, &olduid);
493 }
494 } else
495 inconsistency();
496 }
497
498 /*
499 * If there's an existing BYUID record for the new UID and
500 * the username doesn't match then be sure not to overwrite
501 * it.
502 */
503 if (!getdbent(&sdb, _PW_KEYBYUID, &pwd.pw_uid, &tpwd))
504 if (strcmp(username, tpwd->pw_name) != 0)
505 uid_dbflg = R_NOOVERWRITE;
506
507 /* Write the database entries out */
508 if (!secureonly)
509 putdbents(&idb, &pwd, "*", flags, lineno, dbflg,
510 uid_dbflg);
511 putdbents(&sdb, &pwd, pwd.pw_passwd, flags, lineno, dbflg,
512 uid_dbflg);
513
514 found = 1;
515 if (!makeold)
516 break;
517 }
518
519 if (!secureonly) {
520 /* Store YP token if needed. */
521 if (hasyp)
522 putyptoken(&idb);
523
524 /* Close the insecure database. */
525 closedb(&idb);
526 }
527
528 /*
529 * If rebuilding the databases, we re-parse the text file and write
530 * the secure entries out in a separate pass.
531 */
532 if (username == NULL) {
533 rewind(fp);
534 for (lineno = 0; scan(fp, &pwd, &flags, &lineno);)
535 putdbents(&sdb, &pwd, pwd.pw_passwd, flags,
536 lineno, dbflg, uid_dbflg);
537
538 /* Store YP token if needed. */
539 if (hasyp)
540 putyptoken(&sdb);
541 } else if (!found) {
542 warnx("user `%s' not found in password file", username);
543 bailout();
544 }
545
546 /* Close the secure database. */
547 closedb(&sdb);
548
549 /* Install as the real password files. */
550 if (!secureonly)
551 install(idb.dbname, idb.fname);
552 install(sdb.dbname, sdb.fname);
553
554 /* Install the V7 password file. */
555 if (makeold) {
556 if (fflush(oldfp) == EOF)
557 wr_error(oldpwdfile);
558 if (fclose(oldfp) == EOF)
559 wr_error(oldpwdfile);
560 install(oldpwdfile, _PATH_PASSWD);
561 }
562
563 /* Set master.passwd permissions, in case caller forgot. */
564 (void)fchmod(fileno(fp), S_IRUSR|S_IWUSR);
565 if (fclose(fp) == EOF)
566 wr_error(pname);
567
568 /*
569 * Move the temporary master password file LAST -- chpass(1),
570 * passwd(1), vipw(8) and friends all use its existence to block
571 * other incarnations of themselves. The rename means that
572 * everything is unlocked, as the original file can no longer be
573 * accessed.
574 */
575 install(pname, _PATH_MASTERPASSWD);
576 exit(EXIT_SUCCESS);
577 /* NOTREACHED */
578 }
579
580 int
581 scan(FILE *fp, struct passwd *pw, int *flags, int *lineno)
582 {
583 static char line[LINE_MAX];
584 char *p;
585 int oflags;
586
587 if (fgets(line, (int)sizeof(line), fp) == NULL)
588 return (0);
589 (*lineno)++;
590
591 /*
592 * ``... if I swallow anything evil, put your fingers down my
593 * throat...''
594 * -- The Who
595 */
596 if ((p = strchr(line, '\n')) == NULL) {
597 warnx("line too long");
598 errno = EFTYPE; /* XXX */
599 error(pname);
600 }
601 *p = '\0';
602 if (strcmp(line, "+") == 0) {
603 /* pw_scan() can't handle "+" */
604 (void)strcpy(line, "+:::::::::");
605 }
606 oflags = 0;
607 if (!pw_scan(line, pw, &oflags)) {
608 warnx("at line #%d", *lineno);
609 errno = EFTYPE; /* XXX */
610 error(pname);
611 }
612 *flags = oflags;
613
614 return (1);
615 }
616
617 void
618 install(const char *from, const char *to)
619 {
620 char buf[MAXPATHLEN];
621 char errbuf[BUFSIZ];
622 int sverrno;
623
624 (void)snprintf(buf, sizeof(buf), "%s%s", prefix, to);
625 if (rename(from, buf)) {
626 sverrno = errno;
627 (void)snprintf(errbuf, sizeof(errbuf), "%s to %s", from, buf);
628 errno = sverrno;
629 error(errbuf);
630 }
631 }
632
633 void
634 rm(const char *victim)
635 {
636
637 if (unlink(victim) < 0)
638 warn("unlink(%s)", victim);
639 }
640
641 void
642 cp(const char *from, const char *to, mode_t mode)
643 {
644 static char buf[MAXBSIZE];
645 int from_fd, to_fd, sverrno;
646 ssize_t rcount, wcount;
647
648 if ((from_fd = open(from, O_RDONLY, 0)) < 0)
649 error(from);
650 if ((to_fd = open(to, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0)
651 error(to);
652 while ((rcount = read(from_fd, buf, MAXBSIZE)) > 0) {
653 wcount = write(to_fd, buf, (size_t)rcount);
654 if (rcount != wcount || wcount == -1) {
655 sverrno = errno;
656 (void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
657 errno = sverrno;
658 error(buf);
659 }
660 }
661
662 if (rcount < 0) {
663 sverrno = errno;
664 (void)snprintf(buf, sizeof(buf), "%s to %s", from, to);
665 errno = sverrno;
666 error(buf);
667 }
668 }
669
670 void
671 wr_error(const char *str)
672 {
673 char errbuf[BUFSIZ];
674 int sverrno;
675
676 sverrno = errno;
677
678 (void)snprintf(errbuf, sizeof(errbuf),
679 "attempt to write %s failed", str);
680
681 errno = sverrno;
682 error(errbuf);
683 }
684
685 void
686 error(const char *str)
687 {
688
689 warn("%s", str);
690 bailout();
691 }
692
693 void
694 inconsistency(void)
695 {
696
697 warnx("text files and databases are inconsistent");
698 warnx("re-build the databases without -u");
699 bailout();
700 }
701
702 void
703 bailout(void)
704 {
705
706 if ((clean & FILE_ORIG) != 0)
707 rm(oldpwdfile);
708 if ((clean & FILE_SECURE) != 0)
709 rm(sdb.dbname);
710 if ((clean & FILE_INSECURE) != 0)
711 rm(idb.dbname);
712
713 exit(EXIT_FAILURE);
714 }
715
716 uint32_t
717 getversion(const char *fname)
718 {
719 DBT data, key;
720 int ret;
721 uint32_t version = 0;
722 DB *db;
723
724 db = dbopen(fname, O_RDONLY, PERM_INSECURE, DB_HASH, NULL);
725 if (db == NULL) {
726 /* If we are building on a separate root, assume version 1 */
727 if (errno == EACCES && prefix[0])
728 return 1;
729 warn("Cannot open database %s", fname);
730 bailout();
731 }
732 key.data = __UNCONST("VERSION");
733 key.size = strlen((const char *)key.data) + 1;
734
735 switch (ret = (*db->get)(db, &key, &data, 0)) {
736 case -1: /* Error */
737 warn("Cannot get VERSION record from database");
738 goto out;
739 case 0:
740 if (data.size != sizeof(version)) {
741 warnx("Bad VERSION record in database");
742 goto out;
743 }
744 (void)memcpy(&version, data.data, sizeof(version));
745 /*FALLTHROUGH*/
746 case 1:
747 if (ret == 1)
748 warnx("Database %s has no version info", fname);
749 (*db->close)(db);
750 return version;
751 default:
752 warnx("internal error db->get returns %d", ret);
753 goto out;
754 }
755 out:
756 (*db->close)(db);
757 bailout();
758 /*NOTREACHED*/
759 }
760
761 void
762 setversion(struct pwddb *db)
763 {
764 DBT data, key;
765 key.data = __UNCONST("VERSION");
766 key.size = strlen((const char *)key.data) + 1;
767
768 data.data = &db->wversion;
769 data.size = sizeof(uint32_t);
770
771 if ((*db->db->put)(db->db, &key, &data, 0) != 0) {
772 warn("Can't write VERSION record to %s", db->dbname);
773 bailout();
774 }
775 }
776
777
778 /*
779 * Write entries to a database for a single user.
780 *
781 * The databases actually contain three copies of the original data. Each
782 * password file entry is converted into a rough approximation of a ``struct
783 * passwd'', with the strings placed inline. This object is then stored as
784 * the data for three separate keys. The first key * is the pw_name field
785 * prepended by the _PW_KEYBYNAME character. The second key is the pw_uid
786 * field prepended by the _PW_KEYBYUID character. The third key is the line
787 * number in the original file prepended by the _PW_KEYBYNUM character.
788 * (The special characters are prepended to ensure that the keys do not
789 * collide.)
790 */
791 #define COMPACT(e) for (t = e; (*p++ = *t++) != '\0';)
792
793 void
794 putdbents(struct pwddb *db, struct passwd *pw, const char *passwd, int flags,
795 int lineno, u_int dbflg, u_int uid_dbflg)
796 {
797 struct passwd pwd;
798 char buf[MAX(MAXPATHLEN, LINE_MAX * 2)], tbuf[1024], *p;
799 DBT data, key;
800 const char *t;
801 u_int32_t x;
802 size_t len;
803
804 (void)memcpy(&pwd, pw, sizeof(pwd));
805 data.data = (u_char *)buf;
806 key.data = (u_char *)tbuf;
807
808 if (lorder != BYTE_ORDER) {
809 pwd.pw_uid = SWAP(pwd.pw_uid);
810 pwd.pw_gid = SWAP(pwd.pw_gid);
811 }
812
813 #define WRITEPWTIMEVAR(pwvar) \
814 do { \
815 if (db->wversion == 0 && \
816 /*CONSTCOND*/sizeof(pwvar) == sizeof(uint64_t)) { \
817 uint32_t tmp = (uint32_t)pwvar; \
818 if (lorder != BYTE_ORDER) \
819 tmp = SWAP(tmp); \
820 (void)memmove(p, &tmp, sizeof(tmp)); \
821 p += sizeof(tmp); \
822 } else if (db->wversion == 1 && \
823 /*CONSTCOND*/sizeof(pwvar) == sizeof(uint32_t)) { \
824 uint64_t tmp = pwvar; \
825 if (lorder != BYTE_ORDER) \
826 tmp = SWAP(tmp); \
827 (void)memmove(p, &tmp, sizeof(tmp)); \
828 p += sizeof(tmp); \
829 } else { \
830 if (lorder != BYTE_ORDER) \
831 pwvar = SWAP(pwvar); \
832 (void)memmove(p, &pwvar, sizeof(pwvar)); \
833 p += sizeof(pwvar); \
834 } \
835 } while (/*CONSTCOND*/0)
836
837 /* Create insecure data. */
838 p = buf;
839 COMPACT(pwd.pw_name);
840 COMPACT(passwd);
841 (void)memmove(p, &pwd.pw_uid, sizeof(pwd.pw_uid));
842 p += sizeof(pwd.pw_uid);
843 (void)memmove(p, &pwd.pw_gid, sizeof(pwd.pw_gid));
844 p += sizeof(pwd.pw_gid);
845 WRITEPWTIMEVAR(pwd.pw_change);
846 COMPACT(pwd.pw_class);
847 COMPACT(pwd.pw_gecos);
848 COMPACT(pwd.pw_dir);
849 COMPACT(pwd.pw_shell);
850 WRITEPWTIMEVAR(pwd.pw_expire);
851 x = flags;
852 if (lorder != BYTE_ORDER)
853 x = SWAP(x);
854 (void)memmove(p, &x, sizeof(x));
855 p += sizeof(flags);
856 data.size = p - buf;
857
858 /* Store insecure by name. */
859 tbuf[0] = _PW_KEYBYNAME;
860 len = strlen(pwd.pw_name);
861 (void)memmove(tbuf + 1, pwd.pw_name, len);
862 key.size = len + 1;
863 if ((*db->db->put)(db->db, &key, &data, dbflg) == -1)
864 wr_error(db->dbname);
865
866 /* Store insecure by number. */
867 tbuf[0] = _PW_KEYBYNUM;
868 x = lineno;
869 if (lorder != BYTE_ORDER)
870 x = SWAP(x);
871 (void)memmove(tbuf + 1, &x, sizeof(x));
872 key.size = sizeof(x) + 1;
873 if ((*db->db->put)(db->db, &key, &data, dbflg) == -1)
874 wr_error(db->dbname);
875
876 /* Store insecure by uid. */
877 tbuf[0] = _PW_KEYBYUID;
878 (void)memmove(tbuf + 1, &pwd.pw_uid, sizeof(pwd.pw_uid));
879 key.size = sizeof(pwd.pw_uid) + 1;
880 if ((*db->db->put)(db->db, &key, &data, uid_dbflg) == -1)
881 wr_error(db->dbname);
882 }
883
884 void
885 deldbent(struct pwddb *db, int type, void *keyp)
886 {
887 char tbuf[1024];
888 DBT key;
889 u_int32_t x;
890 size_t len;
891
892 key.data = (u_char *)tbuf;
893
894 switch (tbuf[0] = type) {
895 case _PW_KEYBYNAME:
896 len = strlen((char *)keyp);
897 (void)memcpy(tbuf + 1, keyp, len);
898 key.size = len + 1;
899 break;
900
901 case _PW_KEYBYNUM:
902 case _PW_KEYBYUID:
903 x = *(int *)keyp;
904 if (lorder != BYTE_ORDER)
905 x = SWAP(x);
906 (void)memmove(tbuf + 1, &x, sizeof(x));
907 key.size = sizeof(x) + 1;
908 break;
909 }
910
911 if ((*db->db->del)(db->db, &key, 0) == -1)
912 wr_error(db->dbname);
913 }
914
915 int
916 getdbent(struct pwddb *db, int type, void *keyp, struct passwd **tpwd)
917 {
918 static char buf[MAX(MAXPATHLEN, LINE_MAX * 2)];
919 static struct passwd pwd;
920 char tbuf[1024], *p;
921 DBT key, data;
922 u_int32_t x;
923 size_t len;
924 int rv;
925
926 data.data = (u_char *)buf;
927 data.size = sizeof(buf);
928 key.data = (u_char *)tbuf;
929
930 switch (tbuf[0] = type) {
931 case _PW_KEYBYNAME:
932 len = strlen((char *)keyp);
933 (void)memcpy(tbuf + 1, keyp, len);
934 key.size = len + 1;
935 break;
936
937 case _PW_KEYBYNUM:
938 case _PW_KEYBYUID:
939 x = *(int *)keyp;
940 if (lorder != BYTE_ORDER)
941 x = SWAP(x);
942 (void)memmove(tbuf + 1, &x, sizeof(x));
943 key.size = sizeof(x) + 1;
944 break;
945 }
946
947 if ((rv = (*db->db->get)(db->db, &key, &data, 0)) == 1)
948 return (rv);
949 if (rv == -1)
950 error(db->dbname);
951
952 p = (char *)data.data;
953
954 pwd.pw_name = p;
955 while (*p++ != '\0')
956 continue;
957 pwd.pw_passwd = p;
958 while (*p++ != '\0')
959 continue;
960
961 (void)memcpy(&pwd.pw_uid, p, sizeof(pwd.pw_uid));
962 p += sizeof(pwd.pw_uid);
963 (void)memcpy(&pwd.pw_gid, p, sizeof(pwd.pw_gid));
964 p += sizeof(pwd.pw_gid);
965
966 #define READPWTIMEVAR(pwvar) \
967 do { \
968 if (db->rversion == 0 && \
969 /*CONSTCOND*/sizeof(pwvar) == sizeof(uint64_t)) { \
970 uint32_t tmp; \
971 (void)memcpy(&tmp, p, sizeof(tmp)); \
972 p += sizeof(tmp); \
973 if (lorder != BYTE_ORDER) \
974 pwvar = SWAP(tmp); \
975 else \
976 pwvar = tmp; \
977 } else if (db->rversion == 1 && \
978 /*CONSTCOND*/sizeof(pwvar) == sizeof(uint32_t)) { \
979 uint64_t tmp; \
980 (void)memcpy(&tmp, p, sizeof(tmp)); \
981 p += sizeof(tmp); \
982 if (lorder != BYTE_ORDER) \
983 pwvar = (uint32_t)SWAP(tmp); \
984 else \
985 pwvar = (uint32_t)tmp; \
986 } else { \
987 (void)memcpy(&pwvar, p, sizeof(pwvar)); \
988 p += sizeof(pwvar); \
989 if (lorder != BYTE_ORDER) \
990 pwvar = SWAP(pwvar); \
991 } \
992 } while (/*CONSTCOND*/0)
993
994 READPWTIMEVAR(pwd.pw_change);
995
996 pwd.pw_class = p;
997 while (*p++ != '\0')
998 continue;
999 pwd.pw_gecos = p;
1000 while (*p++ != '\0')
1001 continue;
1002 pwd.pw_dir = p;
1003 while (*p++ != '\0')
1004 continue;
1005 pwd.pw_shell = p;
1006 while (*p++ != '\0')
1007 continue;
1008
1009 READPWTIMEVAR(pwd.pw_expire);
1010
1011 if (lorder != BYTE_ORDER) {
1012 pwd.pw_uid = SWAP(pwd.pw_uid);
1013 pwd.pw_gid = SWAP(pwd.pw_gid);
1014 }
1015
1016 *tpwd = &pwd;
1017 return (0);
1018 }
1019
1020 void
1021 putyptoken(struct pwddb *db)
1022 {
1023 DBT data, key;
1024
1025 key.data = __UNCONST(__yp_token);
1026 key.size = strlen(__yp_token);
1027 data.data = (u_char *)NULL;
1028 data.size = 0;
1029
1030 if ((*db->db->put)(db->db, &key, &data, R_NOOVERWRITE) == -1)
1031 wr_error(db->dbname);
1032 }
1033
1034 void
1035 usage(void)
1036 {
1037
1038 (void)fprintf(stderr,
1039 "Usage: %s [-BLpsvw] [-c cachesize] [-d directory] [-u user] "
1040 "[-V version] file\n",
1041 getprogname());
1042 exit(EXIT_FAILURE);
1043 }
1044