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