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