xref: /netbsd-src/crypto/external/bsd/openssh/dist/auth.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: auth.c,v 1.2 2009/06/07 22:38:46 christos Exp $	*/
2 /* $OpenBSD: auth.c,v 1.80 2008/11/04 07:58:09 djm Exp $ */
3 /*
4  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "includes.h"
28 __RCSID("$NetBSD: auth.c,v 1.2 2009/06/07 22:38:46 christos Exp $");
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/param.h>
32 
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <libgen.h>
36 #include <login_cap.h>
37 #include <paths.h>
38 #include <pwd.h>
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <unistd.h>
43 
44 #include "xmalloc.h"
45 #include "match.h"
46 #include "groupaccess.h"
47 #include "log.h"
48 #include "buffer.h"
49 #include "servconf.h"
50 #include "key.h"
51 #include "hostfile.h"
52 #include "auth.h"
53 #include "auth-options.h"
54 #include "canohost.h"
55 #include "uidswap.h"
56 #include "misc.h"
57 #include "packet.h"
58 #ifdef GSSAPI
59 #include "ssh-gss.h"
60 #endif
61 #include "monitor_wrap.h"
62 
63 #ifdef HAVE_LOGIN_CAP
64 #include <login_cap.h>
65 #endif
66 
67 /* import */
68 extern ServerOptions options;
69 extern int use_privsep;
70 
71 /* Debugging messages */
72 Buffer auth_debug;
73 int auth_debug_init;
74 
75 /*
76  * Check if the user is allowed to log in via ssh. If user is listed
77  * in DenyUsers or one of user's groups is listed in DenyGroups, false
78  * will be returned. If AllowUsers isn't empty and user isn't listed
79  * there, or if AllowGroups isn't empty and one of user's groups isn't
80  * listed there, false will be returned.
81  * If the user's shell is not executable, false will be returned.
82  * Otherwise true is returned.
83  */
84 int
85 allowed_user(struct passwd * pw)
86 {
87 #ifdef HAVE_LOGIN_CAP
88 	extern login_cap_t *lc;
89 	int match_name, match_ip;
90 	char *cap_hlist, *hp;
91 #endif
92 	struct stat st;
93 	const char *hostname = NULL, *ipaddr = NULL;
94 	char *shell;
95 	u_int i;
96 
97 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
98 	if (!pw || !pw->pw_name)
99 		return 0;
100 
101 #ifdef HAVE_LOGIN_CAP
102 	hostname = get_canonical_hostname(1);
103 	ipaddr = get_remote_ipaddr();
104 
105 	lc = login_getclass(pw->pw_class);
106 
107 	/*
108 	 * Check the deny list.
109 	 */
110 	cap_hlist = login_getcapstr(lc, "host.deny", NULL, NULL);
111 	if (cap_hlist != NULL) {
112 		hp = strtok(cap_hlist, ",");
113 		while (hp != NULL) {
114 			match_name = match_hostname(hostname,
115 			    hp, strlen(hp));
116 			match_ip = match_hostname(ipaddr,
117 			    hp, strlen(hp));
118 			/*
119 			 * Only a positive match here causes a "deny".
120 			 */
121 			if (match_name > 0 || match_ip > 0) {
122 				free(cap_hlist);
123 				login_close(lc);
124 				return 0;
125 			}
126 			hp = strtok(NULL, ",");
127 		}
128 		free(cap_hlist);
129 	}
130 
131 	/*
132 	 * Check the allow list.  If the allow list exists, and the
133 	 * remote host is not in it, the user is implicitly denied.
134 	 */
135 	cap_hlist = login_getcapstr(lc, "host.allow", NULL, NULL);
136 	if (cap_hlist != NULL) {
137 		hp = strtok(cap_hlist, ",");
138 		if (hp == NULL) {
139 			/* Just in case there's an empty string... */
140 			free(cap_hlist);
141 			login_close(lc);
142 			return 0;
143 		}
144 		while (hp != NULL) {
145 			match_name = match_hostname(hostname,
146 			    hp, strlen(hp));
147 			match_ip = match_hostname(ipaddr,
148 			    hp, strlen(hp));
149 			/*
150 			 * Negative match causes an immediate "deny".
151 			 * Positive match causes us to break out
152 			 * of the loop (allowing a fallthrough).
153 			 */
154 			if (match_name < 0 || match_ip < 0) {
155 				free(cap_hlist);
156 				login_close(lc);
157 				return 0;
158 			}
159 			if (match_name > 0 || match_ip > 0)
160 				break;
161 			hp = strtok(NULL, ",");
162 		}
163 		free(cap_hlist);
164 		if (hp == NULL) {
165 			login_close(lc);
166 			return 0;
167 		}
168 	}
169 
170 	login_close(lc);
171 #endif
172 
173 #ifdef USE_PAM
174 	if (!options.use_pam) {
175 #endif
176 	/*
177 	 * password/account expiration.
178 	 */
179 	if (pw->pw_change || pw->pw_expire) {
180 		struct timeval tv;
181 
182 		(void)gettimeofday(&tv, (struct timezone *)NULL);
183 		if (pw->pw_expire) {
184 			if (tv.tv_sec >= pw->pw_expire) {
185 				logit("User %.100s not allowed because account has expired",
186 				    pw->pw_name);
187 				return 0;	/* expired */
188 			}
189 		}
190 #ifdef _PASSWORD_CHGNOW
191 		if (pw->pw_change == _PASSWORD_CHGNOW) {
192 			logit("User %.100s not allowed because password needs to be changed",
193 			    pw->pw_name);
194 
195 			return 0;	/* can't force password change (yet) */
196 		}
197 #endif
198 		if (pw->pw_change) {
199 			if (tv.tv_sec >= pw->pw_change) {
200 				logit("User %.100s not allowed because password has expired",
201 				    pw->pw_name);
202 				return 0;	/* expired */
203 			}
204 		}
205 	}
206 #ifdef USE_PAM
207 	}
208 #endif
209 
210 	/*
211 	 * Get the shell from the password data.  An empty shell field is
212 	 * legal, and means /bin/sh.
213 	 */
214 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
215 
216 	/* deny if shell does not exists or is not executable */
217 	/*
218 	 * XXX Should check to see if it is executable by the
219 	 * XXX requesting user.  --thorpej
220 	 */
221 	if (stat(shell, &st) != 0) {
222 		logit("User %.100s not allowed because shell %.100s does not exist",
223 		    pw->pw_name, shell);
224 		return 0;
225 	}
226 	if (S_ISREG(st.st_mode) == 0 ||
227 	    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
228 		logit("User %.100s not allowed because shell %.100s is not executable",
229 		    pw->pw_name, shell);
230 		return 0;
231 	}
232 	/*
233 	 * XXX Consider nuking {Allow,Deny}{Users,Groups}.  We have the
234 	 * XXX login_cap(3) mechanism which covers all other types of
235 	 * XXX logins, too.
236 	 */
237 
238 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
239 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
240 		hostname = get_canonical_hostname(options.use_dns);
241 		ipaddr = get_remote_ipaddr();
242 	}
243 
244 	/* Return false if user is listed in DenyUsers */
245 	if (options.num_deny_users > 0) {
246 		for (i = 0; i < options.num_deny_users; i++)
247 			if (match_user(pw->pw_name, hostname, ipaddr,
248 			    options.deny_users[i])) {
249 				logit("User %.100s from %.100s not allowed "
250 				    "because listed in DenyUsers",
251 				    pw->pw_name, hostname);
252 				return 0;
253 			}
254 	}
255 	/* Return false if AllowUsers isn't empty and user isn't listed there */
256 	if (options.num_allow_users > 0) {
257 		for (i = 0; i < options.num_allow_users; i++)
258 			if (match_user(pw->pw_name, hostname, ipaddr,
259 			    options.allow_users[i]))
260 				break;
261 		/* i < options.num_allow_users iff we break for loop */
262 		if (i >= options.num_allow_users) {
263 			logit("User %.100s from %.100s not allowed because "
264 			    "not listed in AllowUsers", pw->pw_name, hostname);
265 			return 0;
266 		}
267 	}
268 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
269 		/* Get the user's group access list (primary and supplementary) */
270 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
271 			logit("User %.100s from %.100s not allowed because "
272 			    "not in any group", pw->pw_name, hostname);
273 			return 0;
274 		}
275 
276 		/* Return false if one of user's groups is listed in DenyGroups */
277 		if (options.num_deny_groups > 0)
278 			if (ga_match(options.deny_groups,
279 			    options.num_deny_groups)) {
280 				ga_free();
281 				logit("User %.100s from %.100s not allowed "
282 				    "because a group is listed in DenyGroups",
283 				    pw->pw_name, hostname);
284 				return 0;
285 			}
286 		/*
287 		 * Return false if AllowGroups isn't empty and one of user's groups
288 		 * isn't listed there
289 		 */
290 		if (options.num_allow_groups > 0)
291 			if (!ga_match(options.allow_groups,
292 			    options.num_allow_groups)) {
293 				ga_free();
294 				logit("User %.100s from %.100s not allowed "
295 				    "because none of user's groups are listed "
296 				    "in AllowGroups", pw->pw_name, hostname);
297 				return 0;
298 			}
299 		ga_free();
300 	}
301 	/* We found no reason not to let this user try to log on... */
302 	return 1;
303 }
304 
305 void
306 auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
307 {
308 	void (*authlog) (const char *fmt,...) = verbose;
309 	char *authmsg;
310 
311 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
312 		return;
313 
314 	/* Raise logging level */
315 	if (authenticated == 1 ||
316 	    !authctxt->valid ||
317 	    authctxt->failures >= options.max_authtries / 2 ||
318 	    strcmp(method, "password") == 0)
319 		authlog = logit;
320 
321 	if (authctxt->postponed)
322 		authmsg = "Postponed";
323 	else
324 		authmsg = authenticated ? "Accepted" : "Failed";
325 
326 	authlog("%s %s for %s%.100s from %.200s port %d%s",
327 	    authmsg,
328 	    method,
329 	    authctxt->valid ? "" : "invalid user ",
330 	    authctxt->user,
331 	    get_remote_ipaddr(),
332 	    get_remote_port(),
333 	    info);
334 }
335 
336 /*
337  * Check whether root logins are disallowed.
338  */
339 int
340 auth_root_allowed(char *method)
341 {
342 	switch (options.permit_root_login) {
343 	case PERMIT_YES:
344 		return 1;
345 	case PERMIT_NO_PASSWD:
346 		if (strcmp(method, "password") != 0)
347 			return 1;
348 		break;
349 	case PERMIT_FORCED_ONLY:
350 		if (forced_command) {
351 			logit("Root login accepted for forced command.");
352 			return 1;
353 		}
354 		break;
355 	}
356 	logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
357 	return 0;
358 }
359 
360 
361 /*
362  * Given a template and a passwd structure, build a filename
363  * by substituting % tokenised options. Currently, %% becomes '%',
364  * %h becomes the home directory and %u the username.
365  *
366  * This returns a buffer allocated by xmalloc.
367  */
368 static char *
369 expand_authorized_keys(const char *filename, struct passwd *pw)
370 {
371 	char *file, ret[MAXPATHLEN];
372 	int i;
373 
374 	file = percent_expand(filename, "h", pw->pw_dir,
375 	    "u", pw->pw_name, (char *)NULL);
376 
377 	/*
378 	 * Ensure that filename starts anchored. If not, be backward
379 	 * compatible and prepend the '%h/'
380 	 */
381 	if (*file == '/')
382 		return (file);
383 
384 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
385 	if (i < 0 || (size_t)i >= sizeof(ret))
386 		fatal("expand_authorized_keys: path too long");
387 	xfree(file);
388 	return (xstrdup(ret));
389 }
390 
391 char *
392 authorized_keys_file(struct passwd *pw)
393 {
394 	return expand_authorized_keys(options.authorized_keys_file, pw);
395 }
396 
397 char *
398 authorized_keys_file2(struct passwd *pw)
399 {
400 	return expand_authorized_keys(options.authorized_keys_file2, pw);
401 }
402 
403 /* return ok if key exists in sysfile or userfile */
404 HostStatus
405 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
406     const char *sysfile, const char *userfile)
407 {
408 	Key *found;
409 	char *user_hostfile;
410 	struct stat st;
411 	HostStatus host_status;
412 
413 	/* Check if we know the host and its host key. */
414 	found = key_new(key->type);
415 	host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
416 
417 	if (host_status != HOST_OK && userfile != NULL) {
418 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
419 		if (options.strict_modes &&
420 		    (stat(user_hostfile, &st) == 0) &&
421 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
422 		    (st.st_mode & 022) != 0)) {
423 			logit("Authentication refused for %.100s: "
424 			    "bad owner or modes for %.200s",
425 			    pw->pw_name, user_hostfile);
426 		} else {
427 			temporarily_use_uid(pw);
428 			host_status = check_host_in_hostfile(user_hostfile,
429 			    host, key, found, NULL);
430 			restore_uid();
431 		}
432 		xfree(user_hostfile);
433 	}
434 	key_free(found);
435 
436 	debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
437 	    "ok" : "not found", host);
438 	return host_status;
439 }
440 
441 
442 /*
443  * Check a given file for security. This is defined as all components
444  * of the path to the file must be owned by either the owner of
445  * of the file or root and no directories must be group or world writable.
446  *
447  * XXX Should any specific check be done for sym links ?
448  *
449  * Takes an open file descriptor, the file name, a uid and and
450  * error buffer plus max size as arguments.
451  *
452  * Returns 0 on success and -1 on failure
453  */
454 static int
455 secure_filename(FILE *f, const char *file, struct passwd *pw,
456     char *err, size_t errlen)
457 {
458 	uid_t uid = pw->pw_uid;
459 	char buf[MAXPATHLEN], homedir[MAXPATHLEN];
460 	char *cp;
461 	int comparehome = 0;
462 	struct stat st;
463 
464 	if (realpath(file, buf) == NULL) {
465 		snprintf(err, errlen, "realpath %s failed: %s", file,
466 		    strerror(errno));
467 		return -1;
468 	}
469 	if (realpath(pw->pw_dir, homedir) != NULL)
470 		comparehome = 1;
471 
472 	/* check the open file to avoid races */
473 	if (fstat(fileno(f), &st) < 0 ||
474 	    (st.st_uid != 0 && st.st_uid != uid) ||
475 	    (st.st_mode & 022) != 0) {
476 		snprintf(err, errlen, "bad ownership or modes for file %s",
477 		    buf);
478 		return -1;
479 	}
480 
481 	/* for each component of the canonical path, walking upwards */
482 	for (;;) {
483 		if ((cp = dirname(buf)) == NULL) {
484 			snprintf(err, errlen, "dirname() failed");
485 			return -1;
486 		}
487 		strlcpy(buf, cp, sizeof(buf));
488 
489 		debug3("secure_filename: checking '%s'", buf);
490 		if (stat(buf, &st) < 0 ||
491 		    (st.st_uid != 0 && st.st_uid != uid) ||
492 		    (st.st_mode & 022) != 0) {
493 			snprintf(err, errlen,
494 			    "bad ownership or modes for directory %s", buf);
495 			return -1;
496 		}
497 
498 		/* If are passed the homedir then we can stop */
499 		if (comparehome && strcmp(homedir, buf) == 0) {
500 			debug3("secure_filename: terminating check at '%s'",
501 			    buf);
502 			break;
503 		}
504 		/*
505 		 * dirname should always complete with a "/" path,
506 		 * but we can be paranoid and check for "." too
507 		 */
508 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
509 			break;
510 	}
511 	return 0;
512 }
513 
514 FILE *
515 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
516 {
517 	char line[1024];
518 	struct stat st;
519 	int fd;
520 	FILE *f;
521 
522 	/*
523 	 * Open the file containing the authorized keys
524 	 * Fail quietly if file does not exist
525 	 */
526 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1)
527 		return NULL;
528 
529 	if (fstat(fd, &st) < 0) {
530 		close(fd);
531 		return NULL;
532 	}
533 	if (!S_ISREG(st.st_mode)) {
534 		logit("User %s authorized keys %s is not a regular file",
535 		    pw->pw_name, file);
536 		close(fd);
537 		return NULL;
538 	}
539 	unset_nonblock(fd);
540 	if ((f = fdopen(fd, "r")) == NULL) {
541 		close(fd);
542 		return NULL;
543 	}
544 	if (options.strict_modes &&
545 	    secure_filename(f, file, pw, line, sizeof(line)) != 0) {
546 		fclose(f);
547 		logit("Authentication refused: %s", line);
548 		return NULL;
549 	}
550 
551 	return f;
552 }
553 
554 struct passwd *
555 getpwnamallow(const char *user)
556 {
557 #ifdef HAVE_LOGIN_CAP
558  	extern login_cap_t *lc;
559 #ifdef BSD_AUTH
560  	auth_session_t *as;
561 #endif
562 #endif
563 	struct passwd *pw;
564 
565 	parse_server_match_config(&options, user,
566 	    get_canonical_hostname(options.use_dns), get_remote_ipaddr());
567 
568 	pw = getpwnam(user);
569 	if (pw == NULL) {
570 		logit("Invalid user %.100s from %.100s",
571 		    user, get_remote_ipaddr());
572 		return (NULL);
573 	}
574 	if (!allowed_user(pw))
575 		return (NULL);
576 #ifdef HAVE_LOGIN_CAP
577 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
578 		debug("unable to get login class: %s", user);
579 		return (NULL);
580 	}
581 #ifdef BSD_AUTH
582 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
583 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
584 		debug("Approval failure for %s", user);
585 		pw = NULL;
586 	}
587 	if (as != NULL)
588 		auth_close(as);
589 #endif
590 #endif
591 	if (pw != NULL)
592 		return (pwcopy(pw));
593 	return (NULL);
594 }
595 
596 void
597 auth_debug_add(const char *fmt,...)
598 {
599 	char buf[1024];
600 	va_list args;
601 
602 	if (!auth_debug_init)
603 		return;
604 
605 	va_start(args, fmt);
606 	vsnprintf(buf, sizeof(buf), fmt, args);
607 	va_end(args);
608 	buffer_put_cstring(&auth_debug, buf);
609 }
610 
611 void
612 auth_debug_send(void)
613 {
614 	char *msg;
615 
616 	if (!auth_debug_init)
617 		return;
618 	while (buffer_len(&auth_debug)) {
619 		msg = buffer_get_string(&auth_debug, NULL);
620 		packet_send_debug("%s", msg);
621 		xfree(msg);
622 	}
623 }
624 
625 void
626 auth_debug_reset(void)
627 {
628 	if (auth_debug_init)
629 		buffer_clear(&auth_debug);
630 	else {
631 		buffer_init(&auth_debug);
632 		auth_debug_init = 1;
633 	}
634 }
635 
636 struct passwd *
637 fakepw(void)
638 {
639 	static struct passwd fake;
640 
641 	memset(&fake, 0, sizeof(fake));
642 	fake.pw_name = "NOUSER";
643 	fake.pw_passwd =
644 	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
645 	fake.pw_gecos = "NOUSER";
646 	fake.pw_uid = (uid_t)-1;
647 	fake.pw_gid = (gid_t)-1;
648 	fake.pw_class = "";
649 	fake.pw_dir = "/nonexist";
650 	fake.pw_shell = "/nonexist";
651 
652 	return (&fake);
653 }
654