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