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