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