xref: /openbsd-src/usr.bin/ssh/auth.c (revision 850e275390052b330d93020bf619a739a3c277ac)
1 /* $OpenBSD: auth.c,v 1.79 2008/07/02 12:03:51 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 
40 #include "xmalloc.h"
41 #include "match.h"
42 #include "groupaccess.h"
43 #include "log.h"
44 #include "buffer.h"
45 #include "servconf.h"
46 #include "key.h"
47 #include "hostfile.h"
48 #include "auth.h"
49 #include "auth-options.h"
50 #include "canohost.h"
51 #include "uidswap.h"
52 #include "misc.h"
53 #include "packet.h"
54 #ifdef GSSAPI
55 #include "ssh-gss.h"
56 #endif
57 #include "monitor_wrap.h"
58 
59 /* import */
60 extern ServerOptions options;
61 extern int use_privsep;
62 
63 /* Debugging messages */
64 Buffer auth_debug;
65 int auth_debug_init;
66 
67 /*
68  * Check if the user is allowed to log in via ssh. If user is listed
69  * in DenyUsers or one of user's groups is listed in DenyGroups, false
70  * will be returned. If AllowUsers isn't empty and user isn't listed
71  * there, or if AllowGroups isn't empty and one of user's groups isn't
72  * listed there, false will be returned.
73  * If the user's shell is not executable, false will be returned.
74  * Otherwise true is returned.
75  */
76 int
77 allowed_user(struct passwd * pw)
78 {
79 	struct stat st;
80 	const char *hostname = NULL, *ipaddr = NULL;
81 	char *shell;
82 	u_int i;
83 
84 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
85 	if (!pw || !pw->pw_name)
86 		return 0;
87 
88 	/*
89 	 * Get the shell from the password data.  An empty shell field is
90 	 * legal, and means /bin/sh.
91 	 */
92 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
93 
94 	/* deny if shell does not exists or is not executable */
95 	if (stat(shell, &st) != 0) {
96 		logit("User %.100s not allowed because shell %.100s does not exist",
97 		    pw->pw_name, shell);
98 		return 0;
99 	}
100 	if (S_ISREG(st.st_mode) == 0 ||
101 	    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
102 		logit("User %.100s not allowed because shell %.100s is not executable",
103 		    pw->pw_name, shell);
104 		return 0;
105 	}
106 
107 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
108 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
109 		hostname = get_canonical_hostname(options.use_dns);
110 		ipaddr = get_remote_ipaddr();
111 	}
112 
113 	/* Return false if user is listed in DenyUsers */
114 	if (options.num_deny_users > 0) {
115 		for (i = 0; i < options.num_deny_users; i++)
116 			if (match_user(pw->pw_name, hostname, ipaddr,
117 			    options.deny_users[i])) {
118 				logit("User %.100s from %.100s not allowed "
119 				    "because listed in DenyUsers",
120 				    pw->pw_name, hostname);
121 				return 0;
122 			}
123 	}
124 	/* Return false if AllowUsers isn't empty and user isn't listed there */
125 	if (options.num_allow_users > 0) {
126 		for (i = 0; i < options.num_allow_users; i++)
127 			if (match_user(pw->pw_name, hostname, ipaddr,
128 			    options.allow_users[i]))
129 				break;
130 		/* i < options.num_allow_users iff we break for loop */
131 		if (i >= options.num_allow_users) {
132 			logit("User %.100s from %.100s not allowed because "
133 			    "not listed in AllowUsers", pw->pw_name, hostname);
134 			return 0;
135 		}
136 	}
137 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
138 		/* Get the user's group access list (primary and supplementary) */
139 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
140 			logit("User %.100s from %.100s not allowed because "
141 			    "not in any group", pw->pw_name, hostname);
142 			return 0;
143 		}
144 
145 		/* Return false if one of user's groups is listed in DenyGroups */
146 		if (options.num_deny_groups > 0)
147 			if (ga_match(options.deny_groups,
148 			    options.num_deny_groups)) {
149 				ga_free();
150 				logit("User %.100s from %.100s not allowed "
151 				    "because a group is listed in DenyGroups",
152 				    pw->pw_name, hostname);
153 				return 0;
154 			}
155 		/*
156 		 * Return false if AllowGroups isn't empty and one of user's groups
157 		 * isn't listed there
158 		 */
159 		if (options.num_allow_groups > 0)
160 			if (!ga_match(options.allow_groups,
161 			    options.num_allow_groups)) {
162 				ga_free();
163 				logit("User %.100s from %.100s not allowed "
164 				    "because none of user's groups are listed "
165 				    "in AllowGroups", pw->pw_name, hostname);
166 				return 0;
167 			}
168 		ga_free();
169 	}
170 	/* We found no reason not to let this user try to log on... */
171 	return 1;
172 }
173 
174 void
175 auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
176 {
177 	void (*authlog) (const char *fmt,...) = verbose;
178 	char *authmsg;
179 
180 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
181 		return;
182 
183 	/* Raise logging level */
184 	if (authenticated == 1 ||
185 	    !authctxt->valid ||
186 	    authctxt->failures >= options.max_authtries / 2 ||
187 	    strcmp(method, "password") == 0)
188 		authlog = logit;
189 
190 	if (authctxt->postponed)
191 		authmsg = "Postponed";
192 	else
193 		authmsg = authenticated ? "Accepted" : "Failed";
194 
195 	authlog("%s %s for %s%.100s from %.200s port %d%s",
196 	    authmsg,
197 	    method,
198 	    authctxt->valid ? "" : "invalid user ",
199 	    authctxt->user,
200 	    get_remote_ipaddr(),
201 	    get_remote_port(),
202 	    info);
203 }
204 
205 /*
206  * Check whether root logins are disallowed.
207  */
208 int
209 auth_root_allowed(char *method)
210 {
211 	switch (options.permit_root_login) {
212 	case PERMIT_YES:
213 		return 1;
214 	case PERMIT_NO_PASSWD:
215 		if (strcmp(method, "password") != 0)
216 			return 1;
217 		break;
218 	case PERMIT_FORCED_ONLY:
219 		if (forced_command) {
220 			logit("Root login accepted for forced command.");
221 			return 1;
222 		}
223 		break;
224 	}
225 	logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
226 	return 0;
227 }
228 
229 
230 /*
231  * Given a template and a passwd structure, build a filename
232  * by substituting % tokenised options. Currently, %% becomes '%',
233  * %h becomes the home directory and %u the username.
234  *
235  * This returns a buffer allocated by xmalloc.
236  */
237 static char *
238 expand_authorized_keys(const char *filename, struct passwd *pw)
239 {
240 	char *file, ret[MAXPATHLEN];
241 	int i;
242 
243 	file = percent_expand(filename, "h", pw->pw_dir,
244 	    "u", pw->pw_name, (char *)NULL);
245 
246 	/*
247 	 * Ensure that filename starts anchored. If not, be backward
248 	 * compatible and prepend the '%h/'
249 	 */
250 	if (*file == '/')
251 		return (file);
252 
253 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
254 	if (i < 0 || (size_t)i >= sizeof(ret))
255 		fatal("expand_authorized_keys: path too long");
256 	xfree(file);
257 	return (xstrdup(ret));
258 }
259 
260 char *
261 authorized_keys_file(struct passwd *pw)
262 {
263 	return expand_authorized_keys(options.authorized_keys_file, pw);
264 }
265 
266 char *
267 authorized_keys_file2(struct passwd *pw)
268 {
269 	return expand_authorized_keys(options.authorized_keys_file2, pw);
270 }
271 
272 /* return ok if key exists in sysfile or userfile */
273 HostStatus
274 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
275     const char *sysfile, const char *userfile)
276 {
277 	Key *found;
278 	char *user_hostfile;
279 	struct stat st;
280 	HostStatus host_status;
281 
282 	/* Check if we know the host and its host key. */
283 	found = key_new(key->type);
284 	host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
285 
286 	if (host_status != HOST_OK && userfile != NULL) {
287 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
288 		if (options.strict_modes &&
289 		    (stat(user_hostfile, &st) == 0) &&
290 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
291 		    (st.st_mode & 022) != 0)) {
292 			logit("Authentication refused for %.100s: "
293 			    "bad owner or modes for %.200s",
294 			    pw->pw_name, user_hostfile);
295 		} else {
296 			temporarily_use_uid(pw);
297 			host_status = check_host_in_hostfile(user_hostfile,
298 			    host, key, found, NULL);
299 			restore_uid();
300 		}
301 		xfree(user_hostfile);
302 	}
303 	key_free(found);
304 
305 	debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
306 	    "ok" : "not found", host);
307 	return host_status;
308 }
309 
310 
311 /*
312  * Check a given file for security. This is defined as all components
313  * of the path to the file must be owned by either the owner of
314  * of the file or root and no directories must be group or world writable.
315  *
316  * XXX Should any specific check be done for sym links ?
317  *
318  * Takes an open file descriptor, the file name, a uid and and
319  * error buffer plus max size as arguments.
320  *
321  * Returns 0 on success and -1 on failure
322  */
323 static int
324 secure_filename(FILE *f, const char *file, struct passwd *pw,
325     char *err, size_t errlen)
326 {
327 	uid_t uid = pw->pw_uid;
328 	char buf[MAXPATHLEN], homedir[MAXPATHLEN];
329 	char *cp;
330 	int comparehome = 0;
331 	struct stat st;
332 
333 	if (realpath(file, buf) == NULL) {
334 		snprintf(err, errlen, "realpath %s failed: %s", file,
335 		    strerror(errno));
336 		return -1;
337 	}
338 	if (realpath(pw->pw_dir, homedir) != NULL)
339 		comparehome = 1;
340 
341 	/* check the open file to avoid races */
342 	if (fstat(fileno(f), &st) < 0 ||
343 	    (st.st_uid != 0 && st.st_uid != uid) ||
344 	    (st.st_mode & 022) != 0) {
345 		snprintf(err, errlen, "bad ownership or modes for file %s",
346 		    buf);
347 		return -1;
348 	}
349 
350 	/* for each component of the canonical path, walking upwards */
351 	for (;;) {
352 		if ((cp = dirname(buf)) == NULL) {
353 			snprintf(err, errlen, "dirname() failed");
354 			return -1;
355 		}
356 		strlcpy(buf, cp, sizeof(buf));
357 
358 		debug3("secure_filename: checking '%s'", buf);
359 		if (stat(buf, &st) < 0 ||
360 		    (st.st_uid != 0 && st.st_uid != uid) ||
361 		    (st.st_mode & 022) != 0) {
362 			snprintf(err, errlen,
363 			    "bad ownership or modes for directory %s", buf);
364 			return -1;
365 		}
366 
367 		/* If are passed the homedir then we can stop */
368 		if (comparehome && strcmp(homedir, buf) == 0) {
369 			debug3("secure_filename: terminating check at '%s'",
370 			    buf);
371 			break;
372 		}
373 		/*
374 		 * dirname should always complete with a "/" path,
375 		 * but we can be paranoid and check for "." too
376 		 */
377 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
378 			break;
379 	}
380 	return 0;
381 }
382 
383 FILE *
384 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
385 {
386 	char line[1024];
387 	struct stat st;
388 	int fd;
389 	FILE *f;
390 
391 	/*
392 	 * Open the file containing the authorized keys
393 	 * Fail quietly if file does not exist
394 	 */
395 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1)
396 		return NULL;
397 
398 	if (fstat(fd, &st) < 0) {
399 		close(fd);
400 		return NULL;
401 	}
402 	if (!S_ISREG(st.st_mode)) {
403 		logit("User %s authorized keys %s is not a regular file",
404 		    pw->pw_name, file);
405 		close(fd);
406 		return NULL;
407 	}
408 	unset_nonblock(fd);
409 	if ((f = fdopen(fd, "r")) == NULL) {
410 		close(fd);
411 		return NULL;
412 	}
413 	if (options.strict_modes &&
414 	    secure_filename(f, file, pw, line, sizeof(line)) != 0) {
415 		fclose(f);
416 		logit("Authentication refused: %s", line);
417 		return NULL;
418 	}
419 
420 	return f;
421 }
422 
423 struct passwd *
424 getpwnamallow(const char *user)
425 {
426 	extern login_cap_t *lc;
427 	auth_session_t *as;
428 	struct passwd *pw;
429 
430 	parse_server_match_config(&options, user,
431 	    get_canonical_hostname(options.use_dns), get_remote_ipaddr());
432 
433 	pw = getpwnam(user);
434 	if (pw == NULL) {
435 		logit("Invalid user %.100s from %.100s",
436 		    user, get_remote_ipaddr());
437 		return (NULL);
438 	}
439 	if (!allowed_user(pw))
440 		return (NULL);
441 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
442 		debug("unable to get login class: %s", user);
443 		return (NULL);
444 	}
445 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
446 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
447 		debug("Approval failure for %s", user);
448 		pw = NULL;
449 	}
450 	if (as != NULL)
451 		auth_close(as);
452 	if (pw != NULL)
453 		return (pwcopy(pw));
454 	return (NULL);
455 }
456 
457 void
458 auth_debug_add(const char *fmt,...)
459 {
460 	char buf[1024];
461 	va_list args;
462 
463 	if (!auth_debug_init)
464 		return;
465 
466 	va_start(args, fmt);
467 	vsnprintf(buf, sizeof(buf), fmt, args);
468 	va_end(args);
469 	buffer_put_cstring(&auth_debug, buf);
470 }
471 
472 void
473 auth_debug_send(void)
474 {
475 	char *msg;
476 
477 	if (!auth_debug_init)
478 		return;
479 	while (buffer_len(&auth_debug)) {
480 		msg = buffer_get_string(&auth_debug, NULL);
481 		packet_send_debug("%s", msg);
482 		xfree(msg);
483 	}
484 }
485 
486 void
487 auth_debug_reset(void)
488 {
489 	if (auth_debug_init)
490 		buffer_clear(&auth_debug);
491 	else {
492 		buffer_init(&auth_debug);
493 		auth_debug_init = 1;
494 	}
495 }
496 
497 struct passwd *
498 fakepw(void)
499 {
500 	static struct passwd fake;
501 
502 	memset(&fake, 0, sizeof(fake));
503 	fake.pw_name = "NOUSER";
504 	fake.pw_passwd =
505 	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
506 	fake.pw_gecos = "NOUSER";
507 	fake.pw_uid = (uid_t)-1;
508 	fake.pw_gid = (gid_t)-1;
509 	fake.pw_class = "";
510 	fake.pw_dir = "/nonexist";
511 	fake.pw_shell = "/nonexist";
512 
513 	return (&fake);
514 }
515