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