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