sshconnect2.c revision 296853
1/* $OpenBSD: sshconnect2.c,v 1.239 2016/02/23 01:34:14 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 <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
75#ifdef GSSAPI
76#include "ssh-gss.h"
77#endif
78
79/* import */
80extern char *client_version_string;
81extern char *server_version_string;
82extern Options options;
83
84/*
85 * SSH2 key exchange
86 */
87
88u_char *session_id2 = NULL;
89u_int session_id2_len = 0;
90
91char *xxx_host;
92struct sockaddr *xxx_hostaddr;
93
94static int
95verify_host_key_callback(Key *hostkey, struct ssh *ssh)
96{
97	if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1)
98		fatal("Host key verification failed.");
99	return 0;
100}
101
102static char *
103order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port)
104{
105	char *oavail, *avail, *first, *last, *alg, *hostname, *ret;
106	size_t maxlen;
107	struct hostkeys *hostkeys;
108	int ktype;
109	u_int i;
110
111	/* Find all hostkeys for this hostname */
112	get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL);
113	hostkeys = init_hostkeys();
114	for (i = 0; i < options.num_user_hostfiles; i++)
115		load_hostkeys(hostkeys, hostname, options.user_hostfiles[i]);
116	for (i = 0; i < options.num_system_hostfiles; i++)
117		load_hostkeys(hostkeys, hostname, options.system_hostfiles[i]);
118
119	oavail = avail = xstrdup(KEX_DEFAULT_PK_ALG);
120	maxlen = strlen(avail) + 1;
121	first = xmalloc(maxlen);
122	last = xmalloc(maxlen);
123	*first = *last = '\0';
124
125#define ALG_APPEND(to, from) \
126	do { \
127		if (*to != '\0') \
128			strlcat(to, ",", maxlen); \
129		strlcat(to, from, maxlen); \
130	} while (0)
131
132	while ((alg = strsep(&avail, ",")) && *alg != '\0') {
133		if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC)
134			fatal("%s: unknown alg %s", __func__, alg);
135		if (lookup_key_in_hostkeys_by_type(hostkeys,
136		    sshkey_type_plain(ktype), NULL))
137			ALG_APPEND(first, alg);
138		else
139			ALG_APPEND(last, alg);
140	}
141#undef ALG_APPEND
142	xasprintf(&ret, "%s%s%s", first,
143	    (*first == '\0' || *last == '\0') ? "" : ",", last);
144	if (*first != '\0')
145		debug3("%s: prefer hostkeyalgs: %s", __func__, first);
146
147	free(first);
148	free(last);
149	free(hostname);
150	free(oavail);
151	free_hostkeys(hostkeys);
152
153	return ret;
154}
155
156void
157ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
158{
159	char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
160	char *s;
161	struct kex *kex;
162	int r;
163
164	xxx_host = host;
165	xxx_hostaddr = hostaddr;
166
167	if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
168		fatal("%s: kex_names_cat", __func__);
169	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s);
170	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
171	    compat_cipher_proposal(options.ciphers);
172	myproposal[PROPOSAL_ENC_ALGS_STOC] =
173	    compat_cipher_proposal(options.ciphers);
174	if (options.compression) {
175		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
176		myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib@openssh.com,zlib,none";
177	} else {
178		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
179		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com,zlib";
180	}
181	myproposal[PROPOSAL_MAC_ALGS_CTOS] =
182	    myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
183	if (options.hostkeyalgorithms != NULL) {
184		if (kex_assemble_names(KEX_DEFAULT_PK_ALG,
185		    &options.hostkeyalgorithms) != 0)
186			fatal("%s: kex_assemble_namelist", __func__);
187		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
188		    compat_pkalg_proposal(options.hostkeyalgorithms);
189	} else {
190		/* Enforce default */
191		options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG);
192		/* Prefer algorithms that we already have keys for */
193		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
194		    compat_pkalg_proposal(
195		    order_hostkeyalgs(host, hostaddr, port));
196	}
197
198	if (options.rekey_limit || options.rekey_interval)
199		packet_set_rekey_limits((u_int32_t)options.rekey_limit,
200		    (time_t)options.rekey_interval);
201
202	/* start key exchange */
203	if ((r = kex_setup(active_state, myproposal)) != 0)
204		fatal("kex_setup: %s", ssh_err(r));
205	kex = active_state->kex;
206#ifdef WITH_OPENSSL
207	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
208	kex->kex[KEX_DH_GRP14_SHA1] = 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, *raw, *lang;
500	u_int len;
501
502	debug3("input_userauth_banner");
503	raw = packet_get_string(&len);
504	lang = packet_get_string(NULL);
505	if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) {
506		if (len > 65536)
507			len = 65536;
508		msg = xmalloc(len * 4 + 1); /* max expansion from strnvis() */
509		strnvis(msg, raw, len * 4 + 1, VIS_SAFE|VIS_OCTAL|VIS_NOSLASH);
510		fprintf(stderr, "%s", msg);
511		free(msg);
512	}
513	free(raw);
514	free(lang);
515	return 0;
516}
517
518/* ARGSUSED */
519int
520input_userauth_success(int type, u_int32_t seq, void *ctxt)
521{
522	Authctxt *authctxt = ctxt;
523
524	if (authctxt == NULL)
525		fatal("input_userauth_success: no authentication context");
526	free(authctxt->authlist);
527	authctxt->authlist = NULL;
528	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
529		authctxt->method->cleanup(authctxt);
530	free(authctxt->methoddata);
531	authctxt->methoddata = NULL;
532	authctxt->success = 1;			/* break out */
533	return 0;
534}
535
536int
537input_userauth_success_unexpected(int type, u_int32_t seq, void *ctxt)
538{
539	Authctxt *authctxt = ctxt;
540
541	if (authctxt == NULL)
542		fatal("%s: no authentication context", __func__);
543
544	fatal("Unexpected authentication success during %s.",
545	    authctxt->method->name);
546	return 0;
547}
548
549/* ARGSUSED */
550int
551input_userauth_failure(int type, u_int32_t seq, void *ctxt)
552{
553	Authctxt *authctxt = ctxt;
554	char *authlist = NULL;
555	int partial;
556
557	if (authctxt == NULL)
558		fatal("input_userauth_failure: no authentication context");
559
560	authlist = packet_get_string(NULL);
561	partial = packet_get_char();
562	packet_check_eom();
563
564	if (partial != 0) {
565		logit("Authenticated with partial success.");
566		/* reset state */
567		pubkey_cleanup(authctxt);
568		pubkey_prepare(authctxt);
569	}
570	debug("Authentications that can continue: %s", authlist);
571
572	userauth(authctxt, authlist);
573	return 0;
574}
575
576/* ARGSUSED */
577int
578input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
579{
580	Authctxt *authctxt = ctxt;
581	Key *key = NULL;
582	Identity *id = NULL;
583	Buffer b;
584	int pktype, sent = 0;
585	u_int alen, blen;
586	char *pkalg, *fp;
587	u_char *pkblob;
588
589	if (authctxt == NULL)
590		fatal("input_userauth_pk_ok: no authentication context");
591	if (datafellows & SSH_BUG_PKOK) {
592		/* this is similar to SSH_BUG_PKAUTH */
593		debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
594		pkblob = packet_get_string(&blen);
595		buffer_init(&b);
596		buffer_append(&b, pkblob, blen);
597		pkalg = buffer_get_string(&b, &alen);
598		buffer_free(&b);
599	} else {
600		pkalg = packet_get_string(&alen);
601		pkblob = packet_get_string(&blen);
602	}
603	packet_check_eom();
604
605	debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
606
607	if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
608		debug("unknown pkalg %s", pkalg);
609		goto done;
610	}
611	if ((key = key_from_blob(pkblob, blen)) == NULL) {
612		debug("no key from blob. pkalg %s", pkalg);
613		goto done;
614	}
615	if (key->type != pktype) {
616		error("input_userauth_pk_ok: type mismatch "
617		    "for decoded key (received %d, expected %d)",
618		    key->type, pktype);
619		goto done;
620	}
621	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
622	    SSH_FP_DEFAULT)) == NULL)
623		goto done;
624	debug2("input_userauth_pk_ok: fp %s", fp);
625	free(fp);
626
627	/*
628	 * search keys in the reverse order, because last candidate has been
629	 * moved to the end of the queue.  this also avoids confusion by
630	 * duplicate keys
631	 */
632	TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
633		if (key_equal(key, id->key)) {
634			sent = sign_and_send_pubkey(authctxt, id);
635			break;
636		}
637	}
638done:
639	if (key != NULL)
640		key_free(key);
641	free(pkalg);
642	free(pkblob);
643
644	/* try another method if we did not send a packet */
645	if (sent == 0)
646		userauth(authctxt, NULL);
647	return 0;
648}
649
650#ifdef GSSAPI
651int
652userauth_gssapi(Authctxt *authctxt)
653{
654	Gssctxt *gssctxt = NULL;
655	static gss_OID_set gss_supported = NULL;
656	static u_int mech = 0;
657	OM_uint32 min;
658	int ok = 0;
659
660	/* Try one GSSAPI method at a time, rather than sending them all at
661	 * once. */
662
663	if (gss_supported == NULL)
664		gss_indicate_mechs(&min, &gss_supported);
665
666	/* Check to see if the mechanism is usable before we offer it */
667	while (mech < gss_supported->count && !ok) {
668		/* My DER encoding requires length<128 */
669		if (gss_supported->elements[mech].length < 128 &&
670		    ssh_gssapi_check_mechanism(&gssctxt,
671		    &gss_supported->elements[mech], authctxt->host)) {
672			ok = 1; /* Mechanism works */
673		} else {
674			mech++;
675		}
676	}
677
678	if (!ok)
679		return 0;
680
681	authctxt->methoddata=(void *)gssctxt;
682
683	packet_start(SSH2_MSG_USERAUTH_REQUEST);
684	packet_put_cstring(authctxt->server_user);
685	packet_put_cstring(authctxt->service);
686	packet_put_cstring(authctxt->method->name);
687
688	packet_put_int(1);
689
690	packet_put_int((gss_supported->elements[mech].length) + 2);
691	packet_put_char(SSH_GSS_OIDTYPE);
692	packet_put_char(gss_supported->elements[mech].length);
693	packet_put_raw(gss_supported->elements[mech].elements,
694	    gss_supported->elements[mech].length);
695
696	packet_send();
697
698	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
699	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
700	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
701	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
702
703	mech++; /* Move along to next candidate */
704
705	return 1;
706}
707
708static OM_uint32
709process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
710{
711	Authctxt *authctxt = ctxt;
712	Gssctxt *gssctxt = authctxt->methoddata;
713	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
714	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
715	gss_buffer_desc gssbuf;
716	OM_uint32 status, ms, flags;
717	Buffer b;
718
719	status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
720	    recv_tok, &send_tok, &flags);
721
722	if (send_tok.length > 0) {
723		if (GSS_ERROR(status))
724			packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
725		else
726			packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
727
728		packet_put_string(send_tok.value, send_tok.length);
729		packet_send();
730		gss_release_buffer(&ms, &send_tok);
731	}
732
733	if (status == GSS_S_COMPLETE) {
734		/* send either complete or MIC, depending on mechanism */
735		if (!(flags & GSS_C_INTEG_FLAG)) {
736			packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
737			packet_send();
738		} else {
739			ssh_gssapi_buildmic(&b, authctxt->server_user,
740			    authctxt->service, "gssapi-with-mic");
741
742			gssbuf.value = buffer_ptr(&b);
743			gssbuf.length = buffer_len(&b);
744
745			status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
746
747			if (!GSS_ERROR(status)) {
748				packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
749				packet_put_string(mic.value, mic.length);
750
751				packet_send();
752			}
753
754			buffer_free(&b);
755			gss_release_buffer(&ms, &mic);
756		}
757	}
758
759	return status;
760}
761
762/* ARGSUSED */
763int
764input_gssapi_response(int type, u_int32_t plen, void *ctxt)
765{
766	Authctxt *authctxt = ctxt;
767	Gssctxt *gssctxt;
768	int oidlen;
769	char *oidv;
770
771	if (authctxt == NULL)
772		fatal("input_gssapi_response: no authentication context");
773	gssctxt = authctxt->methoddata;
774
775	/* Setup our OID */
776	oidv = packet_get_string(&oidlen);
777
778	if (oidlen <= 2 ||
779	    oidv[0] != SSH_GSS_OIDTYPE ||
780	    oidv[1] != oidlen - 2) {
781		free(oidv);
782		debug("Badly encoded mechanism OID received");
783		userauth(authctxt, NULL);
784		return 0;
785	}
786
787	if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
788		fatal("Server returned different OID than expected");
789
790	packet_check_eom();
791
792	free(oidv);
793
794	if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
795		/* Start again with next method on list */
796		debug("Trying to start again");
797		userauth(authctxt, NULL);
798		return 0;
799	}
800	return 0;
801}
802
803/* ARGSUSED */
804int
805input_gssapi_token(int type, u_int32_t plen, void *ctxt)
806{
807	Authctxt *authctxt = ctxt;
808	gss_buffer_desc recv_tok;
809	OM_uint32 status;
810	u_int slen;
811
812	if (authctxt == NULL)
813		fatal("input_gssapi_response: no authentication context");
814
815	recv_tok.value = packet_get_string(&slen);
816	recv_tok.length = slen;	/* safe typecast */
817
818	packet_check_eom();
819
820	status = process_gssapi_token(ctxt, &recv_tok);
821
822	free(recv_tok.value);
823
824	if (GSS_ERROR(status)) {
825		/* Start again with the next method in the list */
826		userauth(authctxt, NULL);
827		return 0;
828	}
829	return 0;
830}
831
832/* ARGSUSED */
833int
834input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
835{
836	Authctxt *authctxt = ctxt;
837	Gssctxt *gssctxt;
838	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
839	gss_buffer_desc recv_tok;
840	OM_uint32 ms;
841	u_int len;
842
843	if (authctxt == NULL)
844		fatal("input_gssapi_response: no authentication context");
845	gssctxt = authctxt->methoddata;
846
847	recv_tok.value = packet_get_string(&len);
848	recv_tok.length = len;
849
850	packet_check_eom();
851
852	/* Stick it into GSSAPI and see what it says */
853	(void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
854	    &recv_tok, &send_tok, NULL);
855
856	free(recv_tok.value);
857	gss_release_buffer(&ms, &send_tok);
858
859	/* Server will be returning a failed packet after this one */
860	return 0;
861}
862
863/* ARGSUSED */
864int
865input_gssapi_error(int type, u_int32_t plen, void *ctxt)
866{
867	char *msg;
868	char *lang;
869
870	/* maj */(void)packet_get_int();
871	/* min */(void)packet_get_int();
872	msg=packet_get_string(NULL);
873	lang=packet_get_string(NULL);
874
875	packet_check_eom();
876
877	debug("Server GSSAPI Error:\n%s", msg);
878	free(msg);
879	free(lang);
880	return 0;
881}
882#endif /* GSSAPI */
883
884int
885userauth_none(Authctxt *authctxt)
886{
887	/* initial userauth request */
888	packet_start(SSH2_MSG_USERAUTH_REQUEST);
889	packet_put_cstring(authctxt->server_user);
890	packet_put_cstring(authctxt->service);
891	packet_put_cstring(authctxt->method->name);
892	packet_send();
893	return 1;
894}
895
896int
897userauth_passwd(Authctxt *authctxt)
898{
899	static int attempt = 0;
900	char prompt[150];
901	char *password;
902	const char *host = options.host_key_alias ?  options.host_key_alias :
903	    authctxt->host;
904
905	if (attempt++ >= options.number_of_password_prompts)
906		return 0;
907
908	if (attempt != 1)
909		error("Permission denied, please try again.");
910
911	snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
912	    authctxt->server_user, host);
913	password = read_passphrase(prompt, 0);
914	packet_start(SSH2_MSG_USERAUTH_REQUEST);
915	packet_put_cstring(authctxt->server_user);
916	packet_put_cstring(authctxt->service);
917	packet_put_cstring(authctxt->method->name);
918	packet_put_char(0);
919	packet_put_cstring(password);
920	explicit_bzero(password, strlen(password));
921	free(password);
922	packet_add_padding(64);
923	packet_send();
924
925	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
926	    &input_userauth_passwd_changereq);
927
928	return 1;
929}
930
931/*
932 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
933 */
934/* ARGSUSED */
935int
936input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
937{
938	Authctxt *authctxt = ctxt;
939	char *info, *lang, *password = NULL, *retype = NULL;
940	char prompt[150];
941	const char *host = options.host_key_alias ? options.host_key_alias :
942	    authctxt->host;
943
944	debug2("input_userauth_passwd_changereq");
945
946	if (authctxt == NULL)
947		fatal("input_userauth_passwd_changereq: "
948		    "no authentication context");
949
950	info = packet_get_string(NULL);
951	lang = packet_get_string(NULL);
952	if (strlen(info) > 0)
953		logit("%s", info);
954	free(info);
955	free(lang);
956	packet_start(SSH2_MSG_USERAUTH_REQUEST);
957	packet_put_cstring(authctxt->server_user);
958	packet_put_cstring(authctxt->service);
959	packet_put_cstring(authctxt->method->name);
960	packet_put_char(1);			/* additional info */
961	snprintf(prompt, sizeof(prompt),
962	    "Enter %.30s@%.128s's old password: ",
963	    authctxt->server_user, host);
964	password = read_passphrase(prompt, 0);
965	packet_put_cstring(password);
966	explicit_bzero(password, strlen(password));
967	free(password);
968	password = NULL;
969	while (password == NULL) {
970		snprintf(prompt, sizeof(prompt),
971		    "Enter %.30s@%.128s's new password: ",
972		    authctxt->server_user, host);
973		password = read_passphrase(prompt, RP_ALLOW_EOF);
974		if (password == NULL) {
975			/* bail out */
976			return 0;
977		}
978		snprintf(prompt, sizeof(prompt),
979		    "Retype %.30s@%.128s's new password: ",
980		    authctxt->server_user, host);
981		retype = read_passphrase(prompt, 0);
982		if (strcmp(password, retype) != 0) {
983			explicit_bzero(password, strlen(password));
984			free(password);
985			logit("Mismatch; try again, EOF to quit.");
986			password = NULL;
987		}
988		explicit_bzero(retype, strlen(retype));
989		free(retype);
990	}
991	packet_put_cstring(password);
992	explicit_bzero(password, strlen(password));
993	free(password);
994	packet_add_padding(64);
995	packet_send();
996
997	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
998	    &input_userauth_passwd_changereq);
999	return 0;
1000}
1001
1002static const char *
1003identity_sign_encode(struct identity *id)
1004{
1005	struct ssh *ssh = active_state;
1006
1007	if (id->key->type == KEY_RSA) {
1008		switch (ssh->kex->rsa_sha2) {
1009		case 256:
1010			return "rsa-sha2-256";
1011		case 512:
1012			return "rsa-sha2-512";
1013		}
1014	}
1015	return key_ssh_name(id->key);
1016}
1017
1018static int
1019identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
1020    const u_char *data, size_t datalen, u_int compat)
1021{
1022	Key *prv;
1023	int ret;
1024	const char *alg;
1025
1026	alg = identity_sign_encode(id);
1027
1028	/* the agent supports this key */
1029	if (id->agent_fd != -1)
1030		return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
1031		    data, datalen, alg, compat);
1032
1033	/*
1034	 * we have already loaded the private key or
1035	 * the private key is stored in external hardware
1036	 */
1037	if (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))
1038		return (sshkey_sign(id->key, sigp, lenp, data, datalen, alg,
1039		    compat));
1040	/* load the private key from the file */
1041	if ((prv = load_identity_file(id)) == NULL)
1042		return SSH_ERR_KEY_NOT_FOUND;
1043	ret = sshkey_sign(prv, sigp, lenp, data, datalen, alg, compat);
1044	sshkey_free(prv);
1045	return (ret);
1046}
1047
1048static int
1049sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
1050{
1051	Buffer b;
1052	Identity *private_id;
1053	u_char *blob, *signature;
1054	size_t slen;
1055	u_int bloblen, skip = 0;
1056	int matched, ret = -1, have_sig = 1;
1057	char *fp;
1058
1059	if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash,
1060	    SSH_FP_DEFAULT)) == NULL)
1061		return 0;
1062	debug3("%s: %s %s", __func__, key_type(id->key), fp);
1063	free(fp);
1064
1065	if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1066		/* we cannot handle this key */
1067		debug3("sign_and_send_pubkey: cannot handle key");
1068		return 0;
1069	}
1070	/* data to be signed */
1071	buffer_init(&b);
1072	if (datafellows & SSH_OLD_SESSIONID) {
1073		buffer_append(&b, session_id2, session_id2_len);
1074		skip = session_id2_len;
1075	} else {
1076		buffer_put_string(&b, session_id2, session_id2_len);
1077		skip = buffer_len(&b);
1078	}
1079	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1080	buffer_put_cstring(&b, authctxt->server_user);
1081	buffer_put_cstring(&b,
1082	    datafellows & SSH_BUG_PKSERVICE ?
1083	    "ssh-userauth" :
1084	    authctxt->service);
1085	if (datafellows & SSH_BUG_PKAUTH) {
1086		buffer_put_char(&b, have_sig);
1087	} else {
1088		buffer_put_cstring(&b, authctxt->method->name);
1089		buffer_put_char(&b, have_sig);
1090		buffer_put_cstring(&b, identity_sign_encode(id));
1091	}
1092	buffer_put_string(&b, blob, bloblen);
1093
1094	/*
1095	 * If the key is an certificate, try to find a matching private key
1096	 * and use it to complete the signature.
1097	 * If no such private key exists, return failure and continue with
1098	 * other methods of authentication.
1099	 */
1100	if (key_is_cert(id->key)) {
1101		matched = 0;
1102		TAILQ_FOREACH(private_id, &authctxt->keys, next) {
1103			if (sshkey_equal_public(id->key, private_id->key) &&
1104			    id->key->type != private_id->key->type) {
1105				id = private_id;
1106				matched = 1;
1107				break;
1108			}
1109		}
1110		if (matched) {
1111			debug2("%s: using private key \"%s\"%s for "
1112			    "certificate", __func__, id->filename,
1113			    id->agent_fd != -1 ? " from agent" : "");
1114		} else {
1115			/* XXX maybe verbose/error? */
1116			debug("%s: no private key for certificate "
1117			    "\"%s\"", __func__, id->filename);
1118			free(blob);
1119			buffer_free(&b);
1120			return 0;
1121		}
1122	}
1123
1124	/* generate signature */
1125	ret = identity_sign(id, &signature, &slen,
1126	    buffer_ptr(&b), buffer_len(&b), datafellows);
1127	if (ret != 0) {
1128		if (ret != SSH_ERR_KEY_NOT_FOUND)
1129			error("%s: signing failed: %s", __func__, ssh_err(ret));
1130		free(blob);
1131		buffer_free(&b);
1132		return 0;
1133	}
1134#ifdef DEBUG_PK
1135	buffer_dump(&b);
1136#endif
1137	if (datafellows & SSH_BUG_PKSERVICE) {
1138		buffer_clear(&b);
1139		buffer_append(&b, session_id2, session_id2_len);
1140		skip = session_id2_len;
1141		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1142		buffer_put_cstring(&b, authctxt->server_user);
1143		buffer_put_cstring(&b, authctxt->service);
1144		buffer_put_cstring(&b, authctxt->method->name);
1145		buffer_put_char(&b, have_sig);
1146		if (!(datafellows & SSH_BUG_PKAUTH))
1147			buffer_put_cstring(&b, key_ssh_name(id->key));
1148		buffer_put_string(&b, blob, bloblen);
1149	}
1150	free(blob);
1151
1152	/* append signature */
1153	buffer_put_string(&b, signature, slen);
1154	free(signature);
1155
1156	/* skip session id and packet type */
1157	if (buffer_len(&b) < skip + 1)
1158		fatal("userauth_pubkey: internal error");
1159	buffer_consume(&b, skip + 1);
1160
1161	/* put remaining data from buffer into packet */
1162	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1163	packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1164	buffer_free(&b);
1165	packet_send();
1166
1167	return 1;
1168}
1169
1170static int
1171send_pubkey_test(Authctxt *authctxt, Identity *id)
1172{
1173	u_char *blob;
1174	u_int bloblen, have_sig = 0;
1175
1176	debug3("send_pubkey_test");
1177
1178	if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1179		/* we cannot handle this key */
1180		debug3("send_pubkey_test: cannot handle key");
1181		return 0;
1182	}
1183	/* register callback for USERAUTH_PK_OK message */
1184	dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1185
1186	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1187	packet_put_cstring(authctxt->server_user);
1188	packet_put_cstring(authctxt->service);
1189	packet_put_cstring(authctxt->method->name);
1190	packet_put_char(have_sig);
1191	if (!(datafellows & SSH_BUG_PKAUTH))
1192		packet_put_cstring(identity_sign_encode(id));
1193	packet_put_string(blob, bloblen);
1194	free(blob);
1195	packet_send();
1196	return 1;
1197}
1198
1199static Key *
1200load_identity_file(Identity *id)
1201{
1202	Key *private = NULL;
1203	char prompt[300], *passphrase, *comment;
1204	int r, perm_ok = 0, quit = 0, i;
1205	struct stat st;
1206
1207	if (stat(id->filename, &st) < 0) {
1208		(id->userprovided ? logit : debug3)("no such identity: %s: %s",
1209		    id->filename, strerror(errno));
1210		return NULL;
1211	}
1212	snprintf(prompt, sizeof prompt,
1213	    "Enter passphrase for key '%.100s': ", id->filename);
1214	for (i = 0; i <= options.number_of_password_prompts; i++) {
1215		if (i == 0)
1216			passphrase = "";
1217		else {
1218			passphrase = read_passphrase(prompt, 0);
1219			if (*passphrase == '\0') {
1220				debug2("no passphrase given, try next key");
1221				free(passphrase);
1222				break;
1223			}
1224		}
1225		switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename,
1226		    passphrase, &private, &comment, &perm_ok))) {
1227		case 0:
1228			break;
1229		case SSH_ERR_KEY_WRONG_PASSPHRASE:
1230			if (options.batch_mode) {
1231				quit = 1;
1232				break;
1233			}
1234			if (i != 0)
1235				debug2("bad passphrase given, try again...");
1236			break;
1237		case SSH_ERR_SYSTEM_ERROR:
1238			if (errno == ENOENT) {
1239				debug2("Load key \"%s\": %s",
1240				    id->filename, ssh_err(r));
1241				quit = 1;
1242				break;
1243			}
1244			/* FALLTHROUGH */
1245		default:
1246			error("Load key \"%s\": %s", id->filename, ssh_err(r));
1247			quit = 1;
1248			break;
1249		}
1250		if (!quit && private != NULL && id->agent_fd == -1 &&
1251		    !(id->key && id->isprivate))
1252			maybe_add_key_to_agent(id->filename, private, comment,
1253			    passphrase);
1254		if (i > 0) {
1255			explicit_bzero(passphrase, strlen(passphrase));
1256			free(passphrase);
1257		}
1258		free(comment);
1259		if (private != NULL || quit)
1260			break;
1261	}
1262	return private;
1263}
1264
1265/*
1266 * try keys in the following order:
1267 * 	1. certificates listed in the config file
1268 * 	2. other input certificates
1269 *	3. agent keys that are found in the config file
1270 *	4. other agent keys
1271 *	5. keys that are only listed in the config file
1272 */
1273static void
1274pubkey_prepare(Authctxt *authctxt)
1275{
1276	struct identity *id, *id2, *tmp;
1277	struct idlist agent, files, *preferred;
1278	struct sshkey *key;
1279	int agent_fd = -1, i, r, found;
1280	size_t j;
1281	struct ssh_identitylist *idlist;
1282
1283	TAILQ_INIT(&agent);	/* keys from the agent */
1284	TAILQ_INIT(&files);	/* keys from the config file */
1285	preferred = &authctxt->keys;
1286	TAILQ_INIT(preferred);	/* preferred order of keys */
1287
1288	/* list of keys stored in the filesystem and PKCS#11 */
1289	for (i = 0; i < options.num_identity_files; i++) {
1290		key = options.identity_keys[i];
1291		if (key && key->type == KEY_RSA1)
1292			continue;
1293		if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1294			continue;
1295		options.identity_keys[i] = NULL;
1296		id = xcalloc(1, sizeof(*id));
1297		id->agent_fd = -1;
1298		id->key = key;
1299		id->filename = xstrdup(options.identity_files[i]);
1300		id->userprovided = options.identity_file_userprovided[i];
1301		TAILQ_INSERT_TAIL(&files, id, next);
1302	}
1303	/* Prefer PKCS11 keys that are explicitly listed */
1304	TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1305		if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1306			continue;
1307		found = 0;
1308		TAILQ_FOREACH(id2, &files, next) {
1309			if (id2->key == NULL ||
1310			    (id2->key->flags & SSHKEY_FLAG_EXT) == 0)
1311				continue;
1312			if (sshkey_equal(id->key, id2->key)) {
1313				TAILQ_REMOVE(&files, id, next);
1314				TAILQ_INSERT_TAIL(preferred, id, next);
1315				found = 1;
1316				break;
1317			}
1318		}
1319		/* If IdentitiesOnly set and key not found then don't use it */
1320		if (!found && options.identities_only) {
1321			TAILQ_REMOVE(&files, id, next);
1322			explicit_bzero(id, sizeof(*id));
1323			free(id);
1324		}
1325	}
1326	/* list of certificates specified by user */
1327	for (i = 0; i < options.num_certificate_files; i++) {
1328		key = options.certificates[i];
1329		if (!key_is_cert(key) || key->cert == NULL ||
1330		    key->cert->type != SSH2_CERT_TYPE_USER)
1331			continue;
1332		id = xcalloc(1, sizeof(*id));
1333		id->agent_fd = -1;
1334		id->key = key;
1335		id->filename = xstrdup(options.certificate_files[i]);
1336		id->userprovided = options.certificate_file_userprovided[i];
1337		TAILQ_INSERT_TAIL(preferred, id, next);
1338	}
1339	/* list of keys supported by the agent */
1340	if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
1341		if (r != SSH_ERR_AGENT_NOT_PRESENT)
1342			debug("%s: ssh_get_authentication_socket: %s",
1343			    __func__, ssh_err(r));
1344	} else if ((r = ssh_fetch_identitylist(agent_fd, 2, &idlist)) != 0) {
1345		if (r != SSH_ERR_AGENT_NO_IDENTITIES)
1346			debug("%s: ssh_fetch_identitylist: %s",
1347			    __func__, ssh_err(r));
1348		close(agent_fd);
1349	} else {
1350		for (j = 0; j < idlist->nkeys; j++) {
1351			found = 0;
1352			TAILQ_FOREACH(id, &files, next) {
1353				/*
1354				 * agent keys from the config file are
1355				 * preferred
1356				 */
1357				if (sshkey_equal(idlist->keys[j], id->key)) {
1358					TAILQ_REMOVE(&files, id, next);
1359					TAILQ_INSERT_TAIL(preferred, id, next);
1360					id->agent_fd = agent_fd;
1361					found = 1;
1362					break;
1363				}
1364			}
1365			if (!found && !options.identities_only) {
1366				id = xcalloc(1, sizeof(*id));
1367				/* XXX "steals" key/comment from idlist */
1368				id->key = idlist->keys[j];
1369				id->filename = idlist->comments[j];
1370				idlist->keys[j] = NULL;
1371				idlist->comments[j] = NULL;
1372				id->agent_fd = agent_fd;
1373				TAILQ_INSERT_TAIL(&agent, id, next);
1374			}
1375		}
1376		ssh_free_identitylist(idlist);
1377		/* append remaining agent keys */
1378		for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1379			TAILQ_REMOVE(&agent, id, next);
1380			TAILQ_INSERT_TAIL(preferred, id, next);
1381		}
1382		authctxt->agent_fd = agent_fd;
1383	}
1384	/* append remaining keys from the config file */
1385	for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1386		TAILQ_REMOVE(&files, id, next);
1387		TAILQ_INSERT_TAIL(preferred, id, next);
1388	}
1389	/* finally, filter by PubkeyAcceptedKeyTypes */
1390	TAILQ_FOREACH_SAFE(id, preferred, next, id2) {
1391		if (id->key != NULL &&
1392		    match_pattern_list(sshkey_ssh_name(id->key),
1393		    options.pubkey_key_types, 0) != 1) {
1394			debug("Skipping %s key %s - "
1395			    "not in PubkeyAcceptedKeyTypes",
1396			    sshkey_ssh_name(id->key), id->filename);
1397			TAILQ_REMOVE(preferred, id, next);
1398			sshkey_free(id->key);
1399			free(id->filename);
1400			memset(id, 0, sizeof(*id));
1401			continue;
1402		}
1403		debug2("key: %s (%p)%s%s", id->filename, id->key,
1404		    id->userprovided ? ", explicit" : "",
1405		    id->agent_fd != -1 ? ", agent" : "");
1406	}
1407}
1408
1409static void
1410pubkey_cleanup(Authctxt *authctxt)
1411{
1412	Identity *id;
1413
1414	if (authctxt->agent_fd != -1)
1415		ssh_close_authentication_socket(authctxt->agent_fd);
1416	for (id = TAILQ_FIRST(&authctxt->keys); id;
1417	    id = TAILQ_FIRST(&authctxt->keys)) {
1418		TAILQ_REMOVE(&authctxt->keys, id, next);
1419		sshkey_free(id->key);
1420		free(id->filename);
1421		free(id);
1422	}
1423}
1424
1425static int
1426try_identity(Identity *id)
1427{
1428	if (!id->key)
1429		return (0);
1430	if (key_type_plain(id->key->type) == KEY_RSA &&
1431	    (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1432		debug("Skipped %s key %s for RSA/MD5 server",
1433		    key_type(id->key), id->filename);
1434		return (0);
1435	}
1436	return (id->key->type != KEY_RSA1);
1437}
1438
1439int
1440userauth_pubkey(Authctxt *authctxt)
1441{
1442	Identity *id;
1443	int sent = 0;
1444
1445	while ((id = TAILQ_FIRST(&authctxt->keys))) {
1446		if (id->tried++)
1447			return (0);
1448		/* move key to the end of the queue */
1449		TAILQ_REMOVE(&authctxt->keys, id, next);
1450		TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1451		/*
1452		 * send a test message if we have the public key. for
1453		 * encrypted keys we cannot do this and have to load the
1454		 * private key instead
1455		 */
1456		if (id->key != NULL) {
1457			if (try_identity(id)) {
1458				debug("Offering %s public key: %s",
1459				    key_type(id->key), id->filename);
1460				sent = send_pubkey_test(authctxt, id);
1461			}
1462		} else {
1463			debug("Trying private key: %s", id->filename);
1464			id->key = load_identity_file(id);
1465			if (id->key != NULL) {
1466				if (try_identity(id)) {
1467					id->isprivate = 1;
1468					sent = sign_and_send_pubkey(
1469					    authctxt, id);
1470				}
1471				key_free(id->key);
1472				id->key = NULL;
1473			}
1474		}
1475		if (sent)
1476			return (sent);
1477	}
1478	return (0);
1479}
1480
1481/*
1482 * Send userauth request message specifying keyboard-interactive method.
1483 */
1484int
1485userauth_kbdint(Authctxt *authctxt)
1486{
1487	static int attempt = 0;
1488
1489	if (attempt++ >= options.number_of_password_prompts)
1490		return 0;
1491	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1492	if (attempt > 1 && !authctxt->info_req_seen) {
1493		debug3("userauth_kbdint: disable: no info_req_seen");
1494		dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1495		return 0;
1496	}
1497
1498	debug2("userauth_kbdint");
1499	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1500	packet_put_cstring(authctxt->server_user);
1501	packet_put_cstring(authctxt->service);
1502	packet_put_cstring(authctxt->method->name);
1503	packet_put_cstring("");					/* lang */
1504	packet_put_cstring(options.kbd_interactive_devices ?
1505	    options.kbd_interactive_devices : "");
1506	packet_send();
1507
1508	dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1509	return 1;
1510}
1511
1512/*
1513 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1514 */
1515int
1516input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1517{
1518	Authctxt *authctxt = ctxt;
1519	char *name, *inst, *lang, *prompt, *response;
1520	u_int num_prompts, i;
1521	int echo = 0;
1522
1523	debug2("input_userauth_info_req");
1524
1525	if (authctxt == NULL)
1526		fatal("input_userauth_info_req: no authentication context");
1527
1528	authctxt->info_req_seen = 1;
1529
1530	name = packet_get_string(NULL);
1531	inst = packet_get_string(NULL);
1532	lang = packet_get_string(NULL);
1533	if (strlen(name) > 0)
1534		logit("%s", name);
1535	if (strlen(inst) > 0)
1536		logit("%s", inst);
1537	free(name);
1538	free(inst);
1539	free(lang);
1540
1541	num_prompts = packet_get_int();
1542	/*
1543	 * Begin to build info response packet based on prompts requested.
1544	 * We commit to providing the correct number of responses, so if
1545	 * further on we run into a problem that prevents this, we have to
1546	 * be sure and clean this up and send a correct error response.
1547	 */
1548	packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1549	packet_put_int(num_prompts);
1550
1551	debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1552	for (i = 0; i < num_prompts; i++) {
1553		prompt = packet_get_string(NULL);
1554		echo = packet_get_char();
1555
1556		response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1557
1558		packet_put_cstring(response);
1559		explicit_bzero(response, strlen(response));
1560		free(response);
1561		free(prompt);
1562	}
1563	packet_check_eom(); /* done with parsing incoming message. */
1564
1565	packet_add_padding(64);
1566	packet_send();
1567	return 0;
1568}
1569
1570static int
1571ssh_keysign(struct sshkey *key, u_char **sigp, size_t *lenp,
1572    const u_char *data, size_t datalen)
1573{
1574	struct sshbuf *b;
1575	struct stat st;
1576	pid_t pid;
1577	int i, r, to[2], from[2], status, sock = packet_get_connection_in();
1578	u_char rversion = 0, version = 2;
1579	void (*osigchld)(int);
1580
1581	*sigp = NULL;
1582	*lenp = 0;
1583
1584	if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1585		error("%s: not installed: %s", __func__, strerror(errno));
1586		return -1;
1587	}
1588	if (fflush(stdout) != 0) {
1589		error("%s: fflush: %s", __func__, strerror(errno));
1590		return -1;
1591	}
1592	if (pipe(to) < 0) {
1593		error("%s: pipe: %s", __func__, strerror(errno));
1594		return -1;
1595	}
1596	if (pipe(from) < 0) {
1597		error("%s: pipe: %s", __func__, strerror(errno));
1598		return -1;
1599	}
1600	if ((pid = fork()) < 0) {
1601		error("%s: fork: %s", __func__, strerror(errno));
1602		return -1;
1603	}
1604	osigchld = signal(SIGCHLD, SIG_DFL);
1605	if (pid == 0) {
1606		/* keep the socket on exec */
1607		fcntl(sock, F_SETFD, 0);
1608		permanently_drop_suid(getuid());
1609		close(from[0]);
1610		if (dup2(from[1], STDOUT_FILENO) < 0)
1611			fatal("%s: dup2: %s", __func__, strerror(errno));
1612		close(to[1]);
1613		if (dup2(to[0], STDIN_FILENO) < 0)
1614			fatal("%s: dup2: %s", __func__, strerror(errno));
1615		close(from[1]);
1616		close(to[0]);
1617		/* Close everything but stdio and the socket */
1618		for (i = STDERR_FILENO + 1; i < sock; i++)
1619			close(i);
1620		closefrom(sock + 1);
1621		debug3("%s: [child] pid=%ld, exec %s",
1622		    __func__, (long)getpid(), _PATH_SSH_KEY_SIGN);
1623		execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL);
1624		fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN,
1625		    strerror(errno));
1626	}
1627	close(from[1]);
1628	close(to[0]);
1629
1630	if ((b = sshbuf_new()) == NULL)
1631		fatal("%s: sshbuf_new failed", __func__);
1632	/* send # of sock, data to be signed */
1633	if ((r = sshbuf_put_u32(b, sock) != 0) ||
1634	    (r = sshbuf_put_string(b, data, datalen)) != 0)
1635		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1636	if (ssh_msg_send(to[1], version, b) == -1)
1637		fatal("%s: couldn't send request", __func__);
1638	sshbuf_reset(b);
1639	r = ssh_msg_recv(from[0], b);
1640	close(from[0]);
1641	close(to[1]);
1642	if (r < 0) {
1643		error("%s: no reply", __func__);
1644		goto fail;
1645	}
1646
1647	errno = 0;
1648	while (waitpid(pid, &status, 0) < 0) {
1649		if (errno != EINTR) {
1650			error("%s: waitpid %ld: %s",
1651			    __func__, (long)pid, strerror(errno));
1652			goto fail;
1653		}
1654	}
1655	if (!WIFEXITED(status)) {
1656		error("%s: exited abnormally", __func__);
1657		goto fail;
1658	}
1659	if (WEXITSTATUS(status) != 0) {
1660		error("%s: exited with status %d",
1661		    __func__, WEXITSTATUS(status));
1662		goto fail;
1663	}
1664	if ((r = sshbuf_get_u8(b, &rversion)) != 0) {
1665		error("%s: buffer error: %s", __func__, ssh_err(r));
1666		goto fail;
1667	}
1668	if (rversion != version) {
1669		error("%s: bad version", __func__);
1670		goto fail;
1671	}
1672	if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) {
1673		error("%s: buffer error: %s", __func__, ssh_err(r));
1674 fail:
1675		signal(SIGCHLD, osigchld);
1676		sshbuf_free(b);
1677		return -1;
1678	}
1679	signal(SIGCHLD, osigchld);
1680	sshbuf_free(b);
1681
1682	return 0;
1683}
1684
1685int
1686userauth_hostbased(Authctxt *authctxt)
1687{
1688	struct ssh *ssh = active_state;
1689	struct sshkey *private = NULL;
1690	struct sshbuf *b = NULL;
1691	const char *service;
1692	u_char *sig = NULL, *keyblob = NULL;
1693	char *fp = NULL, *chost = NULL, *lname = NULL;
1694	size_t siglen = 0, keylen = 0;
1695	int i, r, success = 0;
1696
1697	if (authctxt->ktypes == NULL) {
1698		authctxt->oktypes = xstrdup(options.hostbased_key_types);
1699		authctxt->ktypes = authctxt->oktypes;
1700	}
1701
1702	/*
1703	 * Work through each listed type pattern in HostbasedKeyTypes,
1704	 * trying each hostkey that matches the type in turn.
1705	 */
1706	for (;;) {
1707		if (authctxt->active_ktype == NULL)
1708			authctxt->active_ktype = strsep(&authctxt->ktypes, ",");
1709		if (authctxt->active_ktype == NULL ||
1710		    *authctxt->active_ktype == '\0')
1711			break;
1712		debug3("%s: trying key type %s", __func__,
1713		    authctxt->active_ktype);
1714
1715		/* check for a useful key */
1716		private = NULL;
1717		for (i = 0; i < authctxt->sensitive->nkeys; i++) {
1718			if (authctxt->sensitive->keys[i] == NULL ||
1719			    authctxt->sensitive->keys[i]->type == KEY_RSA1 ||
1720			    authctxt->sensitive->keys[i]->type == KEY_UNSPEC)
1721				continue;
1722			if (match_pattern_list(
1723			    sshkey_ssh_name(authctxt->sensitive->keys[i]),
1724			    authctxt->active_ktype, 0) != 1)
1725				continue;
1726			/* we take and free the key */
1727			private = authctxt->sensitive->keys[i];
1728			authctxt->sensitive->keys[i] = NULL;
1729			break;
1730		}
1731		/* Found one */
1732		if (private != NULL)
1733			break;
1734		/* No more keys of this type; advance */
1735		authctxt->active_ktype = NULL;
1736	}
1737	if (private == NULL) {
1738		free(authctxt->oktypes);
1739		authctxt->oktypes = authctxt->ktypes = NULL;
1740		authctxt->active_ktype = NULL;
1741		debug("No more client hostkeys for hostbased authentication.");
1742		goto out;
1743	}
1744
1745	if ((fp = sshkey_fingerprint(private, options.fingerprint_hash,
1746	    SSH_FP_DEFAULT)) == NULL) {
1747		error("%s: sshkey_fingerprint failed", __func__);
1748		goto out;
1749	}
1750	debug("%s: trying hostkey %s %s",
1751	    __func__, sshkey_ssh_name(private), fp);
1752
1753	/* figure out a name for the client host */
1754	if ((lname = get_local_name(packet_get_connection_in())) == NULL) {
1755		error("%s: cannot get local ipaddr/name", __func__);
1756		goto out;
1757	}
1758
1759	/* XXX sshbuf_put_stringf? */
1760	xasprintf(&chost, "%s.", lname);
1761	debug2("%s: chost %s", __func__, chost);
1762
1763	service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1764	    authctxt->service;
1765
1766	/* construct data */
1767	if ((b = sshbuf_new()) == NULL) {
1768		error("%s: sshbuf_new failed", __func__);
1769		goto out;
1770	}
1771	if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) {
1772		error("%s: sshkey_to_blob: %s", __func__, ssh_err(r));
1773		goto out;
1774	}
1775	if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
1776	    (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1777	    (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 ||
1778	    (r = sshbuf_put_cstring(b, service)) != 0 ||
1779	    (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 ||
1780	    (r = sshbuf_put_cstring(b, key_ssh_name(private))) != 0 ||
1781	    (r = sshbuf_put_string(b, keyblob, keylen)) != 0 ||
1782	    (r = sshbuf_put_cstring(b, chost)) != 0 ||
1783	    (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) {
1784		error("%s: buffer error: %s", __func__, ssh_err(r));
1785		goto out;
1786	}
1787
1788#ifdef DEBUG_PK
1789	sshbuf_dump(b, stderr);
1790#endif
1791	if (authctxt->sensitive->external_keysign)
1792		r = ssh_keysign(private, &sig, &siglen,
1793		    sshbuf_ptr(b), sshbuf_len(b));
1794	else if ((r = sshkey_sign(private, &sig, &siglen,
1795	    sshbuf_ptr(b), sshbuf_len(b), NULL, datafellows)) != 0)
1796		debug("%s: sshkey_sign: %s", __func__, ssh_err(r));
1797	if (r != 0) {
1798		error("sign using hostkey %s %s failed",
1799		    sshkey_ssh_name(private), fp);
1800		goto out;
1801	}
1802	if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
1803	    (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 ||
1804	    (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 ||
1805	    (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 ||
1806	    (r = sshpkt_put_cstring(ssh, key_ssh_name(private))) != 0 ||
1807	    (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 ||
1808	    (r = sshpkt_put_cstring(ssh, chost)) != 0 ||
1809	    (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 ||
1810	    (r = sshpkt_put_string(ssh, sig, siglen)) != 0 ||
1811	    (r = sshpkt_send(ssh)) != 0) {
1812		error("%s: packet error: %s", __func__, ssh_err(r));
1813		goto out;
1814	}
1815	success = 1;
1816
1817 out:
1818	if (sig != NULL) {
1819		explicit_bzero(sig, siglen);
1820		free(sig);
1821	}
1822	free(keyblob);
1823	free(lname);
1824	free(fp);
1825	free(chost);
1826	sshkey_free(private);
1827	sshbuf_free(b);
1828
1829	return success;
1830}
1831
1832/* find auth method */
1833
1834/*
1835 * given auth method name, if configurable options permit this method fill
1836 * in auth_ident field and return true, otherwise return false.
1837 */
1838static int
1839authmethod_is_enabled(Authmethod *method)
1840{
1841	if (method == NULL)
1842		return 0;
1843	/* return false if options indicate this method is disabled */
1844	if  (method->enabled == NULL || *method->enabled == 0)
1845		return 0;
1846	/* return false if batch mode is enabled but method needs interactive mode */
1847	if  (method->batch_flag != NULL && *method->batch_flag != 0)
1848		return 0;
1849	return 1;
1850}
1851
1852static Authmethod *
1853authmethod_lookup(const char *name)
1854{
1855	Authmethod *method = NULL;
1856	if (name != NULL)
1857		for (method = authmethods; method->name != NULL; method++)
1858			if (strcmp(name, method->name) == 0)
1859				return method;
1860	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1861	return NULL;
1862}
1863
1864/* XXX internal state */
1865static Authmethod *current = NULL;
1866static char *supported = NULL;
1867static char *preferred = NULL;
1868
1869/*
1870 * Given the authentication method list sent by the server, return the
1871 * next method we should try.  If the server initially sends a nil list,
1872 * use a built-in default list.
1873 */
1874static Authmethod *
1875authmethod_get(char *authlist)
1876{
1877	char *name = NULL;
1878	u_int next;
1879
1880	/* Use a suitable default if we're passed a nil list.  */
1881	if (authlist == NULL || strlen(authlist) == 0)
1882		authlist = options.preferred_authentications;
1883
1884	if (supported == NULL || strcmp(authlist, supported) != 0) {
1885		debug3("start over, passed a different list %s", authlist);
1886		free(supported);
1887		supported = xstrdup(authlist);
1888		preferred = options.preferred_authentications;
1889		debug3("preferred %s", preferred);
1890		current = NULL;
1891	} else if (current != NULL && authmethod_is_enabled(current))
1892		return current;
1893
1894	for (;;) {
1895		if ((name = match_list(preferred, supported, &next)) == NULL) {
1896			debug("No more authentication methods to try.");
1897			current = NULL;
1898			return NULL;
1899		}
1900		preferred += next;
1901		debug3("authmethod_lookup %s", name);
1902		debug3("remaining preferred: %s", preferred);
1903		if ((current = authmethod_lookup(name)) != NULL &&
1904		    authmethod_is_enabled(current)) {
1905			debug3("authmethod_is_enabled %s", name);
1906			debug("Next authentication method: %s", name);
1907			free(name);
1908			return current;
1909		}
1910		free(name);
1911	}
1912}
1913
1914static char *
1915authmethods_get(void)
1916{
1917	Authmethod *method = NULL;
1918	Buffer b;
1919	char *list;
1920
1921	buffer_init(&b);
1922	for (method = authmethods; method->name != NULL; method++) {
1923		if (authmethod_is_enabled(method)) {
1924			if (buffer_len(&b) > 0)
1925				buffer_append(&b, ",", 1);
1926			buffer_append(&b, method->name, strlen(method->name));
1927		}
1928	}
1929	buffer_append(&b, "\0", 1);
1930	list = xstrdup(buffer_ptr(&b));
1931	buffer_free(&b);
1932	return list;
1933}
1934
1935