xref: /openbsd-src/usr.bin/ssh/auth.c (revision 47911bd667ac77dc523b8a13ef40b012dbffa741)
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.46 2002/11/04 10:07:53 markus 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 		log("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 		log("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.verify_reverse_mapping);
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 				log("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 			log("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 			log("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 				log("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 				log("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 Authctxt *
157 authctxt_new(void)
158 {
159 	Authctxt *authctxt = xmalloc(sizeof(*authctxt));
160 	memset(authctxt, 0, sizeof(*authctxt));
161 	return authctxt;
162 }
163 
164 void
165 auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
166 {
167 	void (*authlog) (const char *fmt,...) = verbose;
168 	char *authmsg;
169 
170 	/* Raise logging level */
171 	if (authenticated == 1 ||
172 	    !authctxt->valid ||
173 	    authctxt->failures >= AUTH_FAIL_LOG ||
174 	    strcmp(method, "password") == 0)
175 		authlog = log;
176 
177 	if (authctxt->postponed)
178 		authmsg = "Postponed";
179 	else
180 		authmsg = authenticated ? "Accepted" : "Failed";
181 
182 	authlog("%s %s for %s%.100s from %.200s port %d%s",
183 	    authmsg,
184 	    method,
185 	    authctxt->valid ? "" : "illegal user ",
186 	    authctxt->user,
187 	    get_remote_ipaddr(),
188 	    get_remote_port(),
189 	    info);
190 }
191 
192 /*
193  * Check whether root logins are disallowed.
194  */
195 int
196 auth_root_allowed(char *method)
197 {
198 	switch (options.permit_root_login) {
199 	case PERMIT_YES:
200 		return 1;
201 		break;
202 	case PERMIT_NO_PASSWD:
203 		if (strcmp(method, "password") != 0)
204 			return 1;
205 		break;
206 	case PERMIT_FORCED_ONLY:
207 		if (forced_command) {
208 			log("Root login accepted for forced command.");
209 			return 1;
210 		}
211 		break;
212 	}
213 	log("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
214 	return 0;
215 }
216 
217 
218 /*
219  * Given a template and a passwd structure, build a filename
220  * by substituting % tokenised options. Currently, %% becomes '%',
221  * %h becomes the home directory and %u the username.
222  *
223  * This returns a buffer allocated by xmalloc.
224  */
225 char *
226 expand_filename(const char *filename, struct passwd *pw)
227 {
228 	Buffer buffer;
229 	char *file;
230 	const char *cp;
231 
232 	/*
233 	 * Build the filename string in the buffer by making the appropriate
234 	 * substitutions to the given file name.
235 	 */
236 	buffer_init(&buffer);
237 	for (cp = filename; *cp; cp++) {
238 		if (cp[0] == '%' && cp[1] == '%') {
239 			buffer_append(&buffer, "%", 1);
240 			cp++;
241 			continue;
242 		}
243 		if (cp[0] == '%' && cp[1] == 'h') {
244 			buffer_append(&buffer, pw->pw_dir, strlen(pw->pw_dir));
245 			cp++;
246 			continue;
247 		}
248 		if (cp[0] == '%' && cp[1] == 'u') {
249 			buffer_append(&buffer, pw->pw_name,
250 			    strlen(pw->pw_name));
251 			cp++;
252 			continue;
253 		}
254 		buffer_append(&buffer, cp, 1);
255 	}
256 	buffer_append(&buffer, "\0", 1);
257 
258 	/*
259 	 * Ensure that filename starts anchored. If not, be backward
260 	 * compatible and prepend the '%h/'
261 	 */
262 	file = xmalloc(MAXPATHLEN);
263 	cp = buffer_ptr(&buffer);
264 	if (*cp != '/')
265 		snprintf(file, MAXPATHLEN, "%s/%s", pw->pw_dir, cp);
266 	else
267 		strlcpy(file, cp, MAXPATHLEN);
268 
269 	buffer_free(&buffer);
270 	return file;
271 }
272 
273 char *
274 authorized_keys_file(struct passwd *pw)
275 {
276 	return expand_filename(options.authorized_keys_file, pw);
277 }
278 
279 char *
280 authorized_keys_file2(struct passwd *pw)
281 {
282 	return expand_filename(options.authorized_keys_file2, pw);
283 }
284 
285 /* return ok if key exists in sysfile or userfile */
286 HostStatus
287 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
288     const char *sysfile, const char *userfile)
289 {
290 	Key *found;
291 	char *user_hostfile;
292 	struct stat st;
293 	HostStatus host_status;
294 
295 	/* Check if we know the host and its host key. */
296 	found = key_new(key->type);
297 	host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
298 
299 	if (host_status != HOST_OK && userfile != NULL) {
300 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
301 		if (options.strict_modes &&
302 		    (stat(user_hostfile, &st) == 0) &&
303 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
304 		    (st.st_mode & 022) != 0)) {
305 			log("Authentication refused for %.100s: "
306 			    "bad owner or modes for %.200s",
307 			    pw->pw_name, user_hostfile);
308 		} else {
309 			temporarily_use_uid(pw);
310 			host_status = check_host_in_hostfile(user_hostfile,
311 			    host, key, found, NULL);
312 			restore_uid();
313 		}
314 		xfree(user_hostfile);
315 	}
316 	key_free(found);
317 
318 	debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
319 	    "ok" : "not found", host);
320 	return host_status;
321 }
322 
323 
324 /*
325  * Check a given file for security. This is defined as all components
326  * of the path to the file must be owned by either the owner of
327  * of the file or root and no directories must be group or world writable.
328  *
329  * XXX Should any specific check be done for sym links ?
330  *
331  * Takes an open file descriptor, the file name, a uid and and
332  * error buffer plus max size as arguments.
333  *
334  * Returns 0 on success and -1 on failure
335  */
336 int
337 secure_filename(FILE *f, const char *file, struct passwd *pw,
338     char *err, size_t errlen)
339 {
340 	uid_t uid = pw->pw_uid;
341 	char buf[MAXPATHLEN], homedir[MAXPATHLEN];
342 	char *cp;
343 	int comparehome = 0;
344 	struct stat st;
345 
346 	if (realpath(file, buf) == NULL) {
347 		snprintf(err, errlen, "realpath %s failed: %s", file,
348 		    strerror(errno));
349 		return -1;
350 	}
351 	if (realpath(pw->pw_dir, homedir) != NULL)
352 		comparehome = 1;
353 
354 	/* check the open file to avoid races */
355 	if (fstat(fileno(f), &st) < 0 ||
356 	    (st.st_uid != 0 && st.st_uid != uid) ||
357 	    (st.st_mode & 022) != 0) {
358 		snprintf(err, errlen, "bad ownership or modes for file %s",
359 		    buf);
360 		return -1;
361 	}
362 
363 	/* for each component of the canonical path, walking upwards */
364 	for (;;) {
365 		if ((cp = dirname(buf)) == NULL) {
366 			snprintf(err, errlen, "dirname() failed");
367 			return -1;
368 		}
369 		strlcpy(buf, cp, sizeof(buf));
370 
371 		debug3("secure_filename: checking '%s'", buf);
372 		if (stat(buf, &st) < 0 ||
373 		    (st.st_uid != 0 && st.st_uid != uid) ||
374 		    (st.st_mode & 022) != 0) {
375 			snprintf(err, errlen,
376 			    "bad ownership or modes for directory %s", buf);
377 			return -1;
378 		}
379 
380 		/* If are passed the homedir then we can stop */
381 		if (comparehome && strcmp(homedir, buf) == 0) {
382 			debug3("secure_filename: terminating check at '%s'",
383 			    buf);
384 			break;
385 		}
386 		/*
387 		 * dirname should always complete with a "/" path,
388 		 * but we can be paranoid and check for "." too
389 		 */
390 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
391 			break;
392 	}
393 	return 0;
394 }
395 
396 struct passwd *
397 getpwnamallow(const char *user)
398 {
399 #ifdef HAVE_LOGIN_CAP
400 	extern login_cap_t *lc;
401 #ifdef BSD_AUTH
402 	auth_session_t *as;
403 #endif
404 #endif
405 	struct passwd *pw;
406 
407 	pw = getpwnam(user);
408 	if (pw == NULL) {
409 		log("Illegal user %.100s from %.100s",
410 		    user, get_remote_ipaddr());
411 		return (NULL);
412 	}
413 	if (!allowed_user(pw))
414 		return (NULL);
415 #ifdef HAVE_LOGIN_CAP
416 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
417 		debug("unable to get login class: %s", user);
418 		return (NULL);
419 	}
420 #ifdef BSD_AUTH
421 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
422 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
423 		debug("Approval failure for %s", user);
424 		pw = NULL;
425 	}
426 	if (as != NULL)
427 		auth_close(as);
428 #endif
429 #endif
430 	if (pw != NULL)
431 		return (pwcopy(pw));
432 	return (NULL);
433 }
434 
435 void
436 auth_debug_add(const char *fmt,...)
437 {
438 	char buf[1024];
439 	va_list args;
440 
441 	if (!auth_debug_init)
442 		return;
443 
444 	va_start(args, fmt);
445 	vsnprintf(buf, sizeof(buf), fmt, args);
446 	va_end(args);
447 	buffer_put_cstring(&auth_debug, buf);
448 }
449 
450 void
451 auth_debug_send(void)
452 {
453 	char *msg;
454 
455 	if (!auth_debug_init)
456 		return;
457 	while (buffer_len(&auth_debug)) {
458 		msg = buffer_get_string(&auth_debug, NULL);
459 		packet_send_debug("%s", msg);
460 		xfree(msg);
461 	}
462 }
463 
464 void
465 auth_debug_reset(void)
466 {
467 	if (auth_debug_init)
468 		buffer_clear(&auth_debug);
469 	else {
470 		buffer_init(&auth_debug);
471 		auth_debug_init = 1;
472 	}
473 }
474