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 static void SplitHostPort(std::string *out_hostname, std::string *out_port, 74 const std::string &hostname_and_port) { 75 size_t colon_offset = hostname_and_port.find_last_of(':'); 76 const size_t bracket_offset = hostname_and_port.find_last_of(']'); 77 std::string hostname, port; 78 79 // An IPv6 literal may have colons internally, guarded by square brackets. 80 if (bracket_offset != std::string::npos && 81 colon_offset != std::string::npos && bracket_offset > colon_offset) { 82 colon_offset = std::string::npos; 83 } 84 85 if (colon_offset == std::string::npos) { 86 *out_hostname = hostname_and_port; 87 *out_port = "443"; 88 } else { 89 *out_hostname = hostname_and_port.substr(0, colon_offset); 90 *out_port = hostname_and_port.substr(colon_offset + 1); 91 } 92 } 93 94 // Connect sets |*out_sock| to be a socket connected to the destination given 95 // in |hostname_and_port|, which should be of the form "www.example.com:123". 96 // It returns true on success and false otherwise. 97 bool Connect(int *out_sock, const std::string &hostname_and_port) { 98 std::string hostname, port; 99 SplitHostPort(&hostname, &port, hostname_and_port); 100 101 // Handle IPv6 literals. 102 if (hostname.size() >= 2 && hostname[0] == '[' && 103 hostname[hostname.size() - 1] == ']') { 104 hostname = hostname.substr(1, hostname.size() - 2); 105 } 106 107 struct addrinfo hint, *result; 108 OPENSSL_memset(&hint, 0, sizeof(hint)); 109 hint.ai_family = AF_UNSPEC; 110 hint.ai_socktype = SOCK_STREAM; 111 112 int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result); 113 if (ret != 0) { 114 fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret)); 115 return false; 116 } 117 118 bool ok = false; 119 char buf[256]; 120 121 *out_sock = 122 socket(result->ai_family, result->ai_socktype, result->ai_protocol); 123 if (*out_sock < 0) { 124 perror("socket"); 125 goto out; 126 } 127 128 switch (result->ai_family) { 129 case AF_INET: { 130 struct sockaddr_in *sin = 131 reinterpret_cast<struct sockaddr_in *>(result->ai_addr); 132 fprintf(stderr, "Connecting to %s:%d\n", 133 inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)), 134 ntohs(sin->sin_port)); 135 break; 136 } 137 case AF_INET6: { 138 struct sockaddr_in6 *sin6 = 139 reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr); 140 fprintf(stderr, "Connecting to [%s]:%d\n", 141 inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)), 142 ntohs(sin6->sin6_port)); 143 break; 144 } 145 } 146 147 if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) { 148 perror("connect"); 149 goto out; 150 } 151 ok = true; 152 153 out: 154 freeaddrinfo(result); 155 return ok; 156 } 157 158 Listener::~Listener() { 159 if (server_sock_ >= 0) { 160 closesocket(server_sock_); 161 } 162 } 163 164 bool Listener::Init(const std::string &port) { 165 if (server_sock_ >= 0) { 166 return false; 167 } 168 169 struct sockaddr_in6 addr; 170 OPENSSL_memset(&addr, 0, sizeof(addr)); 171 172 addr.sin6_family = AF_INET6; 173 // Windows' IN6ADDR_ANY_INIT does not have enough curly braces for clang-cl 174 // (https://crbug.com/772108), while other platforms like NaCl are missing 175 // in6addr_any, so use a mix of both. 176 #if defined(OPENSSL_WINDOWS) 177 addr.sin6_addr = in6addr_any; 178 #else 179 addr.sin6_addr = IN6ADDR_ANY_INIT; 180 #endif 181 addr.sin6_port = htons(atoi(port.c_str())); 182 183 #if defined(OPENSSL_WINDOWS) 184 const BOOL enable = TRUE; 185 #else 186 const int enable = 1; 187 #endif 188 189 server_sock_ = socket(addr.sin6_family, SOCK_STREAM, 0); 190 if (server_sock_ < 0) { 191 perror("socket"); 192 return false; 193 } 194 195 if (setsockopt(server_sock_, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable, 196 sizeof(enable)) < 0) { 197 perror("setsockopt"); 198 return false; 199 } 200 201 if (bind(server_sock_, (struct sockaddr *)&addr, sizeof(addr)) != 0) { 202 perror("connect"); 203 return false; 204 } 205 206 listen(server_sock_, SOMAXCONN); 207 return true; 208 } 209 210 bool Listener::Accept(int *out_sock) { 211 struct sockaddr_in6 addr; 212 socklen_t addr_len = sizeof(addr); 213 *out_sock = accept(server_sock_, (struct sockaddr *)&addr, &addr_len); 214 return *out_sock >= 0; 215 } 216 217 bool VersionFromString(uint16_t *out_version, const std::string &version) { 218 if (version == "ssl3") { 219 *out_version = SSL3_VERSION; 220 return true; 221 } else if (version == "tls1" || version == "tls1.0") { 222 *out_version = TLS1_VERSION; 223 return true; 224 } else if (version == "tls1.1") { 225 *out_version = TLS1_1_VERSION; 226 return true; 227 } else if (version == "tls1.2") { 228 *out_version = TLS1_2_VERSION; 229 return true; 230 } else if (version == "tls1.3") { 231 *out_version = TLS1_3_VERSION; 232 return true; 233 } 234 return false; 235 } 236 237 void PrintConnectionInfo(BIO *bio, const SSL *ssl) { 238 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl); 239 240 BIO_printf(bio, " Version: %s\n", SSL_get_version(ssl)); 241 BIO_printf(bio, " Resumed session: %s\n", 242 SSL_session_reused(ssl) ? "yes" : "no"); 243 BIO_printf(bio, " Cipher: %s\n", SSL_CIPHER_standard_name(cipher)); 244 uint16_t curve = SSL_get_curve_id(ssl); 245 if (curve != 0) { 246 BIO_printf(bio, " ECDHE curve: %s\n", SSL_get_curve_name(curve)); 247 } 248 uint16_t sigalg = SSL_get_peer_signature_algorithm(ssl); 249 if (sigalg != 0) { 250 BIO_printf(bio, " Signature algorithm: %s\n", 251 SSL_get_signature_algorithm_name( 252 sigalg, SSL_version(ssl) != TLS1_2_VERSION)); 253 } 254 BIO_printf(bio, " Secure renegotiation: %s\n", 255 SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no"); 256 BIO_printf(bio, " Extended master secret: %s\n", 257 SSL_get_extms_support(ssl) ? "yes" : "no"); 258 259 const uint8_t *next_proto; 260 unsigned next_proto_len; 261 SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len); 262 BIO_printf(bio, " Next protocol negotiated: %.*s\n", next_proto_len, 263 next_proto); 264 265 const uint8_t *alpn; 266 unsigned alpn_len; 267 SSL_get0_alpn_selected(ssl, &alpn, &alpn_len); 268 BIO_printf(bio, " ALPN protocol: %.*s\n", alpn_len, alpn); 269 270 const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); 271 if (host_name != nullptr && SSL_is_server(ssl)) { 272 BIO_printf(bio, " Client sent SNI: %s\n", host_name); 273 } 274 275 if (!SSL_is_server(ssl)) { 276 const uint8_t *ocsp_staple; 277 size_t ocsp_staple_len; 278 SSL_get0_ocsp_response(ssl, &ocsp_staple, &ocsp_staple_len); 279 BIO_printf(bio, " OCSP staple: %s\n", ocsp_staple_len > 0 ? "yes" : "no"); 280 281 const uint8_t *sct_list; 282 size_t sct_list_len; 283 SSL_get0_signed_cert_timestamp_list(ssl, &sct_list, &sct_list_len); 284 BIO_printf(bio, " SCT list: %s\n", sct_list_len > 0 ? "yes" : "no"); 285 } 286 287 BIO_printf( 288 bio, " Early data: %s\n", 289 (SSL_early_data_accepted(ssl) || SSL_in_early_data(ssl)) ? "yes" : "no"); 290 291 // Print the server cert subject and issuer names. 292 bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl)); 293 if (peer != nullptr) { 294 BIO_printf(bio, " Cert subject: "); 295 X509_NAME_print_ex(bio, X509_get_subject_name(peer.get()), 0, 296 XN_FLAG_ONELINE); 297 BIO_printf(bio, "\n Cert issuer: "); 298 X509_NAME_print_ex(bio, X509_get_issuer_name(peer.get()), 0, 299 XN_FLAG_ONELINE); 300 BIO_printf(bio, "\n"); 301 } 302 } 303 304 bool SocketSetNonBlocking(int sock, bool is_non_blocking) { 305 bool ok; 306 307 #if defined(OPENSSL_WINDOWS) 308 u_long arg = is_non_blocking; 309 ok = 0 == ioctlsocket(sock, FIONBIO, &arg); 310 #else 311 int flags = fcntl(sock, F_GETFL, 0); 312 if (flags < 0) { 313 return false; 314 } 315 if (is_non_blocking) { 316 flags |= O_NONBLOCK; 317 } else { 318 flags &= ~O_NONBLOCK; 319 } 320 ok = 0 == fcntl(sock, F_SETFL, flags); 321 #endif 322 if (!ok) { 323 fprintf(stderr, "Failed to set socket non-blocking.\n"); 324 } 325 return ok; 326 } 327 328 static bool SocketSelect(int sock, bool stdin_open, bool *socket_ready, 329 bool *stdin_ready) { 330 #if !defined(OPENSSL_WINDOWS) 331 fd_set read_fds; 332 FD_ZERO(&read_fds); 333 if (stdin_open) { 334 FD_SET(0, &read_fds); 335 } 336 FD_SET(sock, &read_fds); 337 if (select(sock + 1, &read_fds, NULL, NULL, NULL) <= 0) { 338 perror("select"); 339 return false; 340 } 341 342 if (FD_ISSET(0, &read_fds)) { 343 *stdin_ready = true; 344 } 345 if (FD_ISSET(sock, &read_fds)) { 346 *socket_ready = true; 347 } 348 349 return true; 350 #else 351 WSAEVENT socket_handle = WSACreateEvent(); 352 if (socket_handle == WSA_INVALID_EVENT || 353 WSAEventSelect(sock, socket_handle, FD_READ) != 0) { 354 WSACloseEvent(socket_handle); 355 return false; 356 } 357 358 HANDLE read_fds[2]; 359 read_fds[0] = socket_handle; 360 read_fds[1] = GetStdHandle(STD_INPUT_HANDLE); 361 362 switch ( 363 WaitForMultipleObjects(stdin_open ? 2 : 1, read_fds, FALSE, INFINITE)) { 364 case WAIT_OBJECT_0 + 0: 365 *socket_ready = true; 366 break; 367 case WAIT_OBJECT_0 + 1: 368 *stdin_ready = true; 369 break; 370 case WAIT_TIMEOUT: 371 break; 372 default: 373 WSACloseEvent(socket_handle); 374 return false; 375 } 376 377 WSACloseEvent(socket_handle); 378 return true; 379 #endif 380 } 381 382 // PrintErrorCallback is a callback function from OpenSSL's 383 // |ERR_print_errors_cb| that writes errors to a given |FILE*|. 384 int PrintErrorCallback(const char *str, size_t len, void *ctx) { 385 fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx)); 386 return 1; 387 } 388 389 bool TransferData(SSL *ssl, int sock) { 390 if (!SocketSetNonBlocking(sock, true)) { 391 return false; 392 } 393 394 bool stdin_open = true; 395 for (;;) { 396 bool socket_ready = false; 397 bool stdin_ready = false; 398 if (!SocketSelect(sock, stdin_open, &socket_ready, &stdin_ready)) { 399 return false; 400 } 401 402 if (stdin_ready) { 403 uint8_t buffer[512]; 404 ssize_t n; 405 406 do { 407 n = BORINGSSL_READ(0, buffer, sizeof(buffer)); 408 } while (n == -1 && errno == EINTR); 409 410 if (n == 0) { 411 stdin_open = false; 412 #if !defined(OPENSSL_WINDOWS) 413 shutdown(sock, SHUT_WR); 414 #else 415 shutdown(sock, SD_SEND); 416 #endif 417 continue; 418 } else if (n < 0) { 419 perror("read from stdin"); 420 return false; 421 } 422 423 // On Windows, SocketSelect ends up setting sock to non-blocking. 424 #if !defined(OPENSSL_WINDOWS) 425 if (!SocketSetNonBlocking(sock, false)) { 426 return false; 427 } 428 #endif 429 int ssl_ret = SSL_write(ssl, buffer, n); 430 if (!SocketSetNonBlocking(sock, true)) { 431 return false; 432 } 433 434 if (ssl_ret <= 0) { 435 int ssl_err = SSL_get_error(ssl, ssl_ret); 436 fprintf(stderr, "Error while writing: %d\n", ssl_err); 437 ERR_print_errors_cb(PrintErrorCallback, stderr); 438 return false; 439 } else if (ssl_ret != n) { 440 fprintf(stderr, "Short write from SSL_write.\n"); 441 return false; 442 } 443 } 444 445 if (socket_ready) { 446 uint8_t buffer[512]; 447 int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer)); 448 449 if (ssl_ret < 0) { 450 int ssl_err = SSL_get_error(ssl, ssl_ret); 451 if (ssl_err == SSL_ERROR_WANT_READ) { 452 continue; 453 } 454 fprintf(stderr, "Error while reading: %d\n", ssl_err); 455 ERR_print_errors_cb(PrintErrorCallback, stderr); 456 return false; 457 } else if (ssl_ret == 0) { 458 return true; 459 } 460 461 ssize_t n; 462 do { 463 n = BORINGSSL_WRITE(1, buffer, ssl_ret); 464 } while (n == -1 && errno == EINTR); 465 466 if (n != ssl_ret) { 467 fprintf(stderr, "Short write to stderr.\n"); 468 return false; 469 } 470 } 471 } 472 } 473 474 // SocketLineReader wraps a small buffer around a socket for line-orientated 475 // protocols. 476 class SocketLineReader { 477 public: 478 explicit SocketLineReader(int sock) : sock_(sock) {} 479 480 // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on 481 // success, sets |*out_line| to it and returns true. Otherwise it returns 482 // false. 483 bool Next(std::string *out_line) { 484 for (;;) { 485 for (size_t i = 0; i < buf_len_; i++) { 486 if (buf_[i] != '\n') { 487 continue; 488 } 489 490 size_t length = i; 491 if (i > 0 && buf_[i - 1] == '\r') { 492 length--; 493 } 494 495 out_line->assign(buf_, length); 496 buf_len_ -= i + 1; 497 OPENSSL_memmove(buf_, &buf_[i + 1], buf_len_); 498 499 return true; 500 } 501 502 if (buf_len_ == sizeof(buf_)) { 503 fprintf(stderr, "Received line too long!\n"); 504 return false; 505 } 506 507 ssize_t n; 508 do { 509 n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0); 510 } while (n == -1 && errno == EINTR); 511 512 if (n < 0) { 513 fprintf(stderr, "Read error from socket\n"); 514 return false; 515 } 516 517 buf_len_ += n; 518 } 519 } 520 521 // ReadSMTPReply reads one or more lines that make up an SMTP reply. On 522 // success, it sets |*out_code| to the reply's code (e.g. 250) and 523 // |*out_content| to the body of the reply (e.g. "OK") and returns true. 524 // Otherwise it returns false. 525 // 526 // See https://tools.ietf.org/html/rfc821#page-48 527 bool ReadSMTPReply(unsigned *out_code, std::string *out_content) { 528 out_content->clear(); 529 530 // kMaxLines is the maximum number of lines that we'll accept in an SMTP 531 // reply. 532 static const unsigned kMaxLines = 512; 533 for (unsigned i = 0; i < kMaxLines; i++) { 534 std::string line; 535 if (!Next(&line)) { 536 return false; 537 } 538 539 if (line.size() < 4) { 540 fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str()); 541 return false; 542 } 543 544 const std::string code_str = line.substr(0, 3); 545 char *endptr; 546 const unsigned long code = strtoul(code_str.c_str(), &endptr, 10); 547 if (*endptr || code > UINT_MAX) { 548 fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str()); 549 return false; 550 } 551 552 if (i == 0) { 553 *out_code = code; 554 } else if (code != *out_code) { 555 fprintf(stderr, 556 "Reply code varied within a single reply: was %u, now %u\n", 557 *out_code, static_cast<unsigned>(code)); 558 return false; 559 } 560 561 if (line[3] == ' ') { 562 // End of reply. 563 *out_content += line.substr(4, std::string::npos); 564 return true; 565 } else if (line[3] == '-') { 566 // Another line of reply will follow this one. 567 *out_content += line.substr(4, std::string::npos); 568 out_content->push_back('\n'); 569 } else { 570 fprintf(stderr, "Bad character after code in SMTP reply: %s\n", 571 line.c_str()); 572 return false; 573 } 574 } 575 576 fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines); 577 return false; 578 } 579 580 private: 581 const int sock_; 582 char buf_[512]; 583 size_t buf_len_ = 0; 584 }; 585 586 // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on 587 // success and false otherwise. 588 static bool SendAll(int sock, const char *data, size_t data_len) { 589 size_t done = 0; 590 591 while (done < data_len) { 592 ssize_t n; 593 do { 594 n = send(sock, &data[done], data_len - done, 0); 595 } while (n == -1 && errno == EINTR); 596 597 if (n < 0) { 598 fprintf(stderr, "Error while writing to socket\n"); 599 return false; 600 } 601 602 done += n; 603 } 604 605 return true; 606 } 607 608 bool DoSMTPStartTLS(int sock) { 609 SocketLineReader line_reader(sock); 610 611 unsigned code_220 = 0; 612 std::string reply_220; 613 if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) { 614 return false; 615 } 616 617 if (code_220 != 220) { 618 fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n", 619 code_220); 620 return false; 621 } 622 623 static const char kHelloLine[] = "EHLO BoringSSL\r\n"; 624 if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) { 625 return false; 626 } 627 628 unsigned code_250 = 0; 629 std::string reply_250; 630 if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) { 631 return false; 632 } 633 634 if (code_250 != 250) { 635 fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250); 636 return false; 637 } 638 639 // https://tools.ietf.org/html/rfc1869#section-4.3 640 if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) { 641 fprintf(stderr, "Server does not support STARTTLS\n"); 642 return false; 643 } 644 645 static const char kSTARTTLSLine[] = "STARTTLS\r\n"; 646 if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) { 647 return false; 648 } 649 650 if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) { 651 return false; 652 } 653 654 if (code_220 != 220) { 655 fprintf( 656 stderr, 657 "Expected 220 line from SMTP server after STARTTLS, but got code %u\n", 658 code_220); 659 return false; 660 } 661 662 return true; 663 } 664 665 bool DoHTTPTunnel(int sock, const std::string &hostname_and_port) { 666 std::string hostname, port; 667 SplitHostPort(&hostname, &port, hostname_and_port); 668 669 fprintf(stderr, "Establishing HTTP tunnel to %s:%s.\n", hostname.c_str(), 670 port.c_str()); 671 char buf[1024]; 672 snprintf(buf, sizeof(buf), "CONNECT %s:%s HTTP/1.0\r\n\r\n", hostname.c_str(), 673 port.c_str()); 674 if (!SendAll(sock, buf, strlen(buf))) { 675 return false; 676 } 677 678 SocketLineReader line_reader(sock); 679 680 // Read until an empty line, signaling the end of the HTTP response. 681 std::string line; 682 for (;;) { 683 if (!line_reader.Next(&line)) { 684 return false; 685 } 686 if (line.empty()) { 687 return true; 688 } 689 fprintf(stderr, "%s\n", line.c_str()); 690 } 691 } 692