xref: /netbsd-src/crypto/external/bsd/openssh/dist/auth2.c (revision 70f7362772ba52b749c976fb5e86e39a8b2c9afc)
1 /*	$NetBSD: auth2.c,v 1.29 2023/12/20 17:15:20 christos Exp $	*/
2 /* $OpenBSD: auth2.c,v 1.168 2023/12/18 14:45:49 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.29 2023/12/20 17:15:20 christos Exp $");
30 
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <sys/uio.h>
34 
35 #include <fcntl.h>
36 #include <limits.h>
37 #include <pwd.h>
38 #include <stdarg.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <time.h>
42 
43 #include "stdlib.h"
44 #include "atomicio.h"
45 #include "xmalloc.h"
46 #include "ssh2.h"
47 #include "packet.h"
48 #include "log.h"
49 #include "sshbuf.h"
50 #include "misc.h"
51 #include "servconf.h"
52 #include "sshkey.h"
53 #include "hostfile.h"
54 #include "auth.h"
55 #include "dispatch.h"
56 #include "pathnames.h"
57 #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 = PRIVSEP(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 = PRIVSEP(getpwnamallow(ssh, user));
315 		authctxt->user = xstrdup(user);
316 		if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
317 			authctxt->valid = 1;
318 			debug2_f("setting up authctxt for %s", user);
319 		} else {
320 			authctxt->valid = 0;
321 			/* Invalid user, fake password information */
322 			authctxt->pw = fakepw();
323 			pfilter_notify(1);
324 		}
325 #ifdef USE_PAM
326 		if (options.use_pam)
327 			PRIVSEP(start_pam(ssh));
328 #endif
329 		ssh_packet_set_log_preamble(ssh, "%suser %s",
330 		    authctxt->valid ? "authenticating " : "invalid ", user);
331 		setproctitle("%s%s", authctxt->valid ? user : "unknown",
332 		    use_privsep ? " [net]" : "");
333 		authctxt->service = xstrdup(service);
334 		authctxt->style = style ? xstrdup(style) : NULL;
335 		if (use_privsep)
336 			mm_inform_authserv(service, style);
337 		userauth_banner(ssh);
338 		if ((r = kex_server_update_ext_info(ssh)) != 0)
339 			fatal_fr(r, "kex_server_update_ext_info failed");
340 		if (auth2_setup_methods_lists(authctxt) != 0)
341 			ssh_packet_disconnect(ssh,
342 			    "no authentication methods enabled");
343 	} else if (strcmp(user, authctxt->user) != 0 ||
344 	    strcmp(service, authctxt->service) != 0) {
345 		ssh_packet_disconnect(ssh, "Change of username or service "
346 		    "not allowed: (%s,%s) -> (%s,%s)",
347 		    authctxt->user, authctxt->service, user, service);
348 	}
349 	/* reset state */
350 	auth2_challenge_stop(ssh);
351 
352 #ifdef GSSAPI
353 	/* XXX move to auth2_gssapi_stop() */
354 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
355 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
356 #endif
357 
358 	auth2_authctxt_reset_info(authctxt);
359 	authctxt->postponed = 0;
360 	authctxt->server_caused_failure = 0;
361 
362 	/* try to authenticate user */
363 	m = authmethod_lookup(authctxt, method);
364 	if (m != NULL && authctxt->failures < options.max_authtries) {
365 		debug2("input_userauth_request: try method %s", method);
366 		authenticated =	m->userauth(ssh, method);
367 	}
368 	if (!authctxt->authenticated && strcmp(method, "none") != 0)
369 		ensure_minimum_time_since(tstart,
370 		    user_specific_delay(authctxt->user));
371 	userauth_finish(ssh, authenticated, method, NULL);
372 	r = 0;
373  out:
374 	free(service);
375 	free(user);
376 	free(method);
377 	return r;
378 }
379 
380 void
381 userauth_finish(struct ssh *ssh, int authenticated, const char *packet_method,
382     const char *submethod)
383 {
384 	Authctxt *authctxt = ssh->authctxt;
385 	Authmethod *m = NULL;
386 	const char *method = packet_method;
387 	char *methods;
388 	int r, partial = 0;
389 
390 	if (authenticated) {
391 		if (!authctxt->valid) {
392 			fatal("INTERNAL ERROR: authenticated invalid user %s",
393 			    authctxt->user);
394 		}
395 		if (authctxt->postponed)
396 			fatal("INTERNAL ERROR: authenticated and postponed");
397 		/* prefer primary authmethod name to possible synonym */
398 		if ((m = authmethod_byname(method)) == NULL)
399 			fatal("INTERNAL ERROR: bad method %s", method);
400 		method = m->name;
401 	}
402 
403 	/* Special handling for root */
404 	if (authenticated && authctxt->pw->pw_uid == 0 &&
405 	    !auth_root_allowed(ssh, method)) {
406 		authenticated = 0;
407 #ifdef SSH_AUDIT_EVENTS
408 		PRIVSEP(audit_event(SSH_LOGIN_ROOT_DENIED));
409 #endif
410 	}
411 
412 #ifdef USE_PAM
413 	if (options.use_pam && authenticated) {
414 		if (!PRIVSEP(do_pam_account())) {
415 			/* if PAM returned a message, send it to the user */
416 			if (sshbuf_len(loginmsg) > 0) {
417 				if ((r = sshbuf_put(loginmsg, "\0", 1)) != 0)
418 					fatal("%s: buffer error: %s",
419 					    __func__, ssh_err(r));
420 				userauth_send_banner(ssh,
421 				    (const char *)sshbuf_ptr(loginmsg));
422 				if ((r = ssh_packet_write_wait(ssh)) < 0) {
423 					sshpkt_fatal(ssh, r,
424 					    "%s: send PAM banner", __func__);
425 				}
426 			}
427 			fatal("Access denied for user %s by PAM account "
428 			    "configuration", authctxt->user);
429 		}
430 	}
431 #endif
432 
433 	if (authenticated && options.num_auth_methods != 0) {
434 		if (!auth2_update_methods_lists(authctxt, method, submethod)) {
435 			authenticated = 0;
436 			partial = 1;
437 		}
438 	}
439 
440 	/* Log before sending the reply */
441 	auth_log(ssh, authenticated, partial, method, submethod);
442 
443 	/* Update information exposed to session */
444 	if (authenticated || partial)
445 		auth2_update_session_info(authctxt, method, submethod);
446 
447 	if (authctxt->postponed)
448 		return;
449 
450 	if (authenticated == 1) {
451 		/* turn off userauth */
452 		ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
453 		    &dispatch_protocol_ignore);
454 		if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_SUCCESS)) != 0 ||
455 		    (r = sshpkt_send(ssh)) != 0 ||
456 		    (r = ssh_packet_write_wait(ssh)) < 0)
457 			fatal_fr(r, "send success packet");
458 		/* now we can break out */
459 		authctxt->success = 1;
460 		ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
461 	} else {
462 		/* Allow initial try of "none" auth without failure penalty */
463 		if (!partial && !authctxt->server_caused_failure &&
464 		    (authctxt->attempt > 1 || strcmp(method, "none") != 0)) {
465 			authctxt->failures++;
466 			pfilter_notify(1);
467 		}
468 		if (authctxt->failures >= options.max_authtries)
469 			auth_maxtries_exceeded(ssh);
470 		methods = authmethods_get(authctxt);
471 		debug3_f("failure partial=%d next methods=\"%s\"",
472 		    partial, methods);
473 		if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_FAILURE)) != 0 ||
474 		    (r = sshpkt_put_cstring(ssh, methods)) != 0 ||
475 		    (r = sshpkt_put_u8(ssh, partial)) != 0 ||
476 		    (r = sshpkt_send(ssh)) != 0 ||
477 		    (r = ssh_packet_write_wait(ssh)) < 0)
478 			fatal_fr(r, "send failure packet");
479 		free(methods);
480 	}
481 }
482 
483 /*
484  * Checks whether method is allowed by at least one AuthenticationMethods
485  * methods list. Returns 1 if allowed, or no methods lists configured.
486  * 0 otherwise.
487  */
488 int
489 auth2_method_allowed(Authctxt *authctxt, const char *method,
490     const char *submethod)
491 {
492 	u_int i;
493 
494 	/*
495 	 * NB. authctxt->num_auth_methods might be zero as a result of
496 	 * auth2_setup_methods_lists(), so check the configuration.
497 	 */
498 	if (options.num_auth_methods == 0)
499 		return 1;
500 	for (i = 0; i < authctxt->num_auth_methods; i++) {
501 		if (list_starts_with(authctxt->auth_methods[i], method,
502 		    submethod) != MATCH_NONE)
503 			return 1;
504 	}
505 	return 0;
506 }
507 
508 static char *
509 authmethods_get(Authctxt *authctxt)
510 {
511 	struct sshbuf *b;
512 	char *list;
513 	int i, r;
514 
515 	if ((b = sshbuf_new()) == NULL)
516 		fatal_f("sshbuf_new failed");
517 	for (i = 0; authmethods[i] != NULL; i++) {
518 		if (strcmp(authmethods[i]->name, "none") == 0)
519 			continue;
520 		if (authmethods[i]->enabled == NULL ||
521 		    *(authmethods[i]->enabled) == 0)
522 			continue;
523 		if (!auth2_method_allowed(authctxt, authmethods[i]->name,
524 		    NULL))
525 			continue;
526 		if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) ? "," : "",
527 		    authmethods[i]->name)) != 0)
528 			fatal_fr(r, "buffer error");
529 	}
530 	if ((list = sshbuf_dup_string(b)) == NULL)
531 		fatal_f("sshbuf_dup_string failed");
532 	sshbuf_free(b);
533 	return list;
534 }
535 
536 static Authmethod *
537 authmethod_byname(const char *name)
538 {
539 	int i;
540 
541 	if (name == NULL)
542 		fatal_f("NULL authentication method name");
543 	for (i = 0; authmethods[i] != NULL; i++) {
544 		if (strcmp(name, authmethods[i]->name) == 0 ||
545 		    (authmethods[i]->synonym != NULL &&
546 		    strcmp(name, authmethods[i]->synonym) == 0))
547 			return authmethods[i];
548 	}
549 	debug_f("unrecognized authentication method name: %s", name);
550 	return NULL;
551 }
552 
553 static Authmethod *
554 authmethod_lookup(Authctxt *authctxt, const char *name)
555 {
556 	Authmethod *method;
557 
558 	if ((method = authmethod_byname(name)) == NULL)
559 		return NULL;
560 
561 	if (method->enabled == NULL || *(method->enabled) == 0) {
562 		debug3_f("method %s not enabled", name);
563 		return NULL;
564 	}
565 	if (!auth2_method_allowed(authctxt, method->name, NULL)) {
566 		debug3_f("method %s not allowed "
567 		    "by AuthenticationMethods", name);
568 		return NULL;
569 	}
570 	return method;
571 }
572 
573 /*
574  * Check a comma-separated list of methods for validity. Is need_enable is
575  * non-zero, then also require that the methods are enabled.
576  * Returns 0 on success or -1 if the methods list is invalid.
577  */
578 int
579 auth2_methods_valid(const char *_methods, int need_enable)
580 {
581 	char *methods, *omethods, *method, *p;
582 	u_int i, found;
583 	int ret = -1;
584 
585 	if (*_methods == '\0') {
586 		error("empty authentication method list");
587 		return -1;
588 	}
589 	omethods = methods = xstrdup(_methods);
590 	while ((method = strsep(&methods, ",")) != NULL) {
591 		for (found = i = 0; !found && authmethods[i] != NULL; i++) {
592 			if ((p = strchr(method, ':')) != NULL)
593 				*p = '\0';
594 			if (strcmp(method, authmethods[i]->name) != 0)
595 				continue;
596 			if (need_enable) {
597 				if (authmethods[i]->enabled == NULL ||
598 				    *(authmethods[i]->enabled) == 0) {
599 					error("Disabled method \"%s\" in "
600 					    "AuthenticationMethods list \"%s\"",
601 					    method, _methods);
602 					goto out;
603 				}
604 			}
605 			found = 1;
606 			break;
607 		}
608 		if (!found) {
609 			error("Unknown authentication method \"%s\" in list",
610 			    method);
611 			goto out;
612 		}
613 	}
614 	ret = 0;
615  out:
616 	free(omethods);
617 	return ret;
618 }
619 
620 /*
621  * Prune the AuthenticationMethods supplied in the configuration, removing
622  * any methods lists that include disabled methods. Note that this might
623  * leave authctxt->num_auth_methods == 0, even when multiple required auth
624  * has been requested. For this reason, all tests for whether multiple is
625  * enabled should consult options.num_auth_methods directly.
626  */
627 int
628 auth2_setup_methods_lists(Authctxt *authctxt)
629 {
630 	u_int i;
631 
632 	/* First, normalise away the "any" pseudo-method */
633 	if (options.num_auth_methods == 1 &&
634 	    strcmp(options.auth_methods[0], "any") == 0) {
635 		free(options.auth_methods[0]);
636 		options.auth_methods[0] = NULL;
637 		options.num_auth_methods = 0;
638 	}
639 
640 	if (options.num_auth_methods == 0)
641 		return 0;
642 	debug3_f("checking methods");
643 	authctxt->auth_methods = xcalloc(options.num_auth_methods,
644 	    sizeof(*authctxt->auth_methods));
645 	authctxt->num_auth_methods = 0;
646 	for (i = 0; i < options.num_auth_methods; i++) {
647 		if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
648 			logit("Authentication methods list \"%s\" contains "
649 			    "disabled method, skipping",
650 			    options.auth_methods[i]);
651 			continue;
652 		}
653 		debug("authentication methods list %d: %s",
654 		    authctxt->num_auth_methods, options.auth_methods[i]);
655 		authctxt->auth_methods[authctxt->num_auth_methods++] =
656 		    xstrdup(options.auth_methods[i]);
657 	}
658 	if (authctxt->num_auth_methods == 0) {
659 		error("No AuthenticationMethods left after eliminating "
660 		    "disabled methods");
661 		return -1;
662 	}
663 	return 0;
664 }
665 
666 static int
667 list_starts_with(const char *methods, const char *method,
668     const char *submethod)
669 {
670 	size_t l = strlen(method);
671 	int match;
672 	const char *p;
673 
674 	if (strncmp(methods, method, l) != 0)
675 		return MATCH_NONE;
676 	p = methods + l;
677 	match = MATCH_METHOD;
678 	if (*p == ':') {
679 		if (!submethod)
680 			return MATCH_PARTIAL;
681 		l = strlen(submethod);
682 		p += 1;
683 		if (strncmp(submethod, p, l))
684 			return MATCH_NONE;
685 		p += l;
686 		match = MATCH_BOTH;
687 	}
688 	if (*p != ',' && *p != '\0')
689 		return MATCH_NONE;
690 	return match;
691 }
692 
693 /*
694  * Remove method from the start of a comma-separated list of methods.
695  * Returns 0 if the list of methods did not start with that method or 1
696  * if it did.
697  */
698 static int
699 remove_method(char **methods, const char *method, const char *submethod)
700 {
701 	char *omethods = *methods, *p;
702 	size_t l = strlen(method);
703 	int match;
704 
705 	match = list_starts_with(omethods, method, submethod);
706 	if (match != MATCH_METHOD && match != MATCH_BOTH)
707 		return 0;
708 	p = omethods + l;
709 	if (submethod && match == MATCH_BOTH)
710 		p += 1 + strlen(submethod); /* include colon */
711 	if (*p == ',')
712 		p++;
713 	*methods = xstrdup(p);
714 	free(omethods);
715 	return 1;
716 }
717 
718 /*
719  * Called after successful authentication. Will remove the successful method
720  * from the start of each list in which it occurs. If it was the last method
721  * in any list, then authentication is deemed successful.
722  * Returns 1 if the method completed any authentication list or 0 otherwise.
723  */
724 int
725 auth2_update_methods_lists(Authctxt *authctxt, const char *method,
726     const char *submethod)
727 {
728 	u_int i, found = 0;
729 
730 	debug3_f("updating methods list after \"%s\"", method);
731 	for (i = 0; i < authctxt->num_auth_methods; i++) {
732 		if (!remove_method(&(authctxt->auth_methods[i]), method,
733 		    submethod))
734 			continue;
735 		found = 1;
736 		if (*authctxt->auth_methods[i] == '\0') {
737 			debug2("authentication methods list %d complete", i);
738 			return 1;
739 		}
740 		debug3("authentication methods list %d remaining: \"%s\"",
741 		    i, authctxt->auth_methods[i]);
742 	}
743 	/* This should not happen, but would be bad if it did */
744 	if (!found)
745 		fatal_f("method not in AuthenticationMethods");
746 	return 0;
747 }
748 
749 /* Reset method-specific information */
750 void auth2_authctxt_reset_info(Authctxt *authctxt)
751 {
752 	sshkey_free(authctxt->auth_method_key);
753 	free(authctxt->auth_method_info);
754 	authctxt->auth_method_key = NULL;
755 	authctxt->auth_method_info = NULL;
756 }
757 
758 /* Record auth method-specific information for logs */
759 void
760 auth2_record_info(Authctxt *authctxt, const char *fmt, ...)
761 {
762 	va_list ap;
763 	int i;
764 
765 	free(authctxt->auth_method_info);
766 	authctxt->auth_method_info = NULL;
767 
768 	va_start(ap, fmt);
769 	i = vasprintf(&authctxt->auth_method_info, fmt, ap);
770 	va_end(ap);
771 
772 	if (i == -1)
773 		fatal_f("vasprintf failed");
774 }
775 
776 /*
777  * Records a public key used in authentication. This is used for logging
778  * and to ensure that the same key is not subsequently accepted again for
779  * multiple authentication.
780  */
781 void
782 auth2_record_key(Authctxt *authctxt, int authenticated,
783     const struct sshkey *key)
784 {
785 	struct sshkey **tmp, *dup;
786 	int r;
787 
788 	if ((r = sshkey_from_private(key, &dup)) != 0)
789 		fatal_fr(r, "copy key");
790 	sshkey_free(authctxt->auth_method_key);
791 	authctxt->auth_method_key = dup;
792 
793 	if (!authenticated)
794 		return;
795 
796 	/* If authenticated, make sure we don't accept this key again */
797 	if ((r = sshkey_from_private(key, &dup)) != 0)
798 		fatal_fr(r, "copy key");
799 	if (authctxt->nprev_keys >= INT_MAX ||
800 	    (tmp = recallocarray(authctxt->prev_keys, authctxt->nprev_keys,
801 	    authctxt->nprev_keys + 1, sizeof(*authctxt->prev_keys))) == NULL)
802 		fatal_f("reallocarray failed");
803 	authctxt->prev_keys = tmp;
804 	authctxt->prev_keys[authctxt->nprev_keys] = dup;
805 	authctxt->nprev_keys++;
806 
807 }
808 
809 /* Checks whether a key has already been previously used for authentication */
810 int
811 auth2_key_already_used(Authctxt *authctxt, const struct sshkey *key)
812 {
813 	u_int i;
814 	char *fp;
815 
816 	for (i = 0; i < authctxt->nprev_keys; i++) {
817 		if (sshkey_equal_public(key, authctxt->prev_keys[i])) {
818 			fp = sshkey_fingerprint(authctxt->prev_keys[i],
819 			    options.fingerprint_hash, SSH_FP_DEFAULT);
820 			debug3_f("key already used: %s %s",
821 			    sshkey_type(authctxt->prev_keys[i]),
822 			    fp == NULL ? "UNKNOWN" : fp);
823 			free(fp);
824 			return 1;
825 		}
826 	}
827 	return 0;
828 }
829 
830 /*
831  * Updates authctxt->session_info with details of authentication. Should be
832  * whenever an authentication method succeeds.
833  */
834 void
835 auth2_update_session_info(Authctxt *authctxt, const char *method,
836     const char *submethod)
837 {
838 	int r;
839 
840 	if (authctxt->session_info == NULL) {
841 		if ((authctxt->session_info = sshbuf_new()) == NULL)
842 			fatal_f("sshbuf_new");
843 	}
844 
845 	/* Append method[/submethod] */
846 	if ((r = sshbuf_putf(authctxt->session_info, "%s%s%s",
847 	    method, submethod == NULL ? "" : "/",
848 	    submethod == NULL ? "" : submethod)) != 0)
849 		fatal_fr(r, "append method");
850 
851 	/* Append key if present */
852 	if (authctxt->auth_method_key != NULL) {
853 		if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
854 		    (r = sshkey_format_text(authctxt->auth_method_key,
855 		    authctxt->session_info)) != 0)
856 			fatal_fr(r, "append key");
857 	}
858 
859 	if (authctxt->auth_method_info != NULL) {
860 		/* Ensure no ambiguity here */
861 		if (strchr(authctxt->auth_method_info, '\n') != NULL)
862 			fatal_f("auth_method_info contains \\n");
863 		if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
864 		    (r = sshbuf_putf(authctxt->session_info, "%s",
865 		    authctxt->auth_method_info)) != 0) {
866 			fatal_fr(r, "append method info");
867 		}
868 	}
869 	if ((r = sshbuf_put_u8(authctxt->session_info, '\n')) != 0)
870 		fatal_fr(r, "append");
871 }
872 
873