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