2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Created: Sat Mar 18 22:15:47 1995 ylo
6 * Code to connect to a remote host, and to perform the client side of the
7 * login (authentication) dialog.
14 #include <openssl/bn.h>
15 #include <openssl/md5.h>
32 #include "fingerprint.h"
34 /* Session id for the current session. */
35 unsigned char session_id[16];
38 * Connect to the given ssh server using a proxy command.
41 ssh_proxy_connect(const char *host, int port, uid_t original_real_uid,
42 const char *proxy_command)
51 /* Convert the port number into a string. */
52 snprintf(portstring, sizeof portstring, "%d", port);
54 /* Build the final command string in the buffer by making the
55 appropriate substitutions to the given proxy command. */
56 buffer_init(&command);
57 for (cp = proxy_command; *cp; cp++) {
58 if (cp[0] == '%' && cp[1] == '%') {
59 buffer_append(&command, "%", 1);
63 if (cp[0] == '%' && cp[1] == 'h') {
64 buffer_append(&command, host, strlen(host));
68 if (cp[0] == '%' && cp[1] == 'p') {
69 buffer_append(&command, portstring, strlen(portstring));
73 buffer_append(&command, cp, 1);
75 buffer_append(&command, "\0", 1);
77 /* Get the final command string. */
78 command_string = buffer_ptr(&command);
80 /* Create pipes for communicating with the proxy. */
81 if (pipe(pin) < 0 || pipe(pout) < 0)
82 fatal("Could not create pipes to communicate with the proxy: %.100s",
85 debug("Executing proxy command: %.500s", command_string);
87 /* Fork and execute the proxy command. */
88 if ((pid = fork()) == 0) {
91 /* Child. Permanently give up superuser privileges. */
92 permanently_set_uid(original_real_uid);
94 /* Redirect stdin and stdout. */
97 if (dup2(pin[0], 0) < 0)
102 if (dup2(pout[1], 1) < 0)
103 perror("dup2 stdout");
104 /* Cannot be 1 because pin allocated two descriptors. */
107 /* Stderr is left as it is so that error messages get
108 printed on the user's terminal. */
111 argv[2] = command_string;
114 /* Execute the proxy command. Note that we gave up any
115 extra privileges above. */
116 execv("/bin/sh", argv);
122 fatal("fork failed: %.100s", strerror(errno));
124 /* Close child side of the descriptors. */
128 /* Free the command name. */
129 buffer_free(&command);
131 /* Set the connection file descriptors. */
132 packet_set_connection(pout[0], pin[1]);
138 * Creates a (possibly privileged) socket for use as the ssh connection.
141 ssh_create_socket(uid_t original_real_uid, int privileged)
146 * If we are running as root and want to connect to a privileged
147 * port, bind our own socket to a privileged port.
150 int p = IPPORT_RESERVED - 1;
152 sock = rresvport(&p);
154 fatal("rresvport: %.100s", strerror(errno));
155 debug("Allocated local port %d.", p);
157 /* Just create an ordinary socket on arbitrary port. We
158 use the user's uid to create the socket. */
159 temporarily_use_uid(original_real_uid);
160 sock = socket(AF_INET, SOCK_STREAM, 0);
162 fatal("socket: %.100s", strerror(errno));
169 * Opens a TCP/IP connection to the remote server on the given host. If
170 * port is 0, the default port will be used. If anonymous is zero,
171 * a privileged port will be allocated to make the connection.
172 * This requires super-user privileges if anonymous is false.
173 * Connection_attempts specifies the maximum number of tries (one per
174 * second). If proxy_command is non-NULL, it specifies the command (with %h
175 * and %p substituted for host and port, respectively) to use to contact
179 ssh_connect(const char *host, struct sockaddr_in * hostaddr,
180 int port, int connection_attempts,
181 int anonymous, uid_t original_real_uid,
182 const char *proxy_command)
184 int sock = -1, attempt, i;
188 struct linger linger;
190 debug("ssh_connect: getuid %d geteuid %d anon %d",
191 (int) getuid(), (int) geteuid(), anonymous);
193 /* Get default port if port has not been set. */
195 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
197 port = ntohs(sp->s_port);
199 port = SSH_DEFAULT_PORT;
201 /* If a proxy command is given, connect using it. */
202 if (proxy_command != NULL)
203 return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
205 /* No proxy command. */
207 /* No host lookup made yet. */
210 /* Try to connect several times. On some machines, the first time
211 will sometimes fail. In general socket code appears to behave
212 quite magically on many machines. */
213 for (attempt = 0; attempt < connection_attempts; attempt++) {
215 debug("Trying again...");
217 /* Try to parse the host name as a numeric inet address. */
218 memset(hostaddr, 0, sizeof(hostaddr));
219 hostaddr->sin_family = AF_INET;
220 hostaddr->sin_port = htons(port);
221 hostaddr->sin_addr.s_addr = inet_addr(host);
222 if ((hostaddr->sin_addr.s_addr & 0xffffffff) != 0xffffffff) {
223 /* Valid numeric IP address */
224 debug("Connecting to %.100s port %d.",
225 inet_ntoa(hostaddr->sin_addr), port);
227 /* Create a socket. */
228 sock = ssh_create_socket(original_real_uid,
229 !anonymous && geteuid() == 0 &&
230 port < IPPORT_RESERVED);
233 * Connect to the host. We use the user's uid in the
234 * hope that it will help with the problems of
235 * tcp_wrappers showing the remote uid as root.
237 temporarily_use_uid(original_real_uid);
238 if (connect(sock, (struct sockaddr *) hostaddr, sizeof(*hostaddr))
240 /* Successful connect. */
244 debug("connect: %.100s", strerror(errno));
247 /* Destroy the failed socket. */
248 shutdown(sock, SHUT_RDWR);
251 /* Not a valid numeric inet address. */
252 /* Map host name to an address. */
254 hp = gethostbyname(host);
256 fatal("Bad host name: %.100s", host);
257 if (!hp->h_addr_list[0])
258 fatal("Host does not have an IP address: %.100s", host);
260 /* Loop through addresses for this host, and try
261 each one in sequence until the connection
263 for (i = 0; hp->h_addr_list[i]; i++) {
264 /* Set the address to connect to. */
265 hostaddr->sin_family = hp->h_addrtype;
266 memcpy(&hostaddr->sin_addr, hp->h_addr_list[i],
267 sizeof(hostaddr->sin_addr));
269 debug("Connecting to %.200s [%.100s] port %d.",
270 host, inet_ntoa(hostaddr->sin_addr), port);
272 /* Create a socket for connecting. */
273 sock = ssh_create_socket(original_real_uid,
274 !anonymous && geteuid() == 0 &&
275 port < IPPORT_RESERVED);
278 * Connect to the host. We use the user's
279 * uid in the hope that it will help with
280 * tcp_wrappers showing the remote uid as
283 temporarily_use_uid(original_real_uid);
284 if (connect(sock, (struct sockaddr *) hostaddr,
285 sizeof(*hostaddr)) >= 0) {
286 /* Successful connection. */
290 debug("connect: %.100s", strerror(errno));
294 * Close the failed socket; there appear to
295 * be some problems when reusing a socket for
296 * which connect() has already returned an
299 shutdown(sock, SHUT_RDWR);
302 if (hp->h_addr_list[i])
303 break; /* Successful connection. */
306 /* Sleep a moment before retrying. */
309 /* Return failure if we didn't get a successful connection. */
310 if (attempt >= connection_attempts)
313 debug("Connection established.");
316 * Set socket options. We would like the socket to disappear as soon
317 * as it has been closed for whatever reason.
319 /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
320 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void *) &on, sizeof(on));
323 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
325 /* Set the connection. */
326 packet_set_connection(sock, sock);
332 * Checks if the user has an authentication agent, and if so, tries to
333 * authenticate using the agent.
336 try_agent_authentication()
340 AuthenticationConnection *auth;
341 unsigned char response[16];
343 BIGNUM *e, *n, *challenge;
345 /* Get connection to the agent. */
346 auth = ssh_get_authentication_connection();
352 challenge = BN_new();
354 /* Loop through identities served by the agent. */
355 for (status = ssh_get_first_identity(auth, e, n, &comment);
357 status = ssh_get_next_identity(auth, e, n, &comment)) {
360 /* Try this identity. */
361 debug("Trying RSA authentication via agent with '%.100s'", comment);
364 /* Tell the server that we are willing to authenticate using this key. */
365 packet_start(SSH_CMSG_AUTH_RSA);
366 packet_put_bignum(n);
370 /* Wait for server's response. */
371 type = packet_read(&plen);
373 /* The server sends failure if it doesn\'t like our key or
374 does not support RSA authentication. */
375 if (type == SSH_SMSG_FAILURE) {
376 debug("Server refused our key.");
379 /* Otherwise it should have sent a challenge. */
380 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
381 packet_disconnect("Protocol error during RSA authentication: %d",
384 packet_get_bignum(challenge, &clen);
386 packet_integrity_check(plen, clen, type);
388 debug("Received RSA challenge from server.");
390 /* Ask the agent to decrypt the challenge. */
391 if (!ssh_decrypt_challenge(auth, e, n, challenge,
392 session_id, 1, response)) {
393 /* The agent failed to authenticate this identifier although it
394 advertised it supports this. Just return a wrong value. */
395 log("Authentication agent failed to decrypt challenge.");
396 memset(response, 0, sizeof(response));
398 debug("Sending response to RSA challenge.");
400 /* Send the decrypted challenge back to the server. */
401 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
402 for (i = 0; i < 16; i++)
403 packet_put_char(response[i]);
407 /* Wait for response from the server. */
408 type = packet_read(&plen);
410 /* The server returns success if it accepted the authentication. */
411 if (type == SSH_SMSG_SUCCESS) {
412 debug("RSA authentication accepted by server.");
415 BN_clear_free(challenge);
418 /* Otherwise it should return failure. */
419 if (type != SSH_SMSG_FAILURE)
420 packet_disconnect("Protocol error waiting RSA auth response: %d",
426 BN_clear_free(challenge);
428 debug("RSA authentication using agent refused.");
433 * Computes the proper response to a RSA challenge, and sends the response to
437 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
439 unsigned char buf[32], response[16];
443 /* Decrypt the challenge using the private key. */
444 rsa_private_decrypt(challenge, challenge, prv);
446 /* Compute the response. */
447 /* The response is MD5 of decrypted challenge plus session id. */
448 len = BN_num_bytes(challenge);
449 if (len <= 0 || len > sizeof(buf))
450 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
453 memset(buf, 0, sizeof(buf));
454 BN_bn2bin(challenge, buf + sizeof(buf) - len);
456 MD5_Update(&md, buf, 32);
457 MD5_Update(&md, session_id, 16);
458 MD5_Final(response, &md);
460 debug("Sending response to host key RSA challenge.");
462 /* Send the response back to the server. */
463 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
464 for (i = 0; i < 16; i++)
465 packet_put_char(response[i]);
469 memset(buf, 0, sizeof(buf));
470 memset(response, 0, sizeof(response));
471 memset(&md, 0, sizeof(md));
475 * Checks if the user has authentication file, and if so, tries to authenticate
479 try_rsa_authentication(struct passwd * pw, const char *authfile)
481 extern Options options;
485 char *passphrase, *comment;
489 /* Try to load identification for the authentication key. */
490 public_key = RSA_new();
491 if (!load_public_key(authfile, public_key, &comment)) {
492 RSA_free(public_key);
493 return 0; /* Could not load it. Fail. */
495 debug("Trying RSA authentication with key '%.100s'", comment);
497 /* Tell the server that we are willing to authenticate using this key. */
498 packet_start(SSH_CMSG_AUTH_RSA);
499 packet_put_bignum(public_key->n);
503 /* We no longer need the public key. */
504 RSA_free(public_key);
506 /* Wait for server's response. */
507 type = packet_read(&plen);
510 * The server responds with failure if it doesn\'t like our key or
511 * doesn\'t support RSA authentication.
513 if (type == SSH_SMSG_FAILURE) {
514 debug("Server refused our key.");
516 return 0; /* Server refuses to authenticate with
519 /* Otherwise, the server should respond with a challenge. */
520 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
521 packet_disconnect("Protocol error during RSA authentication: %d", type);
523 /* Get the challenge from the packet. */
524 challenge = BN_new();
525 packet_get_bignum(challenge, &clen);
527 packet_integrity_check(plen, clen, type);
529 debug("Received RSA challenge from server.");
531 private_key = RSA_new();
533 * Load the private key. Try first with empty passphrase; if it
534 * fails, ask for a passphrase.
536 if (!load_private_key(authfile, "", private_key, NULL)) {
538 snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
540 if (!options.batch_mode)
541 passphrase = read_passphrase(buf, 0);
543 debug("Will not query passphrase for %.100s in batch mode.",
545 passphrase = xstrdup("");
548 /* Load the authentication file using the pasphrase. */
549 if (!load_private_key(authfile, passphrase, private_key, NULL)) {
550 memset(passphrase, 0, strlen(passphrase));
552 error("Bad passphrase.");
554 /* Send a dummy response packet to avoid protocol error. */
555 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
556 for (i = 0; i < 16; i++)
561 /* Expect the server to reject it... */
562 packet_read_expect(&plen, SSH_SMSG_FAILURE);
566 /* Destroy the passphrase. */
567 memset(passphrase, 0, strlen(passphrase));
570 /* We no longer need the comment. */
573 /* Compute and send a response to the challenge. */
574 respond_to_rsa_challenge(challenge, private_key);
576 /* Destroy the private key. */
577 RSA_free(private_key);
579 /* We no longer need the challenge. */
580 BN_clear_free(challenge);
582 /* Wait for response from the server. */
583 type = packet_read(&plen);
584 if (type == SSH_SMSG_SUCCESS) {
585 debug("RSA authentication accepted by server.");
588 if (type != SSH_SMSG_FAILURE)
589 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
590 debug("RSA authentication refused.");
595 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
596 * authentication and RSA host authentication.
599 try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
605 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
607 /* Tell the server that we are willing to authenticate using this key. */
608 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
609 packet_put_string(local_user, strlen(local_user));
610 packet_put_int(BN_num_bits(host_key->n));
611 packet_put_bignum(host_key->e);
612 packet_put_bignum(host_key->n);
616 /* Wait for server's response. */
617 type = packet_read(&plen);
619 /* The server responds with failure if it doesn't admit our
620 .rhosts authentication or doesn't know our host key. */
621 if (type == SSH_SMSG_FAILURE) {
622 debug("Server refused our rhosts authentication or host key.");
625 /* Otherwise, the server should respond with a challenge. */
626 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
627 packet_disconnect("Protocol error during RSA authentication: %d", type);
629 /* Get the challenge from the packet. */
630 challenge = BN_new();
631 packet_get_bignum(challenge, &clen);
633 packet_integrity_check(plen, clen, type);
635 debug("Received RSA challenge for host key from server.");
637 /* Compute a response to the challenge. */
638 respond_to_rsa_challenge(challenge, host_key);
640 /* We no longer need the challenge. */
641 BN_clear_free(challenge);
643 /* Wait for response from the server. */
644 type = packet_read(&plen);
645 if (type == SSH_SMSG_SUCCESS) {
646 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
649 if (type != SSH_SMSG_FAILURE)
650 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
651 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
657 try_kerberos_authentication()
659 KTEXT_ST auth; /* Kerberos data */
665 Key_schedule schedule;
666 u_long checksum, cksum;
668 struct sockaddr_in local, foreign;
671 /* Don't do anything if we don't have any tickets. */
672 if (stat(tkt_string(), &st) < 0)
675 strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
677 realm = (char *) krb_realmofhost(get_canonical_hostname());
679 debug("Kerberos V4: no realm for %s", get_canonical_hostname());
682 /* This can really be anything. */
683 checksum = (u_long) getpid();
685 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
687 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
690 /* Get session key to decrypt the server's reply with. */
691 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
693 debug("get_cred failed: %s", krb_err_txt[r]);
696 des_key_sched((des_cblock *) cred.session, schedule);
698 /* Send authentication info to server. */
699 packet_start(SSH_CMSG_AUTH_KERBEROS);
700 packet_put_string((char *) auth.dat, auth.length);
704 /* Zero the buffer. */
705 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
708 memset(&local, 0, sizeof(local));
709 if (getsockname(packet_get_connection_in(),
710 (struct sockaddr *) & local, &r) < 0)
711 debug("getsockname failed: %s", strerror(errno));
714 memset(&foreign, 0, sizeof(foreign));
715 if (getpeername(packet_get_connection_in(),
716 (struct sockaddr *) & foreign, &r) < 0) {
717 debug("getpeername failed: %s", strerror(errno));
720 /* Get server reply. */
721 type = packet_read(&plen);
723 case SSH_SMSG_FAILURE:
724 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
725 debug("Kerberos V4 authentication failed.");
729 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
730 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
731 debug("Kerberos V4 authentication accepted.");
733 /* Get server's response. */
734 reply = packet_get_string((unsigned int *) &auth.length);
735 memcpy(auth.dat, reply, auth.length);
738 packet_integrity_check(plen, 4 + auth.length, type);
741 * If his response isn't properly encrypted with the session
742 * key, and the decrypted checksum fails to match, he's
745 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
746 &foreign, &local, &msg_data);
748 debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
749 packet_disconnect("Kerberos V4 challenge failed!");
751 /* Fetch the (incremented) checksum that we supplied in the request. */
752 (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
753 cksum = ntohl(cksum);
755 /* If it matches, we're golden. */
756 if (cksum == checksum + 1) {
757 debug("Kerberos V4 challenge successful.");
760 packet_disconnect("Kerberos V4 challenge failed!");
764 packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
776 char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
778 unsigned char buffer[8192];
781 /* Don't do anything if we don't have any tickets. */
782 if (stat(tkt_string(), &st) < 0)
785 creds = xmalloc(sizeof(*creds));
787 if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
788 debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
791 if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
792 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
795 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
796 debug("Kerberos V4 ticket expired: %s", TKT_FILE);
799 creds_to_radix(creds, buffer);
802 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
803 packet_put_string((char *) buffer, strlen(buffer));
807 type = packet_read(&plen);
809 if (type == SSH_SMSG_FAILURE)
810 debug("Kerberos TGT for realm %s rejected.", prealm);
811 else if (type != SSH_SMSG_SUCCESS)
812 packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
818 send_afs_tokens(void)
821 struct ViceIoctl parms;
822 struct ClearToken ct;
823 int i, type, len, plen;
824 char buf[2048], *p, *server_cell;
825 unsigned char buffer[8192];
827 /* Move over ktc_GetToken, here's something leaner. */
828 for (i = 0; i < 100; i++) { /* just in case */
829 parms.in = (char *) &i;
830 parms.in_size = sizeof(i);
832 parms.out_size = sizeof(buf);
833 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
837 /* Get secret token. */
838 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
839 if (creds.ticket_st.length > MAX_KTXT_LEN)
841 p += sizeof(unsigned int);
842 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
843 p += creds.ticket_st.length;
845 /* Get clear token. */
846 memcpy(&len, p, sizeof(len));
847 if (len != sizeof(struct ClearToken))
852 p += sizeof(len); /* primary flag */
855 /* Flesh out our credentials. */
856 strlcpy(creds.service, "afs", sizeof creds.service);
857 creds.instance[0] = '\0';
858 strlcpy(creds.realm, server_cell, REALM_SZ);
859 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
860 creds.issue_date = ct.BeginTimestamp;
861 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
862 creds.kvno = ct.AuthHandle;
863 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
864 creds.pinst[0] = '\0';
866 /* Encode token, ship it off. */
867 if (!creds_to_radix(&creds, buffer))
869 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
870 packet_put_string((char *) buffer, strlen(buffer));
874 /* Roger, Roger. Clearance, Clarence. What's your vector,
876 type = packet_read(&plen);
878 if (type == SSH_SMSG_FAILURE)
879 debug("AFS token for cell %s rejected.", server_cell);
880 else if (type != SSH_SMSG_SUCCESS)
881 packet_disconnect("Protocol error on AFS token response: %d", type);
888 * Waits for the server identification string, and sends our own
889 * identification string.
892 ssh_exchange_identification()
894 char buf[256], remote_version[256]; /* must be same size! */
895 int remote_major, remote_minor, i;
896 int connection_in = packet_get_connection_in();
897 int connection_out = packet_get_connection_out();
898 extern Options options;
900 /* Read other side\'s version identification. */
901 for (i = 0; i < sizeof(buf) - 1; i++) {
902 if (read(connection_in, &buf[i], 1) != 1)
903 fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
904 if (buf[i] == '\r') {
909 if (buf[i] == '\n') {
914 buf[sizeof(buf) - 1] = 0;
917 * Check that the versions match. In future this might accept
918 * several versions and set appropriate flags to handle them.
920 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
921 remote_version) != 3)
922 fatal("Bad remote protocol version identification: '%.100s'", buf);
923 debug("Remote protocol version %d.%d, remote software version %.100s",
924 remote_major, remote_minor, remote_version);
926 /* Check if the remote protocol version is too old. */
927 if (remote_major == 1 && remote_minor < 3)
928 fatal("Remote machine has too old SSH software version.");
930 /* We speak 1.3, too. */
931 if (remote_major == 1 && remote_minor == 3) {
933 if (options.forward_agent && strcmp(remote_version, SSH_VERSION) != 0) {
934 log("Agent forwarding disabled, remote version '%s' is not compatible.",
936 options.forward_agent = 0;
941 * Removed for now, to permit compatibility with latter versions. The
942 * server will reject our version and disconnect if it doesn't
945 if (remote_major != PROTOCOL_MAJOR)
946 fatal("Protocol major versions differ: %d vs. %d",
947 PROTOCOL_MAJOR, remote_major);
950 /* Send our own protocol version identification. */
951 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
952 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
953 if (write(connection_out, buf, strlen(buf)) != strlen(buf))
954 fatal("write: %.100s", strerror(errno));
957 int ssh_cipher_default = SSH_CIPHER_3DES;
960 read_yes_or_no(const char *prompt, int defval)
969 f = fopen("/dev/tty", "rw");
977 fprintf(stderr, "%s", prompt);
978 if (fgets(buf, sizeof(buf), f) == NULL) {
979 /* Print a newline (the prompt probably didn\'t have one). */
980 fprintf(stderr, "\n");
981 strlcpy(buf, "no", sizeof buf);
983 /* Remove newline from response. */
984 if (strchr(buf, '\n'))
985 *strchr(buf, '\n') = 0;
989 if (strcmp(buf, "yes") == 0)
991 if (strcmp(buf, "no") == 0)
1003 * Starts a dialog with the server, and authenticates the current user on the
1004 * server. This does not need any extra privileges. The basic connection
1005 * to the server must already have been established before this is called.
1006 * User is the remote user; if it is NULL, the current local user name will
1007 * be used. Anonymous indicates that no rhosts authentication will be used.
1008 * If login fails, this function prints an error and never returns.
1009 * This function does not require super-user privileges.
1012 ssh_login(int host_key_valid,
1014 const char *orighost,
1015 struct sockaddr_in *hostaddr,
1016 uid_t original_real_uid)
1018 extern Options options;
1023 RSA *host_key, *file_key;
1026 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1027 const char *server_user, *local_user;
1028 char *cp, *host, *ip = NULL;
1029 char hostline[1000], *hostp;
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 was given. */
1055 pw = getpwuid(original_real_uid);
1057 fatal("User id %d not found from user database.", original_real_uid);
1058 local_user = xstrdup(pw->pw_name);
1059 server_user = options.user ? options.user : local_user;
1061 debug("Waiting for server public key.");
1063 /* Wait for a public key packet from the server. */
1064 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1066 /* Get check bytes from the packet. */
1067 for (i = 0; i < 8; i++)
1068 check_bytes[i] = packet_get_char();
1070 /* Get the public key. */
1071 public_key = RSA_new();
1072 bits = packet_get_int();/* bits */
1073 public_key->e = BN_new();
1074 packet_get_bignum(public_key->e, &clen);
1076 public_key->n = BN_new();
1077 packet_get_bignum(public_key->n, &clen);
1080 rbits = BN_num_bits(public_key->n);
1081 if (bits != rbits) {
1082 log("Warning: Server lies about size of server public key: "
1083 "actual size is %d bits vs. announced %d.", rbits, bits);
1084 log("Warning: This may be due to an old implementation of ssh.");
1086 /* Get the host key. */
1087 host_key = RSA_new();
1088 bits = packet_get_int();/* bits */
1089 host_key->e = BN_new();
1090 packet_get_bignum(host_key->e, &clen);
1092 host_key->n = BN_new();
1093 packet_get_bignum(host_key->n, &clen);
1096 rbits = BN_num_bits(host_key->n);
1097 if (bits != rbits) {
1098 log("Warning: Server lies about size of server host key: "
1099 "actual size is %d bits vs. announced %d.", rbits, bits);
1100 log("Warning: This may be due to an old implementation of ssh.");
1102 /* Store the host key from the known host file in here so that we
1103 can compare it with the key for the IP address. */
1104 file_key = RSA_new();
1105 file_key->n = BN_new();
1106 file_key->e = BN_new();
1108 /* Get protocol flags. */
1109 protocol_flags = packet_get_int();
1110 packet_set_protocol_flags(protocol_flags);
1112 supported_ciphers = packet_get_int();
1113 supported_authentications = packet_get_int();
1115 debug("Received server public key (%d bits) and host key (%d bits).",
1116 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1118 packet_integrity_check(payload_len,
1119 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1120 SSH_SMSG_PUBLIC_KEY);
1122 compute_session_id(session_id, check_bytes, host_key->n, public_key->n);
1125 * Check if the host key is present in the user\'s list of known
1126 * hosts or in the systemwide list.
1128 host_status = check_host_in_hostfile(options.user_hostfile, host,
1129 host_key->e, host_key->n,
1130 file_key->e, file_key->n);
1131 if (host_status == HOST_NEW)
1132 host_status = check_host_in_hostfile(options.system_hostfile, host,
1133 host_key->e, host_key->n,
1134 file_key->e, file_key->n);
1136 * Force accepting of the host key for localhost and 127.0.0.1. The
1137 * problem is that if the home directory is NFS-mounted to multiple
1138 * machines, localhost will refer to a different machine in each of
1139 * them, and the user will get bogus HOST_CHANGED warnings. This
1140 * essentially disables host authentication for localhost; however,
1141 * this is probably not a real problem.
1144 debug("Forcing accepting of host key for localhost.");
1145 host_status = HOST_OK;
1148 * Also perform check for the ip address, skip the check if we are
1149 * localhost or the hostname was an ip address to begin with
1151 if (options.check_host_ip && !local && strcmp(host, ip)) {
1152 RSA *ip_key = RSA_new();
1153 ip_key->n = BN_new();
1154 ip_key->e = BN_new();
1155 ip_status = check_host_in_hostfile(options.user_hostfile, ip,
1156 host_key->e, host_key->n,
1157 ip_key->e, ip_key->n);
1159 if (ip_status == HOST_NEW)
1160 ip_status = check_host_in_hostfile(options.system_hostfile, ip,
1161 host_key->e, host_key->n,
1162 ip_key->e, ip_key->n);
1163 if (host_status == HOST_CHANGED &&
1164 (ip_status != HOST_CHANGED ||
1165 (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n))))
1170 ip_status = host_status;
1174 switch (host_status) {
1176 /* The host is known and the key matches. */
1177 debug("Host '%.200s' is known and matches the host key.", host);
1178 if (options.check_host_ip) {
1179 if (ip_status == HOST_NEW) {
1180 if (!add_host_to_hostfile(options.user_hostfile, ip,
1181 host_key->e, host_key->n))
1182 log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1183 ip, options.user_hostfile);
1185 log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1187 } else if (ip_status != HOST_OK)
1188 log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1193 /* The host is new. */
1194 if (options.strict_host_key_checking == 1) {
1195 /* User has requested strict host key checking. We will not add the host key
1196 automatically. The only alternative left is to abort. */
1197 fatal("No host key is known for %.200s and you have requested strict checking.", host);
1198 } else if (options.strict_host_key_checking == 2) {
1201 char *fp = fingerprint(host_key->e, host_key->n);
1202 snprintf(prompt, sizeof(prompt),
1203 "The authenticity of host '%.200s' can't be established.\n"
1204 "Key fingerprint is %d %s.\n"
1205 "Are you sure you want to continue connecting (yes/no)? ",
1206 host, BN_num_bits(host_key->n), fp);
1207 if (!read_yes_or_no(prompt, -1))
1208 fatal("Aborted by user!\n");
1210 if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1211 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1216 /* If not in strict mode, add the key automatically to the local known_hosts file. */
1217 if (!add_host_to_hostfile(options.user_hostfile, hostp,
1218 host_key->e, host_key->n))
1219 log("Failed to add the host to the list of known hosts (%.500s).",
1220 options.user_hostfile);
1222 log("Warning: Permanently added '%.200s' to the list of known hosts.",
1226 if (options.check_host_ip && host_ip_differ) {
1228 if (ip_status == HOST_NEW)
1230 else if (ip_status == HOST_OK)
1231 msg = "is unchanged";
1233 msg = "has a different value";
1234 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1235 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1236 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1237 error("The host key for %s has changed,", host);
1238 error("and the key for the according IP address %s", ip);
1239 error("%s. This could either mean that", msg);
1240 error("DNS SPOOFING is happening or the IP address for the host");
1241 error("and its host key have changed at the same time");
1243 /* The host key has changed. */
1244 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1245 error("@ WARNING: HOST IDENTIFICATION HAS CHANGED! @");
1246 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1247 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1248 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1249 error("It is also possible that the host key has just been changed.");
1250 error("Please contact your system administrator.");
1251 error("Add correct host key in %.100s to get rid of this message.",
1252 options.user_hostfile);
1255 * If strict host key checking is in use, the user will have
1256 * to edit the key manually and we can only abort.
1258 if (options.strict_host_key_checking)
1259 fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1262 * If strict host key checking has not been requested, allow
1263 * the connection but without password authentication or
1266 if (options.password_authentication) {
1267 error("Password authentication is disabled to avoid trojan horses.");
1268 options.password_authentication = 0;
1270 if (options.forward_agent) {
1271 error("Agent forwarding is disabled to avoid trojan horses.");
1272 options.forward_agent = 0;
1275 * XXX Should permit the user to change to use the new id.
1276 * This could be done by converting the host key to an
1277 * identifying sentence, tell that the host identifies itself
1278 * by that sentence, and ask the user if he/she whishes to
1279 * accept the authentication.
1284 if (options.check_host_ip)
1287 /* 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
1293 * significant 8 bits being the first byte of the key.
1295 for (i = 0; i < 32; i++) {
1297 rand = arc4random();
1298 session_key[i] = rand & 0xff;
1303 * According to the protocol spec, the first byte of the session key
1304 * is the highest byte of the integer. The session key is xored with
1305 * the first 16 bytes of the session id.
1308 BN_set_word(key, 0);
1309 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1310 BN_lshift(key, key, 8);
1312 BN_add_word(key, session_key[i] ^ session_id[i]);
1314 BN_add_word(key, session_key[i]);
1318 * Encrypt the integer using the public key and host key of the
1319 * server (key with smaller modulus first).
1321 if (BN_cmp(public_key->n, host_key->n) < 0) {
1322 /* Public key has smaller modulus. */
1323 if (BN_num_bits(host_key->n) <
1324 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1325 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1326 "SSH_KEY_BITS_RESERVED %d",
1327 BN_num_bits(host_key->n),
1328 BN_num_bits(public_key->n),
1329 SSH_KEY_BITS_RESERVED);
1331 rsa_public_encrypt(key, key, public_key);
1332 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);
1343 rsa_public_encrypt(key, key, host_key);
1344 rsa_public_encrypt(key, key, public_key);
1347 if (options.cipher == SSH_CIPHER_NOT_SET) {
1348 if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1349 options.cipher = ssh_cipher_default;
1351 debug("Cipher %s not supported, using %.100s instead.",
1352 cipher_name(ssh_cipher_default),
1353 cipher_name(SSH_FALLBACK_CIPHER));
1354 options.cipher = SSH_FALLBACK_CIPHER;
1357 /* Check that the selected cipher is supported. */
1358 if (!(supported_ciphers & (1 << options.cipher)))
1359 fatal("Selected cipher type %.100s not supported by server.",
1360 cipher_name(options.cipher));
1362 debug("Encryption type: %.100s", cipher_name(options.cipher));
1364 /* Send the encrypted session key to the server. */
1365 packet_start(SSH_CMSG_SESSION_KEY);
1366 packet_put_char(options.cipher);
1368 /* Send the check bytes back to the server. */
1369 for (i = 0; i < 8; i++)
1370 packet_put_char(check_bytes[i]);
1372 /* Send the encrypted encryption key. */
1373 packet_put_bignum(key);
1375 /* Send protocol flags. */
1376 packet_put_int(SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1378 /* Send the packet now. */
1380 packet_write_wait();
1382 /* Destroy the session key integer and the public keys since we no longer need them. */
1384 RSA_free(public_key);
1387 debug("Sent encrypted session key.");
1389 /* Set the encryption key. */
1390 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1392 /* We will no longer need the session key here. Destroy any extra copies. */
1393 memset(session_key, 0, sizeof(session_key));
1396 * Expect a success message from the server. Note that this message
1397 * will be received in encrypted form.
1399 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1401 debug("Received encrypted confirmation.");
1403 /* Send the name of the user to log in as on the server. */
1404 packet_start(SSH_CMSG_USER);
1405 packet_put_string(server_user, strlen(server_user));
1407 packet_write_wait();
1410 * The server should respond with success if no authentication is
1411 * needed (the user has no password). Otherwise the server responds
1414 type = packet_read(&payload_len);
1416 /* check whether the connection was accepted without authentication. */
1417 if (type == SSH_SMSG_SUCCESS)
1419 if (type != SSH_SMSG_FAILURE)
1420 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1424 /* Try Kerberos tgt passing if the server supports it. */
1425 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1426 options.kerberos_tgt_passing) {
1427 if (options.cipher == SSH_CIPHER_NONE)
1428 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1429 (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) {
1443 debug("Trying Kerberos authentication.");
1444 if (try_kerberos_authentication()) {
1445 /* The server should respond with success or failure. */
1446 type = packet_read(&payload_len);
1447 if (type == SSH_SMSG_SUCCESS)
1449 if (type != SSH_SMSG_FAILURE)
1450 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1456 * Use rhosts authentication if running in privileged socket and we
1457 * do not wish to remain anonymous.
1459 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1460 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)
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
1479 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1480 options.rhosts_rsa_authentication && host_key_valid) {
1481 if (try_rhosts_rsa_authentication(local_user, own_host_key))
1484 /* Try RSA authentication if the server supports it. */
1485 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1486 options.rsa_authentication) {
1488 * Try RSA authentication using the authentication agent. The
1489 * agent is tried first because no passphrase is needed for
1490 * it, whereas identity files may require passphrases.
1492 if (try_agent_authentication())
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]))
1500 /* Try skey authentication if the server supports it. */
1501 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1502 options.skey_authentication && !options.batch_mode) {
1503 debug("Doing skey authentication.");
1505 /* request a challenge */
1506 packet_start(SSH_CMSG_AUTH_TIS);
1508 packet_write_wait();
1510 type = packet_read(&payload_len);
1511 if (type != SSH_SMSG_FAILURE &&
1512 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
1513 packet_disconnect("Protocol error: got %d in response "
1514 "to skey auth", type);
1516 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
1517 debug("No challenge for skey authentication.");
1519 char *challenge, *response;
1520 challenge = packet_get_string(&payload_len);
1521 if (options.cipher == SSH_CIPHER_NONE)
1522 log("WARNING: Encryption is disabled! "
1523 "Reponse will be transmitted in clear text.");
1524 fprintf(stderr, "%s\n", challenge);
1526 for (i = 0; i < options.number_of_password_prompts; i++) {
1528 error("Permission denied, please try again.");
1529 response = read_passphrase("Response: ", 0);
1530 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
1531 packet_put_string(response, strlen(response));
1532 memset(response, 0, strlen(response));
1535 packet_write_wait();
1536 type = packet_read(&payload_len);
1537 if (type == SSH_SMSG_SUCCESS)
1539 if (type != SSH_SMSG_FAILURE)
1540 packet_disconnect("Protocol error: got %d in response "
1541 "to skey auth", type);
1545 /* Try password authentication if the server supports it. */
1546 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1547 options.password_authentication && !options.batch_mode) {
1549 snprintf(prompt, sizeof(prompt), "%.30s@%.30s's password: ",
1551 debug("Doing password authentication.");
1552 if (options.cipher == SSH_CIPHER_NONE)
1553 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
1554 for (i = 0; i < options.number_of_password_prompts; i++) {
1556 error("Permission denied, please try again.");
1557 password = read_passphrase(prompt, 0);
1558 packet_start(SSH_CMSG_AUTH_PASSWORD);
1559 packet_put_string(password, strlen(password));
1560 memset(password, 0, strlen(password));
1563 packet_write_wait();
1565 type = packet_read(&payload_len);
1566 if (type == SSH_SMSG_SUCCESS)
1568 if (type != SSH_SMSG_FAILURE)
1569 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
1572 /* All authentication methods have failed. Exit with an error message. */
1573 fatal("Permission denied.");