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