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