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