5 Author: Tatu Ylonen <ylo@cs.hut.fi>
7 Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 Created: Sat Mar 18 22:15:47 1995 ylo
12 Code to connect to a remote host, and to perform the client side of the
13 login (authentication) dialog.
22 #include <openssl/bn.h>
23 #include <openssl/md5.h>
41 /* Session id for the current session. */
42 unsigned char session_id[16];
44 /* Connect to the given ssh server using a proxy command. */
47 ssh_proxy_connect(const char *host, int port, uid_t original_real_uid,
48 const char *proxy_command)
57 /* Convert the port number into a string. */
58 snprintf(portstring, sizeof portstring, "%d", port);
60 /* Build the final command string in the buffer by making the appropriate
61 substitutions to the given proxy command. */
62 buffer_init(&command);
63 for (cp = proxy_command; *cp; cp++)
65 if (cp[0] == '%' && cp[1] == '%')
67 buffer_append(&command, "%", 1);
71 if (cp[0] == '%' && cp[1] == 'h')
73 buffer_append(&command, host, strlen(host));
77 if (cp[0] == '%' && cp[1] == 'p')
79 buffer_append(&command, portstring, strlen(portstring));
83 buffer_append(&command, cp, 1);
85 buffer_append(&command, "\0", 1);
87 /* Get the final command string. */
88 command_string = buffer_ptr(&command);
90 /* Create pipes for communicating with the proxy. */
91 if (pipe(pin) < 0 || pipe(pout) < 0)
92 fatal("Could not create pipes to communicate with the proxy: %.100s",
95 debug("Executing proxy command: %.500s", command_string);
97 /* Fork and execute the proxy command. */
98 if ((pid = fork()) == 0)
102 /* Child. Permanently give up superuser privileges. */
103 permanently_set_uid(original_real_uid);
105 /* Redirect stdin and stdout. */
109 if (dup2(pin[0], 0) < 0)
110 perror("dup2 stdin");
114 if (dup2(pout[1], 1) < 0)
115 perror("dup2 stdout");
116 close(pout[1]); /* Cannot be 1 because pin allocated two descriptors. */
118 /* Stderr is left as it is so that error messages get printed on
119 the user's terminal. */
122 argv[2] = command_string;
125 /* Execute the proxy command. Note that we gave up any extra
127 execv("/bin/sh", argv);
133 fatal("fork failed: %.100s", strerror(errno));
135 /* Close child side of the descriptors. */
139 /* Free the command name. */
140 buffer_free(&command);
142 /* Set the connection file descriptors. */
143 packet_set_connection(pout[0], pin[1]);
148 /* Creates a (possibly privileged) socket for use as the ssh connection. */
150 int ssh_create_socket(uid_t original_real_uid, int privileged)
154 /* If we are running as root and want to connect to a privileged port,
155 bind our own socket to a privileged port. */
158 int p = IPPORT_RESERVED - 1;
160 sock = rresvport(&p);
162 fatal("rresvport: %.100s", strerror(errno));
163 debug("Allocated local port %d.", p);
167 /* Just create an ordinary socket on arbitrary port. We use the
168 user's uid to create the socket. */
169 temporarily_use_uid(original_real_uid);
170 sock = socket(AF_INET, SOCK_STREAM, 0);
172 fatal("socket: %.100s", strerror(errno));
178 /* Opens a TCP/IP connection to the remote server on the given host. If
179 port is 0, the default port will be used. If anonymous is zero,
180 a privileged port will be allocated to make the connection.
181 This requires super-user privileges if anonymous is false.
182 Connection_attempts specifies the maximum number of tries (one per
183 second). If proxy_command is non-NULL, it specifies the command (with %h
184 and %p substituted for host and port, respectively) to use to contact
187 int ssh_connect(const char *host, struct sockaddr_in *hostaddr,
188 int port, int connection_attempts,
189 int anonymous, uid_t original_real_uid,
190 const char *proxy_command)
192 int sock = -1, attempt, i;
196 struct linger linger;
198 debug("ssh_connect: getuid %d geteuid %d anon %d",
199 (int)getuid(), (int)geteuid(), anonymous);
201 /* Get default port if port has not been set. */
204 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
206 port = ntohs(sp->s_port);
208 port = SSH_DEFAULT_PORT;
211 /* If a proxy command is given, connect using it. */
212 if (proxy_command != NULL)
213 return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
215 /* No proxy command. */
217 /* No host lookup made yet. */
220 /* Try to connect several times. On some machines, the first time will
221 sometimes fail. In general socket code appears to behave quite
222 magically on many machines. */
223 for (attempt = 0; attempt < connection_attempts; attempt++)
226 debug("Trying again...");
228 /* Try to parse the host name as a numeric inet address. */
229 memset(hostaddr, 0, sizeof(hostaddr));
230 hostaddr->sin_family = AF_INET;
231 hostaddr->sin_port = htons(port);
232 hostaddr->sin_addr.s_addr = inet_addr(host);
233 if ((hostaddr->sin_addr.s_addr & 0xffffffff) != 0xffffffff)
235 /* Valid numeric IP address */
236 debug("Connecting to %.100s port %d.",
237 inet_ntoa(hostaddr->sin_addr), port);
239 /* Create a socket. */
240 sock = ssh_create_socket(original_real_uid,
241 !anonymous && geteuid() == 0 &&
242 port < IPPORT_RESERVED);
244 /* Connect to the host. We use the user's uid in the hope that
245 it will help with the problems of tcp_wrappers showing the
246 remote uid as root. */
247 temporarily_use_uid(original_real_uid);
248 if (connect(sock, (struct sockaddr *)hostaddr, sizeof(*hostaddr))
251 /* Successful connect. */
255 debug("connect: %.100s", strerror(errno));
258 /* Destroy the failed socket. */
259 shutdown(sock, SHUT_RDWR);
264 /* Not a valid numeric inet address. */
265 /* Map host name to an address. */
267 hp = gethostbyname(host);
269 fatal("Bad host name: %.100s", host);
270 if (!hp->h_addr_list[0])
271 fatal("Host does not have an IP address: %.100s", host);
273 /* Loop through addresses for this host, and try each one in
274 sequence until the connection succeeds. */
275 for (i = 0; hp->h_addr_list[i]; i++)
277 /* Set the address to connect to. */
278 hostaddr->sin_family = hp->h_addrtype;
279 memcpy(&hostaddr->sin_addr, hp->h_addr_list[i],
280 sizeof(hostaddr->sin_addr));
282 debug("Connecting to %.200s [%.100s] port %d.",
283 host, inet_ntoa(hostaddr->sin_addr), port);
285 /* Create a socket for connecting. */
286 sock = ssh_create_socket(original_real_uid,
287 !anonymous && geteuid() == 0 &&
288 port < IPPORT_RESERVED);
290 /* Connect to the host. We use the user's uid in the hope that
291 it will help with tcp_wrappers showing the remote uid as
293 temporarily_use_uid(original_real_uid);
294 if (connect(sock, (struct sockaddr *)hostaddr,
295 sizeof(*hostaddr)) >= 0)
297 /* Successful connection. */
301 debug("connect: %.100s", strerror(errno));
304 /* Close the failed socket; there appear to be some problems
305 when reusing a socket for which connect() has already
306 returned an error. */
307 shutdown(sock, SHUT_RDWR);
310 if (hp->h_addr_list[i])
311 break; /* Successful connection. */
314 /* Sleep a moment before retrying. */
317 /* Return failure if we didn't get a successful connection. */
318 if (attempt >= connection_attempts)
321 debug("Connection established.");
323 /* Set socket options. We would like the socket to disappear as soon as
324 it has been closed for whatever reason. */
325 /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
326 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void *)&on, sizeof(on));
329 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
331 /* Set the connection. */
332 packet_set_connection(sock, sock);
337 /* Checks if the user has an authentication agent, and if so, tries to
338 authenticate using the agent. */
341 try_agent_authentication()
343 int status, type, bits;
345 AuthenticationConnection *auth;
346 unsigned char response[16];
348 BIGNUM *e, *n, *challenge;
350 /* Get connection to the agent. */
351 auth = ssh_get_authentication_connection();
357 challenge = BN_new();
359 /* Loop through identities served by the agent. */
360 for (status = ssh_get_first_identity(auth, &bits, e, n, &comment);
362 status = ssh_get_next_identity(auth, &bits, e, n, &comment))
366 /* Try this identity. */
367 debug("Trying RSA authentication via agent with '%.100s'", comment);
370 /* Tell the server that we are willing to authenticate using this key. */
371 packet_start(SSH_CMSG_AUTH_RSA);
372 packet_put_bignum(n);
376 /* Wait for server's response. */
377 type = packet_read(&plen);
379 /* The server sends failure if it doesn\'t like our key or does not
380 support RSA authentication. */
381 if (type == SSH_SMSG_FAILURE)
383 debug("Server refused our key.");
387 /* Otherwise it should have sent a challenge. */
388 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
389 packet_disconnect("Protocol error during RSA authentication: %d",
392 packet_get_bignum(challenge, &clen);
394 packet_integrity_check(plen, clen, type);
396 debug("Received RSA challenge from server.");
398 /* Ask the agent to decrypt the challenge. */
399 if (!ssh_decrypt_challenge(auth, bits, e, n, challenge,
400 session_id, 1, response))
402 /* The agent failed to authenticate this identifier although it
403 advertised it supports this. Just return a wrong value. */
404 log("Authentication agent failed to decrypt challenge.");
405 memset(response, 0, sizeof(response));
408 debug("Sending response to RSA challenge.");
410 /* Send the decrypted challenge back to the server. */
411 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
412 for (i = 0; i < 16; i++)
413 packet_put_char(response[i]);
417 /* Wait for response from the server. */
418 type = packet_read(&plen);
420 /* The server returns success if it accepted the authentication. */
421 if (type == SSH_SMSG_SUCCESS)
423 debug("RSA authentication accepted by server.");
426 BN_clear_free(challenge);
430 /* Otherwise it should return failure. */
431 if (type != SSH_SMSG_FAILURE)
432 packet_disconnect("Protocol error waiting RSA auth response: %d",
438 BN_clear_free(challenge);
440 debug("RSA authentication using agent refused.");
444 /* Computes the proper response to a RSA challenge, and sends the response to
448 respond_to_rsa_challenge(BIGNUM *challenge, RSA *prv)
450 unsigned char buf[32], response[16];
454 /* Decrypt the challenge using the private key. */
455 rsa_private_decrypt(challenge, challenge, prv);
457 /* Compute the response. */
458 /* The response is MD5 of decrypted challenge plus session id. */
459 len = BN_num_bytes(challenge);
460 if (len <= 0 || len > sizeof(buf))
461 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
464 memset(buf, 0, sizeof(buf));
465 BN_bn2bin(challenge, buf + sizeof(buf) - len);
467 MD5_Update(&md, buf, 32);
468 MD5_Update(&md, session_id, 16);
469 MD5_Final(response, &md);
471 debug("Sending response to host key RSA challenge.");
473 /* Send the response back to the server. */
474 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
475 for (i = 0; i < 16; i++)
476 packet_put_char(response[i]);
480 memset(buf, 0, sizeof(buf));
481 memset(response, 0, sizeof(response));
482 memset(&md, 0, sizeof(md));
485 /* Checks if the user has authentication file, and if so, tries to authenticate
486 the user using it. */
489 try_rsa_authentication(struct passwd *pw, const char *authfile)
491 extern Options options;
495 char *passphrase, *comment;
499 /* Try to load identification for the authentication key. */
500 public_key = RSA_new();
501 if (!load_public_key(authfile, public_key, &comment)) {
502 RSA_free(public_key);
503 return 0; /* Could not load it. Fail. */
506 debug("Trying RSA authentication with key '%.100s'", comment);
508 /* Tell the server that we are willing to authenticate using this key. */
509 packet_start(SSH_CMSG_AUTH_RSA);
510 packet_put_bignum(public_key->n);
514 /* We no longer need the public key. */
515 RSA_free(public_key);
517 /* Wait for server's response. */
518 type = packet_read(&plen);
520 /* The server responds with failure if it doesn\'t like our key or doesn\'t
521 support RSA authentication. */
522 if (type == SSH_SMSG_FAILURE)
524 debug("Server refused our key.");
526 return 0; /* Server refuses to authenticate with this key. */
529 /* Otherwise, the server should respond with a challenge. */
530 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
531 packet_disconnect("Protocol error during RSA authentication: %d", type);
533 /* Get the challenge from the packet. */
534 challenge = BN_new();
535 packet_get_bignum(challenge, &clen);
537 packet_integrity_check(plen, clen, type);
539 debug("Received RSA challenge from server.");
541 private_key = RSA_new();
542 /* Load the private key. Try first with empty passphrase; if it fails,
543 ask for a passphrase. */
544 if (!load_private_key(authfile, "", private_key, NULL))
547 /* Request passphrase from the user. We read from /dev/tty to make
548 this work even if stdin has been redirected. If running in
549 batch mode, we just use the empty passphrase, which will fail and
551 snprintf(buf, sizeof buf,
552 "Enter passphrase for RSA key '%.100s': ", comment);
553 if (!options.batch_mode)
554 passphrase = read_passphrase(buf, 0);
557 debug("Will not query passphrase for %.100s in batch mode.",
559 passphrase = xstrdup("");
562 /* Load the authentication file using the pasphrase. */
563 if (!load_private_key(authfile, passphrase, private_key, NULL))
565 memset(passphrase, 0, strlen(passphrase));
567 error("Bad passphrase.");
569 /* Send a dummy response packet to avoid protocol error. */
570 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
571 for (i = 0; i < 16; i++)
576 /* Expect the server to reject it... */
577 packet_read_expect(&plen, SSH_SMSG_FAILURE);
582 /* Destroy the passphrase. */
583 memset(passphrase, 0, strlen(passphrase));
587 /* We no longer need the comment. */
590 /* Compute and send a response to the challenge. */
591 respond_to_rsa_challenge(challenge, private_key);
593 /* Destroy the private key. */
594 RSA_free(private_key);
596 /* We no longer need the challenge. */
597 BN_clear_free(challenge);
599 /* Wait for response from the server. */
600 type = packet_read(&plen);
601 if (type == SSH_SMSG_SUCCESS)
603 debug("RSA authentication accepted by server.");
606 if (type != SSH_SMSG_FAILURE)
607 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
608 debug("RSA authentication refused.");
612 /* Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
613 authentication and RSA host authentication. */
616 try_rhosts_rsa_authentication(const char *local_user, RSA *host_key)
622 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
624 /* Tell the server that we are willing to authenticate using this key. */
625 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
626 packet_put_string(local_user, strlen(local_user));
627 packet_put_int(BN_num_bits(host_key->n));
628 packet_put_bignum(host_key->e);
629 packet_put_bignum(host_key->n);
633 /* Wait for server's response. */
634 type = packet_read(&plen);
636 /* The server responds with failure if it doesn't admit our .rhosts
637 authentication or doesn't know our host key. */
638 if (type == SSH_SMSG_FAILURE)
640 debug("Server refused our rhosts authentication or host key.");
641 return 0; /* Server refuses to authenticate us with this method. */
644 /* Otherwise, the server should respond with a challenge. */
645 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
646 packet_disconnect("Protocol error during RSA authentication: %d", type);
648 /* Get the challenge from the packet. */
649 challenge = BN_new();
650 packet_get_bignum(challenge, &clen);
652 packet_integrity_check(plen, clen, type);
654 debug("Received RSA challenge for host key from server.");
656 /* Compute a response to the challenge. */
657 respond_to_rsa_challenge(challenge, host_key);
659 /* We no longer need the challenge. */
660 BN_clear_free(challenge);
662 /* Wait for response from the server. */
663 type = packet_read(&plen);
664 if (type == SSH_SMSG_SUCCESS)
666 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
669 if (type != SSH_SMSG_FAILURE)
670 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
671 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
676 int try_kerberos_authentication()
678 KTEXT_ST auth; /* Kerberos data */
684 Key_schedule schedule;
685 u_long checksum, cksum;
687 struct sockaddr_in local, foreign;
690 /* Don't do anything if we don't have any tickets. */
691 if (stat(tkt_string(), &st) < 0) return 0;
693 strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
695 realm = (char *)krb_realmofhost(get_canonical_hostname());
697 debug("Kerberos V4: no realm for %s", get_canonical_hostname());
700 /* This can really be anything. */
701 checksum = (u_long) getpid();
703 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
705 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
708 /* Get session key to decrypt the server's reply with. */
709 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
711 debug("get_cred failed: %s", krb_err_txt[r]);
714 des_key_sched((des_cblock *)cred.session, schedule);
716 /* Send authentication info to server. */
717 packet_start(SSH_CMSG_AUTH_KERBEROS);
718 packet_put_string((char *)auth.dat, auth.length);
722 /* Zero the buffer. */
723 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
726 memset(&local, 0, sizeof(local));
727 if (getsockname(packet_get_connection_in(),
728 (struct sockaddr *) &local, &r) < 0)
729 debug("getsockname failed: %s", strerror(errno));
732 memset(&foreign, 0, sizeof(foreign));
733 if (getpeername(packet_get_connection_in(),
734 (struct sockaddr *)&foreign, &r) < 0)
735 debug("getpeername failed: %s", strerror(errno));
737 /* Get server reply. */
738 type = packet_read(&plen);
741 case SSH_SMSG_FAILURE: /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
742 debug("Kerberos V4 authentication failed.");
746 case SSH_SMSG_AUTH_KERBEROS_RESPONSE: /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
747 debug("Kerberos V4 authentication accepted.");
749 /* Get server's response. */
750 reply = packet_get_string((unsigned int *)&auth.length);
751 memcpy(auth.dat, reply, auth.length);
754 packet_integrity_check(plen, 4 + auth.length, type);
756 /* If his response isn't properly encrypted with the session key,
757 and the decrypted checksum fails to match, he's bogus. Bail out. */
758 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
759 &foreign, &local, &msg_data);
761 debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
762 packet_disconnect("Kerberos V4 challenge failed!");
764 /* Fetch the (incremented) checksum that we supplied in the request. */
765 (void)memcpy((char *)&cksum, (char *)msg_data.app_data, sizeof(cksum));
766 cksum = ntohl(cksum);
768 /* If it matches, we're golden. */
769 if (cksum == checksum + 1) {
770 debug("Kerberos V4 challenge successful.");
774 packet_disconnect("Kerberos V4 challenge failed!");
778 packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
785 int send_kerberos_tgt()
788 char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
790 unsigned char buffer[8192];
793 /* Don't do anything if we don't have any tickets. */
794 if (stat(tkt_string(), &st) < 0) return 0;
796 creds = xmalloc(sizeof(*creds));
798 if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
799 debug("Kerberos V4 tf_fullname failed: %s",krb_err_txt[r]);
802 if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
803 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
806 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
807 debug("Kerberos V4 ticket expired: %s", TKT_FILE);
811 creds_to_radix(creds, buffer);
814 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
815 packet_put_string((char *)buffer, strlen(buffer));
819 type = packet_read(&plen);
821 if (type == SSH_SMSG_FAILURE)
822 debug("Kerberos TGT for realm %s rejected.", prealm);
823 else if (type != SSH_SMSG_SUCCESS)
824 packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
829 void send_afs_tokens(void)
832 struct ViceIoctl parms;
833 struct ClearToken ct;
834 int i, type, len, plen;
835 char buf[2048], *p, *server_cell;
836 unsigned char buffer[8192];
838 /* Move over ktc_GetToken, here's something leaner. */
839 for (i = 0; i < 100; i++) { /* just in case */
840 parms.in = (char *)&i;
841 parms.in_size = sizeof(i);
843 parms.out_size = sizeof(buf);
844 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0) break;
847 /* Get secret token. */
848 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
849 if (creds.ticket_st.length > MAX_KTXT_LEN) break;
850 p += sizeof(unsigned int);
851 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
852 p += creds.ticket_st.length;
854 /* Get clear token. */
855 memcpy(&len, p, sizeof(len));
856 if (len != sizeof(struct ClearToken)) break;
860 p += sizeof(len); /* primary flag */
863 /* Flesh out our credentials. */
864 strlcpy(creds.service, "afs", sizeof creds.service);
865 creds.instance[0] = '\0';
866 strlcpy(creds.realm, server_cell, REALM_SZ);
867 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
868 creds.issue_date = ct.BeginTimestamp;
869 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
870 creds.kvno = ct.AuthHandle;
871 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
872 creds.pinst[0] = '\0';
874 /* Encode token, ship it off. */
875 if (!creds_to_radix(&creds, buffer)) break;
876 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
877 packet_put_string((char *)buffer, strlen(buffer));
881 /* Roger, Roger. Clearance, Clarence. What's your vector, Victor? */
882 type = packet_read(&plen);
884 if (type == SSH_SMSG_FAILURE)
885 debug("AFS token for cell %s rejected.", server_cell);
886 else if (type != SSH_SMSG_SUCCESS)
887 packet_disconnect("Protocol error on AFS token response: %d", type);
892 /* Waits for the server identification string, and sends our own identification
895 void ssh_exchange_identification()
897 char buf[256], remote_version[256]; /* must be same size! */
898 int remote_major, remote_minor, i;
899 int connection_in = packet_get_connection_in();
900 int connection_out = packet_get_connection_out();
901 extern Options options;
903 /* Read other side\'s version identification. */
904 for (i = 0; i < sizeof(buf) - 1; i++)
906 if (read(connection_in, &buf[i], 1) != 1)
907 fatal("read: %.100s", strerror(errno));
920 buf[sizeof(buf) - 1] = 0;
922 /* Check that the versions match. In future this might accept several
923 versions and set appropriate flags to handle them. */
924 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
925 remote_version) != 3)
926 fatal("Bad remote protocol version identification: '%.100s'", buf);
927 debug("Remote protocol version %d.%d, remote software version %.100s",
928 remote_major, remote_minor, remote_version);
930 /* Check if the remote protocol version is too old. */
931 if (remote_major == 1 && remote_minor < 3)
932 fatal("Remote machine has too old SSH software version.");
934 /* We speak 1.3, too. */
935 if (remote_major == 1 && remote_minor == 3) {
937 if (options.forward_agent && strcmp(remote_version, SSH_VERSION) != 0) {
938 log("Agent forwarding disabled, remote version '%s' is not compatible.",
940 options.forward_agent = 0;
944 /* Removed for now, to permit compatibility with latter versions. The server
945 will reject our version and disconnect if it doesn't support it. */
946 if (remote_major != PROTOCOL_MAJOR)
947 fatal("Protocol major versions differ: %d vs. %d",
948 PROTOCOL_MAJOR, remote_major);
951 /* Send our own protocol version identification. */
952 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
953 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
954 if (write(connection_out, buf, strlen(buf)) != strlen(buf))
955 fatal("write: %.100s", strerror(errno));
958 int ssh_cipher_default = SSH_CIPHER_3DES;
960 int read_yes_or_no(const char *prompt, int defval)
969 f = fopen("/dev/tty", "rw");
978 fprintf(stderr, "%s", prompt);
979 if (fgets(buf, sizeof(buf), f) == NULL)
981 /* Print a newline (the prompt probably didn\'t have one). */
982 fprintf(stderr, "\n");
983 strlcpy(buf, "no", sizeof buf);
985 /* Remove newline from response. */
986 if (strchr(buf, '\n'))
987 *strchr(buf, '\n') = 0;
991 if (strcmp(buf, "yes") == 0)
993 if (strcmp(buf, "no") == 0)
1005 /* Starts a dialog with the server, and authenticates the current user on the
1006 server. This does not need any extra privileges. The basic connection
1007 to the server must already have been established before this is called.
1008 User is the remote user; if it is NULL, the current local user name will
1009 be used. Anonymous indicates that no rhosts authentication will be used.
1010 If login fails, this function prints an error and never returns.
1011 This function does not require super-user privileges. */
1013 void ssh_login(int host_key_valid,
1015 const char *orighost,
1016 struct sockaddr_in *hostaddr,
1017 uid_t original_real_uid)
1019 extern Options options;
1024 RSA *host_key, *file_key;
1027 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1028 const char *server_user, *local_user;
1029 char *cp, *host, *ip = NULL;
1030 unsigned char check_bytes[8];
1031 unsigned int supported_ciphers, supported_authentications, protocol_flags;
1032 HostStatus host_status;
1033 HostStatus ip_status;
1034 int host_ip_differ = 0;
1035 int local = (ntohl(hostaddr->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
1036 int payload_len, clen, sum_len = 0;
1039 if (options.check_host_ip)
1040 ip = xstrdup(inet_ntoa(hostaddr->sin_addr));
1042 /* Convert the user-supplied hostname into all lowercase. */
1043 host = xstrdup(orighost);
1044 for (cp = host; *cp; cp++)
1048 /* Exchange protocol version identification strings with the server. */
1049 ssh_exchange_identification();
1051 /* Put the connection into non-blocking mode. */
1052 packet_set_nonblocking();
1054 /* Get local user name. Use it as server user if no user name
1056 pw = getpwuid(original_real_uid);
1058 fatal("User id %d not found from user database.", original_real_uid);
1059 local_user = xstrdup(pw->pw_name);
1060 server_user = options.user ? options.user : local_user;
1062 debug("Waiting for server public key.");
1064 /* Wait for a public key packet from the server. */
1065 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1067 /* Get check bytes from the packet. */
1068 for (i = 0; i < 8; i++)
1069 check_bytes[i] = packet_get_char();
1071 /* Get the public key. */
1072 public_key = RSA_new();
1073 bits = packet_get_int(); /* bits */
1074 public_key->e = BN_new();
1075 packet_get_bignum(public_key->e, &clen);
1077 public_key->n = BN_new();
1078 packet_get_bignum(public_key->n, &clen);
1081 rbits = BN_num_bits(public_key->n);
1082 if (bits != rbits) {
1083 log("Warning: Server lies about size of server public key,");
1084 log("Warning: this may be due to an old implementation of ssh.");
1085 log("Warning: (actual size %d bits, announced size %d bits)", rbits, bits);
1088 /* Get the host key. */
1089 host_key = RSA_new();
1090 bits = packet_get_int(); /* bits */
1091 host_key->e = BN_new();
1092 packet_get_bignum(host_key->e, &clen);
1094 host_key->n = BN_new();
1095 packet_get_bignum(host_key->n, &clen);
1098 rbits = BN_num_bits(host_key->n);
1099 if (bits != rbits) {
1100 log("Warning: Server lies about size of server host key,");
1101 log("Warning: this may be due to an old implementation of ssh.");
1102 log("Warning: (actual size %d bits, announced size %d bits)", rbits, bits);
1105 /* Store the host key from the known host file in here
1106 * so that we can compare it with the key for the IP
1108 file_key = RSA_new();
1109 file_key->n = BN_new();
1110 file_key->e = BN_new();
1112 /* Get protocol flags. */
1113 protocol_flags = packet_get_int();
1114 packet_set_protocol_flags(protocol_flags);
1116 /* Get supported cipher types. */
1117 supported_ciphers = packet_get_int();
1119 /* Get supported authentication types. */
1120 supported_authentications = packet_get_int();
1122 debug("Received server public key (%d bits) and host key (%d bits).",
1123 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1125 packet_integrity_check(payload_len,
1126 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1127 SSH_SMSG_PUBLIC_KEY);
1129 /* Compute the session id. */
1130 compute_session_id(session_id, check_bytes,
1131 BN_num_bits(host_key->n), host_key->n,
1132 BN_num_bits(public_key->n), public_key->n);
1134 /* Check if the host key is present in the user\'s list of known hosts
1135 or in the systemwide list. */
1136 host_status = check_host_in_hostfile(options.user_hostfile,
1137 host, BN_num_bits(host_key->n),
1138 host_key->e, host_key->n,
1139 file_key->e, file_key->n);
1140 if (host_status == HOST_NEW)
1141 host_status = check_host_in_hostfile(options.system_hostfile, host,
1142 BN_num_bits(host_key->n),
1143 host_key->e, host_key->n,
1144 file_key->e, file_key->n);
1145 /* Force accepting of the host key for localhost and 127.0.0.1.
1146 The problem is that if the home directory is NFS-mounted to multiple
1147 machines, localhost will refer to a different machine in each of them,
1148 and the user will get bogus HOST_CHANGED warnings. This essentially
1149 disables host authentication for localhost; however, this is probably
1150 not a real problem. */
1152 debug("Forcing accepting of host key for localhost.");
1153 host_status = HOST_OK;
1156 /* Also perform check for the ip address, skip the check if we are
1157 localhost or the hostname was an ip address to begin with */
1158 if (options.check_host_ip && !local && strcmp(host, ip)) {
1159 RSA *ip_key = RSA_new();
1160 ip_key->n = BN_new();
1161 ip_key->e = BN_new();
1162 ip_status = check_host_in_hostfile(options.user_hostfile, ip,
1163 BN_num_bits(host_key->n),
1164 host_key->e, host_key->n,
1165 ip_key->e, ip_key->n);
1167 if (ip_status == HOST_NEW)
1168 ip_status = check_host_in_hostfile(options.system_hostfile, ip,
1169 BN_num_bits(host_key->n),
1170 host_key->e, host_key->n,
1171 ip_key->e, ip_key->n);
1172 if (host_status == HOST_CHANGED &&
1173 (ip_status != HOST_CHANGED ||
1174 (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n))))
1179 ip_status = host_status;
1183 switch (host_status) {
1185 /* The host is known and the key matches. */
1186 debug("Host '%.200s' is known and matches the host key.", host);
1187 if (options.check_host_ip) {
1188 if (ip_status == HOST_NEW) {
1189 if (!add_host_to_hostfile(options.user_hostfile, ip,
1190 BN_num_bits(host_key->n),
1191 host_key->e, host_key->n))
1192 log("Failed to add the host ip to the list of known hosts (%.30s).",
1193 options.user_hostfile);
1195 log("Warning: Permanently added host ip '%.30s' to the list of known hosts.", ip);
1196 } else if (ip_status != HOST_OK)
1197 log("Warning: the host key differ from the key of the ip address '%.30s' differs", ip);
1203 char hostline[1000], *hostp = hostline;
1204 /* The host is new. */
1205 if (options.strict_host_key_checking == 1) {
1206 /* User has requested strict host key checking. We will not
1207 add the host key automatically. The only alternative left
1209 fatal("No host key is known for %.200s and you have requested strict checking.", host);
1210 } else if (options.strict_host_key_checking == 2) { /* The default */
1212 snprintf(prompt, sizeof(prompt),
1213 "The authenticity of host '%.200s' can't be established.\n"
1214 "Are you sure you want to continue connecting (yes/no)? ",
1216 if (!read_yes_or_no(prompt, -1))
1217 fatal("Aborted by user!\n");
1220 if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip))
1221 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1225 /* If not in strict mode, add the key automatically to the local
1226 known_hosts file. */
1227 if (!add_host_to_hostfile(options.user_hostfile, hostp,
1228 BN_num_bits(host_key->n),
1229 host_key->e, host_key->n))
1230 log("Failed to add the host to the list of known hosts (%.500s).",
1231 options.user_hostfile);
1233 log("Warning: Permanently added '%.200s' to the list of known hosts.",
1238 if (options.check_host_ip) {
1239 if (host_ip_differ) {
1240 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1241 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1242 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1243 error("The host key for %s has changed,", host);
1244 error("but the key for the according IP address %s has", ip);
1245 error("a different status. This could either mean that DNS");
1246 error("SPOOFING is happening or the IP address for the host");
1247 error("and its host key have changed at the same time");
1251 /* The host key has changed. */
1252 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1253 error("@ WARNING: HOST IDENTIFICATION HAS CHANGED! @");
1254 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1255 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1256 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1257 error("It is also possible that the host key has just been changed.");
1258 error("Please contact your system administrator.");
1259 error("Add correct host key in %.100s to get rid of this message.",
1260 options.user_hostfile);
1262 /* If strict host key checking is in use, the user will have to edit
1263 the key manually and we can only abort. */
1264 if (options.strict_host_key_checking)
1265 fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1267 /* If strict host key checking has not been requested, allow the
1268 connection but without password authentication or
1269 agent forwarding. */
1270 if (options.password_authentication) {
1271 error("Password authentication is disabled to avoid trojan horses.");
1272 options.password_authentication = 0;
1274 if (options.forward_agent) {
1275 error("Agent forwarding is disabled to avoid trojan horses.");
1276 options.forward_agent = 0;
1278 /* XXX Should permit the user to change to use the new id. This could
1279 be done by converting the host key to an identifying sentence, tell
1280 that the host identifies itself by that sentence, and ask the user
1281 if he/she whishes to accept the authentication. */
1285 if (options.check_host_ip)
1288 /* Generate a session key. */
1291 /* Generate an encryption key for the session. The key is a 256 bit
1292 random number, interpreted as a 32-byte key, with the least significant
1293 8 bits being the first byte of the key. */
1294 for (i = 0; i < 32; i++) {
1296 rand = arc4random();
1297 session_key[i] = rand & 0xff;
1301 /* According to the protocol spec, the first byte of the session key is
1302 the highest byte of the integer. The session key is xored with the
1303 first 16 bytes of the session id. */
1305 BN_set_word(key, 0);
1306 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++)
1308 BN_lshift(key, key, 8);
1310 BN_add_word(key, session_key[i] ^ session_id[i]);
1312 BN_add_word(key, session_key[i]);
1315 /* Encrypt the integer using the public key and host key of the server
1316 (key with smaller modulus first). */
1317 if (BN_cmp(public_key->n, host_key->n) < 0)
1319 /* Public key has smaller modulus. */
1320 if (BN_num_bits(host_key->n) <
1321 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1322 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1323 "SSH_KEY_BITS_RESERVED %d",
1324 BN_num_bits(host_key->n),
1325 BN_num_bits(public_key->n),
1326 SSH_KEY_BITS_RESERVED);
1329 rsa_public_encrypt(key, key, public_key);
1330 rsa_public_encrypt(key, key, host_key);
1334 /* Host key has smaller modulus (or they are equal). */
1335 if (BN_num_bits(public_key->n) <
1336 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1337 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1338 "SSH_KEY_BITS_RESERVED %d",
1339 BN_num_bits(public_key->n),
1340 BN_num_bits(host_key->n),
1341 SSH_KEY_BITS_RESERVED);
1344 rsa_public_encrypt(key, key, host_key);
1345 rsa_public_encrypt(key, key, public_key);
1348 if (options.cipher == SSH_CIPHER_NOT_SET) {
1349 if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1350 options.cipher = ssh_cipher_default;
1352 debug("Cipher %d not supported, using %.100s instead.",
1353 cipher_name(ssh_cipher_default),
1354 cipher_name(SSH_FALLBACK_CIPHER));
1355 options.cipher = SSH_FALLBACK_CIPHER;
1359 /* Check that the selected cipher is supported. */
1360 if (!(supported_ciphers & (1 << options.cipher)))
1361 fatal("Selected cipher type %.100s not supported by server.",
1362 cipher_name(options.cipher));
1364 debug("Encryption type: %.100s", cipher_name(options.cipher));
1366 /* Send the encrypted session key to the server. */
1367 packet_start(SSH_CMSG_SESSION_KEY);
1368 packet_put_char(options.cipher);
1370 /* Send the check bytes back to the server. */
1371 for (i = 0; i < 8; i++)
1372 packet_put_char(check_bytes[i]);
1374 /* Send the encrypted encryption key. */
1375 packet_put_bignum(key);
1377 /* Send protocol flags. */
1378 packet_put_int(SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1380 /* Send the packet now. */
1382 packet_write_wait();
1384 /* Destroy the session key integer and the public keys since we no longer
1387 RSA_free(public_key);
1390 debug("Sent encrypted session key.");
1392 /* Set the encryption key. */
1393 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH,
1396 /* We will no longer need the session key here. Destroy any extra copies. */
1397 memset(session_key, 0, sizeof(session_key));
1399 /* Expect a success message from the server. Note that this message will
1400 be received in encrypted form. */
1401 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1403 debug("Received encrypted confirmation.");
1405 /* Send the name of the user to log in as on the server. */
1406 packet_start(SSH_CMSG_USER);
1407 packet_put_string(server_user, strlen(server_user));
1409 packet_write_wait();
1411 /* The server should respond with success if no authentication is needed
1412 (the user has no password). Otherwise the server responds with
1414 type = packet_read(&payload_len);
1415 if (type == SSH_SMSG_SUCCESS)
1416 return; /* Connection was accepted without authentication. */
1417 if (type != SSH_SMSG_FAILURE)
1418 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1422 /* Try Kerberos tgt passing if the server supports it. */
1423 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1424 options.kerberos_tgt_passing)
1426 if (options.cipher == SSH_CIPHER_NONE)
1427 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1428 (void)send_kerberos_tgt();
1431 /* Try AFS token passing if the server supports it. */
1432 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1433 options.afs_token_passing && k_hasafs()) {
1434 if (options.cipher == SSH_CIPHER_NONE)
1435 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1441 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1442 options.kerberos_authentication)
1444 debug("Trying Kerberos authentication.");
1445 if (try_kerberos_authentication()) {
1446 /* The server should respond with success or failure. */
1447 type = packet_read(&payload_len);
1448 if (type == SSH_SMSG_SUCCESS)
1449 return; /* Successful connection. */
1450 if (type != SSH_SMSG_FAILURE)
1451 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1456 /* Use rhosts authentication if running in privileged socket and we do not
1457 wish to remain anonymous. */
1458 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1459 options.rhosts_authentication)
1461 debug("Trying rhosts authentication.");
1462 packet_start(SSH_CMSG_AUTH_RHOSTS);
1463 packet_put_string(local_user, strlen(local_user));
1465 packet_write_wait();
1467 /* The server should respond with success or failure. */
1468 type = packet_read(&payload_len);
1469 if (type == SSH_SMSG_SUCCESS)
1470 return; /* Successful connection. */
1471 if (type != SSH_SMSG_FAILURE)
1472 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1476 /* Try .rhosts or /etc/hosts.equiv authentication with RSA host
1478 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1479 options.rhosts_rsa_authentication && host_key_valid)
1481 if (try_rhosts_rsa_authentication(local_user, own_host_key))
1482 return; /* Successful authentication. */
1485 /* Try RSA authentication if the server supports it. */
1486 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1487 options.rsa_authentication)
1489 /* Try RSA authentication using the authentication agent. The agent
1490 is tried first because no passphrase is needed for it, whereas
1491 identity files may require passphrases. */
1492 if (try_agent_authentication())
1493 return; /* Successful connection. */
1495 /* Try RSA authentication for each identity. */
1496 for (i = 0; i < options.num_identity_files; i++)
1497 if (try_rsa_authentication(pw, options.identity_files[i]))
1498 return; /* Successful connection. */
1501 /* Try password authentication if the server supports it. */
1502 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1503 options.password_authentication && !options.batch_mode)
1506 snprintf(prompt, sizeof(prompt), "%.30s@%.30s's password: ",
1508 debug("Doing password authentication.");
1509 if (options.cipher == SSH_CIPHER_NONE)
1510 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
1511 for (i = 0; i < options.number_of_password_prompts; i++) {
1513 error("Permission denied, please try again.");
1514 password = read_passphrase(prompt, 0);
1515 packet_start(SSH_CMSG_AUTH_PASSWORD);
1516 packet_put_string(password, strlen(password));
1517 memset(password, 0, strlen(password));
1520 packet_write_wait();
1522 type = packet_read(&payload_len);
1523 if (type == SSH_SMSG_SUCCESS)
1524 return; /* Successful connection. */
1525 if (type != SSH_SMSG_FAILURE)
1526 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
1530 /* All authentication methods have failed. Exit with an error message. */
1531 fatal("Permission denied.");