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