xref: /netbsd-src/crypto/external/bsd/openssh/dist/auth2.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: auth2.c,v 1.8 2013/11/08 19:18:24 christos Exp $	*/
2 /* $OpenBSD: auth2.c,v 1.126 2012/12/02 20:34:09 djm Exp $ */
3 /*
4  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "includes.h"
28 __RCSID("$NetBSD: auth2.c,v 1.8 2013/11/08 19:18:24 christos Exp $");
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/uio.h>
32 
33 #include <fcntl.h>
34 #include <pwd.h>
35 #include <stdarg.h>
36 #include <string.h>
37 #include <unistd.h>
38 
39 #include "atomicio.h"
40 #include "xmalloc.h"
41 #include "ssh2.h"
42 #include "packet.h"
43 #include "log.h"
44 #include "buffer.h"
45 #include "servconf.h"
46 #include "compat.h"
47 #include "key.h"
48 #include "hostfile.h"
49 #include "auth.h"
50 #include "dispatch.h"
51 #include "pathnames.h"
52 #include "buffer.h"
53 #include "canohost.h"
54 
55 #ifdef GSSAPI
56 #include "ssh-gss.h"
57 #endif
58 
59 #include "monitor_wrap.h"
60 
61 /* import */
62 extern ServerOptions options;
63 extern u_char *session_id2;
64 extern u_int session_id2_len;
65 extern Buffer loginmsg;
66 
67 /* methods */
68 
69 extern Authmethod method_none;
70 extern Authmethod method_pubkey;
71 extern Authmethod method_passwd;
72 extern Authmethod method_kbdint;
73 extern Authmethod method_hostbased;
74 #ifdef KRB5
75 extern Authmethod method_kerberos;
76 #endif
77 #ifdef GSSAPI
78 extern Authmethod method_gssapi;
79 #endif
80 #ifdef JPAKE
81 extern Authmethod method_jpake;
82 #endif
83 
84 static int log_flag = 0;
85 
86 Authmethod *authmethods[] = {
87 	&method_none,
88 	&method_pubkey,
89 #ifdef GSSAPI
90 	&method_gssapi,
91 #endif
92 #ifdef JPAKE
93 	&method_jpake,
94 #endif
95 	&method_passwd,
96 	&method_kbdint,
97 	&method_hostbased,
98 #ifdef KRB5
99 	&method_kerberos,
100 #endif
101 	NULL
102 };
103 
104 /* protocol */
105 
106 static void input_service_request(int, u_int32_t, void *);
107 static void input_userauth_request(int, u_int32_t, void *);
108 
109 /* helper */
110 static Authmethod *authmethod_lookup(Authctxt *, const char *);
111 static char *authmethods_get(Authctxt *authctxt);
112 
113 #define MATCH_NONE	0	/* method or submethod mismatch */
114 #define MATCH_METHOD	1	/* method matches (no submethod specified) */
115 #define MATCH_BOTH	2	/* method and submethod match */
116 #define MATCH_PARTIAL	3	/* method matches, submethod can't be checked */
117 static int list_starts_with(const char *, const char *, const char *);
118 
119 char *
120 auth2_read_banner(void)
121 {
122 	struct stat st;
123 	char *banner = NULL;
124 	size_t len, n;
125 	int fd;
126 
127 	if ((fd = open(options.banner, O_RDONLY)) == -1)
128 		return (NULL);
129 	if (fstat(fd, &st) == -1) {
130 		close(fd);
131 		return (NULL);
132 	}
133 	if (st.st_size <= 0 || st.st_size > 1*1024*1024) {
134 		close(fd);
135 		return (NULL);
136 	}
137 
138 	len = (size_t)st.st_size;		/* truncate */
139 	banner = xmalloc(len + 1);
140 	n = atomicio(read, fd, banner, len);
141 	close(fd);
142 
143 	if (n != len) {
144 		free(banner);
145 		return (NULL);
146 	}
147 	banner[n] = '\0';
148 
149 	return (banner);
150 }
151 
152 static void
153 userauth_send_banner(const char *msg)
154 {
155 	if (datafellows & SSH_BUG_BANNER)
156 		return;
157 
158 	packet_start(SSH2_MSG_USERAUTH_BANNER);
159 	packet_put_cstring(msg);
160 	packet_put_cstring("");		/* language, unused */
161 	packet_send();
162 	debug("%s: sent", __func__);
163 }
164 
165 static void
166 userauth_banner(void)
167 {
168 	char *banner = NULL;
169 
170 	if (options.banner == NULL ||
171 	    strcasecmp(options.banner, "none") == 0 ||
172 	    (datafellows & SSH_BUG_BANNER) != 0)
173 		return;
174 
175 	if ((banner = PRIVSEP(auth2_read_banner())) == NULL)
176 		goto done;
177 
178 	userauth_send_banner(banner);
179 done:
180 	free(banner);
181 }
182 
183 /*
184  * loop until authctxt->success == TRUE
185  */
186 void
187 do_authentication2(Authctxt *authctxt)
188 {
189 	dispatch_init(&dispatch_protocol_error);
190 	dispatch_set(SSH2_MSG_SERVICE_REQUEST, &input_service_request);
191 	dispatch_run(DISPATCH_BLOCK, &authctxt->success, authctxt);
192 }
193 
194 /*ARGSUSED*/
195 static void
196 input_service_request(int type, u_int32_t seq, void *ctxt)
197 {
198 	Authctxt *authctxt = ctxt;
199 	u_int len;
200 	int acceptit = 0;
201 	char *service = packet_get_cstring(&len);
202 	packet_check_eom();
203 
204 	if (authctxt == NULL)
205 		fatal("input_service_request: no authctxt");
206 
207 	if (strcmp(service, "ssh-userauth") == 0) {
208 		if (!authctxt->success) {
209 			acceptit = 1;
210 			/* now we can handle user-auth requests */
211 			dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &input_userauth_request);
212 		}
213 	}
214 	/* XXX all other service requests are denied */
215 
216 	if (acceptit) {
217 		packet_start(SSH2_MSG_SERVICE_ACCEPT);
218 		packet_put_cstring(service);
219 		packet_send();
220 		packet_write_wait();
221 	} else {
222 		debug("bad service request %s", service);
223 		packet_disconnect("bad service request %s", service);
224 	}
225 	free(service);
226 }
227 
228 /*ARGSUSED*/
229 static void
230 input_userauth_request(int type, u_int32_t seq, void *ctxt)
231 {
232 	Authctxt *authctxt = ctxt;
233 	Authmethod *m = NULL;
234 	char *user, *service, *method, *style = NULL;
235 	int authenticated = 0;
236 
237 	if (authctxt == NULL)
238 		fatal("input_userauth_request: no authctxt");
239 
240 	user = packet_get_cstring(NULL);
241 	service = packet_get_cstring(NULL);
242 	method = packet_get_cstring(NULL);
243 	debug("userauth-request for user %s service %s method %s", user, service, method);
244 	if (!log_flag) {
245 		logit("SSH: Server;Ltype: Authname;Remote: %s-%d;Name: %s",
246 		      get_remote_ipaddr(), get_remote_port(), user);
247 		log_flag = 1;
248 	}
249 	debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
250 
251 	if ((style = strchr(user, ':')) != NULL)
252 		*style++ = 0;
253 
254 	if (authctxt->attempt++ == 0) {
255 		/* setup auth context */
256 		authctxt->pw = PRIVSEP(getpwnamallow(user));
257 		authctxt->user = xstrdup(user);
258 		if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
259 			authctxt->valid = 1;
260 			debug2("input_userauth_request: setting up authctxt for %s", user);
261 		} else {
262 			logit("input_userauth_request: invalid user %s", user);
263 			authctxt->pw = fakepw();
264 		}
265 #ifdef USE_PAM
266 		if (options.use_pam)
267 			PRIVSEP(start_pam(authctxt));
268 #endif
269 		setproctitle("%s%s", authctxt->valid ? user : "unknown",
270 		    use_privsep ? " [net]" : "");
271 		authctxt->service = xstrdup(service);
272 		authctxt->style = style ? xstrdup(style) : NULL;
273 		if (use_privsep)
274 			mm_inform_authserv(service, style);
275 		userauth_banner();
276 		if (auth2_setup_methods_lists(authctxt) != 0)
277 			packet_disconnect("no authentication methods enabled");
278 	} else if (strcmp(user, authctxt->user) != 0 ||
279 	    strcmp(service, authctxt->service) != 0) {
280 		packet_disconnect("Change of username or service not allowed: "
281 		    "(%s,%s) -> (%s,%s)",
282 		    authctxt->user, authctxt->service, user, service);
283 	}
284 	/* reset state */
285 	auth2_challenge_stop(authctxt);
286 #ifdef JPAKE
287 	auth2_jpake_stop(authctxt);
288 #endif
289 
290 #ifdef GSSAPI
291 	/* XXX move to auth2_gssapi_stop() */
292 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
293 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
294 #endif
295 
296 	authctxt->postponed = 0;
297 	authctxt->server_caused_failure = 0;
298 
299 	/* try to authenticate user */
300 	m = authmethod_lookup(authctxt, method);
301 	if (m != NULL && authctxt->failures < options.max_authtries) {
302 		debug2("input_userauth_request: try method %s", method);
303 		authenticated =	m->userauth(authctxt);
304 	}
305 	userauth_finish(authctxt, authenticated, method, NULL);
306 
307 	free(service);
308 	free(user);
309 	free(method);
310 }
311 
312 void
313 userauth_finish(Authctxt *authctxt, int authenticated, const char *method,
314     const char *submethod)
315 {
316 	char *methods;
317 	int partial = 0;
318 
319 	if (!authctxt->valid && authenticated)
320 		fatal("INTERNAL ERROR: authenticated invalid user %s",
321 		    authctxt->user);
322 	if (authenticated && authctxt->postponed)
323 		fatal("INTERNAL ERROR: authenticated and postponed");
324 
325 	/* Special handling for root */
326 	if (authenticated && authctxt->pw->pw_uid == 0 &&
327 	    !auth_root_allowed(method)) {
328 		authenticated = 0;
329 #ifdef SSH_AUDIT_EVENTS
330 		PRIVSEP(audit_event(SSH_LOGIN_ROOT_DENIED));
331 #endif
332 	}
333 
334 #ifdef USE_PAM
335 	if (options.use_pam && authenticated) {
336 		if (!PRIVSEP(do_pam_account())) {
337 			/* if PAM returned a message, send it to the user */
338 			if (buffer_len(&loginmsg) > 0) {
339 				buffer_append(&loginmsg, "\0", 1);
340 				userauth_send_banner(buffer_ptr(&loginmsg));
341 				packet_write_wait();
342 			}
343 			fatal("Access denied for user %s by PAM account "
344 			   "configuration", authctxt->user);
345 		}
346 	}
347 #endif
348 
349 	if (authenticated && options.num_auth_methods != 0) {
350 		if (!auth2_update_methods_lists(authctxt, method, submethod)) {
351 			authenticated = 0;
352 			partial = 1;
353 		}
354 	}
355 
356 	/* Log before sending the reply */
357 	auth_log(authctxt, authenticated, partial, method, submethod);
358 
359 	if (authctxt->postponed)
360 		return;
361 
362 	if (authenticated == 1) {
363 		/* turn off userauth */
364 		dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &dispatch_protocol_ignore);
365 		packet_start(SSH2_MSG_USERAUTH_SUCCESS);
366 		packet_send();
367 		packet_write_wait();
368 		/* now we can break out */
369 		authctxt->success = 1;
370 	} else {
371 		/* Allow initial try of "none" auth without failure penalty */
372 		if (!authctxt->server_caused_failure &&
373 		    (authctxt->attempt > 1 || strcmp(method, "none") != 0))
374 			authctxt->failures++;
375 		if (authctxt->failures >= options.max_authtries) {
376 			packet_disconnect(AUTH_FAIL_MSG, authctxt->user);
377 #ifdef SSH_AUDIT_EVENTS
378 			PRIVSEP(audit_event(SSH_LOGIN_EXCEED_MAXTRIES));
379 #endif
380 		}
381 		methods = authmethods_get(authctxt);
382 		debug3("%s: failure partial=%d next methods=\"%s\"", __func__,
383 		    partial, methods);
384 		packet_start(SSH2_MSG_USERAUTH_FAILURE);
385 		packet_put_cstring(methods);
386 		packet_put_char(partial);
387 		packet_send();
388 		packet_write_wait();
389 		free(methods);
390 	}
391 }
392 
393 /*
394  * Checks whether method is allowed by at least one AuthenticationMethods
395  * methods list. Returns 1 if allowed, or no methods lists configured.
396  * 0 otherwise.
397  */
398 int
399 auth2_method_allowed(Authctxt *authctxt, const char *method,
400     const char *submethod)
401 {
402 	u_int i;
403 
404 	/*
405 	 * NB. authctxt->num_auth_methods might be zero as a result of
406 	 * auth2_setup_methods_lists(), so check the configuration.
407 	 */
408 	if (options.num_auth_methods == 0)
409 		return 1;
410 	for (i = 0; i < authctxt->num_auth_methods; i++) {
411 		if (list_starts_with(authctxt->auth_methods[i], method,
412 		    submethod) != MATCH_NONE)
413 			return 1;
414 	}
415 	return 0;
416 }
417 
418 static char *
419 authmethods_get(Authctxt *authctxt)
420 {
421 	Buffer b;
422 	char *list;
423 	u_int i;
424 
425 	buffer_init(&b);
426 	for (i = 0; authmethods[i] != NULL; i++) {
427 		if (strcmp(authmethods[i]->name, "none") == 0)
428 			continue;
429 		if (authmethods[i]->enabled == NULL ||
430 		    *(authmethods[i]->enabled) == 0)
431 			continue;
432 		if (!auth2_method_allowed(authctxt, authmethods[i]->name,
433 		    NULL))
434 			continue;
435 		if (buffer_len(&b) > 0)
436 			buffer_append(&b, ",", 1);
437 		buffer_append(&b, authmethods[i]->name,
438 		    strlen(authmethods[i]->name));
439 	}
440 	buffer_append(&b, "\0", 1);
441 	list = xstrdup(buffer_ptr(&b));
442 	buffer_free(&b);
443 	return list;
444 }
445 
446 static Authmethod *
447 authmethod_lookup(Authctxt *authctxt, const char *name)
448 {
449 	int i;
450 
451 	if (name != NULL)
452 		for (i = 0; authmethods[i] != NULL; i++)
453 			if (authmethods[i]->enabled != NULL &&
454 			    *(authmethods[i]->enabled) != 0 &&
455 			    strcmp(name, authmethods[i]->name) == 0 &&
456 			    auth2_method_allowed(authctxt,
457 			    authmethods[i]->name, NULL))
458 				return authmethods[i];
459 	debug2("Unrecognized authentication method name: %s",
460 	    name ? name : "NULL");
461 	return NULL;
462 }
463 
464 /*
465  * Check a comma-separated list of methods for validity. Is need_enable is
466  * non-zero, then also require that the methods are enabled.
467  * Returns 0 on success or -1 if the methods list is invalid.
468  */
469 int
470 auth2_methods_valid(const char *_methods, int need_enable)
471 {
472 	char *methods, *omethods, *method, *p;
473 	u_int i, found;
474 	int ret = -1;
475 
476 	if (*_methods == '\0') {
477 		error("empty authentication method list");
478 		return -1;
479 	}
480 	omethods = methods = xstrdup(_methods);
481 	while ((method = strsep(&methods, ",")) != NULL) {
482 		for (found = i = 0; !found && authmethods[i] != NULL; i++) {
483 			if ((p = strchr(method, ':')) != NULL)
484 				*p = '\0';
485 			if (strcmp(method, authmethods[i]->name) != 0)
486 				continue;
487 			if (need_enable) {
488 				if (authmethods[i]->enabled == NULL ||
489 				    *(authmethods[i]->enabled) == 0) {
490 					error("Disabled method \"%s\" in "
491 					    "AuthenticationMethods list \"%s\"",
492 					    method, _methods);
493 					goto out;
494 				}
495 			}
496 			found = 1;
497 			break;
498 		}
499 		if (!found) {
500 			error("Unknown authentication method \"%s\" in list",
501 			    method);
502 			goto out;
503 		}
504 	}
505 	ret = 0;
506  out:
507 	free(omethods);
508 	return ret;
509 }
510 
511 /*
512  * Prune the AuthenticationMethods supplied in the configuration, removing
513  * any methods lists that include disabled methods. Note that this might
514  * leave authctxt->num_auth_methods == 0, even when multiple required auth
515  * has been requested. For this reason, all tests for whether multiple is
516  * enabled should consult options.num_auth_methods directly.
517  */
518 int
519 auth2_setup_methods_lists(Authctxt *authctxt)
520 {
521 	u_int i;
522 
523 	if (options.num_auth_methods == 0)
524 		return 0;
525 	debug3("%s: checking methods", __func__);
526 	authctxt->auth_methods = xcalloc(options.num_auth_methods,
527 	    sizeof(*authctxt->auth_methods));
528 	authctxt->num_auth_methods = 0;
529 	for (i = 0; i < options.num_auth_methods; i++) {
530 		if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
531 			logit("Authentication methods list \"%s\" contains "
532 			    "disabled method, skipping",
533 			    options.auth_methods[i]);
534 			continue;
535 		}
536 		debug("authentication methods list %d: %s",
537 		    authctxt->num_auth_methods, options.auth_methods[i]);
538 		authctxt->auth_methods[authctxt->num_auth_methods++] =
539 		    xstrdup(options.auth_methods[i]);
540 	}
541 	if (authctxt->num_auth_methods == 0) {
542 		error("No AuthenticationMethods left after eliminating "
543 		    "disabled methods");
544 		return -1;
545 	}
546 	return 0;
547 }
548 
549 static int
550 list_starts_with(const char *methods, const char *method,
551     const char *submethod)
552 {
553 	size_t l = strlen(method);
554 	int match;
555 	const char *p;
556 
557 	if (strncmp(methods, method, l) != 0)
558 		return MATCH_NONE;
559 	p = methods + l;
560 	match = MATCH_METHOD;
561 	if (*p == ':') {
562 		if (!submethod)
563 			return MATCH_PARTIAL;
564 		l = strlen(submethod);
565 		p += 1;
566 		if (strncmp(submethod, p, l))
567 			return MATCH_NONE;
568 		p += l;
569 		match = MATCH_BOTH;
570 	}
571 	if (*p != ',' && *p != '\0')
572 		return MATCH_NONE;
573 	return match;
574 }
575 
576 /*
577  * Remove method from the start of a comma-separated list of methods.
578  * Returns 0 if the list of methods did not start with that method or 1
579  * if it did.
580  */
581 static int
582 remove_method(char **methods, const char *method, const char *submethod)
583 {
584 	char *omethods = *methods, *p;
585 	size_t l = strlen(method);
586 	int match;
587 
588 	match = list_starts_with(omethods, method, submethod);
589 	if (match != MATCH_METHOD && match != MATCH_BOTH)
590 		return 0;
591 	p = omethods + l;
592 	if (submethod && match == MATCH_BOTH)
593 		p += 1 + strlen(submethod); /* include colon */
594 	if (*p == ',')
595 		p++;
596 	*methods = xstrdup(p);
597 	free(omethods);
598 	return 1;
599 }
600 
601 /*
602  * Called after successful authentication. Will remove the successful method
603  * from the start of each list in which it occurs. If it was the last method
604  * in any list, then authentication is deemed successful.
605  * Returns 1 if the method completed any authentication list or 0 otherwise.
606  */
607 int
608 auth2_update_methods_lists(Authctxt *authctxt, const char *method,
609     const char *submethod)
610 {
611 	u_int i, found = 0;
612 
613 	debug3("%s: updating methods list after \"%s\"", __func__, method);
614 	for (i = 0; i < authctxt->num_auth_methods; i++) {
615 		if (!remove_method(&(authctxt->auth_methods[i]), method,
616 		    submethod))
617 			continue;
618 		found = 1;
619 		if (*authctxt->auth_methods[i] == '\0') {
620 			debug2("authentication methods list %d complete", i);
621 			return 1;
622 		}
623 		debug3("authentication methods list %d remaining: \"%s\"",
624 		    i, authctxt->auth_methods[i]);
625 	}
626 	/* This should not happen, but would be bad if it did */
627 	if (!found)
628 		fatal("%s: method not in AuthenticationMethods", __func__);
629 	return 0;
630 }
631 
632 
633