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