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