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