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.
 
 
 
 
 
 

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