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 #if !defined(__STDC_FORMAT_MACROS)
16 #define __STDC_FORMAT_MACROS
17 #endif
18 
19 #include <openssl/base.h>
20 
21 #if !defined(OPENSSL_WINDOWS)
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
24 #include <netinet/tcp.h>
25 #include <signal.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <unistd.h>
29 #else
30 #include <io.h>
31 #pragma warning(push, 3)
32 #include <winsock2.h>
33 #include <ws2tcpip.h>
34 #pragma warning(pop)
35 
36 #pragma comment(lib, "Ws2_32.lib")
37 #endif
38 
39 #include <inttypes.h>
40 #include <string.h>
41 
42 #include <openssl/bio.h>
43 #include <openssl/buf.h>
44 #include <openssl/bytestring.h>
45 #include <openssl/cipher.h>
46 #include <openssl/crypto.h>
47 #include <openssl/err.h>
48 #include <openssl/hmac.h>
49 #include <openssl/obj.h>
50 #include <openssl/rand.h>
51 #include <openssl/ssl.h>
52 
53 #include <memory>
54 #include <string>
55 #include <vector>
56 
57 #include "../../crypto/test/scoped_types.h"
58 #include "async_bio.h"
59 #include "packeted_bio.h"
60 #include "scoped_types.h"
61 #include "test_config.h"
62 
63 
64 #if !defined(OPENSSL_WINDOWS)
closesocket(int sock)65 static int closesocket(int sock) {
66   return close(sock);
67 }
68 
PrintSocketError(const char * func)69 static void PrintSocketError(const char *func) {
70   perror(func);
71 }
72 #else
PrintSocketError(const char * func)73 static void PrintSocketError(const char *func) {
74   fprintf(stderr, "%s: %d\n", func, WSAGetLastError());
75 }
76 #endif
77 
Usage(const char * program)78 static int Usage(const char *program) {
79   fprintf(stderr, "Usage: %s [flags...]\n", program);
80   return 1;
81 }
82 
83 struct TestState {
TestStateTestState84   TestState() {
85     // MSVC cannot initialize these inline.
86     memset(&clock, 0, sizeof(clock));
87     memset(&clock_delta, 0, sizeof(clock_delta));
88   }
89 
90   // async_bio is async BIO which pauses reads and writes.
91   BIO *async_bio = nullptr;
92   // clock is the current time for the SSL connection.
93   timeval clock;
94   // clock_delta is how far the clock advanced in the most recent failed
95   // |BIO_read|.
96   timeval clock_delta;
97   ScopedEVP_PKEY channel_id;
98   bool cert_ready = false;
99   ScopedSSL_SESSION session;
100   ScopedSSL_SESSION pending_session;
101   bool early_callback_called = false;
102   bool handshake_done = false;
103   // private_key is the underlying private key used when testing custom keys.
104   ScopedEVP_PKEY private_key;
105   std::vector<uint8_t> private_key_result;
106   // private_key_retries is the number of times an asynchronous private key
107   // operation has been retried.
108   unsigned private_key_retries = 0;
109   bool got_new_session = false;
110 };
111 
TestStateExFree(void * parent,void * ptr,CRYPTO_EX_DATA * ad,int index,long argl,void * argp)112 static void TestStateExFree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
113                             int index, long argl, void *argp) {
114   delete ((TestState *)ptr);
115 }
116 
117 static int g_config_index = 0;
118 static int g_state_index = 0;
119 
SetConfigPtr(SSL * ssl,const TestConfig * config)120 static bool SetConfigPtr(SSL *ssl, const TestConfig *config) {
121   return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1;
122 }
123 
GetConfigPtr(const SSL * ssl)124 static const TestConfig *GetConfigPtr(const SSL *ssl) {
125   return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index);
126 }
127 
SetTestState(SSL * ssl,std::unique_ptr<TestState> state)128 static bool SetTestState(SSL *ssl, std::unique_ptr<TestState> state) {
129   // |SSL_set_ex_data| takes ownership of |state| only on success.
130   if (SSL_set_ex_data(ssl, g_state_index, state.get()) == 1) {
131     state.release();
132     return true;
133   }
134   return false;
135 }
136 
GetTestState(const SSL * ssl)137 static TestState *GetTestState(const SSL *ssl) {
138   return (TestState *)SSL_get_ex_data(ssl, g_state_index);
139 }
140 
LoadPrivateKey(const std::string & file)141 static ScopedEVP_PKEY LoadPrivateKey(const std::string &file) {
142   ScopedBIO bio(BIO_new(BIO_s_file()));
143   if (!bio || !BIO_read_filename(bio.get(), file.c_str())) {
144     return nullptr;
145   }
146   ScopedEVP_PKEY pkey(PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL));
147   return pkey;
148 }
149 
AsyncPrivateKeyType(SSL * ssl)150 static int AsyncPrivateKeyType(SSL *ssl) {
151   return EVP_PKEY_id(GetTestState(ssl)->private_key.get());
152 }
153 
AsyncPrivateKeyMaxSignatureLen(SSL * ssl)154 static size_t AsyncPrivateKeyMaxSignatureLen(SSL *ssl) {
155   return EVP_PKEY_size(GetTestState(ssl)->private_key.get());
156 }
157 
AsyncPrivateKeySign(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out,const EVP_MD * md,const uint8_t * in,size_t in_len)158 static ssl_private_key_result_t AsyncPrivateKeySign(
159     SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
160     const EVP_MD *md, const uint8_t *in, size_t in_len) {
161   TestState *test_state = GetTestState(ssl);
162   if (!test_state->private_key_result.empty()) {
163     fprintf(stderr, "AsyncPrivateKeySign called with operation pending.\n");
164     abort();
165   }
166 
167   ScopedEVP_PKEY_CTX ctx(EVP_PKEY_CTX_new(test_state->private_key.get(),
168                                           nullptr));
169   if (!ctx) {
170     return ssl_private_key_failure;
171   }
172 
173   // Write the signature into |test_state|.
174   size_t len = 0;
175   if (!EVP_PKEY_sign_init(ctx.get()) ||
176       !EVP_PKEY_CTX_set_signature_md(ctx.get(), md) ||
177       !EVP_PKEY_sign(ctx.get(), nullptr, &len, in, in_len)) {
178     return ssl_private_key_failure;
179   }
180   test_state->private_key_result.resize(len);
181   if (!EVP_PKEY_sign(ctx.get(), test_state->private_key_result.data(), &len, in,
182                      in_len)) {
183     return ssl_private_key_failure;
184   }
185   test_state->private_key_result.resize(len);
186 
187   // The signature will be released asynchronously in
188   // |AsyncPrivateKeySignComplete|.
189   return ssl_private_key_retry;
190 }
191 
AsyncPrivateKeySignComplete(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out)192 static ssl_private_key_result_t AsyncPrivateKeySignComplete(
193     SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
194   TestState *test_state = GetTestState(ssl);
195   if (test_state->private_key_result.empty()) {
196     fprintf(stderr,
197             "AsyncPrivateKeySignComplete called without operation pending.\n");
198     abort();
199   }
200 
201   if (test_state->private_key_retries < 2) {
202     // Only return the signature on the second attempt, to test both incomplete
203     // |sign| and |sign_complete|.
204     return ssl_private_key_retry;
205   }
206 
207   if (max_out < test_state->private_key_result.size()) {
208     fprintf(stderr, "Output buffer too small.\n");
209     return ssl_private_key_failure;
210   }
211   memcpy(out, test_state->private_key_result.data(),
212          test_state->private_key_result.size());
213   *out_len = test_state->private_key_result.size();
214 
215   test_state->private_key_result.clear();
216   test_state->private_key_retries = 0;
217   return ssl_private_key_success;
218 }
219 
AsyncPrivateKeyDecrypt(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out,const uint8_t * in,size_t in_len)220 static ssl_private_key_result_t AsyncPrivateKeyDecrypt(
221     SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
222     const uint8_t *in, size_t in_len) {
223   TestState *test_state = GetTestState(ssl);
224   if (!test_state->private_key_result.empty()) {
225     fprintf(stderr,
226             "AsyncPrivateKeyDecrypt called with operation pending.\n");
227     abort();
228   }
229 
230   RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get());
231   if (rsa == NULL) {
232     fprintf(stderr,
233             "AsyncPrivateKeyDecrypt called with incorrect key type.\n");
234     abort();
235   }
236   test_state->private_key_result.resize(RSA_size(rsa));
237   if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(),
238                    RSA_size(rsa), in, in_len, RSA_NO_PADDING)) {
239     return ssl_private_key_failure;
240   }
241 
242   test_state->private_key_result.resize(*out_len);
243 
244   // The decryption will be released asynchronously in
245   // |AsyncPrivateKeyDecryptComplete|.
246   return ssl_private_key_retry;
247 }
248 
AsyncPrivateKeyDecryptComplete(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out)249 static ssl_private_key_result_t AsyncPrivateKeyDecryptComplete(
250     SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) {
251   TestState *test_state = GetTestState(ssl);
252   if (test_state->private_key_result.empty()) {
253     fprintf(stderr,
254             "AsyncPrivateKeyDecryptComplete called without operation "
255             "pending.\n");
256     abort();
257   }
258 
259   if (test_state->private_key_retries < 2) {
260     // Only return the decryption on the second attempt, to test both incomplete
261     // |decrypt| and |decrypt_complete|.
262     return ssl_private_key_retry;
263   }
264 
265   if (max_out < test_state->private_key_result.size()) {
266     fprintf(stderr, "Output buffer too small.\n");
267     return ssl_private_key_failure;
268   }
269   memcpy(out, test_state->private_key_result.data(),
270          test_state->private_key_result.size());
271   *out_len = test_state->private_key_result.size();
272 
273   test_state->private_key_result.clear();
274   test_state->private_key_retries = 0;
275   return ssl_private_key_success;
276 }
277 
278 static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = {
279     AsyncPrivateKeyType,
280     AsyncPrivateKeyMaxSignatureLen,
281     AsyncPrivateKeySign,
282     AsyncPrivateKeySignComplete,
283     AsyncPrivateKeyDecrypt,
284     AsyncPrivateKeyDecryptComplete
285 };
286 
287 template<typename T>
288 struct Free {
operator ()Free289   void operator()(T *buf) {
290     free(buf);
291   }
292 };
293 
InstallCertificate(SSL * ssl)294 static bool InstallCertificate(SSL *ssl) {
295   const TestConfig *config = GetConfigPtr(ssl);
296   TestState *test_state = GetTestState(ssl);
297 
298   if (!config->digest_prefs.empty()) {
299     std::unique_ptr<char, Free<char>> digest_prefs(
300         strdup(config->digest_prefs.c_str()));
301     std::vector<int> digest_list;
302 
303     for (;;) {
304       char *token =
305           strtok(digest_list.empty() ? digest_prefs.get() : nullptr, ",");
306       if (token == nullptr) {
307         break;
308       }
309 
310       digest_list.push_back(EVP_MD_type(EVP_get_digestbyname(token)));
311     }
312 
313     if (!SSL_set_private_key_digest_prefs(ssl, digest_list.data(),
314                                           digest_list.size())) {
315       return false;
316     }
317   }
318 
319   if (!config->key_file.empty()) {
320     if (config->async) {
321       test_state->private_key = LoadPrivateKey(config->key_file.c_str());
322       if (!test_state->private_key) {
323         return false;
324       }
325       SSL_set_private_key_method(ssl, &g_async_private_key_method);
326     } else if (!SSL_use_PrivateKey_file(ssl, config->key_file.c_str(),
327                                         SSL_FILETYPE_PEM)) {
328       return false;
329     }
330   }
331   if (!config->cert_file.empty() &&
332       !SSL_use_certificate_file(ssl, config->cert_file.c_str(),
333                                 SSL_FILETYPE_PEM)) {
334     return false;
335   }
336   if (!config->ocsp_response.empty() &&
337       !SSL_CTX_set_ocsp_response(ssl->ctx,
338                                  (const uint8_t *)config->ocsp_response.data(),
339                                  config->ocsp_response.size())) {
340     return false;
341   }
342   return true;
343 }
344 
SelectCertificateCallback(const struct ssl_early_callback_ctx * ctx)345 static int SelectCertificateCallback(const struct ssl_early_callback_ctx *ctx) {
346   const TestConfig *config = GetConfigPtr(ctx->ssl);
347   GetTestState(ctx->ssl)->early_callback_called = true;
348 
349   if (!config->expected_server_name.empty()) {
350     const uint8_t *extension_data;
351     size_t extension_len;
352     CBS extension, server_name_list, host_name;
353     uint8_t name_type;
354 
355     if (!SSL_early_callback_ctx_extension_get(ctx, TLSEXT_TYPE_server_name,
356                                               &extension_data,
357                                               &extension_len)) {
358       fprintf(stderr, "Could not find server_name extension.\n");
359       return -1;
360     }
361 
362     CBS_init(&extension, extension_data, extension_len);
363     if (!CBS_get_u16_length_prefixed(&extension, &server_name_list) ||
364         CBS_len(&extension) != 0 ||
365         !CBS_get_u8(&server_name_list, &name_type) ||
366         name_type != TLSEXT_NAMETYPE_host_name ||
367         !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||
368         CBS_len(&server_name_list) != 0) {
369       fprintf(stderr, "Could not decode server_name extension.\n");
370       return -1;
371     }
372 
373     if (!CBS_mem_equal(&host_name,
374                        (const uint8_t*)config->expected_server_name.data(),
375                        config->expected_server_name.size())) {
376       fprintf(stderr, "Server name mismatch.\n");
377     }
378   }
379 
380   if (config->fail_early_callback) {
381     return -1;
382   }
383 
384   // Install the certificate in the early callback.
385   if (config->use_early_callback) {
386     if (config->async) {
387       // Install the certificate asynchronously.
388       return 0;
389     }
390     if (!InstallCertificate(ctx->ssl)) {
391       return -1;
392     }
393   }
394   return 1;
395 }
396 
VerifySucceed(X509_STORE_CTX * store_ctx,void * arg)397 static int VerifySucceed(X509_STORE_CTX *store_ctx, void *arg) {
398   SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(store_ctx,
399       SSL_get_ex_data_X509_STORE_CTX_idx());
400   const TestConfig *config = GetConfigPtr(ssl);
401 
402   if (!config->expected_ocsp_response.empty()) {
403     const uint8_t *data;
404     size_t len;
405     SSL_get0_ocsp_response(ssl, &data, &len);
406     if (len == 0) {
407       fprintf(stderr, "OCSP response not available in verify callback\n");
408       return 0;
409     }
410   }
411 
412   return 1;
413 }
414 
VerifyFail(X509_STORE_CTX * store_ctx,void * arg)415 static int VerifyFail(X509_STORE_CTX *store_ctx, void *arg) {
416   store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION;
417   return 0;
418 }
419 
NextProtosAdvertisedCallback(SSL * ssl,const uint8_t ** out,unsigned int * out_len,void * arg)420 static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out,
421                                         unsigned int *out_len, void *arg) {
422   const TestConfig *config = GetConfigPtr(ssl);
423   if (config->advertise_npn.empty()) {
424     return SSL_TLSEXT_ERR_NOACK;
425   }
426 
427   *out = (const uint8_t*)config->advertise_npn.data();
428   *out_len = config->advertise_npn.size();
429   return SSL_TLSEXT_ERR_OK;
430 }
431 
NextProtoSelectCallback(SSL * ssl,uint8_t ** out,uint8_t * outlen,const uint8_t * in,unsigned inlen,void * arg)432 static int NextProtoSelectCallback(SSL* ssl, uint8_t** out, uint8_t* outlen,
433                                    const uint8_t* in, unsigned inlen, void* arg) {
434   const TestConfig *config = GetConfigPtr(ssl);
435   if (config->select_next_proto.empty()) {
436     return SSL_TLSEXT_ERR_NOACK;
437   }
438 
439   *out = (uint8_t*)config->select_next_proto.data();
440   *outlen = config->select_next_proto.size();
441   return SSL_TLSEXT_ERR_OK;
442 }
443 
AlpnSelectCallback(SSL * ssl,const uint8_t ** out,uint8_t * outlen,const uint8_t * in,unsigned inlen,void * arg)444 static int AlpnSelectCallback(SSL* ssl, const uint8_t** out, uint8_t* outlen,
445                               const uint8_t* in, unsigned inlen, void* arg) {
446   const TestConfig *config = GetConfigPtr(ssl);
447   if (config->select_alpn.empty()) {
448     return SSL_TLSEXT_ERR_NOACK;
449   }
450 
451   if (!config->expected_advertised_alpn.empty() &&
452       (config->expected_advertised_alpn.size() != inlen ||
453        memcmp(config->expected_advertised_alpn.data(),
454               in, inlen) != 0)) {
455     fprintf(stderr, "bad ALPN select callback inputs\n");
456     exit(1);
457   }
458 
459   *out = (const uint8_t*)config->select_alpn.data();
460   *outlen = config->select_alpn.size();
461   return SSL_TLSEXT_ERR_OK;
462 }
463 
PskClientCallback(SSL * ssl,const char * hint,char * out_identity,unsigned max_identity_len,uint8_t * out_psk,unsigned max_psk_len)464 static unsigned PskClientCallback(SSL *ssl, const char *hint,
465                                   char *out_identity,
466                                   unsigned max_identity_len,
467                                   uint8_t *out_psk, unsigned max_psk_len) {
468   const TestConfig *config = GetConfigPtr(ssl);
469 
470   if (strcmp(hint ? hint : "", config->psk_identity.c_str()) != 0) {
471     fprintf(stderr, "Server PSK hint did not match.\n");
472     return 0;
473   }
474 
475   // Account for the trailing '\0' for the identity.
476   if (config->psk_identity.size() >= max_identity_len ||
477       config->psk.size() > max_psk_len) {
478     fprintf(stderr, "PSK buffers too small\n");
479     return 0;
480   }
481 
482   BUF_strlcpy(out_identity, config->psk_identity.c_str(),
483               max_identity_len);
484   memcpy(out_psk, config->psk.data(), config->psk.size());
485   return config->psk.size();
486 }
487 
PskServerCallback(SSL * ssl,const char * identity,uint8_t * out_psk,unsigned max_psk_len)488 static unsigned PskServerCallback(SSL *ssl, const char *identity,
489                                   uint8_t *out_psk, unsigned max_psk_len) {
490   const TestConfig *config = GetConfigPtr(ssl);
491 
492   if (strcmp(identity, config->psk_identity.c_str()) != 0) {
493     fprintf(stderr, "Client PSK identity did not match.\n");
494     return 0;
495   }
496 
497   if (config->psk.size() > max_psk_len) {
498     fprintf(stderr, "PSK buffers too small\n");
499     return 0;
500   }
501 
502   memcpy(out_psk, config->psk.data(), config->psk.size());
503   return config->psk.size();
504 }
505 
CurrentTimeCallback(const SSL * ssl,timeval * out_clock)506 static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) {
507   *out_clock = GetTestState(ssl)->clock;
508 }
509 
ChannelIdCallback(SSL * ssl,EVP_PKEY ** out_pkey)510 static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) {
511   *out_pkey = GetTestState(ssl)->channel_id.release();
512 }
513 
CertCallback(SSL * ssl,void * arg)514 static int CertCallback(SSL *ssl, void *arg) {
515   if (!GetTestState(ssl)->cert_ready) {
516     return -1;
517   }
518   if (!InstallCertificate(ssl)) {
519     return 0;
520   }
521   return 1;
522 }
523 
GetSessionCallback(SSL * ssl,uint8_t * data,int len,int * copy)524 static SSL_SESSION *GetSessionCallback(SSL *ssl, uint8_t *data, int len,
525                                        int *copy) {
526   TestState *async_state = GetTestState(ssl);
527   if (async_state->session) {
528     *copy = 0;
529     return async_state->session.release();
530   } else if (async_state->pending_session) {
531     return SSL_magic_pending_session_ptr();
532   } else {
533     return NULL;
534   }
535 }
536 
DDoSCallback(const struct ssl_early_callback_ctx * early_context)537 static int DDoSCallback(const struct ssl_early_callback_ctx *early_context) {
538   const TestConfig *config = GetConfigPtr(early_context->ssl);
539   static int callback_num = 0;
540 
541   callback_num++;
542   if (config->fail_ddos_callback ||
543       (config->fail_second_ddos_callback && callback_num == 2)) {
544     return 0;
545   }
546   return 1;
547 }
548 
InfoCallback(const SSL * ssl,int type,int val)549 static void InfoCallback(const SSL *ssl, int type, int val) {
550   if (type == SSL_CB_HANDSHAKE_DONE) {
551     if (GetConfigPtr(ssl)->handshake_never_done) {
552       fprintf(stderr, "handshake completed\n");
553       // Abort before any expected error code is printed, to ensure the overall
554       // test fails.
555       abort();
556     }
557     GetTestState(ssl)->handshake_done = true;
558   }
559 }
560 
NewSessionCallback(SSL * ssl,SSL_SESSION * session)561 static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) {
562   GetTestState(ssl)->got_new_session = true;
563   // BoringSSL passes a reference to |session|.
564   SSL_SESSION_free(session);
565   return 1;
566 }
567 
TicketKeyCallback(SSL * ssl,uint8_t * key_name,uint8_t * iv,EVP_CIPHER_CTX * ctx,HMAC_CTX * hmac_ctx,int encrypt)568 static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv,
569                              EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx,
570                              int encrypt) {
571   // This is just test code, so use the all-zeros key.
572   static const uint8_t kZeros[16] = {0};
573 
574   if (encrypt) {
575     memcpy(key_name, kZeros, sizeof(kZeros));
576     RAND_bytes(iv, 16);
577   } else if (memcmp(key_name, kZeros, 16) != 0) {
578     return 0;
579   }
580 
581   if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) ||
582       !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) {
583     return -1;
584   }
585 
586   if (!encrypt) {
587     return GetConfigPtr(ssl)->renew_ticket ? 2 : 1;
588   }
589   return 1;
590 }
591 
592 // kCustomExtensionValue is the extension value that the custom extension
593 // callbacks will add.
594 static const uint16_t kCustomExtensionValue = 1234;
595 static void *const kCustomExtensionAddArg =
596     reinterpret_cast<void *>(kCustomExtensionValue);
597 static void *const kCustomExtensionParseArg =
598     reinterpret_cast<void *>(kCustomExtensionValue + 1);
599 static const char kCustomExtensionContents[] = "custom extension";
600 
CustomExtensionAddCallback(SSL * ssl,unsigned extension_value,const uint8_t ** out,size_t * out_len,int * out_alert_value,void * add_arg)601 static int CustomExtensionAddCallback(SSL *ssl, unsigned extension_value,
602                                       const uint8_t **out, size_t *out_len,
603                                       int *out_alert_value, void *add_arg) {
604   if (extension_value != kCustomExtensionValue ||
605       add_arg != kCustomExtensionAddArg) {
606     abort();
607   }
608 
609   if (GetConfigPtr(ssl)->custom_extension_skip) {
610     return 0;
611   }
612   if (GetConfigPtr(ssl)->custom_extension_fail_add) {
613     return -1;
614   }
615 
616   *out = reinterpret_cast<const uint8_t*>(kCustomExtensionContents);
617   *out_len = sizeof(kCustomExtensionContents) - 1;
618 
619   return 1;
620 }
621 
CustomExtensionFreeCallback(SSL * ssl,unsigned extension_value,const uint8_t * out,void * add_arg)622 static void CustomExtensionFreeCallback(SSL *ssl, unsigned extension_value,
623                                         const uint8_t *out, void *add_arg) {
624   if (extension_value != kCustomExtensionValue ||
625       add_arg != kCustomExtensionAddArg ||
626       out != reinterpret_cast<const uint8_t *>(kCustomExtensionContents)) {
627     abort();
628   }
629 }
630 
CustomExtensionParseCallback(SSL * ssl,unsigned extension_value,const uint8_t * contents,size_t contents_len,int * out_alert_value,void * parse_arg)631 static int CustomExtensionParseCallback(SSL *ssl, unsigned extension_value,
632                                         const uint8_t *contents,
633                                         size_t contents_len,
634                                         int *out_alert_value, void *parse_arg) {
635   if (extension_value != kCustomExtensionValue ||
636       parse_arg != kCustomExtensionParseArg) {
637     abort();
638   }
639 
640   if (contents_len != sizeof(kCustomExtensionContents) - 1 ||
641       memcmp(contents, kCustomExtensionContents, contents_len) != 0) {
642     *out_alert_value = SSL_AD_DECODE_ERROR;
643     return 0;
644   }
645 
646   return 1;
647 }
648 
649 // Connect returns a new socket connected to localhost on |port| or -1 on
650 // error.
Connect(uint16_t port)651 static int Connect(uint16_t port) {
652   int sock = socket(AF_INET, SOCK_STREAM, 0);
653   if (sock == -1) {
654     PrintSocketError("socket");
655     return -1;
656   }
657   int nodelay = 1;
658   if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
659           reinterpret_cast<const char*>(&nodelay), sizeof(nodelay)) != 0) {
660     PrintSocketError("setsockopt");
661     closesocket(sock);
662     return -1;
663   }
664   sockaddr_in sin;
665   memset(&sin, 0, sizeof(sin));
666   sin.sin_family = AF_INET;
667   sin.sin_port = htons(port);
668   if (!inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr)) {
669     PrintSocketError("inet_pton");
670     closesocket(sock);
671     return -1;
672   }
673   if (connect(sock, reinterpret_cast<const sockaddr*>(&sin),
674               sizeof(sin)) != 0) {
675     PrintSocketError("connect");
676     closesocket(sock);
677     return -1;
678   }
679   return sock;
680 }
681 
682 class SocketCloser {
683  public:
SocketCloser(int sock)684   explicit SocketCloser(int sock) : sock_(sock) {}
~SocketCloser()685   ~SocketCloser() {
686     // Half-close and drain the socket before releasing it. This seems to be
687     // necessary for graceful shutdown on Windows. It will also avoid write
688     // failures in the test runner.
689 #if defined(OPENSSL_WINDOWS)
690     shutdown(sock_, SD_SEND);
691 #else
692     shutdown(sock_, SHUT_WR);
693 #endif
694     while (true) {
695       char buf[1024];
696       if (recv(sock_, buf, sizeof(buf), 0) <= 0) {
697         break;
698       }
699     }
700     closesocket(sock_);
701   }
702 
703  private:
704   const int sock_;
705 };
706 
SetupCtx(const TestConfig * config)707 static ScopedSSL_CTX SetupCtx(const TestConfig *config) {
708   ScopedSSL_CTX ssl_ctx(SSL_CTX_new(
709       config->is_dtls ? DTLS_method() : TLS_method()));
710   if (!ssl_ctx) {
711     return nullptr;
712   }
713 
714   std::string cipher_list = "ALL";
715   if (!config->cipher.empty()) {
716     cipher_list = config->cipher;
717     SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE);
718   }
719   if (!SSL_CTX_set_cipher_list(ssl_ctx.get(), cipher_list.c_str())) {
720     return nullptr;
721   }
722 
723   if (!config->cipher_tls10.empty() &&
724       !SSL_CTX_set_cipher_list_tls10(ssl_ctx.get(),
725                                      config->cipher_tls10.c_str())) {
726     return nullptr;
727   }
728   if (!config->cipher_tls11.empty() &&
729       !SSL_CTX_set_cipher_list_tls11(ssl_ctx.get(),
730                                      config->cipher_tls11.c_str())) {
731     return nullptr;
732   }
733 
734   ScopedDH dh(DH_get_2048_256(NULL));
735 
736   if (config->use_sparse_dh_prime) {
737     // This prime number is 2^1024 + 643 – a value just above a power of two.
738     // Because of its form, values modulo it are essentially certain to be one
739     // byte shorter. This is used to test padding of these values.
740     if (BN_hex2bn(
741             &dh->p,
742             "1000000000000000000000000000000000000000000000000000000000000000"
743             "0000000000000000000000000000000000000000000000000000000000000000"
744             "0000000000000000000000000000000000000000000000000000000000000000"
745             "0000000000000000000000000000000000000000000000000000000000000028"
746             "3") == 0 ||
747         !BN_set_word(dh->g, 2)) {
748       return nullptr;
749     }
750     dh->priv_length = 0;
751   }
752 
753   if (!dh || !SSL_CTX_set_tmp_dh(ssl_ctx.get(), dh.get())) {
754     return nullptr;
755   }
756 
757   if (config->async && config->is_server) {
758     // Disable the internal session cache. To test asynchronous session lookup,
759     // we use an external session cache.
760     SSL_CTX_set_session_cache_mode(
761         ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL);
762     SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback);
763   } else {
764     SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH);
765   }
766 
767   SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback);
768 
769   SSL_CTX_set_next_protos_advertised_cb(
770       ssl_ctx.get(), NextProtosAdvertisedCallback, NULL);
771   if (!config->select_next_proto.empty()) {
772     SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback,
773                                      NULL);
774   }
775 
776   if (!config->select_alpn.empty()) {
777     SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL);
778   }
779 
780   SSL_CTX_enable_tls_channel_id(ssl_ctx.get());
781   SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback);
782 
783   ssl_ctx->current_time_cb = CurrentTimeCallback;
784 
785   SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback);
786   SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback);
787 
788   if (config->use_ticket_callback) {
789     SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback);
790   }
791 
792   if (config->enable_client_custom_extension &&
793       !SSL_CTX_add_client_custom_ext(
794           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
795           CustomExtensionFreeCallback, kCustomExtensionAddArg,
796           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
797     return nullptr;
798   }
799 
800   if (config->enable_server_custom_extension &&
801       !SSL_CTX_add_server_custom_ext(
802           ssl_ctx.get(), kCustomExtensionValue, CustomExtensionAddCallback,
803           CustomExtensionFreeCallback, kCustomExtensionAddArg,
804           CustomExtensionParseCallback, kCustomExtensionParseArg)) {
805     return nullptr;
806   }
807 
808   if (config->verify_fail) {
809     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifyFail, NULL);
810   } else {
811     SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), VerifySucceed, NULL);
812   }
813 
814   if (!config->signed_cert_timestamps.empty() &&
815       !SSL_CTX_set_signed_cert_timestamp_list(
816           ssl_ctx.get(), (const uint8_t *)config->signed_cert_timestamps.data(),
817           config->signed_cert_timestamps.size())) {
818     return nullptr;
819   }
820 
821   return ssl_ctx;
822 }
823 
824 // RetryAsync is called after a failed operation on |ssl| with return code
825 // |ret|. If the operation should be retried, it simulates one asynchronous
826 // event and returns true. Otherwise it returns false.
RetryAsync(SSL * ssl,int ret)827 static bool RetryAsync(SSL *ssl, int ret) {
828   // No error; don't retry.
829   if (ret >= 0) {
830     return false;
831   }
832 
833   const TestConfig *config = GetConfigPtr(ssl);
834   TestState *test_state = GetTestState(ssl);
835   if (test_state->clock_delta.tv_usec != 0 ||
836       test_state->clock_delta.tv_sec != 0) {
837     // Process the timeout and retry.
838     test_state->clock.tv_usec += test_state->clock_delta.tv_usec;
839     test_state->clock.tv_sec += test_state->clock.tv_usec / 1000000;
840     test_state->clock.tv_usec %= 1000000;
841     test_state->clock.tv_sec += test_state->clock_delta.tv_sec;
842     memset(&test_state->clock_delta, 0, sizeof(test_state->clock_delta));
843 
844     // The DTLS retransmit logic silently ignores write failures. So the test
845     // may progress, allow writes through synchronously.
846     if (config->async) {
847       AsyncBioEnforceWriteQuota(test_state->async_bio, false);
848     }
849     int timeout_ret = DTLSv1_handle_timeout(ssl);
850     if (config->async) {
851       AsyncBioEnforceWriteQuota(test_state->async_bio, true);
852     }
853 
854     if (timeout_ret < 0) {
855       fprintf(stderr, "Error retransmitting.\n");
856       return false;
857     }
858     return true;
859   }
860 
861   // See if we needed to read or write more. If so, allow one byte through on
862   // the appropriate end to maximally stress the state machine.
863   switch (SSL_get_error(ssl, ret)) {
864     case SSL_ERROR_WANT_READ:
865       AsyncBioAllowRead(test_state->async_bio, 1);
866       return true;
867     case SSL_ERROR_WANT_WRITE:
868       AsyncBioAllowWrite(test_state->async_bio, 1);
869       return true;
870     case SSL_ERROR_WANT_CHANNEL_ID_LOOKUP: {
871       ScopedEVP_PKEY pkey = LoadPrivateKey(GetConfigPtr(ssl)->send_channel_id);
872       if (!pkey) {
873         return false;
874       }
875       test_state->channel_id = std::move(pkey);
876       return true;
877     }
878     case SSL_ERROR_WANT_X509_LOOKUP:
879       test_state->cert_ready = true;
880       return true;
881     case SSL_ERROR_PENDING_SESSION:
882       test_state->session = std::move(test_state->pending_session);
883       return true;
884     case SSL_ERROR_PENDING_CERTIFICATE:
885       // The handshake will resume without a second call to the early callback.
886       return InstallCertificate(ssl);
887     case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION:
888       test_state->private_key_retries++;
889       return true;
890     default:
891       return false;
892   }
893 }
894 
895 // DoRead reads from |ssl|, resolving any asynchronous operations. It returns
896 // the result value of the final |SSL_read| call.
DoRead(SSL * ssl,uint8_t * out,size_t max_out)897 static int DoRead(SSL *ssl, uint8_t *out, size_t max_out) {
898   const TestConfig *config = GetConfigPtr(ssl);
899   TestState *test_state = GetTestState(ssl);
900   int ret;
901   do {
902     if (config->async) {
903       // The DTLS retransmit logic silently ignores write failures. So the test
904       // may progress, allow writes through synchronously. |SSL_read| may
905       // trigger a retransmit, so disconnect the write quota.
906       AsyncBioEnforceWriteQuota(test_state->async_bio, false);
907     }
908     ret = SSL_read(ssl, out, max_out);
909     if (config->async) {
910       AsyncBioEnforceWriteQuota(test_state->async_bio, true);
911     }
912   } while (config->async && RetryAsync(ssl, ret));
913   return ret;
914 }
915 
916 // WriteAll writes |in_len| bytes from |in| to |ssl|, resolving any asynchronous
917 // operations. It returns the result of the final |SSL_write| call.
WriteAll(SSL * ssl,const uint8_t * in,size_t in_len)918 static int WriteAll(SSL *ssl, const uint8_t *in, size_t in_len) {
919   const TestConfig *config = GetConfigPtr(ssl);
920   int ret;
921   do {
922     ret = SSL_write(ssl, in, in_len);
923     if (ret > 0) {
924       in += ret;
925       in_len -= ret;
926     }
927   } while ((config->async && RetryAsync(ssl, ret)) || (ret > 0 && in_len > 0));
928   return ret;
929 }
930 
931 // DoShutdown calls |SSL_shutdown|, resolving any asynchronous operations. It
932 // returns the result of the final |SSL_shutdown| call.
DoShutdown(SSL * ssl)933 static int DoShutdown(SSL *ssl) {
934   const TestConfig *config = GetConfigPtr(ssl);
935   int ret;
936   do {
937     ret = SSL_shutdown(ssl);
938   } while (config->async && RetryAsync(ssl, ret));
939   return ret;
940 }
941 
942 // CheckHandshakeProperties checks, immediately after |ssl| completes its
943 // initial handshake (or False Starts), whether all the properties are
944 // consistent with the test configuration and invariants.
CheckHandshakeProperties(SSL * ssl,bool is_resume)945 static bool CheckHandshakeProperties(SSL *ssl, bool is_resume) {
946   const TestConfig *config = GetConfigPtr(ssl);
947 
948   if (SSL_get_current_cipher(ssl) == nullptr) {
949     fprintf(stderr, "null cipher after handshake\n");
950     return false;
951   }
952 
953   if (is_resume &&
954       (!!SSL_session_reused(ssl) == config->expect_session_miss)) {
955     fprintf(stderr, "session was%s reused\n",
956             SSL_session_reused(ssl) ? "" : " not");
957     return false;
958   }
959 
960   bool expect_handshake_done = is_resume || !config->false_start;
961   if (expect_handshake_done != GetTestState(ssl)->handshake_done) {
962     fprintf(stderr, "handshake was%s completed\n",
963             GetTestState(ssl)->handshake_done ? "" : " not");
964     return false;
965   }
966 
967   if (expect_handshake_done && !config->is_server) {
968     bool expect_new_session =
969         !config->expect_no_session &&
970         (!SSL_session_reused(ssl) || config->expect_ticket_renewal);
971     if (expect_new_session != GetTestState(ssl)->got_new_session) {
972       fprintf(stderr,
973               "new session was%s cached, but we expected the opposite\n",
974               GetTestState(ssl)->got_new_session ? "" : " not");
975       return false;
976     }
977   }
978 
979   if (config->is_server && !GetTestState(ssl)->early_callback_called) {
980     fprintf(stderr, "early callback not called\n");
981     return false;
982   }
983 
984   if (!config->expected_server_name.empty()) {
985     const char *server_name =
986         SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
987     if (server_name != config->expected_server_name) {
988       fprintf(stderr, "servername mismatch (got %s; want %s)\n",
989               server_name, config->expected_server_name.c_str());
990       return false;
991     }
992   }
993 
994   if (!config->expected_certificate_types.empty()) {
995     const uint8_t *certificate_types;
996     size_t certificate_types_len =
997         SSL_get0_certificate_types(ssl, &certificate_types);
998     if (certificate_types_len != config->expected_certificate_types.size() ||
999         memcmp(certificate_types,
1000                config->expected_certificate_types.data(),
1001                certificate_types_len) != 0) {
1002       fprintf(stderr, "certificate types mismatch\n");
1003       return false;
1004     }
1005   }
1006 
1007   if (!config->expected_next_proto.empty()) {
1008     const uint8_t *next_proto;
1009     unsigned next_proto_len;
1010     SSL_get0_next_proto_negotiated(ssl, &next_proto, &next_proto_len);
1011     if (next_proto_len != config->expected_next_proto.size() ||
1012         memcmp(next_proto, config->expected_next_proto.data(),
1013                next_proto_len) != 0) {
1014       fprintf(stderr, "negotiated next proto mismatch\n");
1015       return false;
1016     }
1017   }
1018 
1019   if (!config->expected_alpn.empty()) {
1020     const uint8_t *alpn_proto;
1021     unsigned alpn_proto_len;
1022     SSL_get0_alpn_selected(ssl, &alpn_proto, &alpn_proto_len);
1023     if (alpn_proto_len != config->expected_alpn.size() ||
1024         memcmp(alpn_proto, config->expected_alpn.data(),
1025                alpn_proto_len) != 0) {
1026       fprintf(stderr, "negotiated alpn proto mismatch\n");
1027       return false;
1028     }
1029   }
1030 
1031   if (!config->expected_channel_id.empty()) {
1032     uint8_t channel_id[64];
1033     if (!SSL_get_tls_channel_id(ssl, channel_id, sizeof(channel_id))) {
1034       fprintf(stderr, "no channel id negotiated\n");
1035       return false;
1036     }
1037     if (config->expected_channel_id.size() != 64 ||
1038         memcmp(config->expected_channel_id.data(),
1039                channel_id, 64) != 0) {
1040       fprintf(stderr, "channel id mismatch\n");
1041       return false;
1042     }
1043   }
1044 
1045   if (config->expect_extended_master_secret) {
1046     if (!ssl->session->extended_master_secret) {
1047       fprintf(stderr, "No EMS for session when expected");
1048       return false;
1049     }
1050   }
1051 
1052   if (!config->expected_ocsp_response.empty()) {
1053     const uint8_t *data;
1054     size_t len;
1055     SSL_get0_ocsp_response(ssl, &data, &len);
1056     if (config->expected_ocsp_response.size() != len ||
1057         memcmp(config->expected_ocsp_response.data(), data, len) != 0) {
1058       fprintf(stderr, "OCSP response mismatch\n");
1059       return false;
1060     }
1061   }
1062 
1063   if (!config->expected_signed_cert_timestamps.empty()) {
1064     const uint8_t *data;
1065     size_t len;
1066     SSL_get0_signed_cert_timestamp_list(ssl, &data, &len);
1067     if (config->expected_signed_cert_timestamps.size() != len ||
1068         memcmp(config->expected_signed_cert_timestamps.data(),
1069                data, len) != 0) {
1070       fprintf(stderr, "SCT list mismatch\n");
1071       return false;
1072     }
1073   }
1074 
1075   if (config->expect_verify_result) {
1076     int expected_verify_result = config->verify_fail ?
1077       X509_V_ERR_APPLICATION_VERIFICATION :
1078       X509_V_OK;
1079 
1080     if (SSL_get_verify_result(ssl) != expected_verify_result) {
1081       fprintf(stderr, "Wrong certificate verification result\n");
1082       return false;
1083     }
1084   }
1085 
1086   if (config->expect_server_key_exchange_hash != 0 &&
1087       config->expect_server_key_exchange_hash !=
1088           SSL_get_server_key_exchange_hash(ssl)) {
1089     fprintf(stderr, "ServerKeyExchange hash was %d, wanted %d.\n",
1090             SSL_get_server_key_exchange_hash(ssl),
1091             config->expect_server_key_exchange_hash);
1092     return false;
1093   }
1094 
1095   if (config->expect_key_exchange_info != 0) {
1096     uint32_t info = SSL_SESSION_get_key_exchange_info(SSL_get_session(ssl));
1097     if (static_cast<uint32_t>(config->expect_key_exchange_info) != info) {
1098       fprintf(stderr, "key_exchange_info was %" PRIu32 ", wanted %" PRIu32 "\n",
1099               info, static_cast<uint32_t>(config->expect_key_exchange_info));
1100       return false;
1101     }
1102   }
1103 
1104   if (!config->is_server) {
1105     /* Clients should expect a peer certificate chain iff this was not a PSK
1106      * cipher suite. */
1107     if (config->psk.empty()) {
1108       if (SSL_get_peer_cert_chain(ssl) == nullptr) {
1109         fprintf(stderr, "Missing peer certificate chain!\n");
1110         return false;
1111       }
1112     } else if (SSL_get_peer_cert_chain(ssl) != nullptr) {
1113       fprintf(stderr, "Unexpected peer certificate chain!\n");
1114       return false;
1115     }
1116   }
1117   return true;
1118 }
1119 
1120 // DoExchange runs a test SSL exchange against the peer. On success, it returns
1121 // true and sets |*out_session| to the negotiated SSL session. If the test is a
1122 // resumption attempt, |is_resume| is true and |session| is the session from the
1123 // previous exchange.
DoExchange(ScopedSSL_SESSION * out_session,SSL_CTX * ssl_ctx,const TestConfig * config,bool is_resume,SSL_SESSION * session)1124 static bool DoExchange(ScopedSSL_SESSION *out_session, SSL_CTX *ssl_ctx,
1125                        const TestConfig *config, bool is_resume,
1126                        SSL_SESSION *session) {
1127   ScopedSSL ssl(SSL_new(ssl_ctx));
1128   if (!ssl) {
1129     return false;
1130   }
1131 
1132   if (!SetConfigPtr(ssl.get(), config) ||
1133       !SetTestState(ssl.get(), std::unique_ptr<TestState>(new TestState))) {
1134     return false;
1135   }
1136 
1137   if (config->fallback_scsv &&
1138       !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) {
1139     return false;
1140   }
1141   if (!config->use_early_callback) {
1142     if (config->async) {
1143       // TODO(davidben): Also test |s->ctx->client_cert_cb| on the client.
1144       SSL_set_cert_cb(ssl.get(), CertCallback, NULL);
1145     } else if (!InstallCertificate(ssl.get())) {
1146       return false;
1147     }
1148   }
1149   if (config->require_any_client_certificate) {
1150     SSL_set_verify(ssl.get(), SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1151                    NULL);
1152   }
1153   if (config->verify_peer) {
1154     SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, NULL);
1155   }
1156   if (config->false_start) {
1157     SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START);
1158   }
1159   if (config->cbc_record_splitting) {
1160     SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING);
1161   }
1162   if (config->partial_write) {
1163     SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE);
1164   }
1165   if (config->no_tls12) {
1166     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2);
1167   }
1168   if (config->no_tls11) {
1169     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1);
1170   }
1171   if (config->no_tls1) {
1172     SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1);
1173   }
1174   if (config->no_ssl3) {
1175     SSL_set_options(ssl.get(), SSL_OP_NO_SSLv3);
1176   }
1177   if (!config->expected_channel_id.empty()) {
1178     SSL_enable_tls_channel_id(ssl.get());
1179   }
1180   if (!config->send_channel_id.empty()) {
1181     SSL_enable_tls_channel_id(ssl.get());
1182     if (!config->async) {
1183       // The async case will be supplied by |ChannelIdCallback|.
1184       ScopedEVP_PKEY pkey = LoadPrivateKey(config->send_channel_id);
1185       if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) {
1186         return false;
1187       }
1188     }
1189   }
1190   if (!config->host_name.empty() &&
1191       !SSL_set_tlsext_host_name(ssl.get(), config->host_name.c_str())) {
1192     return false;
1193   }
1194   if (!config->advertise_alpn.empty() &&
1195       SSL_set_alpn_protos(ssl.get(),
1196                           (const uint8_t *)config->advertise_alpn.data(),
1197                           config->advertise_alpn.size()) != 0) {
1198     return false;
1199   }
1200   if (!config->psk.empty()) {
1201     SSL_set_psk_client_callback(ssl.get(), PskClientCallback);
1202     SSL_set_psk_server_callback(ssl.get(), PskServerCallback);
1203   }
1204   if (!config->psk_identity.empty() &&
1205       !SSL_use_psk_identity_hint(ssl.get(), config->psk_identity.c_str())) {
1206     return false;
1207   }
1208   if (!config->srtp_profiles.empty() &&
1209       !SSL_set_srtp_profiles(ssl.get(), config->srtp_profiles.c_str())) {
1210     return false;
1211   }
1212   if (config->enable_ocsp_stapling &&
1213       !SSL_enable_ocsp_stapling(ssl.get())) {
1214     return false;
1215   }
1216   if (config->enable_signed_cert_timestamps &&
1217       !SSL_enable_signed_cert_timestamps(ssl.get())) {
1218     return false;
1219   }
1220   if (config->min_version != 0) {
1221     SSL_set_min_version(ssl.get(), (uint16_t)config->min_version);
1222   }
1223   if (config->max_version != 0) {
1224     SSL_set_max_version(ssl.get(), (uint16_t)config->max_version);
1225   }
1226   if (config->mtu != 0) {
1227     SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU);
1228     SSL_set_mtu(ssl.get(), config->mtu);
1229   }
1230   if (config->install_ddos_callback) {
1231     SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback);
1232   }
1233   if (config->renegotiate_once) {
1234     SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once);
1235   }
1236   if (config->renegotiate_freely) {
1237     SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely);
1238   }
1239   if (config->renegotiate_ignore) {
1240     SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore);
1241   }
1242   if (!config->check_close_notify) {
1243     SSL_set_quiet_shutdown(ssl.get(), 1);
1244   }
1245   if (config->disable_npn) {
1246     SSL_set_options(ssl.get(), SSL_OP_DISABLE_NPN);
1247   }
1248   if (config->p384_only) {
1249     int nid = NID_secp384r1;
1250     if (!SSL_set1_curves(ssl.get(), &nid, 1)) {
1251       return false;
1252     }
1253   }
1254   if (config->enable_all_curves) {
1255     static const int kAllCurves[] = {
1256         NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_x25519,
1257     };
1258     if (!SSL_set1_curves(ssl.get(), kAllCurves,
1259                          sizeof(kAllCurves) / sizeof(kAllCurves[0]))) {
1260       return false;
1261     }
1262   }
1263 
1264   int sock = Connect(config->port);
1265   if (sock == -1) {
1266     return false;
1267   }
1268   SocketCloser closer(sock);
1269 
1270   ScopedBIO bio(BIO_new_socket(sock, BIO_NOCLOSE));
1271   if (!bio) {
1272     return false;
1273   }
1274   if (config->is_dtls) {
1275     ScopedBIO packeted =
1276         PacketedBioCreate(&GetTestState(ssl.get())->clock_delta);
1277     BIO_push(packeted.get(), bio.release());
1278     bio = std::move(packeted);
1279   }
1280   if (config->async) {
1281     ScopedBIO async_scoped =
1282         config->is_dtls ? AsyncBioCreateDatagram() : AsyncBioCreate();
1283     BIO_push(async_scoped.get(), bio.release());
1284     GetTestState(ssl.get())->async_bio = async_scoped.get();
1285     bio = std::move(async_scoped);
1286   }
1287   SSL_set_bio(ssl.get(), bio.get(), bio.get());
1288   bio.release();  // SSL_set_bio takes ownership.
1289 
1290   if (session != NULL) {
1291     if (!config->is_server) {
1292       if (SSL_set_session(ssl.get(), session) != 1) {
1293         return false;
1294       }
1295     } else if (config->async) {
1296       // The internal session cache is disabled, so install the session
1297       // manually.
1298       GetTestState(ssl.get())->pending_session.reset(
1299           SSL_SESSION_up_ref(session));
1300     }
1301   }
1302 
1303   if (SSL_get_current_cipher(ssl.get()) != nullptr) {
1304     fprintf(stderr, "non-null cipher before handshake\n");
1305     return false;
1306   }
1307 
1308   int ret;
1309   if (config->implicit_handshake) {
1310     if (config->is_server) {
1311       SSL_set_accept_state(ssl.get());
1312     } else {
1313       SSL_set_connect_state(ssl.get());
1314     }
1315   } else {
1316     do {
1317       if (config->is_server) {
1318         ret = SSL_accept(ssl.get());
1319       } else {
1320         ret = SSL_connect(ssl.get());
1321       }
1322     } while (config->async && RetryAsync(ssl.get(), ret));
1323     if (ret != 1 ||
1324         !CheckHandshakeProperties(ssl.get(), is_resume)) {
1325       return false;
1326     }
1327 
1328     // Reset the state to assert later that the callback isn't called in
1329     // renegotations.
1330     GetTestState(ssl.get())->got_new_session = false;
1331   }
1332 
1333   if (config->export_keying_material > 0) {
1334     std::vector<uint8_t> result(
1335         static_cast<size_t>(config->export_keying_material));
1336     if (!SSL_export_keying_material(
1337             ssl.get(), result.data(), result.size(),
1338             config->export_label.data(), config->export_label.size(),
1339             reinterpret_cast<const uint8_t*>(config->export_context.data()),
1340             config->export_context.size(), config->use_export_context)) {
1341       fprintf(stderr, "failed to export keying material\n");
1342       return false;
1343     }
1344     if (WriteAll(ssl.get(), result.data(), result.size()) < 0) {
1345       return false;
1346     }
1347   }
1348 
1349   if (config->tls_unique) {
1350     uint8_t tls_unique[16];
1351     size_t tls_unique_len;
1352     if (!SSL_get_tls_unique(ssl.get(), tls_unique, &tls_unique_len,
1353                             sizeof(tls_unique))) {
1354       fprintf(stderr, "failed to get tls-unique\n");
1355       return false;
1356     }
1357 
1358     if (tls_unique_len != 12) {
1359       fprintf(stderr, "expected 12 bytes of tls-unique but got %u",
1360               static_cast<unsigned>(tls_unique_len));
1361       return false;
1362     }
1363 
1364     if (WriteAll(ssl.get(), tls_unique, tls_unique_len) < 0) {
1365       return false;
1366     }
1367   }
1368 
1369   if (config->write_different_record_sizes) {
1370     if (config->is_dtls) {
1371       fprintf(stderr, "write_different_record_sizes not supported for DTLS\n");
1372       return false;
1373     }
1374     // This mode writes a number of different record sizes in an attempt to
1375     // trip up the CBC record splitting code.
1376     static const size_t kBufLen = 32769;
1377     std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1378     memset(buf.get(), 0x42, kBufLen);
1379     static const size_t kRecordSizes[] = {
1380         0, 1, 255, 256, 257, 16383, 16384, 16385, 32767, 32768, 32769};
1381     for (size_t i = 0; i < sizeof(kRecordSizes) / sizeof(kRecordSizes[0]);
1382          i++) {
1383       const size_t len = kRecordSizes[i];
1384       if (len > kBufLen) {
1385         fprintf(stderr, "Bad kRecordSizes value.\n");
1386         return false;
1387       }
1388       if (WriteAll(ssl.get(), buf.get(), len) < 0) {
1389         return false;
1390       }
1391     }
1392   } else {
1393     if (config->shim_writes_first) {
1394       if (WriteAll(ssl.get(), reinterpret_cast<const uint8_t *>("hello"),
1395                    5) < 0) {
1396         return false;
1397       }
1398     }
1399     if (!config->shim_shuts_down) {
1400       for (;;) {
1401         static const size_t kBufLen = 16384;
1402         std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufLen]);
1403 
1404         // Read only 512 bytes at a time in TLS to ensure records may be
1405         // returned in multiple reads.
1406         int n = DoRead(ssl.get(), buf.get(), config->is_dtls ? kBufLen : 512);
1407         int err = SSL_get_error(ssl.get(), n);
1408         if (err == SSL_ERROR_ZERO_RETURN ||
1409             (n == 0 && err == SSL_ERROR_SYSCALL)) {
1410           if (n != 0) {
1411             fprintf(stderr, "Invalid SSL_get_error output\n");
1412             return false;
1413           }
1414           // Stop on either clean or unclean shutdown.
1415           break;
1416         } else if (err != SSL_ERROR_NONE) {
1417           if (n > 0) {
1418             fprintf(stderr, "Invalid SSL_get_error output\n");
1419             return false;
1420           }
1421           return false;
1422         }
1423         // Successfully read data.
1424         if (n <= 0) {
1425           fprintf(stderr, "Invalid SSL_get_error output\n");
1426           return false;
1427         }
1428 
1429         // After a successful read, with or without False Start, the handshake
1430         // must be complete.
1431         if (!GetTestState(ssl.get())->handshake_done) {
1432           fprintf(stderr, "handshake was not completed after SSL_read\n");
1433           return false;
1434         }
1435 
1436         for (int i = 0; i < n; i++) {
1437           buf[i] ^= 0xff;
1438         }
1439         if (WriteAll(ssl.get(), buf.get(), n) < 0) {
1440           return false;
1441         }
1442       }
1443     }
1444   }
1445 
1446   if (!config->is_server && !config->false_start &&
1447       !config->implicit_handshake &&
1448       GetTestState(ssl.get())->got_new_session) {
1449     fprintf(stderr, "new session was established after the handshake\n");
1450     return false;
1451   }
1452 
1453   if (out_session) {
1454     out_session->reset(SSL_get1_session(ssl.get()));
1455   }
1456 
1457   ret = DoShutdown(ssl.get());
1458 
1459   if (config->shim_shuts_down && config->check_close_notify) {
1460     // We initiate shutdown, so |SSL_shutdown| will return in two stages. First
1461     // it returns zero when our close_notify is sent, then one when the peer's
1462     // is received.
1463     if (ret != 0) {
1464       fprintf(stderr, "Unexpected SSL_shutdown result: %d != 0\n", ret);
1465       return false;
1466     }
1467     ret = DoShutdown(ssl.get());
1468   }
1469 
1470   if (ret != 1) {
1471     fprintf(stderr, "Unexpected SSL_shutdown result: %d != 1\n", ret);
1472     return false;
1473   }
1474 
1475   if (SSL_total_renegotiations(ssl.get()) !=
1476       config->expect_total_renegotiations) {
1477     fprintf(stderr, "Expected %d renegotiations, got %d\n",
1478             config->expect_total_renegotiations,
1479             SSL_total_renegotiations(ssl.get()));
1480     return false;
1481   }
1482 
1483   return true;
1484 }
1485 
main(int argc,char ** argv)1486 int main(int argc, char **argv) {
1487 #if defined(OPENSSL_WINDOWS)
1488   /* Initialize Winsock. */
1489   WORD wsa_version = MAKEWORD(2, 2);
1490   WSADATA wsa_data;
1491   int wsa_err = WSAStartup(wsa_version, &wsa_data);
1492   if (wsa_err != 0) {
1493     fprintf(stderr, "WSAStartup failed: %d\n", wsa_err);
1494     return 1;
1495   }
1496   if (wsa_data.wVersion != wsa_version) {
1497     fprintf(stderr, "Didn't get expected version: %x\n", wsa_data.wVersion);
1498     return 1;
1499   }
1500 #else
1501   signal(SIGPIPE, SIG_IGN);
1502 #endif
1503 
1504   CRYPTO_library_init();
1505   g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);
1506   g_state_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, TestStateExFree);
1507   if (g_config_index < 0 || g_state_index < 0) {
1508     return 1;
1509   }
1510 
1511   TestConfig config;
1512   if (!ParseConfig(argc - 1, argv + 1, &config)) {
1513     return Usage(argv[0]);
1514   }
1515 
1516   ScopedSSL_CTX ssl_ctx = SetupCtx(&config);
1517   if (!ssl_ctx) {
1518     ERR_print_errors_fp(stderr);
1519     return 1;
1520   }
1521 
1522   ScopedSSL_SESSION session;
1523   if (!DoExchange(&session, ssl_ctx.get(), &config, false /* is_resume */,
1524                   NULL /* session */)) {
1525     ERR_print_errors_fp(stderr);
1526     return 1;
1527   }
1528 
1529   if (config.resume &&
1530       !DoExchange(NULL, ssl_ctx.get(), &config, true /* is_resume */,
1531                   session.get())) {
1532     ERR_print_errors_fp(stderr);
1533     return 1;
1534   }
1535 
1536   return 0;
1537 }
1538