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