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