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