sshconnect.c revision 57429
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
10#include "includes.h"
11RCSID("$OpenBSD: sshconnect.c,v 1.56 2000/02/18 08:50:33 markus Exp $");
12
13#include <ssl/bn.h>
14#include "xmalloc.h"
15#include "rsa.h"
16#include "ssh.h"
17#include "packet.h"
18#include "authfd.h"
19#include "cipher.h"
20#include "mpaux.h"
21#include "uidswap.h"
22#include "compat.h"
23#include "readconf.h"
24#include "fingerprint.h"
25
26#include <ssl/md5.h>
27
28/* Session id for the current session. */
29unsigned char session_id[16];
30
31/* authentications supported by server */
32unsigned int supported_authentications;
33
34extern Options options;
35extern char *__progname;
36
37/*
38 * Connect to the given ssh server using a proxy command.
39 */
40int
41ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid,
42		  const char *proxy_command)
43{
44	Buffer command;
45	const char *cp;
46	char *command_string;
47	int pin[2], pout[2];
48	int pid;
49	char strport[NI_MAXSERV];
50
51	/* Convert the port number into a string. */
52	snprintf(strport, sizeof strport, "%hu", port);
53
54	/* Build the final command string in the buffer by making the
55	   appropriate substitutions to the given proxy command. */
56	buffer_init(&command);
57	for (cp = proxy_command; *cp; cp++) {
58		if (cp[0] == '%' && cp[1] == '%') {
59			buffer_append(&command, "%", 1);
60			cp++;
61			continue;
62		}
63		if (cp[0] == '%' && cp[1] == 'h') {
64			buffer_append(&command, host, strlen(host));
65			cp++;
66			continue;
67		}
68		if (cp[0] == '%' && cp[1] == 'p') {
69			buffer_append(&command, strport, strlen(strport));
70			cp++;
71			continue;
72		}
73		buffer_append(&command, cp, 1);
74	}
75	buffer_append(&command, "\0", 1);
76
77	/* Get the final command string. */
78	command_string = buffer_ptr(&command);
79
80	/* Create pipes for communicating with the proxy. */
81	if (pipe(pin) < 0 || pipe(pout) < 0)
82		fatal("Could not create pipes to communicate with the proxy: %.100s",
83		      strerror(errno));
84
85	debug("Executing proxy command: %.500s", command_string);
86
87	/* Fork and execute the proxy command. */
88	if ((pid = fork()) == 0) {
89		char *argv[10];
90
91		/* Child.  Permanently give up superuser privileges. */
92		permanently_set_uid(original_real_uid);
93
94		/* Redirect stdin and stdout. */
95		close(pin[1]);
96		if (pin[0] != 0) {
97			if (dup2(pin[0], 0) < 0)
98				perror("dup2 stdin");
99			close(pin[0]);
100		}
101		close(pout[0]);
102		if (dup2(pout[1], 1) < 0)
103			perror("dup2 stdout");
104		/* Cannot be 1 because pin allocated two descriptors. */
105		close(pout[1]);
106
107		/* Stderr is left as it is so that error messages get
108		   printed on the user's terminal. */
109		argv[0] = "/bin/sh";
110		argv[1] = "-c";
111		argv[2] = command_string;
112		argv[3] = NULL;
113
114		/* Execute the proxy command.  Note that we gave up any
115		   extra privileges above. */
116		execv("/bin/sh", argv);
117		perror("/bin/sh");
118		exit(1);
119	}
120	/* Parent. */
121	if (pid < 0)
122		fatal("fork failed: %.100s", strerror(errno));
123
124	/* Close child side of the descriptors. */
125	close(pin[0]);
126	close(pout[1]);
127
128	/* Free the command name. */
129	buffer_free(&command);
130
131	/* Set the connection file descriptors. */
132	packet_set_connection(pout[0], pin[1]);
133
134	return 1;
135}
136
137/*
138 * Creates a (possibly privileged) socket for use as the ssh connection.
139 */
140int
141ssh_create_socket(uid_t original_real_uid, int privileged, int family)
142{
143	int sock;
144
145	/*
146	 * If we are running as root and want to connect to a privileged
147	 * port, bind our own socket to a privileged port.
148	 */
149	if (privileged) {
150		int p = IPPORT_RESERVED - 1;
151		sock = rresvport_af(&p, family);
152		if (sock < 0)
153			error("rresvport: af=%d %.100s", family, strerror(errno));
154		else
155			debug("Allocated local port %d.", p);
156	} else {
157		/*
158		 * Just create an ordinary socket on arbitrary port.  We use
159		 * the user's uid to create the socket.
160		 */
161		temporarily_use_uid(original_real_uid);
162		sock = socket(family, SOCK_STREAM, 0);
163		if (sock < 0)
164			error("socket: %.100s", strerror(errno));
165		restore_uid();
166	}
167	return sock;
168}
169
170/*
171 * Opens a TCP/IP connection to the remote server on the given host.
172 * The address of the remote host will be returned in hostaddr.
173 * If port is 0, the default port will be used.  If anonymous is zero,
174 * a privileged port will be allocated to make the connection.
175 * This requires super-user privileges if anonymous is false.
176 * Connection_attempts specifies the maximum number of tries (one per
177 * second).  If proxy_command is non-NULL, it specifies the command (with %h
178 * and %p substituted for host and port, respectively) to use to contact
179 * the daemon.
180 */
181int
182ssh_connect(const char *host, struct sockaddr_storage * hostaddr,
183	    u_short port, int connection_attempts,
184	    int anonymous, uid_t original_real_uid,
185	    const char *proxy_command)
186{
187	int sock = -1, attempt;
188	struct servent *sp;
189	struct addrinfo hints, *ai, *aitop;
190	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
191	int gaierr;
192	struct linger linger;
193
194	debug("ssh_connect: getuid %d geteuid %d anon %d",
195	      (int) getuid(), (int) geteuid(), anonymous);
196
197	/* Get default port if port has not been set. */
198	if (port == 0) {
199		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
200		if (sp)
201			port = ntohs(sp->s_port);
202		else
203			port = SSH_DEFAULT_PORT;
204	}
205	/* If a proxy command is given, connect using it. */
206	if (proxy_command != NULL)
207		return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
208
209	/* No proxy command. */
210
211	memset(&hints, 0, sizeof(hints));
212	hints.ai_family = IPv4or6;
213	hints.ai_socktype = SOCK_STREAM;
214	snprintf(strport, sizeof strport, "%d", port);
215	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
216		fatal("%s: %.100s: %s", __progname, host,
217		    gai_strerror(gaierr));
218
219	/*
220	 * Try to connect several times.  On some machines, the first time
221	 * will sometimes fail.  In general socket code appears to behave
222	 * quite magically on many machines.
223	 */
224	for (attempt = 0; attempt < connection_attempts; attempt++) {
225		if (attempt > 0)
226			debug("Trying again...");
227
228		/* Loop through addresses for this host, and try each one in
229 		   sequence until the connection succeeds. */
230		for (ai = aitop; ai; ai = ai->ai_next) {
231			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
232				continue;
233			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
234			    ntop, sizeof(ntop), strport, sizeof(strport),
235			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
236				error("ssh_connect: getnameinfo failed");
237				continue;
238			}
239			debug("Connecting to %.200s [%.100s] port %s.",
240				host, ntop, strport);
241
242			/* Create a socket for connecting. */
243			sock = ssh_create_socket(original_real_uid,
244			    !anonymous && geteuid() == 0 && port < IPPORT_RESERVED,
245			    ai->ai_family);
246			if (sock < 0)
247				continue;
248
249			/* Connect to the host.  We use the user's uid in the
250			 * hope that it will help with tcp_wrappers showing
251			 * the remote uid as root.
252			 */
253			temporarily_use_uid(original_real_uid);
254			if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) {
255				/* Successful connection. */
256				memcpy(hostaddr, ai->ai_addr, sizeof(*hostaddr));
257				restore_uid();
258				break;
259			} else {
260				debug("connect: %.100s", strerror(errno));
261				restore_uid();
262				/*
263				 * Close the failed socket; there appear to
264				 * be some problems when reusing a socket for
265				 * which connect() has already returned an
266				 * error.
267				 */
268				shutdown(sock, SHUT_RDWR);
269				close(sock);
270			}
271		}
272		if (ai)
273			break;	/* Successful connection. */
274
275		/* Sleep a moment before retrying. */
276		sleep(1);
277	}
278
279	freeaddrinfo(aitop);
280
281	/* Return failure if we didn't get a successful connection. */
282	if (attempt >= connection_attempts)
283		return 0;
284
285	debug("Connection established.");
286
287	/*
288	 * Set socket options.  We would like the socket to disappear as soon
289	 * as it has been closed for whatever reason.
290	 */
291	/* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
292	linger.l_onoff = 1;
293	linger.l_linger = 5;
294	setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
295
296	/* Set the connection. */
297	packet_set_connection(sock, sock);
298
299	return 1;
300}
301
302/*
303 * Checks if the user has an authentication agent, and if so, tries to
304 * authenticate using the agent.
305 */
306int
307try_agent_authentication()
308{
309	int status, type;
310	char *comment;
311	AuthenticationConnection *auth;
312	unsigned char response[16];
313	unsigned int i;
314	BIGNUM *e, *n, *challenge;
315
316	/* Get connection to the agent. */
317	auth = ssh_get_authentication_connection();
318	if (!auth)
319		return 0;
320
321	e = BN_new();
322	n = BN_new();
323	challenge = BN_new();
324
325	/* Loop through identities served by the agent. */
326	for (status = ssh_get_first_identity(auth, e, n, &comment);
327	     status;
328	     status = ssh_get_next_identity(auth, e, n, &comment)) {
329		int plen, clen;
330
331		/* Try this identity. */
332		debug("Trying RSA authentication via agent with '%.100s'", comment);
333		xfree(comment);
334
335		/* Tell the server that we are willing to authenticate using this key. */
336		packet_start(SSH_CMSG_AUTH_RSA);
337		packet_put_bignum(n);
338		packet_send();
339		packet_write_wait();
340
341		/* Wait for server's response. */
342		type = packet_read(&plen);
343
344		/* The server sends failure if it doesn\'t like our key or
345		   does not support RSA authentication. */
346		if (type == SSH_SMSG_FAILURE) {
347			debug("Server refused our key.");
348			continue;
349		}
350		/* Otherwise it should have sent a challenge. */
351		if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
352			packet_disconnect("Protocol error during RSA authentication: %d",
353					  type);
354
355		packet_get_bignum(challenge, &clen);
356
357		packet_integrity_check(plen, clen, type);
358
359		debug("Received RSA challenge from server.");
360
361		/* Ask the agent to decrypt the challenge. */
362		if (!ssh_decrypt_challenge(auth, e, n, challenge,
363					   session_id, 1, response)) {
364			/* The agent failed to authenticate this identifier although it
365			   advertised it supports this.  Just return a wrong value. */
366			log("Authentication agent failed to decrypt challenge.");
367			memset(response, 0, sizeof(response));
368		}
369		debug("Sending response to RSA challenge.");
370
371		/* Send the decrypted challenge back to the server. */
372		packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
373		for (i = 0; i < 16; i++)
374			packet_put_char(response[i]);
375		packet_send();
376		packet_write_wait();
377
378		/* Wait for response from the server. */
379		type = packet_read(&plen);
380
381		/* The server returns success if it accepted the authentication. */
382		if (type == SSH_SMSG_SUCCESS) {
383			debug("RSA authentication accepted by server.");
384			BN_clear_free(e);
385			BN_clear_free(n);
386			BN_clear_free(challenge);
387			return 1;
388		}
389		/* Otherwise it should return failure. */
390		if (type != SSH_SMSG_FAILURE)
391			packet_disconnect("Protocol error waiting RSA auth response: %d",
392					  type);
393	}
394
395	BN_clear_free(e);
396	BN_clear_free(n);
397	BN_clear_free(challenge);
398
399	debug("RSA authentication using agent refused.");
400	return 0;
401}
402
403/*
404 * Computes the proper response to a RSA challenge, and sends the response to
405 * the server.
406 */
407void
408respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
409{
410	unsigned char buf[32], response[16];
411	MD5_CTX md;
412	int i, len;
413
414	/* Decrypt the challenge using the private key. */
415	rsa_private_decrypt(challenge, challenge, prv);
416
417	/* Compute the response. */
418	/* The response is MD5 of decrypted challenge plus session id. */
419	len = BN_num_bytes(challenge);
420	if (len <= 0 || len > sizeof(buf))
421		packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
422				  len);
423
424	memset(buf, 0, sizeof(buf));
425	BN_bn2bin(challenge, buf + sizeof(buf) - len);
426	MD5_Init(&md);
427	MD5_Update(&md, buf, 32);
428	MD5_Update(&md, session_id, 16);
429	MD5_Final(response, &md);
430
431	debug("Sending response to host key RSA challenge.");
432
433	/* Send the response back to the server. */
434	packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
435	for (i = 0; i < 16; i++)
436		packet_put_char(response[i]);
437	packet_send();
438	packet_write_wait();
439
440	memset(buf, 0, sizeof(buf));
441	memset(response, 0, sizeof(response));
442	memset(&md, 0, sizeof(md));
443}
444
445/*
446 * Checks if the user has authentication file, and if so, tries to authenticate
447 * the user using it.
448 */
449int
450try_rsa_authentication(const char *authfile)
451{
452	BIGNUM *challenge;
453	RSA *private_key;
454	RSA *public_key;
455	char *passphrase, *comment;
456	int type, i;
457	int plen, clen;
458
459	/* Try to load identification for the authentication key. */
460	public_key = RSA_new();
461	if (!load_public_key(authfile, public_key, &comment)) {
462		RSA_free(public_key);
463		/* Could not load it.  Fail. */
464		return 0;
465	}
466	debug("Trying RSA authentication with key '%.100s'", comment);
467
468	/* Tell the server that we are willing to authenticate using this key. */
469	packet_start(SSH_CMSG_AUTH_RSA);
470	packet_put_bignum(public_key->n);
471	packet_send();
472	packet_write_wait();
473
474	/* We no longer need the public key. */
475	RSA_free(public_key);
476
477	/* Wait for server's response. */
478	type = packet_read(&plen);
479
480	/*
481	 * The server responds with failure if it doesn\'t like our key or
482	 * doesn\'t support RSA authentication.
483	 */
484	if (type == SSH_SMSG_FAILURE) {
485		debug("Server refused our key.");
486		xfree(comment);
487		return 0;
488	}
489	/* Otherwise, the server should respond with a challenge. */
490	if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
491		packet_disconnect("Protocol error during RSA authentication: %d", type);
492
493	/* Get the challenge from the packet. */
494	challenge = BN_new();
495	packet_get_bignum(challenge, &clen);
496
497	packet_integrity_check(plen, clen, type);
498
499	debug("Received RSA challenge from server.");
500
501	private_key = RSA_new();
502	/*
503	 * Load the private key.  Try first with empty passphrase; if it
504	 * fails, ask for a passphrase.
505	 */
506	if (!load_private_key(authfile, "", private_key, NULL)) {
507		char buf[300];
508		snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
509		    comment);
510		if (!options.batch_mode)
511			passphrase = read_passphrase(buf, 0);
512		else {
513			debug("Will not query passphrase for %.100s in batch mode.",
514			      comment);
515			passphrase = xstrdup("");
516		}
517
518		/* Load the authentication file using the pasphrase. */
519		if (!load_private_key(authfile, passphrase, private_key, NULL)) {
520			memset(passphrase, 0, strlen(passphrase));
521			xfree(passphrase);
522			error("Bad passphrase.");
523
524			/* Send a dummy response packet to avoid protocol error. */
525			packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
526			for (i = 0; i < 16; i++)
527				packet_put_char(0);
528			packet_send();
529			packet_write_wait();
530
531			/* Expect the server to reject it... */
532			packet_read_expect(&plen, SSH_SMSG_FAILURE);
533			xfree(comment);
534			return 0;
535		}
536		/* Destroy the passphrase. */
537		memset(passphrase, 0, strlen(passphrase));
538		xfree(passphrase);
539	}
540	/* We no longer need the comment. */
541	xfree(comment);
542
543	/* Compute and send a response to the challenge. */
544	respond_to_rsa_challenge(challenge, private_key);
545
546	/* Destroy the private key. */
547	RSA_free(private_key);
548
549	/* We no longer need the challenge. */
550	BN_clear_free(challenge);
551
552	/* Wait for response from the server. */
553	type = packet_read(&plen);
554	if (type == SSH_SMSG_SUCCESS) {
555		debug("RSA authentication accepted by server.");
556		return 1;
557	}
558	if (type != SSH_SMSG_FAILURE)
559		packet_disconnect("Protocol error waiting RSA auth response: %d", type);
560	debug("RSA authentication refused.");
561	return 0;
562}
563
564/*
565 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
566 * authentication and RSA host authentication.
567 */
568int
569try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
570{
571	int type;
572	BIGNUM *challenge;
573	int plen, clen;
574
575	debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
576
577	/* Tell the server that we are willing to authenticate using this key. */
578	packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
579	packet_put_string(local_user, strlen(local_user));
580	packet_put_int(BN_num_bits(host_key->n));
581	packet_put_bignum(host_key->e);
582	packet_put_bignum(host_key->n);
583	packet_send();
584	packet_write_wait();
585
586	/* Wait for server's response. */
587	type = packet_read(&plen);
588
589	/* The server responds with failure if it doesn't admit our
590	   .rhosts authentication or doesn't know our host key. */
591	if (type == SSH_SMSG_FAILURE) {
592		debug("Server refused our rhosts authentication or host key.");
593		return 0;
594	}
595	/* Otherwise, the server should respond with a challenge. */
596	if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
597		packet_disconnect("Protocol error during RSA authentication: %d", type);
598
599	/* Get the challenge from the packet. */
600	challenge = BN_new();
601	packet_get_bignum(challenge, &clen);
602
603	packet_integrity_check(plen, clen, type);
604
605	debug("Received RSA challenge for host key from server.");
606
607	/* Compute a response to the challenge. */
608	respond_to_rsa_challenge(challenge, host_key);
609
610	/* We no longer need the challenge. */
611	BN_clear_free(challenge);
612
613	/* Wait for response from the server. */
614	type = packet_read(&plen);
615	if (type == SSH_SMSG_SUCCESS) {
616		debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
617		return 1;
618	}
619	if (type != SSH_SMSG_FAILURE)
620		packet_disconnect("Protocol error waiting RSA auth response: %d", type);
621	debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
622	return 0;
623}
624
625#ifdef KRB4
626int
627try_kerberos_authentication()
628{
629	KTEXT_ST auth;		/* Kerberos data */
630	char *reply;
631	char inst[INST_SZ];
632	char *realm;
633	CREDENTIALS cred;
634	int r, type, plen;
635	Key_schedule schedule;
636	u_long checksum, cksum;
637	MSG_DAT msg_data;
638	struct sockaddr_in local, foreign;
639	struct stat st;
640
641	/* Don't do anything if we don't have any tickets. */
642	if (stat(tkt_string(), &st) < 0)
643		return 0;
644
645	strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
646
647	realm = (char *) krb_realmofhost(get_canonical_hostname());
648	if (!realm) {
649		debug("Kerberos V4: no realm for %s", get_canonical_hostname());
650		return 0;
651	}
652	/* This can really be anything. */
653	checksum = (u_long) getpid();
654
655	r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
656	if (r != KSUCCESS) {
657		debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
658		return 0;
659	}
660	/* Get session key to decrypt the server's reply with. */
661	r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
662	if (r != KSUCCESS) {
663		debug("get_cred failed: %s", krb_err_txt[r]);
664		return 0;
665	}
666	des_key_sched((des_cblock *) cred.session, schedule);
667
668	/* Send authentication info to server. */
669	packet_start(SSH_CMSG_AUTH_KERBEROS);
670	packet_put_string((char *) auth.dat, auth.length);
671	packet_send();
672	packet_write_wait();
673
674	/* Zero the buffer. */
675	(void) memset(auth.dat, 0, MAX_KTXT_LEN);
676
677	r = sizeof(local);
678	memset(&local, 0, sizeof(local));
679	if (getsockname(packet_get_connection_in(),
680			(struct sockaddr *) & local, &r) < 0)
681		debug("getsockname failed: %s", strerror(errno));
682
683	r = sizeof(foreign);
684	memset(&foreign, 0, sizeof(foreign));
685	if (getpeername(packet_get_connection_in(),
686			(struct sockaddr *) & foreign, &r) < 0) {
687		debug("getpeername failed: %s", strerror(errno));
688		fatal_cleanup();
689	}
690	/* Get server reply. */
691	type = packet_read(&plen);
692	switch (type) {
693	case SSH_SMSG_FAILURE:
694		/* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
695		debug("Kerberos V4 authentication failed.");
696		return 0;
697		break;
698
699	case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
700		/* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
701		debug("Kerberos V4 authentication accepted.");
702
703		/* Get server's response. */
704		reply = packet_get_string((unsigned int *) &auth.length);
705		memcpy(auth.dat, reply, auth.length);
706		xfree(reply);
707
708		packet_integrity_check(plen, 4 + auth.length, type);
709
710		/*
711		 * If his response isn't properly encrypted with the session
712		 * key, and the decrypted checksum fails to match, he's
713		 * bogus. Bail out.
714		 */
715		r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
716				&foreign, &local, &msg_data);
717		if (r != KSUCCESS) {
718			debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
719			packet_disconnect("Kerberos V4 challenge failed!");
720		}
721		/* Fetch the (incremented) checksum that we supplied in the request. */
722		(void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
723		cksum = ntohl(cksum);
724
725		/* If it matches, we're golden. */
726		if (cksum == checksum + 1) {
727			debug("Kerberos V4 challenge successful.");
728			return 1;
729		} else
730			packet_disconnect("Kerberos V4 challenge failed!");
731		break;
732
733	default:
734		packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
735	}
736	return 0;
737}
738
739#endif /* KRB4 */
740
741#ifdef AFS
742int
743send_kerberos_tgt()
744{
745	CREDENTIALS *creds;
746	char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
747	int r, type, plen;
748	unsigned char buffer[8192];
749	struct stat st;
750
751	/* Don't do anything if we don't have any tickets. */
752	if (stat(tkt_string(), &st) < 0)
753		return 0;
754
755	creds = xmalloc(sizeof(*creds));
756
757	if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
758		debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
759		return 0;
760	}
761	if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
762		debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
763		return 0;
764	}
765	if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
766		debug("Kerberos V4 ticket expired: %s", TKT_FILE);
767		return 0;
768	}
769	creds_to_radix(creds, buffer);
770	xfree(creds);
771
772	packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
773	packet_put_string((char *) buffer, strlen(buffer));
774	packet_send();
775	packet_write_wait();
776
777	type = packet_read(&plen);
778
779	if (type == SSH_SMSG_FAILURE)
780		debug("Kerberos TGT for realm %s rejected.", prealm);
781	else if (type != SSH_SMSG_SUCCESS)
782		packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
783
784	return 1;
785}
786
787void
788send_afs_tokens(void)
789{
790	CREDENTIALS creds;
791	struct ViceIoctl parms;
792	struct ClearToken ct;
793	int i, type, len, plen;
794	char buf[2048], *p, *server_cell;
795	unsigned char buffer[8192];
796
797	/* Move over ktc_GetToken, here's something leaner. */
798	for (i = 0; i < 100; i++) {	/* just in case */
799		parms.in = (char *) &i;
800		parms.in_size = sizeof(i);
801		parms.out = buf;
802		parms.out_size = sizeof(buf);
803		if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
804			break;
805		p = buf;
806
807		/* Get secret token. */
808		memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
809		if (creds.ticket_st.length > MAX_KTXT_LEN)
810			break;
811		p += sizeof(unsigned int);
812		memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
813		p += creds.ticket_st.length;
814
815		/* Get clear token. */
816		memcpy(&len, p, sizeof(len));
817		if (len != sizeof(struct ClearToken))
818			break;
819		p += sizeof(len);
820		memcpy(&ct, p, len);
821		p += len;
822		p += sizeof(len);	/* primary flag */
823		server_cell = p;
824
825		/* Flesh out our credentials. */
826		strlcpy(creds.service, "afs", sizeof creds.service);
827		creds.instance[0] = '\0';
828		strlcpy(creds.realm, server_cell, REALM_SZ);
829		memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
830		creds.issue_date = ct.BeginTimestamp;
831		creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
832		creds.kvno = ct.AuthHandle;
833		snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
834		creds.pinst[0] = '\0';
835
836		/* Encode token, ship it off. */
837		if (!creds_to_radix(&creds, buffer))
838			break;
839		packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
840		packet_put_string((char *) buffer, strlen(buffer));
841		packet_send();
842		packet_write_wait();
843
844		/* Roger, Roger. Clearance, Clarence. What's your vector,
845		   Victor? */
846		type = packet_read(&plen);
847
848		if (type == SSH_SMSG_FAILURE)
849			debug("AFS token for cell %s rejected.", server_cell);
850		else if (type != SSH_SMSG_SUCCESS)
851			packet_disconnect("Protocol error on AFS token response: %d", type);
852	}
853}
854
855#endif /* AFS */
856
857/*
858 * Tries to authenticate with any string-based challenge/response system.
859 * Note that the client code is not tied to s/key or TIS.
860 */
861int
862try_skey_authentication()
863{
864	int type, i, payload_len;
865	char *challenge, *response;
866
867	debug("Doing skey authentication.");
868
869	/* request a challenge */
870	packet_start(SSH_CMSG_AUTH_TIS);
871	packet_send();
872	packet_write_wait();
873
874	type = packet_read(&payload_len);
875	if (type != SSH_SMSG_FAILURE &&
876	    type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
877		packet_disconnect("Protocol error: got %d in response "
878				  "to skey-auth", type);
879	}
880	if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
881		debug("No challenge for skey authentication.");
882		return 0;
883	}
884	challenge = packet_get_string(&payload_len);
885	if (options.cipher == SSH_CIPHER_NONE)
886		log("WARNING: Encryption is disabled! "
887		    "Reponse will be transmitted in clear text.");
888	fprintf(stderr, "%s\n", challenge);
889	xfree(challenge);
890	fflush(stderr);
891	for (i = 0; i < options.number_of_password_prompts; i++) {
892		if (i != 0)
893			error("Permission denied, please try again.");
894		response = read_passphrase("Response: ", 0);
895		packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
896		packet_put_string(response, strlen(response));
897		memset(response, 0, strlen(response));
898		xfree(response);
899		packet_send();
900		packet_write_wait();
901		type = packet_read(&payload_len);
902		if (type == SSH_SMSG_SUCCESS)
903			return 1;
904		if (type != SSH_SMSG_FAILURE)
905			packet_disconnect("Protocol error: got %d in response "
906					  "to skey-auth-reponse", type);
907	}
908	/* failure */
909	return 0;
910}
911
912/*
913 * Tries to authenticate with plain passwd authentication.
914 */
915int
916try_password_authentication(char *prompt)
917{
918	int type, i, payload_len;
919	char *password;
920
921	debug("Doing password authentication.");
922	if (options.cipher == SSH_CIPHER_NONE)
923		log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
924	for (i = 0; i < options.number_of_password_prompts; i++) {
925		if (i != 0)
926			error("Permission denied, please try again.");
927		password = read_passphrase(prompt, 0);
928		packet_start(SSH_CMSG_AUTH_PASSWORD);
929		packet_put_string(password, strlen(password));
930		memset(password, 0, strlen(password));
931		xfree(password);
932		packet_send();
933		packet_write_wait();
934
935		type = packet_read(&payload_len);
936		if (type == SSH_SMSG_SUCCESS)
937			return 1;
938		if (type != SSH_SMSG_FAILURE)
939			packet_disconnect("Protocol error: got %d in response to passwd auth", type);
940	}
941	/* failure */
942	return 0;
943}
944
945/*
946 * Waits for the server identification string, and sends our own
947 * identification string.
948 */
949void
950ssh_exchange_identification()
951{
952	char buf[256], remote_version[256];	/* must be same size! */
953	int remote_major, remote_minor, i;
954	int connection_in = packet_get_connection_in();
955	int connection_out = packet_get_connection_out();
956
957	/* Read other side\'s version identification. */
958	for (i = 0; i < sizeof(buf) - 1; i++) {
959		int len = read(connection_in, &buf[i], 1);
960		if (len < 0)
961			fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
962		if (len != 1)
963			fatal("ssh_exchange_identification: Connection closed by remote host");
964		if (buf[i] == '\r') {
965			buf[i] = '\n';
966			buf[i + 1] = 0;
967			break;
968		}
969		if (buf[i] == '\n') {
970			buf[i + 1] = 0;
971			break;
972		}
973	}
974	buf[sizeof(buf) - 1] = 0;
975
976	/*
977	 * Check that the versions match.  In future this might accept
978	 * several versions and set appropriate flags to handle them.
979	 */
980	if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
981		   remote_version) != 3)
982		fatal("Bad remote protocol version identification: '%.100s'", buf);
983	debug("Remote protocol version %d.%d, remote software version %.100s",
984	      remote_major, remote_minor, remote_version);
985
986	/* Check if the remote protocol version is too old. */
987	if (remote_major == 1 && remote_minor < 3)
988		fatal("Remote machine has too old SSH software version.");
989
990	/* We speak 1.3, too. */
991	if (remote_major == 1 && remote_minor == 3) {
992		enable_compat13();
993		if (options.forward_agent) {
994			log("Agent forwarding disabled for protocol 1.3");
995			options.forward_agent = 0;
996		}
997	}
998#if 0
999	/*
1000	 * Removed for now, to permit compatibility with latter versions. The
1001	 * server will reject our version and disconnect if it doesn't
1002	 * support it.
1003	 */
1004	if (remote_major != PROTOCOL_MAJOR)
1005		fatal("Protocol major versions differ: %d vs. %d",
1006		      PROTOCOL_MAJOR, remote_major);
1007#endif
1008
1009	/* Send our own protocol version identification. */
1010	snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1011	    PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1012	if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
1013		fatal("write: %.100s", strerror(errno));
1014}
1015
1016int ssh_cipher_default = SSH_CIPHER_3DES;
1017
1018int
1019read_yes_or_no(const char *prompt, int defval)
1020{
1021	char buf[1024];
1022	FILE *f;
1023	int retval = -1;
1024
1025	if (isatty(0))
1026		f = stdin;
1027	else
1028		f = fopen("/dev/tty", "rw");
1029
1030	if (f == NULL)
1031		return 0;
1032
1033	fflush(stdout);
1034
1035	while (1) {
1036		fprintf(stderr, "%s", prompt);
1037		if (fgets(buf, sizeof(buf), f) == NULL) {
1038			/* Print a newline (the prompt probably didn\'t have one). */
1039			fprintf(stderr, "\n");
1040			strlcpy(buf, "no", sizeof buf);
1041		}
1042		/* Remove newline from response. */
1043		if (strchr(buf, '\n'))
1044			*strchr(buf, '\n') = 0;
1045
1046		if (buf[0] == 0)
1047			retval = defval;
1048		if (strcmp(buf, "yes") == 0)
1049			retval = 1;
1050		if (strcmp(buf, "no") == 0)
1051			retval = 0;
1052
1053		if (retval != -1) {
1054			if (f != stdin)
1055				fclose(f);
1056			return retval;
1057		}
1058	}
1059}
1060
1061/*
1062 * check whether the supplied host key is valid, return only if ok.
1063 */
1064
1065void
1066check_host_key(char *host, struct sockaddr *hostaddr, RSA *host_key)
1067{
1068	RSA *file_key;
1069	char *ip = NULL;
1070	char hostline[1000], *hostp;
1071	HostStatus host_status;
1072	HostStatus ip_status;
1073	int local = 0, host_ip_differ = 0;
1074	char ntop[NI_MAXHOST];
1075
1076	/*
1077	 * Force accepting of the host key for loopback/localhost. The
1078	 * problem is that if the home directory is NFS-mounted to multiple
1079	 * machines, localhost will refer to a different machine in each of
1080	 * them, and the user will get bogus HOST_CHANGED warnings.  This
1081	 * essentially disables host authentication for localhost; however,
1082	 * this is probably not a real problem.
1083	 */
1084	switch (hostaddr->sa_family) {
1085	case AF_INET:
1086		local = (ntohl(((struct sockaddr_in *)hostaddr)->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
1087		break;
1088	case AF_INET6:
1089		local = IN6_IS_ADDR_LOOPBACK(&(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
1090		break;
1091	default:
1092		local = 0;
1093		break;
1094	}
1095	if (local) {
1096		debug("Forcing accepting of host key for loopback/localhost.");
1097		return;
1098	}
1099
1100	/*
1101	 * Turn off check_host_ip for proxy connects, since
1102	 * we don't have the remote ip-address
1103	 */
1104	if (options.proxy_command != NULL && options.check_host_ip)
1105		options.check_host_ip = 0;
1106
1107	if (options.check_host_ip) {
1108		if (getnameinfo(hostaddr, hostaddr->sa_len, ntop, sizeof(ntop),
1109		    NULL, 0, NI_NUMERICHOST) != 0)
1110			fatal("check_host_key: getnameinfo failed");
1111		ip = xstrdup(ntop);
1112	}
1113
1114	/*
1115	 * Store the host key from the known host file in here so that we can
1116	 * compare it with the key for the IP address.
1117	 */
1118	file_key = RSA_new();
1119	file_key->n = BN_new();
1120	file_key->e = BN_new();
1121
1122	/*
1123	 * Check if the host key is present in the user\'s list of known
1124	 * hosts or in the systemwide list.
1125	 */
1126	host_status = check_host_in_hostfile(options.user_hostfile, host,
1127					     host_key->e, host_key->n,
1128					     file_key->e, file_key->n);
1129	if (host_status == HOST_NEW)
1130		host_status = check_host_in_hostfile(options.system_hostfile, host,
1131						host_key->e, host_key->n,
1132					       file_key->e, file_key->n);
1133	/*
1134	 * Also perform check for the ip address, skip the check if we are
1135	 * localhost or the hostname was an ip address to begin with
1136	 */
1137	if (options.check_host_ip && !local && strcmp(host, ip)) {
1138		RSA *ip_key = RSA_new();
1139		ip_key->n = BN_new();
1140		ip_key->e = BN_new();
1141		ip_status = check_host_in_hostfile(options.user_hostfile, ip,
1142						host_key->e, host_key->n,
1143						   ip_key->e, ip_key->n);
1144
1145		if (ip_status == HOST_NEW)
1146			ip_status = check_host_in_hostfile(options.system_hostfile, ip,
1147						host_key->e, host_key->n,
1148						   ip_key->e, ip_key->n);
1149		if (host_status == HOST_CHANGED &&
1150		    (ip_status != HOST_CHANGED ||
1151		     (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n))))
1152			host_ip_differ = 1;
1153
1154		RSA_free(ip_key);
1155	} else
1156		ip_status = host_status;
1157
1158	RSA_free(file_key);
1159
1160	switch (host_status) {
1161	case HOST_OK:
1162		/* The host is known and the key matches. */
1163		debug("Host '%.200s' is known and matches the host key.", host);
1164		if (options.check_host_ip) {
1165			if (ip_status == HOST_NEW) {
1166				if (!add_host_to_hostfile(options.user_hostfile, ip,
1167					       host_key->e, host_key->n))
1168					log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1169					    ip, options.user_hostfile);
1170				else
1171					log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1172					    ip);
1173			} else if (ip_status != HOST_OK)
1174				log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1175				    host, ip);
1176		}
1177		break;
1178	case HOST_NEW:
1179		/* The host is new. */
1180		if (options.strict_host_key_checking == 1) {
1181			/* User has requested strict host key checking.  We will not add the host key
1182			   automatically.  The only alternative left is to abort. */
1183			fatal("No host key is known for %.200s and you have requested strict checking.", host);
1184		} else if (options.strict_host_key_checking == 2) {
1185			/* The default */
1186			char prompt[1024];
1187			char *fp = fingerprint(host_key->e, host_key->n);
1188			snprintf(prompt, sizeof(prompt),
1189			    "The authenticity of host '%.200s' can't be established.\n"
1190			    "Key fingerprint is %d %s.\n"
1191			    "Are you sure you want to continue connecting (yes/no)? ",
1192			    host, BN_num_bits(host_key->n), fp);
1193			if (!read_yes_or_no(prompt, -1))
1194				fatal("Aborted by user!\n");
1195		}
1196		if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1197			snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1198			hostp = hostline;
1199		} else
1200			hostp = host;
1201
1202		/* If not in strict mode, add the key automatically to the local known_hosts file. */
1203		if (!add_host_to_hostfile(options.user_hostfile, hostp,
1204					  host_key->e, host_key->n))
1205			log("Failed to add the host to the list of known hosts (%.500s).",
1206			    options.user_hostfile);
1207		else
1208			log("Warning: Permanently added '%.200s' to the list of known hosts.",
1209			    hostp);
1210		break;
1211	case HOST_CHANGED:
1212		if (options.check_host_ip && host_ip_differ) {
1213			char *msg;
1214			if (ip_status == HOST_NEW)
1215				msg = "is unknown";
1216			else if (ip_status == HOST_OK)
1217				msg = "is unchanged";
1218			else
1219				msg = "has a different value";
1220			error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1221			error("@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @");
1222			error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1223			error("The host key for %s has changed,", host);
1224			error("and the key for the according IP address %s", ip);
1225			error("%s. This could either mean that", msg);
1226			error("DNS SPOOFING is happening or the IP address for the host");
1227			error("and its host key have changed at the same time");
1228		}
1229		/* The host key has changed. */
1230		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1231		error("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
1232		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1233		error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1234		error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1235		error("It is also possible that the host key has just been changed.");
1236		error("Please contact your system administrator.");
1237		error("Add correct host key in %.100s to get rid of this message.",
1238		      options.user_hostfile);
1239
1240		/*
1241		 * If strict host key checking is in use, the user will have
1242		 * to edit the key manually and we can only abort.
1243		 */
1244		if (options.strict_host_key_checking)
1245			fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1246
1247		/*
1248		 * If strict host key checking has not been requested, allow
1249		 * the connection but without password authentication or
1250		 * agent forwarding.
1251		 */
1252		if (options.password_authentication) {
1253			error("Password authentication is disabled to avoid trojan horses.");
1254			options.password_authentication = 0;
1255		}
1256		if (options.forward_agent) {
1257			error("Agent forwarding is disabled to avoid trojan horses.");
1258			options.forward_agent = 0;
1259		}
1260		/*
1261		 * XXX Should permit the user to change to use the new id.
1262		 * This could be done by converting the host key to an
1263		 * identifying sentence, tell that the host identifies itself
1264		 * by that sentence, and ask the user if he/she whishes to
1265		 * accept the authentication.
1266		 */
1267		break;
1268	}
1269	if (options.check_host_ip)
1270		xfree(ip);
1271}
1272
1273/*
1274 * SSH1 key exchange
1275 */
1276void
1277ssh_kex(char *host, struct sockaddr *hostaddr)
1278{
1279	int i;
1280	BIGNUM *key;
1281	RSA *host_key;
1282	RSA *public_key;
1283	int bits, rbits;
1284	unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1285	unsigned char cookie[8];
1286	unsigned int supported_ciphers;
1287	unsigned int server_flags, client_flags;
1288	int payload_len, clen, sum_len = 0;
1289	u_int32_t rand = 0;
1290
1291	debug("Waiting for server public key.");
1292
1293	/* Wait for a public key packet from the server. */
1294	packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1295
1296	/* Get cookie from the packet. */
1297	for (i = 0; i < 8; i++)
1298		cookie[i] = packet_get_char();
1299
1300	/* Get the public key. */
1301	public_key = RSA_new();
1302	bits = packet_get_int();/* bits */
1303	public_key->e = BN_new();
1304	packet_get_bignum(public_key->e, &clen);
1305	sum_len += clen;
1306	public_key->n = BN_new();
1307	packet_get_bignum(public_key->n, &clen);
1308	sum_len += clen;
1309
1310	rbits = BN_num_bits(public_key->n);
1311	if (bits != rbits) {
1312		log("Warning: Server lies about size of server public key: "
1313		    "actual size is %d bits vs. announced %d.", rbits, bits);
1314		log("Warning: This may be due to an old implementation of ssh.");
1315	}
1316	/* Get the host key. */
1317	host_key = RSA_new();
1318	bits = packet_get_int();/* bits */
1319	host_key->e = BN_new();
1320	packet_get_bignum(host_key->e, &clen);
1321	sum_len += clen;
1322	host_key->n = BN_new();
1323	packet_get_bignum(host_key->n, &clen);
1324	sum_len += clen;
1325
1326	rbits = BN_num_bits(host_key->n);
1327	if (bits != rbits) {
1328		log("Warning: Server lies about size of server host key: "
1329		    "actual size is %d bits vs. announced %d.", rbits, bits);
1330		log("Warning: This may be due to an old implementation of ssh.");
1331	}
1332
1333	/* Get protocol flags. */
1334	server_flags = packet_get_int();
1335	packet_set_protocol_flags(server_flags);
1336
1337	supported_ciphers = packet_get_int();
1338	supported_authentications = packet_get_int();
1339
1340	debug("Received server public key (%d bits) and host key (%d bits).",
1341	      BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1342
1343	packet_integrity_check(payload_len,
1344			       8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1345			       SSH_SMSG_PUBLIC_KEY);
1346
1347	check_host_key(host, hostaddr, host_key);
1348
1349	client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1350
1351	compute_session_id(session_id, cookie, host_key->n, public_key->n);
1352
1353	/* Generate a session key. */
1354	arc4random_stir();
1355
1356	/*
1357	 * Generate an encryption key for the session.   The key is a 256 bit
1358	 * random number, interpreted as a 32-byte key, with the least
1359	 * significant 8 bits being the first byte of the key.
1360	 */
1361	for (i = 0; i < 32; i++) {
1362		if (i % 4 == 0)
1363			rand = arc4random();
1364		session_key[i] = rand & 0xff;
1365		rand >>= 8;
1366	}
1367
1368	/*
1369	 * According to the protocol spec, the first byte of the session key
1370	 * is the highest byte of the integer.  The session key is xored with
1371	 * the first 16 bytes of the session id.
1372	 */
1373	key = BN_new();
1374	BN_set_word(key, 0);
1375	for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1376		BN_lshift(key, key, 8);
1377		if (i < 16)
1378			BN_add_word(key, session_key[i] ^ session_id[i]);
1379		else
1380			BN_add_word(key, session_key[i]);
1381	}
1382
1383	/*
1384	 * Encrypt the integer using the public key and host key of the
1385	 * server (key with smaller modulus first).
1386	 */
1387	if (BN_cmp(public_key->n, host_key->n) < 0) {
1388		/* Public key has smaller modulus. */
1389		if (BN_num_bits(host_key->n) <
1390		    BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1391			fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1392			      "SSH_KEY_BITS_RESERVED %d",
1393			      BN_num_bits(host_key->n),
1394			      BN_num_bits(public_key->n),
1395			      SSH_KEY_BITS_RESERVED);
1396		}
1397		rsa_public_encrypt(key, key, public_key);
1398		rsa_public_encrypt(key, key, host_key);
1399	} else {
1400		/* Host key has smaller modulus (or they are equal). */
1401		if (BN_num_bits(public_key->n) <
1402		    BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1403			fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1404			      "SSH_KEY_BITS_RESERVED %d",
1405			      BN_num_bits(public_key->n),
1406			      BN_num_bits(host_key->n),
1407			      SSH_KEY_BITS_RESERVED);
1408		}
1409		rsa_public_encrypt(key, key, host_key);
1410		rsa_public_encrypt(key, key, public_key);
1411	}
1412
1413	/* Destroy the public keys since we no longer need them. */
1414	RSA_free(public_key);
1415	RSA_free(host_key);
1416
1417	if (options.cipher == SSH_CIPHER_NOT_SET) {
1418		if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1419			options.cipher = ssh_cipher_default;
1420		else {
1421			debug("Cipher %s not supported, using %.100s instead.",
1422			      cipher_name(ssh_cipher_default),
1423			      cipher_name(SSH_FALLBACK_CIPHER));
1424			options.cipher = SSH_FALLBACK_CIPHER;
1425		}
1426	}
1427	/* Check that the selected cipher is supported. */
1428	if (!(supported_ciphers & (1 << options.cipher)))
1429		fatal("Selected cipher type %.100s not supported by server.",
1430		      cipher_name(options.cipher));
1431
1432	debug("Encryption type: %.100s", cipher_name(options.cipher));
1433
1434	/* Send the encrypted session key to the server. */
1435	packet_start(SSH_CMSG_SESSION_KEY);
1436	packet_put_char(options.cipher);
1437
1438	/* Send the cookie back to the server. */
1439	for (i = 0; i < 8; i++)
1440		packet_put_char(cookie[i]);
1441
1442	/* Send and destroy the encrypted encryption key integer. */
1443	packet_put_bignum(key);
1444	BN_clear_free(key);
1445
1446	/* Send protocol flags. */
1447	packet_put_int(client_flags);
1448
1449	/* Send the packet now. */
1450	packet_send();
1451	packet_write_wait();
1452
1453	debug("Sent encrypted session key.");
1454
1455	/* Set the encryption key. */
1456	packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1457
1458	/* We will no longer need the session key here.  Destroy any extra copies. */
1459	memset(session_key, 0, sizeof(session_key));
1460
1461	/*
1462	 * Expect a success message from the server.  Note that this message
1463	 * will be received in encrypted form.
1464	 */
1465	packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1466
1467	debug("Received encrypted confirmation.");
1468}
1469
1470/*
1471 * Authenticate user
1472 */
1473void
1474ssh_userauth(int host_key_valid, RSA *own_host_key,
1475    uid_t original_real_uid, char *host)
1476{
1477	int i, type;
1478	int payload_len;
1479	struct passwd *pw;
1480	const char *server_user, *local_user;
1481
1482	/* Get local user name.  Use it as server user if no user name was given. */
1483	pw = getpwuid(original_real_uid);
1484	if (!pw)
1485		fatal("User id %d not found from user database.", original_real_uid);
1486	local_user = xstrdup(pw->pw_name);
1487	server_user = options.user ? options.user : local_user;
1488
1489	/* Send the name of the user to log in as on the server. */
1490	packet_start(SSH_CMSG_USER);
1491	packet_put_string(server_user, strlen(server_user));
1492	packet_send();
1493	packet_write_wait();
1494
1495	/*
1496	 * The server should respond with success if no authentication is
1497	 * needed (the user has no password).  Otherwise the server responds
1498	 * with failure.
1499	 */
1500	type = packet_read(&payload_len);
1501
1502	/* check whether the connection was accepted without authentication. */
1503	if (type == SSH_SMSG_SUCCESS)
1504		return;
1505	if (type != SSH_SMSG_FAILURE)
1506		packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1507				  type);
1508
1509#ifdef AFS
1510	/* Try Kerberos tgt passing if the server supports it. */
1511	if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1512	    options.kerberos_tgt_passing) {
1513		if (options.cipher == SSH_CIPHER_NONE)
1514			log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1515		(void) send_kerberos_tgt();
1516	}
1517	/* Try AFS token passing if the server supports it. */
1518	if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1519	    options.afs_token_passing && k_hasafs()) {
1520		if (options.cipher == SSH_CIPHER_NONE)
1521			log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1522		send_afs_tokens();
1523	}
1524#endif /* AFS */
1525
1526#ifdef KRB4
1527	if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1528	    options.kerberos_authentication) {
1529		debug("Trying Kerberos authentication.");
1530		if (try_kerberos_authentication()) {
1531			/* The server should respond with success or failure. */
1532			type = packet_read(&payload_len);
1533			if (type == SSH_SMSG_SUCCESS)
1534				return;
1535			if (type != SSH_SMSG_FAILURE)
1536				packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1537		}
1538	}
1539#endif /* KRB4 */
1540
1541	/*
1542	 * Use rhosts authentication if running in privileged socket and we
1543	 * do not wish to remain anonymous.
1544	 */
1545	if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1546	    options.rhosts_authentication) {
1547		debug("Trying rhosts authentication.");
1548		packet_start(SSH_CMSG_AUTH_RHOSTS);
1549		packet_put_string(local_user, strlen(local_user));
1550		packet_send();
1551		packet_write_wait();
1552
1553		/* The server should respond with success or failure. */
1554		type = packet_read(&payload_len);
1555		if (type == SSH_SMSG_SUCCESS)
1556			return;
1557		if (type != SSH_SMSG_FAILURE)
1558			packet_disconnect("Protocol error: got %d in response to rhosts auth",
1559					  type);
1560	}
1561	/*
1562	 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1563	 * authentication.
1564	 */
1565	if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1566	    options.rhosts_rsa_authentication && host_key_valid) {
1567		if (try_rhosts_rsa_authentication(local_user, own_host_key))
1568			return;
1569	}
1570	/* Try RSA authentication if the server supports it. */
1571	if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1572	    options.rsa_authentication) {
1573		/*
1574		 * Try RSA authentication using the authentication agent. The
1575		 * agent is tried first because no passphrase is needed for
1576		 * it, whereas identity files may require passphrases.
1577		 */
1578		if (try_agent_authentication())
1579			return;
1580
1581		/* Try RSA authentication for each identity. */
1582		for (i = 0; i < options.num_identity_files; i++)
1583			if (try_rsa_authentication(options.identity_files[i]))
1584				return;
1585	}
1586	/* Try skey authentication if the server supports it. */
1587	if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1588	    options.skey_authentication && !options.batch_mode) {
1589		if (try_skey_authentication())
1590			return;
1591	}
1592	/* Try password authentication if the server supports it. */
1593	if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1594	    options.password_authentication && !options.batch_mode) {
1595		char prompt[80];
1596
1597		snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1598		    server_user, host);
1599		if (try_password_authentication(prompt))
1600			return;
1601	}
1602	/* All authentication methods have failed.  Exit with an error message. */
1603	fatal("Permission denied.");
1604	/* NOTREACHED */
1605}
1606
1607/*
1608 * Starts a dialog with the server, and authenticates the current user on the
1609 * server.  This does not need any extra privileges.  The basic connection
1610 * to the server must already have been established before this is called.
1611 * If login fails, this function prints an error and never returns.
1612 * This function does not require super-user privileges.
1613 */
1614void
1615ssh_login(int host_key_valid, RSA *own_host_key, const char *orighost,
1616    struct sockaddr *hostaddr, uid_t original_real_uid)
1617{
1618	char *host, *cp;
1619
1620	/* Convert the user-supplied hostname into all lowercase. */
1621	host = xstrdup(orighost);
1622	for (cp = host; *cp; cp++)
1623		if (isupper(*cp))
1624			*cp = tolower(*cp);
1625
1626	/* Exchange protocol version identification strings with the server. */
1627	ssh_exchange_identification();
1628
1629	/* Put the connection into non-blocking mode. */
1630	packet_set_nonblocking();
1631
1632	supported_authentications = 0;
1633	/* key exchange */
1634	ssh_kex(host, hostaddr);
1635	if (supported_authentications == 0)
1636		fatal("supported_authentications == 0.");
1637	/* authenticate user */
1638	ssh_userauth(host_key_valid, own_host_key, original_real_uid, host);
1639}
1640