Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

563 righe
15 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. #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. void PrintConnectionInfo(const SSL *ssl) {
  175. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  176. fprintf(stderr, " Version: %s\n", SSL_get_version(ssl));
  177. fprintf(stderr, " Resumed session: %s\n",
  178. SSL_session_reused(ssl) ? "yes" : "no");
  179. fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_get_name(cipher));
  180. uint16_t curve = SSL_get_curve_id(ssl);
  181. if (curve != 0) {
  182. fprintf(stderr, " ECDHE curve: %s\n", SSL_get_curve_name(curve));
  183. }
  184. unsigned dhe_bits = SSL_get_dhe_group_size(ssl);
  185. if (dhe_bits != 0) {
  186. fprintf(stderr, " DHE group size: %u bits\n", dhe_bits);
  187. }
  188. fprintf(stderr, " Secure renegotiation: %s\n",
  189. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  190. fprintf(stderr, " Extended master secret: %s\n",
  191. SSL_get_extms_support(ssl) ? "yes" : "no");
  192. const uint8_t *next_proto;
  193. unsigned next_proto_len;
  194. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  195. fprintf(stderr, " Next protocol negotiated: %.*s\n", next_proto_len,
  196. next_proto);
  197. const uint8_t *alpn;
  198. unsigned alpn_len;
  199. SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
  200. fprintf(stderr, " ALPN protocol: %.*s\n", alpn_len, alpn);
  201. // Print the server cert subject and issuer names.
  202. X509 *peer = SSL_get_peer_certificate(ssl);
  203. if (peer != NULL) {
  204. fprintf(stderr, " Cert subject: ");
  205. X509_NAME_print_ex_fp(stderr, X509_get_subject_name(peer), 0,
  206. XN_FLAG_ONELINE);
  207. fprintf(stderr, "\n Cert issuer: ");
  208. X509_NAME_print_ex_fp(stderr, X509_get_issuer_name(peer), 0,
  209. XN_FLAG_ONELINE);
  210. fprintf(stderr, "\n");
  211. X509_free(peer);
  212. }
  213. }
  214. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  215. bool ok;
  216. #if defined(OPENSSL_WINDOWS)
  217. u_long arg = is_non_blocking;
  218. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  219. #else
  220. int flags = fcntl(sock, F_GETFL, 0);
  221. if (flags < 0) {
  222. return false;
  223. }
  224. if (is_non_blocking) {
  225. flags |= O_NONBLOCK;
  226. } else {
  227. flags &= ~O_NONBLOCK;
  228. }
  229. ok = 0 == fcntl(sock, F_SETFL, flags);
  230. #endif
  231. if (!ok) {
  232. fprintf(stderr, "Failed to set socket non-blocking.\n");
  233. }
  234. return ok;
  235. }
  236. // PrintErrorCallback is a callback function from OpenSSL's
  237. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  238. int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  239. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  240. return 1;
  241. }
  242. bool TransferData(SSL *ssl, int sock) {
  243. bool stdin_open = true;
  244. fd_set read_fds;
  245. FD_ZERO(&read_fds);
  246. if (!SocketSetNonBlocking(sock, true)) {
  247. return false;
  248. }
  249. for (;;) {
  250. if (stdin_open) {
  251. FD_SET(0, &read_fds);
  252. }
  253. FD_SET(sock, &read_fds);
  254. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  255. if (ret <= 0) {
  256. perror("select");
  257. return false;
  258. }
  259. if (FD_ISSET(0, &read_fds)) {
  260. uint8_t buffer[512];
  261. ssize_t n;
  262. do {
  263. n = BORINGSSL_READ(0, buffer, sizeof(buffer));
  264. } while (n == -1 && errno == EINTR);
  265. if (n == 0) {
  266. FD_CLR(0, &read_fds);
  267. stdin_open = false;
  268. #if !defined(OPENSSL_WINDOWS)
  269. shutdown(sock, SHUT_WR);
  270. #else
  271. shutdown(sock, SD_SEND);
  272. #endif
  273. continue;
  274. } else if (n < 0) {
  275. perror("read from stdin");
  276. return false;
  277. }
  278. if (!SocketSetNonBlocking(sock, false)) {
  279. return false;
  280. }
  281. int ssl_ret = SSL_write(ssl, buffer, n);
  282. if (!SocketSetNonBlocking(sock, true)) {
  283. return false;
  284. }
  285. if (ssl_ret <= 0) {
  286. int ssl_err = SSL_get_error(ssl, ssl_ret);
  287. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  288. ERR_print_errors_cb(PrintErrorCallback, stderr);
  289. return false;
  290. } else if (ssl_ret != n) {
  291. fprintf(stderr, "Short write from SSL_write.\n");
  292. return false;
  293. }
  294. }
  295. if (FD_ISSET(sock, &read_fds)) {
  296. uint8_t buffer[512];
  297. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  298. if (ssl_ret < 0) {
  299. int ssl_err = SSL_get_error(ssl, ssl_ret);
  300. if (ssl_err == SSL_ERROR_WANT_READ) {
  301. continue;
  302. }
  303. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  304. ERR_print_errors_cb(PrintErrorCallback, stderr);
  305. return false;
  306. } else if (ssl_ret == 0) {
  307. return true;
  308. }
  309. ssize_t n;
  310. do {
  311. n = BORINGSSL_WRITE(1, buffer, ssl_ret);
  312. } while (n == -1 && errno == EINTR);
  313. if (n != ssl_ret) {
  314. fprintf(stderr, "Short write to stderr.\n");
  315. return false;
  316. }
  317. }
  318. }
  319. }
  320. // SocketLineReader wraps a small buffer around a socket for line-orientated
  321. // protocols.
  322. class SocketLineReader {
  323. public:
  324. explicit SocketLineReader(int sock) : sock_(sock) {}
  325. // Next reads a '\n'- or '\r\n'-terminated line from the socket and, on
  326. // success, sets |*out_line| to it and returns true. Otherwise it returns
  327. // false.
  328. bool Next(std::string *out_line) {
  329. for (;;) {
  330. for (size_t i = 0; i < buf_len_; i++) {
  331. if (buf_[i] != '\n') {
  332. continue;
  333. }
  334. size_t length = i;
  335. if (i > 0 && buf_[i - 1] == '\r') {
  336. length--;
  337. }
  338. out_line->assign(buf_, length);
  339. buf_len_ -= i + 1;
  340. memmove(buf_, &buf_[i + 1], buf_len_);
  341. return true;
  342. }
  343. if (buf_len_ == sizeof(buf_)) {
  344. fprintf(stderr, "Received line too long!\n");
  345. return false;
  346. }
  347. ssize_t n;
  348. do {
  349. n = recv(sock_, &buf_[buf_len_], sizeof(buf_) - buf_len_, 0);
  350. } while (n == -1 && errno == EINTR);
  351. if (n < 0) {
  352. fprintf(stderr, "Read error from socket\n");
  353. return false;
  354. }
  355. buf_len_ += n;
  356. }
  357. }
  358. // ReadSMTPReply reads one or more lines that make up an SMTP reply. On
  359. // success, it sets |*out_code| to the reply's code (e.g. 250) and
  360. // |*out_content| to the body of the reply (e.g. "OK") and returns true.
  361. // Otherwise it returns false.
  362. //
  363. // See https://tools.ietf.org/html/rfc821#page-48
  364. bool ReadSMTPReply(unsigned *out_code, std::string *out_content) {
  365. out_content->clear();
  366. // kMaxLines is the maximum number of lines that we'll accept in an SMTP
  367. // reply.
  368. static const unsigned kMaxLines = 512;
  369. for (unsigned i = 0; i < kMaxLines; i++) {
  370. std::string line;
  371. if (!Next(&line)) {
  372. return false;
  373. }
  374. if (line.size() < 4) {
  375. fprintf(stderr, "Short line from SMTP server: %s\n", line.c_str());
  376. return false;
  377. }
  378. const std::string code_str = line.substr(0, 3);
  379. char *endptr;
  380. const unsigned long code = strtoul(code_str.c_str(), &endptr, 10);
  381. if (*endptr || code > UINT_MAX) {
  382. fprintf(stderr, "Failed to parse code from line: %s\n", line.c_str());
  383. return false;
  384. }
  385. if (i == 0) {
  386. *out_code = code;
  387. } else if (code != *out_code) {
  388. fprintf(stderr,
  389. "Reply code varied within a single reply: was %u, now %u\n",
  390. *out_code, static_cast<unsigned>(code));
  391. return false;
  392. }
  393. if (line[3] == ' ') {
  394. // End of reply.
  395. *out_content += line.substr(4, std::string::npos);
  396. return true;
  397. } else if (line[3] == '-') {
  398. // Another line of reply will follow this one.
  399. *out_content += line.substr(4, std::string::npos);
  400. out_content->push_back('\n');
  401. } else {
  402. fprintf(stderr, "Bad character after code in SMTP reply: %s\n",
  403. line.c_str());
  404. return false;
  405. }
  406. }
  407. fprintf(stderr, "Rejected SMTP reply of more then %u lines\n", kMaxLines);
  408. return false;
  409. }
  410. private:
  411. const int sock_;
  412. char buf_[512];
  413. size_t buf_len_ = 0;
  414. };
  415. // SendAll writes |data_len| bytes from |data| to |sock|. It returns true on
  416. // success and false otherwise.
  417. static bool SendAll(int sock, const char *data, size_t data_len) {
  418. size_t done = 0;
  419. while (done < data_len) {
  420. ssize_t n;
  421. do {
  422. n = send(sock, &data[done], data_len - done, 0);
  423. } while (n == -1 && errno == EINTR);
  424. if (n < 0) {
  425. fprintf(stderr, "Error while writing to socket\n");
  426. return false;
  427. }
  428. done += n;
  429. }
  430. return true;
  431. }
  432. bool DoSMTPStartTLS(int sock) {
  433. SocketLineReader line_reader(sock);
  434. unsigned code_220 = 0;
  435. std::string reply_220;
  436. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  437. return false;
  438. }
  439. if (code_220 != 220) {
  440. fprintf(stderr, "Expected 220 line from SMTP server but got code %u\n",
  441. code_220);
  442. return false;
  443. }
  444. static const char kHelloLine[] = "EHLO BoringSSL\r\n";
  445. if (!SendAll(sock, kHelloLine, sizeof(kHelloLine) - 1)) {
  446. return false;
  447. }
  448. unsigned code_250 = 0;
  449. std::string reply_250;
  450. if (!line_reader.ReadSMTPReply(&code_250, &reply_250)) {
  451. return false;
  452. }
  453. if (code_250 != 250) {
  454. fprintf(stderr, "Expected 250 line after EHLO but got code %u\n", code_250);
  455. return false;
  456. }
  457. // https://tools.ietf.org/html/rfc1869#section-4.3
  458. if (reply_250.find("\nSTARTTLS\n") == std::string::npos &&
  459. reply_250.find("\nSTARTTLS") != reply_250.size() - 8) {
  460. fprintf(stderr, "Server does not support STARTTLS\n");
  461. return false;
  462. }
  463. static const char kSTARTTLSLine[] = "STARTTLS\r\n";
  464. if (!SendAll(sock, kSTARTTLSLine, sizeof(kSTARTTLSLine) - 1)) {
  465. return false;
  466. }
  467. if (!line_reader.ReadSMTPReply(&code_220, &reply_220)) {
  468. return false;
  469. }
  470. if (code_220 != 220) {
  471. fprintf(
  472. stderr,
  473. "Expected 220 line from SMTP server after STARTTLS, but got code %u\n",
  474. code_220);
  475. return false;
  476. }
  477. return true;
  478. }