xref: /netbsd-src/lib/libutil/passwd.c (revision 466a16a118933bd295a8a104f095714fadf9cf68)
1 /*	$NetBSD: passwd.c,v 1.46 2008/12/21 17:54:43 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1987, 1993, 1994, 1995
5  *	The Regents of the University of California.  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  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #if defined(LIBC_SCCS) && !defined(lint)
34 __RCSID("$NetBSD: passwd.c,v 1.46 2008/12/21 17:54:43 christos Exp $");
35 #endif /* LIBC_SCCS and not lint */
36 
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/stat.h>
40 #include <sys/time.h>
41 #include <sys/resource.h>
42 #include <sys/wait.h>
43 
44 #include <assert.h>
45 #include <ctype.h>
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <limits.h>
50 #include <paths.h>
51 #include <pwd.h>
52 #include <grp.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 #include <util.h>
59 
60 static const char      *pw_filename(const char *filename);
61 static void		pw_cont(int sig);
62 static const char *	pw_equal(char *buf, struct passwd *old_pw);
63 static const char      *pw_default(const char *option);
64 static int		read_line(FILE *fp, char *line, int max);
65 static void		trim_whitespace(char *line);
66 
67 static	char	pw_prefix[MAXPATHLEN];
68 
69 const char *
70 pw_getprefix(void)
71 {
72 
73 	return(pw_prefix);
74 }
75 
76 int
77 pw_setprefix(const char *new_prefix)
78 {
79 	size_t length;
80 
81 	_DIAGASSERT(new_prefix != NULL);
82 
83 	length = strlen(new_prefix);
84 	if (length < sizeof(pw_prefix)) {
85 		(void)strcpy(pw_prefix, new_prefix);
86 		while (length > 0 && pw_prefix[length - 1] == '/')
87 			pw_prefix[--length] = '\0';
88 		return(0);
89 	}
90 	errno = ENAMETOOLONG;
91 	return(-1);
92 }
93 
94 static const char *
95 pw_filename(const char *filename)
96 {
97 	static char newfilename[MAXPATHLEN];
98 
99 	_DIAGASSERT(filename != NULL);
100 
101 	if (pw_prefix[0] == '\0')
102 		return filename;
103 
104 	if (strlen(pw_prefix) + strlen(filename) < sizeof(newfilename))
105 		return strcat(strcpy(newfilename, pw_prefix), filename);
106 
107 	errno = ENAMETOOLONG;
108 	return(NULL);
109 }
110 
111 int
112 pw_lock(int retries)
113 {
114 	const char *filename;
115 	int i, fd;
116 	mode_t old_mode;
117 	int oerrno;
118 
119 	/* Acquire the lock file. */
120 	filename = pw_filename(_PATH_MASTERPASSWD_LOCK);
121 	if (filename == NULL)
122 		return(-1);
123 	old_mode = umask(0);
124 	fd = open(filename, O_WRONLY|O_CREAT|O_EXCL, 0600);
125 	for (i = 0; i < retries && fd < 0 && errno == EEXIST; i++) {
126 		sleep(1);
127 		fd = open(filename, O_WRONLY|O_CREAT|O_EXCL,
128 			  0600);
129 	}
130 	oerrno = errno;
131 	(void)umask(old_mode);
132 	errno = oerrno;
133 	return(fd);
134 }
135 
136 int
137 pw_mkdb(username, secureonly)
138 	const char *username;
139 	int secureonly;
140 {
141 	const char *args[9];
142 	int pstat, i;
143 	pid_t pid;
144 
145 	pid = vfork();
146 	if (pid == -1)
147 		return (-1);
148 
149 	if (pid == 0) {
150 		args[0] = "pwd_mkdb";
151 		args[1] = "-d";
152 		args[2] = pw_prefix;
153 		args[3] = "-p";
154 		i = 4;
155 
156 		if (secureonly)
157 			args[i++] = "-s";
158 		if (username != NULL) {
159 			args[i++] = "-u";
160 			args[i++] = username;
161 		}
162 
163 		args[i++] = pw_filename(_PATH_MASTERPASSWD_LOCK);
164 		args[i] = NULL;
165 		execv(_PATH_PWD_MKDB, (char * const *)__UNCONST(args));
166 		_exit(1);
167 	}
168 	pid = waitpid(pid, &pstat, 0);
169 	if (pid == -1 || !WIFEXITED(pstat) || WEXITSTATUS(pstat) != 0)
170 		return(-1);
171 	return(0);
172 }
173 
174 int
175 pw_abort(void)
176 {
177 	const char *filename;
178 
179 	filename = pw_filename(_PATH_MASTERPASSWD_LOCK);
180 	return((filename == NULL) ? -1 : unlink(filename));
181 }
182 
183 /* Everything below this point is intended for the convenience of programs
184  * which allow a user to interactively edit the passwd file.  Errors in the
185  * routines below will cause the process to abort. */
186 
187 static pid_t editpid = -1;
188 
189 static void
190 pw_cont(int sig)
191 {
192 
193 	if (editpid != -1)
194 		kill(editpid, sig);
195 }
196 
197 void
198 pw_init(void)
199 {
200 	struct rlimit rlim;
201 
202 	/* Unlimited resource limits. */
203 	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
204 	(void)setrlimit(RLIMIT_CPU, &rlim);
205 	(void)setrlimit(RLIMIT_FSIZE, &rlim);
206 	(void)setrlimit(RLIMIT_STACK, &rlim);
207 	(void)setrlimit(RLIMIT_DATA, &rlim);
208 	(void)setrlimit(RLIMIT_RSS, &rlim);
209 
210 	/* Don't drop core (not really necessary, but GP's). */
211 	rlim.rlim_cur = rlim.rlim_max = 0;
212 	(void)setrlimit(RLIMIT_CORE, &rlim);
213 
214 	/* Turn off signals. */
215 	(void)signal(SIGALRM, SIG_IGN);
216 	(void)signal(SIGHUP, SIG_IGN);
217 	(void)signal(SIGINT, SIG_IGN);
218 	(void)signal(SIGPIPE, SIG_IGN);
219 	(void)signal(SIGQUIT, SIG_IGN);
220 	(void)signal(SIGTERM, SIG_IGN);
221 	(void)signal(SIGCONT, pw_cont);
222 }
223 
224 void
225 pw_edit(int notsetuid, const char *filename)
226 {
227 	int pstat;
228 	char *p;
229 	const char * volatile editor;
230 	const char *argp[] = { "sh", "-c", NULL, NULL };
231 
232 	if (filename == NULL)
233 		filename = _PATH_MASTERPASSWD_LOCK;
234 
235 	filename = pw_filename(filename);
236 	if (filename == NULL)
237 		return;
238 
239 	if ((editor = getenv("EDITOR")) == NULL)
240 		editor = _PATH_VI;
241 
242 	p = malloc(strlen(editor) + 1 + strlen(filename) + 1);
243 	if (p == NULL)
244 		return;
245 
246 	sprintf(p, "%s %s", editor, filename);
247 	argp[2] = p;
248 
249 	switch(editpid = vfork()) {
250 	case -1:
251 		free(p);
252 		return;
253 	case 0:
254 		if (notsetuid) {
255 			setgid(getgid());
256 			setuid(getuid());
257 		}
258 		execvp(_PATH_BSHELL, (char *const *)__UNCONST(argp));
259 		_exit(1);
260 	}
261 
262 	free(p);
263 
264 	for (;;) {
265 		editpid = waitpid(editpid, (int *)&pstat, WUNTRACED);
266 		if (editpid == -1)
267 			pw_error(editor, 1, 1);
268 		else if (WIFSTOPPED(pstat))
269 			raise(WSTOPSIG(pstat));
270 		else if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0)
271 			break;
272 		else
273 			pw_error(editor, 1, 1);
274 	}
275 	editpid = -1;
276 }
277 
278 void
279 pw_prompt(void)
280 {
281 	int c;
282 
283 	(void)printf("re-edit the password file? [y]: ");
284 	(void)fflush(stdout);
285 	c = getchar();
286 	if (c != EOF && c != '\n')
287 		while (getchar() != '\n');
288 	if (c == 'n')
289 		pw_error(NULL, 0, 0);
290 }
291 
292 /* for use in pw_copy(). Compare a pw entry to a pw struct. */
293 /* returns a character string labelling the miscompared field or 0 */
294 static const char *
295 pw_equal(char *buf, struct passwd *pw)
296 {
297 	struct passwd buf_pw;
298 	size_t len;
299 
300 	_DIAGASSERT(buf != NULL);
301 	_DIAGASSERT(pw != NULL);
302 
303 	len = strlen (buf);
304 	if (buf[len-1] == '\n')
305 		buf[len-1] = '\0';
306 	if (!pw_scan(buf, &buf_pw, NULL))
307 		return "corrupt line";
308 	if (strcmp(pw->pw_name, buf_pw.pw_name) != 0)
309 		return "name";
310 	if (pw->pw_uid != buf_pw.pw_uid)
311 		return "uid";
312 	if (pw->pw_gid != buf_pw.pw_gid)
313 		return "gid";
314 	if (strcmp( pw->pw_class, buf_pw.pw_class) != 0)
315 		return "class";
316 	if (pw->pw_change != buf_pw.pw_change)
317 		return "change";
318 	if (pw->pw_expire != buf_pw.pw_expire)
319 		return "expire";
320 	if (strcmp( pw->pw_gecos, buf_pw.pw_gecos) != 0)
321 		return "gecos";
322 	if (strcmp( pw->pw_dir, buf_pw.pw_dir) != 0)
323 		return "dir";
324 	if (strcmp( pw->pw_shell, buf_pw.pw_shell) != 0)
325 		return "shell";
326 	return (char *)0;
327 }
328 
329 void
330 pw_copy(int ffd, int tfd, struct passwd *pw, struct passwd *old_pw)
331 {
332 	char errbuf[200];
333 	int rv;
334 
335 	rv = pw_copyx(ffd, tfd, pw, old_pw, errbuf, sizeof(errbuf));
336 	if (rv == 0) {
337 		warnx("%s", errbuf);
338 		pw_error(NULL, 0, 1);
339 	}
340 }
341 
342 int
343 pw_copyx(int ffd, int tfd, struct passwd *pw, struct passwd *old_pw,
344     char *errbuf, size_t errbufsz)
345 {
346 	const char *filename;
347 	char mpwd[MAXPATHLEN], mpwdl[MAXPATHLEN], *p, buf[8192];
348 	FILE *from, *to;
349 	int done;
350 
351 	_DIAGASSERT(pw != NULL);
352 	_DIAGASSERT(errbuf != NULL);
353 	/* old_pw may be NULL */
354 
355 	if ((filename = pw_filename(_PATH_MASTERPASSWD)) == NULL) {
356 		snprintf(errbuf, errbufsz, "%s: %s", pw_prefix,
357 		    strerror(errno));
358 		return (0);
359 	}
360 	(void)strcpy(mpwd, filename);
361 	if ((filename = pw_filename(_PATH_MASTERPASSWD_LOCK)) == NULL) {
362 		snprintf(errbuf, errbufsz, "%s: %s", pw_prefix,
363 		    strerror(errno));
364 		return (0);
365 	}
366 	(void)strcpy(mpwdl, filename);
367 
368 	if (!(from = fdopen(ffd, "r"))) {
369 		snprintf(errbuf, errbufsz, "%s: %s", mpwd, strerror(errno));
370 		return (0);
371 	}
372 	if (!(to = fdopen(tfd, "w"))) {
373 		snprintf(errbuf, errbufsz, "%s: %s", mpwdl, strerror(errno));
374 		(void)fclose(from);
375 		return (0);
376 	}
377 
378 	for (done = 0; fgets(buf, (int)sizeof(buf), from);) {
379 		const char *neq;
380 		if (!strchr(buf, '\n')) {
381 			snprintf(errbuf, errbufsz, "%s: line too long", mpwd);
382 			(void)fclose(from);
383 			(void)fclose(to);
384 			return (0);
385 		}
386 		if (done) {
387 			(void)fprintf(to, "%s", buf);
388 			if (ferror(to)) {
389 				snprintf(errbuf, errbufsz, "%s",
390 				    strerror(errno));
391 				(void)fclose(from);
392 				(void)fclose(to);
393 				return (0);
394 			}
395 			continue;
396 		}
397 		if (!(p = strchr(buf, ':'))) {
398 			snprintf(errbuf, errbufsz, "%s: corrupted entry", mpwd);
399 			(void)fclose(from);
400 			(void)fclose(to);
401 			return (0);
402 		}
403 		*p = '\0';
404 		if (strcmp(buf, pw->pw_name)) {
405 			*p = ':';
406 			(void)fprintf(to, "%s", buf);
407 			if (ferror(to)) {
408 				snprintf(errbuf, errbufsz, "%s",
409 				    strerror(errno));
410 				(void)fclose(from);
411 				(void)fclose(to);
412 				return (0);
413 			}
414 			continue;
415 		}
416 		*p = ':';
417 		if (old_pw && (neq = pw_equal(buf, old_pw)) != NULL) {
418 			if (strcmp(neq, "corrupt line") == 0)
419 				(void)snprintf(errbuf, errbufsz,
420 				    "%s: entry %s corrupted", mpwd,
421 				    pw->pw_name);
422 			else
423 				(void)snprintf(errbuf, errbufsz,
424 				    "%s: entry %s inconsistent %s",
425 				    mpwd, pw->pw_name, neq);
426 			(void)fclose(from);
427 			(void)fclose(to);
428 			return (0);
429 		}
430 		(void)fprintf(to, "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
431 		    pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid,
432 		    pw->pw_class, (long)pw->pw_change, (long)pw->pw_expire,
433 		    pw->pw_gecos, pw->pw_dir, pw->pw_shell);
434 		done = 1;
435 		if (ferror(to)) {
436 			snprintf(errbuf, errbufsz, "%s", strerror(errno));
437 			(void)fclose(from);
438 			(void)fclose(to);
439 			return (0);
440 		}
441 	}
442 	/* Only append a new entry if real uid is root! */
443 	if (!done) {
444 		if (getuid() == 0) {
445 			(void)fprintf(to, "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
446 			    pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid,
447 			    pw->pw_class, (long)pw->pw_change,
448 			    (long)pw->pw_expire, pw->pw_gecos, pw->pw_dir,
449 			    pw->pw_shell);
450 			done = 1;
451 		} else {
452 			snprintf(errbuf, errbufsz,
453 			    "%s: changes not made, no such entry", mpwd);
454 		}
455 	}
456 
457 	if (ferror(to)) {
458 		snprintf(errbuf, errbufsz, "%s", strerror(errno));
459 		(void)fclose(from);
460 		(void)fclose(to);
461 		return (0);
462 	}
463 	(void)fclose(from);
464 	(void)fclose(to);
465 
466 	return (done);
467 }
468 
469 void
470 pw_error(const char *name, int error, int eval)
471 {
472 
473 	if (error) {
474 		if (name)
475 			warn("%s", name);
476 		else
477 			warn(NULL);
478 	}
479 
480 	warnx("%s%s: unchanged", pw_prefix, _PATH_MASTERPASSWD);
481 	pw_abort();
482 	exit(eval);
483 }
484 
485 /* Removes head and/or tail spaces. */
486 static void
487 trim_whitespace(char *line)
488 {
489 	char *p;
490 
491 	_DIAGASSERT(line != NULL);
492 
493 	/* Remove leading spaces */
494 	p = line;
495 	while (isspace((unsigned char) *p))
496 		p++;
497 	memmove(line, p, strlen(p) + 1);
498 
499 	/* Remove trailing spaces */
500 	p = line + strlen(line) - 1;
501 	while (isspace((unsigned char) *p))
502 		p--;
503 	*(p + 1) = '\0';
504 }
505 
506 
507 /* Get one line, remove spaces from front and tail */
508 static int
509 read_line(FILE *fp, char *line, int max)
510 {
511 	char   *p;
512 
513 	_DIAGASSERT(fp != NULL);
514 	_DIAGASSERT(line != NULL);
515 
516 	/* Read one line of config */
517 	if (fgets(line, max, fp) == NULL)
518 		return (0);
519 
520 	if ((p = strchr(line, '\n')) == NULL) {
521 		warnx("line too long");
522 		return (0);
523 	}
524 	*p = '\0';
525 
526 	/* Remove comments */
527 	if ((p = strchr(line, '#')) != NULL)
528 		*p = '\0';
529 
530 	trim_whitespace(line);
531 	return (1);
532 }
533 
534 static const char *
535 pw_default(const char *option)
536 {
537 	static const char *options[][2] = {
538 		{ "localcipher",	"old" },
539 		{ "ypcipher",		"old" },
540 	};
541 	int i;
542 
543 	_DIAGASSERT(option != NULL);
544 	for (i = 0; i < sizeof(options) / sizeof(options[0]); i++)
545 		if (strcmp(options[i][0], option) == 0)
546 			return (options[i][1]);
547 
548 	return (NULL);
549 }
550 
551 /*
552  * Retrieve password information from the /etc/passwd.conf file, at the
553  * moment this is only for choosing the cipher to use.  It could easily be
554  * used for other authentication methods as well.
555  */
556 void
557 pw_getconf(char *data, size_t max, const char *key, const char *option)
558 {
559 	FILE *fp;
560 	char line[LINE_MAX], *p, *p2;
561 	static char result[LINE_MAX];
562 	int got, found;
563 	const char *cp;
564 
565 	_DIAGASSERT(data != NULL);
566 	_DIAGASSERT(key != NULL);
567 	_DIAGASSERT(option != NULL);
568 
569 	got = 0;
570 	found = 0;
571 	result[0] = '\0';
572 
573 	if ((fp = fopen(_PATH_PASSWD_CONF, "r")) == NULL) {
574 		if ((cp = pw_default(option)) != NULL)
575 			strlcpy(data, cp, max);
576 		else
577 			data[0] = '\0';
578 		return;
579 	}
580 
581 	while (!found && (got || read_line(fp, line, LINE_MAX))) {
582 		got = 0;
583 
584 		if (strncmp(key, line, strlen(key)) != 0 ||
585 		    line[strlen(key)] != ':')
586 			continue;
587 
588 		/* Now we found our specified key */
589 		while (read_line(fp, line, LINE_MAX)) {
590 			/* Leaving key field */
591 			if (line[0] != '\0' && strchr(line + 1, ':') != NULL) {
592 				got = 1;
593 				break;
594 			}
595 			p2 = line;
596 			if ((p = strsep(&p2, "=")) == NULL || p2 == NULL)
597 				continue;
598 			trim_whitespace(p);
599 
600 			if (!strncmp(p, option, strlen(option))) {
601 				trim_whitespace(p2);
602 				strcpy(result, p2);
603 				found = 1;
604 				break;
605 			}
606 		}
607 	}
608 	fclose(fp);
609 
610 	if (!found)
611 		errno = ENOENT;
612 	if (!got)
613 		errno = ENOTDIR;
614 
615 	/*
616 	 * If we got no result and were looking for a default
617 	 * value, try hard coded defaults.
618 	 */
619 
620 	if (strlen(result) == 0 && strcmp(key, "default") == 0 &&
621 	    (cp = pw_default(option)) != NULL)
622 		strlcpy(data, cp, max);
623 	else
624 		strlcpy(data, result, max);
625 }
626 
627 void
628 pw_getpwconf(char *data, size_t max, const struct passwd *pwd,
629     const char *option)
630 {
631 	char grpkey[LINE_MAX];
632 	struct group grs, *grp;
633 	char grbuf[1024];
634 
635 	pw_getconf(data, max, pwd->pw_name, option);
636 
637 	/* Try to find an entry for the group */
638 	if (*data == '\0') {
639 		(void)getgrgid_r(pwd->pw_gid, &grs, grbuf, sizeof(grbuf), &grp);
640 		if (grp != NULL) {
641 			(void)snprintf(grpkey, sizeof(grpkey), ":%s",
642 			    grp->gr_name);
643 			pw_getconf(data, max, grpkey, option);
644 		}
645 		if (*data == '\0')
646 		        pw_getconf(data, max, "default", option);
647 	}
648 }
649