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