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