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