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