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