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