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