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