You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

626 rivejä
17 KiB

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