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