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