xref: /openbsd/usr.bin/ssh/auth2.c (revision cecf84d4)
1 /* $OpenBSD: auth2.c,v 1.135 2015/01/19 20:07:45 markus 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 
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/uio.h>
30 
31 #include <fcntl.h>
32 #include <pwd.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <unistd.h>
36 
37 #include "atomicio.h"
38 #include "xmalloc.h"
39 #include "ssh2.h"
40 #include "packet.h"
41 #include "log.h"
42 #include "buffer.h"
43 #include "misc.h"
44 #include "servconf.h"
45 #include "compat.h"
46 #include "key.h"
47 #include "hostfile.h"
48 #include "auth.h"
49 #include "dispatch.h"
50 #include "pathnames.h"
51 #ifdef GSSAPI
52 #include "ssh-gss.h"
53 #endif
54 #include "monitor_wrap.h"
55 
56 /* import */
57 extern ServerOptions options;
58 extern u_char *session_id2;
59 extern u_int session_id2_len;
60 
61 /* methods */
62 
63 extern Authmethod method_none;
64 extern Authmethod method_pubkey;
65 extern Authmethod method_passwd;
66 extern Authmethod method_kbdint;
67 extern Authmethod method_hostbased;
68 #ifdef GSSAPI
69 extern Authmethod method_gssapi;
70 #endif
71 
72 Authmethod *authmethods[] = {
73 	&method_none,
74 	&method_pubkey,
75 #ifdef GSSAPI
76 	&method_gssapi,
77 #endif
78 	&method_passwd,
79 	&method_kbdint,
80 	&method_hostbased,
81 	NULL
82 };
83 
84 /* protocol */
85 
86 static int input_service_request(int, u_int32_t, void *);
87 static int input_userauth_request(int, u_int32_t, void *);
88 
89 /* helper */
90 static Authmethod *authmethod_lookup(Authctxt *, const char *);
91 static char *authmethods_get(Authctxt *authctxt);
92 
93 #define MATCH_NONE	0	/* method or submethod mismatch */
94 #define MATCH_METHOD	1	/* method matches (no submethod specified) */
95 #define MATCH_BOTH	2	/* method and submethod match */
96 #define MATCH_PARTIAL	3	/* method matches, submethod can't be checked */
97 static int list_starts_with(const char *, const char *, const char *);
98 
99 char *
100 auth2_read_banner(void)
101 {
102 	struct stat st;
103 	char *banner = NULL;
104 	size_t len, n;
105 	int fd;
106 
107 	if ((fd = open(options.banner, O_RDONLY)) == -1)
108 		return (NULL);
109 	if (fstat(fd, &st) == -1) {
110 		close(fd);
111 		return (NULL);
112 	}
113 	if (st.st_size <= 0 || st.st_size > 1*1024*1024) {
114 		close(fd);
115 		return (NULL);
116 	}
117 
118 	len = (size_t)st.st_size;		/* truncate */
119 	banner = xmalloc(len + 1);
120 	n = atomicio(read, fd, banner, len);
121 	close(fd);
122 
123 	if (n != len) {
124 		free(banner);
125 		return (NULL);
126 	}
127 	banner[n] = '\0';
128 
129 	return (banner);
130 }
131 
132 static void
133 userauth_banner(void)
134 {
135 	char *banner = NULL;
136 
137 	if (options.banner == NULL || (datafellows & SSH_BUG_BANNER) != 0)
138 		return;
139 
140 	if ((banner = PRIVSEP(auth2_read_banner())) == NULL)
141 		goto done;
142 
143 	packet_start(SSH2_MSG_USERAUTH_BANNER);
144 	packet_put_cstring(banner);
145 	packet_put_cstring("");		/* language, unused */
146 	packet_send();
147 	debug("userauth_banner: sent");
148 done:
149 	free(banner);
150 }
151 
152 /*
153  * loop until authctxt->success == TRUE
154  */
155 void
156 do_authentication2(Authctxt *authctxt)
157 {
158 	dispatch_init(&dispatch_protocol_error);
159 	dispatch_set(SSH2_MSG_SERVICE_REQUEST, &input_service_request);
160 	dispatch_run(DISPATCH_BLOCK, &authctxt->success, authctxt);
161 }
162 
163 /*ARGSUSED*/
164 static int
165 input_service_request(int type, u_int32_t seq, void *ctxt)
166 {
167 	Authctxt *authctxt = ctxt;
168 	u_int len;
169 	int acceptit = 0;
170 	char *service = packet_get_cstring(&len);
171 	packet_check_eom();
172 
173 	if (authctxt == NULL)
174 		fatal("input_service_request: no authctxt");
175 
176 	if (strcmp(service, "ssh-userauth") == 0) {
177 		if (!authctxt->success) {
178 			acceptit = 1;
179 			/* now we can handle user-auth requests */
180 			dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &input_userauth_request);
181 		}
182 	}
183 	/* XXX all other service requests are denied */
184 
185 	if (acceptit) {
186 		packet_start(SSH2_MSG_SERVICE_ACCEPT);
187 		packet_put_cstring(service);
188 		packet_send();
189 		packet_write_wait();
190 	} else {
191 		debug("bad service request %s", service);
192 		packet_disconnect("bad service request %s", service);
193 	}
194 	free(service);
195 	return 0;
196 }
197 
198 /*ARGSUSED*/
199 static int
200 input_userauth_request(int type, u_int32_t seq, void *ctxt)
201 {
202 	Authctxt *authctxt = ctxt;
203 	Authmethod *m = NULL;
204 	char *user, *service, *method, *style = NULL;
205 	int authenticated = 0;
206 
207 	if (authctxt == NULL)
208 		fatal("input_userauth_request: no authctxt");
209 
210 	user = packet_get_cstring(NULL);
211 	service = packet_get_cstring(NULL);
212 	method = packet_get_cstring(NULL);
213 	debug("userauth-request for user %s service %s method %s", user, service, method);
214 	debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
215 
216 	if ((style = strchr(user, ':')) != NULL)
217 		*style++ = 0;
218 
219 	if (authctxt->attempt++ == 0) {
220 		/* setup auth context */
221 		authctxt->pw = PRIVSEP(getpwnamallow(user));
222 		if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
223 			authctxt->valid = 1;
224 			debug2("input_userauth_request: setting up authctxt for %s", user);
225 		} else {
226 			logit("input_userauth_request: invalid user %s", user);
227 			authctxt->pw = fakepw();
228 		}
229 		setproctitle("%s%s", authctxt->valid ? user : "unknown",
230 		    use_privsep ? " [net]" : "");
231 		authctxt->user = xstrdup(user);
232 		authctxt->service = xstrdup(service);
233 		authctxt->style = style ? xstrdup(style) : NULL;
234 		if (use_privsep)
235 			mm_inform_authserv(service, style);
236 		userauth_banner();
237 		if (auth2_setup_methods_lists(authctxt) != 0)
238 			packet_disconnect("no authentication methods enabled");
239 	} else if (strcmp(user, authctxt->user) != 0 ||
240 	    strcmp(service, authctxt->service) != 0) {
241 		packet_disconnect("Change of username or service not allowed: "
242 		    "(%s,%s) -> (%s,%s)",
243 		    authctxt->user, authctxt->service, user, service);
244 	}
245 	/* reset state */
246 	auth2_challenge_stop(authctxt);
247 
248 #ifdef GSSAPI
249 	/* XXX move to auth2_gssapi_stop() */
250 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
251 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
252 #endif
253 
254 	authctxt->postponed = 0;
255 	authctxt->server_caused_failure = 0;
256 
257 	/* try to authenticate user */
258 	m = authmethod_lookup(authctxt, method);
259 	if (m != NULL && authctxt->failures < options.max_authtries) {
260 		debug2("input_userauth_request: try method %s", method);
261 		authenticated =	m->userauth(authctxt);
262 	}
263 	userauth_finish(authctxt, authenticated, method, NULL);
264 
265 	free(service);
266 	free(user);
267 	free(method);
268 	return 0;
269 }
270 
271 void
272 userauth_finish(Authctxt *authctxt, int authenticated, const char *method,
273     const char *submethod)
274 {
275 	char *methods;
276 	int partial = 0;
277 
278 	if (!authctxt->valid && authenticated)
279 		fatal("INTERNAL ERROR: authenticated invalid user %s",
280 		    authctxt->user);
281 	if (authenticated && authctxt->postponed)
282 		fatal("INTERNAL ERROR: authenticated and postponed");
283 
284 	/* Special handling for root */
285 	if (authenticated && authctxt->pw->pw_uid == 0 &&
286 	    !auth_root_allowed(method))
287 		authenticated = 0;
288 
289 	if (authenticated && options.num_auth_methods != 0) {
290 		if (!auth2_update_methods_lists(authctxt, method, submethod)) {
291 			authenticated = 0;
292 			partial = 1;
293 		}
294 	}
295 
296 	/* Log before sending the reply */
297 	auth_log(authctxt, authenticated, partial, method, submethod);
298 
299 	if (authctxt->postponed)
300 		return;
301 
302 	if (authenticated == 1) {
303 		/* turn off userauth */
304 		dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &dispatch_protocol_ignore);
305 		packet_start(SSH2_MSG_USERAUTH_SUCCESS);
306 		packet_send();
307 		packet_write_wait();
308 		/* now we can break out */
309 		authctxt->success = 1;
310 	} else {
311 		/* Allow initial try of "none" auth without failure penalty */
312 		if (!partial && !authctxt->server_caused_failure &&
313 		    (authctxt->attempt > 1 || strcmp(method, "none") != 0))
314 			authctxt->failures++;
315 		if (authctxt->failures >= options.max_authtries)
316 			auth_maxtries_exceeded(authctxt);
317 		methods = authmethods_get(authctxt);
318 		debug3("%s: failure partial=%d next methods=\"%s\"", __func__,
319 		    partial, methods);
320 		packet_start(SSH2_MSG_USERAUTH_FAILURE);
321 		packet_put_cstring(methods);
322 		packet_put_char(partial);
323 		packet_send();
324 		packet_write_wait();
325 		free(methods);
326 	}
327 }
328 
329 /*
330  * Checks whether method is allowed by at least one AuthenticationMethods
331  * methods list. Returns 1 if allowed, or no methods lists configured.
332  * 0 otherwise.
333  */
334 int
335 auth2_method_allowed(Authctxt *authctxt, const char *method,
336     const char *submethod)
337 {
338 	u_int i;
339 
340 	/*
341 	 * NB. authctxt->num_auth_methods might be zero as a result of
342 	 * auth2_setup_methods_lists(), so check the configuration.
343 	 */
344 	if (options.num_auth_methods == 0)
345 		return 1;
346 	for (i = 0; i < authctxt->num_auth_methods; i++) {
347 		if (list_starts_with(authctxt->auth_methods[i], method,
348 		    submethod) != MATCH_NONE)
349 			return 1;
350 	}
351 	return 0;
352 }
353 
354 static char *
355 authmethods_get(Authctxt *authctxt)
356 {
357 	Buffer b;
358 	char *list;
359 	u_int i;
360 
361 	buffer_init(&b);
362 	for (i = 0; authmethods[i] != NULL; i++) {
363 		if (strcmp(authmethods[i]->name, "none") == 0)
364 			continue;
365 		if (authmethods[i]->enabled == NULL ||
366 		    *(authmethods[i]->enabled) == 0)
367 			continue;
368 		if (!auth2_method_allowed(authctxt, authmethods[i]->name,
369 		    NULL))
370 			continue;
371 		if (buffer_len(&b) > 0)
372 			buffer_append(&b, ",", 1);
373 		buffer_append(&b, authmethods[i]->name,
374 		    strlen(authmethods[i]->name));
375 	}
376 	buffer_append(&b, "\0", 1);
377 	list = xstrdup(buffer_ptr(&b));
378 	buffer_free(&b);
379 	return list;
380 }
381 
382 static Authmethod *
383 authmethod_lookup(Authctxt *authctxt, const char *name)
384 {
385 	int i;
386 
387 	if (name != NULL)
388 		for (i = 0; authmethods[i] != NULL; i++)
389 			if (authmethods[i]->enabled != NULL &&
390 			    *(authmethods[i]->enabled) != 0 &&
391 			    strcmp(name, authmethods[i]->name) == 0 &&
392 			    auth2_method_allowed(authctxt,
393 			    authmethods[i]->name, NULL))
394 				return authmethods[i];
395 	debug2("Unrecognized authentication method name: %s",
396 	    name ? name : "NULL");
397 	return NULL;
398 }
399 
400 /*
401  * Check a comma-separated list of methods for validity. Is need_enable is
402  * non-zero, then also require that the methods are enabled.
403  * Returns 0 on success or -1 if the methods list is invalid.
404  */
405 int
406 auth2_methods_valid(const char *_methods, int need_enable)
407 {
408 	char *methods, *omethods, *method, *p;
409 	u_int i, found;
410 	int ret = -1;
411 
412 	if (*_methods == '\0') {
413 		error("empty authentication method list");
414 		return -1;
415 	}
416 	omethods = methods = xstrdup(_methods);
417 	while ((method = strsep(&methods, ",")) != NULL) {
418 		for (found = i = 0; !found && authmethods[i] != NULL; i++) {
419 			if ((p = strchr(method, ':')) != NULL)
420 				*p = '\0';
421 			if (strcmp(method, authmethods[i]->name) != 0)
422 				continue;
423 			if (need_enable) {
424 				if (authmethods[i]->enabled == NULL ||
425 				    *(authmethods[i]->enabled) == 0) {
426 					error("Disabled method \"%s\" in "
427 					    "AuthenticationMethods list \"%s\"",
428 					    method, _methods);
429 					goto out;
430 				}
431 			}
432 			found = 1;
433 			break;
434 		}
435 		if (!found) {
436 			error("Unknown authentication method \"%s\" in list",
437 			    method);
438 			goto out;
439 		}
440 	}
441 	ret = 0;
442  out:
443 	free(omethods);
444 	return ret;
445 }
446 
447 /*
448  * Prune the AuthenticationMethods supplied in the configuration, removing
449  * any methods lists that include disabled methods. Note that this might
450  * leave authctxt->num_auth_methods == 0, even when multiple required auth
451  * has been requested. For this reason, all tests for whether multiple is
452  * enabled should consult options.num_auth_methods directly.
453  */
454 int
455 auth2_setup_methods_lists(Authctxt *authctxt)
456 {
457 	u_int i;
458 
459 	if (options.num_auth_methods == 0)
460 		return 0;
461 	debug3("%s: checking methods", __func__);
462 	authctxt->auth_methods = xcalloc(options.num_auth_methods,
463 	    sizeof(*authctxt->auth_methods));
464 	authctxt->num_auth_methods = 0;
465 	for (i = 0; i < options.num_auth_methods; i++) {
466 		if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
467 			logit("Authentication methods list \"%s\" contains "
468 			    "disabled method, skipping",
469 			    options.auth_methods[i]);
470 			continue;
471 		}
472 		debug("authentication methods list %d: %s",
473 		    authctxt->num_auth_methods, options.auth_methods[i]);
474 		authctxt->auth_methods[authctxt->num_auth_methods++] =
475 		    xstrdup(options.auth_methods[i]);
476 	}
477 	if (authctxt->num_auth_methods == 0) {
478 		error("No AuthenticationMethods left after eliminating "
479 		    "disabled methods");
480 		return -1;
481 	}
482 	return 0;
483 }
484 
485 static int
486 list_starts_with(const char *methods, const char *method,
487     const char *submethod)
488 {
489 	size_t l = strlen(method);
490 	int match;
491 	const char *p;
492 
493 	if (strncmp(methods, method, l) != 0)
494 		return MATCH_NONE;
495 	p = methods + l;
496 	match = MATCH_METHOD;
497 	if (*p == ':') {
498 		if (!submethod)
499 			return MATCH_PARTIAL;
500 		l = strlen(submethod);
501 		p += 1;
502 		if (strncmp(submethod, p, l))
503 			return MATCH_NONE;
504 		p += l;
505 		match = MATCH_BOTH;
506 	}
507 	if (*p != ',' && *p != '\0')
508 		return MATCH_NONE;
509 	return match;
510 }
511 
512 /*
513  * Remove method from the start of a comma-separated list of methods.
514  * Returns 0 if the list of methods did not start with that method or 1
515  * if it did.
516  */
517 static int
518 remove_method(char **methods, const char *method, const char *submethod)
519 {
520 	char *omethods = *methods, *p;
521 	size_t l = strlen(method);
522 	int match;
523 
524 	match = list_starts_with(omethods, method, submethod);
525 	if (match != MATCH_METHOD && match != MATCH_BOTH)
526 		return 0;
527 	p = omethods + l;
528 	if (submethod && match == MATCH_BOTH)
529 		p += 1 + strlen(submethod); /* include colon */
530 	if (*p == ',')
531 		p++;
532 	*methods = xstrdup(p);
533 	free(omethods);
534 	return 1;
535 }
536 
537 /*
538  * Called after successful authentication. Will remove the successful method
539  * from the start of each list in which it occurs. If it was the last method
540  * in any list, then authentication is deemed successful.
541  * Returns 1 if the method completed any authentication list or 0 otherwise.
542  */
543 int
544 auth2_update_methods_lists(Authctxt *authctxt, const char *method,
545     const char *submethod)
546 {
547 	u_int i, found = 0;
548 
549 	debug3("%s: updating methods list after \"%s\"", __func__, method);
550 	for (i = 0; i < authctxt->num_auth_methods; i++) {
551 		if (!remove_method(&(authctxt->auth_methods[i]), method,
552 		    submethod))
553 			continue;
554 		found = 1;
555 		if (*authctxt->auth_methods[i] == '\0') {
556 			debug2("authentication methods list %d complete", i);
557 			return 1;
558 		}
559 		debug3("authentication methods list %d remaining: \"%s\"",
560 		    i, authctxt->auth_methods[i]);
561 	}
562 	/* This should not happen, but would be bad if it did */
563 	if (!found)
564 		fatal("%s: method not in AuthenticationMethods", __func__);
565 	return 0;
566 }
567 
568 
569