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