Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

634 rindas
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. Listener::~Listener() {
  131. if (server_sock_ >= 0) {
  132. closesocket(server_sock_);
  133. }
  134. }
  135. bool Listener::Init(const std::string &port) {
  136. if (server_sock_ >= 0) {
  137. return false;
  138. }
  139. struct sockaddr_in6 addr;
  140. OPENSSL_memset(&addr, 0, sizeof(addr));
  141. addr.sin6_family = AF_INET6;
  142. addr.sin6_addr = IN6ADDR_ANY_INIT;
  143. addr.sin6_port = htons(atoi(port.c_str()));
  144. #if defined(OPENSSL_WINDOWS)
  145. const BOOL enable = TRUE;
  146. #else
  147. const int enable = 1;
  148. #endif
  149. server_sock_ = socket(addr.sin6_family, SOCK_STREAM, 0);
  150. if (server_sock_ < 0) {
  151. perror("socket");
  152. return false;
  153. }
  154. if (setsockopt(server_sock_, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable,
  155. sizeof(enable)) < 0) {
  156. perror("setsockopt");
  157. return false;
  158. }
  159. if (bind(server_sock_, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
  160. perror("connect");
  161. return false;
  162. }
  163. listen(server_sock_, SOMAXCONN);
  164. return true;
  165. }
  166. bool Listener::Accept(int *out_sock) {
  167. struct sockaddr_in6 addr;
  168. socklen_t addr_len = sizeof(addr);
  169. *out_sock = accept(server_sock_, (struct sockaddr *)&addr, &addr_len);
  170. return *out_sock >= 0;
  171. }
  172. bool VersionFromString(uint16_t *out_version, const std::string &version) {
  173. if (version == "ssl3") {
  174. *out_version = SSL3_VERSION;
  175. return true;
  176. } else if (version == "tls1" || version == "tls1.0") {
  177. *out_version = TLS1_VERSION;
  178. return true;
  179. } else if (version == "tls1.1") {
  180. *out_version = TLS1_1_VERSION;
  181. return true;
  182. } else if (version == "tls1.2") {
  183. *out_version = TLS1_2_VERSION;
  184. return true;
  185. } else if (version == "tls1.3") {
  186. *out_version = TLS1_3_VERSION;
  187. return true;
  188. }
  189. return false;
  190. }
  191. static const char *SignatureAlgorithmToString(uint16_t version, uint16_t sigalg) {
  192. const bool is_tls12 = version == TLS1_2_VERSION || version == DTLS1_2_VERSION;
  193. switch (sigalg) {
  194. case SSL_SIGN_RSA_PKCS1_SHA1:
  195. return "rsa_pkcs1_sha1";
  196. case SSL_SIGN_RSA_PKCS1_SHA256:
  197. return "rsa_pkcs1_sha256";
  198. case SSL_SIGN_RSA_PKCS1_SHA384:
  199. return "rsa_pkcs1_sha384";
  200. case SSL_SIGN_RSA_PKCS1_SHA512:
  201. return "rsa_pkcs1_sha512";
  202. case SSL_SIGN_ECDSA_SHA1:
  203. return "ecdsa_sha1";
  204. case SSL_SIGN_ECDSA_SECP256R1_SHA256:
  205. return is_tls12 ? "ecdsa_sha256" : "ecdsa_secp256r1_sha256";
  206. case SSL_SIGN_ECDSA_SECP384R1_SHA384:
  207. return is_tls12 ? "ecdsa_sha384" : "ecdsa_secp384r1_sha384";
  208. case SSL_SIGN_ECDSA_SECP521R1_SHA512:
  209. return is_tls12 ? "ecdsa_sha512" : "ecdsa_secp521r1_sha512";
  210. case SSL_SIGN_RSA_PSS_SHA256:
  211. return "rsa_pss_sha256";
  212. case SSL_SIGN_RSA_PSS_SHA384:
  213. return "rsa_pss_sha384";
  214. case SSL_SIGN_RSA_PSS_SHA512:
  215. return "rsa_pss_sha512";
  216. case SSL_SIGN_ED25519:
  217. return "ed25519";
  218. default:
  219. return "(unknown)";
  220. }
  221. }
  222. void PrintConnectionInfo(const SSL *ssl) {
  223. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  224. fprintf(stderr, " Version: %s\n", SSL_get_version(ssl));
  225. fprintf(stderr, " Resumed session: %s\n",
  226. SSL_session_reused(ssl) ? "yes" : "no");
  227. fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_standard_name(cipher));
  228. uint16_t curve = SSL_get_curve_id(ssl);
  229. if (curve != 0) {
  230. fprintf(stderr, " ECDHE curve: %s\n", SSL_get_curve_name(curve));
  231. }
  232. uint16_t sigalg = SSL_get_peer_signature_algorithm(ssl);
  233. if (sigalg != 0) {
  234. fprintf(stderr, " Signature algorithm: %s\n",
  235. SignatureAlgorithmToString(SSL_version(ssl), sigalg));
  236. }
  237. fprintf(stderr, " Secure renegotiation: %s\n",
  238. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  239. fprintf(stderr, " Extended master secret: %s\n",
  240. SSL_get_extms_support(ssl) ? "yes" : "no");
  241. const uint8_t *next_proto;
  242. unsigned next_proto_len;
  243. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  244. fprintf(stderr, " Next protocol negotiated: %.*s\n", next_proto_len,
  245. next_proto);
  246. const uint8_t *alpn;
  247. unsigned alpn_len;
  248. SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
  249. fprintf(stderr, " ALPN protocol: %.*s\n", alpn_len, alpn);
  250. const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  251. if (host_name != nullptr && SSL_is_server(ssl)) {
  252. fprintf(stderr, " Client sent SNI: %s\n", host_name);
  253. }
  254. if (!SSL_is_server(ssl)) {
  255. const uint8_t *ocsp_staple;
  256. size_t ocsp_staple_len;
  257. SSL_get0_ocsp_response(ssl, &ocsp_staple, &ocsp_staple_len);
  258. fprintf(stderr, " OCSP staple: %s\n", ocsp_staple_len > 0 ? "yes" : "no");
  259. const uint8_t *sct_list;
  260. size_t sct_list_len;
  261. SSL_get0_signed_cert_timestamp_list(ssl, &sct_list, &sct_list_len);
  262. fprintf(stderr, " SCT list: %s\n", sct_list_len > 0 ? "yes" : "no");
  263. }
  264. fprintf(stderr, " Early data: %s\n",
  265. SSL_early_data_accepted(ssl) ? "yes" : "no");
  266. // Print the server cert subject and issuer names.
  267. bssl::UniquePtr<X509> peer(SSL_get_peer_certificate(ssl));
  268. if (peer != nullptr) {
  269. fprintf(stderr, " Cert subject: ");
  270. X509_NAME_print_ex_fp(stderr, X509_get_subject_name(peer.get()), 0,
  271. XN_FLAG_ONELINE);
  272. fprintf(stderr, "\n Cert issuer: ");
  273. X509_NAME_print_ex_fp(stderr, X509_get_issuer_name(peer.get()), 0,
  274. XN_FLAG_ONELINE);
  275. fprintf(stderr, "\n");
  276. }
  277. }
  278. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  279. bool ok;
  280. #if defined(OPENSSL_WINDOWS)
  281. u_long arg = is_non_blocking;
  282. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  283. #else
  284. int flags = fcntl(sock, F_GETFL, 0);
  285. if (flags < 0) {
  286. return false;
  287. }
  288. if (is_non_blocking) {
  289. flags |= O_NONBLOCK;
  290. } else {
  291. flags &= ~O_NONBLOCK;
  292. }
  293. ok = 0 == fcntl(sock, F_SETFL, flags);
  294. #endif
  295. if (!ok) {
  296. fprintf(stderr, "Failed to set socket non-blocking.\n");
  297. }
  298. return ok;
  299. }
  300. // PrintErrorCallback is a callback function from OpenSSL's
  301. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  302. int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  303. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  304. return 1;
  305. }
  306. bool TransferData(SSL *ssl, int sock) {
  307. bool stdin_open = true;
  308. fd_set read_fds;
  309. FD_ZERO(&read_fds);
  310. if (!SocketSetNonBlocking(sock, true)) {
  311. return false;
  312. }
  313. for (;;) {
  314. if (stdin_open) {
  315. FD_SET(0, &read_fds);
  316. }
  317. FD_SET(sock, &read_fds);
  318. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  319. if (ret <= 0) {
  320. perror("select");
  321. return false;
  322. }
  323. if (FD_ISSET(0, &read_fds)) {
  324. uint8_t buffer[512];
  325. ssize_t n;
  326. do {
  327. n = BORINGSSL_READ(0, buffer, sizeof(buffer));
  328. } while (n == -1 && errno == EINTR);
  329. if (n == 0) {
  330. FD_CLR(0, &read_fds);
  331. stdin_open = false;
  332. #if !defined(OPENSSL_WINDOWS)
  333. shutdown(sock, SHUT_WR);
  334. #else
  335. shutdown(sock, SD_SEND);
  336. #endif
  337. continue;
  338. } else if (n < 0) {
  339. perror("read from stdin");
  340. return false;
  341. }
  342. if (!SocketSetNonBlocking(sock, false)) {
  343. return false;
  344. }
  345. int ssl_ret = SSL_write(ssl, buffer, n);
  346. if (!SocketSetNonBlocking(sock, true)) {
  347. return false;
  348. }
  349. if (ssl_ret <= 0) {
  350. int ssl_err = SSL_get_error(ssl, ssl_ret);
  351. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  352. ERR_print_errors_cb(PrintErrorCallback, stderr);
  353. return false;
  354. } else if (ssl_ret != n) {
  355. fprintf(stderr, "Short write from SSL_write.\n");
  356. return false;
  357. }
  358. }
  359. if (FD_ISSET(sock, &read_fds)) {
  360. uint8_t buffer[512];
  361. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  362. if (ssl_ret < 0) {
  363. int ssl_err = SSL_get_error(ssl, ssl_ret);
  364. if (ssl_err == SSL_ERROR_WANT_READ) {
  365. continue;
  366. }
  367. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  368. ERR_print_errors_cb(PrintErrorCallback, stderr);
  369. return false;
  370. } else if (ssl_ret == 0) {
  371. return true;
  372. }
  373. ssize_t n;
  374. do {
  375. n = BORINGSSL_WRITE(1, buffer, ssl_ret);
  376. } while (n == -1 && errno == EINTR);
  377. if (n != ssl_ret) {
  378. fprintf(stderr, "Short write to stderr.\n");
  379. return false;
  380. }
  381. }
  382. }
  383. }
  384. // SocketLineReader wraps a small buffer around a socket for line-orientated
  385. // protocols.
  386. class SocketLineReader {
  387. public:
  388. explicit SocketLineReader(int sock) : sock_(sock) {}
  389. // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
  390. // success, sets |*out_line| to it and returns true. Otherwise it returns
  391. // false.
  392. bool Next(std::string *out_line) {
  393. for (;;) {
  394. for (size_t i = 0; i < buf_len_; i++) {
  395. if (buf_[i] != '\n') {
  396. continue;
  397. }
  398. size_t length = i;
  399. if (i > 0 && buf_[i - 1] == '\r') {
  400. length--;
  401. }
  402. out_line->assign(buf_, length);
  403. buf_len_ -= i + 1;
  404. OPENSSL_memmove(buf_, &buf_[i + 1], buf_len_);
  405. return true;
  406. }
  407. if (buf_len_ == sizeof(buf_)) {
  408. fprintf(stderr, "Received line too long!\n");
  409. return false;
  410. }
  411. ssize_t n;
  412. do {
  413. n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
  414. } while (n == -1 && errno == EINTR);
  415. if (n < 0) {
  416. fprintf(stderr, "Read error from socket\n");
  417. return false;
  418. }
  419. buf_len_ += n;
  420. }
  421. }
  422. // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
  423. // success, it sets |*out_code| to the reply's code (e.g. 250) and
  424. // |*out_content| to the body of the reply (e.g. "OK") and returns true.
  425. // Otherwise it returns false.
  426. //
  427. // See https://tools.ietf.org/html/rfc821#page-48
  428. bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
  429. out_content->clear();
  430. // kMaxLines is the maximum number of lines that we'll accept in an SMTP
  431. // reply.
  432. static const unsigned kMaxLines = 512;
  433. for (unsigned i = 0; i < kMaxLines; i++) {
  434. std::string line;
  435. if (!Next(&line)) {
  436. return false;
  437. }
  438. if (line.size() < 4) {
  439. fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
  440. return false;
  441. }
  442. const std::string code_str = line.substr(0, 3);
  443. char *endptr;
  444. const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
  445. if (*endptr || code > UINT_MAX) {
  446. fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
  447. return false;
  448. }
  449. if (i == 0) {
  450. *out_code = code;
  451. } else if (code != *out_code) {
  452. fprintf(stderr,
  453. "Reply code varied within a single reply: was %u, now %u\n",
  454. *out_code, static_cast<unsigned>(code));
  455. return false;
  456. }
  457. if (line[3] == ' ') {
  458. // End of reply.
  459. *out_content += line.substr(4, std::string::npos);
  460. return true;
  461. } else if (line[3] == '-') {
  462. // Another line of reply will follow this one.
  463. *out_content += line.substr(4, std::string::npos);
  464. out_content->push_back('\n');
  465. } else {
  466. fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
  467. line.c_str());
  468. return false;
  469. }
  470. }
  471. fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
  472. return false;
  473. }
  474. private:
  475. const int sock_;
  476. char buf_[512];
  477. size_t buf_len_ = 0;
  478. };
  479. // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
  480. // success and false otherwise.
  481. static bool SendAll(int sock, const char *data, size_t data_len) {
  482. size_t done = 0;
  483. while (done < data_len) {
  484. ssize_t n;
  485. do {
  486. n = send(sock, &data[done], data_len - done, 0);
  487. } while (n == -1 && errno == EINTR);
  488. if (n < 0) {
  489. fprintf(stderr, "Error while writing to socket\n");
  490. return false;
  491. }
  492. done += n;
  493. }
  494. return true;
  495. }
  496. bool DoSMTPStartTLS(int sock) {
  497. SocketLineReader line_reader(sock);
  498. unsigned code_220 = 0;
  499. std::string reply_220;
  500. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  501. return false;
  502. }
  503. if (code_220 != 220) {
  504. fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
  505. code_220);
  506. return false;
  507. }
  508. static const char kHelloLine[] = "EHLO BoringSSL\r\n";
  509. if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
  510. return false;
  511. }
  512. unsigned code_250 = 0;
  513. std::string reply_250;
  514. if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
  515. return false;
  516. }
  517. if (code_250 != 250) {
  518. fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
  519. return false;
  520. }
  521. // https://tools.ietf.org/html/rfc1869#section-4.3
  522. if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) {
  523. fprintf(stderr, "Server does not support STARTTLS\n");
  524. return false;
  525. }
  526. static const char kSTARTTLSLine[] = "STARTTLS\r\n";
  527. if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
  528. return false;
  529. }
  530. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  531. return false;
  532. }
  533. if (code_220 != 220) {
  534. fprintf(
  535. stderr,
  536. "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
  537. code_220);
  538. return false;
  539. }
  540. return true;
  541. }