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