Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

332 linhas
8.6 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 <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. #pragma warning(push, 3)
  33. #include <winsock2.h>
  34. #include <ws2tcpip.h>
  35. #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. const size_t colon_offset = hostname_and_port.find_last_of(':');
  65. std::string hostname, port;
  66. if (colon_offset == std::string::npos) {
  67. hostname = hostname_and_port;
  68. port = "443";
  69. } else {
  70. hostname = hostname_and_port.substr(0, colon_offset);
  71. port = hostname_and_port.substr(colon_offset + 1);
  72. }
  73. struct addrinfo hint, *result;
  74. memset(&hint, 0, sizeof(hint));
  75. hint.ai_family = AF_UNSPEC;
  76. hint.ai_socktype = SOCK_STREAM;
  77. int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
  78. if (ret != 0) {
  79. fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
  80. return false;
  81. }
  82. bool ok = false;
  83. char buf[256];
  84. *out_sock =
  85. socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  86. if (*out_sock < 0) {
  87. perror("socket");
  88. goto out;
  89. }
  90. switch (result->ai_family) {
  91. case AF_INET: {
  92. struct sockaddr_in *sin =
  93. reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
  94. fprintf(stderr, "Connecting to %s:%d\n",
  95. inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
  96. ntohs(sin->sin_port));
  97. break;
  98. }
  99. case AF_INET6: {
  100. struct sockaddr_in6 *sin6 =
  101. reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
  102. fprintf(stderr, "Connecting to [%s]:%d\n",
  103. inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
  104. ntohs(sin6->sin6_port));
  105. break;
  106. }
  107. }
  108. if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
  109. perror("connect");
  110. goto out;
  111. }
  112. ok = true;
  113. out:
  114. freeaddrinfo(result);
  115. return ok;
  116. }
  117. bool Accept(int *out_sock, const std::string &port) {
  118. struct sockaddr_in6 addr, cli_addr;
  119. socklen_t cli_addr_len = sizeof(cli_addr);
  120. memset(&addr, 0, sizeof(addr));
  121. addr.sin6_family = AF_INET6;
  122. addr.sin6_addr = in6addr_any;
  123. addr.sin6_port = htons(atoi(port.c_str()));
  124. bool ok = false;
  125. int server_sock = -1;
  126. server_sock =
  127. socket(addr.sin6_family, SOCK_STREAM, 0);
  128. if (server_sock < 0) {
  129. perror("socket");
  130. goto out;
  131. }
  132. if (bind(server_sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
  133. perror("connect");
  134. goto out;
  135. }
  136. listen(server_sock, 1);
  137. *out_sock = accept(server_sock, (struct sockaddr*)&cli_addr, &cli_addr_len);
  138. ok = true;
  139. out:
  140. closesocket(server_sock);
  141. return ok;
  142. }
  143. void PrintConnectionInfo(const SSL *ssl) {
  144. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  145. fprintf(stderr, " Version: %s\n", SSL_get_version(ssl));
  146. fprintf(stderr, " Resumed session: %s\n",
  147. SSL_session_reused(ssl) ? "yes" : "no");
  148. fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_get_name(cipher));
  149. if (SSL_CIPHER_is_ECDHE(cipher)) {
  150. fprintf(stderr, " ECDHE curve: %s\n",
  151. SSL_get_curve_name(
  152. SSL_SESSION_get_key_exchange_info(SSL_get_session(ssl))));
  153. }
  154. fprintf(stderr, " Secure renegotiation: %s\n",
  155. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  156. const uint8_t *next_proto;
  157. unsigned next_proto_len;
  158. SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
  159. fprintf(stderr, " Next protocol negotiated: %.*s\n", next_proto_len,
  160. next_proto);
  161. const uint8_t *alpn;
  162. unsigned alpn_len;
  163. SSL_get0_alpn_selected(ssl, &alpn, &alpn_len);
  164. fprintf(stderr, " ALPN protocol: %.*s\n", alpn_len, alpn);
  165. // Print the server cert subject and issuer names.
  166. X509 *peer = SSL_get_peer_certificate(ssl);
  167. if (peer != NULL) {
  168. fprintf(stderr, " Cert subject: ");
  169. X509_NAME_print_ex_fp(stderr, X509_get_subject_name(peer), 0,
  170. XN_FLAG_ONELINE);
  171. fprintf(stderr, "\n Cert issuer: ");
  172. X509_NAME_print_ex_fp(stderr, X509_get_issuer_name(peer), 0,
  173. XN_FLAG_ONELINE);
  174. fprintf(stderr, "\n");
  175. X509_free(peer);
  176. }
  177. }
  178. bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  179. bool ok;
  180. #if defined(OPENSSL_WINDOWS)
  181. u_long arg = is_non_blocking;
  182. ok = 0 == ioctlsocket(sock, FIONBIO, &arg);
  183. #else
  184. int flags = fcntl(sock, F_GETFL, 0);
  185. if (flags < 0) {
  186. return false;
  187. }
  188. if (is_non_blocking) {
  189. flags |= O_NONBLOCK;
  190. } else {
  191. flags &= ~O_NONBLOCK;
  192. }
  193. ok = 0 == fcntl(sock, F_SETFL, flags);
  194. #endif
  195. if (!ok) {
  196. fprintf(stderr, "Failed to set socket non-blocking.\n");
  197. }
  198. return ok;
  199. }
  200. // PrintErrorCallback is a callback function from OpenSSL's
  201. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  202. int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  203. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  204. return 1;
  205. }
  206. bool TransferData(SSL *ssl, int sock) {
  207. bool stdin_open = true;
  208. fd_set read_fds;
  209. FD_ZERO(&read_fds);
  210. if (!SocketSetNonBlocking(sock, true)) {
  211. return false;
  212. }
  213. for (;;) {
  214. if (stdin_open) {
  215. FD_SET(0, &read_fds);
  216. }
  217. FD_SET(sock, &read_fds);
  218. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  219. if (ret <= 0) {
  220. perror("select");
  221. return false;
  222. }
  223. if (FD_ISSET(0, &read_fds)) {
  224. uint8_t buffer[512];
  225. ssize_t n;
  226. do {
  227. n = read(0, buffer, sizeof(buffer));
  228. } while (n == -1 && errno == EINTR);
  229. if (n == 0) {
  230. FD_CLR(0, &read_fds);
  231. stdin_open = false;
  232. #if !defined(OPENSSL_WINDOWS)
  233. shutdown(sock, SHUT_WR);
  234. #else
  235. shutdown(sock, SD_SEND);
  236. #endif
  237. continue;
  238. } else if (n < 0) {
  239. perror("read from stdin");
  240. return false;
  241. }
  242. if (!SocketSetNonBlocking(sock, false)) {
  243. return false;
  244. }
  245. int ssl_ret = SSL_write(ssl, buffer, n);
  246. if (!SocketSetNonBlocking(sock, true)) {
  247. return false;
  248. }
  249. if (ssl_ret <= 0) {
  250. int ssl_err = SSL_get_error(ssl, ssl_ret);
  251. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  252. ERR_print_errors_cb(PrintErrorCallback, stderr);
  253. return false;
  254. } else if (ssl_ret != n) {
  255. fprintf(stderr, "Short write from SSL_write.\n");
  256. return false;
  257. }
  258. }
  259. if (FD_ISSET(sock, &read_fds)) {
  260. uint8_t buffer[512];
  261. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  262. if (ssl_ret < 0) {
  263. int ssl_err = SSL_get_error(ssl, ssl_ret);
  264. if (ssl_err == SSL_ERROR_WANT_READ) {
  265. continue;
  266. }
  267. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  268. ERR_print_errors_cb(PrintErrorCallback, stderr);
  269. return false;
  270. } else if (ssl_ret == 0) {
  271. return true;
  272. }
  273. ssize_t n;
  274. do {
  275. n = write(1, buffer, ssl_ret);
  276. } while (n == -1 && errno == EINTR);
  277. if (n != ssl_ret) {
  278. fprintf(stderr, "Short write to stderr.\n");
  279. return false;
  280. }
  281. }
  282. }
  283. }