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