sshconnect2.c revision 294328
1/* $OpenBSD: sshconnect2.c,v 1.210 2014/07/15 15:54:14 millert 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
74#ifdef GSSAPI
75#include "ssh-gss.h"
76#endif
77
78/* import */
79extern char *client_version_string;
80extern char *server_version_string;
81extern Options options;
82
83/*
84 * SSH2 key exchange
85 */
86
87u_char *session_id2 = NULL;
88u_int session_id2_len = 0;
89
90char *xxx_host;
91struct sockaddr *xxx_hostaddr;
92
93Kex *xxx_kex = NULL;
94
95static int
96verify_host_key_callback(Key *hostkey)
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 = key_type_from_name(alg)) == KEY_UNSPEC)
135			fatal("%s: unknown alg %s", __func__, alg);
136		if (lookup_key_in_hostkeys_by_type(hostkeys,
137		    key_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, *first == '\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	Kex *kex;
161
162	xxx_host = host;
163	xxx_hostaddr = hostaddr;
164
165	if (options.ciphers == (char *)-1) {
166		logit("No valid ciphers for protocol version 2 given, using defaults.");
167		options.ciphers = NULL;
168	}
169	if (options.ciphers != NULL) {
170		myproposal[PROPOSAL_ENC_ALGS_CTOS] =
171		myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
172	}
173	myproposal[PROPOSAL_ENC_ALGS_CTOS] =
174	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
175	myproposal[PROPOSAL_ENC_ALGS_STOC] =
176	    compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
177	if (options.compression) {
178		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
179		myproposal[PROPOSAL_COMP_ALGS_STOC] = "zlib@openssh.com,zlib,none";
180	} else {
181		myproposal[PROPOSAL_COMP_ALGS_CTOS] =
182		myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com,zlib";
183	}
184	if (options.macs != NULL) {
185		myproposal[PROPOSAL_MAC_ALGS_CTOS] =
186		myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
187	}
188	if (options.hostkeyalgorithms != NULL)
189		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
190		    compat_pkalg_proposal(options.hostkeyalgorithms);
191	else {
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	if (options.kex_algorithms != NULL)
198		myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
199	myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
200	    myproposal[PROPOSAL_KEX_ALGS]);
201
202	if (options.rekey_limit || options.rekey_interval)
203		packet_set_rekey_limits((u_int32_t)options.rekey_limit,
204		    (time_t)options.rekey_interval);
205
206	/* start key exchange */
207	kex = kex_setup(myproposal);
208#ifdef WITH_OPENSSL
209	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
210	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
211	kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
212	kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
213	kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
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	xxx_kex = kex;
221
222	dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
223
224	if (options.use_roaming && !kex->roaming) {
225		debug("Roaming not allowed by server");
226		options.use_roaming = 0;
227	}
228
229	session_id2 = kex->session_id;
230	session_id2_len = kex->session_id_len;
231
232#ifdef DEBUG_KEXDH
233	/* send 1st encrypted/maced/compressed message */
234	packet_start(SSH2_MSG_IGNORE);
235	packet_put_cstring("markus");
236	packet_send();
237	packet_write_wait();
238#endif
239}
240
241/*
242 * Authenticate user
243 */
244
245typedef struct Authctxt Authctxt;
246typedef struct Authmethod Authmethod;
247typedef struct identity Identity;
248typedef struct idlist Idlist;
249
250struct identity {
251	TAILQ_ENTRY(identity) next;
252	AuthenticationConnection *ac;	/* set if agent supports key */
253	Key	*key;			/* public/private key */
254	char	*filename;		/* comment for agent-only keys */
255	int	tried;
256	int	isprivate;		/* key points to the private key */
257	int	userprovided;
258};
259TAILQ_HEAD(idlist, identity);
260
261struct Authctxt {
262	const char *server_user;
263	const char *local_user;
264	const char *host;
265	const char *service;
266	Authmethod *method;
267	sig_atomic_t success;
268	char *authlist;
269	/* pubkey */
270	Idlist keys;
271	AuthenticationConnection *agent;
272	/* hostbased */
273	Sensitive *sensitive;
274	/* kbd-interactive */
275	int info_req_seen;
276	/* generic */
277	void *methoddata;
278};
279struct Authmethod {
280	char	*name;		/* string to compare against server's list */
281	int	(*userauth)(Authctxt *authctxt);
282	void	(*cleanup)(Authctxt *authctxt);
283	int	*enabled;	/* flag in option struct that enables method */
284	int	*batch_flag;	/* flag in option struct that disables method */
285};
286
287void	input_userauth_success(int, u_int32_t, void *);
288void	input_userauth_success_unexpected(int, u_int32_t, void *);
289void	input_userauth_failure(int, u_int32_t, void *);
290void	input_userauth_banner(int, u_int32_t, void *);
291void	input_userauth_error(int, u_int32_t, void *);
292void	input_userauth_info_req(int, u_int32_t, void *);
293void	input_userauth_pk_ok(int, u_int32_t, void *);
294void	input_userauth_passwd_changereq(int, u_int32_t, void *);
295
296int	userauth_none(Authctxt *);
297int	userauth_pubkey(Authctxt *);
298int	userauth_passwd(Authctxt *);
299int	userauth_kbdint(Authctxt *);
300int	userauth_hostbased(Authctxt *);
301
302#ifdef GSSAPI
303int	userauth_gssapi(Authctxt *authctxt);
304void	input_gssapi_response(int type, u_int32_t, void *);
305void	input_gssapi_token(int type, u_int32_t, void *);
306void	input_gssapi_hash(int type, u_int32_t, void *);
307void	input_gssapi_error(int, u_int32_t, void *);
308void	input_gssapi_errtok(int, u_int32_t, void *);
309#endif
310
311void	userauth(Authctxt *, char *);
312
313static int sign_and_send_pubkey(Authctxt *, Identity *);
314static void pubkey_prepare(Authctxt *);
315static void pubkey_cleanup(Authctxt *);
316static Key *load_identity_file(char *, int);
317
318static Authmethod *authmethod_get(char *authlist);
319static Authmethod *authmethod_lookup(const char *name);
320static char *authmethods_get(void);
321
322Authmethod authmethods[] = {
323#ifdef GSSAPI
324	{"gssapi-with-mic",
325		userauth_gssapi,
326		NULL,
327		&options.gss_authentication,
328		NULL},
329#endif
330	{"hostbased",
331		userauth_hostbased,
332		NULL,
333		&options.hostbased_authentication,
334		NULL},
335	{"publickey",
336		userauth_pubkey,
337		NULL,
338		&options.pubkey_authentication,
339		NULL},
340	{"keyboard-interactive",
341		userauth_kbdint,
342		NULL,
343		&options.kbd_interactive_authentication,
344		&options.batch_mode},
345	{"password",
346		userauth_passwd,
347		NULL,
348		&options.password_authentication,
349		&options.batch_mode},
350	{"none",
351		userauth_none,
352		NULL,
353		NULL,
354		NULL},
355	{NULL, NULL, NULL, NULL, NULL}
356};
357
358void
359ssh_userauth2(const char *local_user, const char *server_user, char *host,
360    Sensitive *sensitive)
361{
362	Authctxt authctxt;
363	int type;
364
365	if (options.challenge_response_authentication)
366		options.kbd_interactive_authentication = 1;
367
368	packet_start(SSH2_MSG_SERVICE_REQUEST);
369	packet_put_cstring("ssh-userauth");
370	packet_send();
371	debug("SSH2_MSG_SERVICE_REQUEST sent");
372	packet_write_wait();
373	type = packet_read();
374	if (type != SSH2_MSG_SERVICE_ACCEPT)
375		fatal("Server denied authentication request: %d", type);
376	if (packet_remaining() > 0) {
377		char *reply = packet_get_string(NULL);
378		debug2("service_accept: %s", reply);
379		free(reply);
380	} else {
381		debug2("buggy server: service_accept w/o service");
382	}
383	packet_check_eom();
384	debug("SSH2_MSG_SERVICE_ACCEPT received");
385
386	if (options.preferred_authentications == NULL)
387		options.preferred_authentications = authmethods_get();
388
389	/* setup authentication context */
390	memset(&authctxt, 0, sizeof(authctxt));
391	pubkey_prepare(&authctxt);
392	authctxt.server_user = server_user;
393	authctxt.local_user = local_user;
394	authctxt.host = host;
395	authctxt.service = "ssh-connection";		/* service name */
396	authctxt.success = 0;
397	authctxt.method = authmethod_lookup("none");
398	authctxt.authlist = NULL;
399	authctxt.methoddata = NULL;
400	authctxt.sensitive = sensitive;
401	authctxt.info_req_seen = 0;
402	if (authctxt.method == NULL)
403		fatal("ssh_userauth2: internal error: cannot send userauth none request");
404
405	/* initial userauth request */
406	userauth_none(&authctxt);
407
408	dispatch_init(&input_userauth_error);
409	dispatch_set(SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success);
410	dispatch_set(SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure);
411	dispatch_set(SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner);
412	dispatch_run(DISPATCH_BLOCK, &authctxt.success, &authctxt);	/* loop until success */
413
414	pubkey_cleanup(&authctxt);
415	dispatch_range(SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL);
416
417	debug("Authentication succeeded (%s).", authctxt.method->name);
418}
419
420void
421userauth(Authctxt *authctxt, char *authlist)
422{
423	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
424		authctxt->method->cleanup(authctxt);
425
426	free(authctxt->methoddata);
427	authctxt->methoddata = NULL;
428	if (authlist == NULL) {
429		authlist = authctxt->authlist;
430	} else {
431		free(authctxt->authlist);
432		authctxt->authlist = authlist;
433	}
434	for (;;) {
435		Authmethod *method = authmethod_get(authlist);
436		if (method == NULL)
437			fatal("Permission denied (%s).", authlist);
438		authctxt->method = method;
439
440		/* reset the per method handler */
441		dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN,
442		    SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL);
443
444		/* and try new method */
445		if (method->userauth(authctxt) != 0) {
446			debug2("we sent a %s packet, wait for reply", method->name);
447			break;
448		} else {
449			debug2("we did not send a packet, disable method");
450			method->enabled = NULL;
451		}
452	}
453}
454
455/* ARGSUSED */
456void
457input_userauth_error(int type, u_int32_t seq, void *ctxt)
458{
459	fatal("input_userauth_error: bad message during authentication: "
460	    "type %d", type);
461}
462
463/* ARGSUSED */
464void
465input_userauth_banner(int type, u_int32_t seq, void *ctxt)
466{
467	char *msg, *raw, *lang;
468	u_int len;
469
470	debug3("input_userauth_banner");
471	raw = packet_get_string(&len);
472	lang = packet_get_string(NULL);
473	if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) {
474		if (len > 65536)
475			len = 65536;
476		msg = xmalloc(len * 4 + 1); /* max expansion from strnvis() */
477		strnvis(msg, raw, len * 4 + 1, VIS_SAFE|VIS_OCTAL|VIS_NOSLASH);
478		fprintf(stderr, "%s", msg);
479		free(msg);
480	}
481	free(raw);
482	free(lang);
483}
484
485/* ARGSUSED */
486void
487input_userauth_success(int type, u_int32_t seq, void *ctxt)
488{
489	Authctxt *authctxt = ctxt;
490
491	if (authctxt == NULL)
492		fatal("input_userauth_success: no authentication context");
493	free(authctxt->authlist);
494	authctxt->authlist = NULL;
495	if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
496		authctxt->method->cleanup(authctxt);
497	free(authctxt->methoddata);
498	authctxt->methoddata = NULL;
499	authctxt->success = 1;			/* break out */
500}
501
502void
503input_userauth_success_unexpected(int type, u_int32_t seq, void *ctxt)
504{
505	Authctxt *authctxt = ctxt;
506
507	if (authctxt == NULL)
508		fatal("%s: no authentication context", __func__);
509
510	fatal("Unexpected authentication success during %s.",
511	    authctxt->method->name);
512}
513
514/* ARGSUSED */
515void
516input_userauth_failure(int type, u_int32_t seq, void *ctxt)
517{
518	Authctxt *authctxt = ctxt;
519	char *authlist = NULL;
520	int partial;
521
522	if (authctxt == NULL)
523		fatal("input_userauth_failure: no authentication context");
524
525	authlist = packet_get_string(NULL);
526	partial = packet_get_char();
527	packet_check_eom();
528
529	if (partial != 0) {
530		logit("Authenticated with partial success.");
531		/* reset state */
532		pubkey_cleanup(authctxt);
533		pubkey_prepare(authctxt);
534	}
535	debug("Authentications that can continue: %s", authlist);
536
537	userauth(authctxt, authlist);
538}
539
540/* ARGSUSED */
541void
542input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt)
543{
544	Authctxt *authctxt = ctxt;
545	Key *key = NULL;
546	Identity *id = NULL;
547	Buffer b;
548	int pktype, sent = 0;
549	u_int alen, blen;
550	char *pkalg, *fp;
551	u_char *pkblob;
552
553	if (authctxt == NULL)
554		fatal("input_userauth_pk_ok: no authentication context");
555	if (datafellows & SSH_BUG_PKOK) {
556		/* this is similar to SSH_BUG_PKAUTH */
557		debug2("input_userauth_pk_ok: SSH_BUG_PKOK");
558		pkblob = packet_get_string(&blen);
559		buffer_init(&b);
560		buffer_append(&b, pkblob, blen);
561		pkalg = buffer_get_string(&b, &alen);
562		buffer_free(&b);
563	} else {
564		pkalg = packet_get_string(&alen);
565		pkblob = packet_get_string(&blen);
566	}
567	packet_check_eom();
568
569	debug("Server accepts key: pkalg %s blen %u", pkalg, blen);
570
571	if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) {
572		debug("unknown pkalg %s", pkalg);
573		goto done;
574	}
575	if ((key = key_from_blob(pkblob, blen)) == NULL) {
576		debug("no key from blob. pkalg %s", pkalg);
577		goto done;
578	}
579	if (key->type != pktype) {
580		error("input_userauth_pk_ok: type mismatch "
581		    "for decoded key (received %d, expected %d)",
582		    key->type, pktype);
583		goto done;
584	}
585	fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
586	debug2("input_userauth_pk_ok: fp %s", fp);
587	free(fp);
588
589	/*
590	 * search keys in the reverse order, because last candidate has been
591	 * moved to the end of the queue.  this also avoids confusion by
592	 * duplicate keys
593	 */
594	TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) {
595		if (key_equal(key, id->key)) {
596			sent = sign_and_send_pubkey(authctxt, id);
597			break;
598		}
599	}
600done:
601	if (key != NULL)
602		key_free(key);
603	free(pkalg);
604	free(pkblob);
605
606	/* try another method if we did not send a packet */
607	if (sent == 0)
608		userauth(authctxt, NULL);
609}
610
611#ifdef GSSAPI
612int
613userauth_gssapi(Authctxt *authctxt)
614{
615	Gssctxt *gssctxt = NULL;
616	static gss_OID_set gss_supported = NULL;
617	static u_int mech = 0;
618	OM_uint32 min;
619	int ok = 0;
620
621	/* Try one GSSAPI method at a time, rather than sending them all at
622	 * once. */
623
624	if (gss_supported == NULL)
625		gss_indicate_mechs(&min, &gss_supported);
626
627	/* Check to see if the mechanism is usable before we offer it */
628	while (mech < gss_supported->count && !ok) {
629		/* My DER encoding requires length<128 */
630		if (gss_supported->elements[mech].length < 128 &&
631		    ssh_gssapi_check_mechanism(&gssctxt,
632		    &gss_supported->elements[mech], authctxt->host)) {
633			ok = 1; /* Mechanism works */
634		} else {
635			mech++;
636		}
637	}
638
639	if (!ok)
640		return 0;
641
642	authctxt->methoddata=(void *)gssctxt;
643
644	packet_start(SSH2_MSG_USERAUTH_REQUEST);
645	packet_put_cstring(authctxt->server_user);
646	packet_put_cstring(authctxt->service);
647	packet_put_cstring(authctxt->method->name);
648
649	packet_put_int(1);
650
651	packet_put_int((gss_supported->elements[mech].length) + 2);
652	packet_put_char(SSH_GSS_OIDTYPE);
653	packet_put_char(gss_supported->elements[mech].length);
654	packet_put_raw(gss_supported->elements[mech].elements,
655	    gss_supported->elements[mech].length);
656
657	packet_send();
658
659	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response);
660	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
661	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error);
662	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
663
664	mech++; /* Move along to next candidate */
665
666	return 1;
667}
668
669static OM_uint32
670process_gssapi_token(void *ctxt, gss_buffer_t recv_tok)
671{
672	Authctxt *authctxt = ctxt;
673	Gssctxt *gssctxt = authctxt->methoddata;
674	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
675	gss_buffer_desc mic = GSS_C_EMPTY_BUFFER;
676	gss_buffer_desc gssbuf;
677	OM_uint32 status, ms, flags;
678	Buffer b;
679
680	status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
681	    recv_tok, &send_tok, &flags);
682
683	if (send_tok.length > 0) {
684		if (GSS_ERROR(status))
685			packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK);
686		else
687			packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
688
689		packet_put_string(send_tok.value, send_tok.length);
690		packet_send();
691		gss_release_buffer(&ms, &send_tok);
692	}
693
694	if (status == GSS_S_COMPLETE) {
695		/* send either complete or MIC, depending on mechanism */
696		if (!(flags & GSS_C_INTEG_FLAG)) {
697			packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE);
698			packet_send();
699		} else {
700			ssh_gssapi_buildmic(&b, authctxt->server_user,
701			    authctxt->service, "gssapi-with-mic");
702
703			gssbuf.value = buffer_ptr(&b);
704			gssbuf.length = buffer_len(&b);
705
706			status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic);
707
708			if (!GSS_ERROR(status)) {
709				packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC);
710				packet_put_string(mic.value, mic.length);
711
712				packet_send();
713			}
714
715			buffer_free(&b);
716			gss_release_buffer(&ms, &mic);
717		}
718	}
719
720	return status;
721}
722
723/* ARGSUSED */
724void
725input_gssapi_response(int type, u_int32_t plen, void *ctxt)
726{
727	Authctxt *authctxt = ctxt;
728	Gssctxt *gssctxt;
729	int oidlen;
730	char *oidv;
731
732	if (authctxt == NULL)
733		fatal("input_gssapi_response: no authentication context");
734	gssctxt = authctxt->methoddata;
735
736	/* Setup our OID */
737	oidv = packet_get_string(&oidlen);
738
739	if (oidlen <= 2 ||
740	    oidv[0] != SSH_GSS_OIDTYPE ||
741	    oidv[1] != oidlen - 2) {
742		free(oidv);
743		debug("Badly encoded mechanism OID received");
744		userauth(authctxt, NULL);
745		return;
746	}
747
748	if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2))
749		fatal("Server returned different OID than expected");
750
751	packet_check_eom();
752
753	free(oidv);
754
755	if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) {
756		/* Start again with next method on list */
757		debug("Trying to start again");
758		userauth(authctxt, NULL);
759		return;
760	}
761}
762
763/* ARGSUSED */
764void
765input_gssapi_token(int type, u_int32_t plen, void *ctxt)
766{
767	Authctxt *authctxt = ctxt;
768	gss_buffer_desc recv_tok;
769	OM_uint32 status;
770	u_int slen;
771
772	if (authctxt == NULL)
773		fatal("input_gssapi_response: no authentication context");
774
775	recv_tok.value = packet_get_string(&slen);
776	recv_tok.length = slen;	/* safe typecast */
777
778	packet_check_eom();
779
780	status = process_gssapi_token(ctxt, &recv_tok);
781
782	free(recv_tok.value);
783
784	if (GSS_ERROR(status)) {
785		/* Start again with the next method in the list */
786		userauth(authctxt, NULL);
787		return;
788	}
789}
790
791/* ARGSUSED */
792void
793input_gssapi_errtok(int type, u_int32_t plen, void *ctxt)
794{
795	Authctxt *authctxt = ctxt;
796	Gssctxt *gssctxt;
797	gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER;
798	gss_buffer_desc recv_tok;
799	OM_uint32 ms;
800	u_int len;
801
802	if (authctxt == NULL)
803		fatal("input_gssapi_response: no authentication context");
804	gssctxt = authctxt->methoddata;
805
806	recv_tok.value = packet_get_string(&len);
807	recv_tok.length = len;
808
809	packet_check_eom();
810
811	/* Stick it into GSSAPI and see what it says */
812	(void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds,
813	    &recv_tok, &send_tok, NULL);
814
815	free(recv_tok.value);
816	gss_release_buffer(&ms, &send_tok);
817
818	/* Server will be returning a failed packet after this one */
819}
820
821/* ARGSUSED */
822void
823input_gssapi_error(int type, u_int32_t plen, void *ctxt)
824{
825	char *msg;
826	char *lang;
827
828	/* maj */(void)packet_get_int();
829	/* min */(void)packet_get_int();
830	msg=packet_get_string(NULL);
831	lang=packet_get_string(NULL);
832
833	packet_check_eom();
834
835	debug("Server GSSAPI Error:\n%s", msg);
836	free(msg);
837	free(lang);
838}
839#endif /* GSSAPI */
840
841int
842userauth_none(Authctxt *authctxt)
843{
844	/* initial userauth request */
845	packet_start(SSH2_MSG_USERAUTH_REQUEST);
846	packet_put_cstring(authctxt->server_user);
847	packet_put_cstring(authctxt->service);
848	packet_put_cstring(authctxt->method->name);
849	packet_send();
850	return 1;
851}
852
853int
854userauth_passwd(Authctxt *authctxt)
855{
856	static int attempt = 0;
857	char prompt[150];
858	char *password;
859	const char *host = options.host_key_alias ?  options.host_key_alias :
860	    authctxt->host;
861
862	if (attempt++ >= options.number_of_password_prompts)
863		return 0;
864
865	if (attempt != 1)
866		error("Permission denied, please try again.");
867
868	snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
869	    authctxt->server_user, host);
870	password = read_passphrase(prompt, 0);
871	packet_start(SSH2_MSG_USERAUTH_REQUEST);
872	packet_put_cstring(authctxt->server_user);
873	packet_put_cstring(authctxt->service);
874	packet_put_cstring(authctxt->method->name);
875	packet_put_char(0);
876	packet_put_cstring(password);
877	explicit_bzero(password, strlen(password));
878	free(password);
879	packet_add_padding(64);
880	packet_send();
881
882	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
883	    &input_userauth_passwd_changereq);
884
885	return 1;
886}
887
888/*
889 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST
890 */
891/* ARGSUSED */
892void
893input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt)
894{
895	Authctxt *authctxt = ctxt;
896	char *info, *lang, *password = NULL, *retype = NULL;
897	char prompt[150];
898	const char *host = options.host_key_alias ? options.host_key_alias :
899	    authctxt->host;
900
901	debug2("input_userauth_passwd_changereq");
902
903	if (authctxt == NULL)
904		fatal("input_userauth_passwd_changereq: "
905		    "no authentication context");
906
907	info = packet_get_string(NULL);
908	lang = packet_get_string(NULL);
909	if (strlen(info) > 0)
910		logit("%s", info);
911	free(info);
912	free(lang);
913	packet_start(SSH2_MSG_USERAUTH_REQUEST);
914	packet_put_cstring(authctxt->server_user);
915	packet_put_cstring(authctxt->service);
916	packet_put_cstring(authctxt->method->name);
917	packet_put_char(1);			/* additional info */
918	snprintf(prompt, sizeof(prompt),
919	    "Enter %.30s@%.128s's old password: ",
920	    authctxt->server_user, host);
921	password = read_passphrase(prompt, 0);
922	packet_put_cstring(password);
923	explicit_bzero(password, strlen(password));
924	free(password);
925	password = NULL;
926	while (password == NULL) {
927		snprintf(prompt, sizeof(prompt),
928		    "Enter %.30s@%.128s's new password: ",
929		    authctxt->server_user, host);
930		password = read_passphrase(prompt, RP_ALLOW_EOF);
931		if (password == NULL) {
932			/* bail out */
933			return;
934		}
935		snprintf(prompt, sizeof(prompt),
936		    "Retype %.30s@%.128s's new password: ",
937		    authctxt->server_user, host);
938		retype = read_passphrase(prompt, 0);
939		if (strcmp(password, retype) != 0) {
940			explicit_bzero(password, strlen(password));
941			free(password);
942			logit("Mismatch; try again, EOF to quit.");
943			password = NULL;
944		}
945		explicit_bzero(retype, strlen(retype));
946		free(retype);
947	}
948	packet_put_cstring(password);
949	explicit_bzero(password, strlen(password));
950	free(password);
951	packet_add_padding(64);
952	packet_send();
953
954	dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ,
955	    &input_userauth_passwd_changereq);
956}
957
958static int
959identity_sign(Identity *id, u_char **sigp, u_int *lenp,
960    u_char *data, u_int datalen)
961{
962	Key *prv;
963	int ret;
964
965	/* the agent supports this key */
966	if (id->ac)
967		return (ssh_agent_sign(id->ac, id->key, sigp, lenp,
968		    data, datalen));
969	/*
970	 * we have already loaded the private key or
971	 * the private key is stored in external hardware
972	 */
973	if (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))
974		return (key_sign(id->key, sigp, lenp, data, datalen));
975	/* load the private key from the file */
976	if ((prv = load_identity_file(id->filename, id->userprovided)) == NULL)
977		return (-1);
978	ret = key_sign(prv, sigp, lenp, data, datalen);
979	key_free(prv);
980	return (ret);
981}
982
983static int
984sign_and_send_pubkey(Authctxt *authctxt, Identity *id)
985{
986	Buffer b;
987	u_char *blob, *signature;
988	u_int bloblen, slen;
989	u_int skip = 0;
990	int ret = -1;
991	int have_sig = 1;
992	char *fp;
993
994	fp = key_fingerprint(id->key, SSH_FP_MD5, SSH_FP_HEX);
995	debug3("sign_and_send_pubkey: %s %s", key_type(id->key), fp);
996	free(fp);
997
998	if (key_to_blob(id->key, &blob, &bloblen) == 0) {
999		/* we cannot handle this key */
1000		debug3("sign_and_send_pubkey: cannot handle key");
1001		return 0;
1002	}
1003	/* data to be signed */
1004	buffer_init(&b);
1005	if (datafellows & SSH_OLD_SESSIONID) {
1006		buffer_append(&b, session_id2, session_id2_len);
1007		skip = session_id2_len;
1008	} else {
1009		buffer_put_string(&b, session_id2, session_id2_len);
1010		skip = buffer_len(&b);
1011	}
1012	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1013	buffer_put_cstring(&b, authctxt->server_user);
1014	buffer_put_cstring(&b,
1015	    datafellows & SSH_BUG_PKSERVICE ?
1016	    "ssh-userauth" :
1017	    authctxt->service);
1018	if (datafellows & SSH_BUG_PKAUTH) {
1019		buffer_put_char(&b, have_sig);
1020	} else {
1021		buffer_put_cstring(&b, authctxt->method->name);
1022		buffer_put_char(&b, have_sig);
1023		buffer_put_cstring(&b, key_ssh_name(id->key));
1024	}
1025	buffer_put_string(&b, blob, bloblen);
1026
1027	/* generate signature */
1028	ret = identity_sign(id, &signature, &slen,
1029	    buffer_ptr(&b), buffer_len(&b));
1030	if (ret == -1) {
1031		free(blob);
1032		buffer_free(&b);
1033		return 0;
1034	}
1035#ifdef DEBUG_PK
1036	buffer_dump(&b);
1037#endif
1038	if (datafellows & SSH_BUG_PKSERVICE) {
1039		buffer_clear(&b);
1040		buffer_append(&b, session_id2, session_id2_len);
1041		skip = session_id2_len;
1042		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1043		buffer_put_cstring(&b, authctxt->server_user);
1044		buffer_put_cstring(&b, authctxt->service);
1045		buffer_put_cstring(&b, authctxt->method->name);
1046		buffer_put_char(&b, have_sig);
1047		if (!(datafellows & SSH_BUG_PKAUTH))
1048			buffer_put_cstring(&b, key_ssh_name(id->key));
1049		buffer_put_string(&b, blob, bloblen);
1050	}
1051	free(blob);
1052
1053	/* append signature */
1054	buffer_put_string(&b, signature, slen);
1055	free(signature);
1056
1057	/* skip session id and packet type */
1058	if (buffer_len(&b) < skip + 1)
1059		fatal("userauth_pubkey: internal error");
1060	buffer_consume(&b, skip + 1);
1061
1062	/* put remaining data from buffer into packet */
1063	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1064	packet_put_raw(buffer_ptr(&b), buffer_len(&b));
1065	buffer_free(&b);
1066	packet_send();
1067
1068	return 1;
1069}
1070
1071static int
1072send_pubkey_test(Authctxt *authctxt, Identity *id)
1073{
1074	u_char *blob;
1075	u_int bloblen, have_sig = 0;
1076
1077	debug3("send_pubkey_test");
1078
1079	if (key_to_blob(id->key, &blob, &bloblen) == 0) {
1080		/* we cannot handle this key */
1081		debug3("send_pubkey_test: cannot handle key");
1082		return 0;
1083	}
1084	/* register callback for USERAUTH_PK_OK message */
1085	dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok);
1086
1087	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1088	packet_put_cstring(authctxt->server_user);
1089	packet_put_cstring(authctxt->service);
1090	packet_put_cstring(authctxt->method->name);
1091	packet_put_char(have_sig);
1092	if (!(datafellows & SSH_BUG_PKAUTH))
1093		packet_put_cstring(key_ssh_name(id->key));
1094	packet_put_string(blob, bloblen);
1095	free(blob);
1096	packet_send();
1097	return 1;
1098}
1099
1100static Key *
1101load_identity_file(char *filename, int userprovided)
1102{
1103	Key *private;
1104	char prompt[300], *passphrase;
1105	int perm_ok = 0, quit, i;
1106	struct stat st;
1107
1108	if (stat(filename, &st) < 0) {
1109		(userprovided ? logit : debug3)("no such identity: %s: %s",
1110		    filename, strerror(errno));
1111		return NULL;
1112	}
1113	private = key_load_private_type(KEY_UNSPEC, filename, "", NULL, &perm_ok);
1114	if (!perm_ok) {
1115		if (private != NULL)
1116			key_free(private);
1117		return NULL;
1118	}
1119	if (private == NULL) {
1120		if (options.batch_mode)
1121			return NULL;
1122		snprintf(prompt, sizeof prompt,
1123		    "Enter passphrase for key '%.100s': ", filename);
1124		for (i = 0; i < options.number_of_password_prompts; i++) {
1125			passphrase = read_passphrase(prompt, 0);
1126			if (strcmp(passphrase, "") != 0) {
1127				private = key_load_private_type(KEY_UNSPEC,
1128				    filename, passphrase, NULL, NULL);
1129				quit = 0;
1130			} else {
1131				debug2("no passphrase given, try next key");
1132				quit = 1;
1133			}
1134			explicit_bzero(passphrase, strlen(passphrase));
1135			free(passphrase);
1136			if (private != NULL || quit)
1137				break;
1138			debug2("bad passphrase given, try again...");
1139		}
1140	}
1141	return private;
1142}
1143
1144/*
1145 * try keys in the following order:
1146 *	1. agent keys that are found in the config file
1147 *	2. other agent keys
1148 *	3. keys that are only listed in the config file
1149 */
1150static void
1151pubkey_prepare(Authctxt *authctxt)
1152{
1153	Identity *id, *id2, *tmp;
1154	Idlist agent, files, *preferred;
1155	Key *key;
1156	AuthenticationConnection *ac;
1157	char *comment;
1158	int i, found;
1159
1160	TAILQ_INIT(&agent);	/* keys from the agent */
1161	TAILQ_INIT(&files);	/* keys from the config file */
1162	preferred = &authctxt->keys;
1163	TAILQ_INIT(preferred);	/* preferred order of keys */
1164
1165	/* list of keys stored in the filesystem and PKCS#11 */
1166	for (i = 0; i < options.num_identity_files; i++) {
1167		key = options.identity_keys[i];
1168		if (key && key->type == KEY_RSA1)
1169			continue;
1170		if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER)
1171			continue;
1172		options.identity_keys[i] = NULL;
1173		id = xcalloc(1, sizeof(*id));
1174		id->key = key;
1175		id->filename = xstrdup(options.identity_files[i]);
1176		id->userprovided = options.identity_file_userprovided[i];
1177		TAILQ_INSERT_TAIL(&files, id, next);
1178	}
1179	/* Prefer PKCS11 keys that are explicitly listed */
1180	TAILQ_FOREACH_SAFE(id, &files, next, tmp) {
1181		if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0)
1182			continue;
1183		found = 0;
1184		TAILQ_FOREACH(id2, &files, next) {
1185			if (id2->key == NULL ||
1186			    (id2->key->flags & SSHKEY_FLAG_EXT) == 0)
1187				continue;
1188			if (key_equal(id->key, id2->key)) {
1189				TAILQ_REMOVE(&files, id, next);
1190				TAILQ_INSERT_TAIL(preferred, id, next);
1191				found = 1;
1192				break;
1193			}
1194		}
1195		/* If IdentitiesOnly set and key not found then don't use it */
1196		if (!found && options.identities_only) {
1197			TAILQ_REMOVE(&files, id, next);
1198			explicit_bzero(id, sizeof(*id));
1199			free(id);
1200		}
1201	}
1202	/* list of keys supported by the agent */
1203	if ((ac = ssh_get_authentication_connection())) {
1204		for (key = ssh_get_first_identity(ac, &comment, 2);
1205		    key != NULL;
1206		    key = ssh_get_next_identity(ac, &comment, 2)) {
1207			found = 0;
1208			TAILQ_FOREACH(id, &files, next) {
1209				/* agent keys from the config file are preferred */
1210				if (key_equal(key, id->key)) {
1211					key_free(key);
1212					free(comment);
1213					TAILQ_REMOVE(&files, id, next);
1214					TAILQ_INSERT_TAIL(preferred, id, next);
1215					id->ac = ac;
1216					found = 1;
1217					break;
1218				}
1219			}
1220			if (!found && !options.identities_only) {
1221				id = xcalloc(1, sizeof(*id));
1222				id->key = key;
1223				id->filename = comment;
1224				id->ac = ac;
1225				TAILQ_INSERT_TAIL(&agent, id, next);
1226			}
1227		}
1228		/* append remaining agent keys */
1229		for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) {
1230			TAILQ_REMOVE(&agent, id, next);
1231			TAILQ_INSERT_TAIL(preferred, id, next);
1232		}
1233		authctxt->agent = ac;
1234	}
1235	/* append remaining keys from the config file */
1236	for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) {
1237		TAILQ_REMOVE(&files, id, next);
1238		TAILQ_INSERT_TAIL(preferred, id, next);
1239	}
1240	TAILQ_FOREACH(id, preferred, next) {
1241		debug2("key: %s (%p),%s", id->filename, id->key,
1242		    id->userprovided ? " explicit" : "");
1243	}
1244}
1245
1246static void
1247pubkey_cleanup(Authctxt *authctxt)
1248{
1249	Identity *id;
1250
1251	if (authctxt->agent != NULL)
1252		ssh_close_authentication_connection(authctxt->agent);
1253	for (id = TAILQ_FIRST(&authctxt->keys); id;
1254	    id = TAILQ_FIRST(&authctxt->keys)) {
1255		TAILQ_REMOVE(&authctxt->keys, id, next);
1256		if (id->key)
1257			key_free(id->key);
1258		free(id->filename);
1259		free(id);
1260	}
1261}
1262
1263int
1264userauth_pubkey(Authctxt *authctxt)
1265{
1266	Identity *id;
1267	int sent = 0;
1268
1269	while ((id = TAILQ_FIRST(&authctxt->keys))) {
1270		if (id->tried++)
1271			return (0);
1272		/* move key to the end of the queue */
1273		TAILQ_REMOVE(&authctxt->keys, id, next);
1274		TAILQ_INSERT_TAIL(&authctxt->keys, id, next);
1275		/*
1276		 * send a test message if we have the public key. for
1277		 * encrypted keys we cannot do this and have to load the
1278		 * private key instead
1279		 */
1280		if (id->key != NULL) {
1281			if (key_type_plain(id->key->type) == KEY_RSA &&
1282			    (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1283				debug("Skipped %s key %s for RSA/MD5 server",
1284				    key_type(id->key), id->filename);
1285			} else if (id->key->type != KEY_RSA1) {
1286				debug("Offering %s public key: %s",
1287				    key_type(id->key), id->filename);
1288				sent = send_pubkey_test(authctxt, id);
1289			}
1290		} else {
1291			debug("Trying private key: %s", id->filename);
1292			id->key = load_identity_file(id->filename,
1293			    id->userprovided);
1294			if (id->key != NULL) {
1295				id->isprivate = 1;
1296				if (key_type_plain(id->key->type) == KEY_RSA &&
1297				    (datafellows & SSH_BUG_RSASIGMD5) != 0) {
1298					debug("Skipped %s key %s for RSA/MD5 "
1299					    "server", key_type(id->key),
1300					    id->filename);
1301				} else {
1302					sent = sign_and_send_pubkey(
1303					    authctxt, id);
1304				}
1305				key_free(id->key);
1306				id->key = NULL;
1307			}
1308		}
1309		if (sent)
1310			return (sent);
1311	}
1312	return (0);
1313}
1314
1315/*
1316 * Send userauth request message specifying keyboard-interactive method.
1317 */
1318int
1319userauth_kbdint(Authctxt *authctxt)
1320{
1321	static int attempt = 0;
1322
1323	if (attempt++ >= options.number_of_password_prompts)
1324		return 0;
1325	/* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */
1326	if (attempt > 1 && !authctxt->info_req_seen) {
1327		debug3("userauth_kbdint: disable: no info_req_seen");
1328		dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL);
1329		return 0;
1330	}
1331
1332	debug2("userauth_kbdint");
1333	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1334	packet_put_cstring(authctxt->server_user);
1335	packet_put_cstring(authctxt->service);
1336	packet_put_cstring(authctxt->method->name);
1337	packet_put_cstring("");					/* lang */
1338	packet_put_cstring(options.kbd_interactive_devices ?
1339	    options.kbd_interactive_devices : "");
1340	packet_send();
1341
1342	dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req);
1343	return 1;
1344}
1345
1346/*
1347 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE
1348 */
1349void
1350input_userauth_info_req(int type, u_int32_t seq, void *ctxt)
1351{
1352	Authctxt *authctxt = ctxt;
1353	char *name, *inst, *lang, *prompt, *response;
1354	u_int num_prompts, i;
1355	int echo = 0;
1356
1357	debug2("input_userauth_info_req");
1358
1359	if (authctxt == NULL)
1360		fatal("input_userauth_info_req: no authentication context");
1361
1362	authctxt->info_req_seen = 1;
1363
1364	name = packet_get_string(NULL);
1365	inst = packet_get_string(NULL);
1366	lang = packet_get_string(NULL);
1367	if (strlen(name) > 0)
1368		logit("%s", name);
1369	if (strlen(inst) > 0)
1370		logit("%s", inst);
1371	free(name);
1372	free(inst);
1373	free(lang);
1374
1375	num_prompts = packet_get_int();
1376	/*
1377	 * Begin to build info response packet based on prompts requested.
1378	 * We commit to providing the correct number of responses, so if
1379	 * further on we run into a problem that prevents this, we have to
1380	 * be sure and clean this up and send a correct error response.
1381	 */
1382	packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE);
1383	packet_put_int(num_prompts);
1384
1385	debug2("input_userauth_info_req: num_prompts %d", num_prompts);
1386	for (i = 0; i < num_prompts; i++) {
1387		prompt = packet_get_string(NULL);
1388		echo = packet_get_char();
1389
1390		response = read_passphrase(prompt, echo ? RP_ECHO : 0);
1391
1392		packet_put_cstring(response);
1393		explicit_bzero(response, strlen(response));
1394		free(response);
1395		free(prompt);
1396	}
1397	packet_check_eom(); /* done with parsing incoming message. */
1398
1399	packet_add_padding(64);
1400	packet_send();
1401}
1402
1403static int
1404ssh_keysign(Key *key, u_char **sigp, u_int *lenp,
1405    u_char *data, u_int datalen)
1406{
1407	Buffer b;
1408	struct stat st;
1409	pid_t pid;
1410	int to[2], from[2], status, version = 2;
1411
1412	debug2("ssh_keysign called");
1413
1414	if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) {
1415		error("ssh_keysign: not installed: %s", strerror(errno));
1416		return -1;
1417	}
1418	if (fflush(stdout) != 0)
1419		error("ssh_keysign: fflush: %s", strerror(errno));
1420	if (pipe(to) < 0) {
1421		error("ssh_keysign: pipe: %s", strerror(errno));
1422		return -1;
1423	}
1424	if (pipe(from) < 0) {
1425		error("ssh_keysign: pipe: %s", strerror(errno));
1426		return -1;
1427	}
1428	if ((pid = fork()) < 0) {
1429		error("ssh_keysign: fork: %s", strerror(errno));
1430		return -1;
1431	}
1432	if (pid == 0) {
1433		/* keep the socket on exec */
1434		fcntl(packet_get_connection_in(), F_SETFD, 0);
1435		permanently_drop_suid(getuid());
1436		close(from[0]);
1437		if (dup2(from[1], STDOUT_FILENO) < 0)
1438			fatal("ssh_keysign: dup2: %s", strerror(errno));
1439		close(to[1]);
1440		if (dup2(to[0], STDIN_FILENO) < 0)
1441			fatal("ssh_keysign: dup2: %s", strerror(errno));
1442		close(from[1]);
1443		close(to[0]);
1444		execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *) 0);
1445		fatal("ssh_keysign: exec(%s): %s", _PATH_SSH_KEY_SIGN,
1446		    strerror(errno));
1447	}
1448	close(from[1]);
1449	close(to[0]);
1450
1451	buffer_init(&b);
1452	buffer_put_int(&b, packet_get_connection_in()); /* send # of socket */
1453	buffer_put_string(&b, data, datalen);
1454	if (ssh_msg_send(to[1], version, &b) == -1)
1455		fatal("ssh_keysign: couldn't send request");
1456
1457	if (ssh_msg_recv(from[0], &b) < 0) {
1458		error("ssh_keysign: no reply");
1459		buffer_free(&b);
1460		return -1;
1461	}
1462	close(from[0]);
1463	close(to[1]);
1464
1465	while (waitpid(pid, &status, 0) < 0)
1466		if (errno != EINTR)
1467			break;
1468
1469	if (buffer_get_char(&b) != version) {
1470		error("ssh_keysign: bad version");
1471		buffer_free(&b);
1472		return -1;
1473	}
1474	*sigp = buffer_get_string(&b, lenp);
1475	buffer_free(&b);
1476
1477	return 0;
1478}
1479
1480int
1481userauth_hostbased(Authctxt *authctxt)
1482{
1483	Key *private = NULL;
1484	Sensitive *sensitive = authctxt->sensitive;
1485	Buffer b;
1486	u_char *signature, *blob;
1487	char *chost, *pkalg, *p;
1488	const char *service;
1489	u_int blen, slen;
1490	int ok, i, found = 0;
1491
1492	/* check for a useful key */
1493	for (i = 0; i < sensitive->nkeys; i++) {
1494		private = sensitive->keys[i];
1495		if (private && private->type != KEY_RSA1) {
1496			found = 1;
1497			/* we take and free the key */
1498			sensitive->keys[i] = NULL;
1499			break;
1500		}
1501	}
1502	if (!found) {
1503		debug("No more client hostkeys for hostbased authentication.");
1504		return 0;
1505	}
1506	if (key_to_blob(private, &blob, &blen) == 0) {
1507		key_free(private);
1508		return 0;
1509	}
1510	/* figure out a name for the client host */
1511	p = get_local_name(packet_get_connection_in());
1512	if (p == NULL) {
1513		error("userauth_hostbased: cannot get local ipaddr/name");
1514		key_free(private);
1515		free(blob);
1516		return 0;
1517	}
1518	xasprintf(&chost, "%s.", p);
1519	debug2("userauth_hostbased: chost %s", chost);
1520	free(p);
1521
1522	service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" :
1523	    authctxt->service;
1524	pkalg = xstrdup(key_ssh_name(private));
1525	buffer_init(&b);
1526	/* construct data */
1527	buffer_put_string(&b, session_id2, session_id2_len);
1528	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
1529	buffer_put_cstring(&b, authctxt->server_user);
1530	buffer_put_cstring(&b, service);
1531	buffer_put_cstring(&b, authctxt->method->name);
1532	buffer_put_cstring(&b, pkalg);
1533	buffer_put_string(&b, blob, blen);
1534	buffer_put_cstring(&b, chost);
1535	buffer_put_cstring(&b, authctxt->local_user);
1536#ifdef DEBUG_PK
1537	buffer_dump(&b);
1538#endif
1539	if (sensitive->external_keysign)
1540		ok = ssh_keysign(private, &signature, &slen,
1541		    buffer_ptr(&b), buffer_len(&b));
1542	else
1543		ok = key_sign(private, &signature, &slen,
1544		    buffer_ptr(&b), buffer_len(&b));
1545	key_free(private);
1546	buffer_free(&b);
1547	if (ok != 0) {
1548		error("key_sign failed");
1549		free(chost);
1550		free(pkalg);
1551		free(blob);
1552		return 0;
1553	}
1554	packet_start(SSH2_MSG_USERAUTH_REQUEST);
1555	packet_put_cstring(authctxt->server_user);
1556	packet_put_cstring(authctxt->service);
1557	packet_put_cstring(authctxt->method->name);
1558	packet_put_cstring(pkalg);
1559	packet_put_string(blob, blen);
1560	packet_put_cstring(chost);
1561	packet_put_cstring(authctxt->local_user);
1562	packet_put_string(signature, slen);
1563	explicit_bzero(signature, slen);
1564	free(signature);
1565	free(chost);
1566	free(pkalg);
1567	free(blob);
1568
1569	packet_send();
1570	return 1;
1571}
1572
1573/* find auth method */
1574
1575/*
1576 * given auth method name, if configurable options permit this method fill
1577 * in auth_ident field and return true, otherwise return false.
1578 */
1579static int
1580authmethod_is_enabled(Authmethod *method)
1581{
1582	if (method == NULL)
1583		return 0;
1584	/* return false if options indicate this method is disabled */
1585	if  (method->enabled == NULL || *method->enabled == 0)
1586		return 0;
1587	/* return false if batch mode is enabled but method needs interactive mode */
1588	if  (method->batch_flag != NULL && *method->batch_flag != 0)
1589		return 0;
1590	return 1;
1591}
1592
1593static Authmethod *
1594authmethod_lookup(const char *name)
1595{
1596	Authmethod *method = NULL;
1597	if (name != NULL)
1598		for (method = authmethods; method->name != NULL; method++)
1599			if (strcmp(name, method->name) == 0)
1600				return method;
1601	debug2("Unrecognized authentication method name: %s", name ? name : "NULL");
1602	return NULL;
1603}
1604
1605/* XXX internal state */
1606static Authmethod *current = NULL;
1607static char *supported = NULL;
1608static char *preferred = NULL;
1609
1610/*
1611 * Given the authentication method list sent by the server, return the
1612 * next method we should try.  If the server initially sends a nil list,
1613 * use a built-in default list.
1614 */
1615static Authmethod *
1616authmethod_get(char *authlist)
1617{
1618	char *name = NULL;
1619	u_int next;
1620
1621	/* Use a suitable default if we're passed a nil list.  */
1622	if (authlist == NULL || strlen(authlist) == 0)
1623		authlist = options.preferred_authentications;
1624
1625	if (supported == NULL || strcmp(authlist, supported) != 0) {
1626		debug3("start over, passed a different list %s", authlist);
1627		free(supported);
1628		supported = xstrdup(authlist);
1629		preferred = options.preferred_authentications;
1630		debug3("preferred %s", preferred);
1631		current = NULL;
1632	} else if (current != NULL && authmethod_is_enabled(current))
1633		return current;
1634
1635	for (;;) {
1636		if ((name = match_list(preferred, supported, &next)) == NULL) {
1637			debug("No more authentication methods to try.");
1638			current = NULL;
1639			return NULL;
1640		}
1641		preferred += next;
1642		debug3("authmethod_lookup %s", name);
1643		debug3("remaining preferred: %s", preferred);
1644		if ((current = authmethod_lookup(name)) != NULL &&
1645		    authmethod_is_enabled(current)) {
1646			debug3("authmethod_is_enabled %s", name);
1647			debug("Next authentication method: %s", name);
1648			free(name);
1649			return current;
1650		}
1651		free(name);
1652	}
1653}
1654
1655static char *
1656authmethods_get(void)
1657{
1658	Authmethod *method = NULL;
1659	Buffer b;
1660	char *list;
1661
1662	buffer_init(&b);
1663	for (method = authmethods; method->name != NULL; method++) {
1664		if (authmethod_is_enabled(method)) {
1665			if (buffer_len(&b) > 0)
1666				buffer_append(&b, ",", 1);
1667			buffer_append(&b, method->name, strlen(method->name));
1668		}
1669	}
1670	buffer_append(&b, "\0", 1);
1671	list = xstrdup(buffer_ptr(&b));
1672	buffer_free(&b);
1673	return list;
1674}
1675
1676