xref: /freebsd/crypto/openssh/auth2.c (revision 38a52bd3)
1 /* $OpenBSD: auth2.c,v 1.164 2022/02/23 11:18:13 djm 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 #include "includes.h"
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/uio.h>
31 
32 #include <fcntl.h>
33 #include <limits.h>
34 #include <pwd.h>
35 #include <stdarg.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <time.h>
39 
40 #include "stdlib.h"
41 #include "atomicio.h"
42 #include "xmalloc.h"
43 #include "ssh2.h"
44 #include "packet.h"
45 #include "log.h"
46 #include "sshbuf.h"
47 #include "misc.h"
48 #include "servconf.h"
49 #include "compat.h"
50 #include "sshkey.h"
51 #include "hostfile.h"
52 #include "auth.h"
53 #include "dispatch.h"
54 #include "pathnames.h"
55 #include "ssherr.h"
56 #include "blacklist_client.h"
57 #ifdef GSSAPI
58 #include "ssh-gss.h"
59 #endif
60 #include "monitor_wrap.h"
61 #include "digest.h"
62 
63 /* import */
64 extern ServerOptions options;
65 extern struct sshbuf *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 GSSAPI
75 extern Authmethod method_gssapi;
76 #endif
77 
78 Authmethod *authmethods[] = {
79 	&method_none,
80 	&method_pubkey,
81 #ifdef GSSAPI
82 	&method_gssapi,
83 #endif
84 	&method_passwd,
85 	&method_kbdint,
86 	&method_hostbased,
87 	NULL
88 };
89 
90 /* protocol */
91 
92 static int input_service_request(int, u_int32_t, struct ssh *);
93 static int input_userauth_request(int, u_int32_t, struct ssh *);
94 
95 /* helper */
96 static Authmethod *authmethod_byname(const char *);
97 static Authmethod *authmethod_lookup(Authctxt *, const char *);
98 static char *authmethods_get(Authctxt *authctxt);
99 
100 #define MATCH_NONE	0	/* method or submethod mismatch */
101 #define MATCH_METHOD	1	/* method matches (no submethod specified) */
102 #define MATCH_BOTH	2	/* method and submethod match */
103 #define MATCH_PARTIAL	3	/* method matches, submethod can't be checked */
104 static int list_starts_with(const char *, const char *, const char *);
105 
106 char *
107 auth2_read_banner(void)
108 {
109 	struct stat st;
110 	char *banner = NULL;
111 	size_t len, n;
112 	int fd;
113 
114 	if ((fd = open(options.banner, O_RDONLY)) == -1)
115 		return (NULL);
116 	if (fstat(fd, &st) == -1) {
117 		close(fd);
118 		return (NULL);
119 	}
120 	if (st.st_size <= 0 || st.st_size > 1*1024*1024) {
121 		close(fd);
122 		return (NULL);
123 	}
124 
125 	len = (size_t)st.st_size;		/* truncate */
126 	banner = xmalloc(len + 1);
127 	n = atomicio(read, fd, banner, len);
128 	close(fd);
129 
130 	if (n != len) {
131 		free(banner);
132 		return (NULL);
133 	}
134 	banner[n] = '\0';
135 
136 	return (banner);
137 }
138 
139 static void
140 userauth_send_banner(struct ssh *ssh, const char *msg)
141 {
142 	int r;
143 
144 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_BANNER)) != 0 ||
145 	    (r = sshpkt_put_cstring(ssh, msg)) != 0 ||
146 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||	/* language, unused */
147 	    (r = sshpkt_send(ssh)) != 0)
148 		fatal_fr(r, "send packet");
149 	debug("%s: sent", __func__);
150 }
151 
152 static void
153 userauth_banner(struct ssh *ssh)
154 {
155 	char *banner = NULL;
156 
157 	if (options.banner == NULL)
158 		return;
159 
160 	if ((banner = PRIVSEP(auth2_read_banner())) == NULL)
161 		goto done;
162 	userauth_send_banner(ssh, banner);
163 
164 done:
165 	free(banner);
166 }
167 
168 /*
169  * loop until authctxt->success == TRUE
170  */
171 void
172 do_authentication2(struct ssh *ssh)
173 {
174 	Authctxt *authctxt = ssh->authctxt;
175 
176 	ssh_dispatch_init(ssh, &dispatch_protocol_error);
177 	ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_REQUEST, &input_service_request);
178 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt->success);
179 	ssh->authctxt = NULL;
180 }
181 
182 /*ARGSUSED*/
183 static int
184 input_service_request(int type, u_int32_t seq, struct ssh *ssh)
185 {
186 	Authctxt *authctxt = ssh->authctxt;
187 	char *service = NULL;
188 	int r, acceptit = 0;
189 
190 	if ((r = sshpkt_get_cstring(ssh, &service, NULL)) != 0 ||
191 	    (r = sshpkt_get_end(ssh)) != 0)
192 		goto out;
193 
194 	if (authctxt == NULL)
195 		fatal("input_service_request: no authctxt");
196 
197 	if (strcmp(service, "ssh-userauth") == 0) {
198 		if (!authctxt->success) {
199 			acceptit = 1;
200 			/* now we can handle user-auth requests */
201 			ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
202 			    &input_userauth_request);
203 		}
204 	}
205 	/* XXX all other service requests are denied */
206 
207 	if (acceptit) {
208 		if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_ACCEPT)) != 0 ||
209 		    (r = sshpkt_put_cstring(ssh, service)) != 0 ||
210 		    (r = sshpkt_send(ssh)) != 0 ||
211 		    (r = ssh_packet_write_wait(ssh)) != 0)
212 			goto out;
213 	} else {
214 		debug("bad service request %s", service);
215 		ssh_packet_disconnect(ssh, "bad service request %s", service);
216 	}
217 	r = 0;
218  out:
219 	free(service);
220 	return r;
221 }
222 
223 #define MIN_FAIL_DELAY_SECONDS 0.005
224 static double
225 user_specific_delay(const char *user)
226 {
227 	char b[512];
228 	size_t len = ssh_digest_bytes(SSH_DIGEST_SHA512);
229 	u_char *hash = xmalloc(len);
230 	double delay;
231 
232 	(void)snprintf(b, sizeof b, "%llu%s",
233 	    (unsigned long long)options.timing_secret, user);
234 	if (ssh_digest_memory(SSH_DIGEST_SHA512, b, strlen(b), hash, len) != 0)
235 		fatal_f("ssh_digest_memory");
236 	/* 0-4.2 ms of delay */
237 	delay = (double)PEEK_U32(hash) / 1000 / 1000 / 1000 / 1000;
238 	freezero(hash, len);
239 	debug3_f("user specific delay %0.3lfms", delay/1000);
240 	return MIN_FAIL_DELAY_SECONDS + delay;
241 }
242 
243 static void
244 ensure_minimum_time_since(double start, double seconds)
245 {
246 	struct timespec ts;
247 	double elapsed = monotime_double() - start, req = seconds, remain;
248 
249 	/* if we've already passed the requested time, scale up */
250 	while ((remain = seconds - elapsed) < 0.0)
251 		seconds *= 2;
252 
253 	ts.tv_sec = remain;
254 	ts.tv_nsec = (remain - ts.tv_sec) * 1000000000;
255 	debug3_f("elapsed %0.3lfms, delaying %0.3lfms (requested %0.3lfms)",
256 	    elapsed*1000, remain*1000, req*1000);
257 	nanosleep(&ts, NULL);
258 }
259 
260 /*ARGSUSED*/
261 static int
262 input_userauth_request(int type, u_int32_t seq, struct ssh *ssh)
263 {
264 	Authctxt *authctxt = ssh->authctxt;
265 	Authmethod *m = NULL;
266 	char *user = NULL, *service = NULL, *method = NULL, *style = NULL;
267 	int r, authenticated = 0;
268 	double tstart = monotime_double();
269 
270 	if (authctxt == NULL)
271 		fatal("input_userauth_request: no authctxt");
272 
273 	if ((r = sshpkt_get_cstring(ssh, &user, NULL)) != 0 ||
274 	    (r = sshpkt_get_cstring(ssh, &service, NULL)) != 0 ||
275 	    (r = sshpkt_get_cstring(ssh, &method, NULL)) != 0)
276 		goto out;
277 	debug("userauth-request for user %s service %s method %s", user, service, method);
278 	debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
279 
280 	if ((style = strchr(user, ':')) != NULL)
281 		*style++ = 0;
282 
283 	if (authctxt->attempt >= 1024)
284 		auth_maxtries_exceeded(ssh);
285 	if (authctxt->attempt++ == 0) {
286 		/* setup auth context */
287 		authctxt->pw = PRIVSEP(getpwnamallow(ssh, user));
288 		authctxt->user = xstrdup(user);
289 		if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
290 			authctxt->valid = 1;
291 			debug2_f("setting up authctxt for %s", user);
292 		} else {
293 			authctxt->valid = 0;
294 			/* Invalid user, fake password information */
295 			authctxt->pw = fakepw();
296 #ifdef SSH_AUDIT_EVENTS
297 			PRIVSEP(audit_event(ssh, SSH_INVALID_USER));
298 #endif
299 		}
300 #ifdef USE_PAM
301 		if (options.use_pam)
302 			PRIVSEP(start_pam(ssh));
303 #endif
304 		ssh_packet_set_log_preamble(ssh, "%suser %s",
305 		    authctxt->valid ? "authenticating " : "invalid ", user);
306 		setproctitle("%s%s", authctxt->valid ? user : "unknown",
307 		    use_privsep ? " [net]" : "");
308 		authctxt->service = xstrdup(service);
309 		authctxt->style = style ? xstrdup(style) : NULL;
310 		if (use_privsep)
311 			mm_inform_authserv(service, style);
312 		userauth_banner(ssh);
313 		if (auth2_setup_methods_lists(authctxt) != 0)
314 			ssh_packet_disconnect(ssh,
315 			    "no authentication methods enabled");
316 	} else if (strcmp(user, authctxt->user) != 0 ||
317 	    strcmp(service, authctxt->service) != 0) {
318 		ssh_packet_disconnect(ssh, "Change of username or service "
319 		    "not allowed: (%s,%s) -> (%s,%s)",
320 		    authctxt->user, authctxt->service, user, service);
321 	}
322 	/* reset state */
323 	auth2_challenge_stop(ssh);
324 
325 #ifdef GSSAPI
326 	/* XXX move to auth2_gssapi_stop() */
327 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
328 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
329 #endif
330 
331 	auth2_authctxt_reset_info(authctxt);
332 	authctxt->postponed = 0;
333 	authctxt->server_caused_failure = 0;
334 
335 	/* try to authenticate user */
336 	m = authmethod_lookup(authctxt, method);
337 	if (m != NULL && authctxt->failures < options.max_authtries) {
338 		debug2("input_userauth_request: try method %s", method);
339 		authenticated =	m->userauth(ssh, method);
340 	}
341 	if (!authctxt->authenticated)
342 		ensure_minimum_time_since(tstart,
343 		    user_specific_delay(authctxt->user));
344 	userauth_finish(ssh, authenticated, method, NULL);
345 	r = 0;
346  out:
347 	free(service);
348 	free(user);
349 	free(method);
350 	return r;
351 }
352 
353 void
354 userauth_finish(struct ssh *ssh, int authenticated, const char *packet_method,
355     const char *submethod)
356 {
357 	Authctxt *authctxt = ssh->authctxt;
358 	Authmethod *m = NULL;
359 	const char *method = packet_method;
360 	char *methods;
361 	int r, partial = 0;
362 
363 	if (authenticated) {
364 		if (!authctxt->valid) {
365 			fatal("INTERNAL ERROR: authenticated invalid user %s",
366 			    authctxt->user);
367 		}
368 		if (authctxt->postponed)
369 			fatal("INTERNAL ERROR: authenticated and postponed");
370 		/* prefer primary authmethod name to possible synonym */
371 		if ((m = authmethod_byname(method)) == NULL)
372 			fatal("INTERNAL ERROR: bad method %s", method);
373 		method = m->name;
374 	}
375 
376 	/* Special handling for root */
377 	if (authenticated && authctxt->pw->pw_uid == 0 &&
378 	    !auth_root_allowed(ssh, method)) {
379 		authenticated = 0;
380 #ifdef SSH_AUDIT_EVENTS
381 		PRIVSEP(audit_event(ssh, SSH_LOGIN_ROOT_DENIED));
382 #endif
383 	}
384 
385 	if (authenticated && options.num_auth_methods != 0) {
386 		if (!auth2_update_methods_lists(authctxt, method, submethod)) {
387 			authenticated = 0;
388 			partial = 1;
389 		}
390 	}
391 
392 	/* Log before sending the reply */
393 	auth_log(ssh, authenticated, partial, method, submethod);
394 
395 	/* Update information exposed to session */
396 	if (authenticated || partial)
397 		auth2_update_session_info(authctxt, method, submethod);
398 
399 	if (authctxt->postponed)
400 		return;
401 
402 #ifdef USE_PAM
403 	if (options.use_pam && authenticated) {
404 		int r, success = PRIVSEP(do_pam_account());
405 
406 		/* If PAM returned a message, send it to the user. */
407 		if (sshbuf_len(loginmsg) > 0) {
408 			if ((r = sshbuf_put(loginmsg, "\0", 1)) != 0)
409 				fatal("%s: buffer error: %s",
410 				    __func__, ssh_err(r));
411 			userauth_send_banner(ssh, sshbuf_ptr(loginmsg));
412 			if ((r = ssh_packet_write_wait(ssh)) != 0) {
413 				sshpkt_fatal(ssh, r,
414 				    "%s: send PAM banner", __func__);
415 			}
416 		}
417 		if (!success) {
418 			fatal("Access denied for user %s by PAM account "
419 			    "configuration", authctxt->user);
420 		}
421 	}
422 #endif
423 
424 	if (authenticated == 1) {
425 		/* turn off userauth */
426 		ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
427 		    &dispatch_protocol_ignore);
428 		if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_SUCCESS)) != 0 ||
429 		    (r = sshpkt_send(ssh)) != 0 ||
430 		    (r = ssh_packet_write_wait(ssh)) != 0)
431 			fatal_fr(r, "send success packet");
432 		/* now we can break out */
433 		authctxt->success = 1;
434 		ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
435 	} else {
436 		/* Allow initial try of "none" auth without failure penalty */
437 		if (!partial && !authctxt->server_caused_failure &&
438 		    (authctxt->attempt > 1 || strcmp(method, "none") != 0)) {
439 			authctxt->failures++;
440 			BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_FAIL, "ssh");
441 		}
442 		if (authctxt->failures >= options.max_authtries) {
443 #ifdef SSH_AUDIT_EVENTS
444 			PRIVSEP(audit_event(ssh, SSH_LOGIN_EXCEED_MAXTRIES));
445 #endif
446 			auth_maxtries_exceeded(ssh);
447 		}
448 		methods = authmethods_get(authctxt);
449 		debug3_f("failure partial=%d next methods=\"%s\"",
450 		    partial, methods);
451 		if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_FAILURE)) != 0 ||
452 		    (r = sshpkt_put_cstring(ssh, methods)) != 0 ||
453 		    (r = sshpkt_put_u8(ssh, partial)) != 0 ||
454 		    (r = sshpkt_send(ssh)) != 0 ||
455 		    (r = ssh_packet_write_wait(ssh)) != 0)
456 			fatal_fr(r, "send failure packet");
457 		free(methods);
458 	}
459 }
460 
461 /*
462  * Checks whether method is allowed by at least one AuthenticationMethods
463  * methods list. Returns 1 if allowed, or no methods lists configured.
464  * 0 otherwise.
465  */
466 int
467 auth2_method_allowed(Authctxt *authctxt, const char *method,
468     const char *submethod)
469 {
470 	u_int i;
471 
472 	/*
473 	 * NB. authctxt->num_auth_methods might be zero as a result of
474 	 * auth2_setup_methods_lists(), so check the configuration.
475 	 */
476 	if (options.num_auth_methods == 0)
477 		return 1;
478 	for (i = 0; i < authctxt->num_auth_methods; i++) {
479 		if (list_starts_with(authctxt->auth_methods[i], method,
480 		    submethod) != MATCH_NONE)
481 			return 1;
482 	}
483 	return 0;
484 }
485 
486 static char *
487 authmethods_get(Authctxt *authctxt)
488 {
489 	struct sshbuf *b;
490 	char *list;
491 	int i, r;
492 
493 	if ((b = sshbuf_new()) == NULL)
494 		fatal_f("sshbuf_new failed");
495 	for (i = 0; authmethods[i] != NULL; i++) {
496 		if (strcmp(authmethods[i]->name, "none") == 0)
497 			continue;
498 		if (authmethods[i]->enabled == NULL ||
499 		    *(authmethods[i]->enabled) == 0)
500 			continue;
501 		if (!auth2_method_allowed(authctxt, authmethods[i]->name,
502 		    NULL))
503 			continue;
504 		if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) ? "," : "",
505 		    authmethods[i]->name)) != 0)
506 			fatal_fr(r, "buffer error");
507 	}
508 	if ((list = sshbuf_dup_string(b)) == NULL)
509 		fatal_f("sshbuf_dup_string failed");
510 	sshbuf_free(b);
511 	return list;
512 }
513 
514 static Authmethod *
515 authmethod_byname(const char *name)
516 {
517 	int i;
518 
519 	if (name == NULL)
520 		fatal_f("NULL authentication method name");
521 	for (i = 0; authmethods[i] != NULL; i++) {
522 		if (strcmp(name, authmethods[i]->name) == 0 ||
523 		    (authmethods[i]->synonym != NULL &&
524 		    strcmp(name, authmethods[i]->synonym) == 0))
525 			return authmethods[i];
526 	}
527 	debug_f("unrecognized authentication method name: %s", name);
528 	return NULL;
529 }
530 
531 static Authmethod *
532 authmethod_lookup(Authctxt *authctxt, const char *name)
533 {
534 	Authmethod *method;
535 
536 	if ((method = authmethod_byname(name)) == NULL)
537 		return NULL;
538 
539 	if (method->enabled == NULL || *(method->enabled) == 0) {
540 		debug3_f("method %s not enabled", name);
541 		return NULL;
542 	}
543 	if (!auth2_method_allowed(authctxt, method->name, NULL)) {
544 		debug3_f("method %s not allowed "
545 		    "by AuthenticationMethods", name);
546 		return NULL;
547 	}
548 	return method;
549 }
550 
551 /*
552  * Check a comma-separated list of methods for validity. Is need_enable is
553  * non-zero, then also require that the methods are enabled.
554  * Returns 0 on success or -1 if the methods list is invalid.
555  */
556 int
557 auth2_methods_valid(const char *_methods, int need_enable)
558 {
559 	char *methods, *omethods, *method, *p;
560 	u_int i, found;
561 	int ret = -1;
562 
563 	if (*_methods == '\0') {
564 		error("empty authentication method list");
565 		return -1;
566 	}
567 	omethods = methods = xstrdup(_methods);
568 	while ((method = strsep(&methods, ",")) != NULL) {
569 		for (found = i = 0; !found && authmethods[i] != NULL; i++) {
570 			if ((p = strchr(method, ':')) != NULL)
571 				*p = '\0';
572 			if (strcmp(method, authmethods[i]->name) != 0)
573 				continue;
574 			if (need_enable) {
575 				if (authmethods[i]->enabled == NULL ||
576 				    *(authmethods[i]->enabled) == 0) {
577 					error("Disabled method \"%s\" in "
578 					    "AuthenticationMethods list \"%s\"",
579 					    method, _methods);
580 					goto out;
581 				}
582 			}
583 			found = 1;
584 			break;
585 		}
586 		if (!found) {
587 			error("Unknown authentication method \"%s\" in list",
588 			    method);
589 			goto out;
590 		}
591 	}
592 	ret = 0;
593  out:
594 	free(omethods);
595 	return ret;
596 }
597 
598 /*
599  * Prune the AuthenticationMethods supplied in the configuration, removing
600  * any methods lists that include disabled methods. Note that this might
601  * leave authctxt->num_auth_methods == 0, even when multiple required auth
602  * has been requested. For this reason, all tests for whether multiple is
603  * enabled should consult options.num_auth_methods directly.
604  */
605 int
606 auth2_setup_methods_lists(Authctxt *authctxt)
607 {
608 	u_int i;
609 
610 	/* First, normalise away the "any" pseudo-method */
611 	if (options.num_auth_methods == 1 &&
612 	    strcmp(options.auth_methods[0], "any") == 0) {
613 		free(options.auth_methods[0]);
614 		options.auth_methods[0] = NULL;
615 		options.num_auth_methods = 0;
616 	}
617 
618 	if (options.num_auth_methods == 0)
619 		return 0;
620 	debug3_f("checking methods");
621 	authctxt->auth_methods = xcalloc(options.num_auth_methods,
622 	    sizeof(*authctxt->auth_methods));
623 	authctxt->num_auth_methods = 0;
624 	for (i = 0; i < options.num_auth_methods; i++) {
625 		if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
626 			logit("Authentication methods list \"%s\" contains "
627 			    "disabled method, skipping",
628 			    options.auth_methods[i]);
629 			continue;
630 		}
631 		debug("authentication methods list %d: %s",
632 		    authctxt->num_auth_methods, options.auth_methods[i]);
633 		authctxt->auth_methods[authctxt->num_auth_methods++] =
634 		    xstrdup(options.auth_methods[i]);
635 	}
636 	if (authctxt->num_auth_methods == 0) {
637 		error("No AuthenticationMethods left after eliminating "
638 		    "disabled methods");
639 		return -1;
640 	}
641 	return 0;
642 }
643 
644 static int
645 list_starts_with(const char *methods, const char *method,
646     const char *submethod)
647 {
648 	size_t l = strlen(method);
649 	int match;
650 	const char *p;
651 
652 	if (strncmp(methods, method, l) != 0)
653 		return MATCH_NONE;
654 	p = methods + l;
655 	match = MATCH_METHOD;
656 	if (*p == ':') {
657 		if (!submethod)
658 			return MATCH_PARTIAL;
659 		l = strlen(submethod);
660 		p += 1;
661 		if (strncmp(submethod, p, l))
662 			return MATCH_NONE;
663 		p += l;
664 		match = MATCH_BOTH;
665 	}
666 	if (*p != ',' && *p != '\0')
667 		return MATCH_NONE;
668 	return match;
669 }
670 
671 /*
672  * Remove method from the start of a comma-separated list of methods.
673  * Returns 0 if the list of methods did not start with that method or 1
674  * if it did.
675  */
676 static int
677 remove_method(char **methods, const char *method, const char *submethod)
678 {
679 	char *omethods = *methods, *p;
680 	size_t l = strlen(method);
681 	int match;
682 
683 	match = list_starts_with(omethods, method, submethod);
684 	if (match != MATCH_METHOD && match != MATCH_BOTH)
685 		return 0;
686 	p = omethods + l;
687 	if (submethod && match == MATCH_BOTH)
688 		p += 1 + strlen(submethod); /* include colon */
689 	if (*p == ',')
690 		p++;
691 	*methods = xstrdup(p);
692 	free(omethods);
693 	return 1;
694 }
695 
696 /*
697  * Called after successful authentication. Will remove the successful method
698  * from the start of each list in which it occurs. If it was the last method
699  * in any list, then authentication is deemed successful.
700  * Returns 1 if the method completed any authentication list or 0 otherwise.
701  */
702 int
703 auth2_update_methods_lists(Authctxt *authctxt, const char *method,
704     const char *submethod)
705 {
706 	u_int i, found = 0;
707 
708 	debug3_f("updating methods list after \"%s\"", method);
709 	for (i = 0; i < authctxt->num_auth_methods; i++) {
710 		if (!remove_method(&(authctxt->auth_methods[i]), method,
711 		    submethod))
712 			continue;
713 		found = 1;
714 		if (*authctxt->auth_methods[i] == '\0') {
715 			debug2("authentication methods list %d complete", i);
716 			return 1;
717 		}
718 		debug3("authentication methods list %d remaining: \"%s\"",
719 		    i, authctxt->auth_methods[i]);
720 	}
721 	/* This should not happen, but would be bad if it did */
722 	if (!found)
723 		fatal_f("method not in AuthenticationMethods");
724 	return 0;
725 }
726 
727 /* Reset method-specific information */
728 void auth2_authctxt_reset_info(Authctxt *authctxt)
729 {
730 	sshkey_free(authctxt->auth_method_key);
731 	free(authctxt->auth_method_info);
732 	authctxt->auth_method_key = NULL;
733 	authctxt->auth_method_info = NULL;
734 }
735 
736 /* Record auth method-specific information for logs */
737 void
738 auth2_record_info(Authctxt *authctxt, const char *fmt, ...)
739 {
740 	va_list ap;
741 	int i;
742 
743 	free(authctxt->auth_method_info);
744 	authctxt->auth_method_info = NULL;
745 
746 	va_start(ap, fmt);
747 	i = vasprintf(&authctxt->auth_method_info, fmt, ap);
748 	va_end(ap);
749 
750 	if (i == -1)
751 		fatal_f("vasprintf failed");
752 }
753 
754 /*
755  * Records a public key used in authentication. This is used for logging
756  * and to ensure that the same key is not subsequently accepted again for
757  * multiple authentication.
758  */
759 void
760 auth2_record_key(Authctxt *authctxt, int authenticated,
761     const struct sshkey *key)
762 {
763 	struct sshkey **tmp, *dup;
764 	int r;
765 
766 	if ((r = sshkey_from_private(key, &dup)) != 0)
767 		fatal_fr(r, "copy key");
768 	sshkey_free(authctxt->auth_method_key);
769 	authctxt->auth_method_key = dup;
770 
771 	if (!authenticated)
772 		return;
773 
774 	/* If authenticated, make sure we don't accept this key again */
775 	if ((r = sshkey_from_private(key, &dup)) != 0)
776 		fatal_fr(r, "copy key");
777 	if (authctxt->nprev_keys >= INT_MAX ||
778 	    (tmp = recallocarray(authctxt->prev_keys, authctxt->nprev_keys,
779 	    authctxt->nprev_keys + 1, sizeof(*authctxt->prev_keys))) == NULL)
780 		fatal_f("reallocarray failed");
781 	authctxt->prev_keys = tmp;
782 	authctxt->prev_keys[authctxt->nprev_keys] = dup;
783 	authctxt->nprev_keys++;
784 
785 }
786 
787 /* Checks whether a key has already been previously used for authentication */
788 int
789 auth2_key_already_used(Authctxt *authctxt, const struct sshkey *key)
790 {
791 	u_int i;
792 	char *fp;
793 
794 	for (i = 0; i < authctxt->nprev_keys; i++) {
795 		if (sshkey_equal_public(key, authctxt->prev_keys[i])) {
796 			fp = sshkey_fingerprint(authctxt->prev_keys[i],
797 			    options.fingerprint_hash, SSH_FP_DEFAULT);
798 			debug3_f("key already used: %s %s",
799 			    sshkey_type(authctxt->prev_keys[i]),
800 			    fp == NULL ? "UNKNOWN" : fp);
801 			free(fp);
802 			return 1;
803 		}
804 	}
805 	return 0;
806 }
807 
808 /*
809  * Updates authctxt->session_info with details of authentication. Should be
810  * whenever an authentication method succeeds.
811  */
812 void
813 auth2_update_session_info(Authctxt *authctxt, const char *method,
814     const char *submethod)
815 {
816 	int r;
817 
818 	if (authctxt->session_info == NULL) {
819 		if ((authctxt->session_info = sshbuf_new()) == NULL)
820 			fatal_f("sshbuf_new");
821 	}
822 
823 	/* Append method[/submethod] */
824 	if ((r = sshbuf_putf(authctxt->session_info, "%s%s%s",
825 	    method, submethod == NULL ? "" : "/",
826 	    submethod == NULL ? "" : submethod)) != 0)
827 		fatal_fr(r, "append method");
828 
829 	/* Append key if present */
830 	if (authctxt->auth_method_key != NULL) {
831 		if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
832 		    (r = sshkey_format_text(authctxt->auth_method_key,
833 		    authctxt->session_info)) != 0)
834 			fatal_fr(r, "append key");
835 	}
836 
837 	if (authctxt->auth_method_info != NULL) {
838 		/* Ensure no ambiguity here */
839 		if (strchr(authctxt->auth_method_info, '\n') != NULL)
840 			fatal_f("auth_method_info contains \\n");
841 		if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
842 		    (r = sshbuf_putf(authctxt->session_info, "%s",
843 		    authctxt->auth_method_info)) != 0) {
844 			fatal_fr(r, "append method info");
845 		}
846 	}
847 	if ((r = sshbuf_put_u8(authctxt->session_info, '\n')) != 0)
848 		fatal_fr(r, "append");
849 }
850 
851