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