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