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.
 
 
 
 
 
 

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