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