1 // Copyright 2014 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <openssl/base.h>
16 
17 #include <stdio.h>
18 
19 #if !defined(OPENSSL_WINDOWS)
20 #include <sys/select.h>
21 #else
22 #include <winsock2.h>
23 #endif
24 
25 #include <openssl/err.h>
26 #include <openssl/pem.h>
27 #include <openssl/ssl.h>
28 
29 #include "../crypto/internal.h"
30 #include "internal.h"
31 #include "transport_common.h"
32 
33 
34 static const struct argument kArguments[] = {
35     {
36         "-connect", kRequiredArgument,
37         "The hostname and port of the server to connect to, e.g. foo.com:443",
38     },
39     {
40         "-cipher", kOptionalArgument,
41         "An OpenSSL-style cipher suite string that configures the offered "
42         "ciphers",
43     },
44     {
45         "-curves", kOptionalArgument,
46         "An OpenSSL-style ECDH curves list that configures the offered curves",
47     },
48     {
49         "-sigalgs", kOptionalArgument,
50         "An OpenSSL-style signature algorithms list that configures the "
51         "signature algorithm preferences",
52     },
53     {
54         "-max-version", kOptionalArgument,
55         "The maximum acceptable protocol version",
56     },
57     {
58         "-min-version", kOptionalArgument,
59         "The minimum acceptable protocol version",
60     },
61     {
62         "-server-name", kOptionalArgument, "The server name to advertise",
63     },
64     {
65         "-ech-grease", kBooleanArgument, "Enable ECH GREASE",
66     },
67     {
68         "-ech-config-list", kOptionalArgument,
69         "Path to file containing serialized ECHConfigs",
70     },
71     {
72         "-select-next-proto", kOptionalArgument,
73         "An NPN protocol to select if the server supports NPN",
74     },
75     {
76         "-alpn-protos", kOptionalArgument,
77         "A comma-separated list of ALPN protocols to advertise",
78     },
79     {
80         "-fallback-scsv", kBooleanArgument, "Enable FALLBACK_SCSV",
81     },
82     {
83         "-ocsp-stapling", kBooleanArgument,
84         "Advertise support for OCSP stabling",
85     },
86     {
87         "-signed-certificate-timestamps", kBooleanArgument,
88         "Advertise support for signed certificate timestamps",
89     },
90     {
91         "-channel-id-key", kOptionalArgument,
92         "The key to use for signing a channel ID",
93     },
94     {
95         "-false-start", kBooleanArgument, "Enable False Start",
96     },
97     {
98         "-session-in", kOptionalArgument,
99         "A file containing a session to resume.",
100     },
101     {
102         "-session-out", kOptionalArgument,
103         "A file to write the negotiated session to.",
104     },
105     {
106         "-key", kOptionalArgument,
107         "PEM-encoded file containing the private key.",
108     },
109     {
110         "-cert", kOptionalArgument,
111         "PEM-encoded file containing the leaf certificate and optional "
112         "certificate chain. This is taken from the -key argument if this "
113         "argument is not provided.",
114     },
115     {
116         "-starttls", kOptionalArgument,
117         "A STARTTLS mini-protocol to run before the TLS handshake. Supported"
118         " values: 'smtp'",
119     },
120     {
121         "-grease", kBooleanArgument, "Enable GREASE",
122     },
123     {
124         "-permute-extensions",
125         kBooleanArgument,
126         "Permute extensions in handshake messages",
127     },
128     {
129         "-test-resumption", kBooleanArgument,
130         "Connect to the server twice. The first connection is closed once a "
131         "session is established. The second connection offers it.",
132     },
133     {
134         "-root-certs", kOptionalArgument,
135         "A filename containing one or more PEM root certificates. Implies that "
136         "verification is required.",
137     },
138     {
139         "-root-cert-dir", kOptionalArgument,
140         "A directory containing one or more root certificate PEM files in "
141         "OpenSSL's hashed-directory format. Implies that verification is "
142         "required.",
143     },
144     {
145         "-early-data", kOptionalArgument, "Enable early data. The argument to "
146         "this flag is the early data to send or if it starts with '@', the "
147         "file to read from for early data.",
148     },
149     {
150         "-http-tunnel", kOptionalArgument,
151         "An HTTP proxy server to tunnel the TCP connection through",
152     },
153     {
154         "-renegotiate-freely", kBooleanArgument,
155         "Allow renegotiations from the peer.",
156     },
157     {
158         "-debug", kBooleanArgument,
159         "Print debug information about the handshake",
160     },
161     {
162         "", kOptionalArgument, "",
163     },
164 };
165 
LoadPrivateKey(const std::string & file)166 static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
167   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
168   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
169     return nullptr;
170   }
171   bssl::UniquePtr<EVP_PKEY> pkey(PEM_read_bio_PrivateKey(bio.get(), nullptr,
172                                  nullptr, nullptr));
173   return pkey;
174 }
175 
NextProtoSelectCallback(SSL * ssl,uint8_t ** out,uint8_t * outlen,const uint8_t * in,unsigned inlen,void * arg)176 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
177                                    const uint8_t* in, unsigned inlen, void* arg) {
178   *out = reinterpret_cast<uint8_t *>(arg);
179   *outlen = strlen(reinterpret_cast<const char *>(arg));
180   return SSL_TLSEXT_ERR_OK;
181 }
182 
183 static FILE *g_keylog_file = nullptr;
184 
KeyLogCallback(const SSL * ssl,const char * line)185 static void KeyLogCallback(const SSL *ssl, const char *line) {
186   fprintf(g_keylog_file, "%s\n", line);
187   fflush(g_keylog_file);
188 }
189 
190 static bssl::UniquePtr<BIO> session_out;
191 static bssl::UniquePtr<SSL_SESSION> resume_session;
192 
NewSessionCallback(SSL * ssl,SSL_SESSION * session)193 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
194   if (session_out) {
195     if (!PEM_write_bio_SSL_SESSION(session_out.get(), session) ||
196         BIO_flush(session_out.get()) <= 0) {
197       fprintf(stderr, "Error while saving session:\n");
198       ERR_print_errors_fp(stderr);
199       return 0;
200     }
201   }
202   resume_session = bssl::UniquePtr<SSL_SESSION>(session);
203   return 1;
204 }
205 
WaitForSession(SSL * ssl,int sock)206 static bool WaitForSession(SSL *ssl, int sock) {
207   fd_set read_fds;
208   FD_ZERO(&read_fds);
209 
210   if (!SocketSetNonBlocking(sock, true)) {
211     return false;
212   }
213 
214   while (!resume_session) {
215 #if defined(OPENSSL_WINDOWS)
216     // Windows sockets are really of type SOCKET, not int, but everything here
217     // casts them to ints. Clang gets unhappy about signed values as a result.
218     //
219     // TODO(davidben): Keep everything as the appropriate platform type.
220     FD_SET(static_cast<SOCKET>(sock), &read_fds);
221 #else
222     FD_SET(sock, &read_fds);
223 #endif
224     int ret = select(sock + 1, &read_fds, NULL, NULL, NULL);
225     if (ret <= 0) {
226       perror("select");
227       return false;
228     }
229 
230     uint8_t buffer[512];
231     int ssl_ret = SSL_read(ssl, buffer, sizeof(buffer));
232 
233     if (ssl_ret <= 0) {
234       int ssl_err = SSL_get_error(ssl, ssl_ret);
235       if (ssl_err == SSL_ERROR_WANT_READ) {
236         continue;
237       }
238       PrintSSLError(stderr, "Error while reading", ssl_err, ssl_ret);
239       return false;
240     }
241   }
242 
243   return true;
244 }
245 
DoConnection(SSL_CTX * ctx,std::map<std::string,std::string> args_map,bool (* cb)(SSL * ssl,int sock))246 static bool DoConnection(SSL_CTX *ctx,
247                          std::map<std::string, std::string> args_map,
248                          bool (*cb)(SSL *ssl, int sock)) {
249   int sock = -1;
250   if (args_map.count("-http-tunnel") != 0) {
251     if (!Connect(&sock, args_map["-http-tunnel"]) ||
252         !DoHTTPTunnel(sock, args_map["-connect"])) {
253       return false;
254     }
255   } else if (!Connect(&sock, args_map["-connect"])) {
256     return false;
257   }
258 
259   if (args_map.count("-starttls") != 0) {
260     const std::string& starttls = args_map["-starttls"];
261     if (starttls == "smtp") {
262       if (!DoSMTPStartTLS(sock)) {
263         return false;
264       }
265     } else {
266       fprintf(stderr, "Unknown value for -starttls: %s\n", starttls.c_str());
267       return false;
268     }
269   }
270 
271   bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_CLOSE));
272   bssl::UniquePtr<SSL> ssl(SSL_new(ctx));
273 
274   if (args_map.count("-server-name") != 0) {
275     SSL_set_tlsext_host_name(ssl.get(), args_map["-server-name"].c_str());
276   }
277 
278   if (args_map.count("-ech-grease") != 0) {
279     SSL_set_enable_ech_grease(ssl.get(), 1);
280   }
281 
282   if (args_map.count("-ech-config-list") != 0) {
283     const char *filename = args_map["-ech-config-list"].c_str();
284     ScopedFILE f(fopen(filename, "rb"));
285     std::vector<uint8_t> data;
286     if (f == nullptr || !ReadAll(&data, f.get())) {
287       fprintf(stderr, "Error reading %s.\n", filename);
288       return false;
289     }
290     if (!SSL_set1_ech_config_list(ssl.get(), data.data(), data.size())) {
291       fprintf(stderr, "Error setting ECHConfigList\n");
292       return false;
293     }
294   }
295 
296   if (args_map.count("-session-in") != 0) {
297     bssl::UniquePtr<BIO> in(BIO_new_file(args_map["-session-in"].c_str(),
298                                          "rb"));
299     if (!in) {
300       fprintf(stderr, "Error reading session\n");
301       ERR_print_errors_fp(stderr);
302       return false;
303     }
304     bssl::UniquePtr<SSL_SESSION> session(PEM_read_bio_SSL_SESSION(in.get(),
305                                          nullptr, nullptr, nullptr));
306     if (!session) {
307       fprintf(stderr, "Error reading session\n");
308       ERR_print_errors_fp(stderr);
309       return false;
310     }
311     SSL_set_session(ssl.get(), session.get());
312   }
313 
314   if (args_map.count("-renegotiate-freely") != 0) {
315     SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
316   }
317 
318   if (resume_session) {
319     SSL_set_session(ssl.get(), resume_session.get());
320   }
321 
322   SSL_set_bio(ssl.get(), bio.get(), bio.get());
323   bio.release();
324 
325   int ret = SSL_connect(ssl.get());
326   if (ret != 1) {
327     int ssl_err = SSL_get_error(ssl.get(), ret);
328     PrintSSLError(stderr, "Error while connecting", ssl_err, ret);
329     return false;
330   }
331 
332   if (args_map.count("-early-data") != 0 && SSL_in_early_data(ssl.get())) {
333     std::string early_data = args_map["-early-data"];
334     if (early_data.size() > 0 && early_data[0] == '@') {
335       const char *filename = early_data.c_str() + 1;
336       std::vector<uint8_t> data;
337       ScopedFILE f(fopen(filename, "rb"));
338       if (f == nullptr || !ReadAll(&data, f.get())) {
339         fprintf(stderr, "Error reading %s.\n", filename);
340         return false;
341       }
342       early_data = std::string(data.begin(), data.end());
343     }
344     if (!early_data.empty()) {
345       int ed_size = early_data.size();
346       int ssl_ret = SSL_write(ssl.get(), early_data.data(), ed_size);
347       if (ssl_ret <= 0) {
348         int ssl_err = SSL_get_error(ssl.get(), ssl_ret);
349         PrintSSLError(stderr, "Error while writing", ssl_err, ssl_ret);
350         return false;
351       } else if (ssl_ret != ed_size) {
352         fprintf(stderr, "Short write from SSL_write.\n");
353         return false;
354       }
355     }
356   }
357 
358   fprintf(stderr, "Connected.\n");
359   bssl::UniquePtr<BIO> bio_stderr(BIO_new_fp(stderr, BIO_NOCLOSE));
360   PrintConnectionInfo(bio_stderr.get(), ssl.get());
361 
362   return cb(ssl.get(), sock);
363 }
364 
InfoCallback(const SSL * ssl,int type,int value)365 static void InfoCallback(const SSL *ssl, int type, int value) {
366   switch (type) {
367     case SSL_CB_HANDSHAKE_START:
368       fprintf(stderr, "Handshake started.\n");
369       break;
370     case SSL_CB_HANDSHAKE_DONE:
371       fprintf(stderr, "Handshake done.\n");
372       break;
373     case SSL_CB_CONNECT_LOOP:
374       fprintf(stderr, "Handshake progress: %s\n", SSL_state_string_long(ssl));
375       break;
376   }
377 }
378 
Client(const std::vector<std::string> & args)379 bool Client(const std::vector<std::string> &args) {
380   if (!InitSocketLibrary()) {
381     return false;
382   }
383 
384   std::map<std::string, std::string> args_map;
385 
386   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
387     PrintUsage(kArguments);
388     return false;
389   }
390 
391   bssl::UniquePtr<SSL_CTX> ctx(SSL_CTX_new(TLS_method()));
392 
393   const char *keylog_file = getenv("SSLKEYLOGFILE");
394   if (keylog_file) {
395     g_keylog_file = fopen(keylog_file, "a");
396     if (g_keylog_file == nullptr) {
397       perror("fopen");
398       return false;
399     }
400     SSL_CTX_set_keylog_callback(ctx.get(), KeyLogCallback);
401   }
402 
403   if (args_map.count("-cipher") != 0 &&
404       !SSL_CTX_set_strict_cipher_list(ctx.get(), args_map["-cipher"].c_str())) {
405     fprintf(stderr, "Failed setting cipher list\n");
406     return false;
407   }
408 
409   if (args_map.count("-curves") != 0 &&
410       !SSL_CTX_set1_curves_list(ctx.get(), args_map["-curves"].c_str())) {
411     fprintf(stderr, "Failed setting curves list\n");
412     return false;
413   }
414 
415   if (args_map.count("-sigalgs") != 0 &&
416       !SSL_CTX_set1_sigalgs_list(ctx.get(), args_map["-sigalgs"].c_str())) {
417     fprintf(stderr, "Failed setting signature algorithms list\n");
418     return false;
419   }
420 
421   uint16_t max_version = TLS1_3_VERSION;
422   if (args_map.count("-max-version") != 0 &&
423       !VersionFromString(&max_version, args_map["-max-version"])) {
424     fprintf(stderr, "Unknown protocol version: '%s'\n",
425             args_map["-max-version"].c_str());
426     return false;
427   }
428 
429   if (!SSL_CTX_set_max_proto_version(ctx.get(), max_version)) {
430     return false;
431   }
432 
433   if (args_map.count("-min-version") != 0) {
434     uint16_t version;
435     if (!VersionFromString(&version, args_map["-min-version"])) {
436       fprintf(stderr, "Unknown protocol version: '%s'\n",
437               args_map["-min-version"].c_str());
438       return false;
439     }
440     if (!SSL_CTX_set_min_proto_version(ctx.get(), version)) {
441       return false;
442     }
443   }
444 
445   if (args_map.count("-select-next-proto") != 0) {
446     const std::string &proto = args_map["-select-next-proto"];
447     if (proto.size() > 255) {
448       fprintf(stderr, "Bad NPN protocol: '%s'\n", proto.c_str());
449       return false;
450     }
451     // |SSL_CTX_set_next_proto_select_cb| is not const-correct.
452     SSL_CTX_set_next_proto_select_cb(ctx.get(), NextProtoSelectCallback,
453                                      const_cast<char *>(proto.c_str()));
454   }
455 
456   if (args_map.count("-alpn-protos") != 0) {
457     const std::string &alpn_protos = args_map["-alpn-protos"];
458     std::vector<uint8_t> wire;
459     size_t i = 0;
460     while (i <= alpn_protos.size()) {
461       size_t j = alpn_protos.find(',', i);
462       if (j == std::string::npos) {
463         j = alpn_protos.size();
464       }
465       size_t len = j - i;
466       if (len > 255) {
467         fprintf(stderr, "Invalid ALPN protocols: '%s'\n", alpn_protos.c_str());
468         return false;
469       }
470       wire.push_back(static_cast<uint8_t>(len));
471       wire.resize(wire.size() + len);
472       OPENSSL_memcpy(wire.data() + wire.size() - len, alpn_protos.data() + i,
473                      len);
474       i = j + 1;
475     }
476     if (SSL_CTX_set_alpn_protos(ctx.get(), wire.data(), wire.size()) != 0) {
477       return false;
478     }
479   }
480 
481   if (args_map.count("-fallback-scsv") != 0) {
482     SSL_CTX_set_mode(ctx.get(), SSL_MODE_SEND_FALLBACK_SCSV);
483   }
484 
485   if (args_map.count("-ocsp-stapling") != 0) {
486     SSL_CTX_enable_ocsp_stapling(ctx.get());
487   }
488 
489   if (args_map.count("-signed-certificate-timestamps") != 0) {
490     SSL_CTX_enable_signed_cert_timestamps(ctx.get());
491   }
492 
493   if (args_map.count("-channel-id-key") != 0) {
494     bssl::UniquePtr<EVP_PKEY> pkey =
495         LoadPrivateKey(args_map["-channel-id-key"]);
496     if (!pkey || !SSL_CTX_set1_tls_channel_id(ctx.get(), pkey.get())) {
497       return false;
498     }
499   }
500 
501   if (args_map.count("-false-start") != 0) {
502     SSL_CTX_set_mode(ctx.get(), SSL_MODE_ENABLE_FALSE_START);
503   }
504 
505   if (args_map.count("-key") != 0) {
506     const std::string &key = args_map["-key"];
507     if (!SSL_CTX_use_PrivateKey_file(ctx.get(), key.c_str(),
508                                      SSL_FILETYPE_PEM)) {
509       fprintf(stderr, "Failed to load private key: %s\n", key.c_str());
510       return false;
511     }
512     const std::string &cert =
513         args_map.count("-cert") != 0 ? args_map["-cert"] : key;
514     if (!SSL_CTX_use_certificate_chain_file(ctx.get(), cert.c_str())) {
515       fprintf(stderr, "Failed to load cert chain: %s\n", cert.c_str());
516       return false;
517     }
518   }
519 
520   SSL_CTX_set_session_cache_mode(ctx.get(), SSL_SESS_CACHE_CLIENT);
521   SSL_CTX_sess_set_new_cb(ctx.get(), NewSessionCallback);
522 
523   if (args_map.count("-session-out") != 0) {
524     session_out.reset(BIO_new_file(args_map["-session-out"].c_str(), "wb"));
525     if (!session_out) {
526       fprintf(stderr, "Error while opening %s:\n",
527               args_map["-session-out"].c_str());
528       ERR_print_errors_fp(stderr);
529       return false;
530     }
531   }
532 
533   if (args_map.count("-grease") != 0) {
534     SSL_CTX_set_grease_enabled(ctx.get(), 1);
535   }
536 
537   if (args_map.count("-permute-extensions") != 0) {
538     SSL_CTX_set_permute_extensions(ctx.get(), 1);
539   }
540 
541   if (args_map.count("-root-certs") != 0) {
542     if (!SSL_CTX_load_verify_locations(
543             ctx.get(), args_map["-root-certs"].c_str(), nullptr)) {
544       fprintf(stderr, "Failed to load root certificates.\n");
545       ERR_print_errors_fp(stderr);
546       return false;
547     }
548     SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr);
549   }
550 
551   if (args_map.count("-root-cert-dir") != 0) {
552     if (!SSL_CTX_load_verify_locations(
553             ctx.get(), nullptr, args_map["-root-cert-dir"].c_str())) {
554       fprintf(stderr, "Failed to load root certificates.\n");
555       ERR_print_errors_fp(stderr);
556       return false;
557     }
558     SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER, nullptr);
559   }
560 
561   if (args_map.count("-early-data") != 0) {
562     SSL_CTX_set_early_data_enabled(ctx.get(), 1);
563   }
564 
565   if (args_map.count("-debug") != 0) {
566     SSL_CTX_set_info_callback(ctx.get(), InfoCallback);
567   }
568 
569   if (args_map.count("-test-resumption") != 0) {
570     if (args_map.count("-session-in") != 0) {
571       fprintf(stderr,
572               "Flags -session-in and -test-resumption are incompatible.\n");
573       return false;
574     }
575 
576     if (!DoConnection(ctx.get(), args_map, &WaitForSession)) {
577       return false;
578     }
579   }
580 
581   return DoConnection(ctx.get(), args_map, &TransferData);
582 }
583