Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

281 рядки
7.2 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 <sys/types.h>
  18. #include <sys/socket.h>
  19. #if !defined(OPENSSL_WINDOWS)
  20. #include <arpa/inet.h>
  21. #include <fcntl.h>
  22. #include <netdb.h>
  23. #include <sys/select.h>
  24. #include <unistd.h>
  25. #else
  26. #include <WinSock2.h>
  27. #include <WS2tcpip.h>
  28. typedef int socklen_t;
  29. #endif
  30. #include <openssl/err.h>
  31. #include <openssl/ssl.h>
  32. #include "internal.h"
  33. static const struct argument kArguments[] = {
  34. {
  35. "-connect", true,
  36. "The hostname and port of the server to connect to, e.g. foo.com:443",
  37. },
  38. {
  39. "", false, "",
  40. },
  41. };
  42. // Connect sets |*out_sock| to be a socket connected to the destination given
  43. // in |hostname_and_port|, which should be of the form "www.example.com:123".
  44. // It returns true on success and false otherwise.
  45. static bool Connect(int *out_sock, const std::string &hostname_and_port) {
  46. const size_t colon_offset = hostname_and_port.find_last_of(':');
  47. std::string hostname, port;
  48. if (colon_offset == std::string::npos) {
  49. hostname = hostname_and_port;
  50. port = "443";
  51. } else {
  52. hostname = hostname_and_port.substr(0, colon_offset);
  53. port = hostname_and_port.substr(colon_offset + 1);
  54. }
  55. struct addrinfo hint, *result;
  56. memset(&hint, 0, sizeof(hint));
  57. hint.ai_family = AF_UNSPEC;
  58. hint.ai_socktype = SOCK_STREAM;
  59. int ret = getaddrinfo(hostname.c_str(), port.c_str(), &hint, &result);
  60. if (ret != 0) {
  61. fprintf(stderr, "getaddrinfo returned: %s\n", gai_strerror(ret));
  62. return false;
  63. }
  64. bool ok = false;
  65. char buf[256];
  66. *out_sock =
  67. socket(result->ai_family, result->ai_socktype, result->ai_protocol);
  68. if (*out_sock < 0) {
  69. perror("socket");
  70. goto out;
  71. }
  72. switch (result->ai_family) {
  73. case AF_INET: {
  74. struct sockaddr_in *sin =
  75. reinterpret_cast<struct sockaddr_in *>(result->ai_addr);
  76. fprintf(stderr, "Connecting to %s:%d\n",
  77. inet_ntop(result->ai_family, &sin->sin_addr, buf, sizeof(buf)),
  78. ntohs(sin->sin_port));
  79. break;
  80. }
  81. case AF_INET6: {
  82. struct sockaddr_in6 *sin6 =
  83. reinterpret_cast<struct sockaddr_in6 *>(result->ai_addr);
  84. fprintf(stderr, "Connecting to [%s]:%d\n",
  85. inet_ntop(result->ai_family, &sin6->sin6_addr, buf, sizeof(buf)),
  86. ntohs(sin6->sin6_port));
  87. break;
  88. }
  89. }
  90. if (connect(*out_sock, result->ai_addr, result->ai_addrlen) != 0) {
  91. perror("connect");
  92. goto out;
  93. }
  94. ok = true;
  95. out:
  96. freeaddrinfo(result);
  97. return ok;
  98. }
  99. static void PrintConnectionInfo(const SSL *ssl) {
  100. const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  101. fprintf(stderr, " Version: %s\n", SSL_get_version(ssl));
  102. fprintf(stderr, " Cipher: %s\n", SSL_CIPHER_get_name(cipher));
  103. fprintf(stderr, " Secure renegotiation: %s\n",
  104. SSL_get_secure_renegotiation_support(ssl) ? "yes" : "no");
  105. }
  106. static bool SocketSetNonBlocking(int sock, bool is_non_blocking) {
  107. bool ok;
  108. #if defined(OPENSSL_WINDOWS)
  109. u_long arg = is_non_blocking;
  110. ok = 0 == ioctlsocket(sock, FIOBIO, &arg);
  111. #else
  112. int flags = fcntl(sock, F_GETFL, 0);
  113. if (flags < 0) {
  114. return false;
  115. }
  116. if (is_non_blocking) {
  117. flags |= O_NONBLOCK;
  118. } else {
  119. flags &= ~O_NONBLOCK;
  120. }
  121. ok = 0 == fcntl(sock, F_SETFL, flags);
  122. #endif
  123. if (!ok) {
  124. fprintf(stderr, "Failed to set socket non-blocking.\n");
  125. }
  126. return ok;
  127. }
  128. // PrintErrorCallback is a callback function from OpenSSL's
  129. // |ERR_print_errors_cb| that writes errors to a given |FILE*|.
  130. static int PrintErrorCallback(const char *str, size_t len, void *ctx) {
  131. fwrite(str, len, 1, reinterpret_cast<FILE*>(ctx));
  132. return 1;
  133. }
  134. bool TransferData(SSL *ssl, int sock) {
  135. bool stdin_open = true;
  136. fd_set read_fds;
  137. FD_ZERO(&read_fds);
  138. if (!SocketSetNonBlocking(sock, true)) {
  139. return false;
  140. }
  141. for (;;) {
  142. if (stdin_open) {
  143. FD_SET(0, &read_fds);
  144. }
  145. FD_SET(sock, &read_fds);
  146. int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
  147. if (ret <= 0) {
  148. perror("select");
  149. return false;
  150. }
  151. if (FD_ISSET(0, &read_fds)) {
  152. uint8_t buffer[512];
  153. ssize_t n;
  154. do {
  155. n = read(0, buffer, sizeof(buffer));
  156. } while (n == -1 && errno == EINTR);
  157. if (n == 0) {
  158. FD_CLR(0, &read_fds);
  159. stdin_open = false;
  160. shutdown(sock, SHUT_WR);
  161. continue;
  162. } else if (n < 0) {
  163. perror("read from stdin");
  164. return false;
  165. }
  166. if (!SocketSetNonBlocking(sock, false)) {
  167. return false;
  168. }
  169. int ssl_ret = SSL_write(ssl, buffer, n);
  170. if (!SocketSetNonBlocking(sock, true)) {
  171. return false;
  172. }
  173. if (ssl_ret <= 0) {
  174. int ssl_err = SSL_get_error(ssl, ssl_ret);
  175. fprintf(stderr, "Error while writing: %d\n", ssl_err);
  176. ERR_print_errors_cb(PrintErrorCallback, stderr);
  177. return false;
  178. } else if (ssl_ret != n) {
  179. fprintf(stderr, "Short write from SSL_write.\n");
  180. return false;
  181. }
  182. }
  183. if (FD_ISSET(sock, &read_fds)) {
  184. uint8_t buffer[512];
  185. int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
  186. if (ssl_ret < 0) {
  187. int ssl_err = SSL_get_error(ssl, ssl_ret);
  188. if (ssl_err == SSL_ERROR_WANT_READ) {
  189. continue;
  190. }
  191. fprintf(stderr, "Error while reading: %d\n", ssl_err);
  192. ERR_print_errors_cb(PrintErrorCallback, stderr);
  193. return false;
  194. } else if (ssl_ret == 0) {
  195. return true;
  196. }
  197. ssize_t n;
  198. do {
  199. n = write(1, buffer, ssl_ret);
  200. } while (n == -1 && errno == EINTR);
  201. if (n != ssl_ret) {
  202. fprintf(stderr, "Short write to stderr.\n");
  203. return false;
  204. }
  205. }
  206. }
  207. }
  208. bool Client(const std::vector<std::string> &args) {
  209. std::map<std::string, std::string> args_map;
  210. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  211. PrintUsage(kArguments);
  212. return false;
  213. }
  214. SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method());
  215. int sock;
  216. if (!Connect(&sock, args_map["-connect"])) {
  217. return false;
  218. }
  219. BIO *bio = BIO_new_socket(sock, BIO_CLOSE);
  220. SSL *ssl = SSL_new(ctx);
  221. SSL_set_bio(ssl, bio, bio);
  222. int ret = SSL_connect(ssl);
  223. if (ret != 1) {
  224. int ssl_err = SSL_get_error(ssl, ret);
  225. fprintf(stderr, "Error while connecting: %d\n", ssl_err);
  226. ERR_print_errors_cb(PrintErrorCallback, stderr);
  227. return false;
  228. }
  229. fprintf(stderr, "Connected.\n");
  230. PrintConnectionInfo(ssl);
  231. bool ok = TransferData(ssl, sock);
  232. SSL_free(ssl);
  233. SSL_CTX_free(ctx);
  234. return ok;
  235. }