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