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