Fix ossl_shim SNI handling
[oweals/openssl.git] / test / ossl_shim / ossl_shim.cc
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #if !defined(__STDC_FORMAT_MACROS)
11 #define __STDC_FORMAT_MACROS
12 #endif
13
14 #include "packeted_bio.h"
15 #include <openssl/e_os2.h>
16
17 #if !defined(OPENSSL_SYS_WINDOWS)
18 #include <arpa/inet.h>
19 #include <netinet/in.h>
20 #include <netinet/tcp.h>
21 #include <signal.h>
22 #include <sys/socket.h>
23 #include <sys/time.h>
24 #include <unistd.h>
25 #else
26 #include <io.h>
27 OPENSSL_MSVC_PRAGMA(warning(push, 3))
28 #include <winsock2.h>
29 #include <ws2tcpip.h>
30 OPENSSL_MSVC_PRAGMA(warning(pop))
31
32 OPENSSL_MSVC_PRAGMA(comment(lib, "Ws2_32.lib"))
33 #endif
34
35 #include <assert.h>
36 #include <inttypes.h>
37 #include <string.h>
38
39 #include <openssl/bio.h>
40 #include <openssl/buffer.h>
41 #include <openssl/bn.h>
42 #include <openssl/crypto.h>
43 #include <openssl/dh.h>
44 #include <openssl/err.h>
45 #include <openssl/evp.h>
46 #include <openssl/hmac.h>
47 #include <openssl/objects.h>
48 #include <openssl/rand.h>
49 #include <openssl/ssl.h>
50 #include <openssl/x509.h>
51
52 #include <memory>
53 #include <string>
54 #include <vector>
55
56 #include "async_bio.h"
57 #include "test_config.h"
58
59 namespace bssl {
60
61 #if !defined(OPENSSL_SYS_WINDOWS)
62 static int closesocket(int sock) {
63   return close(sock);
64 }
65
66 static void PrintSocketError(const char *func) {
67   perror(func);
68 }
69 #else
70 static void PrintSocketError(const char *func) {
71   fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
72 }
73 #endif
74
75 static int Usage(const char *program) {
76   fprintf(stderr, "Usage: %s [flags...]\n", program);
77   return 1;
78 }
79
80 struct TestState {
81   // async_bio is async BIO which pauses reads and writes.
82   BIO *async_bio = nullptr;
83   // packeted_bio is the packeted BIO which simulates read timeouts.
84   BIO *packeted_bio = nullptr;
85   bool cert_ready = false;
86   bool handshake_done = false;
87   // private_key is the underlying private key used when testing custom keys.
88   bssl::UniquePtr<EVP_PKEY> private_key;
89   bool got_new_session = false;
90   bssl::UniquePtr<SSL_SESSION> new_session;
91   bool ticket_decrypt_done = false;
92   bool alpn_select_done = false;
93 };
94
95 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
96                             int index, long argl, void *argp) {
97   delete ((TestState *)ptr);
98 }
99
100 static int g_config_index = 0;
101 static int g_state_index = 0;
102
103 static bool SetTestConfig(SSL *ssl, const TestConfig *config) {
104   return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
105 }
106
107 static const TestConfig *GetTestConfig(const SSL *ssl) {
108   return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
109 }
110
111 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
112   // |SSL_set_ex_data| takes ownership of |state| only on success.
113   if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
114     state.release();
115     return true;
116   }
117   return false;
118 }
119
120 static TestState *GetTestState(const SSL *ssl) {
121   return (TestState *)SSL_get_ex_data(ssl, g_state_index);
122 }
123
124 static bssl::UniquePtr<X509> LoadCertificate(const std::string &file) {
125   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
126   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
127     return nullptr;
128   }
129   return bssl::UniquePtr<X509>(PEM_read_bio_X509(bio.get(), NULL, NULL, NULL));
130 }
131
132 static bssl::UniquePtr<EVP_PKEY> LoadPrivateKey(const std::string &file) {
133   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
134   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
135     return nullptr;
136   }
137   return bssl::UniquePtr<EVP_PKEY>(
138       PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
139 }
140
141 template<typename T>
142 struct Free {
143   void operator()(T *buf) {
144     free(buf);
145   }
146 };
147
148 static bool GetCertificate(SSL *ssl, bssl::UniquePtr<X509> *out_x509,
149                            bssl::UniquePtr<EVP_PKEY> *out_pkey) {
150   const TestConfig *config = GetTestConfig(ssl);
151
152   if (!config->key_file.empty()) {
153     *out_pkey = LoadPrivateKey(config->key_file.c_str());
154     if (!*out_pkey) {
155       return false;
156     }
157   }
158   if (!config->cert_file.empty()) {
159     *out_x509 = LoadCertificate(config->cert_file.c_str());
160     if (!*out_x509) {
161       return false;
162     }
163   }
164   return true;
165 }
166
167 static bool InstallCertificate(SSL *ssl) {
168   bssl::UniquePtr<X509> x509;
169   bssl::UniquePtr<EVP_PKEY> pkey;
170   if (!GetCertificate(ssl, &x509, &pkey)) {
171     return false;
172   }
173
174   if (pkey && !SSL_use_PrivateKey(ssl, pkey.get())) {
175     return false;
176   }
177
178   if (x509 && !SSL_use_certificate(ssl, x509.get())) {
179     return false;
180   }
181
182   return true;
183 }
184
185 static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
186   if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) {
187     return -1;
188   }
189
190   bssl::UniquePtr<X509> x509;
191   bssl::UniquePtr<EVP_PKEY> pkey;
192   if (!GetCertificate(ssl, &x509, &pkey)) {
193     return -1;
194   }
195
196   // Return zero for no certificate.
197   if (!x509) {
198     return 0;
199   }
200
201   // Asynchronous private keys are not supported with client_cert_cb.
202   *out_x509 = x509.release();
203   *out_pkey = pkey.release();
204   return 1;
205 }
206
207 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
208   return 1;
209 }
210
211 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
212   X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_APPLICATION_VERIFICATION);
213   return 0;
214 }
215
216 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
217                                         unsigned int *out_len, void *arg) {
218   const TestConfig *config = GetTestConfig(ssl);
219   if (config->advertise_npn.empty()) {
220     return SSL_TLSEXT_ERR_NOACK;
221   }
222
223   *out = (const uint8_t*)config->advertise_npn.data();
224   *out_len = config->advertise_npn.size();
225   return SSL_TLSEXT_ERR_OK;
226 }
227
228 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
229                                    const uint8_t* in, unsigned inlen, void* arg) {
230   const TestConfig *config = GetTestConfig(ssl);
231   if (config->select_next_proto.empty()) {
232     return SSL_TLSEXT_ERR_NOACK;
233   }
234
235   *out = (uint8_t*)config->select_next_proto.data();
236   *outlen = config->select_next_proto.size();
237   return SSL_TLSEXT_ERR_OK;
238 }
239
240 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
241                               const uint8_t* in, unsigned inlen, void* arg) {
242   if (GetTestState(ssl)->alpn_select_done) {
243     fprintf(stderr, "AlpnSelectCallback called after completion.\n");
244     exit(1);
245   }
246
247   GetTestState(ssl)->alpn_select_done = true;
248
249   const TestConfig *config = GetTestConfig(ssl);
250   if (config->decline_alpn) {
251     return SSL_TLSEXT_ERR_NOACK;
252   }
253
254   if (!config->expected_advertised_alpn.empty() &&
255       (config->expected_advertised_alpn.size() != inlen ||
256        memcmp(config->expected_advertised_alpn.data(),
257               in, inlen) != 0)) {
258     fprintf(stderr, "bad ALPN select callback inputs\n");
259     exit(1);
260   }
261
262   *out = (const uint8_t*)config->select_alpn.data();
263   *outlen = config->select_alpn.size();
264   return SSL_TLSEXT_ERR_OK;
265 }
266
267 static unsigned PskClientCallback(SSL *ssl, const char *hint,
268                                   char *out_identity,
269                                   unsigned max_identity_len,
270                                   uint8_t *out_psk, unsigned max_psk_len) {
271   const TestConfig *config = GetTestConfig(ssl);
272
273   if (config->psk_identity.empty()) {
274     if (hint != nullptr) {
275       fprintf(stderr, "Server PSK hint was non-null.\n");
276       return 0;
277     }
278   } else if (hint == nullptr ||
279              strcmp(hint, config->psk_identity.c_str()) != 0) {
280     fprintf(stderr, "Server PSK hint did not match.\n");
281     return 0;
282   }
283
284   // Account for the trailing '\0' for the identity.
285   if (config->psk_identity.size() >= max_identity_len ||
286       config->psk.size() > max_psk_len) {
287     fprintf(stderr, "PSK buffers too small\n");
288     return 0;
289   }
290
291   BUF_strlcpy(out_identity, config->psk_identity.c_str(),
292               max_identity_len);
293   memcpy(out_psk, config->psk.data(), config->psk.size());
294   return config->psk.size();
295 }
296
297 static unsigned PskServerCallback(SSL *ssl, const char *identity,
298                                   uint8_t *out_psk, unsigned max_psk_len) {
299   const TestConfig *config = GetTestConfig(ssl);
300
301   if (strcmp(identity, config->psk_identity.c_str()) != 0) {
302     fprintf(stderr, "Client PSK identity did not match.\n");
303     return 0;
304   }
305
306   if (config->psk.size() > max_psk_len) {
307     fprintf(stderr, "PSK buffers too small\n");
308     return 0;
309   }
310
311   memcpy(out_psk, config->psk.data(), config->psk.size());
312   return config->psk.size();
313 }
314
315 static int CertCallback(SSL *ssl, void *arg) {
316   const TestConfig *config = GetTestConfig(ssl);
317
318   // Check the CertificateRequest metadata is as expected.
319   //
320   // TODO(davidben): Test |SSL_get_client_CA_list|.
321   if (!SSL_is_server(ssl) &&
322       !config->expected_certificate_types.empty()) {
323     const uint8_t *certificate_types;
324     size_t certificate_types_len =
325         SSL_get0_certificate_types(ssl, &certificate_types);
326     if (certificate_types_len != config->expected_certificate_types.size() ||
327         memcmp(certificate_types,
328                config->expected_certificate_types.data(),
329                certificate_types_len) != 0) {
330       fprintf(stderr, "certificate types mismatch\n");
331       return 0;
332     }
333   }
334
335   // The certificate will be installed via other means.
336   if (!config->async ||
337       config->use_old_client_cert_callback) {
338     return 1;
339   }
340
341   if (!GetTestState(ssl)->cert_ready) {
342     return -1;
343   }
344   if (!InstallCertificate(ssl)) {
345     return 0;
346   }
347   return 1;
348 }
349
350 static void InfoCallback(const SSL *ssl, int type, int val) {
351   if (type == SSL_CB_HANDSHAKE_DONE) {
352     if (GetTestConfig(ssl)->handshake_never_done) {
353       fprintf(stderr, "Handshake unexpectedly completed.\n");
354       // Abort before any expected error code is printed, to ensure the overall
355       // test fails.
356       abort();
357     }
358     GetTestState(ssl)->handshake_done = true;
359
360     // Callbacks may be called again on a new handshake.
361     GetTestState(ssl)->ticket_decrypt_done = false;
362     GetTestState(ssl)->alpn_select_done = false;
363   }
364 }
365
366 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
367   GetTestState(ssl)->got_new_session = true;
368   GetTestState(ssl)->new_session.reset(session);
369   return 1;
370 }
371
372 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
373                              EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
374                              int encrypt) {
375   if (!encrypt) {
376     if (GetTestState(ssl)->ticket_decrypt_done) {
377       fprintf(stderr, "TicketKeyCallback called after completion.\n");
378       return -1;
379     }
380
381     GetTestState(ssl)->ticket_decrypt_done = true;
382   }
383
384   // This is just test code, so use the all-zeros key.
385   static const uint8_t kZeros[16] = {0};
386
387   if (encrypt) {
388     memcpy(key_name, kZeros, sizeof(kZeros));
389     RAND_bytes(iv, 16);
390   } else if (memcmp(key_name, kZeros, 16) != 0) {
391     return 0;
392   }
393
394   if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
395       !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
396     return -1;
397   }
398
399   if (!encrypt) {
400     return GetTestConfig(ssl)->renew_ticket ? 2 : 1;
401   }
402   return 1;
403 }
404
405 // kCustomExtensionValue is the extension value that the custom extension
406 // callbacks will add.
407 static const uint16_t kCustomExtensionValue = 1234;
408 static void *const kCustomExtensionAddArg =
409     reinterpret_cast<void *>(kCustomExtensionValue);
410 static void *const kCustomExtensionParseArg =
411     reinterpret_cast<void *>(kCustomExtensionValue + 1);
412 static const char kCustomExtensionContents[] = "custom extension";
413
414 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
415                                       const uint8_t **out, size_t *out_len,
416                                       int *out_alert_value, void *add_arg) {
417   if (extension_value != kCustomExtensionValue ||
418       add_arg != kCustomExtensionAddArg) {
419     abort();
420   }
421
422   if (GetTestConfig(ssl)->custom_extension_skip) {
423     return 0;
424   }
425   if (GetTestConfig(ssl)->custom_extension_fail_add) {
426     return -1;
427   }
428
429   *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
430   *out_len = sizeof(kCustomExtensionContents) - 1;
431
432   return 1;
433 }
434
435 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
436                                         const uint8_t *out, void *add_arg) {
437   if (extension_value != kCustomExtensionValue ||
438       add_arg != kCustomExtensionAddArg ||
439       out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
440     abort();
441   }
442 }
443
444 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
445                                         const uint8_t *contents,
446                                         size_t contents_len,
447                                         int *out_alert_value, void *parse_arg) {
448   if (extension_value != kCustomExtensionValue ||
449       parse_arg != kCustomExtensionParseArg) {
450     abort();
451   }
452
453   if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
454       memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
455     *out_alert_value = SSL_AD_DECODE_ERROR;
456     return 0;
457   }
458
459   return 1;
460 }
461
462 static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) {
463   // SNI must be accessible from the SNI callback.
464   const TestConfig *config = GetTestConfig(ssl);
465   const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
466   if (server_name == nullptr ||
467       std::string(server_name) != config->expected_server_name) {
468     fprintf(stderr, "servername mismatch (got %s; want %s)\n", server_name,
469             config->expected_server_name.c_str());
470     return SSL_TLSEXT_ERR_ALERT_FATAL;
471   }
472
473   return SSL_TLSEXT_ERR_OK;
474 }
475
476 // Connect returns a new socket connected to localhost on |port| or -1 on
477 // error.
478 static int Connect(uint16_t port) {
479   int sock = socket(AF_INET, SOCK_STREAM, 0);
480   if (sock == -1) {
481     PrintSocketError("socket");
482     return -1;
483   }
484   int nodelay = 1;
485   if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
486           reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
487     PrintSocketError("setsockopt");
488     closesocket(sock);
489     return -1;
490   }
491   sockaddr_in sin;
492   memset(&sin, 0, sizeof(sin));
493   sin.sin_family = AF_INET;
494   sin.sin_port = htons(port);
495   if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
496     PrintSocketError("inet_pton");
497     closesocket(sock);
498     return -1;
499   }
500   if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
501               sizeof(sin)) != 0) {
502     PrintSocketError("connect");
503     closesocket(sock);
504     return -1;
505   }
506   return sock;
507 }
508
509 class SocketCloser {
510  public:
511   explicit SocketCloser(int sock) : sock_(sock) {}
512   ~SocketCloser() {
513     // Half-close and drain the socket before releasing it. This seems to be
514     // necessary for graceful shutdown on Windows. It will also avoid write
515     // failures in the test runner.
516 #if defined(OPENSSL_SYS_WINDOWS)
517     shutdown(sock_, SD_SEND);
518 #else
519     shutdown(sock_, SHUT_WR);
520 #endif
521     while (true) {
522       char buf[1024];
523       if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
524         break;
525       }
526     }
527     closesocket(sock_);
528   }
529
530  private:
531   const int sock_;
532 };
533
534 static bssl::UniquePtr<SSL_CTX> SetupCtx(const TestConfig *config) {
535   const char sess_id_ctx[] = "ossl_shim";
536   bssl::UniquePtr<SSL_CTX> ssl_ctx(SSL_CTX_new(
537       config->is_dtls ? DTLS_method() : TLS_method()));
538   if (!ssl_ctx) {
539     return nullptr;
540   }
541
542   SSL_CTX_set_security_level(ssl_ctx.get(), 0);
543 #if 0
544   /* Disabled for now until we have some TLS1.3 support */
545   // Enable TLS 1.3 for tests.
546   if (!config->is_dtls &&
547       !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_3_VERSION)) {
548     return nullptr;
549   }
550 #else
551   /* Ensure we don't negotiate TLSv1.3 until we can handle it */
552   if (!config->is_dtls &&
553       !SSL_CTX_set_max_proto_version(ssl_ctx.get(), TLS1_2_VERSION)) {
554     return nullptr;
555   }
556 #endif
557
558   std::string cipher_list = "ALL";
559   if (!config->cipher.empty()) {
560     cipher_list = config->cipher;
561     SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
562   }
563   if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
564     return nullptr;
565   }
566
567   DH *tmpdh;
568
569   if (config->use_sparse_dh_prime) {
570     BIGNUM *p, *g;
571     p = BN_new();
572     g = BN_new();
573     tmpdh = DH_new();
574     if (p == NULL || g == NULL || tmpdh == NULL) {
575         BN_free(p);
576         BN_free(g);
577         DH_free(tmpdh);
578         return nullptr;
579     }
580     // This prime number is 2^1024 + 643 â€“ a value just above a power of two.
581     // Because of its form, values modulo it are essentially certain to be one
582     // byte shorter. This is used to test padding of these values.
583     if (BN_hex2bn(
584             &p,
585             "1000000000000000000000000000000000000000000000000000000000000000"
586             "0000000000000000000000000000000000000000000000000000000000000000"
587             "0000000000000000000000000000000000000000000000000000000000000000"
588             "0000000000000000000000000000000000000000000000000000000000000028"
589             "3") == 0 ||
590         !BN_set_word(g, 2)) {
591       BN_free(p);
592       BN_free(g);
593       DH_free(tmpdh);
594       return nullptr;
595     }
596     DH_set0_pqg(tmpdh, p, NULL, g);
597   } else {
598       tmpdh = DH_get_2048_256();
599   }
600
601   bssl::UniquePtr<DH> dh(tmpdh);
602
603   if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
604     return nullptr;
605   }
606
607   SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
608
609   if (config->use_old_client_cert_callback) {
610     SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback);
611   }
612
613   SSL_CTX_set_npn_advertised_cb(
614       ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
615   if (!config->select_next_proto.empty()) {
616     SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
617                                      NULL);
618   }
619
620   if (!config->select_alpn.empty() || config->decline_alpn) {
621     SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
622   }
623
624   SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
625   SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
626
627   if (config->use_ticket_callback) {
628     SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
629   }
630
631   if (config->enable_client_custom_extension &&
632       !SSL_CTX_add_client_custom_ext(
633           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
634           CustomExtensionFreeCallback, kCustomExtensionAddArg,
635           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
636     return nullptr;
637   }
638
639   if (config->enable_server_custom_extension &&
640       !SSL_CTX_add_server_custom_ext(
641           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
642           CustomExtensionFreeCallback, kCustomExtensionAddArg,
643           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
644     return nullptr;
645   }
646
647   if (config->verify_fail) {
648     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
649   } else {
650     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
651   }
652
653   if (config->use_null_client_ca_list) {
654     SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr);
655   }
656
657   if (!SSL_CTX_set_session_id_context(ssl_ctx.get(),
658                                       (const unsigned char *)sess_id_ctx,
659                                       sizeof(sess_id_ctx) - 1))
660     return nullptr;
661
662   if (!config->expected_server_name.empty()) {
663     SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback);
664   }
665
666   return ssl_ctx;
667 }
668
669 // RetryAsync is called after a failed operation on |ssl| with return code
670 // |ret|. If the operation should be retried, it simulates one asynchronous
671 // event and returns true. Otherwise it returns false.
672 static bool RetryAsync(SSL *ssl, int ret) {
673   // No error; don't retry.
674   if (ret >= 0) {
675     return false;
676   }
677
678   TestState *test_state = GetTestState(ssl);
679   assert(GetTestConfig(ssl)->async);
680
681   if (test_state->packeted_bio != nullptr &&
682       PacketedBioAdvanceClock(test_state->packeted_bio)) {
683     // The DTLS retransmit logic silently ignores write failures. So the test
684     // may progress, allow writes through synchronously.
685     AsyncBioEnforceWriteQuota(test_state->async_bio, false);
686     int timeout_ret = DTLSv1_handle_timeout(ssl);
687     AsyncBioEnforceWriteQuota(test_state->async_bio, true);
688
689     if (timeout_ret < 0) {
690       fprintf(stderr, "Error retransmitting.\n");
691       return false;
692     }
693     return true;
694   }
695
696   // See if we needed to read or write more. If so, allow one byte through on
697   // the appropriate end to maximally stress the state machine.
698   switch (SSL_get_error(ssl, ret)) {
699     case SSL_ERROR_WANT_READ:
700       AsyncBioAllowRead(test_state->async_bio, 1);
701       return true;
702     case SSL_ERROR_WANT_WRITE:
703       AsyncBioAllowWrite(test_state->async_bio, 1);
704       return true;
705     case SSL_ERROR_WANT_X509_LOOKUP:
706       test_state->cert_ready = true;
707       return true;
708     default:
709       return false;
710   }
711 }
712
713 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
714 // the result value of the final |SSL_read| call.
715 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
716   const TestConfig *config = GetTestConfig(ssl);
717   TestState *test_state = GetTestState(ssl);
718   int ret;
719   do {
720     if (config->async) {
721       // The DTLS retransmit logic silently ignores write failures. So the test
722       // may progress, allow writes through synchronously. |SSL_read| may
723       // trigger a retransmit, so disconnect the write quota.
724       AsyncBioEnforceWriteQuota(test_state->async_bio, false);
725     }
726     ret = config->peek_then_read ? SSL_peek(ssl, out, max_out)
727                                  : SSL_read(ssl, out, max_out);
728     if (config->async) {
729       AsyncBioEnforceWriteQuota(test_state->async_bio, true);
730     }
731   } while (config->async && RetryAsync(ssl, ret));
732
733   if (config->peek_then_read && ret > 0) {
734     std::unique_ptr<uint8_t[]> buf(new uint8_t[static_cast<size_t>(ret)]);
735
736     // SSL_peek should synchronously return the same data.
737     int ret2 = SSL_peek(ssl, buf.get(), ret);
738     if (ret2 != ret ||
739         memcmp(buf.get(), out, ret) != 0) {
740       fprintf(stderr, "First and second SSL_peek did not match.\n");
741       return -1;
742     }
743
744     // SSL_read should synchronously return the same data and consume it.
745     ret2 = SSL_read(ssl, buf.get(), ret);
746     if (ret2 != ret ||
747         memcmp(buf.get(), out, ret) != 0) {
748       fprintf(stderr, "SSL_peek and SSL_read did not match.\n");
749       return -1;
750     }
751   }
752
753   return ret;
754 }
755
756 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
757 // operations. It returns the result of the final |SSL_write| call.
758 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
759   const TestConfig *config = GetTestConfig(ssl);
760   int ret;
761   do {
762     ret = SSL_write(ssl, in, in_len);
763     if (ret > 0) {
764       in += ret;
765       in_len -= ret;
766     }
767   } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
768   return ret;
769 }
770
771 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
772 // returns the result of the final |SSL_shutdown| call.
773 static int DoShutdown(SSL *ssl) {
774   const TestConfig *config = GetTestConfig(ssl);
775   int ret;
776   do {
777     ret = SSL_shutdown(ssl);
778   } while (config->async && RetryAsync(ssl, ret));
779   return ret;
780 }
781
782 static uint16_t GetProtocolVersion(const SSL *ssl) {
783   uint16_t version = SSL_version(ssl);
784   if (!SSL_is_dtls(ssl)) {
785     return version;
786   }
787   return 0x0201 + ~version;
788 }
789
790 // CheckHandshakeProperties checks, immediately after |ssl| completes its
791 // initial handshake (or False Starts), whether all the properties are
792 // consistent with the test configuration and invariants.
793 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
794   const TestConfig *config = GetTestConfig(ssl);
795
796   if (SSL_get_current_cipher(ssl) == nullptr) {
797     fprintf(stderr, "null cipher after handshake\n");
798     return false;
799   }
800
801   if (is_resume &&
802       (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
803     fprintf(stderr, "session was%s reused\n",
804             SSL_session_reused(ssl) ? "" : " not");
805     return false;
806   }
807
808   if (!GetTestState(ssl)->handshake_done) {
809     fprintf(stderr, "handshake was not completed\n");
810     return false;
811   }
812
813   if (!config->is_server) {
814     bool expect_new_session =
815         !config->expect_no_session &&
816         (!SSL_session_reused(ssl) || config->expect_ticket_renewal) &&
817         // Session tickets are sent post-handshake in TLS 1.3.
818         GetProtocolVersion(ssl) < TLS1_3_VERSION;
819     if (expect_new_session != GetTestState(ssl)->got_new_session) {
820       fprintf(stderr,
821               "new session was%s cached, but we expected the opposite\n",
822               GetTestState(ssl)->got_new_session ? "" : " not");
823       return false;
824     }
825   }
826
827   if (!config->expected_server_name.empty()) {
828     const char *server_name =
829         SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
830     if (server_name == nullptr ||
831             std::string(server_name) != config->expected_server_name) {
832       fprintf(stderr, "servername mismatch (got %s; want %s)\n",
833               server_name, config->expected_server_name.c_str());
834       return false;
835     }
836   }
837
838   if (!config->expected_next_proto.empty()) {
839     const uint8_t *next_proto;
840     unsigned next_proto_len;
841     SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
842     if (next_proto_len != config->expected_next_proto.size() ||
843         memcmp(next_proto, config->expected_next_proto.data(),
844                next_proto_len) != 0) {
845       fprintf(stderr, "negotiated next proto mismatch\n");
846       return false;
847     }
848   }
849
850   if (!config->expected_alpn.empty()) {
851     const uint8_t *alpn_proto;
852     unsigned alpn_proto_len;
853     SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
854     if (alpn_proto_len != config->expected_alpn.size() ||
855         memcmp(alpn_proto, config->expected_alpn.data(),
856                alpn_proto_len) != 0) {
857       fprintf(stderr, "negotiated alpn proto mismatch\n");
858       return false;
859     }
860   }
861
862   if (config->expect_extended_master_secret) {
863     if (!SSL_get_extms_support(ssl)) {
864       fprintf(stderr, "No EMS for connection when expected");
865       return false;
866     }
867   }
868
869   if (config->expect_verify_result) {
870     int expected_verify_result = config->verify_fail ?
871       X509_V_ERR_APPLICATION_VERIFICATION :
872       X509_V_OK;
873
874     if (SSL_get_verify_result(ssl) != expected_verify_result) {
875       fprintf(stderr, "Wrong certificate verification result\n");
876       return false;
877     }
878   }
879
880   if (!config->psk.empty()) {
881     if (SSL_get_peer_cert_chain(ssl) != nullptr) {
882       fprintf(stderr, "Received peer certificate on a PSK cipher.\n");
883       return false;
884     }
885   } else if (!config->is_server || config->require_any_client_certificate) {
886     if (SSL_get_peer_certificate(ssl) == nullptr) {
887       fprintf(stderr, "Received no peer certificate but expected one.\n");
888       return false;
889     }
890   }
891
892   return true;
893 }
894
895 // DoExchange runs a test SSL exchange against the peer. On success, it returns
896 // true and sets |*out_session| to the negotiated SSL session. If the test is a
897 // resumption attempt, |is_resume| is true and |session| is the session from the
898 // previous exchange.
899 static bool DoExchange(bssl::UniquePtr<SSL_SESSION> *out_session,
900                        SSL_CTX *ssl_ctx, const TestConfig *config,
901                        bool is_resume, SSL_SESSION *session) {
902   bssl::UniquePtr<SSL> ssl(SSL_new(ssl_ctx));
903   if (!ssl) {
904     return false;
905   }
906
907   if (!SetTestConfig(ssl.get(), config) ||
908       !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
909     return false;
910   }
911
912   if (config->fallback_scsv &&
913       !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
914     return false;
915   }
916   // Install the certificate synchronously if nothing else will handle it.
917   if (!config->use_old_client_cert_callback &&
918       !config->async &&
919       !InstallCertificate(ssl.get())) {
920     return false;
921   }
922   SSL_set_cert_cb(ssl.get(), CertCallback, nullptr);
923   if (config->require_any_client_certificate) {
924     SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
925                    NULL);
926   }
927   if (config->verify_peer) {
928     SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
929   }
930   if (config->partial_write) {
931     SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
932   }
933   if (config->no_tls13) {
934     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3);
935   }
936   if (config->no_tls12) {
937     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
938   }
939   if (config->no_tls11) {
940     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
941   }
942   if (config->no_tls1) {
943     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
944   }
945   if (config->no_ssl3) {
946     SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
947   }
948   if (!config->host_name.empty() &&
949       !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
950     return false;
951   }
952   if (!config->advertise_alpn.empty() &&
953       SSL_set_alpn_protos(ssl.get(),
954                           (const uint8_t *)config->advertise_alpn.data(),
955                           config->advertise_alpn.size()) != 0) {
956     return false;
957   }
958   if (!config->psk.empty()) {
959     SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
960     SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
961   }
962   if (!config->psk_identity.empty() &&
963       !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
964     return false;
965   }
966   if (!config->srtp_profiles.empty() &&
967       SSL_set_tlsext_use_srtp(ssl.get(), config->srtp_profiles.c_str())) {
968     return false;
969   }
970   if (config->min_version != 0 &&
971       !SSL_set_min_proto_version(ssl.get(), (uint16_t)config->min_version)) {
972     return false;
973   }
974   if (config->max_version != 0 &&
975       !SSL_set_max_proto_version(ssl.get(), (uint16_t)config->max_version)) {
976     return false;
977   }
978   if (config->mtu != 0) {
979     SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
980     SSL_set_mtu(ssl.get(), config->mtu);
981   }
982   if (config->renegotiate_freely) {
983     // This is always on for OpenSSL.
984   }
985   if (!config->check_close_notify) {
986     SSL_set_quiet_shutdown(ssl.get(), 1);
987   }
988   if (config->p384_only) {
989     int nid = NID_secp384r1;
990     if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
991       return false;
992     }
993   }
994   if (config->enable_all_curves) {
995     static const int kAllCurves[] = {
996       NID_X25519, NID_X9_62_prime256v1, NID_X448, NID_secp521r1, NID_secp384r1
997     };
998     if (!SSL_set1_curves(ssl.get(), kAllCurves,
999                          OPENSSL_ARRAY_SIZE(kAllCurves))) {
1000       return false;
1001     }
1002   }
1003   if (config->max_cert_list > 0) {
1004     SSL_set_max_cert_list(ssl.get(), config->max_cert_list);
1005   }
1006
1007   if (!config->async) {
1008     SSL_set_mode(ssl.get(), SSL_MODE_AUTO_RETRY);
1009   }
1010
1011   int sock = Connect(config->port);
1012   if (sock == -1) {
1013     return false;
1014   }
1015   SocketCloser closer(sock);
1016
1017   bssl::UniquePtr<BIO> bio(BIO_new_socket(sock, BIO_NOCLOSE));
1018   if (!bio) {
1019     return false;
1020   }
1021   if (config->is_dtls) {
1022     bssl::UniquePtr<BIO> packeted = PacketedBioCreate(!config->async);
1023     if (!packeted) {
1024       return false;
1025     }
1026     GetTestState(ssl.get())->packeted_bio = packeted.get();
1027     BIO_push(packeted.get(), bio.release());
1028     bio = std::move(packeted);
1029   }
1030   if (config->async) {
1031     bssl::UniquePtr<BIO> async_scoped =
1032         config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1033     if (!async_scoped) {
1034       return false;
1035     }
1036     BIO_push(async_scoped.get(), bio.release());
1037     GetTestState(ssl.get())->async_bio = async_scoped.get();
1038     bio = std::move(async_scoped);
1039   }
1040   SSL_set_bio(ssl.get(), bio.get(), bio.get());
1041   bio.release();  // SSL_set_bio takes ownership.
1042
1043   if (session != NULL) {
1044     if (!config->is_server) {
1045       if (SSL_set_session(ssl.get(), session) != 1) {
1046         return false;
1047       }
1048     }
1049   }
1050
1051 #if 0
1052   // KNOWN BUG: OpenSSL's SSL_get_current_cipher behaves incorrectly when
1053   // offering resumption.
1054   if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1055     fprintf(stderr, "non-null cipher before handshake\n");
1056     return false;
1057   }
1058 #endif
1059
1060   int ret;
1061   if (config->implicit_handshake) {
1062     if (config->is_server) {
1063       SSL_set_accept_state(ssl.get());
1064     } else {
1065       SSL_set_connect_state(ssl.get());
1066     }
1067   } else {
1068     do {
1069       if (config->is_server) {
1070         ret = SSL_accept(ssl.get());
1071       } else {
1072         ret = SSL_connect(ssl.get());
1073       }
1074     } while (config->async && RetryAsync(ssl.get(), ret));
1075     if (ret != 1 ||
1076         !CheckHandshakeProperties(ssl.get(), is_resume)) {
1077       return false;
1078     }
1079
1080     // Reset the state to assert later that the callback isn't called in
1081     // renegotiations.
1082     GetTestState(ssl.get())->got_new_session = false;
1083   }
1084
1085   if (config->export_keying_material > 0) {
1086     std::vector<uint8_t> result(
1087         static_cast<size_t>(config->export_keying_material));
1088     if (SSL_export_keying_material(
1089             ssl.get(), result.data(), result.size(),
1090             config->export_label.data(), config->export_label.size(),
1091             reinterpret_cast<const uint8_t*>(config->export_context.data()),
1092             config->export_context.size(), config->use_export_context) != 1) {
1093       fprintf(stderr, "failed to export keying material\n");
1094       return false;
1095     }
1096     if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1097       return false;
1098     }
1099   }
1100
1101   if (config->write_different_record_sizes) {
1102     if (config->is_dtls) {
1103       fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1104       return false;
1105     }
1106     // This mode writes a number of different record sizes in an attempt to
1107     // trip up the CBC record splitting code.
1108     static const size_t kBufLen = 32769;
1109     std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1110     memset(buf.get(), 0x42, kBufLen);
1111     static const size_t kRecordSizes[] = {
1112         0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1113     for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kRecordSizes); i++) {
1114       const size_t len = kRecordSizes[i];
1115       if (len > kBufLen) {
1116         fprintf(stderr, "Bad kRecordSizes value.\n");
1117         return false;
1118       }
1119       if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1120         return false;
1121       }
1122     }
1123   } else {
1124     if (config->shim_writes_first) {
1125       if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1126                    5) < 0) {
1127         return false;
1128       }
1129     }
1130     if (!config->shim_shuts_down) {
1131       for (;;) {
1132         static const size_t kBufLen = 16384;
1133         std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1134
1135         // Read only 512 bytes at a time in TLS to ensure records may be
1136         // returned in multiple reads.
1137         int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1138         int err = SSL_get_error(ssl.get(), n);
1139         if (err == SSL_ERROR_ZERO_RETURN ||
1140             (n == 0 && err == SSL_ERROR_SYSCALL)) {
1141           if (n != 0) {
1142             fprintf(stderr, "Invalid SSL_get_error output\n");
1143             return false;
1144           }
1145           // Stop on either clean or unclean shutdown.
1146           break;
1147         } else if (err != SSL_ERROR_NONE) {
1148           if (n > 0) {
1149             fprintf(stderr, "Invalid SSL_get_error output\n");
1150             return false;
1151           }
1152           return false;
1153         }
1154         // Successfully read data.
1155         if (n <= 0) {
1156           fprintf(stderr, "Invalid SSL_get_error output\n");
1157           return false;
1158         }
1159
1160         // After a successful read, with or without False Start, the handshake
1161         // must be complete.
1162         if (!GetTestState(ssl.get())->handshake_done) {
1163           fprintf(stderr, "handshake was not completed after SSL_read\n");
1164           return false;
1165         }
1166
1167         for (int i = 0; i < n; i++) {
1168           buf[i] ^= 0xff;
1169         }
1170         if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1171           return false;
1172         }
1173       }
1174     }
1175   }
1176
1177   if (!config->is_server &&
1178       !config->implicit_handshake &&
1179       // Session tickets are sent post-handshake in TLS 1.3.
1180       GetProtocolVersion(ssl.get()) < TLS1_3_VERSION &&
1181       GetTestState(ssl.get())->got_new_session) {
1182     fprintf(stderr, "new session was established after the handshake\n");
1183     return false;
1184   }
1185
1186   if (GetProtocolVersion(ssl.get()) >= TLS1_3_VERSION && !config->is_server) {
1187     bool expect_new_session =
1188         !config->expect_no_session && !config->shim_shuts_down;
1189     if (expect_new_session != GetTestState(ssl.get())->got_new_session) {
1190       fprintf(stderr,
1191               "new session was%s cached, but we expected the opposite\n",
1192               GetTestState(ssl.get())->got_new_session ? "" : " not");
1193       return false;
1194     }
1195   }
1196
1197   if (out_session) {
1198     *out_session = std::move(GetTestState(ssl.get())->new_session);
1199   }
1200
1201   ret = DoShutdown(ssl.get());
1202
1203   if (config->shim_shuts_down && config->check_close_notify) {
1204     // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1205     // it returns zero when our close_notify is sent, then one when the peer's
1206     // is received.
1207     if (ret != 0) {
1208       fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1209       return false;
1210     }
1211     ret = DoShutdown(ssl.get());
1212   }
1213
1214   if (ret != 1) {
1215     fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1216     return false;
1217   }
1218
1219   if (SSL_total_renegotiations(ssl.get()) !=
1220       config->expect_total_renegotiations) {
1221     fprintf(stderr, "Expected %d renegotiations, got %ld\n",
1222             config->expect_total_renegotiations,
1223             SSL_total_renegotiations(ssl.get()));
1224     return false;
1225   }
1226
1227   return true;
1228 }
1229
1230 class StderrDelimiter {
1231  public:
1232   ~StderrDelimiter() { fprintf(stderr, "--- DONE ---\n"); }
1233 };
1234
1235 static int Main(int argc, char **argv) {
1236   // To distinguish ASan's output from ours, add a trailing message to stderr.
1237   // Anything following this line will be considered an error.
1238   StderrDelimiter delimiter;
1239
1240 #if defined(OPENSSL_SYS_WINDOWS)
1241   /* Initialize Winsock. */
1242   WORD wsa_version = MAKEWORD(2, 2);
1243   WSADATA wsa_data;
1244   int wsa_err = WSAStartup(wsa_version, &wsa_data);
1245   if (wsa_err != 0) {
1246     fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1247     return 1;
1248   }
1249   if (wsa_data.wVersion != wsa_version) {
1250     fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1251     return 1;
1252   }
1253 #else
1254   signal(SIGPIPE, SIG_IGN);
1255 #endif
1256
1257   OPENSSL_init_crypto(0, NULL);
1258   OPENSSL_init_ssl(0, NULL);
1259   g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1260   g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1261   if (g_config_index < 0 || g_state_index < 0) {
1262     return 1;
1263   }
1264
1265   TestConfig config;
1266   if (!ParseConfig(argc - 1, argv + 1, &config)) {
1267     return Usage(argv[0]);
1268   }
1269
1270   bssl::UniquePtr<SSL_CTX> ssl_ctx = SetupCtx(&config);
1271   if (!ssl_ctx) {
1272     ERR_print_errors_fp(stderr);
1273     return 1;
1274   }
1275
1276   bssl::UniquePtr<SSL_SESSION> session;
1277   for (int i = 0; i < config.resume_count + 1; i++) {
1278     bool is_resume = i > 0;
1279     if (is_resume && !config.is_server && !session) {
1280       fprintf(stderr, "No session to offer.\n");
1281       return 1;
1282     }
1283
1284     bssl::UniquePtr<SSL_SESSION> offer_session = std::move(session);
1285     if (!DoExchange(&session, ssl_ctx.get(), &config, is_resume,
1286                     offer_session.get())) {
1287       fprintf(stderr, "Connection %d failed.\n", i + 1);
1288       ERR_print_errors_fp(stderr);
1289       return 1;
1290     }
1291   }
1292
1293   return 0;
1294 }
1295
1296 }  // namespace bssl
1297
1298 int main(int argc, char **argv) {
1299   return bssl::Main(argc, argv);
1300 }