sshconnect1.c revision 114426
1/*
2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 *                    All rights reserved
5 * Code to connect to a remote host, and to perform the client side of the
6 * login (authentication) dialog.
7 *
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose.  Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
13 */
14
15#include "includes.h"
16RCSID("$OpenBSD: sshconnect1.c,v 1.52 2002/08/08 13:50:23 aaron Exp $");
17
18#include <openssl/bn.h>
19#include <openssl/md5.h>
20
21#ifdef KRB4
22#include <krb.h>
23#endif
24#ifdef KRB5
25#include <krb5.h>
26#ifndef HEIMDAL
27#define krb5_get_err_text(context,code) error_message(code)
28#endif /* !HEIMDAL */
29#endif
30#ifdef AFS
31#include <kafs.h>
32#include "radix.h"
33#endif
34
35#include "ssh.h"
36#include "ssh1.h"
37#include "xmalloc.h"
38#include "rsa.h"
39#include "buffer.h"
40#include "packet.h"
41#include "mpaux.h"
42#include "uidswap.h"
43#include "log.h"
44#include "readconf.h"
45#include "key.h"
46#include "authfd.h"
47#include "sshconnect.h"
48#include "authfile.h"
49#include "readpass.h"
50#include "cipher.h"
51#include "canohost.h"
52#include "auth.h"
53
54/* Session id for the current session. */
55u_char session_id[16];
56u_int supported_authentications = 0;
57
58extern Options options;
59extern char *__progname;
60
61/*
62 * Checks if the user has an authentication agent, and if so, tries to
63 * authenticate using the agent.
64 */
65static int
66try_agent_authentication(void)
67{
68	int type;
69	char *comment;
70	AuthenticationConnection *auth;
71	u_char response[16];
72	u_int i;
73	Key *key;
74	BIGNUM *challenge;
75
76	/* Get connection to the agent. */
77	auth = ssh_get_authentication_connection();
78	if (!auth)
79		return 0;
80
81	if ((challenge = BN_new()) == NULL)
82		fatal("try_agent_authentication: BN_new failed");
83	/* Loop through identities served by the agent. */
84	for (key = ssh_get_first_identity(auth, &comment, 1);
85	    key != NULL;
86	    key = ssh_get_next_identity(auth, &comment, 1)) {
87
88		/* Try this identity. */
89		debug("Trying RSA authentication via agent with '%.100s'", comment);
90		xfree(comment);
91
92		/* Tell the server that we are willing to authenticate using this key. */
93		packet_start(SSH_CMSG_AUTH_RSA);
94		packet_put_bignum(key->rsa->n);
95		packet_send();
96		packet_write_wait();
97
98		/* Wait for server's response. */
99		type = packet_read();
100
101		/* The server sends failure if it doesn\'t like our key or
102		   does not support RSA authentication. */
103		if (type == SSH_SMSG_FAILURE) {
104			debug("Server refused our key.");
105			key_free(key);
106			continue;
107		}
108		/* Otherwise it should have sent a challenge. */
109		if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
110			packet_disconnect("Protocol error during RSA authentication: %d",
111					  type);
112
113		packet_get_bignum(challenge);
114		packet_check_eom();
115
116		debug("Received RSA challenge from server.");
117
118		/* Ask the agent to decrypt the challenge. */
119		if (!ssh_decrypt_challenge(auth, key, challenge, session_id, 1, response)) {
120			/*
121			 * The agent failed to authenticate this identifier
122			 * although it advertised it supports this.  Just
123			 * return a wrong value.
124			 */
125			log("Authentication agent failed to decrypt challenge.");
126			memset(response, 0, sizeof(response));
127		}
128		key_free(key);
129		debug("Sending response to RSA challenge.");
130
131		/* Send the decrypted challenge back to the server. */
132		packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
133		for (i = 0; i < 16; i++)
134			packet_put_char(response[i]);
135		packet_send();
136		packet_write_wait();
137
138		/* Wait for response from the server. */
139		type = packet_read();
140
141		/* The server returns success if it accepted the authentication. */
142		if (type == SSH_SMSG_SUCCESS) {
143			ssh_close_authentication_connection(auth);
144			BN_clear_free(challenge);
145			debug("RSA authentication accepted by server.");
146			return 1;
147		}
148		/* Otherwise it should return failure. */
149		if (type != SSH_SMSG_FAILURE)
150			packet_disconnect("Protocol error waiting RSA auth response: %d",
151					  type);
152	}
153	ssh_close_authentication_connection(auth);
154	BN_clear_free(challenge);
155	debug("RSA authentication using agent refused.");
156	return 0;
157}
158
159/*
160 * Computes the proper response to a RSA challenge, and sends the response to
161 * the server.
162 */
163static void
164respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
165{
166	u_char buf[32], response[16];
167	MD5_CTX md;
168	int i, len;
169
170	/* Decrypt the challenge using the private key. */
171	/* XXX think about Bleichenbacher, too */
172	if (rsa_private_decrypt(challenge, challenge, prv) <= 0)
173		packet_disconnect(
174		    "respond_to_rsa_challenge: rsa_private_decrypt failed");
175
176	/* Compute the response. */
177	/* The response is MD5 of decrypted challenge plus session id. */
178	len = BN_num_bytes(challenge);
179	if (len <= 0 || len > sizeof(buf))
180		packet_disconnect(
181		    "respond_to_rsa_challenge: bad challenge length %d", len);
182
183	memset(buf, 0, sizeof(buf));
184	BN_bn2bin(challenge, buf + sizeof(buf) - len);
185	MD5_Init(&md);
186	MD5_Update(&md, buf, 32);
187	MD5_Update(&md, session_id, 16);
188	MD5_Final(response, &md);
189
190	debug("Sending response to host key RSA challenge.");
191
192	/* Send the response back to the server. */
193	packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
194	for (i = 0; i < 16; i++)
195		packet_put_char(response[i]);
196	packet_send();
197	packet_write_wait();
198
199	memset(buf, 0, sizeof(buf));
200	memset(response, 0, sizeof(response));
201	memset(&md, 0, sizeof(md));
202}
203
204/*
205 * Checks if the user has authentication file, and if so, tries to authenticate
206 * the user using it.
207 */
208static int
209try_rsa_authentication(int idx)
210{
211	BIGNUM *challenge;
212	Key *public, *private;
213	char buf[300], *passphrase, *comment, *authfile;
214	int i, type, quit;
215
216	public = options.identity_keys[idx];
217	authfile = options.identity_files[idx];
218	comment = xstrdup(authfile);
219
220	debug("Trying RSA authentication with key '%.100s'", comment);
221
222	/* Tell the server that we are willing to authenticate using this key. */
223	packet_start(SSH_CMSG_AUTH_RSA);
224	packet_put_bignum(public->rsa->n);
225	packet_send();
226	packet_write_wait();
227
228	/* Wait for server's response. */
229	type = packet_read();
230
231	/*
232	 * The server responds with failure if it doesn\'t like our key or
233	 * doesn\'t support RSA authentication.
234	 */
235	if (type == SSH_SMSG_FAILURE) {
236		debug("Server refused our key.");
237		xfree(comment);
238		return 0;
239	}
240	/* Otherwise, the server should respond with a challenge. */
241	if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
242		packet_disconnect("Protocol error during RSA authentication: %d", type);
243
244	/* Get the challenge from the packet. */
245	if ((challenge = BN_new()) == NULL)
246		fatal("try_rsa_authentication: BN_new failed");
247	packet_get_bignum(challenge);
248	packet_check_eom();
249
250	debug("Received RSA challenge from server.");
251
252	/*
253	 * If the key is not stored in external hardware, we have to
254	 * load the private key.  Try first with empty passphrase; if it
255	 * fails, ask for a passphrase.
256	 */
257	if (public->flags & KEY_FLAG_EXT)
258		private = public;
259	else
260		private = key_load_private_type(KEY_RSA1, authfile, "", NULL);
261	if (private == NULL && !options.batch_mode) {
262		snprintf(buf, sizeof(buf),
263		    "Enter passphrase for RSA key '%.100s': ", comment);
264		for (i = 0; i < options.number_of_password_prompts; i++) {
265			passphrase = read_passphrase(buf, 0);
266			if (strcmp(passphrase, "") != 0) {
267				private = key_load_private_type(KEY_RSA1,
268				    authfile, passphrase, NULL);
269				quit = 0;
270			} else {
271				debug2("no passphrase given, try next key");
272				quit = 1;
273			}
274			memset(passphrase, 0, strlen(passphrase));
275			xfree(passphrase);
276			if (private != NULL || quit)
277				break;
278			debug2("bad passphrase given, try again...");
279		}
280	}
281	/* We no longer need the comment. */
282	xfree(comment);
283
284	if (private == NULL) {
285		if (!options.batch_mode)
286			error("Bad passphrase.");
287
288		/* Send a dummy response packet to avoid protocol error. */
289		packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
290		for (i = 0; i < 16; i++)
291			packet_put_char(0);
292		packet_send();
293		packet_write_wait();
294
295		/* Expect the server to reject it... */
296		packet_read_expect(SSH_SMSG_FAILURE);
297		BN_clear_free(challenge);
298		return 0;
299	}
300
301	/* Compute and send a response to the challenge. */
302	respond_to_rsa_challenge(challenge, private->rsa);
303
304	/* Destroy the private key unless it in external hardware. */
305	if (!(private->flags & KEY_FLAG_EXT))
306		key_free(private);
307
308	/* We no longer need the challenge. */
309	BN_clear_free(challenge);
310
311	/* Wait for response from the server. */
312	type = packet_read();
313	if (type == SSH_SMSG_SUCCESS) {
314		debug("RSA authentication accepted by server.");
315		return 1;
316	}
317	if (type != SSH_SMSG_FAILURE)
318		packet_disconnect("Protocol error waiting RSA auth response: %d", type);
319	debug("RSA authentication refused.");
320	return 0;
321}
322
323/*
324 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
325 * authentication and RSA host authentication.
326 */
327static int
328try_rhosts_rsa_authentication(const char *local_user, Key * host_key)
329{
330	int type;
331	BIGNUM *challenge;
332
333	debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
334
335	/* Tell the server that we are willing to authenticate using this key. */
336	packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
337	packet_put_cstring(local_user);
338	packet_put_int(BN_num_bits(host_key->rsa->n));
339	packet_put_bignum(host_key->rsa->e);
340	packet_put_bignum(host_key->rsa->n);
341	packet_send();
342	packet_write_wait();
343
344	/* Wait for server's response. */
345	type = packet_read();
346
347	/* The server responds with failure if it doesn't admit our
348	   .rhosts authentication or doesn't know our host key. */
349	if (type == SSH_SMSG_FAILURE) {
350		debug("Server refused our rhosts authentication or host key.");
351		return 0;
352	}
353	/* Otherwise, the server should respond with a challenge. */
354	if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
355		packet_disconnect("Protocol error during RSA authentication: %d", type);
356
357	/* Get the challenge from the packet. */
358	if ((challenge = BN_new()) == NULL)
359		fatal("try_rhosts_rsa_authentication: BN_new failed");
360	packet_get_bignum(challenge);
361	packet_check_eom();
362
363	debug("Received RSA challenge for host key from server.");
364
365	/* Compute a response to the challenge. */
366	respond_to_rsa_challenge(challenge, host_key->rsa);
367
368	/* We no longer need the challenge. */
369	BN_clear_free(challenge);
370
371	/* Wait for response from the server. */
372	type = packet_read();
373	if (type == SSH_SMSG_SUCCESS) {
374		debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
375		return 1;
376	}
377	if (type != SSH_SMSG_FAILURE)
378		packet_disconnect("Protocol error waiting RSA auth response: %d", type);
379	debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
380	return 0;
381}
382
383#ifdef KRB4
384static int
385try_krb4_authentication(void)
386{
387	KTEXT_ST auth;		/* Kerberos data */
388	char *reply;
389	char inst[INST_SZ];
390	char *realm;
391	CREDENTIALS cred;
392	int r, type;
393	socklen_t slen;
394	Key_schedule schedule;
395	u_long checksum, cksum;
396	MSG_DAT msg_data;
397	struct sockaddr_in local, foreign;
398	struct stat st;
399
400	/* Don't do anything if we don't have any tickets. */
401	if (stat(tkt_string(), &st) < 0)
402		return 0;
403
404	strlcpy(inst, (char *)krb_get_phost(get_canonical_hostname(1)),
405	    INST_SZ);
406
407	realm = (char *)krb_realmofhost(get_canonical_hostname(1));
408	if (!realm) {
409		debug("Kerberos v4: no realm for %s", get_canonical_hostname(1));
410		return 0;
411	}
412	/* This can really be anything. */
413	checksum = (u_long)getpid();
414
415	r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
416	if (r != KSUCCESS) {
417		debug("Kerberos v4 krb_mk_req failed: %s", krb_err_txt[r]);
418		return 0;
419	}
420	/* Get session key to decrypt the server's reply with. */
421	r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
422	if (r != KSUCCESS) {
423		debug("get_cred failed: %s", krb_err_txt[r]);
424		return 0;
425	}
426	des_key_sched((des_cblock *) cred.session, schedule);
427
428	/* Send authentication info to server. */
429	packet_start(SSH_CMSG_AUTH_KERBEROS);
430	packet_put_string((char *) auth.dat, auth.length);
431	packet_send();
432	packet_write_wait();
433
434	/* Zero the buffer. */
435	(void) memset(auth.dat, 0, MAX_KTXT_LEN);
436
437	slen = sizeof(local);
438	memset(&local, 0, sizeof(local));
439	if (getsockname(packet_get_connection_in(),
440	    (struct sockaddr *)&local, &slen) < 0)
441		debug("getsockname failed: %s", strerror(errno));
442
443	slen = sizeof(foreign);
444	memset(&foreign, 0, sizeof(foreign));
445	if (getpeername(packet_get_connection_in(),
446	    (struct sockaddr *)&foreign, &slen) < 0) {
447		debug("getpeername failed: %s", strerror(errno));
448		fatal_cleanup();
449	}
450	/* Get server reply. */
451	type = packet_read();
452	switch (type) {
453	case SSH_SMSG_FAILURE:
454		/* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
455		debug("Kerberos v4 authentication failed.");
456		return 0;
457		break;
458
459	case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
460		/* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
461		debug("Kerberos v4 authentication accepted.");
462
463		/* Get server's response. */
464		reply = packet_get_string((u_int *) &auth.length);
465		if (auth.length >= MAX_KTXT_LEN)
466			fatal("Kerberos v4: Malformed response from server");
467		memcpy(auth.dat, reply, auth.length);
468		xfree(reply);
469
470		packet_check_eom();
471
472		/*
473		 * If his response isn't properly encrypted with the session
474		 * key, and the decrypted checksum fails to match, he's
475		 * bogus. Bail out.
476		 */
477		r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
478		    &foreign, &local, &msg_data);
479		if (r != KSUCCESS) {
480			debug("Kerberos v4 krb_rd_priv failed: %s",
481			    krb_err_txt[r]);
482			packet_disconnect("Kerberos v4 challenge failed!");
483		}
484		/* Fetch the (incremented) checksum that we supplied in the request. */
485		memcpy((char *)&cksum, (char *)msg_data.app_data,
486		    sizeof(cksum));
487		cksum = ntohl(cksum);
488
489		/* If it matches, we're golden. */
490		if (cksum == checksum + 1) {
491			debug("Kerberos v4 challenge successful.");
492			return 1;
493		} else
494			packet_disconnect("Kerberos v4 challenge failed!");
495		break;
496
497	default:
498		packet_disconnect("Protocol error on Kerberos v4 response: %d", type);
499	}
500	return 0;
501}
502
503#endif /* KRB4 */
504
505#ifdef KRB5
506static int
507try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context)
508{
509	krb5_error_code problem;
510	const char *tkfile;
511	struct stat buf;
512	krb5_ccache ccache = NULL;
513	const char *remotehost;
514	krb5_data ap;
515	int type;
516	krb5_ap_rep_enc_part *reply = NULL;
517	int ret;
518
519	memset(&ap, 0, sizeof(ap));
520
521	problem = krb5_init_context(context);
522	if (problem) {
523		debug("Kerberos v5: krb5_init_context failed");
524		ret = 0;
525		goto out;
526	}
527
528	problem = krb5_auth_con_init(*context, auth_context);
529	if (problem) {
530		debug("Kerberos v5: krb5_auth_con_init failed");
531		ret = 0;
532		goto out;
533	}
534
535#ifndef HEIMDAL
536	problem = krb5_auth_con_setflags(*context, *auth_context,
537					 KRB5_AUTH_CONTEXT_RET_TIME);
538	if (problem) {
539		debug("Keberos v5: krb5_auth_con_setflags failed");
540		ret = 0;
541		goto out;
542	}
543#endif
544
545	tkfile = krb5_cc_default_name(*context);
546	if (strncmp(tkfile, "FILE:", 5) == 0)
547		tkfile += 5;
548
549	if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
550		debug("Kerberos v5: could not get default ccache (permission denied).");
551		ret = 0;
552		goto out;
553	}
554
555	problem = krb5_cc_default(*context, &ccache);
556	if (problem) {
557		debug("Kerberos v5: krb5_cc_default failed: %s",
558		    krb5_get_err_text(*context, problem));
559		ret = 0;
560		goto out;
561	}
562
563	remotehost = get_canonical_hostname(1);
564
565	problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
566	    "host", remotehost, NULL, ccache, &ap);
567	if (problem) {
568		debug("Kerberos v5: krb5_mk_req failed: %s",
569		    krb5_get_err_text(*context, problem));
570		ret = 0;
571		goto out;
572	}
573
574	packet_start(SSH_CMSG_AUTH_KERBEROS);
575	packet_put_string((char *) ap.data, ap.length);
576	packet_send();
577	packet_write_wait();
578
579	xfree(ap.data);
580	ap.length = 0;
581
582	type = packet_read();
583	switch (type) {
584	case SSH_SMSG_FAILURE:
585		/* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
586		debug("Kerberos v5 authentication failed.");
587		ret = 0;
588		break;
589
590	case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
591		/* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
592		debug("Kerberos v5 authentication accepted.");
593
594		/* Get server's response. */
595		ap.data = packet_get_string((unsigned int *) &ap.length);
596		packet_check_eom();
597		/* XXX je to dobre? */
598
599		problem = krb5_rd_rep(*context, *auth_context, &ap, &reply);
600		if (problem) {
601			ret = 0;
602		}
603		ret = 1;
604		break;
605
606	default:
607		packet_disconnect("Protocol error on Kerberos v5 response: %d",
608		    type);
609		ret = 0;
610		break;
611
612	}
613
614 out:
615	if (ccache != NULL)
616		krb5_cc_close(*context, ccache);
617	if (reply != NULL)
618		krb5_free_ap_rep_enc_part(*context, reply);
619	if (ap.length > 0)
620#ifdef HEIMDAL
621		krb5_data_free(&ap);
622#else
623		krb5_free_data_contents(*context, &ap);
624#endif
625
626	return (ret);
627}
628
629static void
630send_krb5_tgt(krb5_context context, krb5_auth_context auth_context)
631{
632	int fd, type;
633	krb5_error_code problem;
634	krb5_data outbuf;
635	krb5_ccache ccache = NULL;
636	krb5_creds creds;
637#ifdef HEIMDAL
638	krb5_kdc_flags flags;
639#else
640	int forwardable;
641#endif
642	const char *remotehost;
643
644	memset(&creds, 0, sizeof(creds));
645	memset(&outbuf, 0, sizeof(outbuf));
646
647	fd = packet_get_connection_in();
648
649#ifdef HEIMDAL
650	problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd);
651#else
652	problem = krb5_auth_con_genaddrs(context, auth_context, fd,
653			KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR |
654			KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR);
655#endif
656	if (problem)
657		goto out;
658
659	problem = krb5_cc_default(context, &ccache);
660	if (problem)
661		goto out;
662
663	problem = krb5_cc_get_principal(context, ccache, &creds.client);
664	if (problem)
665		goto out;
666
667	remotehost = get_canonical_hostname(1);
668
669#ifdef HEIMDAL
670	problem = krb5_build_principal(context, &creds.server,
671	    strlen(creds.client->realm), creds.client->realm,
672	    "krbtgt", creds.client->realm, NULL);
673#else
674	problem = krb5_build_principal(context, &creds.server,
675	    creds.client->realm.length, creds.client->realm.data,
676	    "host", remotehost, NULL);
677#endif
678	if (problem)
679		goto out;
680
681	creds.times.endtime = 0;
682
683#ifdef HEIMDAL
684	flags.i = 0;
685	flags.b.forwarded = 1;
686	flags.b.forwardable = krb5_config_get_bool(context,  NULL,
687	    "libdefaults", "forwardable", NULL);
688	problem = krb5_get_forwarded_creds(context, auth_context,
689	    ccache, flags.i, remotehost, &creds, &outbuf);
690#else
691	forwardable = 1;
692	problem = krb5_fwd_tgt_creds(context, auth_context, remotehost,
693	    creds.client, creds.server, ccache, forwardable, &outbuf);
694#endif
695
696	if (problem)
697		goto out;
698
699	packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
700	packet_put_string((char *)outbuf.data, outbuf.length);
701	packet_send();
702	packet_write_wait();
703
704	type = packet_read();
705
706	if (type == SSH_SMSG_SUCCESS) {
707		char *pname;
708
709		krb5_unparse_name(context, creds.client, &pname);
710		debug("Kerberos v5 TGT forwarded (%s).", pname);
711		xfree(pname);
712	} else
713		debug("Kerberos v5 TGT forwarding failed.");
714
715	return;
716
717 out:
718	if (problem)
719		debug("Kerberos v5 TGT forwarding failed: %s",
720		    krb5_get_err_text(context, problem));
721	if (creds.client)
722		krb5_free_principal(context, creds.client);
723	if (creds.server)
724		krb5_free_principal(context, creds.server);
725	if (ccache)
726		krb5_cc_close(context, ccache);
727	if (outbuf.data)
728		xfree(outbuf.data);
729}
730#endif /* KRB5 */
731
732#ifdef AFS
733static void
734send_krb4_tgt(void)
735{
736	CREDENTIALS *creds;
737	struct stat st;
738	char buffer[4096], pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
739	int problem, type;
740
741	/* Don't do anything if we don't have any tickets. */
742	if (stat(tkt_string(), &st) < 0)
743		return;
744
745	creds = xmalloc(sizeof(*creds));
746
747	problem = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm);
748	if (problem)
749		goto out;
750
751	problem = krb_get_cred("krbtgt", prealm, prealm, creds);
752	if (problem)
753		goto out;
754
755	if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
756		problem = RD_AP_EXP;
757		goto out;
758	}
759	creds_to_radix(creds, (u_char *)buffer, sizeof(buffer));
760
761	packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
762	packet_put_cstring(buffer);
763	packet_send();
764	packet_write_wait();
765
766	type = packet_read();
767
768	if (type == SSH_SMSG_SUCCESS)
769		debug("Kerberos v4 TGT forwarded (%s%s%s@%s).",
770		    creds->pname, creds->pinst[0] ? "." : "",
771		    creds->pinst, creds->realm);
772	else
773		debug("Kerberos v4 TGT rejected.");
774
775	xfree(creds);
776	return;
777
778 out:
779	debug("Kerberos v4 TGT passing failed: %s", krb_err_txt[problem]);
780	xfree(creds);
781}
782
783static void
784send_afs_tokens(void)
785{
786	CREDENTIALS creds;
787	struct ViceIoctl parms;
788	struct ClearToken ct;
789	int i, type, len;
790	char buf[2048], *p, *server_cell;
791	char buffer[8192];
792
793	/* Move over ktc_GetToken, here's something leaner. */
794	for (i = 0; i < 100; i++) {	/* just in case */
795		parms.in = (char *) &i;
796		parms.in_size = sizeof(i);
797		parms.out = buf;
798		parms.out_size = sizeof(buf);
799		if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
800			break;
801		p = buf;
802
803		/* Get secret token. */
804		memcpy(&creds.ticket_st.length, p, sizeof(u_int));
805		if (creds.ticket_st.length > MAX_KTXT_LEN)
806			break;
807		p += sizeof(u_int);
808		memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
809		p += creds.ticket_st.length;
810
811		/* Get clear token. */
812		memcpy(&len, p, sizeof(len));
813		if (len != sizeof(struct ClearToken))
814			break;
815		p += sizeof(len);
816		memcpy(&ct, p, len);
817		p += len;
818		p += sizeof(len);	/* primary flag */
819		server_cell = p;
820
821		/* Flesh out our credentials. */
822		strlcpy(creds.service, "afs", sizeof(creds.service));
823		creds.instance[0] = '\0';
824		strlcpy(creds.realm, server_cell, REALM_SZ);
825		memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
826		creds.issue_date = ct.BeginTimestamp;
827		creds.lifetime = krb_time_to_life(creds.issue_date,
828		    ct.EndTimestamp);
829		creds.kvno = ct.AuthHandle;
830		snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
831		creds.pinst[0] = '\0';
832
833		/* Encode token, ship it off. */
834		if (creds_to_radix(&creds, (u_char *)buffer,
835		    sizeof(buffer)) <= 0)
836			break;
837		packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
838		packet_put_cstring(buffer);
839		packet_send();
840		packet_write_wait();
841
842		/* Roger, Roger. Clearance, Clarence. What's your vector,
843		   Victor? */
844		type = packet_read();
845
846		if (type == SSH_SMSG_FAILURE)
847			debug("AFS token for cell %s rejected.", server_cell);
848		else if (type != SSH_SMSG_SUCCESS)
849			packet_disconnect("Protocol error on AFS token response: %d", type);
850	}
851}
852
853#endif /* AFS */
854
855/*
856 * Tries to authenticate with any string-based challenge/response system.
857 * Note that the client code is not tied to s/key or TIS.
858 */
859static int
860try_challenge_response_authentication(void)
861{
862	int type, i;
863	u_int clen;
864	char prompt[1024];
865	char *challenge, *response;
866
867	debug("Doing challenge response authentication.");
868
869	for (i = 0; i < options.number_of_password_prompts; i++) {
870		/* request a challenge */
871		packet_start(SSH_CMSG_AUTH_TIS);
872		packet_send();
873		packet_write_wait();
874
875		type = packet_read();
876		if (type != SSH_SMSG_FAILURE &&
877		    type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
878			packet_disconnect("Protocol error: got %d in response "
879			    "to SSH_CMSG_AUTH_TIS", type);
880		}
881		if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
882			debug("No challenge.");
883			return 0;
884		}
885		challenge = packet_get_string(&clen);
886		packet_check_eom();
887		snprintf(prompt, sizeof prompt, "%s%s", challenge,
888		    strchr(challenge, '\n') ? "" : "\nResponse: ");
889		xfree(challenge);
890		if (i != 0)
891			error("Permission denied, please try again.");
892		if (options.cipher == SSH_CIPHER_NONE)
893			log("WARNING: Encryption is disabled! "
894			    "Response will be transmitted in clear text.");
895		response = read_passphrase(prompt, 0);
896		if (strcmp(response, "") == 0) {
897			xfree(response);
898			break;
899		}
900		packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
901		ssh_put_password(response);
902		memset(response, 0, strlen(response));
903		xfree(response);
904		packet_send();
905		packet_write_wait();
906		type = packet_read();
907		if (type == SSH_SMSG_SUCCESS)
908			return 1;
909		if (type != SSH_SMSG_FAILURE)
910			packet_disconnect("Protocol error: got %d in response "
911			    "to SSH_CMSG_AUTH_TIS_RESPONSE", type);
912	}
913	/* failure */
914	return 0;
915}
916
917/*
918 * Tries to authenticate with plain passwd authentication.
919 */
920static int
921try_password_authentication(char *prompt)
922{
923	int type, i;
924	char *password;
925
926	debug("Doing password authentication.");
927	if (options.cipher == SSH_CIPHER_NONE)
928		log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
929	for (i = 0; i < options.number_of_password_prompts; i++) {
930		if (i != 0)
931			error("Permission denied, please try again.");
932		password = read_passphrase(prompt, 0);
933		packet_start(SSH_CMSG_AUTH_PASSWORD);
934		ssh_put_password(password);
935		memset(password, 0, strlen(password));
936		xfree(password);
937		packet_send();
938		packet_write_wait();
939
940		type = packet_read();
941		if (type == SSH_SMSG_SUCCESS)
942			return 1;
943		if (type != SSH_SMSG_FAILURE)
944			packet_disconnect("Protocol error: got %d in response to passwd auth", type);
945	}
946	/* failure */
947	return 0;
948}
949
950/*
951 * SSH1 key exchange
952 */
953void
954ssh_kex(char *host, struct sockaddr *hostaddr)
955{
956	int i;
957	BIGNUM *key;
958	Key *host_key, *server_key;
959	int bits, rbits;
960	int ssh_cipher_default = SSH_CIPHER_3DES;
961	u_char session_key[SSH_SESSION_KEY_LENGTH];
962	u_char cookie[8];
963	u_int supported_ciphers;
964	u_int server_flags, client_flags;
965	u_int32_t rand = 0;
966
967	debug("Waiting for server public key.");
968
969	/* Wait for a public key packet from the server. */
970	packet_read_expect(SSH_SMSG_PUBLIC_KEY);
971
972	/* Get cookie from the packet. */
973	for (i = 0; i < 8; i++)
974		cookie[i] = packet_get_char();
975
976	/* Get the public key. */
977	server_key = key_new(KEY_RSA1);
978	bits = packet_get_int();
979	packet_get_bignum(server_key->rsa->e);
980	packet_get_bignum(server_key->rsa->n);
981
982	rbits = BN_num_bits(server_key->rsa->n);
983	if (bits != rbits) {
984		log("Warning: Server lies about size of server public key: "
985		    "actual size is %d bits vs. announced %d.", rbits, bits);
986		log("Warning: This may be due to an old implementation of ssh.");
987	}
988	/* Get the host key. */
989	host_key = key_new(KEY_RSA1);
990	bits = packet_get_int();
991	packet_get_bignum(host_key->rsa->e);
992	packet_get_bignum(host_key->rsa->n);
993
994	rbits = BN_num_bits(host_key->rsa->n);
995	if (bits != rbits) {
996		log("Warning: Server lies about size of server host key: "
997		    "actual size is %d bits vs. announced %d.", rbits, bits);
998		log("Warning: This may be due to an old implementation of ssh.");
999	}
1000
1001	/* Get protocol flags. */
1002	server_flags = packet_get_int();
1003	packet_set_protocol_flags(server_flags);
1004
1005	supported_ciphers = packet_get_int();
1006	supported_authentications = packet_get_int();
1007	packet_check_eom();
1008
1009	debug("Received server public key (%d bits) and host key (%d bits).",
1010	    BN_num_bits(server_key->rsa->n), BN_num_bits(host_key->rsa->n));
1011
1012	if (verify_host_key(host, hostaddr, host_key) == -1)
1013		fatal("Host key verification failed.");
1014
1015	client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1016
1017	compute_session_id(session_id, cookie, host_key->rsa->n, server_key->rsa->n);
1018
1019	/* Generate a session key. */
1020	arc4random_stir();
1021
1022	/*
1023	 * Generate an encryption key for the session.   The key is a 256 bit
1024	 * random number, interpreted as a 32-byte key, with the least
1025	 * significant 8 bits being the first byte of the key.
1026	 */
1027	for (i = 0; i < 32; i++) {
1028		if (i % 4 == 0)
1029			rand = arc4random();
1030		session_key[i] = rand & 0xff;
1031		rand >>= 8;
1032	}
1033
1034	/*
1035	 * According to the protocol spec, the first byte of the session key
1036	 * is the highest byte of the integer.  The session key is xored with
1037	 * the first 16 bytes of the session id.
1038	 */
1039	if ((key = BN_new()) == NULL)
1040		fatal("respond_to_rsa_challenge: BN_new failed");
1041	BN_set_word(key, 0);
1042	for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1043		BN_lshift(key, key, 8);
1044		if (i < 16)
1045			BN_add_word(key, session_key[i] ^ session_id[i]);
1046		else
1047			BN_add_word(key, session_key[i]);
1048	}
1049
1050	/*
1051	 * Encrypt the integer using the public key and host key of the
1052	 * server (key with smaller modulus first).
1053	 */
1054	if (BN_cmp(server_key->rsa->n, host_key->rsa->n) < 0) {
1055		/* Public key has smaller modulus. */
1056		if (BN_num_bits(host_key->rsa->n) <
1057		    BN_num_bits(server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1058			fatal("respond_to_rsa_challenge: host_key %d < server_key %d + "
1059			    "SSH_KEY_BITS_RESERVED %d",
1060			    BN_num_bits(host_key->rsa->n),
1061			    BN_num_bits(server_key->rsa->n),
1062			    SSH_KEY_BITS_RESERVED);
1063		}
1064		rsa_public_encrypt(key, key, server_key->rsa);
1065		rsa_public_encrypt(key, key, host_key->rsa);
1066	} else {
1067		/* Host key has smaller modulus (or they are equal). */
1068		if (BN_num_bits(server_key->rsa->n) <
1069		    BN_num_bits(host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1070			fatal("respond_to_rsa_challenge: server_key %d < host_key %d + "
1071			    "SSH_KEY_BITS_RESERVED %d",
1072			    BN_num_bits(server_key->rsa->n),
1073			    BN_num_bits(host_key->rsa->n),
1074			    SSH_KEY_BITS_RESERVED);
1075		}
1076		rsa_public_encrypt(key, key, host_key->rsa);
1077		rsa_public_encrypt(key, key, server_key->rsa);
1078	}
1079
1080	/* Destroy the public keys since we no longer need them. */
1081	key_free(server_key);
1082	key_free(host_key);
1083
1084	if (options.cipher == SSH_CIPHER_NOT_SET) {
1085		if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
1086			options.cipher = ssh_cipher_default;
1087	} else if (options.cipher == SSH_CIPHER_ILLEGAL ||
1088	    !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
1089		log("No valid SSH1 cipher, using %.100s instead.",
1090		    cipher_name(ssh_cipher_default));
1091		options.cipher = ssh_cipher_default;
1092	}
1093	/* Check that the selected cipher is supported. */
1094	if (!(supported_ciphers & (1 << options.cipher)))
1095		fatal("Selected cipher type %.100s not supported by server.",
1096		    cipher_name(options.cipher));
1097
1098	debug("Encryption type: %.100s", cipher_name(options.cipher));
1099
1100	/* Send the encrypted session key to the server. */
1101	packet_start(SSH_CMSG_SESSION_KEY);
1102	packet_put_char(options.cipher);
1103
1104	/* Send the cookie back to the server. */
1105	for (i = 0; i < 8; i++)
1106		packet_put_char(cookie[i]);
1107
1108	/* Send and destroy the encrypted encryption key integer. */
1109	packet_put_bignum(key);
1110	BN_clear_free(key);
1111
1112	/* Send protocol flags. */
1113	packet_put_int(client_flags);
1114
1115	/* Send the packet now. */
1116	packet_send();
1117	packet_write_wait();
1118
1119	debug("Sent encrypted session key.");
1120
1121	/* Set the encryption key. */
1122	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1123
1124	/* We will no longer need the session key here.  Destroy any extra copies. */
1125	memset(session_key, 0, sizeof(session_key));
1126
1127	/*
1128	 * Expect a success message from the server.  Note that this message
1129	 * will be received in encrypted form.
1130	 */
1131	packet_read_expect(SSH_SMSG_SUCCESS);
1132
1133	debug("Received encrypted confirmation.");
1134}
1135
1136/*
1137 * Authenticate user
1138 */
1139void
1140ssh_userauth1(const char *local_user, const char *server_user, char *host,
1141    Sensitive *sensitive)
1142{
1143#ifdef KRB5
1144	krb5_context context = NULL;
1145	krb5_auth_context auth_context = NULL;
1146#endif
1147	int i, type;
1148
1149	if (supported_authentications == 0)
1150		fatal("ssh_userauth1: server supports no auth methods");
1151
1152	/* Send the name of the user to log in as on the server. */
1153	packet_start(SSH_CMSG_USER);
1154	packet_put_cstring(server_user);
1155	packet_send();
1156	packet_write_wait();
1157
1158	/*
1159	 * The server should respond with success if no authentication is
1160	 * needed (the user has no password).  Otherwise the server responds
1161	 * with failure.
1162	 */
1163	type = packet_read();
1164
1165	/* check whether the connection was accepted without authentication. */
1166	if (type == SSH_SMSG_SUCCESS)
1167		goto success;
1168	if (type != SSH_SMSG_FAILURE)
1169		packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", type);
1170
1171#ifdef KRB5
1172	if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1173	    options.kerberos_authentication) {
1174		debug("Trying Kerberos v5 authentication.");
1175
1176		if (try_krb5_authentication(&context, &auth_context)) {
1177			type = packet_read();
1178			if (type == SSH_SMSG_SUCCESS)
1179				goto success;
1180			if (type != SSH_SMSG_FAILURE)
1181				packet_disconnect("Protocol error: got %d in response to Kerberos v5 auth", type);
1182		}
1183	}
1184#endif /* KRB5 */
1185
1186#ifdef KRB4
1187	if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1188	    options.kerberos_authentication) {
1189		debug("Trying Kerberos v4 authentication.");
1190
1191		if (try_krb4_authentication()) {
1192			type = packet_read();
1193			if (type == SSH_SMSG_SUCCESS)
1194				goto success;
1195			if (type != SSH_SMSG_FAILURE)
1196				packet_disconnect("Protocol error: got %d in response to Kerberos v4 auth", type);
1197		}
1198	}
1199#endif /* KRB4 */
1200
1201	/*
1202	 * Use rhosts authentication if running in privileged socket and we
1203	 * do not wish to remain anonymous.
1204	 */
1205	if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1206	    options.rhosts_authentication) {
1207		debug("Trying rhosts authentication.");
1208		packet_start(SSH_CMSG_AUTH_RHOSTS);
1209		packet_put_cstring(local_user);
1210		packet_send();
1211		packet_write_wait();
1212
1213		/* The server should respond with success or failure. */
1214		type = packet_read();
1215		if (type == SSH_SMSG_SUCCESS)
1216			goto success;
1217		if (type != SSH_SMSG_FAILURE)
1218			packet_disconnect("Protocol error: got %d in response to rhosts auth",
1219					  type);
1220	}
1221	/*
1222	 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1223	 * authentication.
1224	 */
1225	if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1226	    options.rhosts_rsa_authentication) {
1227		for (i = 0; i < sensitive->nkeys; i++) {
1228			if (sensitive->keys[i] != NULL &&
1229			    sensitive->keys[i]->type == KEY_RSA1 &&
1230			    try_rhosts_rsa_authentication(local_user,
1231			    sensitive->keys[i]))
1232				goto success;
1233		}
1234	}
1235	/* Try RSA authentication if the server supports it. */
1236	if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1237	    options.rsa_authentication) {
1238		/*
1239		 * Try RSA authentication using the authentication agent. The
1240		 * agent is tried first because no passphrase is needed for
1241		 * it, whereas identity files may require passphrases.
1242		 */
1243		if (try_agent_authentication())
1244			goto success;
1245
1246		/* Try RSA authentication for each identity. */
1247		for (i = 0; i < options.num_identity_files; i++)
1248			if (options.identity_keys[i] != NULL &&
1249			    options.identity_keys[i]->type == KEY_RSA1 &&
1250			    try_rsa_authentication(i))
1251				goto success;
1252	}
1253	/* Try challenge response authentication if the server supports it. */
1254	if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1255	    options.challenge_response_authentication && !options.batch_mode) {
1256		if (try_challenge_response_authentication())
1257			goto success;
1258	}
1259	/* Try password authentication if the server supports it. */
1260	if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1261	    options.password_authentication && !options.batch_mode) {
1262		char prompt[80];
1263
1264		snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
1265		    server_user, host);
1266		if (try_password_authentication(prompt))
1267			goto success;
1268	}
1269	/* All authentication methods have failed.  Exit with an error message. */
1270	fatal("Permission denied.");
1271	/* NOTREACHED */
1272
1273 success:
1274#ifdef KRB5
1275	/* Try Kerberos v5 TGT passing. */
1276	if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1277	    options.kerberos_tgt_passing && context && auth_context) {
1278		if (options.cipher == SSH_CIPHER_NONE)
1279			log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1280		send_krb5_tgt(context, auth_context);
1281	}
1282	if (auth_context)
1283		krb5_auth_con_free(context, auth_context);
1284	if (context)
1285		krb5_free_context(context);
1286#endif
1287
1288#ifdef AFS
1289	/* Try Kerberos v4 TGT passing if the server supports it. */
1290	if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1291	    options.kerberos_tgt_passing) {
1292		if (options.cipher == SSH_CIPHER_NONE)
1293			log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1294		send_krb4_tgt();
1295	}
1296	/* Try AFS token passing if the server supports it. */
1297	if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1298	    options.afs_token_passing && k_hasafs()) {
1299		if (options.cipher == SSH_CIPHER_NONE)
1300			log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1301		send_afs_tokens();
1302	}
1303#endif /* AFS */
1304
1305	return;	/* need statement after label */
1306}
1307