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