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