xref: /openbsd-src/usr.bin/ssh/sshconnect2.c (revision 68dd5bb1859285b71cb62a10bf107b8ad54064d9)
1 /* $OpenBSD: sshconnect2.c,v 1.372 2024/01/08 00:34:34 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  * Copyright (c) 2008 Damien Miller.  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 <sys/types.h>
28 #include <sys/socket.h>
29 #include <sys/wait.h>
30 #include <sys/queue.h>
31 #include <sys/stat.h>
32 
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <limits.h>
36 #include <netdb.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <stdarg.h>
40 #include <signal.h>
41 #include <pwd.h>
42 #include <unistd.h>
43 #include <vis.h>
44 
45 #include "xmalloc.h"
46 #include "ssh.h"
47 #include "ssh2.h"
48 #include "sshbuf.h"
49 #include "packet.h"
50 #include "compat.h"
51 #include "cipher.h"
52 #include "sshkey.h"
53 #include "kex.h"
54 #include "sshconnect.h"
55 #include "authfile.h"
56 #include "dh.h"
57 #include "authfd.h"
58 #include "log.h"
59 #include "misc.h"
60 #include "readconf.h"
61 #include "match.h"
62 #include "dispatch.h"
63 #include "canohost.h"
64 #include "msg.h"
65 #include "pathnames.h"
66 #include "uidswap.h"
67 #include "hostfile.h"
68 #include "ssherr.h"
69 #include "utf8.h"
70 #include "ssh-sk.h"
71 #include "sk-api.h"
72 
73 #ifdef GSSAPI
74 #include "ssh-gss.h"
75 #endif
76 
77 /* import */
78 extern char *client_version_string;
79 extern char *server_version_string;
80 extern Options options;
81 
82 /*
83  * SSH2 key exchange
84  */
85 
86 static char *xxx_host;
87 static struct sockaddr *xxx_hostaddr;
88 static const struct ssh_conn_info *xxx_conn_info;
89 
90 static int
91 verify_host_key_callback(struct sshkey *hostkey, struct ssh *ssh)
92 {
93 	int r;
94 
95 	if ((r = sshkey_check_rsa_length(hostkey,
96 	    options.required_rsa_size)) != 0)
97 		fatal_r(r, "Bad server host key");
98 	if (verify_host_key(xxx_host, xxx_hostaddr, hostkey,
99 	    xxx_conn_info) == -1)
100 		fatal("Host key verification failed.");
101 	return 0;
102 }
103 
104 /* Returns the first item from a comma-separated algorithm list */
105 static char *
106 first_alg(const char *algs)
107 {
108 	char *ret, *cp;
109 
110 	ret = xstrdup(algs);
111 	if ((cp = strchr(ret, ',')) != NULL)
112 		*cp = '\0';
113 	return ret;
114 }
115 
116 static char *
117 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port,
118     const struct ssh_conn_info *cinfo)
119 {
120 	char *oavail = NULL, *avail = NULL, *first = NULL, *last = NULL;
121 	char *alg = NULL, *hostname = NULL, *ret = NULL, *best = NULL;
122 	size_t maxlen;
123 	struct hostkeys *hostkeys = NULL;
124 	int ktype;
125 	u_int i;
126 
127 	/* Find all hostkeys for this hostname */
128 	get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
129 	hostkeys = init_hostkeys();
130 	for (i = 0; i < options.num_user_hostfiles; i++)
131 		load_hostkeys(hostkeys, hostname, options.user_hostfiles[i], 0);
132 	for (i = 0; i < options.num_system_hostfiles; i++) {
133 		load_hostkeys(hostkeys, hostname,
134 		    options.system_hostfiles[i], 0);
135 	}
136 	if (options.known_hosts_command != NULL) {
137 		load_hostkeys_command(hostkeys, options.known_hosts_command,
138 		    "ORDER", cinfo, NULL, hostname);
139 	}
140 	/*
141 	 * If a plain public key exists that matches the type of the best
142 	 * preference HostkeyAlgorithms, then use the whole list as is.
143 	 * Note that we ignore whether the best preference algorithm is a
144 	 * certificate type, as sshconnect.c will downgrade certs to
145 	 * plain keys if necessary.
146 	 */
147 	best = first_alg(options.hostkeyalgorithms);
148 	if (lookup_key_in_hostkeys_by_type(hostkeys,
149 	    sshkey_type_plain(sshkey_type_from_name(best)),
150 	    sshkey_ecdsa_nid_from_name(best), NULL)) {
151 		debug3_f("have matching best-preference key type %s, "
152 		    "using HostkeyAlgorithms verbatim", best);
153 		ret = xstrdup(options.hostkeyalgorithms);
154 		goto out;
155 	}
156 
157 	/*
158 	 * Otherwise, prefer the host key algorithms that match known keys
159 	 * while keeping the ordering of HostkeyAlgorithms as much as possible.
160 	 */
161 	oavail = avail = xstrdup(options.hostkeyalgorithms);
162 	maxlen = strlen(avail) + 1;
163 	first = xmalloc(maxlen);
164 	last = xmalloc(maxlen);
165 	*first = *last = '\0';
166 
167 #define ALG_APPEND(to, from) \
168 	do { \
169 		if (*to != '\0') \
170 			strlcat(to, ",", maxlen); \
171 		strlcat(to, from, maxlen); \
172 	} while (0)
173 
174 	while ((alg = strsep(&avail, ",")) && *alg != '\0') {
175 		if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
176 			fatal_f("unknown alg %s", alg);
177 		/*
178 		 * If we have a @cert-authority marker in known_hosts then
179 		 * prefer all certificate algorithms.
180 		 */
181 		if (sshkey_type_is_cert(ktype) &&
182 		    lookup_marker_in_hostkeys(hostkeys, MRK_CA)) {
183 			ALG_APPEND(first, alg);
184 			continue;
185 		}
186 		/* If the key appears in known_hosts then prefer it */
187 		if (lookup_key_in_hostkeys_by_type(hostkeys,
188 		    sshkey_type_plain(ktype),
189 		    sshkey_ecdsa_nid_from_name(alg), NULL)) {
190 			ALG_APPEND(first, alg);
191 			continue;
192 		}
193 		/* Otherwise, put it last */
194 		ALG_APPEND(last, alg);
195 	}
196 #undef ALG_APPEND
197 	xasprintf(&ret, "%s%s%s", first,
198 	    (*first == '\0' || *last == '\0') ? "" : ",", last);
199 	if (*first != '\0')
200 		debug3_f("prefer hostkeyalgs: %s", first);
201 	else
202 		debug3_f("no algorithms matched; accept original");
203  out:
204 	free(best);
205 	free(first);
206 	free(last);
207 	free(hostname);
208 	free(oavail);
209 	free_hostkeys(hostkeys);
210 
211 	return ret;
212 }
213 
214 void
215 ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port,
216     const struct ssh_conn_info *cinfo)
217 {
218 	char *myproposal[PROPOSAL_MAX];
219 	char *all_key, *hkalgs = NULL;
220 	int r, use_known_hosts_order = 0;
221 
222 	xxx_host = host;
223 	xxx_hostaddr = hostaddr;
224 	xxx_conn_info = cinfo;
225 
226 	if (options.rekey_limit || options.rekey_interval)
227 		ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
228 		    options.rekey_interval);
229 
230 	/*
231 	 * If the user has not specified HostkeyAlgorithms, or has only
232 	 * appended or removed algorithms from that list then prefer algorithms
233 	 * that are in the list that are supported by known_hosts keys.
234 	 */
235 	if (options.hostkeyalgorithms == NULL ||
236 	    options.hostkeyalgorithms[0] == '-' ||
237 	    options.hostkeyalgorithms[0] == '+')
238 		use_known_hosts_order = 1;
239 
240 	/* Expand or fill in HostkeyAlgorithms */
241 	all_key = sshkey_alg_list(0, 0, 1, ',');
242 	if ((r = kex_assemble_names(&options.hostkeyalgorithms,
243 	    kex_default_pk_alg(), all_key)) != 0)
244 		fatal_fr(r, "kex_assemble_namelist");
245 	free(all_key);
246 
247 	if (use_known_hosts_order)
248 		hkalgs = order_hostkeyalgs(host, hostaddr, port, cinfo);
249 
250 	kex_proposal_populate_entries(ssh, myproposal,
251 	    options.kex_algorithms, options.ciphers, options.macs,
252 	    compression_alg_list(options.compression),
253 	    hkalgs ? hkalgs : options.hostkeyalgorithms);
254 
255 	free(hkalgs);
256 
257 	/* start key exchange */
258 	if ((r = kex_setup(ssh, myproposal)) != 0)
259 		fatal_r(r, "kex_setup");
260 #ifdef WITH_OPENSSL
261 	ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
262 	ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
263 	ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
264 	ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
265 	ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
266 	ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
267 	ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
268 	ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
269 #endif
270 	ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
271 	ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
272 	ssh->kex->verify_host_key=&verify_host_key_callback;
273 
274 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &ssh->kex->done);
275 	kex_proposal_free_entries(myproposal);
276 
277 #ifdef DEBUG_KEXDH
278 	/* send 1st encrypted/maced/compressed message */
279 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
280 	    (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
281 	    (r = sshpkt_send(ssh)) != 0 ||
282 	    (r = ssh_packet_write_wait(ssh)) != 0)
283 		fatal_fr(r, "send packet");
284 #endif
285 }
286 
287 /*
288  * Authenticate user
289  */
290 
291 typedef struct cauthctxt Authctxt;
292 typedef struct cauthmethod Authmethod;
293 typedef struct identity Identity;
294 typedef struct idlist Idlist;
295 
296 struct identity {
297 	TAILQ_ENTRY(identity) next;
298 	int	agent_fd;		/* >=0 if agent supports key */
299 	struct sshkey	*key;		/* public/private key */
300 	char	*filename;		/* comment for agent-only keys */
301 	int	tried;
302 	int	isprivate;		/* key points to the private key */
303 	int	userprovided;
304 };
305 TAILQ_HEAD(idlist, identity);
306 
307 struct cauthctxt {
308 	const char *server_user;
309 	const char *local_user;
310 	const char *host;
311 	const char *service;
312 	struct cauthmethod *method;
313 	sig_atomic_t success;
314 	char *authlist;
315 #ifdef GSSAPI
316 	/* gssapi */
317 	gss_OID_set gss_supported_mechs;
318 	u_int mech_tried;
319 #endif
320 	/* pubkey */
321 	struct idlist keys;
322 	int agent_fd;
323 	/* hostbased */
324 	Sensitive *sensitive;
325 	char *oktypes, *ktypes;
326 	const char *active_ktype;
327 	/* kbd-interactive */
328 	int info_req_seen;
329 	int attempt_kbdint;
330 	/* password */
331 	int attempt_passwd;
332 	/* generic */
333 	void *methoddata;
334 };
335 
336 struct cauthmethod {
337 	char	*name;		/* string to compare against server's list */
338 	int	(*userauth)(struct ssh *ssh);
339 	void	(*cleanup)(struct ssh *ssh);
340 	int	*enabled;	/* flag in option struct that enables method */
341 	int	*batch_flag;	/* flag in option struct that disables method */
342 };
343 
344 static int input_userauth_service_accept(int, u_int32_t, struct ssh *);
345 static int input_userauth_success(int, u_int32_t, struct ssh *);
346 static int input_userauth_failure(int, u_int32_t, struct ssh *);
347 static int input_userauth_banner(int, u_int32_t, struct ssh *);
348 static int input_userauth_error(int, u_int32_t, struct ssh *);
349 static int input_userauth_info_req(int, u_int32_t, struct ssh *);
350 static int input_userauth_pk_ok(int, u_int32_t, struct ssh *);
351 static int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *);
352 
353 static int userauth_none(struct ssh *);
354 static int userauth_pubkey(struct ssh *);
355 static int userauth_passwd(struct ssh *);
356 static int userauth_kbdint(struct ssh *);
357 static int userauth_hostbased(struct ssh *);
358 
359 #ifdef GSSAPI
360 static int userauth_gssapi(struct ssh *);
361 static void userauth_gssapi_cleanup(struct ssh *);
362 static int input_gssapi_response(int type, u_int32_t, struct ssh *);
363 static int input_gssapi_token(int type, u_int32_t, struct ssh *);
364 static int input_gssapi_error(int, u_int32_t, struct ssh *);
365 static int input_gssapi_errtok(int, u_int32_t, struct ssh *);
366 #endif
367 
368 void	userauth(struct ssh *, char *);
369 
370 static void pubkey_cleanup(struct ssh *);
371 static int sign_and_send_pubkey(struct ssh *ssh, Identity *);
372 static void pubkey_prepare(struct ssh *, Authctxt *);
373 static void pubkey_reset(Authctxt *);
374 static struct sshkey *load_identity_file(Identity *);
375 
376 static Authmethod *authmethod_get(char *authlist);
377 static Authmethod *authmethod_lookup(const char *name);
378 static char *authmethods_get(void);
379 
380 Authmethod authmethods[] = {
381 #ifdef GSSAPI
382 	{"gssapi-with-mic",
383 		userauth_gssapi,
384 		userauth_gssapi_cleanup,
385 		&options.gss_authentication,
386 		NULL},
387 #endif
388 	{"hostbased",
389 		userauth_hostbased,
390 		NULL,
391 		&options.hostbased_authentication,
392 		NULL},
393 	{"publickey",
394 		userauth_pubkey,
395 		NULL,
396 		&options.pubkey_authentication,
397 		NULL},
398 	{"keyboard-interactive",
399 		userauth_kbdint,
400 		NULL,
401 		&options.kbd_interactive_authentication,
402 		&options.batch_mode},
403 	{"password",
404 		userauth_passwd,
405 		NULL,
406 		&options.password_authentication,
407 		&options.batch_mode},
408 	{"none",
409 		userauth_none,
410 		NULL,
411 		NULL,
412 		NULL},
413 	{NULL, NULL, NULL, NULL, NULL}
414 };
415 
416 void
417 ssh_userauth2(struct ssh *ssh, const char *local_user,
418     const char *server_user, char *host, Sensitive *sensitive)
419 {
420 	Authctxt authctxt;
421 	int r;
422 
423 	if (options.preferred_authentications == NULL)
424 		options.preferred_authentications = authmethods_get();
425 
426 	/* setup authentication context */
427 	memset(&authctxt, 0, sizeof(authctxt));
428 	authctxt.server_user = server_user;
429 	authctxt.local_user = local_user;
430 	authctxt.host = host;
431 	authctxt.service = "ssh-connection";		/* service name */
432 	authctxt.success = 0;
433 	authctxt.method = authmethod_lookup("none");
434 	authctxt.authlist = NULL;
435 	authctxt.methoddata = NULL;
436 	authctxt.sensitive = sensitive;
437 	authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL;
438 	authctxt.info_req_seen = 0;
439 	authctxt.attempt_kbdint = 0;
440 	authctxt.attempt_passwd = 0;
441 #if GSSAPI
442 	authctxt.gss_supported_mechs = NULL;
443 	authctxt.mech_tried = 0;
444 #endif
445 	authctxt.agent_fd = -1;
446 	if (authctxt.method == NULL)
447 		fatal_f("internal error: cannot send userauth none request");
448 
449 	if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 ||
450 	    (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 ||
451 	    (r = sshpkt_send(ssh)) != 0)
452 		fatal_fr(r, "send packet");
453 
454 	ssh->authctxt = &authctxt;
455 	ssh_dispatch_init(ssh, &input_userauth_error);
456 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, kex_input_ext_info);
457 	ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept);
458 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success);	/* loop until success */
459 	pubkey_cleanup(ssh);
460 #ifdef GSSAPI
461 	if (authctxt.gss_supported_mechs != NULL) {
462 		u_int ms;
463 
464 		gss_release_oid_set(&ms, &authctxt.gss_supported_mechs);
465 		authctxt.gss_supported_mechs = NULL;
466 	}
467 #endif
468 	ssh->authctxt = NULL;
469 
470 	ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
471 
472 	if (!authctxt.success)
473 		fatal("Authentication failed.");
474 	if (ssh_packet_connection_is_on_socket(ssh)) {
475 		verbose("Authenticated to %s ([%s]:%d) using \"%s\".", host,
476 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
477 		    authctxt.method->name);
478 	} else {
479 		verbose("Authenticated to %s (via proxy) using \"%s\".", host,
480 		    authctxt.method->name);
481 	}
482 }
483 
484 static int
485 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh)
486 {
487 	int r;
488 
489 	if (ssh_packet_remaining(ssh) > 0) {
490 		char *reply;
491 
492 		if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0)
493 			goto out;
494 		debug2("service_accept: %s", reply);
495 		free(reply);
496 	} else {
497 		debug2("buggy server: service_accept w/o service");
498 	}
499 	if ((r = sshpkt_get_end(ssh)) != 0)
500 		goto out;
501 	debug("SSH2_MSG_SERVICE_ACCEPT received");
502 
503 	/* initial userauth request */
504 	userauth_none(ssh);
505 
506 	/* accept EXT_INFO at any time during userauth */
507 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, ssh->kex->ext_info_s ?
508 	    &kex_input_ext_info : &input_userauth_error);
509 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
510 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
511 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
512 	r = 0;
513  out:
514 	return r;
515 }
516 
517 void
518 userauth(struct ssh *ssh, char *authlist)
519 {
520 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
521 
522 	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
523 		authctxt->method->cleanup(ssh);
524 
525 	free(authctxt->methoddata);
526 	authctxt->methoddata = NULL;
527 	if (authlist == NULL) {
528 		authlist = authctxt->authlist;
529 	} else {
530 		free(authctxt->authlist);
531 		authctxt->authlist = authlist;
532 	}
533 	for (;;) {
534 		Authmethod *method = authmethod_get(authlist);
535 		if (method == NULL)
536 			fatal("%s@%s: Permission denied (%s).",
537 			    authctxt->server_user, authctxt->host, authlist);
538 		authctxt->method = method;
539 
540 		/* reset the per method handler */
541 		ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_PER_METHOD_MIN,
542 		    SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
543 
544 		/* and try new method */
545 		if (method->userauth(ssh) != 0) {
546 			debug2("we sent a %s packet, wait for reply", method->name);
547 			break;
548 		} else {
549 			debug2("we did not send a packet, disable method");
550 			method->enabled = NULL;
551 		}
552 	}
553 }
554 
555 static int
556 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh)
557 {
558 	fatal_f("bad message during authentication: type %d", type);
559 	return 0;
560 }
561 
562 static int
563 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh)
564 {
565 	char *msg = NULL;
566 	size_t len;
567 	int r;
568 
569 	debug3_f("entering");
570 	if ((r = sshpkt_get_cstring(ssh, &msg, &len)) != 0 ||
571 	    (r = sshpkt_get_cstring(ssh, NULL, NULL)) != 0)
572 		goto out;
573 	if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO)
574 		fmprintf(stderr, "%s", msg);
575 	r = 0;
576  out:
577 	free(msg);
578 	return r;
579 }
580 
581 static int
582 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh)
583 {
584 	Authctxt *authctxt = ssh->authctxt;
585 
586 	if (authctxt == NULL)
587 		fatal_f("no authentication context");
588 	free(authctxt->authlist);
589 	authctxt->authlist = NULL;
590 	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
591 		authctxt->method->cleanup(ssh);
592 	free(authctxt->methoddata);
593 	authctxt->methoddata = NULL;
594 	authctxt->success = 1;			/* break out */
595 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, dispatch_protocol_error);
596 	return 0;
597 }
598 
599 #if 0
600 static int
601 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh)
602 {
603 	Authctxt *authctxt = ssh->authctxt;
604 
605 	if (authctxt == NULL)
606 		fatal_f("no authentication context");
607 
608 	fatal("Unexpected authentication success during %s.",
609 	    authctxt->method->name);
610 	return 0;
611 }
612 #endif
613 
614 static int
615 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh)
616 {
617 	Authctxt *authctxt = ssh->authctxt;
618 	char *authlist = NULL;
619 	u_char partial;
620 
621 	if (authctxt == NULL)
622 		fatal("input_userauth_failure: no authentication context");
623 
624 	if (sshpkt_get_cstring(ssh, &authlist, NULL) != 0 ||
625 	    sshpkt_get_u8(ssh, &partial) != 0 ||
626 	    sshpkt_get_end(ssh) != 0)
627 		goto out;
628 
629 	if (partial != 0) {
630 		verbose("Authenticated using \"%s\" with partial success.",
631 		    authctxt->method->name);
632 		/* reset state */
633 		pubkey_reset(authctxt);
634 	}
635 	debug("Authentications that can continue: %s", authlist);
636 
637 	userauth(ssh, authlist);
638 	authlist = NULL;
639  out:
640 	free(authlist);
641 	return 0;
642 }
643 
644 /*
645  * Format an identity for logging including filename, key type, fingerprint
646  * and location (agent, etc.). Caller must free.
647  */
648 static char *
649 format_identity(Identity *id)
650 {
651 	char *fp = NULL, *ret = NULL;
652 	const char *note = "";
653 
654 	if (id->key != NULL) {
655 		fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
656 		    SSH_FP_DEFAULT);
657 	}
658 	if (id->key) {
659 		if ((id->key->flags & SSHKEY_FLAG_EXT) != 0)
660 			note = " token";
661 		else if (sshkey_is_sk(id->key))
662 			note = " authenticator";
663 	}
664 	xasprintf(&ret, "%s %s%s%s%s%s%s",
665 	    id->filename,
666 	    id->key ? sshkey_type(id->key) : "", id->key ? " " : "",
667 	    fp ? fp : "",
668 	    id->userprovided ? " explicit" : "", note,
669 	    id->agent_fd != -1 ? " agent" : "");
670 	free(fp);
671 	return ret;
672 }
673 
674 static int
675 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh)
676 {
677 	Authctxt *authctxt = ssh->authctxt;
678 	struct sshkey *key = NULL;
679 	Identity *id = NULL;
680 	int pktype, found = 0, sent = 0;
681 	size_t blen;
682 	char *pkalg = NULL, *fp = NULL, *ident = NULL;
683 	u_char *pkblob = NULL;
684 	int r;
685 
686 	if (authctxt == NULL)
687 		fatal("input_userauth_pk_ok: no authentication context");
688 
689 	if ((r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
690 	    (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
691 	    (r = sshpkt_get_end(ssh)) != 0)
692 		goto done;
693 
694 	if ((pktype = sshkey_type_from_name(pkalg)) == KEY_UNSPEC) {
695 		debug_f("server sent unknown pkalg %s", pkalg);
696 		goto done;
697 	}
698 	if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
699 		debug_r(r, "no key from blob. pkalg %s", pkalg);
700 		goto done;
701 	}
702 	if (key->type != pktype) {
703 		error("input_userauth_pk_ok: type mismatch "
704 		    "for decoded key (received %d, expected %d)",
705 		    key->type, pktype);
706 		goto done;
707 	}
708 
709 	/*
710 	 * search keys in the reverse order, because last candidate has been
711 	 * moved to the end of the queue.  this also avoids confusion by
712 	 * duplicate keys
713 	 */
714 	TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
715 		if (sshkey_equal(key, id->key)) {
716 			found = 1;
717 			break;
718 		}
719 	}
720 	if (!found || id == NULL) {
721 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
722 		    SSH_FP_DEFAULT);
723 		error_f("server replied with unknown key: %s %s",
724 		    sshkey_type(key), fp == NULL ? "<ERROR>" : fp);
725 		goto done;
726 	}
727 	ident = format_identity(id);
728 	debug("Server accepts key: %s", ident);
729 	sent = sign_and_send_pubkey(ssh, id);
730 	r = 0;
731  done:
732 	sshkey_free(key);
733 	free(ident);
734 	free(fp);
735 	free(pkalg);
736 	free(pkblob);
737 
738 	/* try another method if we did not send a packet */
739 	if (r == 0 && sent == 0)
740 		userauth(ssh, NULL);
741 	return r;
742 }
743 
744 #ifdef GSSAPI
745 static int
746 userauth_gssapi(struct ssh *ssh)
747 {
748 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
749 	Gssctxt *gssctxt = NULL;
750 	OM_uint32 min;
751 	int r, ok = 0;
752 	gss_OID mech = NULL;
753 
754 	/* Try one GSSAPI method at a time, rather than sending them all at
755 	 * once. */
756 
757 	if (authctxt->gss_supported_mechs == NULL)
758 		gss_indicate_mechs(&min, &authctxt->gss_supported_mechs);
759 
760 	/* Check to see whether the mechanism is usable before we offer it */
761 	while (authctxt->mech_tried < authctxt->gss_supported_mechs->count &&
762 	    !ok) {
763 		mech = &authctxt->gss_supported_mechs->
764 		    elements[authctxt->mech_tried];
765 		/* My DER encoding requires length<128 */
766 		if (mech->length < 128 && ssh_gssapi_check_mechanism(&gssctxt,
767 		    mech, authctxt->host)) {
768 			ok = 1; /* Mechanism works */
769 		} else {
770 			authctxt->mech_tried++;
771 		}
772 	}
773 
774 	if (!ok || mech == NULL)
775 		return 0;
776 
777 	authctxt->methoddata=(void *)gssctxt;
778 
779 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
780 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
781 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
782 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
783 	    (r = sshpkt_put_u32(ssh, 1)) != 0 ||
784 	    (r = sshpkt_put_u32(ssh, (mech->length) + 2)) != 0 ||
785 	    (r = sshpkt_put_u8(ssh, SSH_GSS_OIDTYPE)) != 0 ||
786 	    (r = sshpkt_put_u8(ssh, mech->length)) != 0 ||
787 	    (r = sshpkt_put(ssh, mech->elements, mech->length)) != 0 ||
788 	    (r = sshpkt_send(ssh)) != 0)
789 		fatal_fr(r, "send packet");
790 
791 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
792 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
793 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
794 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
795 
796 	authctxt->mech_tried++; /* Move along to next candidate */
797 
798 	return 1;
799 }
800 
801 static void
802 userauth_gssapi_cleanup(struct ssh *ssh)
803 {
804 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
805 	Gssctxt *gssctxt = (Gssctxt *)authctxt->methoddata;
806 
807 	ssh_gssapi_delete_ctx(&gssctxt);
808 	authctxt->methoddata = NULL;
809 }
810 
811 static OM_uint32
812 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok)
813 {
814 	Authctxt *authctxt = ssh->authctxt;
815 	Gssctxt *gssctxt = authctxt->methoddata;
816 	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
817 	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
818 	gss_buffer_desc gssbuf;
819 	OM_uint32 status, ms, flags;
820 	int r;
821 
822 	status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
823 	    recv_tok, &send_tok, &flags);
824 
825 	if (send_tok.length > 0) {
826 		u_char type = GSS_ERROR(status) ?
827 		    SSH2_MSG_USERAUTH_GSSAPI_ERRTOK :
828 		    SSH2_MSG_USERAUTH_GSSAPI_TOKEN;
829 
830 		if ((r = sshpkt_start(ssh, type)) != 0 ||
831 		    (r = sshpkt_put_string(ssh, send_tok.value,
832 		    send_tok.length)) != 0 ||
833 		    (r = sshpkt_send(ssh)) != 0)
834 			fatal_fr(r, "send %u packet", type);
835 
836 		gss_release_buffer(&ms, &send_tok);
837 	}
838 
839 	if (status == GSS_S_COMPLETE) {
840 		/* send either complete or MIC, depending on mechanism */
841 		if (!(flags & GSS_C_INTEG_FLAG)) {
842 			if ((r = sshpkt_start(ssh,
843 			    SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)) != 0 ||
844 			    (r = sshpkt_send(ssh)) != 0)
845 				fatal_fr(r, "send completion");
846 		} else {
847 			struct sshbuf *b;
848 
849 			if ((b = sshbuf_new()) == NULL)
850 				fatal_f("sshbuf_new failed");
851 			ssh_gssapi_buildmic(b, authctxt->server_user,
852 			    authctxt->service, "gssapi-with-mic",
853 			    ssh->kex->session_id);
854 
855 			if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL)
856 				fatal_f("sshbuf_mutable_ptr failed");
857 			gssbuf.length = sshbuf_len(b);
858 
859 			status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
860 
861 			if (!GSS_ERROR(status)) {
862 				if ((r = sshpkt_start(ssh,
863 				    SSH2_MSG_USERAUTH_GSSAPI_MIC)) != 0 ||
864 				    (r = sshpkt_put_string(ssh, mic.value,
865 				    mic.length)) != 0 ||
866 				    (r = sshpkt_send(ssh)) != 0)
867 					fatal_fr(r, "send MIC");
868 			}
869 
870 			sshbuf_free(b);
871 			gss_release_buffer(&ms, &mic);
872 		}
873 	}
874 
875 	return status;
876 }
877 
878 static int
879 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh)
880 {
881 	Authctxt *authctxt = ssh->authctxt;
882 	Gssctxt *gssctxt;
883 	size_t oidlen;
884 	u_char *oidv = NULL;
885 	int r;
886 
887 	if (authctxt == NULL)
888 		fatal("input_gssapi_response: no authentication context");
889 	gssctxt = authctxt->methoddata;
890 
891 	/* Setup our OID */
892 	if ((r = sshpkt_get_string(ssh, &oidv, &oidlen)) != 0)
893 		goto done;
894 
895 	if (oidlen <= 2 ||
896 	    oidv[0] != SSH_GSS_OIDTYPE ||
897 	    oidv[1] != oidlen - 2) {
898 		debug("Badly encoded mechanism OID received");
899 		userauth(ssh, NULL);
900 		goto ok;
901 	}
902 
903 	if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
904 		fatal("Server returned different OID than expected");
905 
906 	if ((r = sshpkt_get_end(ssh)) != 0)
907 		goto done;
908 
909 	if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) {
910 		/* Start again with next method on list */
911 		debug("Trying to start again");
912 		userauth(ssh, NULL);
913 		goto ok;
914 	}
915  ok:
916 	r = 0;
917  done:
918 	free(oidv);
919 	return r;
920 }
921 
922 static int
923 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh)
924 {
925 	Authctxt *authctxt = ssh->authctxt;
926 	gss_buffer_desc recv_tok;
927 	u_char *p = NULL;
928 	size_t len;
929 	OM_uint32 status;
930 	int r;
931 
932 	if (authctxt == NULL)
933 		fatal("input_gssapi_response: no authentication context");
934 
935 	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
936 	    (r = sshpkt_get_end(ssh)) != 0)
937 		goto out;
938 
939 	recv_tok.value = p;
940 	recv_tok.length = len;
941 	status = process_gssapi_token(ssh, &recv_tok);
942 
943 	/* Start again with the next method in the list */
944 	if (GSS_ERROR(status)) {
945 		userauth(ssh, NULL);
946 		/* ok */
947 	}
948 	r = 0;
949  out:
950 	free(p);
951 	return r;
952 }
953 
954 static int
955 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh)
956 {
957 	Authctxt *authctxt = ssh->authctxt;
958 	Gssctxt *gssctxt;
959 	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
960 	gss_buffer_desc recv_tok;
961 	OM_uint32 ms;
962 	u_char *p = NULL;
963 	size_t len;
964 	int r;
965 
966 	if (authctxt == NULL)
967 		fatal("input_gssapi_response: no authentication context");
968 	gssctxt = authctxt->methoddata;
969 
970 	if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 ||
971 	    (r = sshpkt_get_end(ssh)) != 0) {
972 		free(p);
973 		return r;
974 	}
975 
976 	/* Stick it into GSSAPI and see what it says */
977 	recv_tok.value = p;
978 	recv_tok.length = len;
979 	(void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
980 	    &recv_tok, &send_tok, NULL);
981 	free(p);
982 	gss_release_buffer(&ms, &send_tok);
983 
984 	/* Server will be returning a failed packet after this one */
985 	return 0;
986 }
987 
988 static int
989 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh)
990 {
991 	char *msg = NULL;
992 	char *lang = NULL;
993 	int r;
994 
995 	if ((r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* maj */
996 	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* min */
997 	    (r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
998 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
999 		goto out;
1000 	r = sshpkt_get_end(ssh);
1001 	debug("Server GSSAPI Error:\n%s", msg);
1002  out:
1003 	free(msg);
1004 	free(lang);
1005 	return r;
1006 }
1007 #endif /* GSSAPI */
1008 
1009 static int
1010 userauth_none(struct ssh *ssh)
1011 {
1012 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1013 	int r;
1014 
1015 	/* initial userauth request */
1016 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1017 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1018 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1019 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1020 	    (r = sshpkt_send(ssh)) != 0)
1021 		fatal_fr(r, "send packet");
1022 	return 1;
1023 }
1024 
1025 static int
1026 userauth_passwd(struct ssh *ssh)
1027 {
1028 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1029 	char *password, *prompt = NULL;
1030 	const char *host = options.host_key_alias ?  options.host_key_alias :
1031 	    authctxt->host;
1032 	int r;
1033 
1034 	if (authctxt->attempt_passwd++ >= options.number_of_password_prompts)
1035 		return 0;
1036 
1037 	if (authctxt->attempt_passwd != 1)
1038 		error("Permission denied, please try again.");
1039 
1040 	xasprintf(&prompt, "%s@%s's password: ", authctxt->server_user, host);
1041 	password = read_passphrase(prompt, 0);
1042 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1043 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1044 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1045 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1046 	    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
1047 	    (r = sshpkt_put_cstring(ssh, password)) != 0 ||
1048 	    (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1049 	    (r = sshpkt_send(ssh)) != 0)
1050 		fatal_fr(r, "send packet");
1051 
1052 	free(prompt);
1053 	if (password != NULL)
1054 		freezero(password, strlen(password));
1055 
1056 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1057 	    &input_userauth_passwd_changereq);
1058 
1059 	return 1;
1060 }
1061 
1062 /*
1063  * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
1064  */
1065 static int
1066 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh)
1067 {
1068 	Authctxt *authctxt = ssh->authctxt;
1069 	char *info = NULL, *lang = NULL, *password = NULL, *retype = NULL;
1070 	char prompt[256];
1071 	const char *host;
1072 	int r;
1073 
1074 	debug2("input_userauth_passwd_changereq");
1075 
1076 	if (authctxt == NULL)
1077 		fatal("input_userauth_passwd_changereq: "
1078 		    "no authentication context");
1079 	host = options.host_key_alias ? options.host_key_alias : authctxt->host;
1080 
1081 	if ((r = sshpkt_get_cstring(ssh, &info, NULL)) != 0 ||
1082 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1083 		goto out;
1084 	if (strlen(info) > 0)
1085 		logit("%s", info);
1086 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1087 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1088 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1089 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1090 	    (r = sshpkt_put_u8(ssh, 1)) != 0)	/* additional info */
1091 		goto out;
1092 
1093 	snprintf(prompt, sizeof(prompt),
1094 	    "Enter %.30s@%.128s's old password: ",
1095 	    authctxt->server_user, host);
1096 	password = read_passphrase(prompt, 0);
1097 	if ((r = sshpkt_put_cstring(ssh, password)) != 0)
1098 		goto out;
1099 
1100 	freezero(password, strlen(password));
1101 	password = NULL;
1102 	while (password == NULL) {
1103 		snprintf(prompt, sizeof(prompt),
1104 		    "Enter %.30s@%.128s's new password: ",
1105 		    authctxt->server_user, host);
1106 		password = read_passphrase(prompt, RP_ALLOW_EOF);
1107 		if (password == NULL) {
1108 			/* bail out */
1109 			r = 0;
1110 			goto out;
1111 		}
1112 		snprintf(prompt, sizeof(prompt),
1113 		    "Retype %.30s@%.128s's new password: ",
1114 		    authctxt->server_user, host);
1115 		retype = read_passphrase(prompt, 0);
1116 		if (strcmp(password, retype) != 0) {
1117 			freezero(password, strlen(password));
1118 			logit("Mismatch; try again, EOF to quit.");
1119 			password = NULL;
1120 		}
1121 		freezero(retype, strlen(retype));
1122 	}
1123 	if ((r = sshpkt_put_cstring(ssh, password)) != 0 ||
1124 	    (r = sshpkt_add_padding(ssh, 64)) != 0 ||
1125 	    (r = sshpkt_send(ssh)) != 0)
1126 		goto out;
1127 
1128 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
1129 	    &input_userauth_passwd_changereq);
1130 	r = 0;
1131  out:
1132 	if (password)
1133 		freezero(password, strlen(password));
1134 	free(info);
1135 	free(lang);
1136 	return r;
1137 }
1138 
1139 /*
1140  * Select an algorithm for publickey signatures.
1141  * Returns algorithm (caller must free) or NULL if no mutual algorithm found.
1142  *
1143  * Call with ssh==NULL to ignore server-sig-algs extension list and
1144  * only attempt with the key's base signature type.
1145  */
1146 static char *
1147 key_sig_algorithm(struct ssh *ssh, const struct sshkey *key)
1148 {
1149 	char *allowed, *oallowed, *cp, *tmp, *alg = NULL;
1150 	const char *server_sig_algs;
1151 
1152 	/*
1153 	 * The signature algorithm will only differ from the key algorithm
1154 	 * for RSA keys/certs and when the server advertises support for
1155 	 * newer (SHA2) algorithms.
1156 	 */
1157 	if (ssh == NULL || ssh->kex->server_sig_algs == NULL ||
1158 	    (key->type != KEY_RSA && key->type != KEY_RSA_CERT) ||
1159 	    (key->type == KEY_RSA_CERT && (ssh->compat & SSH_BUG_SIGTYPE))) {
1160 		/* Filter base key signature alg against our configuration */
1161 		return match_list(sshkey_ssh_name(key),
1162 		    options.pubkey_accepted_algos, NULL);
1163 	}
1164 
1165 	/*
1166 	 * Workaround OpenSSH 7.4 bug: this version supports RSA/SHA-2 but
1167 	 * fails to advertise it via SSH2_MSG_EXT_INFO.
1168 	 */
1169 	server_sig_algs = ssh->kex->server_sig_algs;
1170 	if (key->type == KEY_RSA && (ssh->compat & SSH_BUG_SIGTYPE74))
1171 		server_sig_algs = "rsa-sha2-256,rsa-sha2-512";
1172 
1173 	/*
1174 	 * For RSA keys/certs, since these might have a different sig type:
1175 	 * find the first entry in PubkeyAcceptedAlgorithms of the right type
1176 	 * that also appears in the supported signature algorithms list from
1177 	 * the server.
1178 	 */
1179 	oallowed = allowed = xstrdup(options.pubkey_accepted_algos);
1180 	while ((cp = strsep(&allowed, ",")) != NULL) {
1181 		if (sshkey_type_from_name(cp) != key->type)
1182 			continue;
1183 		tmp = match_list(sshkey_sigalg_by_name(cp),
1184 		    server_sig_algs, NULL);
1185 		if (tmp != NULL)
1186 			alg = xstrdup(cp);
1187 		free(tmp);
1188 		if (alg != NULL)
1189 			break;
1190 	}
1191 	free(oallowed);
1192 	return alg;
1193 }
1194 
1195 static int
1196 identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1197     const u_char *data, size_t datalen, u_int compat, const char *alg)
1198 {
1199 	struct sshkey *sign_key = NULL, *prv = NULL;
1200 	int is_agent = 0, retried = 0, r = SSH_ERR_INTERNAL_ERROR;
1201 	struct notifier_ctx *notifier = NULL;
1202 	char *fp = NULL, *pin = NULL, *prompt = NULL;
1203 
1204 	*sigp = NULL;
1205 	*lenp = 0;
1206 
1207 	/* The agent supports this key. */
1208 	if (id->key != NULL && id->agent_fd != -1) {
1209 		return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1210 		    data, datalen, alg, compat);
1211 	}
1212 
1213 	/*
1214 	 * We have already loaded the private key or the private key is
1215 	 * stored in external hardware.
1216 	 */
1217 	if (id->key != NULL &&
1218 	    (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) {
1219 		sign_key = id->key;
1220 		is_agent = 1;
1221 	} else {
1222 		/* Load the private key from the file. */
1223 		if ((prv = load_identity_file(id)) == NULL)
1224 			return SSH_ERR_KEY_NOT_FOUND;
1225 		if (id->key != NULL && !sshkey_equal_public(prv, id->key)) {
1226 			error_f("private key %s contents do not match public",
1227 			    id->filename);
1228 			r = SSH_ERR_KEY_NOT_FOUND;
1229 			goto out;
1230 		}
1231 		sign_key = prv;
1232 	}
1233  retry_pin:
1234 	/* Prompt for touch for non-agent FIDO keys that request UP */
1235 	if (!is_agent && sshkey_is_sk(sign_key) &&
1236 	    (sign_key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1237 		/* XXX should batch mode just skip these? */
1238 		if ((fp = sshkey_fingerprint(sign_key,
1239 		    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1240 			fatal_f("fingerprint failed");
1241 		notifier = notify_start(options.batch_mode,
1242 		    "Confirm user presence for key %s %s",
1243 		    sshkey_type(sign_key), fp);
1244 		free(fp);
1245 	}
1246 	if ((r = sshkey_sign(sign_key, sigp, lenp, data, datalen,
1247 	    alg, options.sk_provider, pin, compat)) != 0) {
1248 		debug_fr(r, "sshkey_sign");
1249 		if (!retried && pin == NULL && !is_agent &&
1250 		    sshkey_is_sk(sign_key) &&
1251 		    r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1252 			notify_complete(notifier, NULL);
1253 			notifier = NULL;
1254 			xasprintf(&prompt, "Enter PIN for %s key %s: ",
1255 			    sshkey_type(sign_key), id->filename);
1256 			pin = read_passphrase(prompt, 0);
1257 			retried = 1;
1258 			goto retry_pin;
1259 		}
1260 		goto out;
1261 	}
1262 
1263 	/*
1264 	 * PKCS#11 tokens may not support all signature algorithms,
1265 	 * so check what we get back.
1266 	 */
1267 	if ((r = sshkey_check_sigtype(*sigp, *lenp, alg)) != 0) {
1268 		debug_fr(r, "sshkey_check_sigtype");
1269 		goto out;
1270 	}
1271 	/* success */
1272 	r = 0;
1273  out:
1274 	free(prompt);
1275 	if (pin != NULL)
1276 		freezero(pin, strlen(pin));
1277 	notify_complete(notifier, r == 0 ? "User presence confirmed" : NULL);
1278 	sshkey_free(prv);
1279 	return r;
1280 }
1281 
1282 static int
1283 id_filename_matches(Identity *id, Identity *private_id)
1284 {
1285 	static const char * const suffixes[] = { ".pub", "-cert.pub", NULL };
1286 	size_t len = strlen(id->filename), plen = strlen(private_id->filename);
1287 	size_t i, slen;
1288 
1289 	if (strcmp(id->filename, private_id->filename) == 0)
1290 		return 1;
1291 	for (i = 0; suffixes[i]; i++) {
1292 		slen = strlen(suffixes[i]);
1293 		if (len > slen && plen == len - slen &&
1294 		    strcmp(id->filename + (len - slen), suffixes[i]) == 0 &&
1295 		    memcmp(id->filename, private_id->filename, plen) == 0)
1296 			return 1;
1297 	}
1298 	return 0;
1299 }
1300 
1301 static int
1302 sign_and_send_pubkey(struct ssh *ssh, Identity *id)
1303 {
1304 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1305 	struct sshbuf *b = NULL;
1306 	Identity *private_id, *sign_id = NULL;
1307 	u_char *signature = NULL;
1308 	size_t slen = 0, skip = 0;
1309 	int r, fallback_sigtype, sent = 0;
1310 	char *alg = NULL, *fp = NULL;
1311 	const char *loc = "", *method = "publickey";
1312 	int hostbound = 0;
1313 
1314 	/* prefer host-bound pubkey signatures if supported by server */
1315 	if ((ssh->kex->flags & KEX_HAS_PUBKEY_HOSTBOUND) != 0 &&
1316 	    (options.pubkey_authentication & SSH_PUBKEY_AUTH_HBOUND) != 0) {
1317 		hostbound = 1;
1318 		method = "publickey-hostbound-v00@openssh.com";
1319 	}
1320 
1321 	if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1322 	    SSH_FP_DEFAULT)) == NULL)
1323 		return 0;
1324 
1325 	debug3_f("using %s with %s %s", method, sshkey_type(id->key), fp);
1326 
1327 	/*
1328 	 * If the key is an certificate, try to find a matching private key
1329 	 * and use it to complete the signature.
1330 	 * If no such private key exists, fall back to trying the certificate
1331 	 * key itself in case it has a private half already loaded.
1332 	 * This will try to set sign_id to the private key that will perform
1333 	 * the signature.
1334 	 */
1335 	if (sshkey_is_cert(id->key)) {
1336 		TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1337 			if (sshkey_equal_public(id->key, private_id->key) &&
1338 			    id->key->type != private_id->key->type) {
1339 				sign_id = private_id;
1340 				break;
1341 			}
1342 		}
1343 		/*
1344 		 * Exact key matches are preferred, but also allow
1345 		 * filename matches for non-PKCS#11/agent keys that
1346 		 * didn't load public keys. This supports the case
1347 		 * of keeping just a private key file and public
1348 		 * certificate on disk.
1349 		 */
1350 		if (sign_id == NULL &&
1351 		    !id->isprivate && id->agent_fd == -1 &&
1352 		    (id->key->flags & SSHKEY_FLAG_EXT) == 0) {
1353 			TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1354 				if (private_id->key == NULL &&
1355 				    id_filename_matches(id, private_id)) {
1356 					sign_id = private_id;
1357 					break;
1358 				}
1359 			}
1360 		}
1361 		if (sign_id != NULL) {
1362 			debug2_f("using private key \"%s\"%s for "
1363 			    "certificate", sign_id->filename,
1364 			    sign_id->agent_fd != -1 ? " from agent" : "");
1365 		} else {
1366 			debug_f("no separate private key for certificate "
1367 			    "\"%s\"", id->filename);
1368 		}
1369 	}
1370 
1371 	/*
1372 	 * If the above didn't select another identity to do the signing
1373 	 * then default to the one we started with.
1374 	 */
1375 	if (sign_id == NULL)
1376 		sign_id = id;
1377 
1378 	/* assemble and sign data */
1379 	for (fallback_sigtype = 0; fallback_sigtype <= 1; fallback_sigtype++) {
1380 		free(alg);
1381 		slen = 0;
1382 		signature = NULL;
1383 		if ((alg = key_sig_algorithm(fallback_sigtype ? NULL : ssh,
1384 		    id->key)) == NULL) {
1385 			error_f("no mutual signature supported");
1386 			goto out;
1387 		}
1388 		debug3_f("signing using %s %s", alg, fp);
1389 
1390 		sshbuf_free(b);
1391 		if ((b = sshbuf_new()) == NULL)
1392 			fatal_f("sshbuf_new failed");
1393 		if (ssh->compat & SSH_OLD_SESSIONID) {
1394 			if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
1395 				fatal_fr(r, "sshbuf_putb");
1396 		} else {
1397 			if ((r = sshbuf_put_stringb(b,
1398 			    ssh->kex->session_id)) != 0)
1399 				fatal_fr(r, "sshbuf_put_stringb");
1400 		}
1401 		skip = sshbuf_len(b);
1402 		if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1403 		    (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1404 		    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
1405 		    (r = sshbuf_put_cstring(b, method)) != 0 ||
1406 		    (r = sshbuf_put_u8(b, 1)) != 0 ||
1407 		    (r = sshbuf_put_cstring(b, alg)) != 0 ||
1408 		    (r = sshkey_puts(id->key, b)) != 0) {
1409 			fatal_fr(r, "assemble signed data");
1410 		}
1411 		if (hostbound) {
1412 			if (ssh->kex->initial_hostkey == NULL) {
1413 				fatal_f("internal error: initial hostkey "
1414 				    "not recorded");
1415 			}
1416 			if ((r = sshkey_puts(ssh->kex->initial_hostkey, b)) != 0)
1417 				fatal_fr(r, "assemble %s hostkey", method);
1418 		}
1419 		/* generate signature */
1420 		r = identity_sign(sign_id, &signature, &slen,
1421 		    sshbuf_ptr(b), sshbuf_len(b), ssh->compat, alg);
1422 		if (r == 0)
1423 			break;
1424 		else if (r == SSH_ERR_KEY_NOT_FOUND)
1425 			goto out; /* soft failure */
1426 		else if (r == SSH_ERR_SIGN_ALG_UNSUPPORTED &&
1427 		    !fallback_sigtype) {
1428 			if (sign_id->agent_fd != -1)
1429 				loc = "agent ";
1430 			else if ((sign_id->key->flags & SSHKEY_FLAG_EXT) != 0)
1431 				loc = "token ";
1432 			logit("%skey %s %s returned incorrect signature type",
1433 			    loc, sshkey_type(id->key), fp);
1434 			continue;
1435 		}
1436 		error_fr(r, "signing failed for %s \"%s\"%s",
1437 		    sshkey_type(sign_id->key), sign_id->filename,
1438 		    id->agent_fd != -1 ? " from agent" : "");
1439 		goto out;
1440 	}
1441 	if (slen == 0 || signature == NULL) /* shouldn't happen */
1442 		fatal_f("no signature");
1443 
1444 	/* append signature */
1445 	if ((r = sshbuf_put_string(b, signature, slen)) != 0)
1446 		fatal_fr(r, "append signature");
1447 
1448 #ifdef DEBUG_PK
1449 	sshbuf_dump(b, stderr);
1450 #endif
1451 	/* skip session id and packet type */
1452 	if ((r = sshbuf_consume(b, skip + 1)) != 0)
1453 		fatal_fr(r, "consume");
1454 
1455 	/* put remaining data from buffer into packet */
1456 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1457 	    (r = sshpkt_putb(ssh, b)) != 0 ||
1458 	    (r = sshpkt_send(ssh)) != 0)
1459 		fatal_fr(r, "enqueue request");
1460 
1461 	/* success */
1462 	sent = 1;
1463 
1464  out:
1465 	free(fp);
1466 	free(alg);
1467 	sshbuf_free(b);
1468 	freezero(signature, slen);
1469 	return sent;
1470 }
1471 
1472 static int
1473 send_pubkey_test(struct ssh *ssh, Identity *id)
1474 {
1475 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1476 	u_char *blob = NULL;
1477 	char *alg = NULL;
1478 	size_t bloblen;
1479 	u_int have_sig = 0;
1480 	int sent = 0, r;
1481 
1482 	if ((alg = key_sig_algorithm(ssh, id->key)) == NULL) {
1483 		debug_f("no mutual signature algorithm");
1484 		goto out;
1485 	}
1486 
1487 	if ((r = sshkey_to_blob(id->key, &blob, &bloblen)) != 0) {
1488 		/* we cannot handle this key */
1489 		debug3_f("cannot handle key");
1490 		goto out;
1491 	}
1492 	/* register callback for USERAUTH_PK_OK message */
1493 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1494 
1495 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1496 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1497 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1498 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1499 	    (r = sshpkt_put_u8(ssh, have_sig)) != 0 ||
1500 	    (r = sshpkt_put_cstring(ssh, alg)) != 0 ||
1501 	    (r = sshpkt_put_string(ssh, blob, bloblen)) != 0 ||
1502 	    (r = sshpkt_send(ssh)) != 0)
1503 		fatal_fr(r, "send packet");
1504 	sent = 1;
1505 
1506  out:
1507 	free(alg);
1508 	free(blob);
1509 	return sent;
1510 }
1511 
1512 static struct sshkey *
1513 load_identity_file(Identity *id)
1514 {
1515 	struct sshkey *private = NULL;
1516 	char prompt[300], *passphrase, *comment;
1517 	int r, quit = 0, i;
1518 	struct stat st;
1519 
1520 	if (stat(id->filename, &st) == -1) {
1521 		do_log2(id->userprovided ?
1522 		    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_DEBUG3,
1523 		    "no such identity: %s: %s", id->filename, strerror(errno));
1524 		return NULL;
1525 	}
1526 	snprintf(prompt, sizeof prompt,
1527 	    "Enter passphrase for key '%.100s': ", id->filename);
1528 	for (i = 0; i <= options.number_of_password_prompts; i++) {
1529 		if (i == 0)
1530 			passphrase = "";
1531 		else {
1532 			passphrase = read_passphrase(prompt, 0);
1533 			if (*passphrase == '\0') {
1534 				debug2("no passphrase given, try next key");
1535 				free(passphrase);
1536 				break;
1537 			}
1538 		}
1539 		switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1540 		    passphrase, &private, &comment))) {
1541 		case 0:
1542 			break;
1543 		case SSH_ERR_KEY_WRONG_PASSPHRASE:
1544 			if (options.batch_mode) {
1545 				quit = 1;
1546 				break;
1547 			}
1548 			if (i != 0)
1549 				debug2("bad passphrase given, try again...");
1550 			break;
1551 		case SSH_ERR_SYSTEM_ERROR:
1552 			if (errno == ENOENT) {
1553 				debug2_r(r, "Load key \"%s\"", id->filename);
1554 				quit = 1;
1555 				break;
1556 			}
1557 			/* FALLTHROUGH */
1558 		default:
1559 			error_r(r, "Load key \"%s\"", id->filename);
1560 			quit = 1;
1561 			break;
1562 		}
1563 		if (private != NULL && sshkey_is_sk(private) &&
1564 		    options.sk_provider == NULL) {
1565 			debug("key \"%s\" is an authenticator-hosted key, "
1566 			    "but no provider specified", id->filename);
1567 			sshkey_free(private);
1568 			private = NULL;
1569 			quit = 1;
1570 		}
1571 		if (!quit && (r = sshkey_check_rsa_length(private,
1572 		    options.required_rsa_size)) != 0) {
1573 			debug_fr(r, "Skipping key %s", id->filename);
1574 			sshkey_free(private);
1575 			private = NULL;
1576 			quit = 1;
1577 		}
1578 		if (!quit && private != NULL && id->agent_fd == -1 &&
1579 		    !(id->key && id->isprivate))
1580 			maybe_add_key_to_agent(id->filename, private, comment,
1581 			    passphrase);
1582 		if (i > 0)
1583 			freezero(passphrase, strlen(passphrase));
1584 		free(comment);
1585 		if (private != NULL || quit)
1586 			break;
1587 	}
1588 	return private;
1589 }
1590 
1591 static int
1592 key_type_allowed_by_config(struct sshkey *key)
1593 {
1594 	if (match_pattern_list(sshkey_ssh_name(key),
1595 	    options.pubkey_accepted_algos, 0) == 1)
1596 		return 1;
1597 
1598 	/* RSA keys/certs might be allowed by alternate signature types */
1599 	switch (key->type) {
1600 	case KEY_RSA:
1601 		if (match_pattern_list("rsa-sha2-512",
1602 		    options.pubkey_accepted_algos, 0) == 1)
1603 			return 1;
1604 		if (match_pattern_list("rsa-sha2-256",
1605 		    options.pubkey_accepted_algos, 0) == 1)
1606 			return 1;
1607 		break;
1608 	case KEY_RSA_CERT:
1609 		if (match_pattern_list("rsa-sha2-512-cert-v01@openssh.com",
1610 		    options.pubkey_accepted_algos, 0) == 1)
1611 			return 1;
1612 		if (match_pattern_list("rsa-sha2-256-cert-v01@openssh.com",
1613 		    options.pubkey_accepted_algos, 0) == 1)
1614 			return 1;
1615 		break;
1616 	}
1617 	return 0;
1618 }
1619 
1620 /* obtain a list of keys from the agent */
1621 static int
1622 get_agent_identities(struct ssh *ssh, int *agent_fdp,
1623     struct ssh_identitylist **idlistp)
1624 {
1625 	int r, agent_fd;
1626 	struct ssh_identitylist *idlist;
1627 
1628 	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1629 		if (r != SSH_ERR_AGENT_NOT_PRESENT)
1630 			debug_fr(r, "ssh_get_authentication_socket");
1631 		return r;
1632 	}
1633 	if ((r = ssh_agent_bind_hostkey(agent_fd, ssh->kex->initial_hostkey,
1634 	    ssh->kex->session_id, ssh->kex->initial_sig, 0)) == 0)
1635 		debug_f("bound agent to hostkey");
1636 	else
1637 		debug2_fr(r, "ssh_agent_bind_hostkey");
1638 
1639 	if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
1640 		debug_fr(r, "ssh_fetch_identitylist");
1641 		close(agent_fd);
1642 		return r;
1643 	}
1644 	/* success */
1645 	*agent_fdp = agent_fd;
1646 	*idlistp = idlist;
1647 	debug_f("agent returned %zu keys", idlist->nkeys);
1648 	return 0;
1649 }
1650 
1651 /*
1652  * try keys in the following order:
1653  *	1. certificates listed in the config file
1654  *	2. other input certificates
1655  *	3. agent keys that are found in the config file
1656  *	4. other agent keys
1657  *	5. keys that are only listed in the config file
1658  */
1659 static void
1660 pubkey_prepare(struct ssh *ssh, Authctxt *authctxt)
1661 {
1662 	struct identity *id, *id2, *tmp;
1663 	struct idlist agent, files, *preferred;
1664 	struct sshkey *key;
1665 	int disallowed, agent_fd = -1, i, r, found;
1666 	size_t j;
1667 	struct ssh_identitylist *idlist;
1668 	char *cp, *ident;
1669 
1670 	TAILQ_INIT(&agent);	/* keys from the agent */
1671 	TAILQ_INIT(&files);	/* keys from the config file */
1672 	preferred = &authctxt->keys;
1673 	TAILQ_INIT(preferred);	/* preferred order of keys */
1674 
1675 	/* list of keys stored in the filesystem and PKCS#11 */
1676 	for (i = 0; i < options.num_identity_files; i++) {
1677 		key = options.identity_keys[i];
1678 		if (key && key->cert &&
1679 		    key->cert->type != SSH2_CERT_TYPE_USER) {
1680 			debug_f("ignoring certificate %s: not a user "
1681 			    "certificate", options.identity_files[i]);
1682 			continue;
1683 		}
1684 		if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1685 			debug_f("ignoring authenticator-hosted key %s as no "
1686 			    "SecurityKeyProvider has been specified",
1687 			    options.identity_files[i]);
1688 			continue;
1689 		}
1690 		options.identity_keys[i] = NULL;
1691 		id = xcalloc(1, sizeof(*id));
1692 		id->agent_fd = -1;
1693 		id->key = key;
1694 		id->filename = xstrdup(options.identity_files[i]);
1695 		id->userprovided = options.identity_file_userprovided[i];
1696 		TAILQ_INSERT_TAIL(&files, id, next);
1697 	}
1698 	/* list of certificates specified by user */
1699 	for (i = 0; i < options.num_certificate_files; i++) {
1700 		key = options.certificates[i];
1701 		if (!sshkey_is_cert(key) || key->cert == NULL ||
1702 		    key->cert->type != SSH2_CERT_TYPE_USER) {
1703 			debug_f("ignoring certificate %s: not a user "
1704 			    "certificate", options.identity_files[i]);
1705 			continue;
1706 		}
1707 		if (key && sshkey_is_sk(key) && options.sk_provider == NULL) {
1708 			debug_f("ignoring authenticator-hosted key "
1709 			    "certificate %s as no "
1710 			    "SecurityKeyProvider has been specified",
1711 			    options.identity_files[i]);
1712 			continue;
1713 		}
1714 		id = xcalloc(1, sizeof(*id));
1715 		id->agent_fd = -1;
1716 		id->key = key;
1717 		id->filename = xstrdup(options.certificate_files[i]);
1718 		id->userprovided = options.certificate_file_userprovided[i];
1719 		TAILQ_INSERT_TAIL(preferred, id, next);
1720 	}
1721 	/* list of keys supported by the agent */
1722 	if ((r = get_agent_identities(ssh, &agent_fd, &idlist)) == 0) {
1723 		for (j = 0; j < idlist->nkeys; j++) {
1724 			if ((r = sshkey_check_rsa_length(idlist->keys[j],
1725 			    options.required_rsa_size)) != 0) {
1726 				debug_fr(r, "ignoring %s agent key",
1727 				    sshkey_ssh_name(idlist->keys[j]));
1728 				continue;
1729 			}
1730 			found = 0;
1731 			TAILQ_FOREACH(id, &files, next) {
1732 				/*
1733 				 * agent keys from the config file are
1734 				 * preferred
1735 				 */
1736 				if (sshkey_equal(idlist->keys[j], id->key)) {
1737 					TAILQ_REMOVE(&files, id, next);
1738 					TAILQ_INSERT_TAIL(preferred, id, next);
1739 					id->agent_fd = agent_fd;
1740 					found = 1;
1741 					break;
1742 				}
1743 			}
1744 			if (!found && !options.identities_only) {
1745 				id = xcalloc(1, sizeof(*id));
1746 				/* XXX "steals" key/comment from idlist */
1747 				id->key = idlist->keys[j];
1748 				id->filename = idlist->comments[j];
1749 				idlist->keys[j] = NULL;
1750 				idlist->comments[j] = NULL;
1751 				id->agent_fd = agent_fd;
1752 				TAILQ_INSERT_TAIL(&agent, id, next);
1753 			}
1754 		}
1755 		ssh_free_identitylist(idlist);
1756 		/* append remaining agent keys */
1757 		TAILQ_CONCAT(preferred, &agent, next);
1758 		authctxt->agent_fd = agent_fd;
1759 	}
1760 	/* Prefer PKCS11 keys that are explicitly listed */
1761 	TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1762 		if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1763 			continue;
1764 		found = 0;
1765 		TAILQ_FOREACH(id2, &files, next) {
1766 			if (id2->key == NULL ||
1767 			    (id2->key->flags & SSHKEY_FLAG_EXT) != 0)
1768 				continue;
1769 			if (sshkey_equal(id->key, id2->key)) {
1770 				TAILQ_REMOVE(&files, id, next);
1771 				TAILQ_INSERT_TAIL(preferred, id, next);
1772 				found = 1;
1773 				break;
1774 			}
1775 		}
1776 		/* If IdentitiesOnly set and key not found then don't use it */
1777 		if (!found && options.identities_only) {
1778 			TAILQ_REMOVE(&files, id, next);
1779 			freezero(id, sizeof(*id));
1780 		}
1781 	}
1782 	/* append remaining keys from the config file */
1783 	TAILQ_CONCAT(preferred, &files, next);
1784 	/* finally, filter by PubkeyAcceptedAlgorithms */
1785 	TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1786 		disallowed = 0;
1787 		cp = NULL;
1788 		if (id->key == NULL)
1789 			continue;
1790 		if (!key_type_allowed_by_config(id->key)) {
1791 			debug("Skipping %s key %s - corresponding algorithm "
1792 			    "not in PubkeyAcceptedAlgorithms",
1793 			    sshkey_ssh_name(id->key), id->filename);
1794 			disallowed = 1;
1795 		} else if (ssh->kex->server_sig_algs != NULL &&
1796 		    (cp = key_sig_algorithm(ssh, id->key)) == NULL) {
1797 			debug("Skipping %s key %s - corresponding algorithm "
1798 			    "not supported by server",
1799 			    sshkey_ssh_name(id->key), id->filename);
1800 			disallowed = 1;
1801 		}
1802 		free(cp);
1803 		if (!disallowed)
1804 			continue;
1805 		/* remove key */
1806 		TAILQ_REMOVE(preferred, id, next);
1807 		sshkey_free(id->key);
1808 		free(id->filename);
1809 		memset(id, 0, sizeof(*id));
1810 	}
1811 	/* List the keys we plan on using */
1812 	TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1813 		ident = format_identity(id);
1814 		debug("Will attempt key: %s", ident);
1815 		free(ident);
1816 	}
1817 	debug2_f("done");
1818 }
1819 
1820 static void
1821 pubkey_cleanup(struct ssh *ssh)
1822 {
1823 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1824 	Identity *id;
1825 
1826 	if (authctxt->agent_fd != -1) {
1827 		ssh_close_authentication_socket(authctxt->agent_fd);
1828 		authctxt->agent_fd = -1;
1829 	}
1830 	for (id = TAILQ_FIRST(&authctxt->keys); id;
1831 	    id = TAILQ_FIRST(&authctxt->keys)) {
1832 		TAILQ_REMOVE(&authctxt->keys, id, next);
1833 		sshkey_free(id->key);
1834 		free(id->filename);
1835 		free(id);
1836 	}
1837 }
1838 
1839 static void
1840 pubkey_reset(Authctxt *authctxt)
1841 {
1842 	Identity *id;
1843 
1844 	TAILQ_FOREACH(id, &authctxt->keys, next)
1845 		id->tried = 0;
1846 }
1847 
1848 static int
1849 userauth_pubkey(struct ssh *ssh)
1850 {
1851 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1852 	Identity *id;
1853 	int sent = 0;
1854 	char *ident;
1855 	static int prepared;
1856 
1857 	if (!prepared) {
1858 		pubkey_prepare(ssh, authctxt);
1859 		prepared = 1;
1860 	}
1861 
1862 	while ((id = TAILQ_FIRST(&authctxt->keys))) {
1863 		if (id->tried++)
1864 			return (0);
1865 		/* move key to the end of the queue */
1866 		TAILQ_REMOVE(&authctxt->keys, id, next);
1867 		TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1868 		/*
1869 		 * send a test message if we have the public key. for
1870 		 * encrypted keys we cannot do this and have to load the
1871 		 * private key instead
1872 		 */
1873 		if (id->key != NULL) {
1874 			ident = format_identity(id);
1875 			debug("Offering public key: %s", ident);
1876 			free(ident);
1877 			sent = send_pubkey_test(ssh, id);
1878 		} else {
1879 			debug("Trying private key: %s", id->filename);
1880 			id->key = load_identity_file(id);
1881 			if (id->key != NULL) {
1882 				if (id->key != NULL) {
1883 					id->isprivate = 1;
1884 					sent = sign_and_send_pubkey(ssh, id);
1885 				}
1886 				sshkey_free(id->key);
1887 				id->key = NULL;
1888 				id->isprivate = 0;
1889 			}
1890 		}
1891 		if (sent)
1892 			return (sent);
1893 	}
1894 	return (0);
1895 }
1896 
1897 /*
1898  * Send userauth request message specifying keyboard-interactive method.
1899  */
1900 static int
1901 userauth_kbdint(struct ssh *ssh)
1902 {
1903 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1904 	int r;
1905 
1906 	if (authctxt->attempt_kbdint++ >= options.number_of_password_prompts)
1907 		return 0;
1908 	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1909 	if (authctxt->attempt_kbdint > 1 && !authctxt->info_req_seen) {
1910 		debug3("userauth_kbdint: disable: no info_req_seen");
1911 		ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1912 		return 0;
1913 	}
1914 
1915 	debug2("userauth_kbdint");
1916 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1917 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1918 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1919 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1920 	    (r = sshpkt_put_cstring(ssh, "")) != 0 ||		/* lang */
1921 	    (r = sshpkt_put_cstring(ssh, options.kbd_interactive_devices ?
1922 	    options.kbd_interactive_devices : "")) != 0 ||
1923 	    (r = sshpkt_send(ssh)) != 0)
1924 		fatal_fr(r, "send packet");
1925 
1926 	ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1927 	return 1;
1928 }
1929 
1930 /*
1931  * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1932  */
1933 static int
1934 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh)
1935 {
1936 	Authctxt *authctxt = ssh->authctxt;
1937 	char *name = NULL, *inst = NULL, *lang = NULL, *prompt = NULL;
1938 	char *display_prompt = NULL, *response = NULL;
1939 	u_char echo = 0;
1940 	u_int num_prompts, i;
1941 	int r;
1942 
1943 	debug2_f("entering");
1944 
1945 	if (authctxt == NULL)
1946 		fatal_f("no authentication context");
1947 
1948 	authctxt->info_req_seen = 1;
1949 
1950 	if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
1951 	    (r = sshpkt_get_cstring(ssh, &inst, NULL)) != 0 ||
1952 	    (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0)
1953 		goto out;
1954 	if (strlen(name) > 0)
1955 		logit("%s", name);
1956 	if (strlen(inst) > 0)
1957 		logit("%s", inst);
1958 
1959 	if ((r = sshpkt_get_u32(ssh, &num_prompts)) != 0)
1960 		goto out;
1961 	/*
1962 	 * Begin to build info response packet based on prompts requested.
1963 	 * We commit to providing the correct number of responses, so if
1964 	 * further on we run into a problem that prevents this, we have to
1965 	 * be sure and clean this up and send a correct error response.
1966 	 */
1967 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE)) != 0 ||
1968 	    (r = sshpkt_put_u32(ssh, num_prompts)) != 0)
1969 		goto out;
1970 
1971 	debug2_f("num_prompts %d", num_prompts);
1972 	for (i = 0; i < num_prompts; i++) {
1973 		if ((r = sshpkt_get_cstring(ssh, &prompt, NULL)) != 0 ||
1974 		    (r = sshpkt_get_u8(ssh, &echo)) != 0)
1975 			goto out;
1976 		if (asmprintf(&display_prompt, INT_MAX, NULL, "(%s@%s) %s",
1977 		    authctxt->server_user, options.host_key_alias ?
1978 		    options.host_key_alias : authctxt->host, prompt) == -1)
1979 			fatal_f("asmprintf failed");
1980 		response = read_passphrase(display_prompt, echo ? RP_ECHO : 0);
1981 		if ((r = sshpkt_put_cstring(ssh, response)) != 0)
1982 			goto out;
1983 		freezero(response, strlen(response));
1984 		free(prompt);
1985 		free(display_prompt);
1986 		display_prompt = response = prompt = NULL;
1987 	}
1988 	/* done with parsing incoming message. */
1989 	if ((r = sshpkt_get_end(ssh)) != 0 ||
1990 	    (r = sshpkt_add_padding(ssh, 64)) != 0)
1991 		goto out;
1992 	r = sshpkt_send(ssh);
1993  out:
1994 	if (response)
1995 		freezero(response, strlen(response));
1996 	free(prompt);
1997 	free(display_prompt);
1998 	free(name);
1999 	free(inst);
2000 	free(lang);
2001 	return r;
2002 }
2003 
2004 static int
2005 ssh_keysign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp,
2006     const u_char *data, size_t datalen)
2007 {
2008 	struct sshbuf *b;
2009 	struct stat st;
2010 	pid_t pid;
2011 	int r, to[2], from[2], status;
2012 	int sock = ssh_packet_get_connection_in(ssh);
2013 	u_char rversion = 0, version = 2;
2014 	void (*osigchld)(int);
2015 
2016 	*sigp = NULL;
2017 	*lenp = 0;
2018 
2019 	if (stat(_PATH_SSH_KEY_SIGN, &st) == -1) {
2020 		error_f("not installed: %s", strerror(errno));
2021 		return -1;
2022 	}
2023 	if (fflush(stdout) != 0) {
2024 		error_f("fflush: %s", strerror(errno));
2025 		return -1;
2026 	}
2027 	if (pipe(to) == -1) {
2028 		error_f("pipe: %s", strerror(errno));
2029 		return -1;
2030 	}
2031 	if (pipe(from) == -1) {
2032 		error_f("pipe: %s", strerror(errno));
2033 		return -1;
2034 	}
2035 	if ((pid = fork()) == -1) {
2036 		error_f("fork: %s", strerror(errno));
2037 		return -1;
2038 	}
2039 	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
2040 	if (pid == 0) {
2041 		close(from[0]);
2042 		if (dup2(from[1], STDOUT_FILENO) == -1)
2043 			fatal_f("dup2: %s", strerror(errno));
2044 		close(to[1]);
2045 		if (dup2(to[0], STDIN_FILENO) == -1)
2046 			fatal_f("dup2: %s", strerror(errno));
2047 		close(from[1]);
2048 		close(to[0]);
2049 
2050 		if (dup2(sock, STDERR_FILENO + 1) == -1)
2051 			fatal_f("dup2: %s", strerror(errno));
2052 		sock = STDERR_FILENO + 1;
2053 		if (fcntl(sock, F_SETFD, 0) == -1) /* keep the socket on exec */
2054 			debug3_f("fcntl F_SETFD: %s", strerror(errno));
2055 		closefrom(sock + 1);
2056 
2057 		debug3_f("[child] pid=%ld, exec %s",
2058 		    (long)getpid(), _PATH_SSH_KEY_SIGN);
2059 		execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
2060 		fatal_f("exec(%s): %s", _PATH_SSH_KEY_SIGN,
2061 		    strerror(errno));
2062 	}
2063 	close(from[1]);
2064 	close(to[0]);
2065 	sock = STDERR_FILENO + 1;
2066 
2067 	if ((b = sshbuf_new()) == NULL)
2068 		fatal_f("sshbuf_new failed");
2069 	/* send # of sock, data to be signed */
2070 	if ((r = sshbuf_put_u32(b, sock)) != 0 ||
2071 	    (r = sshbuf_put_string(b, data, datalen)) != 0)
2072 		fatal_fr(r, "buffer error");
2073 	if (ssh_msg_send(to[1], version, b) == -1)
2074 		fatal_f("couldn't send request");
2075 	sshbuf_reset(b);
2076 	r = ssh_msg_recv(from[0], b);
2077 	close(from[0]);
2078 	close(to[1]);
2079 	if (r < 0) {
2080 		error_f("no reply");
2081 		goto fail;
2082 	}
2083 
2084 	errno = 0;
2085 	while (waitpid(pid, &status, 0) == -1) {
2086 		if (errno != EINTR) {
2087 			error_f("waitpid %ld: %s", (long)pid, strerror(errno));
2088 			goto fail;
2089 		}
2090 	}
2091 	if (!WIFEXITED(status)) {
2092 		error_f("exited abnormally");
2093 		goto fail;
2094 	}
2095 	if (WEXITSTATUS(status) != 0) {
2096 		error_f("exited with status %d", WEXITSTATUS(status));
2097 		goto fail;
2098 	}
2099 	if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
2100 		error_fr(r, "buffer error");
2101 		goto fail;
2102 	}
2103 	if (rversion != version) {
2104 		error_f("bad version");
2105 		goto fail;
2106 	}
2107 	if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
2108 		error_fr(r, "buffer error");
2109  fail:
2110 		ssh_signal(SIGCHLD, osigchld);
2111 		sshbuf_free(b);
2112 		return -1;
2113 	}
2114 	ssh_signal(SIGCHLD, osigchld);
2115 	sshbuf_free(b);
2116 
2117 	return 0;
2118 }
2119 
2120 static int
2121 userauth_hostbased(struct ssh *ssh)
2122 {
2123 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
2124 	struct sshkey *private = NULL;
2125 	struct sshbuf *b = NULL;
2126 	u_char *sig = NULL, *keyblob = NULL;
2127 	char *fp = NULL, *chost = NULL, *lname = NULL;
2128 	size_t siglen = 0, keylen = 0;
2129 	int i, r, success = 0;
2130 
2131 	if (authctxt->ktypes == NULL) {
2132 		authctxt->oktypes = xstrdup(options.hostbased_accepted_algos);
2133 		authctxt->ktypes = authctxt->oktypes;
2134 	}
2135 
2136 	/*
2137 	 * Work through each listed type pattern in HostbasedAcceptedAlgorithms,
2138 	 * trying each hostkey that matches the type in turn.
2139 	 */
2140 	for (;;) {
2141 		if (authctxt->active_ktype == NULL)
2142 			authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
2143 		if (authctxt->active_ktype == NULL ||
2144 		    *authctxt->active_ktype == '\0')
2145 			break;
2146 		debug3_f("trying key type %s", authctxt->active_ktype);
2147 
2148 		/* check for a useful key */
2149 		private = NULL;
2150 		for (i = 0; i < authctxt->sensitive->nkeys; i++) {
2151 			if (authctxt->sensitive->keys[i] == NULL ||
2152 			    authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
2153 				continue;
2154 			if (!sshkey_match_keyname_to_sigalgs(
2155 			    sshkey_ssh_name(authctxt->sensitive->keys[i]),
2156 			    authctxt->active_ktype))
2157 				continue;
2158 			/* we take and free the key */
2159 			private = authctxt->sensitive->keys[i];
2160 			authctxt->sensitive->keys[i] = NULL;
2161 			break;
2162 		}
2163 		/* Found one */
2164 		if (private != NULL)
2165 			break;
2166 		/* No more keys of this type; advance */
2167 		authctxt->active_ktype = NULL;
2168 	}
2169 	if (private == NULL) {
2170 		free(authctxt->oktypes);
2171 		authctxt->oktypes = authctxt->ktypes = NULL;
2172 		authctxt->active_ktype = NULL;
2173 		debug("No more client hostkeys for hostbased authentication.");
2174 		goto out;
2175 	}
2176 
2177 	if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
2178 	    SSH_FP_DEFAULT)) == NULL) {
2179 		error_f("sshkey_fingerprint failed");
2180 		goto out;
2181 	}
2182 	debug_f("trying hostkey %s %s using sigalg %s",
2183 	    sshkey_ssh_name(private), fp, authctxt->active_ktype);
2184 
2185 	/* figure out a name for the client host */
2186 	lname = get_local_name(ssh_packet_get_connection_in(ssh));
2187 	if (lname == NULL) {
2188 		error_f("cannot get local ipaddr/name");
2189 		goto out;
2190 	}
2191 
2192 	/* XXX sshbuf_put_stringf? */
2193 	xasprintf(&chost, "%s.", lname);
2194 	debug2_f("chost %s", chost);
2195 
2196 	/* construct data */
2197 	if ((b = sshbuf_new()) == NULL) {
2198 		error_f("sshbuf_new failed");
2199 		goto out;
2200 	}
2201 	if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
2202 		error_fr(r, "sshkey_to_blob");
2203 		goto out;
2204 	}
2205 	if ((r = sshbuf_put_stringb(b, ssh->kex->session_id)) != 0 ||
2206 	    (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2207 	    (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
2208 	    (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
2209 	    (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
2210 	    (r = sshbuf_put_cstring(b, authctxt->active_ktype)) != 0 ||
2211 	    (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
2212 	    (r = sshbuf_put_cstring(b, chost)) != 0 ||
2213 	    (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
2214 		error_fr(r, "buffer error");
2215 		goto out;
2216 	}
2217 
2218 #ifdef DEBUG_PK
2219 	sshbuf_dump(b, stderr);
2220 #endif
2221 	if ((r = ssh_keysign(ssh, private, &sig, &siglen,
2222 	    sshbuf_ptr(b), sshbuf_len(b))) != 0) {
2223 		error("sign using hostkey %s %s failed",
2224 		    sshkey_ssh_name(private), fp);
2225 		goto out;
2226 	}
2227 	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
2228 	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
2229 	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
2230 	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
2231 	    (r = sshpkt_put_cstring(ssh, authctxt->active_ktype)) != 0 ||
2232 	    (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
2233 	    (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
2234 	    (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
2235 	    (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
2236 	    (r = sshpkt_send(ssh)) != 0) {
2237 		error_fr(r, "packet error");
2238 		goto out;
2239 	}
2240 	success = 1;
2241 
2242  out:
2243 	if (sig != NULL)
2244 		freezero(sig, siglen);
2245 	free(keyblob);
2246 	free(lname);
2247 	free(fp);
2248 	free(chost);
2249 	sshkey_free(private);
2250 	sshbuf_free(b);
2251 
2252 	return success;
2253 }
2254 
2255 /* find auth method */
2256 
2257 /*
2258  * given auth method name, if configurable options permit this method fill
2259  * in auth_ident field and return true, otherwise return false.
2260  */
2261 static int
2262 authmethod_is_enabled(Authmethod *method)
2263 {
2264 	if (method == NULL)
2265 		return 0;
2266 	/* return false if options indicate this method is disabled */
2267 	if  (method->enabled == NULL || *method->enabled == 0)
2268 		return 0;
2269 	/* return false if batch mode is enabled but method needs interactive mode */
2270 	if  (method->batch_flag != NULL && *method->batch_flag != 0)
2271 		return 0;
2272 	return 1;
2273 }
2274 
2275 static Authmethod *
2276 authmethod_lookup(const char *name)
2277 {
2278 	Authmethod *method = NULL;
2279 	if (name != NULL)
2280 		for (method = authmethods; method->name != NULL; method++)
2281 			if (strcmp(name, method->name) == 0)
2282 				return method;
2283 	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
2284 	return NULL;
2285 }
2286 
2287 /* XXX internal state */
2288 static Authmethod *current = NULL;
2289 static char *supported = NULL;
2290 static char *preferred = NULL;
2291 
2292 /*
2293  * Given the authentication method list sent by the server, return the
2294  * next method we should try.  If the server initially sends a nil list,
2295  * use a built-in default list.
2296  */
2297 static Authmethod *
2298 authmethod_get(char *authlist)
2299 {
2300 	char *name = NULL;
2301 	u_int next;
2302 
2303 	/* Use a suitable default if we're passed a nil list.  */
2304 	if (authlist == NULL || strlen(authlist) == 0)
2305 		authlist = options.preferred_authentications;
2306 
2307 	if (supported == NULL || strcmp(authlist, supported) != 0) {
2308 		debug3("start over, passed a different list %s", authlist);
2309 		free(supported);
2310 		supported = xstrdup(authlist);
2311 		preferred = options.preferred_authentications;
2312 		debug3("preferred %s", preferred);
2313 		current = NULL;
2314 	} else if (current != NULL && authmethod_is_enabled(current))
2315 		return current;
2316 
2317 	for (;;) {
2318 		if ((name = match_list(preferred, supported, &next)) == NULL) {
2319 			debug("No more authentication methods to try.");
2320 			current = NULL;
2321 			return NULL;
2322 		}
2323 		preferred += next;
2324 		debug3("authmethod_lookup %s", name);
2325 		debug3("remaining preferred: %s", preferred);
2326 		if ((current = authmethod_lookup(name)) != NULL &&
2327 		    authmethod_is_enabled(current)) {
2328 			debug3("authmethod_is_enabled %s", name);
2329 			debug("Next authentication method: %s", name);
2330 			free(name);
2331 			return current;
2332 		}
2333 		free(name);
2334 	}
2335 }
2336 
2337 static char *
2338 authmethods_get(void)
2339 {
2340 	Authmethod *method = NULL;
2341 	struct sshbuf *b;
2342 	char *list;
2343 	int r;
2344 
2345 	if ((b = sshbuf_new()) == NULL)
2346 		fatal_f("sshbuf_new failed");
2347 	for (method = authmethods; method->name != NULL; method++) {
2348 		if (authmethod_is_enabled(method)) {
2349 			if ((r = sshbuf_putf(b, "%s%s",
2350 			    sshbuf_len(b) ? "," : "", method->name)) != 0)
2351 				fatal_fr(r, "buffer error");
2352 		}
2353 	}
2354 	if ((list = sshbuf_dup_string(b)) == NULL)
2355 		fatal_f("sshbuf_dup_string failed");
2356 	sshbuf_free(b);
2357 	return list;
2358 }
2359