Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. #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;
  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. // Print the server cert subject and issuer names.
  236. X509 *peer = SSL_get_peer_certificate(ssl);
  237. if (peer != NULL) {
  238. fprintf(stderr, " Cert subject: ");
  239. X509_NAME_print_ex_fp(stderr, X509_get_subject_name(peer), 0,
  240. XN_FLAG_ONELINE);
  241. fprintf(stderr, "\n Cert issuer: ");
  242. X509_NAME_print_ex_fp(stderr, X509_get_issuer_name(peer), 0,
  243. XN_FLAG_ONELINE);
  244. fprintf(stderr, "\n");
  245. X509_free(peer);
  246. }
  247. }
  248. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  249. bool ok;
  250. #if defined(OPENSSL_WINDOWS)
  251. u_long arg = is_non_blocking;
  252. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  253. #else
  254. int flags = fcntl(sock, F_GETFL, 0);
  255. if (flags < 0) {
  256. return false;
  257. }
  258. if (is_non_blocking) {
  259. flags |= O_NONBLOCK;
  260. } else {
  261. flags &= ~O_NONBLOCK;
  262. }
  263. ok = 0 == fcntl(sock, F_SETFL, flags);
  264. #endif
  265. if (!ok) {
  266. fprintf(stderr, "Failed to set socket non-blocking.\n");
  267. }
  268. return ok;
  269. }
  270. // PrintErrorCallback is a callback function from OpenSSL's
  271. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  272. int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  273. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  274. return 1;
  275. }
  276. bool TransferData(SSL *ssl, int sock) {
  277. bool stdin_open = true;
  278. fd_set read_fds;
  279. FD_ZERO(&read_fds);
  280. if (!SocketSetNonBlocking(sock, true)) {
  281. return false;
  282. }
  283. for (;;) {
  284. if (stdin_open) {
  285. FD_SET(0, &read_fds);
  286. }
  287. FD_SET(sock, &read_fds);
  288. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  289. if (ret <= 0) {
  290. perror("select");
  291. return false;
  292. }
  293. if (FD_ISSET(0, &read_fds)) {
  294. uint8_t buffer[512];
  295. ssize_t n;
  296. do {
  297. n = BORINGSSL_READ(0, buffer, sizeof(buffer));
  298. } while (n == -1 && errno == EINTR);
  299. if (n == 0) {
  300. FD_CLR(0, &read_fds);
  301. stdin_open = false;
  302. #if !defined(OPENSSL_WINDOWS)
  303. shutdown(sock, SHUT_WR);
  304. #else
  305. shutdown(sock, SD_SEND);
  306. #endif
  307. continue;
  308. } else if (n < 0) {
  309. perror("read from stdin");
  310. return false;
  311. }
  312. if (!SocketSetNonBlocking(sock, false)) {
  313. return false;
  314. }
  315. int ssl_ret = SSL_write(ssl, buffer, n);
  316. if (!SocketSetNonBlocking(sock, true)) {
  317. return false;
  318. }
  319. if (ssl_ret <= 0) {
  320. int ssl_err = SSL_get_error(ssl, ssl_ret);
  321. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  322. ERR_print_errors_cb(PrintErrorCallback, stderr);
  323. return false;
  324. } else if (ssl_ret != n) {
  325. fprintf(stderr, "Short write from SSL_write.\n");
  326. return false;
  327. }
  328. }
  329. if (FD_ISSET(sock, &read_fds)) {
  330. uint8_t buffer[512];
  331. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  332. if (ssl_ret < 0) {
  333. int ssl_err = SSL_get_error(ssl, ssl_ret);
  334. if (ssl_err == SSL_ERROR_WANT_READ) {
  335. continue;
  336. }
  337. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  338. ERR_print_errors_cb(PrintErrorCallback, stderr);
  339. return false;
  340. } else if (ssl_ret == 0) {
  341. return true;
  342. }
  343. ssize_t n;
  344. do {
  345. n = BORINGSSL_WRITE(1, buffer, ssl_ret);
  346. } while (n == -1 && errno == EINTR);
  347. if (n != ssl_ret) {
  348. fprintf(stderr, "Short write to stderr.\n");
  349. return false;
  350. }
  351. }
  352. }
  353. }
  354. // SocketLineReader wraps a small buffer around a socket for line-orientated
  355. // protocols.
  356. class SocketLineReader {
  357. public:
  358. explicit SocketLineReader(int sock) : sock_(sock) {}
  359. // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
  360. // success, sets |*out_line| to it and returns true. Otherwise it returns
  361. // false.
  362. bool Next(std::string *out_line) {
  363. for (;;) {
  364. for (size_t i = 0; i < buf_len_; i++) {
  365. if (buf_[i] != '\n') {
  366. continue;
  367. }
  368. size_t length = i;
  369. if (i > 0 && buf_[i - 1] == '\r') {
  370. length--;
  371. }
  372. out_line->assign(buf_, length);
  373. buf_len_ -= i + 1;
  374. memmove(buf_, &buf_[i + 1], buf_len_);
  375. return true;
  376. }
  377. if (buf_len_ == sizeof(buf_)) {
  378. fprintf(stderr, "Received line too long!\n");
  379. return false;
  380. }
  381. ssize_t n;
  382. do {
  383. n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
  384. } while (n == -1 && errno == EINTR);
  385. if (n < 0) {
  386. fprintf(stderr, "Read error from socket\n");
  387. return false;
  388. }
  389. buf_len_ += n;
  390. }
  391. }
  392. // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
  393. // success, it sets |*out_code| to the reply's code (e.g. 250) and
  394. // |*out_content| to the body of the reply (e.g. "OK") and returns true.
  395. // Otherwise it returns false.
  396. //
  397. // See https://tools.ietf.org/html/rfc821#page-48
  398. bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
  399. out_content->clear();
  400. // kMaxLines is the maximum number of lines that we'll accept in an SMTP
  401. // reply.
  402. static const unsigned kMaxLines = 512;
  403. for (unsigned i = 0; i < kMaxLines; i++) {
  404. std::string line;
  405. if (!Next(&line)) {
  406. return false;
  407. }
  408. if (line.size() < 4) {
  409. fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
  410. return false;
  411. }
  412. const std::string code_str = line.substr(0, 3);
  413. char *endptr;
  414. const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
  415. if (*endptr || code > UINT_MAX) {
  416. fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
  417. return false;
  418. }
  419. if (i == 0) {
  420. *out_code = code;
  421. } else if (code != *out_code) {
  422. fprintf(stderr,
  423. "Reply code varied within a single reply: was %u, now %u\n",
  424. *out_code, static_cast<unsigned>(code));
  425. return false;
  426. }
  427. if (line[3] == ' ') {
  428. // End of reply.
  429. *out_content += line.substr(4, std::string::npos);
  430. return true;
  431. } else if (line[3] == '-') {
  432. // Another line of reply will follow this one.
  433. *out_content += line.substr(4, std::string::npos);
  434. out_content->push_back('\n');
  435. } else {
  436. fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
  437. line.c_str());
  438. return false;
  439. }
  440. }
  441. fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
  442. return false;
  443. }
  444. private:
  445. const int sock_;
  446. char buf_[512];
  447. size_t buf_len_ = 0;
  448. };
  449. // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
  450. // success and false otherwise.
  451. static bool SendAll(int sock, const char *data, size_t data_len) {
  452. size_t done = 0;
  453. while (done < data_len) {
  454. ssize_t n;
  455. do {
  456. n = send(sock, &data[done], data_len - done, 0);
  457. } while (n == -1 && errno == EINTR);
  458. if (n < 0) {
  459. fprintf(stderr, "Error while writing to socket\n");
  460. return false;
  461. }
  462. done += n;
  463. }
  464. return true;
  465. }
  466. bool DoSMTPStartTLS(int sock) {
  467. SocketLineReader line_reader(sock);
  468. unsigned code_220 = 0;
  469. std::string reply_220;
  470. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  471. return false;
  472. }
  473. if (code_220 != 220) {
  474. fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
  475. code_220);
  476. return false;
  477. }
  478. static const char kHelloLine[] = "EHLO BoringSSL\r\n";
  479. if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
  480. return false;
  481. }
  482. unsigned code_250 = 0;
  483. std::string reply_250;
  484. if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
  485. return false;
  486. }
  487. if (code_250 != 250) {
  488. fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
  489. return false;
  490. }
  491. // https://tools.ietf.org/html/rfc1869#section-4.3
  492. if (("\n" + reply_250 + "\n").find("\nSTARTTLS\n") == std::string::npos) {
  493. fprintf(stderr, "Server does not support STARTTLS\n");
  494. return false;
  495. }
  496. static const char kSTARTTLSLine[] = "STARTTLS\r\n";
  497. if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
  498. return false;
  499. }
  500. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  501. return false;
  502. }
  503. if (code_220 != 220) {
  504. fprintf(
  505. stderr,
  506. "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
  507. code_220);
  508. return false;
  509. }
  510. return true;
  511. }