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