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