• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
15 #include <openssl/base.h>
16 
17 #include <stdio.h>
18 
19 #include <openssl/err.h>
20 #include <openssl/pem.h>
21 #include <openssl/ssl.h>
22 
23 #include "../crypto/test/scoped_types.h"
24 #include "../ssl/test/scoped_types.h"
25 #include "internal.h"
26 #include "transport_common.h"
27 
28 
29 static const struct argument kArguments[] = {
30     {
31      "-connect", kRequiredArgument,
32      "The hostname and port of the server to connect to, e.g. foo.com:443",
33     },
34     {
35      "-cipher", kOptionalArgument,
36      "An OpenSSL-style cipher suite string that configures the offered ciphers",
37     },
38     {
39      "-max-version", kOptionalArgument,
40      "The maximum acceptable protocol version",
41     },
42     {
43      "-min-version", kOptionalArgument,
44      "The minimum acceptable protocol version",
45     },
46     {
47      "-server-name", kOptionalArgument,
48      "The server name to advertise",
49     },
50     {
51      "-select-next-proto", kOptionalArgument,
52      "An NPN protocol to select if the server supports NPN",
53     },
54     {
55      "-alpn-protos", kOptionalArgument,
56      "A comma-separated list of ALPN protocols to advertise",
57     },
58     {
59      "-fallback-scsv", kBooleanArgument,
60      "Enable FALLBACK_SCSV",
61     },
62     {
63      "-ocsp-stapling", kBooleanArgument,
64      "Advertise support for OCSP stabling",
65     },
66     {
67      "-signed-certificate-timestamps", kBooleanArgument,
68      "Advertise support for signed certificate timestamps",
69     },
70     {
71      "-channel-id-key", kOptionalArgument,
72      "The key to use for signing a channel ID",
73     },
74     {
75      "-false-start", kBooleanArgument,
76      "Enable False Start",
77     },
78     { "-session-in", kOptionalArgument,
79       "A file containing a session to resume.",
80     },
81     { "-session-out", kOptionalArgument,
82       "A file to write the negotiated session to.",
83     },
84     {
85       "-key", kOptionalArgument,
86       "Private-key file to use (default is no client certificate)",
87     },
88     {
89      "", kOptionalArgument, "",
90     },
91 };
92 
LoadPrivateKey(const std::string & file)93 static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
94   ScopedBIO bio(BIO_new(BIO_s_file()));
95   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
96     return nullptr;
97   }
98   ScopedEVP_PKEY pkey(PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr,
99                                               nullptr));
100   return pkey;
101 }
102 
VersionFromString(uint16_t * out_version,const std::string & version)103 static bool VersionFromString(uint16_t *out_version,
104                               const std::string& version) {
105   if (version == "ssl3") {
106     *out_version = SSL3_VERSION;
107     return true;
108   } else if (version == "tls1" || version == "tls1.0") {
109     *out_version = TLS1_VERSION;
110     return true;
111   } else if (version == "tls1.1") {
112     *out_version = TLS1_1_VERSION;
113     return true;
114   } else if (version == "tls1.2") {
115     *out_version = TLS1_2_VERSION;
116     return true;
117   }
118   return false;
119 }
120 
NextProtoSelectCallback(SSL * ssl,uint8_t ** out,uint8_t * outlen,const uint8_t * in,unsigned inlen,void * arg)121 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
122                                    const uint8_t* in, unsigned inlen, void* arg) {
123   *out = reinterpret_cast<uint8_t *>(arg);
124   *outlen = strlen(reinterpret_cast<const char *>(arg));
125   return SSL_TLSEXT_ERR_OK;
126 }
127 
128 static FILE *g_keylog_file = nullptr;
129 
KeyLogCallback(const SSL * ssl,const char * line)130 static void KeyLogCallback(const SSL *ssl, const char *line) {
131   fprintf(g_keylog_file, "%s\n", line);
132   fflush(g_keylog_file);
133 }
134 
Client(const std::vector<std::string> & args)135 bool Client(const std::vector<std::string> &args) {
136   if (!InitSocketLibrary()) {
137     return false;
138   }
139 
140   std::map<std::string, std::string> args_map;
141 
142   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
143     PrintUsage(kArguments);
144     return false;
145   }
146 
147   ScopedSSL_CTX ctx(SSL_CTX_new(SSLv23_client_method()));
148 
149   const char *keylog_file = getenv("SSLKEYLOGFILE");
150   if (keylog_file) {
151     g_keylog_file = fopen(keylog_file, "a");
152     if (g_keylog_file == nullptr) {
153       perror("fopen");
154       return false;
155     }
156     SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
157   }
158 
159   if (args_map.count("-cipher") != 0 &&
160       !SSL_CTX_set_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
161     fprintf(stderr, "Failed setting cipher list\n");
162     return false;
163   }
164 
165   if (args_map.count("-max-version") != 0) {
166     uint16_t version;
167     if (!VersionFromString(&version, args_map["-max-version"])) {
168       fprintf(stderr, "Unknown protocol version: '%s'\n",
169               args_map["-max-version"].c_str());
170       return false;
171     }
172     SSL_CTX_set_max_version(ctx.get(), version);
173   }
174 
175   if (args_map.count("-min-version") != 0) {
176     uint16_t version;
177     if (!VersionFromString(&version, args_map["-min-version"])) {
178       fprintf(stderr, "Unknown protocol version: '%s'\n",
179               args_map["-min-version"].c_str());
180       return false;
181     }
182     SSL_CTX_set_min_version(ctx.get(), version);
183   }
184 
185   if (args_map.count("-select-next-proto") != 0) {
186     const std::string &proto = args_map["-select-next-proto"];
187     if (proto.size() > 255) {
188       fprintf(stderr, "Bad NPN protocol: '%s'\n", proto.c_str());
189       return false;
190     }
191     // |SSL_CTX_set_next_proto_select_cb| is not const-correct.
192     SSL_CTX_set_next_proto_select_cb(ctx.get(), NextProtoSelectCallback,
193                                      const_cast<char *>(proto.c_str()));
194   }
195 
196   if (args_map.count("-alpn-protos") != 0) {
197     const std::string &alpn_protos = args_map["-alpn-protos"];
198     std::vector<uint8_t> wire;
199     size_t i = 0;
200     while (i <= alpn_protos.size()) {
201       size_t j = alpn_protos.find(',', i);
202       if (j == std::string::npos) {
203         j = alpn_protos.size();
204       }
205       size_t len = j - i;
206       if (len > 255) {
207         fprintf(stderr, "Invalid ALPN protocols: '%s'\n", alpn_protos.c_str());
208         return false;
209       }
210       wire.push_back(static_cast<uint8_t>(len));
211       wire.resize(wire.size() + len);
212       memcpy(wire.data() + wire.size() - len, alpn_protos.data() + i, len);
213       i = j + 1;
214     }
215     if (SSL_CTX_set_alpn_protos(ctx.get(), wire.data(), wire.size()) != 0) {
216       return false;
217     }
218   }
219 
220   if (args_map.count("-fallback-scsv") != 0) {
221     SSL_CTX_set_mode(ctx.get(), SSL_MODE_SEND_FALLBACK_SCSV);
222   }
223 
224   if (args_map.count("-ocsp-stapling") != 0) {
225     SSL_CTX_enable_ocsp_stapling(ctx.get());
226   }
227 
228   if (args_map.count("-signed-certificate-timestamps") != 0) {
229     SSL_CTX_enable_signed_cert_timestamps(ctx.get());
230   }
231 
232   if (args_map.count("-channel-id-key") != 0) {
233     ScopedEVP_PKEY pkey = LoadPrivateKey(args_map["-channel-id-key"]);
234     if (!pkey || !SSL_CTX_set1_tls_channel_id(ctx.get(), pkey.get())) {
235       return false;
236     }
237   }
238 
239   if (args_map.count("-false-start") != 0) {
240     SSL_CTX_set_mode(ctx.get(), SSL_MODE_ENABLE_FALSE_START);
241   }
242 
243   if (args_map.count("-key") != 0) {
244     const std::string &key = args_map["-key"];
245     if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(), SSL_FILETYPE_PEM)) {
246       fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
247       return false;
248     }
249     if (!SSL_CTX_use_certificate_chain_file(ctx.get(), key.c_str())) {
250       fprintf(stderr, "Failed to load cert chain: %s\n", key.c_str());
251       return false;
252     }
253   }
254 
255   int sock = -1;
256   if (!Connect(&sock, args_map["-connect"])) {
257     return false;
258   }
259 
260   ScopedBIO bio(BIO_new_socket(sock, BIO_CLOSE));
261   ScopedSSL ssl(SSL_new(ctx.get()));
262 
263   if (args_map.count("-server-name") != 0) {
264     SSL_set_tlsext_host_name(ssl.get(), args_map["-server-name"].c_str());
265   }
266 
267   if (args_map.count("-session-in") != 0) {
268     ScopedBIO in(BIO_new_file(args_map["-session-in"].c_str(), "rb"));
269     if (!in) {
270       fprintf(stderr, "Error reading session\n");
271       ERR_print_errors_cb(PrintErrorCallback, stderr);
272       return false;
273     }
274     ScopedSSL_SESSION session(PEM_read_bio_SSL_SESSION(in.get(), nullptr,
275                                                        nullptr, nullptr));
276     if (!session) {
277       fprintf(stderr, "Error reading session\n");
278       ERR_print_errors_cb(PrintErrorCallback, stderr);
279       return false;
280     }
281     SSL_set_session(ssl.get(), session.get());
282   }
283 
284   SSL_set_bio(ssl.get(), bio.get(), bio.get());
285   bio.release();
286 
287   int ret = SSL_connect(ssl.get());
288   if (ret != 1) {
289     int ssl_err = SSL_get_error(ssl.get(), ret);
290     fprintf(stderr, "Error while connecting: %d\n", ssl_err);
291     ERR_print_errors_cb(PrintErrorCallback, stderr);
292     return false;
293   }
294 
295   fprintf(stderr, "Connected.\n");
296   PrintConnectionInfo(ssl.get());
297 
298   if (args_map.count("-session-out") != 0) {
299     ScopedBIO out(BIO_new_file(args_map["-session-out"].c_str(), "wb"));
300     if (!out ||
301         !PEM_write_bio_SSL_SESSION(out.get(), SSL_get0_session(ssl.get()))) {
302       fprintf(stderr, "Error while saving session:\n");
303       ERR_print_errors_cb(PrintErrorCallback, stderr);
304       return false;
305     }
306   }
307 
308   bool ok = TransferData(ssl.get(), sock);
309 
310   return ok;
311 }
312