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