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