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