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