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