Home | History | Annotate | Download | only in tool
      1 /* Copyright (c) 2014, Google Inc.
      2  *
      3  * Permission to use, copy, modify, and/or distribute this software for any
      4  * purpose with or without fee is hereby granted, provided that the above
      5  * copyright notice and this permission notice appear in all copies.
      6  *
      7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
     10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
     12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
     13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
     14 
     15 #include <openssl/base.h>
     16 
     17 #include <string>
     18 #include <vector>
     19 
     20 #include <errno.h>
     21 #include <limits.h>
     22 #include <stddef.h>
     23 #include <stdlib.h>
     24 #include <string.h>
     25 #include <sys/types.h>
     26 
     27 #if !defined(OPENSSL_WINDOWS)
     28 #include <arpa/inet.h>
     29 #include <fcntl.h>
     30 #include <netdb.h>
     31 #include <netinet/in.h>
     32 #include <sys/select.h>
     33 #include <sys/socket.h>
     34 #include <unistd.h>
     35 #else
     36 #include <io.h>
     37 OPENSSL_MSVC_PRAGMA(warning(push, 3))
     38 #include <winsock2.h>
     39 #include <ws2tcpip.h>
     40 OPENSSL_MSVC_PRAGMA(warning(pop))
     41 
     42 typedef int ssize_t;
     43 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
     44 #endif
     45 
     46 #include <openssl/err.h>
     47 #include <openssl/ssl.h>
     48 #include <openssl/x509.h>
     49 
     50 #include "../crypto/internal.h"
     51 #include "internal.h"
     52 #include "transport_common.h"
     53 
     54 
     55 #if !defined(OPENSSL_WINDOWS)
     56 static int closesocket(int sock) {
     57   return close(sock);
     58 }
     59 #endif
     60 
     61 bool InitSocketLibrary() {
     62 #if defined(OPENSSL_WINDOWS)
     63   WSADATA wsaData;
     64   int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
     65   if (err != 0) {
     66     fprintf(stderr, "WSAStartup failed with error %d\n", err);
     67     return false;
     68   }
     69 #endif
     70   return true;
     71 }
     72 
     73 // Connect sets |*out_sock| to be a socket connected to the destination given
     74 // in |hostname_and_port|, which should be of the form "www.example.com:123".
     75 // It returns true on success and false otherwise.
     76 bool Connect(int *out_sock, const std::string &hostname_and_port) {
     77   size_t colon_offset = hostname_and_port.find_last_of(':');
     78   const size_t bracket_offset = hostname_and_port.find_last_of(']');
     79   std::string hostname, port;
     80 
     81   // An IPv6 literal may have colons internally, guarded by square brackets.
     82   if (bracket_offset != std::string::npos &&
     83       colon_offset != std::string::npos && bracket_offset > colon_offset) {
     84     colon_offset = std::string::npos;
     85   }
     86 
     87   if (colon_offset == std::string::npos) {
     88     hostname = hostname_and_port;
     89     port = "443";
     90   } else {
     91     hostname = hostname_and_port.substr(0, colon_offset);
     92     port = hostname_and_port.substr(colon_offset + 1);
     93   }
     94 
     95   // Handle IPv6 literals.
     96   if (hostname.size() >= 2 && hostname[0] == '[' &&
     97       hostname[hostname.size() - 1] == ']') {
     98     hostname = hostname.substr(1, hostname.size() - 2);
     99   }
    100 
    101   struct addrinfo hint, *result;
    102   OPENSSL_memset(&hint, 0, sizeof(hint));
    103   hint.ai_family = AF_UNSPEC;
    104   hint.ai_socktype = SOCK_STREAM;
    105 
    106   int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
    107   if (ret != 0) {
    108     fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
    109     return false;
    110   }
    111 
    112   bool ok = false;
    113   char buf[256];
    114 
    115   *out_sock =
    116       socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    117   if (*out_sock < 0) {
    118     perror("socket");
    119     goto out;
    120   }
    121 
    122   switch (result->ai_family) {
    123     case AF_INET: {
    124       struct sockaddr_in *sin =
    125           reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
    126       fprintf(stderr, "Connecting to %s:%d\n",
    127               inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
    128               ntohs(sin->sin_port));
    129       break;
    130     }
    131     case AF_INET6: {
    132       struct sockaddr_in6 *sin6 =
    133           reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
    134       fprintf(stderr, "Connecting to [%s]:%d\n",
    135               inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
    136               ntohs(sin6->sin6_port));
    137       break;
    138     }
    139   }
    140 
    141   if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
    142     perror("connect");
    143     goto out;
    144   }
    145   ok = true;
    146 
    147 out:
    148   freeaddrinfo(result);
    149   return ok;
    150 }
    151 
    152 bool Accept(int *out_sock, const std::string &port) {
    153   struct sockaddr_in6 addr, cli_addr;
    154   socklen_t cli_addr_len = sizeof(cli_addr);
    155   OPENSSL_memset(&addr, 0, sizeof(addr));
    156 
    157   addr.sin6_family = AF_INET6;
    158   addr.sin6_addr = IN6ADDR_ANY_INIT;
    159   addr.sin6_port = htons(atoi(port.c_str()));
    160 
    161   bool ok = false;
    162 #if defined(OPENSSL_WINDOWS)
    163   const BOOL enable = TRUE;
    164 #else
    165   const int enable = 1;
    166 #endif
    167   int server_sock = -1;
    168 
    169   server_sock =
    170       socket(addr.sin6_family, SOCK_STREAM, 0);
    171   if (server_sock < 0) {
    172     perror("socket");
    173     goto out;
    174   }
    175 
    176   if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable,
    177                  sizeof(enable)) < 0) {
    178     perror("setsockopt");
    179     goto out;
    180   }
    181 
    182   if (bind(server_sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
    183     perror("connect");
    184     goto out;
    185   }
    186   listen(server_sock, 1);
    187   *out_sock = accept(server_sock, (struct sockaddr*)&cli_addr, &cli_addr_len);
    188 
    189   ok = true;
    190 
    191 out:
    192   closesocket(server_sock);
    193   return ok;
    194 }
    195 
    196 bool VersionFromString(uint16_t *out_version, const std::string &version) {
    197   if (version == "ssl3") {
    198     *out_version = SSL3_VERSION;
    199     return true;
    200   } else if (version == "tls1" || version == "tls1.0") {
    201     *out_version = TLS1_VERSION;
    202     return true;
    203   } else if (version == "tls1.1") {
    204     *out_version = TLS1_1_VERSION;
    205     return true;
    206   } else if (version == "tls1.2") {
    207     *out_version = TLS1_2_VERSION;
    208     return true;
    209   } else if (version == "tls1.3") {
    210     *out_version = TLS1_3_VERSION;
    211     return true;
    212   }
    213   return false;
    214 }
    215 
    216 static const char *SignatureAlgorithmToString(uint16_t version, uint16_t sigalg) {
    217   const bool is_tls12 = version == TLS1_2_VERSION || version == DTLS1_2_VERSION;
    218   switch (sigalg) {
    219     case SSL_SIGN_RSA_PKCS1_SHA1:
    220       return "rsa_pkcs1_sha1";
    221     case SSL_SIGN_RSA_PKCS1_SHA256:
    222       return "rsa_pkcs1_sha256";
    223     case SSL_SIGN_RSA_PKCS1_SHA384:
    224       return "rsa_pkcs1_sha384";
    225     case SSL_SIGN_RSA_PKCS1_SHA512:
    226       return "rsa_pkcs1_sha512";
    227     case SSL_SIGN_ECDSA_SHA1:
    228       return "ecdsa_sha1";
    229     case SSL_SIGN_ECDSA_SECP256R1_SHA256:
    230       return is_tls12 ? "ecdsa_sha256" : "ecdsa_secp256r1_sha256";
    231     case SSL_SIGN_ECDSA_SECP384R1_SHA384:
    232       return is_tls12 ? "ecdsa_sha384" : "ecdsa_secp384r1_sha384";
    233     case SSL_SIGN_ECDSA_SECP521R1_SHA512:
    234       return is_tls12 ? "ecdsa_sha512" : "ecdsa_secp521r1_sha512";
    235     case SSL_SIGN_RSA_PSS_SHA256:
    236       return "rsa_pss_sha256";
    237     case SSL_SIGN_RSA_PSS_SHA384:
    238       return "rsa_pss_sha384";
    239     case SSL_SIGN_RSA_PSS_SHA512:
    240       return "rsa_pss_sha512";
    241     default:
    242       return "(unknown)";
    243   }
    244 }
    245 
    246 void PrintConnectionInfo(const SSL *ssl) {
    247   const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
    248 
    249   fprintf(stderr, "  Version: %s\n", SSL_get_version(ssl));
    250   fprintf(stderr, "  Resumed session: %s\n",
    251           SSL_session_reused(ssl) ? "yes" : "no");
    252   fprintf(stderr, "  Cipher: %s\n", SSL_CIPHER_get_name(cipher));
    253   uint16_t curve = SSL_get_curve_id(ssl);
    254   if (curve != 0) {
    255     fprintf(stderr, "  ECDHE curve: %s\n", SSL_get_curve_name(curve));
    256   }
    257   uint16_t sigalg = SSL_get_peer_signature_algorithm(ssl);
    258   if (sigalg != 0) {
    259     fprintf(stderr, "  Signature algorithm: %s\n",
    260             SignatureAlgorithmToString(SSL_version(ssl), sigalg));
    261   }
    262   fprintf(stderr, "  Secure renegotiation: %s\n",
    263           SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
    264   fprintf(stderr, "  Extended master secret: %s\n",
    265           SSL_get_extms_support(ssl) ? "yes" : "no");
    266 
    267   const uint8_t *next_proto;
    268   unsigned next_proto_len;
    269   SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
    270   fprintf(stderr, "  Next protocol negotiated: %.*s\n", next_proto_len,
    271           next_proto);
    272 
    273   const uint8_t *alpn;
    274   unsigned alpn_len;
    275   SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
    276   fprintf(stderr, "  ALPN protocol: %.*s\n", alpn_len, alpn);
    277 
    278   const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
    279   if (host_name != nullptr && SSL_is_server(ssl)) {
    280     fprintf(stderr, "  Client sent SNI: %s\n", host_name);
    281   }
    282 
    283   if (!SSL_is_server(ssl)) {
    284     const uint8_t *ocsp_staple;
    285     size_t ocsp_staple_len;
    286     SSL_get0_ocsp_response(ssl, &ocsp_staple, &ocsp_staple_len);
    287     fprintf(stderr, "  OCSP staple: %s\n", ocsp_staple_len > 0 ? "yes" : "no");
    288 
    289     const uint8_t *sct_list;
    290     size_t sct_list_len;
    291     SSL_get0_signed_cert_timestamp_list(ssl, &sct_list, &sct_list_len);
    292     fprintf(stderr, "  SCT list: %s\n", sct_list_len > 0 ? "yes" : "no");
    293   }
    294 
    295   fprintf(stderr, "  Early data: %s\n",
    296           SSL_early_data_accepted(ssl) ? "yes" : "no");
    297 
    298   // Print the server cert subject and issuer names.
    299   bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl));
    300   if (peer != nullptr) {
    301     fprintf(stderr, "  Cert subject: ");
    302     X509_NAME_print_ex_fp(stderr, X509_get_subject_name(peer.get()), 0,
    303                           XN_FLAG_ONELINE);
    304     fprintf(stderr, "\n  Cert issuer: ");
    305     X509_NAME_print_ex_fp(stderr, X509_get_issuer_name(peer.get()), 0,
    306                           XN_FLAG_ONELINE);
    307     fprintf(stderr, "\n");
    308   }
    309 }
    310 
    311 bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
    312   bool ok;
    313 
    314 #if defined(OPENSSL_WINDOWS)
    315   u_long arg = is_non_blocking;
    316   ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
    317 #else
    318   int flags = fcntl(sock, F_GETFL, 0);
    319   if (flags < 0) {
    320     return false;
    321   }
    322   if (is_non_blocking) {
    323     flags |= O_NONBLOCK;
    324   } else {
    325     flags &= ~O_NONBLOCK;
    326   }
    327   ok = 0 == fcntl(sock, F_SETFL, flags);
    328 #endif
    329   if (!ok) {
    330     fprintf(stderr, "Failed to set socket non-blocking.\n");
    331   }
    332   return ok;
    333 }
    334 
    335 // PrintErrorCallback is a callback function from OpenSSL's
    336 // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
    337 int PrintErrorCallback(const char *str, size_t len, void *ctx) {
    338   fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
    339   return 1;
    340 }
    341 
    342 bool TransferData(SSL *ssl, int sock) {
    343   bool stdin_open = true;
    344 
    345   fd_set read_fds;
    346   FD_ZERO(&read_fds);
    347 
    348   if (!SocketSetNonBlocking(sock, true)) {
    349     return false;
    350   }
    351 
    352   for (;;) {
    353     if (stdin_open) {
    354       FD_SET(0, &read_fds);
    355     }
    356     FD_SET(sock, &read_fds);
    357 
    358     int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
    359     if (ret <= 0) {
    360       perror("select");
    361       return false;
    362     }
    363 
    364     if (FD_ISSET(0, &read_fds)) {
    365       uint8_t buffer[512];
    366       ssize_t n;
    367 
    368       do {
    369         n = BORINGSSL_READ(0, buffer, sizeof(buffer));
    370       } while (n == -1 && errno == EINTR);
    371 
    372       if (n == 0) {
    373         FD_CLR(0, &read_fds);
    374         stdin_open = false;
    375 #if !defined(OPENSSL_WINDOWS)
    376         shutdown(sock, SHUT_WR);
    377 #else
    378         shutdown(sock, SD_SEND);
    379 #endif
    380         continue;
    381       } else if (n < 0) {
    382         perror("read from stdin");
    383         return false;
    384       }
    385 
    386       if (!SocketSetNonBlocking(sock, false)) {
    387         return false;
    388       }
    389       int ssl_ret = SSL_write(ssl, buffer, n);
    390       if (!SocketSetNonBlocking(sock, true)) {
    391         return false;
    392       }
    393 
    394       if (ssl_ret <= 0) {
    395         int ssl_err = SSL_get_error(ssl, ssl_ret);
    396         fprintf(stderr, "Error while writing: %d\n", ssl_err);
    397         ERR_print_errors_cb(PrintErrorCallback, stderr);
    398         return false;
    399       } else if (ssl_ret != n) {
    400         fprintf(stderr, "Short write from SSL_write.\n");
    401         return false;
    402       }
    403     }
    404 
    405     if (FD_ISSET(sock, &read_fds)) {
    406       uint8_t buffer[512];
    407       int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
    408 
    409       if (ssl_ret < 0) {
    410         int ssl_err = SSL_get_error(ssl, ssl_ret);
    411         if (ssl_err == SSL_ERROR_WANT_READ) {
    412           continue;
    413         }
    414         fprintf(stderr, "Error while reading: %d\n", ssl_err);
    415         ERR_print_errors_cb(PrintErrorCallback, stderr);
    416         return false;
    417       } else if (ssl_ret == 0) {
    418         return true;
    419       }
    420 
    421       ssize_t n;
    422       do {
    423         n = BORINGSSL_WRITE(1, buffer, ssl_ret);
    424       } while (n == -1 && errno == EINTR);
    425 
    426       if (n != ssl_ret) {
    427         fprintf(stderr, "Short write to stderr.\n");
    428         return false;
    429       }
    430     }
    431   }
    432 }
    433 
    434 // SocketLineReader wraps a small buffer around a socket for line-orientated
    435 // protocols.
    436 class SocketLineReader {
    437  public:
    438   explicit SocketLineReader(int sock) : sock_(sock) {}
    439 
    440   // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
    441   // success, sets |*out_line| to it and returns true. Otherwise it returns
    442   // false.
    443   bool Next(std::string *out_line) {
    444     for (;;) {
    445       for (size_t i = 0; i < buf_len_; i++) {
    446         if (buf_[i] != '\n') {
    447           continue;
    448         }
    449 
    450         size_t length = i;
    451         if (i > 0 && buf_[i - 1] == '\r') {
    452           length--;
    453         }
    454 
    455         out_line->assign(buf_, length);
    456         buf_len_ -= i + 1;
    457         OPENSSL_memmove(buf_, &buf_[i + 1], buf_len_);
    458 
    459         return true;
    460       }
    461 
    462       if (buf_len_ == sizeof(buf_)) {
    463         fprintf(stderr, "Received line too long!\n");
    464         return false;
    465       }
    466 
    467       ssize_t n;
    468       do {
    469         n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
    470       } while (n == -1 && errno == EINTR);
    471 
    472       if (n < 0) {
    473         fprintf(stderr, "Read error from socket\n");
    474         return false;
    475       }
    476 
    477       buf_len_ += n;
    478     }
    479   }
    480 
    481   // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
    482   // success, it sets |*out_code| to the reply's code (e.g. 250) and
    483   // |*out_content| to the body of the reply (e.g. "OK") and returns true.
    484   // Otherwise it returns false.
    485   //
    486   // See https://tools.ietf.org/html/rfc821#page-48
    487   bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
    488     out_content->clear();
    489 
    490     // kMaxLines is the maximum number of lines that we'll accept in an SMTP
    491     // reply.
    492     static const unsigned kMaxLines = 512;
    493     for (unsigned i = 0; i < kMaxLines; i++) {
    494       std::string line;
    495       if (!Next(&line)) {
    496         return false;
    497       }
    498 
    499       if (line.size() < 4) {
    500         fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
    501         return false;
    502       }
    503 
    504       const std::string code_str = line.substr(0, 3);
    505       char *endptr;
    506       const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
    507       if (*endptr || code > UINT_MAX) {
    508         fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
    509         return false;
    510       }
    511 
    512       if (i == 0) {
    513         *out_code = code;
    514       } else if (code != *out_code) {
    515         fprintf(stderr,
    516                 "Reply code varied within a single reply: was %u, now %u\n",
    517                 *out_code, static_cast<unsigned>(code));
    518         return false;
    519       }
    520 
    521       if (line[3] == ' ') {
    522         // End of reply.
    523         *out_content += line.substr(4, std::string::npos);
    524         return true;
    525       } else if (line[3] == '-') {
    526         // Another line of reply will follow this one.
    527         *out_content += line.substr(4, std::string::npos);
    528         out_content->push_back('\n');
    529       } else {
    530         fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
    531                 line.c_str());
    532         return false;
    533       }
    534     }
    535 
    536     fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
    537     return false;
    538   }
    539 
    540  private:
    541   const int sock_;
    542   char buf_[512];
    543   size_t buf_len_ = 0;
    544 };
    545 
    546 // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
    547 // success and false otherwise.
    548 static bool SendAll(int sock, const char *data, size_t data_len) {
    549   size_t done = 0;
    550 
    551   while (done < data_len) {
    552     ssize_t n;
    553     do {
    554       n = send(sock, &data[done], data_len - done, 0);
    555     } while (n == -1 && errno == EINTR);
    556 
    557     if (n < 0) {
    558       fprintf(stderr, "Error while writing to socket\n");
    559       return false;
    560     }
    561 
    562     done += n;
    563   }
    564 
    565   return true;
    566 }
    567 
    568 bool DoSMTPStartTLS(int sock) {
    569   SocketLineReader line_reader(sock);
    570 
    571   unsigned code_220 = 0;
    572   std::string reply_220;
    573   if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
    574     return false;
    575   }
    576 
    577   if (code_220 != 220) {
    578     fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
    579             code_220);
    580     return false;
    581   }
    582 
    583   static const char kHelloLine[] = "EHLO BoringSSL\r\n";
    584   if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
    585     return false;
    586   }
    587 
    588   unsigned code_250 = 0;
    589   std::string reply_250;
    590   if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
    591     return false;
    592   }
    593 
    594   if (code_250 != 250) {
    595     fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
    596     return false;
    597   }
    598 
    599   // https://tools.ietf.org/html/rfc1869#section-4.3
    600   if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) {
    601     fprintf(stderr, "Server does not support STARTTLS\n");
    602     return false;
    603   }
    604 
    605   static const char kSTARTTLSLine[] = "STARTTLS\r\n";
    606   if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
    607     return false;
    608   }
    609 
    610   if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
    611     return false;
    612   }
    613 
    614   if (code_220 != 220) {
    615     fprintf(
    616         stderr,
    617         "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
    618         code_220);
    619     return false;
    620   }
    621 
    622   return true;
    623 }
    624