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