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