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