]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libutil/pw_util.c
Merge llvm-project main llvmorg-17-init-19304-gd0b54bb50e51
[FreeBSD/FreeBSD.git] / lib / libutil / pw_util.c
1 /*--
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1990, 1993, 1994
5  *      The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 2002 Networks Associates Technology, Inc.
7  * All rights reserved.
8  *
9  * Portions of this software were developed for the FreeBSD Project by
10  * ThinkSec AS and NAI Labs, the Security Research Division of Network
11  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
12  * ("CBOSS"), as part of the DARPA CHATS research program.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38
39
40 /*
41  * This file is used by all the "password" programs; vipw(8), chpass(1),
42  * and passwd(1).
43  */
44
45 #include <sys/param.h>
46 #include <sys/errno.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <sys/stat.h>
50 #include <sys/wait.h>
51
52 #include <ctype.h>
53 #include <err.h>
54 #include <fcntl.h>
55 #include <inttypes.h>
56 #include <paths.h>
57 #include <pwd.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63
64 #include "libutil.h"
65
66 static pid_t editpid = -1;
67 static int lockfd = -1;
68 static char masterpasswd[PATH_MAX];
69 static char passwd_dir[PATH_MAX];
70 static char tempname[PATH_MAX];
71 static int initialized;
72
73 #if 0
74 void
75 pw_cont(int sig)
76 {
77
78         if (editpid != -1)
79                 kill(editpid, sig);
80 }
81 #endif
82
83 /*
84  * Initialize statics and set limits, signals & umask to try to avoid
85  * interruptions, crashes etc. that might expose passord data.
86  */
87 int
88 pw_init(const char *dir, const char *master)
89 {
90 #if 0
91         struct rlimit rlim;
92 #endif
93
94         if (dir == NULL) {
95                 strcpy(passwd_dir, _PATH_ETC);
96         } else {
97                 if (strlen(dir) >= sizeof(passwd_dir)) {
98                         errno = ENAMETOOLONG;
99                         return (-1);
100                 }
101                 strcpy(passwd_dir, dir);
102         }
103
104         if (master == NULL) {
105                 if (dir == NULL) {
106                         strcpy(masterpasswd, _PATH_MASTERPASSWD);
107                 } else if (snprintf(masterpasswd, sizeof(masterpasswd), "%s/%s",
108                     passwd_dir, _MASTERPASSWD) > (int)sizeof(masterpasswd)) {
109                         errno = ENAMETOOLONG;
110                         return (-1);
111                 }
112         } else {
113                 if (strlen(master) >= sizeof(masterpasswd)) {
114                         errno = ENAMETOOLONG;
115                         return (-1);
116                 }
117                 strcpy(masterpasswd, master);
118         }
119
120         /*
121          * The code that follows is extremely disruptive to the calling
122          * process, and is therefore disabled until someone can conceive
123          * of a realistic scenario where it would fend off a compromise.
124          * Race conditions concerning the temporary files can be guarded
125          * against in other ways than masking signals (by checking stat(2)
126          * results after creation).
127          */
128 #if 0
129         /* Unlimited resource limits. */
130         rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
131         (void)setrlimit(RLIMIT_CPU, &rlim);
132         (void)setrlimit(RLIMIT_FSIZE, &rlim);
133         (void)setrlimit(RLIMIT_STACK, &rlim);
134         (void)setrlimit(RLIMIT_DATA, &rlim);
135         (void)setrlimit(RLIMIT_RSS, &rlim);
136
137         /* Don't drop core (not really necessary, but GP's). */
138         rlim.rlim_cur = rlim.rlim_max = 0;
139         (void)setrlimit(RLIMIT_CORE, &rlim);
140
141         /* Turn off signals. */
142         (void)signal(SIGALRM, SIG_IGN);
143         (void)signal(SIGHUP, SIG_IGN);
144         (void)signal(SIGINT, SIG_IGN);
145         (void)signal(SIGPIPE, SIG_IGN);
146         (void)signal(SIGQUIT, SIG_IGN);
147         (void)signal(SIGTERM, SIG_IGN);
148         (void)signal(SIGCONT, pw_cont);
149
150         /* Create with exact permissions. */
151         (void)umask(0);
152 #endif
153         initialized = 1;
154         return (0);
155 }
156
157 /*
158  * Lock the master password file.
159  */
160 int
161 pw_lock(void)
162 {
163
164         if (*masterpasswd == '\0')
165                 return (-1);
166
167         /*
168          * If the master password file doesn't exist, the system is hosed.
169          * Might as well try to build one.  Set the close-on-exec bit so
170          * that users can't get at the encrypted passwords while editing.
171          * Open should allow flock'ing the file; see 4.4BSD.    XXX
172          */
173         for (;;) {
174                 struct stat st;
175
176                 lockfd = flopen(masterpasswd, O_RDONLY|O_NONBLOCK|O_CLOEXEC, 0);
177                 if (lockfd == -1) {
178                         if (errno == EWOULDBLOCK) {
179                                 errx(1, "the password db file is busy");
180                         } else {
181                                 err(1, "could not lock the passwd file");
182                         }
183                 }
184
185                 /*
186                  * If the password file was replaced while we were trying to
187                  * get the lock, our hardlink count will be 0 and we have to
188                  * close and retry.
189                  */
190                 if (fstat(lockfd, &st) == -1)
191                         err(1, "fstat() failed");
192                 if (st.st_nlink != 0)
193                         break;
194                 close(lockfd);
195                 lockfd = -1;
196         }
197         return (lockfd);
198 }
199
200 /*
201  * Create and open a presumably safe temp file for editing the password
202  * data, and copy the master password file into it.
203  */
204 int
205 pw_tmp(int mfd)
206 {
207         char buf[8192];
208         ssize_t nr;
209         const char *p;
210         int tfd;
211
212         if (*masterpasswd == '\0')
213                 return (-1);
214         if ((p = strrchr(masterpasswd, '/')))
215                 ++p;
216         else
217                 p = masterpasswd;
218         if (snprintf(tempname, sizeof(tempname), "%.*spw.XXXXXX",
219                 (int)(p - masterpasswd), masterpasswd) >= (int)sizeof(tempname)) {
220                 errno = ENAMETOOLONG;
221                 return (-1);
222         }
223         if ((tfd = mkostemp(tempname, 0)) == -1)
224                 return (-1);
225         if (mfd != -1) {
226                 while ((nr = read(mfd, buf, sizeof(buf))) > 0)
227                         if (write(tfd, buf, (size_t)nr) != nr)
228                                 break;
229                 if (nr != 0) {
230                         unlink(tempname);
231                         *tempname = '\0';
232                         close(tfd);
233                         return (-1);
234                 }
235         }
236         return (tfd);
237 }
238
239 /*
240  * Regenerate the password database.
241  */
242 int
243 pw_mkdb(const char *user)
244 {
245         int pstat;
246         pid_t pid;
247
248         (void)fflush(stderr);
249         switch ((pid = fork())) {
250         case -1:
251                 return (-1);
252         case 0:
253                 /* child */
254                 if (user == NULL)
255                         execl(_PATH_PWD_MKDB, "pwd_mkdb", "-p",
256                             "-d", passwd_dir, tempname, (char *)NULL);
257                 else
258                         execl(_PATH_PWD_MKDB, "pwd_mkdb", "-p",
259                             "-d", passwd_dir, "-u", user, tempname,
260                             (char *)NULL);
261                 _exit(1);
262                 /* NOTREACHED */
263         default:
264                 /* parent */
265                 break;
266         }
267         if (waitpid(pid, &pstat, 0) == -1)
268                 return (-1);
269         if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0)
270                 return (0);
271         errno = 0;
272         return (-1);
273 }
274
275 /*
276  * Edit the temp file.  Return -1 on error, >0 if the file was modified, 0
277  * if it was not.
278  */
279 int
280 pw_edit(int notsetuid)
281 {
282         struct sigaction sa, sa_int, sa_quit;
283         sigset_t oldsigset, nsigset;
284         struct stat st1, st2;
285         const char *editor;
286         int pstat;
287
288         if ((editor = getenv("EDITOR")) == NULL)
289                 editor = _PATH_VI;
290         if (stat(tempname, &st1) == -1)
291                 return (-1);
292         sa.sa_handler = SIG_IGN;
293         sigemptyset(&sa.sa_mask);
294         sa.sa_flags = 0;
295         sigaction(SIGINT, &sa, &sa_int);
296         sigaction(SIGQUIT, &sa, &sa_quit);
297         sigemptyset(&nsigset);
298         sigaddset(&nsigset, SIGCHLD);
299         sigprocmask(SIG_BLOCK, &nsigset, &oldsigset);
300         switch ((editpid = fork())) {
301         case -1:
302                 return (-1);
303         case 0:
304                 sigaction(SIGINT, &sa_int, NULL);
305                 sigaction(SIGQUIT, &sa_quit, NULL);
306                 sigprocmask(SIG_SETMASK, &oldsigset, NULL);
307                 if (notsetuid) {
308                         if (setgid(getgid()) == -1)
309                                 err(1, "setgid");
310                         if (setuid(getuid()) == -1)
311                                 err(1, "setuid");
312                 }
313                 execlp(editor, editor, tempname, (char *)NULL);
314                 err(1, "%s", editor);
315         default:
316                 /* parent */
317                 break;
318         }
319         for (;;) {
320                 if (waitpid(editpid, &pstat, WUNTRACED) == -1) {
321                         if (errno == EINTR)
322                                 continue;
323                         unlink(tempname);
324                         editpid = -1;
325                         break;
326                 } else if (WIFSTOPPED(pstat)) {
327                         raise(WSTOPSIG(pstat));
328                 } else if (WIFEXITED(pstat)) {
329                         if (WEXITSTATUS(pstat) != 0)
330                                 errx(1, "\"%s\" exited with status %d", editor, WEXITSTATUS(pstat));
331                         editpid = -1;
332                         break;
333                 } else {
334                         unlink(tempname);
335                         editpid = -1;
336                         break;
337                 }
338         }
339         sigaction(SIGINT, &sa_int, NULL);
340         sigaction(SIGQUIT, &sa_quit, NULL);
341         sigprocmask(SIG_SETMASK, &oldsigset, NULL);
342         if (stat(tempname, &st2) == -1)
343                 return (-1);
344         return (st1.st_mtim.tv_sec != st2.st_mtim.tv_sec ||
345             st1.st_mtim.tv_nsec != st2.st_mtim.tv_nsec);
346 }
347
348 /*
349  * Clean up.  Preserve errno for the caller's convenience.
350  */
351 void
352 pw_fini(void)
353 {
354         int serrno, status;
355
356         if (!initialized)
357                 return;
358         initialized = 0;
359         serrno = errno;
360         if (editpid != -1) {
361                 kill(editpid, SIGTERM);
362                 kill(editpid, SIGCONT);
363                 waitpid(editpid, &status, 0);
364                 editpid = -1;
365         }
366         if (*tempname != '\0') {
367                 unlink(tempname);
368                 *tempname = '\0';
369         }
370         if (lockfd != -1)
371                 close(lockfd);
372         errno = serrno;
373 }
374
375 /*
376  * Compares two struct pwds.
377  */
378 int
379 pw_equal(const struct passwd *pw1, const struct passwd *pw2)
380 {
381         return (strcmp(pw1->pw_name, pw2->pw_name) == 0 &&
382             pw1->pw_uid == pw2->pw_uid &&
383             pw1->pw_gid == pw2->pw_gid &&
384             strcmp(pw1->pw_class, pw2->pw_class) == 0 &&
385             pw1->pw_change == pw2->pw_change &&
386             pw1->pw_expire == pw2->pw_expire &&
387             strcmp(pw1->pw_gecos, pw2->pw_gecos) == 0 &&
388             strcmp(pw1->pw_dir, pw2->pw_dir) == 0 &&
389             strcmp(pw1->pw_shell, pw2->pw_shell) == 0);
390 }
391
392 /*
393  * Make a passwd line out of a struct passwd.
394  */
395 char *
396 pw_make(const struct passwd *pw)
397 {
398         char *line;
399
400         asprintf(&line, "%s:%s:%ju:%ju:%s:%ju:%ju:%s:%s:%s", pw->pw_name,
401             pw->pw_passwd, (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid,
402             pw->pw_class, (uintmax_t)pw->pw_change, (uintmax_t)pw->pw_expire,
403             pw->pw_gecos, pw->pw_dir, pw->pw_shell);
404         return (line);
405 }
406
407 /*
408  * Make a passwd line (in v7 format) out of a struct passwd
409  */
410 char *
411 pw_make_v7(const struct passwd *pw)
412 {
413         char *line;
414
415         asprintf(&line, "%s:*:%ju:%ju:%s:%s:%s", pw->pw_name,
416             (uintmax_t)pw->pw_uid, (uintmax_t)pw->pw_gid,
417             pw->pw_gecos, pw->pw_dir, pw->pw_shell);
418         return (line);
419 }
420
421 /*
422  * Copy password file from one descriptor to another, replacing, deleting
423  * or adding a single record on the way.
424  */
425 int
426 pw_copy(int ffd, int tfd, const struct passwd *pw, struct passwd *old_pw)
427 {
428         char *buf, *end, *line, *p, *q, *r, *tmp;
429         struct passwd *fpw;
430         const struct passwd *spw;
431         size_t len, size;
432         int eof, readlen;
433         char t;
434
435         if (old_pw == NULL && pw == NULL)
436                         return (-1);
437
438         spw = old_pw;
439         /* deleting a user */
440         if (pw == NULL) {
441                 line = NULL;
442         } else {
443                 if ((line = pw_make(pw)) == NULL)
444                         return (-1);
445         }
446
447         /* adding a user */
448         if (spw == NULL)
449                 spw = pw;
450
451         /* initialize the buffer */
452         if ((buf = malloc(size = 1024)) == NULL)
453                 goto err;
454
455         eof = 0;
456         len = 0;
457         p = q = end = buf;
458         for (;;) {
459                 /* find the end of the current line */
460                 for (p = q; q < end && *q != '\0'; ++q)
461                         if (*q == '\n')
462                                 break;
463
464                 /* if we don't have a complete line, fill up the buffer */
465                 if (q >= end) {
466                         if (eof)
467                                 break;
468                         while ((size_t)(q - p) >= size) {
469                                 if ((tmp = reallocarray(buf, 2, size)) == NULL) {
470                                         warnx("passwd line too long");
471                                         goto err;
472                                 }
473                                 p = tmp + (p - buf);
474                                 q = tmp + (q - buf);
475                                 end = tmp + (end - buf);
476                                 buf = tmp;
477                                 size = size * 2;
478                         }
479                         if (p < end) {
480                                 q = memmove(buf, p, end - p);
481                                 end -= p - buf;
482                         } else {
483                                 p = q = end = buf;
484                         }
485                         readlen = read(ffd, end, size - (end - buf));
486                         if (readlen == -1)
487                                 goto err;
488                         else
489                                 len = (size_t)readlen;
490                         if (len == 0 && p == buf)
491                                 break;
492                         end += len;
493                         len = end - buf;
494                         if (len < size) {
495                                 eof = 1;
496                                 if (len > 0 && buf[len - 1] != '\n')
497                                         ++len, *end++ = '\n';
498                         }
499                         continue;
500                 }
501
502                 /* is it a blank line or a comment? */
503                 for (r = p; r < q && isspace(*r); ++r)
504                         /* nothing */ ;
505                 if (r == q || *r == '#') {
506                         /* yep */
507                         if (write(tfd, p, q - p + 1) != q - p + 1)
508                                 goto err;
509                         ++q;
510                         continue;
511                 }
512
513                 /* is it the one we're looking for? */
514
515                 t = *q;
516                 *q = '\0';
517
518                 fpw = pw_scan(r, PWSCAN_MASTER);
519
520                 /*
521                  * fpw is either the struct passwd for the current line,
522                  * or NULL if the line is malformed.
523                  */
524
525                 *q = t;
526                 if (fpw == NULL || strcmp(fpw->pw_name, spw->pw_name) != 0) {
527                         /* nope */
528                         if (fpw != NULL)
529                                 free(fpw);
530                         if (write(tfd, p, q - p + 1) != q - p + 1)
531                                 goto err;
532                         ++q;
533                         continue;
534                 }
535                 if (old_pw && !pw_equal(fpw, old_pw)) {
536                         warnx("entry inconsistent");
537                         free(fpw);
538                         errno = EINVAL; /* hack */
539                         goto err;
540                 }
541                 free(fpw);
542
543                 /* it is, replace or remove it */
544                 if (line != NULL) {
545                         len = strlen(line);
546                         if (write(tfd, line, len) != (int)len)
547                                 goto err;
548                 } else {
549                         /* when removed, avoid the \n */
550                         q++;
551                 }
552                 /* we're done, just copy the rest over */
553                 for (;;) {
554                         if (write(tfd, q, end - q) != end - q)
555                                 goto err;
556                         q = buf;
557                         readlen = read(ffd, buf, size);
558                         if (readlen == 0)
559                                 break;
560                         else
561                                 len = (size_t)readlen;
562                         if (readlen == -1)
563                                 goto err;
564                         end = buf + len;
565                 }
566                 goto done;
567         }
568
569         /* if we got here, we didn't find the old entry */
570         if (line == NULL) {
571                 errno = ENOENT;
572                 goto err;
573         }
574         len = strlen(line);
575         if ((size_t)write(tfd, line, len) != len ||
576             write(tfd, "\n", 1) != 1)
577                 goto err;
578  done:
579         free(line);
580         free(buf);
581         return (0);
582  err:
583         free(line);
584         free(buf);
585         return (-1);
586 }
587
588 /*
589  * Return the current value of tempname.
590  */
591 const char *
592 pw_tempname(void)
593 {
594
595         return (tempname);
596 }
597
598 /*
599  * Duplicate a struct passwd.
600  */
601 struct passwd *
602 pw_dup(const struct passwd *pw)
603 {
604         char *dst;
605         struct passwd *npw;
606         ssize_t len;
607
608         len = sizeof(*npw);
609         if (pw->pw_name != NULL)
610                 len += strlen(pw->pw_name) + 1;
611         if (pw->pw_passwd != NULL)
612                 len += strlen(pw->pw_passwd) + 1;
613         if (pw->pw_class != NULL)
614                 len += strlen(pw->pw_class) + 1;
615         if (pw->pw_gecos != NULL)
616                 len += strlen(pw->pw_gecos) + 1;
617         if (pw->pw_dir != NULL)
618                 len += strlen(pw->pw_dir) + 1;
619         if (pw->pw_shell != NULL)
620                 len += strlen(pw->pw_shell) + 1;
621         if ((npw = malloc((size_t)len)) == NULL)
622                 return (NULL);
623         memcpy(npw, pw, sizeof(*npw));
624         dst = (char *)npw + sizeof(*npw);
625         if (pw->pw_name != NULL) {
626                 npw->pw_name = dst;
627                 dst = stpcpy(npw->pw_name, pw->pw_name) + 1;
628         }
629         if (pw->pw_passwd != NULL) {
630                 npw->pw_passwd = dst;
631                 dst = stpcpy(npw->pw_passwd, pw->pw_passwd) + 1;
632         }
633         if (pw->pw_class != NULL) {
634                 npw->pw_class = dst;
635                 dst = stpcpy(npw->pw_class, pw->pw_class) + 1;
636         }
637         if (pw->pw_gecos != NULL) {
638                 npw->pw_gecos = dst;
639                 dst = stpcpy(npw->pw_gecos, pw->pw_gecos) + 1;
640         }
641         if (pw->pw_dir != NULL) {
642                 npw->pw_dir = dst;
643                 dst = stpcpy(npw->pw_dir, pw->pw_dir) + 1;
644         }
645         if (pw->pw_shell != NULL) {
646                 npw->pw_shell = dst;
647                 dst = stpcpy(npw->pw_shell, pw->pw_shell) + 1;
648         }
649         return (npw);
650 }
651
652 #include "pw_scan.h"
653
654 /*
655  * Wrapper around some internal libc functions.
656  */
657
658 void
659 pw_initpwd(struct passwd *pw)
660 {
661
662         __pw_initpwd(pw);
663 }
664
665 struct passwd *
666 pw_scan(const char *line, int flags)
667 {
668         struct passwd pw, *ret;
669         char *bp;
670
671         if ((bp = strdup(line)) == NULL)
672                 return (NULL);
673         __pw_initpwd(&pw);
674         if (!__pw_scan(bp, &pw, flags)) {
675                 free(bp);
676                 return (NULL);
677         }
678         ret = pw_dup(&pw);
679         free(bp);
680         return (ret);
681 }