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.

transport_common.cc 9.2 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 <stddef.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <sys/types.h>
  22. #if !defined(OPENSSL_WINDOWS)
  23. #include <arpa/inet.h>
  24. #include <fcntl.h>
  25. #include <netdb.h>
  26. #include <netinet/in.h>
  27. #include <sys/select.h>
  28. #include <sys/socket.h>
  29. #include <unistd.h>
  30. #else
  31. #include <io.h>
  32. OPENSSL_MSVC_PRAGMA(warning(push, 3))
  33. #include <winsock2.h>
  34. #include <ws2tcpip.h>
  35. OPENSSL_MSVC_PRAGMA(warning(pop))
  36. typedef int ssize_t;
  37. #pragma comment(lib, "Ws2_32.lib")
  38. #endif
  39. #include <openssl/err.h>
  40. #include <openssl/ssl.h>
  41. #include <openssl/x509.h>
  42. #include "internal.h"
  43. #include "transport_common.h"
  44. #if !defined(OPENSSL_WINDOWS)
  45. static int closesocket(int sock) {
  46. return close(sock);
  47. }
  48. #endif
  49. bool InitSocketLibrary() {
  50. #if defined(OPENSSL_WINDOWS)
  51. WSADATA wsaData;
  52. int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
  53. if (err != 0) {
  54. fprintf(stderr, "WSAStartup failed with error %d\n", err);
  55. return false;
  56. }
  57. #endif
  58. return true;
  59. }
  60. // Connect sets |*out_sock| to be a socket connected to the destination given
  61. // in |hostname_and_port|, which should be of the form "www.example.com:123".
  62. // It returns true on success and false otherwise.
  63. bool Connect(int *out_sock, const std::string &hostname_and_port) {
  64. size_t colon_offset = hostname_and_port.find_last_of(':');
  65. const size_t bracket_offset = hostname_and_port.find_last_of(']');
  66. std::string hostname, port;
  67. // An IPv6 literal may have colons internally, guarded by square brackets.
  68. if (bracket_offset != std::string::npos &&
  69. colon_offset != std::string::npos && bracket_offset > colon_offset) {
  70. colon_offset = std::string::npos;
  71. }
  72. if (colon_offset == std::string::npos) {
  73. hostname = hostname_and_port;
  74. port = "443";
  75. } else {
  76. hostname = hostname_and_port.substr(0, colon_offset);
  77. port = hostname_and_port.substr(colon_offset + 1);
  78. }
  79. // Handle IPv6 literals.
  80. if (hostname.size() >= 2 && hostname[0] == '[' &&
  81. hostname[hostname.size() - 1] == ']') {
  82. hostname = hostname.substr(1, hostname.size() - 2);
  83. }
  84. struct addrinfo hint, *result;
  85. memset(&hint, 0, sizeof(hint));
  86. hint.ai_family = AF_UNSPEC;
  87. hint.ai_socktype = SOCK_STREAM;
  88. int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
  89. if (ret != 0) {
  90. fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
  91. return false;
  92. }
  93. bool ok = false;
  94. char buf[256];
  95. *out_sock =
  96. socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  97. if (*out_sock < 0) {
  98. perror("socket");
  99. goto out;
  100. }
  101. switch (result->ai_family) {
  102. case AF_INET: {
  103. struct sockaddr_in *sin =
  104. reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
  105. fprintf(stderr, "Connecting to %s:%d\n",
  106. inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
  107. ntohs(sin->sin_port));
  108. break;
  109. }
  110. case AF_INET6: {
  111. struct sockaddr_in6 *sin6 =
  112. reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
  113. fprintf(stderr, "Connecting to [%s]:%d\n",
  114. inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
  115. ntohs(sin6->sin6_port));
  116. break;
  117. }
  118. }
  119. if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
  120. perror("connect");
  121. goto out;
  122. }
  123. ok = true;
  124. out:
  125. freeaddrinfo(result);
  126. return ok;
  127. }
  128. bool Accept(int *out_sock, const std::string &port) {
  129. struct sockaddr_in6 addr, cli_addr;
  130. socklen_t cli_addr_len = sizeof(cli_addr);
  131. memset(&addr, 0, sizeof(addr));
  132. addr.sin6_family = AF_INET6;
  133. addr.sin6_addr = in6addr_any;
  134. addr.sin6_port = htons(atoi(port.c_str()));
  135. bool ok = false;
  136. int server_sock = -1;
  137. server_sock =
  138. socket(addr.sin6_family, SOCK_STREAM, 0);
  139. if (server_sock < 0) {
  140. perror("socket");
  141. goto out;
  142. }
  143. if (bind(server_sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
  144. perror("connect");
  145. goto out;
  146. }
  147. listen(server_sock, 1);
  148. *out_sock = accept(server_sock, (struct sockaddr*)&cli_addr, &cli_addr_len);
  149. ok = true;
  150. out:
  151. closesocket(server_sock);
  152. return ok;
  153. }
  154. void PrintConnectionInfo(const SSL *ssl) {
  155. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  156. fprintf(stderr, " Version: %s\n", SSL_get_version(ssl));
  157. fprintf(stderr, " Resumed session: %s\n",
  158. SSL_session_reused(ssl) ? "yes" : "no");
  159. fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_get_name(cipher));
  160. if (SSL_CIPHER_is_ECDHE(cipher)) {
  161. fprintf(stderr, " ECDHE curve: %s\n",
  162. SSL_get_curve_name(
  163. SSL_SESSION_get_key_exchange_info(SSL_get_session(ssl))));
  164. }
  165. fprintf(stderr, " Secure renegotiation: %s\n",
  166. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  167. fprintf(stderr, " Extended master secret: %s\n",
  168. SSL_get_extms_support(ssl) ? "yes" : "no");
  169. const uint8_t *next_proto;
  170. unsigned next_proto_len;
  171. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  172. fprintf(stderr, " Next protocol negotiated: %.*s\n", next_proto_len,
  173. next_proto);
  174. const uint8_t *alpn;
  175. unsigned alpn_len;
  176. SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
  177. fprintf(stderr, " ALPN protocol: %.*s\n", alpn_len, alpn);
  178. // Print the server cert subject and issuer names.
  179. X509 *peer = SSL_get_peer_certificate(ssl);
  180. if (peer != NULL) {
  181. fprintf(stderr, " Cert subject: ");
  182. X509_NAME_print_ex_fp(stderr, X509_get_subject_name(peer), 0,
  183. XN_FLAG_ONELINE);
  184. fprintf(stderr, "\n Cert issuer: ");
  185. X509_NAME_print_ex_fp(stderr, X509_get_issuer_name(peer), 0,
  186. XN_FLAG_ONELINE);
  187. fprintf(stderr, "\n");
  188. X509_free(peer);
  189. }
  190. }
  191. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  192. bool ok;
  193. #if defined(OPENSSL_WINDOWS)
  194. u_long arg = is_non_blocking;
  195. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  196. #else
  197. int flags = fcntl(sock, F_GETFL, 0);
  198. if (flags < 0) {
  199. return false;
  200. }
  201. if (is_non_blocking) {
  202. flags |= O_NONBLOCK;
  203. } else {
  204. flags &= ~O_NONBLOCK;
  205. }
  206. ok = 0 == fcntl(sock, F_SETFL, flags);
  207. #endif
  208. if (!ok) {
  209. fprintf(stderr, "Failed to set socket non-blocking.\n");
  210. }
  211. return ok;
  212. }
  213. // PrintErrorCallback is a callback function from OpenSSL's
  214. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  215. int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  216. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  217. return 1;
  218. }
  219. bool TransferData(SSL *ssl, int sock) {
  220. bool stdin_open = true;
  221. fd_set read_fds;
  222. FD_ZERO(&read_fds);
  223. if (!SocketSetNonBlocking(sock, true)) {
  224. return false;
  225. }
  226. for (;;) {
  227. if (stdin_open) {
  228. FD_SET(0, &read_fds);
  229. }
  230. FD_SET(sock, &read_fds);
  231. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  232. if (ret <= 0) {
  233. perror("select");
  234. return false;
  235. }
  236. if (FD_ISSET(0, &read_fds)) {
  237. uint8_t buffer[512];
  238. ssize_t n;
  239. do {
  240. n = BORINGSSL_READ(0, buffer, sizeof(buffer));
  241. } while (n == -1 && errno == EINTR);
  242. if (n == 0) {
  243. FD_CLR(0, &read_fds);
  244. stdin_open = false;
  245. #if !defined(OPENSSL_WINDOWS)
  246. shutdown(sock, SHUT_WR);
  247. #else
  248. shutdown(sock, SD_SEND);
  249. #endif
  250. continue;
  251. } else if (n < 0) {
  252. perror("read from stdin");
  253. return false;
  254. }
  255. if (!SocketSetNonBlocking(sock, false)) {
  256. return false;
  257. }
  258. int ssl_ret = SSL_write(ssl, buffer, n);
  259. if (!SocketSetNonBlocking(sock, true)) {
  260. return false;
  261. }
  262. if (ssl_ret <= 0) {
  263. int ssl_err = SSL_get_error(ssl, ssl_ret);
  264. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  265. ERR_print_errors_cb(PrintErrorCallback, stderr);
  266. return false;
  267. } else if (ssl_ret != n) {
  268. fprintf(stderr, "Short write from SSL_write.\n");
  269. return false;
  270. }
  271. }
  272. if (FD_ISSET(sock, &read_fds)) {
  273. uint8_t buffer[512];
  274. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  275. if (ssl_ret < 0) {
  276. int ssl_err = SSL_get_error(ssl, ssl_ret);
  277. if (ssl_err == SSL_ERROR_WANT_READ) {
  278. continue;
  279. }
  280. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  281. ERR_print_errors_cb(PrintErrorCallback, stderr);
  282. return false;
  283. } else if (ssl_ret == 0) {
  284. return true;
  285. }
  286. ssize_t n;
  287. do {
  288. n = BORINGSSL_WRITE(1, buffer, ssl_ret);
  289. } while (n == -1 && errno == EINTR);
  290. if (n != ssl_ret) {
  291. fprintf(stderr, "Short write to stderr.\n");
  292. return false;
  293. }
  294. }
  295. }
  296. }