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