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