xref: /netbsd-src/lib/libutil/passwd.c (revision 9c1da17e908379b8a470f1117a6395bd6a0ca559)
1 /*	$NetBSD: passwd.c,v 1.41 2005/08/19 10:10:08 elad 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.41 2005/08/19 10:10:08 elad 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 int		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 *editor;
230 	const char *argp[] = { "sh", "-c", NULL, NULL };
231 
232 #ifdef __GNUC__
233 	(void) &editor;
234 #endif
235 
236 	if (filename == NULL)
237 		filename = _PATH_MASTERPASSWD_LOCK;
238 
239 	filename = pw_filename(filename);
240 	if (filename == NULL)
241 		return;
242 
243 	if ((editor = getenv("EDITOR")) == NULL)
244 		editor = _PATH_VI;
245 
246 	p = malloc(strlen(editor) + 1 + strlen(filename) + 1);
247 	if (p == NULL)
248 		return;
249 
250 	sprintf(p, "%s %s", editor, filename);
251 	argp[2] = p;
252 
253 	switch(editpid = vfork()) {
254 	case -1:
255 		free(p);
256 		return;
257 	case 0:
258 		if (notsetuid) {
259 			setgid(getgid());
260 			setuid(getuid());
261 		}
262 		execvp(_PATH_BSHELL, (char *const *)__UNCONST(argp));
263 		_exit(1);
264 	}
265 
266 	free(p);
267 
268 	for (;;) {
269 		editpid = waitpid(editpid, (int *)&pstat, WUNTRACED);
270 		if (editpid == -1)
271 			pw_error(editor, 1, 1);
272 		else if (WIFSTOPPED(pstat))
273 			raise(WSTOPSIG(pstat));
274 		else if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0)
275 			break;
276 		else
277 			pw_error(editor, 1, 1);
278 	}
279 	editpid = -1;
280 }
281 
282 void
283 pw_prompt(void)
284 {
285 	int c;
286 
287 	(void)printf("re-edit the password file? [y]: ");
288 	(void)fflush(stdout);
289 	c = getchar();
290 	if (c != EOF && c != '\n')
291 		while (getchar() != '\n');
292 	if (c == 'n')
293 		pw_error(NULL, 0, 0);
294 }
295 
296 /* for use in pw_copy(). Compare a pw entry to a pw struct. */
297 static int
298 pw_equal(char *buf, struct passwd *pw)
299 {
300 	struct passwd buf_pw;
301 	size_t len;
302 
303 	_DIAGASSERT(buf != NULL);
304 	_DIAGASSERT(pw != NULL);
305 
306 	len = strlen (buf);
307 	if (buf[len-1] == '\n')
308 		buf[len-1] = '\0';
309 	if (!pw_scan(buf, &buf_pw, NULL))
310 		return 0;
311 	return !strcmp(pw->pw_name, buf_pw.pw_name)
312 		&& pw->pw_uid == buf_pw.pw_uid
313 		&& pw->pw_gid == buf_pw.pw_gid
314 		&& !strcmp(pw->pw_class, buf_pw.pw_class)
315 		&& (long)pw->pw_change == (long)buf_pw.pw_change
316 		&& (long)pw->pw_expire == (long)buf_pw.pw_expire
317 		&& !strcmp(pw->pw_gecos, buf_pw.pw_gecos)
318 		&& !strcmp(pw->pw_dir, buf_pw.pw_dir)
319 		&& !strcmp(pw->pw_shell, buf_pw.pw_shell);
320 }
321 
322 void
323 pw_copy(int ffd, int tfd, struct passwd *pw, struct passwd *old_pw)
324 {
325 	char errbuf[200];
326 	int rv;
327 
328 	rv = pw_copyx(ffd, tfd, pw, old_pw, errbuf, sizeof(errbuf));
329 	if (rv == 0) {
330 		warnx("%s", errbuf);
331 		pw_error(NULL, 0, 1);
332 	}
333 }
334 
335 int
336 pw_copyx(int ffd, int tfd, struct passwd *pw, struct passwd *old_pw,
337     char *errbuf, size_t errbufsz)
338 {
339 	const char *filename;
340 	char mpwd[MAXPATHLEN], mpwdl[MAXPATHLEN], *p, buf[8192];
341 	FILE *from, *to;
342 	int done;
343 
344 	_DIAGASSERT(pw != NULL);
345 	_DIAGASSERT(errbuf != NULL);
346 	/* old_pw may be NULL */
347 
348 	if ((filename = pw_filename(_PATH_MASTERPASSWD)) == NULL) {
349 		snprintf(errbuf, errbufsz, "%s: %s", pw_prefix,
350 		    strerror(errno));
351 		return (0);
352 	}
353 	(void)strcpy(mpwd, filename);
354 	if ((filename = pw_filename(_PATH_MASTERPASSWD_LOCK)) == NULL) {
355 		snprintf(errbuf, errbufsz, "%s: %s", pw_prefix,
356 		    strerror(errno));
357 		return (0);
358 	}
359 	(void)strcpy(mpwdl, filename);
360 
361 	if (!(from = fdopen(ffd, "r"))) {
362 		snprintf(errbuf, errbufsz, "%s: %s", mpwd, strerror(errno));
363 		return (0);
364 	}
365 	if (!(to = fdopen(tfd, "w"))) {
366 		snprintf(errbuf, errbufsz, "%s: %s", mpwdl, strerror(errno));
367 		return (0);
368 	}
369 
370 	for (done = 0; fgets(buf, (int)sizeof(buf), from);) {
371 		if (!strchr(buf, '\n')) {
372 			snprintf(errbuf, errbufsz, "%s: line too long", mpwd);
373 			return (0);
374 		}
375 		if (done) {
376 			(void)fprintf(to, "%s", buf);
377 			if (ferror(to)) {
378 				snprintf(errbuf, errbufsz, "%s",
379 				    strerror(errno));
380 				return (0);
381 			}
382 			continue;
383 		}
384 		if (!(p = strchr(buf, ':'))) {
385 			snprintf(errbuf, errbufsz, "%s: corrupted entry", mpwd);
386 			return (0);
387 		}
388 		*p = '\0';
389 		if (strcmp(buf, pw->pw_name)) {
390 			*p = ':';
391 			(void)fprintf(to, "%s", buf);
392 			if (ferror(to)) {
393 				snprintf(errbuf, errbufsz, "%s",
394 				    strerror(errno));
395 				return (0);
396 			}
397 			continue;
398 		}
399 		*p = ':';
400 		if (old_pw && !pw_equal(buf, old_pw)) {
401 			snprintf(errbuf, errbufsz, "%s: entry inconsistent",
402 			    mpwd);
403 			return (0);
404 		}
405 		(void)fprintf(to, "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
406 		    pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid,
407 		    pw->pw_class, (long)pw->pw_change, (long)pw->pw_expire,
408 		    pw->pw_gecos, pw->pw_dir, pw->pw_shell);
409 		done = 1;
410 		if (ferror(to)) {
411 			snprintf(errbuf, errbufsz, "%s", strerror(errno));
412 			return (0);
413 		}
414 	}
415 	/* Only append a new entry if real uid is root! */
416 	if (!done) {
417 		if (getuid() == 0) {
418 			(void)fprintf(to, "%s:%s:%d:%d:%s:%ld:%ld:%s:%s:%s\n",
419 			    pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid,
420 			    pw->pw_class, (long)pw->pw_change,
421 			    (long)pw->pw_expire, pw->pw_gecos, pw->pw_dir,
422 			    pw->pw_shell);
423 			done = 1;
424 		} else {
425 			snprintf(errbuf, errbufsz,
426 			    "%s: changes not made, no such entry", mpwd);
427 		}
428 	}
429 
430 	if (ferror(to)) {
431 		snprintf(errbuf, errbufsz, "%s", strerror(errno));
432 		return (0);
433 	}
434 	(void)fclose(to);
435 
436 	return (done);
437 }
438 
439 void
440 pw_error(const char *name, int error, int eval)
441 {
442 
443 	if (error) {
444 		if (name)
445 			warn("%s", name);
446 		else
447 			warn(NULL);
448 	}
449 
450 	warnx("%s%s: unchanged", pw_prefix, _PATH_MASTERPASSWD);
451 	pw_abort();
452 	exit(eval);
453 }
454 
455 /* Removes head and/or tail spaces. */
456 static void
457 trim_whitespace(char *line)
458 {
459 	char *p;
460 
461 	_DIAGASSERT(line != NULL);
462 
463 	/* Remove leading spaces */
464 	p = line;
465 	while (isspace((unsigned char) *p))
466 		p++;
467 	memmove(line, p, strlen(p) + 1);
468 
469 	/* Remove trailing spaces */
470 	p = line + strlen(line) - 1;
471 	while (isspace((unsigned char) *p))
472 		p--;
473 	*(p + 1) = '\0';
474 }
475 
476 
477 /* Get one line, remove spaces from front and tail */
478 static int
479 read_line(FILE *fp, char *line, int max)
480 {
481 	char   *p;
482 
483 	_DIAGASSERT(fp != NULL);
484 	_DIAGASSERT(line != NULL);
485 
486 	/* Read one line of config */
487 	if (fgets(line, max, fp) == NULL)
488 		return (0);
489 
490 	if ((p = strchr(line, '\n')) == NULL) {
491 		warnx("line too long");
492 		return (0);
493 	}
494 	*p = '\0';
495 
496 	/* Remove comments */
497 	if ((p = strchr(line, '#')) != NULL)
498 		*p = '\0';
499 
500 	trim_whitespace(line);
501 	return (1);
502 }
503 
504 static const char *
505 pw_default(const char *option)
506 {
507 	static const char *options[][2] = {
508 		{ "localcipher",	"old" },
509 		{ "ypcipher",		"old" },
510 	};
511 	int i;
512 
513 	_DIAGASSERT(option != NULL);
514 	for (i = 0; i < sizeof(options) / sizeof(options[0]); i++)
515 		if (strcmp(options[i][0], option) == 0)
516 			return (options[i][1]);
517 
518 	return (NULL);
519 }
520 
521 /*
522  * Retrieve password information from the /etc/passwd.conf file, at the
523  * moment this is only for choosing the cipher to use.  It could easily be
524  * used for other authentication methods as well.
525  */
526 void
527 pw_getconf(char *data, size_t max, const char *key, const char *option)
528 {
529 	FILE *fp;
530 	char line[LINE_MAX], *p, *p2;
531 	static char result[LINE_MAX];
532 	int got, found;
533 	const char *cp;
534 
535 	_DIAGASSERT(data != NULL);
536 	_DIAGASSERT(key != NULL);
537 	_DIAGASSERT(option != NULL);
538 
539 	got = 0;
540 	found = 0;
541 	result[0] = '\0';
542 
543 	if ((fp = fopen(_PATH_PASSWD_CONF, "r")) == NULL) {
544 		if ((cp = pw_default(option)) != NULL)
545 			strlcpy(data, cp, max);
546 		else
547 			data[0] = '\0';
548 		return;
549 	}
550 
551 	while (!found && (got || read_line(fp, line, LINE_MAX))) {
552 		got = 0;
553 
554 		if (strncmp(key, line, strlen(key)) != 0 ||
555 		    line[strlen(key)] != ':')
556 			continue;
557 
558 		/* Now we found our specified key */
559 		while (read_line(fp, line, LINE_MAX)) {
560 			/* Leaving key field */
561 			if (line[0] != '\0' && strchr(line + 1, ':') != NULL) {
562 				got = 1;
563 				break;
564 			}
565 			p2 = line;
566 			if ((p = strsep(&p2, "=")) == NULL || p2 == NULL)
567 				continue;
568 			trim_whitespace(p);
569 
570 			if (!strncmp(p, option, strlen(option))) {
571 				trim_whitespace(p2);
572 				strcpy(result, p2);
573 				found = 1;
574 				break;
575 			}
576 		}
577 	}
578 	fclose(fp);
579 
580 	if (!found)
581 		errno = ENOENT;
582 	if (!got)
583 		errno = ENOTDIR;
584 
585 	/*
586 	 * If we got no result and were looking for a default
587 	 * value, try hard coded defaults.
588 	 */
589 
590 	if (strlen(result) == 0 && strcmp(key, "default") == 0 &&
591 	    (cp = pw_default(option)) != NULL)
592 		strlcpy(data, cp, max);
593 	else
594 		strlcpy(data, result, max);
595 }
596 
597 void
598 pw_getpwconf(char *data, size_t max, const struct passwd *pwd,
599     const char *option)
600 {
601 	char grpkey[LINE_MAX];
602 	struct group *grp;
603 
604 	pw_getconf(data, max, pwd->pw_name, option);
605 
606 	/* Try to find an entry for the group */
607 	if (*data == '\0') {
608 		if ((grp = getgrgid(pwd->pw_gid)) != NULL) {
609 			snprintf(grpkey, sizeof(grpkey), ":%s", grp->gr_name);
610 			pw_getconf(data, max, grpkey, option);
611 		}
612 		if (*data == '\0')
613 		        pw_getconf(data, max, "default", option);
614 	}
615 }
616