xref: /minix3/lib/libutil/passwd.c (revision 58a2b0008e28f606a7f7f5faaeaba4faac57a1ea)
1 /*	$NetBSD: passwd.c,v 1.50 2010/08/18 08:32:02 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.50 2010/08/18 08:32:02 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] = "-pl";
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) {
170 		warn("error waiting for pid %lu", (unsigned long)pid);
171 		return -1;
172 	}
173 	if (WIFEXITED(pstat)) {
174 		if (WEXITSTATUS(pstat) != 0) {
175 			warnx("pwd_mkdb exited with static %d",
176 			    WEXITSTATUS(pstat));
177 			return -1;
178 		}
179 	} else if (WIFSIGNALED(pstat)) {
180 		warnx("pwd_mkdb exited with signal %d", WTERMSIG(pstat));
181 		return -1;
182 	}
183 	return 0;
184 }
185 
186 int
187 pw_abort(void)
188 {
189 	const char *filename;
190 
191 	filename = pw_filename(_PATH_MASTERPASSWD_LOCK);
192 	return((filename == NULL) ? -1 : unlink(filename));
193 }
194 
195 /* Everything below this point is intended for the convenience of programs
196  * which allow a user to interactively edit the passwd file.  Errors in the
197  * routines below will cause the process to abort. */
198 
199 static pid_t editpid = -1;
200 
201 static void
202 pw_cont(int sig)
203 {
204 
205 	if (editpid != -1)
206 		kill(editpid, sig);
207 }
208 
209 void
210 pw_init(void)
211 {
212 #ifndef __minix
213 	struct rlimit rlim;
214 
215 	/* Unlimited resource limits. */
216 	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
217 	(void)setrlimit(RLIMIT_CPU, &rlim);
218 	(void)setrlimit(RLIMIT_FSIZE, &rlim);
219 	(void)setrlimit(RLIMIT_STACK, &rlim);
220 	(void)setrlimit(RLIMIT_DATA, &rlim);
221 	(void)setrlimit(RLIMIT_RSS, &rlim);
222 
223 	/* Don't drop core (not really necessary, but GP's). */
224 	rlim.rlim_cur = rlim.rlim_max = 0;
225 	(void)setrlimit(RLIMIT_CORE, &rlim);
226 #endif
227 
228 	/* Turn off signals. */
229 	(void)signal(SIGALRM, SIG_IGN);
230 	(void)signal(SIGHUP, SIG_IGN);
231 	(void)signal(SIGINT, SIG_IGN);
232 	(void)signal(SIGPIPE, SIG_IGN);
233 	(void)signal(SIGQUIT, SIG_IGN);
234 	(void)signal(SIGTERM, SIG_IGN);
235 	(void)signal(SIGCONT, pw_cont);
236 }
237 
238 void
239 pw_edit(int notsetuid, const char *filename)
240 {
241 	int pstat;
242 	char *p;
243 	const char * volatile editor;
244 	const char *argp[] = { "sh", "-c", NULL, NULL };
245 
246 	if (filename == NULL)
247 		filename = _PATH_MASTERPASSWD_LOCK;
248 
249 	filename = pw_filename(filename);
250 	if (filename == NULL)
251 		return;
252 
253 	if ((editor = getenv("EDITOR")) == NULL)
254 		editor = _PATH_VI;
255 
256 	p = malloc(strlen(editor) + 1 + strlen(filename) + 1);
257 	if (p == NULL)
258 		return;
259 
260 	sprintf(p, "%s %s", editor, filename);
261 	argp[2] = p;
262 
263 	switch(editpid = vfork()) {
264 	case -1:
265 		free(p);
266 		return;
267 	case 0:
268 		if (notsetuid) {
269 			setgid(getgid());
270 			setuid(getuid());
271 		}
272 		execvp(_PATH_BSHELL, (char *const *)__UNCONST(argp));
273 		_exit(1);
274 	}
275 
276 	free(p);
277 
278 	for (;;) {
279 		editpid = waitpid(editpid, (int *)&pstat, WUNTRACED);
280 		if (editpid == -1)
281 			pw_error(editor, 1, 1);
282 		else if (WIFSTOPPED(pstat))
283 			raise(WSTOPSIG(pstat));
284 		else if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0)
285 			break;
286 		else
287 			pw_error(editor, 1, 1);
288 	}
289 	editpid = -1;
290 }
291 
292 void
293 pw_prompt(void)
294 {
295 	int c;
296 
297 	(void)printf("re-edit the password file? [y]: ");
298 	(void)fflush(stdout);
299 	c = getchar();
300 	if (c != EOF && c != '\n')
301 		while (getchar() != '\n');
302 	if (c == 'n')
303 		pw_error(NULL, 0, 0);
304 }
305 
306 /* for use in pw_copy(). Compare a pw entry to a pw struct. */
307 /* returns a character string labelling the miscompared field or 0 */
308 static const char *
309 pw_equal(char *buf, struct passwd *pw)
310 {
311 	struct passwd buf_pw;
312 	size_t len;
313 
314 	_DIAGASSERT(buf != NULL);
315 	_DIAGASSERT(pw != NULL);
316 
317 	len = strlen (buf);
318 	if (buf[len-1] == '\n')
319 		buf[len-1] = '\0';
320 	if (!pw_scan(buf, &buf_pw, NULL))
321 		return "corrupt line";
322 	if (strcmp(pw->pw_name, buf_pw.pw_name) != 0)
323 		return "name";
324 	if (pw->pw_uid != buf_pw.pw_uid)
325 		return "uid";
326 	if (pw->pw_gid != buf_pw.pw_gid)
327 		return "gid";
328 	if (strcmp( pw->pw_class, buf_pw.pw_class) != 0)
329 		return "class";
330 	if (pw->pw_change != buf_pw.pw_change)
331 		return "change";
332 	if (pw->pw_expire != buf_pw.pw_expire)
333 		return "expire";
334 	if (strcmp( pw->pw_gecos, buf_pw.pw_gecos) != 0)
335 		return "gecos";
336 	if (strcmp( pw->pw_dir, buf_pw.pw_dir) != 0)
337 		return "dir";
338 	if (strcmp( pw->pw_shell, buf_pw.pw_shell) != 0)
339 		return "shell";
340 	return (char *)0;
341 }
342 
343 void
344 pw_copy(int ffd, int tfd, struct passwd *pw, struct passwd *old_pw)
345 {
346 	char errbuf[200];
347 	int rv;
348 
349 	rv = pw_copyx(ffd, tfd, pw, old_pw, errbuf, sizeof(errbuf));
350 	if (rv == 0) {
351 		warnx("%s", errbuf);
352 		pw_error(NULL, 0, 1);
353 	}
354 }
355 
356 static void
357 pw_print(FILE *to, const struct passwd *pw)
358 {
359 	(void)fprintf(to, "%s:%s:%d:%d:%s:%lld:%lld:%s:%s:%s\n",
360 	    pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid,
361 	    pw->pw_class, (long long)pw->pw_change,
362 	    (long long)pw->pw_expire,
363 	    pw->pw_gecos, pw->pw_dir, pw->pw_shell);
364 }
365 
366 int
367 pw_copyx(int ffd, int tfd, struct passwd *pw, struct passwd *old_pw,
368     char *errbuf, size_t errbufsz)
369 {
370 	const char *filename;
371 	char mpwd[MAXPATHLEN], mpwdl[MAXPATHLEN], *p, buf[8192];
372 	FILE *from, *to;
373 	int done;
374 
375 	_DIAGASSERT(pw != NULL);
376 	_DIAGASSERT(errbuf != NULL);
377 	/* old_pw may be NULL */
378 
379 	if ((filename = pw_filename(_PATH_MASTERPASSWD)) == NULL) {
380 		snprintf(errbuf, errbufsz, "%s: %s", pw_prefix,
381 		    strerror(errno));
382 		return (0);
383 	}
384 	(void)strcpy(mpwd, filename);
385 	if ((filename = pw_filename(_PATH_MASTERPASSWD_LOCK)) == NULL) {
386 		snprintf(errbuf, errbufsz, "%s: %s", pw_prefix,
387 		    strerror(errno));
388 		return (0);
389 	}
390 	(void)strcpy(mpwdl, filename);
391 
392 	if (!(from = fdopen(ffd, "r"))) {
393 		snprintf(errbuf, errbufsz, "%s: %s", mpwd, strerror(errno));
394 		return (0);
395 	}
396 	if (!(to = fdopen(tfd, "w"))) {
397 		snprintf(errbuf, errbufsz, "%s: %s", mpwdl, strerror(errno));
398 		(void)fclose(from);
399 		return (0);
400 	}
401 
402 	for (done = 0; fgets(buf, (int)sizeof(buf), from);) {
403 		const char *neq;
404 		if (!strchr(buf, '\n')) {
405 			snprintf(errbuf, errbufsz, "%s: line too long", mpwd);
406 			(void)fclose(from);
407 			(void)fclose(to);
408 			return (0);
409 		}
410 		if (done) {
411 			(void)fprintf(to, "%s", buf);
412 			if (ferror(to)) {
413 				snprintf(errbuf, errbufsz, "%s",
414 				    strerror(errno));
415 				(void)fclose(from);
416 				(void)fclose(to);
417 				return (0);
418 			}
419 			continue;
420 		}
421 		if (!(p = strchr(buf, ':'))) {
422 			snprintf(errbuf, errbufsz, "%s: corrupted entry", mpwd);
423 			(void)fclose(from);
424 			(void)fclose(to);
425 			return (0);
426 		}
427 		*p = '\0';
428 		if (strcmp(buf, pw->pw_name)) {
429 			*p = ':';
430 			(void)fprintf(to, "%s", buf);
431 			if (ferror(to)) {
432 				snprintf(errbuf, errbufsz, "%s",
433 				    strerror(errno));
434 				(void)fclose(from);
435 				(void)fclose(to);
436 				return (0);
437 			}
438 			continue;
439 		}
440 		*p = ':';
441 		if (old_pw && (neq = pw_equal(buf, old_pw)) != NULL) {
442 			if (strcmp(neq, "corrupt line") == 0)
443 				(void)snprintf(errbuf, errbufsz,
444 				    "%s: entry %s corrupted", mpwd,
445 				    pw->pw_name);
446 			else
447 				(void)snprintf(errbuf, errbufsz,
448 				    "%s: entry %s inconsistent %s",
449 				    mpwd, pw->pw_name, neq);
450 			(void)fclose(from);
451 			(void)fclose(to);
452 			return (0);
453 		}
454 		pw_print(to, pw);
455 		done = 1;
456 		if (ferror(to)) {
457 			snprintf(errbuf, errbufsz, "%s", strerror(errno));
458 			(void)fclose(from);
459 			(void)fclose(to);
460 			return (0);
461 		}
462 	}
463 	/* Only append a new entry if real uid is root! */
464 	if (!done) {
465 		if (getuid() == 0) {
466 			pw_print(to, pw);
467 			done = 1;
468 		} else {
469 			snprintf(errbuf, errbufsz,
470 			    "%s: changes not made, no such entry", mpwd);
471 		}
472 	}
473 
474 	if (ferror(to)) {
475 		snprintf(errbuf, errbufsz, "%s", strerror(errno));
476 		(void)fclose(from);
477 		(void)fclose(to);
478 		return (0);
479 	}
480 	(void)fclose(from);
481 	(void)fclose(to);
482 
483 	return (done);
484 }
485 
486 void
487 pw_error(const char *name, int error, int eval)
488 {
489 
490 	if (error) {
491 		if (name)
492 			warn("%s", name);
493 		else
494 			warn(NULL);
495 	}
496 
497 	warnx("%s%s: unchanged", pw_prefix, _PATH_MASTERPASSWD);
498 	pw_abort();
499 	exit(eval);
500 }
501 
502 /* Removes head and/or tail spaces. */
503 static void
504 trim_whitespace(char *line)
505 {
506 	char *p;
507 
508 	_DIAGASSERT(line != NULL);
509 
510 	/* Remove leading spaces */
511 	p = line;
512 	while (isspace((unsigned char) *p))
513 		p++;
514 	memmove(line, p, strlen(p) + 1);
515 
516 	/* Remove trailing spaces */
517 	p = line + strlen(line) - 1;
518 	while (isspace((unsigned char) *p))
519 		p--;
520 	*(p + 1) = '\0';
521 }
522 
523 
524 /* Get one line, remove spaces from front and tail */
525 static int
526 read_line(FILE *fp, char *line, int max)
527 {
528 	char   *p;
529 
530 	_DIAGASSERT(fp != NULL);
531 	_DIAGASSERT(line != NULL);
532 
533 	/* Read one line of config */
534 	if (fgets(line, max, fp) == NULL)
535 		return (0);
536 
537 	if ((p = strchr(line, '\n')) == NULL) {
538 		warnx("line too long");
539 		return (0);
540 	}
541 	*p = '\0';
542 
543 	/* Remove comments */
544 	if ((p = strchr(line, '#')) != NULL)
545 		*p = '\0';
546 
547 	trim_whitespace(line);
548 	return (1);
549 }
550 
551 static const char *
552 pw_default(const char *option)
553 {
554 	static const char *options[][2] = {
555 		{ "localcipher",	"old" },
556 		{ "ypcipher",		"old" },
557 	};
558 	size_t i;
559 
560 	_DIAGASSERT(option != NULL);
561 	for (i = 0; i < sizeof(options) / sizeof(options[0]); i++)
562 		if (strcmp(options[i][0], option) == 0)
563 			return (options[i][1]);
564 
565 	return (NULL);
566 }
567 
568 /*
569  * Retrieve password information from the /etc/passwd.conf file, at the
570  * moment this is only for choosing the cipher to use.  It could easily be
571  * used for other authentication methods as well.
572  */
573 void
574 pw_getconf(char *data, size_t max, const char *key, const char *option)
575 {
576 	FILE *fp;
577 	char line[LINE_MAX], *p, *p2;
578 	static char result[LINE_MAX];
579 	int got, found;
580 	const char *cp;
581 
582 	_DIAGASSERT(data != NULL);
583 	_DIAGASSERT(key != NULL);
584 	_DIAGASSERT(option != NULL);
585 
586 	got = 0;
587 	found = 0;
588 	result[0] = '\0';
589 
590 	if ((fp = fopen(_PATH_PASSWD_CONF, "r")) == NULL) {
591 		if ((cp = pw_default(option)) != NULL)
592 			strlcpy(data, cp, max);
593 		else
594 			data[0] = '\0';
595 		return;
596 	}
597 
598 	while (!found && (got || read_line(fp, line, LINE_MAX))) {
599 		got = 0;
600 
601 		if (strncmp(key, line, strlen(key)) != 0 ||
602 		    line[strlen(key)] != ':')
603 			continue;
604 
605 		/* Now we found our specified key */
606 		while (read_line(fp, line, LINE_MAX)) {
607 			/* Leaving key field */
608 			if (line[0] != '\0' && strchr(line + 1, ':') != NULL) {
609 				got = 1;
610 				break;
611 			}
612 			p2 = line;
613 			if ((p = strsep(&p2, "=")) == NULL || p2 == NULL)
614 				continue;
615 			trim_whitespace(p);
616 
617 			if (!strncmp(p, option, strlen(option))) {
618 				trim_whitespace(p2);
619 				strcpy(result, p2);
620 				found = 1;
621 				break;
622 			}
623 		}
624 	}
625 	fclose(fp);
626 
627 	if (!found)
628 		errno = ENOENT;
629 	if (!got)
630 		errno = ENOTDIR;
631 
632 	/*
633 	 * If we got no result and were looking for a default
634 	 * value, try hard coded defaults.
635 	 */
636 
637 	if (strlen(result) == 0 && strcmp(key, "default") == 0 &&
638 	    (cp = pw_default(option)) != NULL)
639 		strlcpy(data, cp, max);
640 	else
641 		strlcpy(data, result, max);
642 }
643 
644 void
645 pw_getpwconf(char *data, size_t max, const struct passwd *pwd,
646     const char *option)
647 {
648 	char grpkey[LINE_MAX];
649 	struct group grs, *grp;
650 	char grbuf[1024];
651 
652 	pw_getconf(data, max, pwd->pw_name, option);
653 
654 	/* Try to find an entry for the group */
655 	if (*data == '\0') {
656 		(void)getgrgid_r(pwd->pw_gid, &grs, grbuf, sizeof(grbuf), &grp);
657 		if (grp != NULL) {
658 			(void)snprintf(grpkey, sizeof(grpkey), ":%s",
659 			    grp->gr_name);
660 			pw_getconf(data, max, grpkey, option);
661 		}
662 		if (*data == '\0')
663 		        pw_getconf(data, max, "default", option);
664 	}
665 }
666