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