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