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