xref: /openbsd-src/usr.bin/ssh/auth.c (revision aa5e9e10509ffd51558f081f01cd78bfa3c4f2a5)
1 /* $OpenBSD: auth.c,v 1.103 2013/05/19 02:42:42 djm 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 #include "krl.h"
61 #include "compat.h"
62 
63 /* import */
64 extern ServerOptions options;
65 extern int use_privsep;
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 	u_int i;
86 
87 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
88 	if (!pw || !pw->pw_name)
89 		return 0;
90 
91 	/*
92 	 * Deny if shell does not exist or is not executable unless we
93 	 * are chrooting.
94 	 */
95 	if (options.chroot_directory == NULL ||
96 	    strcasecmp(options.chroot_directory, "none") == 0) {
97 		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
98 		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
99 
100 		if (stat(shell, &st) != 0) {
101 			logit("User %.100s not allowed because shell %.100s "
102 			    "does not exist", pw->pw_name, shell);
103 			free(shell);
104 			return 0;
105 		}
106 		if (S_ISREG(st.st_mode) == 0 ||
107 		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
108 			logit("User %.100s not allowed because shell %.100s "
109 			    "is not executable", pw->pw_name, shell);
110 			free(shell);
111 			return 0;
112 		}
113 		free(shell);
114 	}
115 
116 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
117 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
118 		hostname = get_canonical_hostname(options.use_dns);
119 		ipaddr = get_remote_ipaddr();
120 	}
121 
122 	/* Return false if user is listed in DenyUsers */
123 	if (options.num_deny_users > 0) {
124 		for (i = 0; i < options.num_deny_users; i++)
125 			if (match_user(pw->pw_name, hostname, ipaddr,
126 			    options.deny_users[i])) {
127 				logit("User %.100s from %.100s not allowed "
128 				    "because listed in DenyUsers",
129 				    pw->pw_name, hostname);
130 				return 0;
131 			}
132 	}
133 	/* Return false if AllowUsers isn't empty and user isn't listed there */
134 	if (options.num_allow_users > 0) {
135 		for (i = 0; i < options.num_allow_users; i++)
136 			if (match_user(pw->pw_name, hostname, ipaddr,
137 			    options.allow_users[i]))
138 				break;
139 		/* i < options.num_allow_users iff we break for loop */
140 		if (i >= options.num_allow_users) {
141 			logit("User %.100s from %.100s not allowed because "
142 			    "not listed in AllowUsers", pw->pw_name, hostname);
143 			return 0;
144 		}
145 	}
146 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
147 		/* Get the user's group access list (primary and supplementary) */
148 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
149 			logit("User %.100s from %.100s not allowed because "
150 			    "not in any group", pw->pw_name, hostname);
151 			return 0;
152 		}
153 
154 		/* Return false if one of user's groups is listed in DenyGroups */
155 		if (options.num_deny_groups > 0)
156 			if (ga_match(options.deny_groups,
157 			    options.num_deny_groups)) {
158 				ga_free();
159 				logit("User %.100s from %.100s not allowed "
160 				    "because a group is listed in DenyGroups",
161 				    pw->pw_name, hostname);
162 				return 0;
163 			}
164 		/*
165 		 * Return false if AllowGroups isn't empty and one of user's groups
166 		 * isn't listed there
167 		 */
168 		if (options.num_allow_groups > 0)
169 			if (!ga_match(options.allow_groups,
170 			    options.num_allow_groups)) {
171 				ga_free();
172 				logit("User %.100s from %.100s not allowed "
173 				    "because none of user's groups are listed "
174 				    "in AllowGroups", pw->pw_name, hostname);
175 				return 0;
176 			}
177 		ga_free();
178 	}
179 	/* We found no reason not to let this user try to log on... */
180 	return 1;
181 }
182 
183 void
184 auth_info(Authctxt *authctxt, const char *fmt, ...)
185 {
186 	va_list ap;
187         int i;
188 
189 	free(authctxt->info);
190 	authctxt->info = NULL;
191 
192 	va_start(ap, fmt);
193 	i = vasprintf(&authctxt->info, fmt, ap);
194 	va_end(ap);
195 
196 	if (i < 0 || authctxt->info == NULL)
197 		fatal("vasprintf failed");
198 }
199 
200 void
201 auth_log(Authctxt *authctxt, int authenticated, int partial,
202     const char *method, const char *submethod)
203 {
204 	void (*authlog) (const char *fmt,...) = verbose;
205 	char *authmsg;
206 
207 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
208 		return;
209 
210 	/* Raise logging level */
211 	if (authenticated == 1 ||
212 	    !authctxt->valid ||
213 	    authctxt->failures >= options.max_authtries / 2 ||
214 	    strcmp(method, "password") == 0)
215 		authlog = logit;
216 
217 	if (authctxt->postponed)
218 		authmsg = "Postponed";
219 	else if (partial)
220 		authmsg = "Partial";
221 	else
222 		authmsg = authenticated ? "Accepted" : "Failed";
223 
224 	authlog("%s %s%s%s for %s%.100s from %.200s port %d %s%s%s",
225 	    authmsg,
226 	    method,
227 	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
228 	    authctxt->valid ? "" : "invalid user ",
229 	    authctxt->user,
230 	    get_remote_ipaddr(),
231 	    get_remote_port(),
232 	    compat20 ? "ssh2" : "ssh1",
233 	    authctxt->info != NULL ? ": " : "",
234 	    authctxt->info != NULL ? authctxt->info : "");
235 	free(authctxt->info);
236 	authctxt->info = NULL;
237 }
238 
239 /*
240  * Check whether root logins are disallowed.
241  */
242 int
243 auth_root_allowed(const char *method)
244 {
245 	switch (options.permit_root_login) {
246 	case PERMIT_YES:
247 		return 1;
248 	case PERMIT_NO_PASSWD:
249 		if (strcmp(method, "password") != 0)
250 			return 1;
251 		break;
252 	case PERMIT_FORCED_ONLY:
253 		if (forced_command) {
254 			logit("Root login accepted for forced command.");
255 			return 1;
256 		}
257 		break;
258 	}
259 	logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
260 	return 0;
261 }
262 
263 
264 /*
265  * Given a template and a passwd structure, build a filename
266  * by substituting % tokenised options. Currently, %% becomes '%',
267  * %h becomes the home directory and %u the username.
268  *
269  * This returns a buffer allocated by xmalloc.
270  */
271 char *
272 expand_authorized_keys(const char *filename, struct passwd *pw)
273 {
274 	char *file, ret[MAXPATHLEN];
275 	int i;
276 
277 	file = percent_expand(filename, "h", pw->pw_dir,
278 	    "u", pw->pw_name, (char *)NULL);
279 
280 	/*
281 	 * Ensure that filename starts anchored. If not, be backward
282 	 * compatible and prepend the '%h/'
283 	 */
284 	if (*file == '/')
285 		return (file);
286 
287 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
288 	if (i < 0 || (size_t)i >= sizeof(ret))
289 		fatal("expand_authorized_keys: path too long");
290 	free(file);
291 	return (xstrdup(ret));
292 }
293 
294 char *
295 authorized_principals_file(struct passwd *pw)
296 {
297 	if (options.authorized_principals_file == NULL ||
298 	    strcasecmp(options.authorized_principals_file, "none") == 0)
299 		return NULL;
300 	return expand_authorized_keys(options.authorized_principals_file, pw);
301 }
302 
303 /* return ok if key exists in sysfile or userfile */
304 HostStatus
305 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
306     const char *sysfile, const char *userfile)
307 {
308 	char *user_hostfile;
309 	struct stat st;
310 	HostStatus host_status;
311 	struct hostkeys *hostkeys;
312 	const struct hostkey_entry *found;
313 
314 	hostkeys = init_hostkeys();
315 	load_hostkeys(hostkeys, host, sysfile);
316 	if (userfile != NULL) {
317 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
318 		if (options.strict_modes &&
319 		    (stat(user_hostfile, &st) == 0) &&
320 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
321 		    (st.st_mode & 022) != 0)) {
322 			logit("Authentication refused for %.100s: "
323 			    "bad owner or modes for %.200s",
324 			    pw->pw_name, user_hostfile);
325 			auth_debug_add("Ignored %.200s: bad ownership or modes",
326 			    user_hostfile);
327 		} else {
328 			temporarily_use_uid(pw);
329 			load_hostkeys(hostkeys, host, user_hostfile);
330 			restore_uid();
331 		}
332 		free(user_hostfile);
333 	}
334 	host_status = check_key_in_hostkeys(hostkeys, key, &found);
335 	if (host_status == HOST_REVOKED)
336 		error("WARNING: revoked key for %s attempted authentication",
337 		    found->host);
338 	else if (host_status == HOST_OK)
339 		debug("%s: key for %s found at %s:%ld", __func__,
340 		    found->host, found->file, found->line);
341 	else
342 		debug("%s: key for host %s not found", __func__, host);
343 
344 	free_hostkeys(hostkeys);
345 
346 	return host_status;
347 }
348 
349 /*
350  * Check a given path for security. This is defined as all components
351  * of the path to the file must be owned by either the owner of
352  * of the file or root and no directories must be group or world writable.
353  *
354  * XXX Should any specific check be done for sym links ?
355  *
356  * Takes a file name, its stat information (preferably from fstat() to
357  * avoid races), the uid of the expected owner, their home directory and an
358  * error buffer plus max size as arguments.
359  *
360  * Returns 0 on success and -1 on failure
361  */
362 int
363 auth_secure_path(const char *name, struct stat *stp, const char *pw_dir,
364     uid_t uid, char *err, size_t errlen)
365 {
366 	char buf[MAXPATHLEN], homedir[MAXPATHLEN];
367 	char *cp;
368 	int comparehome = 0;
369 	struct stat st;
370 
371 	if (realpath(name, buf) == NULL) {
372 		snprintf(err, errlen, "realpath %s failed: %s", name,
373 		    strerror(errno));
374 		return -1;
375 	}
376 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
377 		comparehome = 1;
378 
379 	if (!S_ISREG(stp->st_mode)) {
380 		snprintf(err, errlen, "%s is not a regular file", buf);
381 		return -1;
382 	}
383 	if ((stp->st_uid != 0 && stp->st_uid != uid) ||
384 	    (stp->st_mode & 022) != 0) {
385 		snprintf(err, errlen, "bad ownership or modes for file %s",
386 		    buf);
387 		return -1;
388 	}
389 
390 	/* for each component of the canonical path, walking upwards */
391 	for (;;) {
392 		if ((cp = dirname(buf)) == NULL) {
393 			snprintf(err, errlen, "dirname() failed");
394 			return -1;
395 		}
396 		strlcpy(buf, cp, sizeof(buf));
397 
398 		if (stat(buf, &st) < 0 ||
399 		    (st.st_uid != 0 && st.st_uid != uid) ||
400 		    (st.st_mode & 022) != 0) {
401 			snprintf(err, errlen,
402 			    "bad ownership or modes for directory %s", buf);
403 			return -1;
404 		}
405 
406 		/* If are past the homedir then we can stop */
407 		if (comparehome && strcmp(homedir, buf) == 0)
408 			break;
409 
410 		/*
411 		 * dirname should always complete with a "/" path,
412 		 * but we can be paranoid and check for "." too
413 		 */
414 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
415 			break;
416 	}
417 	return 0;
418 }
419 
420 /*
421  * Version of secure_path() that accepts an open file descriptor to
422  * avoid races.
423  *
424  * Returns 0 on success and -1 on failure
425  */
426 static int
427 secure_filename(FILE *f, const char *file, struct passwd *pw,
428     char *err, size_t errlen)
429 {
430 	struct stat st;
431 
432 	/* check the open file to avoid races */
433 	if (fstat(fileno(f), &st) < 0) {
434 		snprintf(err, errlen, "cannot stat file %s: %s",
435 		    file, strerror(errno));
436 		return -1;
437 	}
438 	return auth_secure_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
439 }
440 
441 static FILE *
442 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
443     int log_missing, char *file_type)
444 {
445 	char line[1024];
446 	struct stat st;
447 	int fd;
448 	FILE *f;
449 
450 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
451 		if (log_missing || errno != ENOENT)
452 			debug("Could not open %s '%s': %s", file_type, file,
453 			   strerror(errno));
454 		return NULL;
455 	}
456 
457 	if (fstat(fd, &st) < 0) {
458 		close(fd);
459 		return NULL;
460 	}
461 	if (!S_ISREG(st.st_mode)) {
462 		logit("User %s %s %s is not a regular file",
463 		    pw->pw_name, file_type, file);
464 		close(fd);
465 		return NULL;
466 	}
467 	unset_nonblock(fd);
468 	if ((f = fdopen(fd, "r")) == NULL) {
469 		close(fd);
470 		return NULL;
471 	}
472 	if (strict_modes &&
473 	    secure_filename(f, file, pw, line, sizeof(line)) != 0) {
474 		fclose(f);
475 		logit("Authentication refused: %s", line);
476 		auth_debug_add("Ignored %s: %s", file_type, line);
477 		return NULL;
478 	}
479 
480 	return f;
481 }
482 
483 
484 FILE *
485 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
486 {
487 	return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
488 }
489 
490 FILE *
491 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
492 {
493 	return auth_openfile(file, pw, strict_modes, 0,
494 	    "authorized principals");
495 }
496 
497 struct passwd *
498 getpwnamallow(const char *user)
499 {
500 	extern login_cap_t *lc;
501 	auth_session_t *as;
502 	struct passwd *pw;
503 	struct connection_info *ci = get_connection_info(1, options.use_dns);
504 
505 	ci->user = user;
506 	parse_server_match_config(&options, ci);
507 
508 	pw = getpwnam(user);
509 	if (pw == NULL) {
510 		logit("Invalid user %.100s from %.100s",
511 		    user, get_remote_ipaddr());
512 		return (NULL);
513 	}
514 	if (!allowed_user(pw))
515 		return (NULL);
516 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
517 		debug("unable to get login class: %s", user);
518 		return (NULL);
519 	}
520 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
521 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
522 		debug("Approval failure for %s", user);
523 		pw = NULL;
524 	}
525 	if (as != NULL)
526 		auth_close(as);
527 	if (pw != NULL)
528 		return (pwcopy(pw));
529 	return (NULL);
530 }
531 
532 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
533 int
534 auth_key_is_revoked(Key *key)
535 {
536 	char *key_fp;
537 
538 	if (options.revoked_keys_file == NULL)
539 		return 0;
540 	switch (ssh_krl_file_contains_key(options.revoked_keys_file, key)) {
541 	case 0:
542 		return 0;	/* Not revoked */
543 	case -2:
544 		break;		/* Not a KRL */
545 	default:
546 		goto revoked;
547 	}
548 	debug3("%s: treating %s as a key list", __func__,
549 	    options.revoked_keys_file);
550 	switch (key_in_file(key, options.revoked_keys_file, 0)) {
551 	case 0:
552 		/* key not revoked */
553 		return 0;
554 	case -1:
555 		/* Error opening revoked_keys_file: refuse all keys */
556 		error("Revoked keys file is unreadable: refusing public key "
557 		    "authentication");
558 		return 1;
559 	case 1:
560  revoked:
561 		/* Key revoked */
562 		key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
563 		error("WARNING: authentication attempt with a revoked "
564 		    "%s key %s ", key_type(key), key_fp);
565 		free(key_fp);
566 		return 1;
567 	}
568 	fatal("key_in_file returned junk");
569 }
570 
571 void
572 auth_debug_add(const char *fmt,...)
573 {
574 	char buf[1024];
575 	va_list args;
576 
577 	if (!auth_debug_init)
578 		return;
579 
580 	va_start(args, fmt);
581 	vsnprintf(buf, sizeof(buf), fmt, args);
582 	va_end(args);
583 	buffer_put_cstring(&auth_debug, buf);
584 }
585 
586 void
587 auth_debug_send(void)
588 {
589 	char *msg;
590 
591 	if (!auth_debug_init)
592 		return;
593 	while (buffer_len(&auth_debug)) {
594 		msg = buffer_get_string(&auth_debug, NULL);
595 		packet_send_debug("%s", msg);
596 		free(msg);
597 	}
598 }
599 
600 void
601 auth_debug_reset(void)
602 {
603 	if (auth_debug_init)
604 		buffer_clear(&auth_debug);
605 	else {
606 		buffer_init(&auth_debug);
607 		auth_debug_init = 1;
608 	}
609 }
610 
611 struct passwd *
612 fakepw(void)
613 {
614 	static struct passwd fake;
615 
616 	memset(&fake, 0, sizeof(fake));
617 	fake.pw_name = "NOUSER";
618 	fake.pw_passwd =
619 	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
620 	fake.pw_gecos = "NOUSER";
621 	fake.pw_uid = (uid_t)-1;
622 	fake.pw_gid = (gid_t)-1;
623 	fake.pw_class = "";
624 	fake.pw_dir = "/nonexist";
625 	fake.pw_shell = "/nonexist";
626 
627 	return (&fake);
628 }
629