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