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