1 /* $OpenBSD: auth.c,v 1.80 2008/11/04 07:58:09 djm Exp $ */
2 /*
3  * Copyright © 2013
4  *	Thorsten “mirabilos” Glaser <tg@mirbsd.org>
5  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/param.h>
29 #include <sys/stat.h>
30 
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <libgen.h>
34 #include <login_cap.h>
35 #include <paths.h>
36 #include <pwd.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <unistd.h>
41 
42 #include "xmalloc.h"
43 #include "match.h"
44 #include "groupaccess.h"
45 #include "log.h"
46 #include "buffer.h"
47 #include "servconf.h"
48 #include "key.h"
49 #include "hostfile.h"
50 #include "auth.h"
51 #include "auth-options.h"
52 #include "canohost.h"
53 #include "uidswap.h"
54 #include "misc.h"
55 #include "packet.h"
56 #include "monitor_wrap.h"
57 #include "pathnames.h"
58 
59 __RCSID("$MirOS: src/usr.bin/ssh/auth.c,v 1.13 2013/10/31 20:07:10 tg Exp $");
60 
61 /* import */
62 extern ServerOptions options;
63 
64 /* Debugging messages */
65 Buffer auth_debug;
66 int auth_debug_init;
67 
68 /*
69  * Check if the user is allowed to log in via ssh. If user is listed
70  * in DenyUsers or one of user's groups is listed in DenyGroups, false
71  * will be returned. If AllowUsers isn't empty and user isn't listed
72  * there, or if AllowGroups isn't empty and one of user's groups isn't
73  * listed there, false will be returned.
74  * If the user's shell is not executable, false will be returned.
75  * Otherwise true is returned.
76  */
77 int
allowed_user(struct passwd * pw)78 allowed_user(struct passwd * pw)
79 {
80 	struct stat st;
81 	const char *hostname = NULL, *ipaddr = NULL;
82 	const char *shell;
83 	u_int i;
84 
85 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
86 	if (!pw || !pw->pw_name)
87 		return 0;
88 
89 	/*
90 	 * Get the shell from the password data.  An empty shell field is
91 	 * legal, and means /bin/sh.
92 	 */
93 	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
94 
95 	/* deny if shell does not exists or is not executable */
96 	if (stat(shell, &st) != 0) {
97 		logit("User %.100s not allowed because shell %.100s does not exist",
98 		    pw->pw_name, shell);
99 		return 0;
100 	}
101 	if (S_ISREG(st.st_mode) == 0 ||
102 	    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
103 		logit("User %.100s not allowed because shell %.100s is not executable",
104 		    pw->pw_name, shell);
105 		return 0;
106 	}
107 
108 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
109 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
110 		hostname = get_canonical_hostname(options.use_dns);
111 		ipaddr = get_remote_ipaddr();
112 	}
113 
114 	/* Return false if user is listed in DenyUsers */
115 	if (options.num_deny_users > 0) {
116 		for (i = 0; i < options.num_deny_users; i++)
117 			if (match_user(pw->pw_name, hostname, ipaddr,
118 			    options.deny_users[i])) {
119 				logit("User %.100s from %.100s not allowed "
120 				    "because listed in DenyUsers",
121 				    pw->pw_name, hostname);
122 				return 0;
123 			}
124 	}
125 	/* Return false if AllowUsers isn't empty and user isn't listed there */
126 	if (options.num_allow_users > 0) {
127 		for (i = 0; i < options.num_allow_users; i++)
128 			if (match_user(pw->pw_name, hostname, ipaddr,
129 			    options.allow_users[i]))
130 				break;
131 		/* i < options.num_allow_users iff we break for loop */
132 		if (i >= options.num_allow_users) {
133 			logit("User %.100s from %.100s not allowed because "
134 			    "not listed in AllowUsers", pw->pw_name, hostname);
135 			return 0;
136 		}
137 	}
138 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
139 		/* Get the user's group access list (primary and supplementary) */
140 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
141 			logit("User %.100s from %.100s not allowed because "
142 			    "not in any group", pw->pw_name, hostname);
143 			return 0;
144 		}
145 
146 		/* Return false if one of user's groups is listed in DenyGroups */
147 		if (options.num_deny_groups > 0)
148 			if (ga_match(options.deny_groups,
149 			    options.num_deny_groups)) {
150 				ga_free();
151 				logit("User %.100s from %.100s not allowed "
152 				    "because a group is listed in DenyGroups",
153 				    pw->pw_name, hostname);
154 				return 0;
155 			}
156 		/*
157 		 * Return false if AllowGroups isn't empty and one of user's groups
158 		 * isn't listed there
159 		 */
160 		if (options.num_allow_groups > 0)
161 			if (!ga_match(options.allow_groups,
162 			    options.num_allow_groups)) {
163 				ga_free();
164 				logit("User %.100s from %.100s not allowed "
165 				    "because none of user's groups are listed "
166 				    "in AllowGroups", pw->pw_name, hostname);
167 				return 0;
168 			}
169 		ga_free();
170 	}
171 	/* We found no reason not to let this user try to log on... */
172 	return 1;
173 }
174 
175 void
auth_log(Authctxt * authctxt,int authenticated,const char * method,const char * info)176 auth_log(Authctxt *authctxt, int authenticated, const char *method,
177     const char *info)
178 {
179 	void (*authlog) (const char *fmt,...) = verbose;
180 	const char *authmsg;
181 
182 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
183 		return;
184 
185 	/* Raise logging level */
186 	if (authenticated == 1 ||
187 	    !authctxt->valid ||
188 	    authctxt->failures >= options.max_authtries / 2 ||
189 	    strcmp(method, "password") == 0)
190 		authlog = logit;
191 
192 	if (authctxt->postponed)
193 		authmsg = "Postponed";
194 	else
195 		authmsg = authenticated ? "Accepted" : "Failed";
196 
197 	authlog("%s %s for %s%.100s from %.200s port %d%s",
198 	    authmsg,
199 	    method,
200 	    authctxt->valid ? "" : "invalid user ",
201 	    authctxt->user,
202 	    get_remote_ipaddr(),
203 	    get_remote_port(),
204 	    info);
205 }
206 
207 /*
208  * Check whether root logins are disallowed.
209  */
210 int
auth_root_allowed(const char * method)211 auth_root_allowed(const char *method)
212 {
213 	switch (options.permit_root_login) {
214 	case PERMIT_YES:
215 		return 1;
216 	case PERMIT_NO_PASSWD:
217 		if (strcmp(method, "password") != 0)
218 			return 1;
219 		break;
220 	case PERMIT_FORCED_ONLY:
221 		if (forced_command) {
222 			logit("Root login accepted for forced command.");
223 			return 1;
224 		}
225 		break;
226 	}
227 	logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
228 	return 0;
229 }
230 
231 
232 /*
233  * Given a template and a passwd structure, build a filename
234  * by substituting % tokenised options. Currently, %% becomes '%',
235  * %h becomes the home directory and %u the username.
236  *
237  * This returns a buffer allocated by xmalloc.
238  */
239 static char *
expand_authorised_keys(const char * filename,struct passwd * pw)240 expand_authorised_keys(const char *filename, struct passwd *pw)
241 {
242 	char *file, ret[MAXPATHLEN];
243 	int i;
244 
245 	file = percent_expand(filename, "h", pw->pw_dir,
246 	    "u", pw->pw_name, (char *)NULL);
247 
248 	/*
249 	 * Ensure that filename starts anchored. If not, be backward
250 	 * compatible and prepend the '%h/'
251 	 */
252 	if (*file == '/')
253 		return (file);
254 
255 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
256 	if (i < 0 || (size_t)i >= sizeof(ret))
257 		fatal("expand_authorised_keys: path too long");
258 	xfree(file);
259 	return (xstrdup(ret));
260 }
261 
262 char *
authorised_keys_file(struct passwd * pw)263 authorised_keys_file(struct passwd *pw)
264 {
265 	if (!pw->pw_dir || !pw->pw_dir[0] || (pw->pw_dir[0] == '/' &&
266 	    !pw->pw_dir[1]))
267 		return (xstrdup(_PATH_SSH_ROOT_PERMITTED_KEYS));
268 	return expand_authorised_keys(options.authorised_keys_file1, pw);
269 }
270 
271 char *
authorised_keys_file2(struct passwd * pw)272 authorised_keys_file2(struct passwd *pw)
273 {
274 	return expand_authorised_keys(options.authorised_keys_file2, pw);
275 }
276 
277 /* return ok if key exists in sysfile or userfile */
278 HostStatus
check_key_in_hostfiles(struct passwd * pw,Key * key,const char * host,const char * sysfile,const char * userfile)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 static int
secure_filename(FILE * f,const char * file,struct passwd * pw,char * err,size_t errlen)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 FILE *
auth_openkeyfile(const char * file,struct passwd * pw,int strict_modes)389 auth_openkeyfile(const char *file, struct passwd *pw,
390     int strict_modes __attribute__((__unused__)))
391 {
392 	char line[1024];
393 	struct stat st;
394 	int fd;
395 	FILE *f;
396 
397 	/*
398 	 * Open the file containing the authorised keys
399 	 * Fail quietly if file does not exist
400 	 */
401 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1)
402 		return NULL;
403 
404 	if (fstat(fd, &st) < 0) {
405 		close(fd);
406 		return NULL;
407 	}
408 	if (!S_ISREG(st.st_mode)) {
409 		logit("User %s authorised keys %s is not a regular file",
410 		    pw->pw_name, file);
411 		close(fd);
412 		return NULL;
413 	}
414 	unset_nonblock(fd);
415 	if ((f = fdopen(fd, "r")) == NULL) {
416 		close(fd);
417 		return NULL;
418 	}
419 	if (options.strict_modes &&
420 	    secure_filename(f, file, pw, line, sizeof(line)) != 0) {
421 		fclose(f);
422 		logit("Authentication refused: %s", line);
423 		return NULL;
424 	}
425 
426 	return f;
427 }
428 
429 struct passwd *
getpwnamallow(const char * user)430 getpwnamallow(const char *user)
431 {
432 	extern login_cap_t *lc;
433 #ifdef BSD_AUTH
434 	auth_session_t *as;
435 #endif
436 	struct passwd *pw;
437 
438 	parse_server_match_config(&options, user,
439 	    get_canonical_hostname(options.use_dns), get_remote_ipaddr());
440 
441 	pw = getpwnam(user);
442 	if (pw == NULL) {
443 		logit("Invalid user %.100s from %.100s",
444 		    user, get_remote_ipaddr());
445 		return (NULL);
446 	}
447 	if (!allowed_user(pw))
448 		return (NULL);
449 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
450 		debug("unable to get login class: %s", user);
451 		return (NULL);
452 	}
453 #ifdef BSD_AUTH
454 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
455 	    auth_approval(as, lc, pw->pw_name, (char *)"ssh") <= 0) {
456 		debug("Approval failure for %s", user);
457 		pw = NULL;
458 	}
459 	if (as != NULL)
460 		auth_close(as);
461 #endif
462 	if (pw != NULL)
463 		return (pwcopy(pw));
464 	return (NULL);
465 }
466 
467 void
auth_debug_add(const char * fmt,...)468 auth_debug_add(const char *fmt,...)
469 {
470 	char buf[1024];
471 	va_list args;
472 
473 	if (!auth_debug_init)
474 		return;
475 
476 	va_start(args, fmt);
477 	vsnprintf(buf, sizeof(buf), fmt, args);
478 	va_end(args);
479 	buffer_put_cstring(&auth_debug, buf);
480 }
481 
482 void
auth_debug_send(void)483 auth_debug_send(void)
484 {
485 	char *msg;
486 
487 	if (!auth_debug_init)
488 		return;
489 	while (buffer_len(&auth_debug)) {
490 		msg = buffer_get_string(&auth_debug, NULL);
491 		packet_send_debug("%s", msg);
492 		xfree(msg);
493 	}
494 }
495 
496 void
auth_debug_reset(void)497 auth_debug_reset(void)
498 {
499 	if (auth_debug_init)
500 		buffer_clear(&auth_debug);
501 	else {
502 		buffer_init(&auth_debug);
503 		auth_debug_init = 1;
504 	}
505 }
506 
507 struct passwd *
fakepw(void)508 fakepw(void)
509 {
510 	static struct passwd fake;
511 
512 	memset(&fake, 0, sizeof(fake));
513 	fake.pw_name = (char *)"NOUSER";
514 	fake.pw_passwd =
515 	    (char *)"$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
516 	fake.pw_gecos = (char *)"NOUSER";
517 	fake.pw_uid = (uid_t)-1;
518 	fake.pw_gid = (gid_t)-1;
519 	fake.pw_class = (char *)"";
520 	fake.pw_dir = (char *)"/nonexist";
521 	fake.pw_shell = (char *)"/nonexist";
522 
523 	return (&fake);
524 }
525