Code review. Split tests up
[openssl.git] / test / handshake_helper.c
1 /*
2  * Copyright 2016 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 #include <string.h>
11
12 #include <openssl/bio.h>
13 #include <openssl/x509_vfy.h>
14 #include <openssl/ssl.h>
15 #ifndef OPENSSL_NO_SRP
16 #include <openssl/srp.h>
17 #endif
18
19 #include "handshake_helper.h"
20 #include "testutil.h"
21
22 HANDSHAKE_RESULT *HANDSHAKE_RESULT_new()
23 {
24     HANDSHAKE_RESULT *ret = OPENSSL_zalloc(sizeof(*ret));
25     TEST_check(ret != NULL);
26     return ret;
27 }
28
29 void HANDSHAKE_RESULT_free(HANDSHAKE_RESULT *result)
30 {
31     if (result == NULL)
32         return;
33     OPENSSL_free(result->client_npn_negotiated);
34     OPENSSL_free(result->server_npn_negotiated);
35     OPENSSL_free(result->client_alpn_negotiated);
36     OPENSSL_free(result->server_alpn_negotiated);
37     sk_X509_NAME_pop_free(result->server_ca_names, X509_NAME_free);
38     sk_X509_NAME_pop_free(result->client_ca_names, X509_NAME_free);
39     OPENSSL_free(result);
40 }
41
42 /*
43  * Since there appears to be no way to extract the sent/received alert
44  * from the SSL object directly, we use the info callback and stash
45  * the result in ex_data.
46  */
47 typedef struct handshake_ex_data_st {
48     int alert_sent;
49     int num_fatal_alerts_sent;
50     int alert_received;
51     int session_ticket_do_not_call;
52     ssl_servername_t servername;
53 } HANDSHAKE_EX_DATA;
54
55 typedef struct ctx_data_st {
56     unsigned char *npn_protocols;
57     size_t npn_protocols_len;
58     unsigned char *alpn_protocols;
59     size_t alpn_protocols_len;
60     char *srp_user;
61     char *srp_password;
62 } CTX_DATA;
63
64 /* |ctx_data| itself is stack-allocated. */
65 static void ctx_data_free_data(CTX_DATA *ctx_data)
66 {
67     OPENSSL_free(ctx_data->npn_protocols);
68     ctx_data->npn_protocols = NULL;
69     OPENSSL_free(ctx_data->alpn_protocols);
70     ctx_data->alpn_protocols = NULL;
71     OPENSSL_free(ctx_data->srp_user);
72     ctx_data->srp_user = NULL;
73     OPENSSL_free(ctx_data->srp_password);
74     ctx_data->srp_password = NULL;
75 }
76
77 static int ex_data_idx;
78
79 static void info_cb(const SSL *s, int where, int ret)
80 {
81     if (where & SSL_CB_ALERT) {
82         HANDSHAKE_EX_DATA *ex_data =
83             (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
84         if (where & SSL_CB_WRITE) {
85             ex_data->alert_sent = ret;
86             if (strcmp(SSL_alert_type_string(ret), "F") == 0
87                 || strcmp(SSL_alert_desc_string(ret), "CN") == 0)
88                 ex_data->num_fatal_alerts_sent++;
89         } else {
90             ex_data->alert_received = ret;
91         }
92     }
93 }
94
95 /* Select the appropriate server CTX.
96  * Returns SSL_TLSEXT_ERR_OK if a match was found.
97  * If |ignore| is 1, returns SSL_TLSEXT_ERR_NOACK on mismatch.
98  * Otherwise, returns SSL_TLSEXT_ERR_ALERT_FATAL on mismatch.
99  * An empty SNI extension also returns SSL_TSLEXT_ERR_NOACK.
100  */
101 static int select_server_ctx(SSL *s, void *arg, int ignore)
102 {
103     const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
104     HANDSHAKE_EX_DATA *ex_data =
105         (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
106
107     if (servername == NULL) {
108         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
109         return SSL_TLSEXT_ERR_NOACK;
110     }
111
112     if (strcmp(servername, "server2") == 0) {
113         SSL_CTX *new_ctx = (SSL_CTX*)arg;
114         SSL_set_SSL_CTX(s, new_ctx);
115         /*
116          * Copy over all the SSL_CTX options - reasonable behavior
117          * allows testing of cases where the options between two
118          * contexts differ/conflict
119          */
120         SSL_clear_options(s, 0xFFFFFFFFL);
121         SSL_set_options(s, SSL_CTX_get_options(new_ctx));
122
123         ex_data->servername = SSL_TEST_SERVERNAME_SERVER2;
124         return SSL_TLSEXT_ERR_OK;
125     } else if (strcmp(servername, "server1") == 0) {
126         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
127         return SSL_TLSEXT_ERR_OK;
128     } else if (ignore) {
129         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
130         return SSL_TLSEXT_ERR_NOACK;
131     } else {
132         /* Don't set an explicit alert, to test library defaults. */
133         return SSL_TLSEXT_ERR_ALERT_FATAL;
134     }
135 }
136
137 static int early_select_server_ctx(SSL *s, void *arg, int ignore)
138 {
139     const char *servername;
140     const unsigned char *p;
141     size_t len, remaining;
142     HANDSHAKE_EX_DATA *ex_data =
143         (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
144
145     /*
146      * The server_name extension was given too much extensibility when it
147      * was written, so parsing the normal case is a bit complex.
148      */
149     if (!SSL_early_get0_ext(s, TLSEXT_TYPE_server_name, &p, &remaining) ||
150         remaining <= 2)
151         return 0;
152     /* Extract the length of the supplied list of names. */
153     len = (*(p++) << 1);
154     len += *(p++);
155     if (len + 2 != remaining)
156         return 0;
157     remaining = len;
158     /*
159      * The list in practice only has a single element, so we only consider
160      * the first one.
161      */
162     if (remaining == 0 || *p++ != TLSEXT_NAMETYPE_host_name)
163         return 0;
164     remaining--;
165     /* Now we can finally pull out the byte array with the actual hostname. */
166     if (remaining <= 2)
167         return 0;
168     len = (*(p++) << 1);
169     len += *(p++);
170     if (len + 2 > remaining)
171         return 0;
172     remaining = len;
173     servername = (const char *)p;
174
175     if (len == strlen("server2") && strncmp(servername, "server2", len) == 0) {
176         SSL_CTX *new_ctx = arg;
177         SSL_set_SSL_CTX(s, new_ctx);
178         /*
179          * Copy over all the SSL_CTX options - reasonable behavior
180          * allows testing of cases where the options between two
181          * contexts differ/conflict
182          */
183         SSL_clear_options(s, 0xFFFFFFFFL);
184         SSL_set_options(s, SSL_CTX_get_options(new_ctx));
185
186         ex_data->servername = SSL_TEST_SERVERNAME_SERVER2;
187         return 1;
188     } else if (len == strlen("server1") &&
189                strncmp(servername, "server1", len) == 0) {
190         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
191         return 1;
192     } else if (ignore) {
193         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
194         return 1;
195     }
196     return 0;
197 }
198 /*
199  * (RFC 6066):
200  *  If the server understood the ClientHello extension but
201  *  does not recognize the server name, the server SHOULD take one of two
202  *  actions: either abort the handshake by sending a fatal-level
203  *  unrecognized_name(112) alert or continue the handshake.
204  *
205  * This behaviour is up to the application to configure; we test both
206  * configurations to ensure the state machine propagates the result
207  * correctly.
208  */
209 static int servername_ignore_cb(SSL *s, int *ad, void *arg)
210 {
211     return select_server_ctx(s, arg, 1);
212 }
213
214 static int servername_reject_cb(SSL *s, int *ad, void *arg)
215 {
216     return select_server_ctx(s, arg, 0);
217 }
218
219 static int early_ignore_cb(SSL *s, int *al, void *arg)
220 {
221     if (!early_select_server_ctx(s, arg, 1)) {
222         *al = SSL_AD_UNRECOGNIZED_NAME;
223         return 0;
224     }
225     return 1;
226 }
227
228 static int early_reject_cb(SSL *s, int *al, void *arg)
229 {
230     if (!early_select_server_ctx(s, arg, 0)) {
231         *al = SSL_AD_UNRECOGNIZED_NAME;
232         return 0;
233     }
234     return 1;
235 }
236
237 static int early_nov12_cb(SSL *s, int *al, void *arg)
238 {
239     int ret;
240     unsigned int v;
241     const unsigned char *p;
242
243     v = SSL_early_get0_legacy_version(s);
244     if (v > TLS1_2_VERSION || v < SSL3_VERSION) {
245         *al = SSL_AD_PROTOCOL_VERSION;
246         return 0;
247     }
248     (void)SSL_early_get0_session_id(s, &p);
249     if (p == NULL ||
250         SSL_early_get0_random(s, &p) == 0 ||
251         SSL_early_get0_ciphers(s, &p) == 0 ||
252         SSL_early_get0_compression_methods(s, &p) == 0) {
253         *al = SSL_AD_INTERNAL_ERROR;
254         return 0;
255     }
256     ret = early_select_server_ctx(s, arg, 0);
257     SSL_set_max_proto_version(s, TLS1_1_VERSION);
258     if (!ret)
259         *al = SSL_AD_UNRECOGNIZED_NAME;
260     return ret;
261 }
262
263 static unsigned char dummy_ocsp_resp_good_val = 0xff;
264 static unsigned char dummy_ocsp_resp_bad_val = 0xfe;
265
266 static int server_ocsp_cb(SSL *s, void *arg)
267 {
268     unsigned char *resp;
269
270     resp = OPENSSL_malloc(1);
271     if (resp == NULL)
272         return SSL_TLSEXT_ERR_ALERT_FATAL;
273     /*
274      * For the purposes of testing we just send back a dummy OCSP response
275      */
276     *resp = *(unsigned char *)arg;
277     if (!SSL_set_tlsext_status_ocsp_resp(s, resp, 1))
278         return SSL_TLSEXT_ERR_ALERT_FATAL;
279
280     return SSL_TLSEXT_ERR_OK;
281 }
282
283 static int client_ocsp_cb(SSL *s, void *arg)
284 {
285     const unsigned char *resp;
286     int len;
287
288     len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
289     if (len != 1 || *resp != dummy_ocsp_resp_good_val)
290         return 0;
291
292     return 1;
293 }
294
295 static int verify_reject_cb(X509_STORE_CTX *ctx, void *arg) {
296     X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
297     return 0;
298 }
299
300 static int verify_accept_cb(X509_STORE_CTX *ctx, void *arg) {
301     return 1;
302 }
303
304 static int broken_session_ticket_cb(SSL *s, unsigned char *key_name, unsigned char *iv,
305                                     EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
306 {
307     return 0;
308 }
309
310 static int do_not_call_session_ticket_cb(SSL *s, unsigned char *key_name,
311                                          unsigned char *iv,
312                                          EVP_CIPHER_CTX *ctx,
313                                          HMAC_CTX *hctx, int enc)
314 {
315     HANDSHAKE_EX_DATA *ex_data =
316         (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
317     ex_data->session_ticket_do_not_call = 1;
318     return 0;
319 }
320
321 /* Parse the comma-separated list into TLS format. */
322 static void parse_protos(const char *protos, unsigned char **out, size_t *outlen)
323 {
324     size_t len, i, prefix;
325
326     len = strlen(protos);
327
328     /* Should never have reuse. */
329     TEST_check(*out == NULL);
330
331     /* Test values are small, so we omit length limit checks. */
332     *out = OPENSSL_malloc(len + 1);
333     TEST_check(*out != NULL);
334     *outlen = len + 1;
335
336     /*
337      * foo => '3', 'f', 'o', 'o'
338      * foo,bar => '3', 'f', 'o', 'o', '3', 'b', 'a', 'r'
339      */
340     memcpy(*out + 1, protos, len);
341
342     prefix = 0;
343     i = prefix + 1;
344     while (i <= len) {
345         if ((*out)[i] == ',') {
346             TEST_check(i - 1 - prefix > 0);
347             (*out)[prefix] = i - 1 - prefix;
348             prefix = i;
349         }
350         i++;
351     }
352     TEST_check(len - prefix > 0);
353     (*out)[prefix] = len - prefix;
354 }
355
356 #ifndef OPENSSL_NO_NEXTPROTONEG
357 /*
358  * The client SHOULD select the first protocol advertised by the server that it
359  * also supports.  In the event that the client doesn't support any of server's
360  * protocols, or the server doesn't advertise any, it SHOULD select the first
361  * protocol that it supports.
362  */
363 static int client_npn_cb(SSL *s, unsigned char **out, unsigned char *outlen,
364                          const unsigned char *in, unsigned int inlen,
365                          void *arg)
366 {
367     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
368     int ret;
369
370     ret = SSL_select_next_proto(out, outlen, in, inlen,
371                                 ctx_data->npn_protocols,
372                                 ctx_data->npn_protocols_len);
373     /* Accept both OPENSSL_NPN_NEGOTIATED and OPENSSL_NPN_NO_OVERLAP. */
374     TEST_check(ret == OPENSSL_NPN_NEGOTIATED || ret == OPENSSL_NPN_NO_OVERLAP);
375     return SSL_TLSEXT_ERR_OK;
376 }
377
378 static int server_npn_cb(SSL *s, const unsigned char **data,
379                          unsigned int *len, void *arg)
380 {
381     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
382     *data = ctx_data->npn_protocols;
383     *len = ctx_data->npn_protocols_len;
384     return SSL_TLSEXT_ERR_OK;
385 }
386 #endif
387
388 /*
389  * The server SHOULD select the most highly preferred protocol that it supports
390  * and that is also advertised by the client.  In the event that the server
391  * supports no protocols that the client advertises, then the server SHALL
392  * respond with a fatal "no_application_protocol" alert.
393  */
394 static int server_alpn_cb(SSL *s, const unsigned char **out,
395                           unsigned char *outlen, const unsigned char *in,
396                           unsigned int inlen, void *arg)
397 {
398     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
399     int ret;
400
401     /* SSL_select_next_proto isn't const-correct... */
402     unsigned char *tmp_out;
403
404     /*
405      * The result points either to |in| or to |ctx_data->alpn_protocols|.
406      * The callback is allowed to point to |in| or to a long-lived buffer,
407      * so we can return directly without storing a copy.
408      */
409     ret = SSL_select_next_proto(&tmp_out, outlen,
410                                 ctx_data->alpn_protocols,
411                                 ctx_data->alpn_protocols_len, in, inlen);
412
413     *out = tmp_out;
414     /* Unlike NPN, we don't tolerate a mismatch. */
415     return ret == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
416         : SSL_TLSEXT_ERR_ALERT_FATAL;
417 }
418
419 #ifndef OPENSSL_NO_SRP
420 static char *client_srp_cb(SSL *s, void *arg)
421 {
422     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
423     return OPENSSL_strdup(ctx_data->srp_password);
424 }
425
426 static int server_srp_cb(SSL *s, int *ad, void *arg)
427 {
428     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
429     if (strcmp(ctx_data->srp_user, SSL_get_srp_username(s)) != 0)
430         return SSL3_AL_FATAL;
431     if (SSL_set_srp_server_param_pw(s, ctx_data->srp_user,
432                                     ctx_data->srp_password,
433                                     "2048" /* known group */) < 0) {
434         *ad = SSL_AD_INTERNAL_ERROR;
435         return SSL3_AL_FATAL;
436     }
437     return SSL_ERROR_NONE;
438 }
439 #endif  /* !OPENSSL_NO_SRP */
440
441 /*
442  * Configure callbacks and other properties that can't be set directly
443  * in the server/client CONF.
444  */
445 static void configure_handshake_ctx(SSL_CTX *server_ctx, SSL_CTX *server2_ctx,
446                                     SSL_CTX *client_ctx,
447                                     const SSL_TEST_CTX *test,
448                                     const SSL_TEST_EXTRA_CONF *extra,
449                                     CTX_DATA *server_ctx_data,
450                                     CTX_DATA *server2_ctx_data,
451                                     CTX_DATA *client_ctx_data)
452 {
453     unsigned char *ticket_keys;
454     size_t ticket_key_len;
455
456     TEST_check(SSL_CTX_set_max_send_fragment(server_ctx,
457                                              test->max_fragment_size) == 1);
458     if (server2_ctx != NULL) {
459         TEST_check(SSL_CTX_set_max_send_fragment(server2_ctx,
460                                                  test->max_fragment_size) == 1);
461     }
462     TEST_check(SSL_CTX_set_max_send_fragment(client_ctx,
463                                              test->max_fragment_size) == 1);
464
465     switch (extra->client.verify_callback) {
466     case SSL_TEST_VERIFY_ACCEPT_ALL:
467         SSL_CTX_set_cert_verify_callback(client_ctx, &verify_accept_cb,
468                                          NULL);
469         break;
470     case SSL_TEST_VERIFY_REJECT_ALL:
471         SSL_CTX_set_cert_verify_callback(client_ctx, &verify_reject_cb,
472                                          NULL);
473         break;
474     case SSL_TEST_VERIFY_NONE:
475         break;
476     }
477
478     /*
479      * Link the two contexts for SNI purposes.
480      * Also do early callbacks here, as setting both early and SNI is bad.
481      */
482     switch (extra->server.servername_callback) {
483     case SSL_TEST_SERVERNAME_IGNORE_MISMATCH:
484         SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_ignore_cb);
485         SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx);
486         break;
487     case SSL_TEST_SERVERNAME_REJECT_MISMATCH:
488         SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_reject_cb);
489         SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx);
490         break;
491     case SSL_TEST_SERVERNAME_CB_NONE:
492         break;
493     case SSL_TEST_SERVERNAME_EARLY_IGNORE_MISMATCH:
494         SSL_CTX_set_early_cb(server_ctx, early_ignore_cb, server2_ctx);
495         break;
496     case SSL_TEST_SERVERNAME_EARLY_REJECT_MISMATCH:
497         SSL_CTX_set_early_cb(server_ctx, early_reject_cb, server2_ctx);
498         break;
499     case SSL_TEST_SERVERNAME_EARLY_NO_V12:
500         SSL_CTX_set_early_cb(server_ctx, early_nov12_cb, server2_ctx);
501     }
502
503     if (extra->server.cert_status != SSL_TEST_CERT_STATUS_NONE) {
504         SSL_CTX_set_tlsext_status_type(client_ctx, TLSEXT_STATUSTYPE_ocsp);
505         SSL_CTX_set_tlsext_status_cb(client_ctx, client_ocsp_cb);
506         SSL_CTX_set_tlsext_status_arg(client_ctx, NULL);
507         SSL_CTX_set_tlsext_status_cb(server_ctx, server_ocsp_cb);
508         SSL_CTX_set_tlsext_status_arg(server_ctx,
509             ((extra->server.cert_status == SSL_TEST_CERT_STATUS_GOOD_RESPONSE)
510             ? &dummy_ocsp_resp_good_val : &dummy_ocsp_resp_bad_val));
511     }
512
513     /*
514      * The initial_ctx/session_ctx always handles the encrypt/decrypt of the
515      * session ticket. This ticket_key callback is assigned to the second
516      * session (assigned via SNI), and should never be invoked
517      */
518     if (server2_ctx != NULL)
519         SSL_CTX_set_tlsext_ticket_key_cb(server2_ctx,
520                                          do_not_call_session_ticket_cb);
521
522     if (extra->server.broken_session_ticket) {
523         SSL_CTX_set_tlsext_ticket_key_cb(server_ctx, broken_session_ticket_cb);
524     }
525 #ifndef OPENSSL_NO_NEXTPROTONEG
526     if (extra->server.npn_protocols != NULL) {
527         parse_protos(extra->server.npn_protocols,
528                      &server_ctx_data->npn_protocols,
529                      &server_ctx_data->npn_protocols_len);
530         SSL_CTX_set_npn_advertised_cb(server_ctx, server_npn_cb,
531                                       server_ctx_data);
532     }
533     if (extra->server2.npn_protocols != NULL) {
534         parse_protos(extra->server2.npn_protocols,
535                      &server2_ctx_data->npn_protocols,
536                      &server2_ctx_data->npn_protocols_len);
537         TEST_check(server2_ctx != NULL);
538         SSL_CTX_set_npn_advertised_cb(server2_ctx, server_npn_cb,
539                                       server2_ctx_data);
540     }
541     if (extra->client.npn_protocols != NULL) {
542         parse_protos(extra->client.npn_protocols,
543                      &client_ctx_data->npn_protocols,
544                      &client_ctx_data->npn_protocols_len);
545         SSL_CTX_set_next_proto_select_cb(client_ctx, client_npn_cb,
546                                          client_ctx_data);
547     }
548 #endif
549     if (extra->server.alpn_protocols != NULL) {
550         parse_protos(extra->server.alpn_protocols,
551                      &server_ctx_data->alpn_protocols,
552                      &server_ctx_data->alpn_protocols_len);
553         SSL_CTX_set_alpn_select_cb(server_ctx, server_alpn_cb, server_ctx_data);
554     }
555     if (extra->server2.alpn_protocols != NULL) {
556         TEST_check(server2_ctx != NULL);
557         parse_protos(extra->server2.alpn_protocols,
558                      &server2_ctx_data->alpn_protocols,
559                      &server2_ctx_data->alpn_protocols_len);
560         SSL_CTX_set_alpn_select_cb(server2_ctx, server_alpn_cb, server2_ctx_data);
561     }
562     if (extra->client.alpn_protocols != NULL) {
563         unsigned char *alpn_protos = NULL;
564         size_t alpn_protos_len;
565         parse_protos(extra->client.alpn_protocols,
566                      &alpn_protos, &alpn_protos_len);
567         /* Reversed return value convention... */
568         TEST_check(SSL_CTX_set_alpn_protos(client_ctx, alpn_protos,
569                                            alpn_protos_len) == 0);
570         OPENSSL_free(alpn_protos);
571     }
572
573     /*
574      * Use fixed session ticket keys so that we can decrypt a ticket created with
575      * one CTX in another CTX. Don't address server2 for the moment.
576      */
577     ticket_key_len = SSL_CTX_set_tlsext_ticket_keys(server_ctx, NULL, 0);
578     ticket_keys = OPENSSL_zalloc(ticket_key_len);
579     TEST_check(ticket_keys != NULL);
580     TEST_check(SSL_CTX_set_tlsext_ticket_keys(server_ctx, ticket_keys,
581                                               ticket_key_len) == 1);
582     OPENSSL_free(ticket_keys);
583
584     /* The default log list includes EC keys, so CT can't work without EC. */
585 #if !defined(OPENSSL_NO_CT) && !defined(OPENSSL_NO_EC)
586     TEST_check(SSL_CTX_set_default_ctlog_list_file(client_ctx));
587     switch (extra->client.ct_validation) {
588     case SSL_TEST_CT_VALIDATION_PERMISSIVE:
589         TEST_check(SSL_CTX_enable_ct(client_ctx, SSL_CT_VALIDATION_PERMISSIVE));
590         break;
591     case SSL_TEST_CT_VALIDATION_STRICT:
592         TEST_check(SSL_CTX_enable_ct(client_ctx, SSL_CT_VALIDATION_STRICT));
593         break;
594     case SSL_TEST_CT_VALIDATION_NONE:
595         break;
596     }
597 #endif
598 #ifndef OPENSSL_NO_SRP
599     if (extra->server.srp_user != NULL) {
600         SSL_CTX_set_srp_username_callback(server_ctx, server_srp_cb);
601         server_ctx_data->srp_user = OPENSSL_strdup(extra->server.srp_user);
602         server_ctx_data->srp_password = OPENSSL_strdup(extra->server.srp_password);
603         SSL_CTX_set_srp_cb_arg(server_ctx, server_ctx_data);
604     }
605     if (extra->server2.srp_user != NULL) {
606         TEST_check(server2_ctx != NULL);
607         SSL_CTX_set_srp_username_callback(server2_ctx, server_srp_cb);
608         server2_ctx_data->srp_user = OPENSSL_strdup(extra->server2.srp_user);
609         server2_ctx_data->srp_password = OPENSSL_strdup(extra->server2.srp_password);
610         SSL_CTX_set_srp_cb_arg(server2_ctx, server2_ctx_data);
611     }
612     if (extra->client.srp_user != NULL) {
613         TEST_check(SSL_CTX_set_srp_username(client_ctx, extra->client.srp_user));
614         SSL_CTX_set_srp_client_pwd_callback(client_ctx, client_srp_cb);
615         client_ctx_data->srp_password = OPENSSL_strdup(extra->client.srp_password);
616         SSL_CTX_set_srp_cb_arg(client_ctx, client_ctx_data);
617     }
618 #endif  /* !OPENSSL_NO_SRP */
619 }
620
621 /* Configure per-SSL callbacks and other properties. */
622 static void configure_handshake_ssl(SSL *server, SSL *client,
623                                     const SSL_TEST_EXTRA_CONF *extra)
624 {
625     if (extra->client.servername != SSL_TEST_SERVERNAME_NONE)
626         SSL_set_tlsext_host_name(client,
627                                  ssl_servername_name(extra->client.servername));
628 }
629
630 /* The status for each connection phase. */
631 typedef enum {
632     PEER_SUCCESS,
633     PEER_RETRY,
634     PEER_ERROR
635 } peer_status_t;
636
637 /* An SSL object and associated read-write buffers. */
638 typedef struct peer_st {
639     SSL *ssl;
640     /* Buffer lengths are int to match the SSL read/write API. */
641     unsigned char *write_buf;
642     int write_buf_len;
643     unsigned char *read_buf;
644     int read_buf_len;
645     int bytes_to_write;
646     int bytes_to_read;
647     peer_status_t status;
648 } PEER;
649
650 static void create_peer(PEER *peer, SSL_CTX *ctx)
651 {
652     static const int peer_buffer_size = 64 * 1024;
653
654     peer->ssl = SSL_new(ctx);
655     TEST_check(peer->ssl != NULL);
656     peer->write_buf = OPENSSL_zalloc(peer_buffer_size);
657     TEST_check(peer->write_buf != NULL);
658     peer->read_buf = OPENSSL_zalloc(peer_buffer_size);
659     TEST_check(peer->read_buf != NULL);
660     peer->write_buf_len = peer->read_buf_len = peer_buffer_size;
661 }
662
663 static void peer_free_data(PEER *peer)
664 {
665     SSL_free(peer->ssl);
666     OPENSSL_free(peer->write_buf);
667     OPENSSL_free(peer->read_buf);
668 }
669
670 /*
671  * Note that we could do the handshake transparently under an SSL_write,
672  * but separating the steps is more helpful for debugging test failures.
673  */
674 static void do_handshake_step(PEER *peer)
675 {
676     int ret;
677
678     TEST_check(peer->status == PEER_RETRY);
679     ret = SSL_do_handshake(peer->ssl);
680
681     if (ret == 1) {
682         peer->status = PEER_SUCCESS;
683     } else if (ret == 0) {
684         peer->status = PEER_ERROR;
685     } else {
686         int error = SSL_get_error(peer->ssl, ret);
687         /* Memory bios should never block with SSL_ERROR_WANT_WRITE. */
688         if (error != SSL_ERROR_WANT_READ)
689             peer->status = PEER_ERROR;
690     }
691 }
692
693 /*-
694  * Send/receive some application data. The read-write sequence is
695  * Peer A: (R) W - first read will yield no data
696  * Peer B:  R  W
697  * ...
698  * Peer A:  R  W
699  * Peer B:  R  W
700  * Peer A:  R
701  */
702 static void do_app_data_step(PEER *peer)
703 {
704     int ret = 1, write_bytes;
705
706     TEST_check(peer->status == PEER_RETRY);
707
708     /* We read everything available... */
709     while (ret > 0 && peer->bytes_to_read) {
710         ret = SSL_read(peer->ssl, peer->read_buf, peer->read_buf_len);
711         if (ret > 0) {
712             TEST_check(ret <= peer->bytes_to_read);
713             peer->bytes_to_read -= ret;
714         } else if (ret == 0) {
715             peer->status = PEER_ERROR;
716             return;
717         } else {
718             int error = SSL_get_error(peer->ssl, ret);
719             if (error != SSL_ERROR_WANT_READ) {
720                 peer->status = PEER_ERROR;
721                 return;
722             } /* Else continue with write. */
723         }
724     }
725
726     /* ... but we only write one write-buffer-full of data. */
727     write_bytes = peer->bytes_to_write < peer->write_buf_len ? peer->bytes_to_write :
728         peer->write_buf_len;
729     if (write_bytes) {
730         ret = SSL_write(peer->ssl, peer->write_buf, write_bytes);
731         if (ret > 0) {
732             /* SSL_write will only succeed with a complete write. */
733             TEST_check(ret == write_bytes);
734             peer->bytes_to_write -= ret;
735         } else {
736             /*
737              * We should perhaps check for SSL_ERROR_WANT_READ/WRITE here
738              * but this doesn't yet occur with current app data sizes.
739              */
740             peer->status = PEER_ERROR;
741             return;
742         }
743     }
744
745     /*
746      * We could simply finish when there was nothing to read, and we have
747      * nothing left to write. But keeping track of the expected number of bytes
748      * to read gives us somewhat better guarantees that all data sent is in fact
749      * received.
750      */
751     if (!peer->bytes_to_write && !peer->bytes_to_read) {
752         peer->status = PEER_SUCCESS;
753     }
754 }
755
756 static void do_reneg_setup_step(const SSL_TEST_CTX *test_ctx, PEER *peer)
757 {
758     int ret;
759     char buf;
760
761     TEST_check(peer->status == PEER_RETRY);
762     TEST_check(test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_SERVER
763                 || test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_CLIENT
764                 || test_ctx->handshake_mode
765                    == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER
766                 || test_ctx->handshake_mode
767                    == SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT);
768
769     /* Reset the count of the amount of app data we need to read/write */
770     peer->bytes_to_write = peer->bytes_to_read = test_ctx->app_data_size;
771
772     /* Check if we are the peer that is going to initiate */
773     if ((test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_SERVER
774                 && SSL_is_server(peer->ssl))
775             || (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_CLIENT
776                 && !SSL_is_server(peer->ssl))) {
777         /*
778          * If we already asked for a renegotiation then fall through to the
779          * SSL_read() below.
780          */
781         if (!SSL_renegotiate_pending(peer->ssl)) {
782             /*
783              * If we are the client we will always attempt to resume the
784              * session. The server may or may not resume dependant on the
785              * setting of SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
786              */
787             if (SSL_is_server(peer->ssl)) {
788                 ret = SSL_renegotiate(peer->ssl);
789             } else {
790                 if (test_ctx->extra.client.reneg_ciphers != NULL) {
791                     if (!SSL_set_cipher_list(peer->ssl,
792                                 test_ctx->extra.client.reneg_ciphers)) {
793                         peer->status = PEER_ERROR;
794                         return;
795                     }
796                     ret = SSL_renegotiate(peer->ssl);
797                 } else {
798                     ret = SSL_renegotiate_abbreviated(peer->ssl);
799                 }
800             }
801             if (!ret) {
802                 peer->status = PEER_ERROR;
803                 return;
804             }
805             do_handshake_step(peer);
806             /*
807              * If status is PEER_RETRY it means we're waiting on the peer to
808              * continue the handshake. As far as setting up the renegotiation is
809              * concerned that is a success. The next step will continue the
810              * handshake to its conclusion.
811              *
812              * If status is PEER_SUCCESS then we are the server and we have
813              * successfully sent the HelloRequest. We need to continue to wait
814              * until the handshake arrives from the client.
815              */
816             if (peer->status == PEER_RETRY)
817                 peer->status = PEER_SUCCESS;
818             else if (peer->status == PEER_SUCCESS)
819                 peer->status = PEER_RETRY;
820             return;
821         }
822     } else if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER
823                || test_ctx->handshake_mode
824                   == SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT) {
825         if (SSL_is_server(peer->ssl)
826                 != (test_ctx->handshake_mode
827                     == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER)) {
828             peer->status = PEER_SUCCESS;
829             return;
830         }
831
832         ret = SSL_key_update(peer->ssl, test_ctx->key_update_type);
833         if (!ret) {
834             peer->status = PEER_ERROR;
835             return;
836         }
837         do_handshake_step(peer);
838         /*
839          * This is a one step handshake. We shouldn't get anything other than
840          * PEER_SUCCESS
841          */
842         if (peer->status != PEER_SUCCESS)
843             peer->status = PEER_ERROR;
844         return;
845     }
846
847     /*
848      * The SSL object is still expecting app data, even though it's going to
849      * get a handshake message. We try to read, and it should fail - after which
850      * we should be in a handshake
851      */
852     ret = SSL_read(peer->ssl, &buf, sizeof(buf));
853     if (ret >= 0) {
854         /*
855          * We're not actually expecting data - we're expecting a reneg to
856          * start
857          */
858         peer->status = PEER_ERROR;
859         return;
860     } else {
861         int error = SSL_get_error(peer->ssl, ret);
862         if (error != SSL_ERROR_WANT_READ) {
863             peer->status = PEER_ERROR;
864             return;
865         }
866         /* If we're not in init yet then we're not done with setup yet */
867         if (!SSL_in_init(peer->ssl))
868             return;
869     }
870
871     peer->status = PEER_SUCCESS;
872 }
873
874
875 /*
876  * RFC 5246 says:
877  *
878  * Note that as of TLS 1.1,
879  *     failure to properly close a connection no longer requires that a
880  *     session not be resumed.  This is a change from TLS 1.0 to conform
881  *     with widespread implementation practice.
882  *
883  * However,
884  * (a) OpenSSL requires that a connection be shutdown for all protocol versions.
885  * (b) We test lower versions, too.
886  * So we just implement shutdown. We do a full bidirectional shutdown so that we
887  * can compare sent and received close_notify alerts and get some test coverage
888  * for SSL_shutdown as a bonus.
889  */
890 static void do_shutdown_step(PEER *peer)
891 {
892     int ret;
893
894     TEST_check(peer->status == PEER_RETRY);
895     ret = SSL_shutdown(peer->ssl);
896
897     if (ret == 1) {
898         peer->status = PEER_SUCCESS;
899     } else if (ret < 0) { /* On 0, we retry. */
900         int error = SSL_get_error(peer->ssl, ret);
901         /* Memory bios should never block with SSL_ERROR_WANT_WRITE. */
902         if (error != SSL_ERROR_WANT_READ)
903             peer->status = PEER_ERROR;
904     }
905 }
906
907 typedef enum {
908     HANDSHAKE,
909     RENEG_APPLICATION_DATA,
910     RENEG_SETUP,
911     RENEG_HANDSHAKE,
912     APPLICATION_DATA,
913     SHUTDOWN,
914     CONNECTION_DONE
915 } connect_phase_t;
916
917 static connect_phase_t next_phase(const SSL_TEST_CTX *test_ctx,
918                                   connect_phase_t phase)
919 {
920     switch (phase) {
921     case HANDSHAKE:
922         if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_SERVER
923                 || test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_CLIENT
924                 || test_ctx->handshake_mode
925                    == SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT
926                 || test_ctx->handshake_mode
927                    == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER)
928             return RENEG_APPLICATION_DATA;
929         return APPLICATION_DATA;
930     case RENEG_APPLICATION_DATA:
931         return RENEG_SETUP;
932     case RENEG_SETUP:
933         if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER
934                 || test_ctx->handshake_mode
935                    == SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT)
936             return APPLICATION_DATA;
937         return RENEG_HANDSHAKE;
938     case RENEG_HANDSHAKE:
939         return APPLICATION_DATA;
940     case APPLICATION_DATA:
941         return SHUTDOWN;
942     case SHUTDOWN:
943         return CONNECTION_DONE;
944     case CONNECTION_DONE:
945         TEST_check(0);
946         break;
947     }
948     return -1;
949 }
950
951 static void do_connect_step(const SSL_TEST_CTX *test_ctx, PEER *peer,
952                             connect_phase_t phase)
953 {
954     switch (phase) {
955     case HANDSHAKE:
956         do_handshake_step(peer);
957         break;
958     case RENEG_APPLICATION_DATA:
959         do_app_data_step(peer);
960         break;
961     case RENEG_SETUP:
962         do_reneg_setup_step(test_ctx, peer);
963         break;
964     case RENEG_HANDSHAKE:
965         do_handshake_step(peer);
966         break;
967     case APPLICATION_DATA:
968         do_app_data_step(peer);
969         break;
970     case SHUTDOWN:
971         do_shutdown_step(peer);
972         break;
973     case CONNECTION_DONE:
974         TEST_check(0);
975         break;
976     }
977 }
978
979 typedef enum {
980     /* Both parties succeeded. */
981     HANDSHAKE_SUCCESS,
982     /* Client errored. */
983     CLIENT_ERROR,
984     /* Server errored. */
985     SERVER_ERROR,
986     /* Peers are in inconsistent state. */
987     INTERNAL_ERROR,
988     /* One or both peers not done. */
989     HANDSHAKE_RETRY
990 } handshake_status_t;
991
992 /*
993  * Determine the handshake outcome.
994  * last_status: the status of the peer to have acted last.
995  * previous_status: the status of the peer that didn't act last.
996  * client_spoke_last: 1 if the client went last.
997  */
998 static handshake_status_t handshake_status(peer_status_t last_status,
999                                            peer_status_t previous_status,
1000                                            int client_spoke_last)
1001 {
1002     switch (last_status) {
1003     case PEER_SUCCESS:
1004         switch (previous_status) {
1005         case PEER_SUCCESS:
1006             /* Both succeeded. */
1007             return HANDSHAKE_SUCCESS;
1008         case PEER_RETRY:
1009             /* Let the first peer finish. */
1010             return HANDSHAKE_RETRY;
1011         case PEER_ERROR:
1012             /*
1013              * Second peer succeeded despite the fact that the first peer
1014              * already errored. This shouldn't happen.
1015              */
1016             return INTERNAL_ERROR;
1017         }
1018
1019     case PEER_RETRY:
1020         if (previous_status == PEER_RETRY) {
1021             /* Neither peer is done. */
1022             return HANDSHAKE_RETRY;
1023         } else {
1024             /*
1025              * Deadlock: second peer is waiting for more input while first
1026              * peer thinks they're done (no more input is coming).
1027              */
1028             return INTERNAL_ERROR;
1029         }
1030     case PEER_ERROR:
1031         switch (previous_status) {
1032         case PEER_SUCCESS:
1033             /*
1034              * First peer succeeded but second peer errored.
1035              * TODO(emilia): we should be able to continue here (with some
1036              * application data?) to ensure the first peer receives the
1037              * alert / close_notify.
1038              * (No tests currently exercise this branch.)
1039              */
1040             return client_spoke_last ? CLIENT_ERROR : SERVER_ERROR;
1041         case PEER_RETRY:
1042             /* We errored; let the peer finish. */
1043             return HANDSHAKE_RETRY;
1044         case PEER_ERROR:
1045             /* Both peers errored. Return the one that errored first. */
1046             return client_spoke_last ? SERVER_ERROR : CLIENT_ERROR;
1047         }
1048     }
1049     /* Control should never reach here. */
1050     return INTERNAL_ERROR;
1051 }
1052
1053 /* Convert unsigned char buf's that shouldn't contain any NUL-bytes to char. */
1054 static char *dup_str(const unsigned char *in, size_t len)
1055 {
1056     char *ret;
1057
1058     if (len == 0)
1059         return NULL;
1060
1061     /* Assert that the string does not contain NUL-bytes. */
1062     TEST_check(OPENSSL_strnlen((const char*)(in), len) == len);
1063     ret = OPENSSL_strndup((const char*)(in), len);
1064     TEST_check(ret != NULL);
1065     return ret;
1066 }
1067
1068 static int pkey_type(EVP_PKEY *pkey)
1069 {
1070     int nid = EVP_PKEY_id(pkey);
1071
1072 #ifndef OPENSSL_NO_EC
1073     if (nid == EVP_PKEY_EC) {
1074         const EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
1075         return EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
1076     }
1077 #endif
1078     return nid;
1079 }
1080
1081 static int peer_pkey_type(SSL *s)
1082 {
1083     X509 *x = SSL_get_peer_certificate(s);
1084
1085     if (x != NULL) {
1086         int nid = pkey_type(X509_get0_pubkey(x));
1087
1088         X509_free(x);
1089         return nid;
1090     }
1091     return NID_undef;
1092 }
1093
1094 /*
1095  * Note that |extra| points to the correct client/server configuration
1096  * within |test_ctx|. When configuring the handshake, general mode settings
1097  * are taken from |test_ctx|, and client/server-specific settings should be
1098  * taken from |extra|.
1099  *
1100  * The configuration code should never reach into |test_ctx->extra| or
1101  * |test_ctx->resume_extra| directly.
1102  *
1103  * (We could refactor test mode settings into a substructure. This would result
1104  * in cleaner argument passing but would complicate the test configuration
1105  * parsing.)
1106  */
1107 static HANDSHAKE_RESULT *do_handshake_internal(
1108     SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx,
1109     const SSL_TEST_CTX *test_ctx, const SSL_TEST_EXTRA_CONF *extra,
1110     SSL_SESSION *session_in, SSL_SESSION **session_out)
1111 {
1112     PEER server, client;
1113     BIO *client_to_server, *server_to_client;
1114     HANDSHAKE_EX_DATA server_ex_data, client_ex_data;
1115     CTX_DATA client_ctx_data, server_ctx_data, server2_ctx_data;
1116     HANDSHAKE_RESULT *ret = HANDSHAKE_RESULT_new();
1117     int client_turn = 1, client_turn_count = 0;
1118     connect_phase_t phase = HANDSHAKE;
1119     handshake_status_t status = HANDSHAKE_RETRY;
1120     const unsigned char* tick = NULL;
1121     size_t tick_len = 0;
1122     SSL_SESSION* sess = NULL;
1123     const unsigned char *proto = NULL;
1124     /* API dictates unsigned int rather than size_t. */
1125     unsigned int proto_len = 0;
1126     EVP_PKEY *tmp_key;
1127     const STACK_OF(X509_NAME) *names;
1128
1129     memset(&server_ctx_data, 0, sizeof(server_ctx_data));
1130     memset(&server2_ctx_data, 0, sizeof(server2_ctx_data));
1131     memset(&client_ctx_data, 0, sizeof(client_ctx_data));
1132     memset(&server, 0, sizeof(server));
1133     memset(&client, 0, sizeof(client));
1134
1135     configure_handshake_ctx(server_ctx, server2_ctx, client_ctx, test_ctx, extra,
1136                             &server_ctx_data, &server2_ctx_data, &client_ctx_data);
1137
1138     /* Setup SSL and buffers; additional configuration happens below. */
1139     create_peer(&server, server_ctx);
1140     create_peer(&client, client_ctx);
1141
1142     server.bytes_to_write = client.bytes_to_read = test_ctx->app_data_size;
1143     client.bytes_to_write = server.bytes_to_read = test_ctx->app_data_size;
1144
1145     configure_handshake_ssl(server.ssl, client.ssl, extra);
1146     if (session_in != NULL) {
1147         /* In case we're testing resumption without tickets. */
1148         TEST_check(SSL_CTX_add_session(server_ctx, session_in));
1149         TEST_check(SSL_set_session(client.ssl, session_in));
1150     }
1151
1152     memset(&server_ex_data, 0, sizeof(server_ex_data));
1153     memset(&client_ex_data, 0, sizeof(client_ex_data));
1154
1155     ret->result = SSL_TEST_INTERNAL_ERROR;
1156
1157     client_to_server = BIO_new(BIO_s_mem());
1158     server_to_client = BIO_new(BIO_s_mem());
1159
1160     TEST_check(client_to_server != NULL);
1161     TEST_check(server_to_client != NULL);
1162
1163     /* Non-blocking bio. */
1164     BIO_set_nbio(client_to_server, 1);
1165     BIO_set_nbio(server_to_client, 1);
1166
1167     SSL_set_connect_state(client.ssl);
1168     SSL_set_accept_state(server.ssl);
1169
1170     /* The bios are now owned by the SSL object. */
1171     SSL_set_bio(client.ssl, server_to_client, client_to_server);
1172     TEST_check(BIO_up_ref(server_to_client) > 0);
1173     TEST_check(BIO_up_ref(client_to_server) > 0);
1174     SSL_set_bio(server.ssl, client_to_server, server_to_client);
1175
1176     ex_data_idx = SSL_get_ex_new_index(0, "ex data", NULL, NULL, NULL);
1177     TEST_check(ex_data_idx >= 0);
1178
1179     TEST_check(SSL_set_ex_data(server.ssl, ex_data_idx, &server_ex_data) == 1);
1180     TEST_check(SSL_set_ex_data(client.ssl, ex_data_idx, &client_ex_data) == 1);
1181
1182     SSL_set_info_callback(server.ssl, &info_cb);
1183     SSL_set_info_callback(client.ssl, &info_cb);
1184
1185     client.status = server.status = PEER_RETRY;
1186
1187     /*
1188      * Half-duplex handshake loop.
1189      * Client and server speak to each other synchronously in the same process.
1190      * We use non-blocking BIOs, so whenever one peer blocks for read, it
1191      * returns PEER_RETRY to indicate that it's the other peer's turn to write.
1192      * The handshake succeeds once both peers have succeeded. If one peer
1193      * errors out, we also let the other peer retry (and presumably fail).
1194      */
1195     for(;;) {
1196         if (client_turn) {
1197             do_connect_step(test_ctx, &client, phase);
1198             status = handshake_status(client.status, server.status,
1199                                       1 /* client went last */);
1200         } else {
1201             do_connect_step(test_ctx, &server, phase);
1202             status = handshake_status(server.status, client.status,
1203                                       0 /* server went last */);
1204         }
1205
1206         switch (status) {
1207         case HANDSHAKE_SUCCESS:
1208             client_turn_count = 0;
1209             phase = next_phase(test_ctx, phase);
1210             if (phase == CONNECTION_DONE) {
1211                 ret->result = SSL_TEST_SUCCESS;
1212                 goto err;
1213             } else {
1214                 client.status = server.status = PEER_RETRY;
1215                 /*
1216                  * For now, client starts each phase. Since each phase is
1217                  * started separately, we can later control this more
1218                  * precisely, for example, to test client-initiated and
1219                  * server-initiated shutdown.
1220                  */
1221                 client_turn = 1;
1222                 break;
1223             }
1224         case CLIENT_ERROR:
1225             ret->result = SSL_TEST_CLIENT_FAIL;
1226             goto err;
1227         case SERVER_ERROR:
1228             ret->result = SSL_TEST_SERVER_FAIL;
1229             goto err;
1230         case INTERNAL_ERROR:
1231             ret->result = SSL_TEST_INTERNAL_ERROR;
1232             goto err;
1233         case HANDSHAKE_RETRY:
1234             if (client_turn_count++ >= 2000) {
1235                 /*
1236                  * At this point, there's been so many PEER_RETRY in a row
1237                  * that it's likely both sides are stuck waiting for a read.
1238                  * It's time to give up.
1239                  */
1240                 ret->result = SSL_TEST_INTERNAL_ERROR;
1241                 goto err;
1242             }
1243
1244             /* Continue. */
1245             client_turn ^= 1;
1246             break;
1247         }
1248     }
1249  err:
1250     ret->server_alert_sent = server_ex_data.alert_sent;
1251     ret->server_num_fatal_alerts_sent = server_ex_data.num_fatal_alerts_sent;
1252     ret->server_alert_received = client_ex_data.alert_received;
1253     ret->client_alert_sent = client_ex_data.alert_sent;
1254     ret->client_num_fatal_alerts_sent = client_ex_data.num_fatal_alerts_sent;
1255     ret->client_alert_received = server_ex_data.alert_received;
1256     ret->server_protocol = SSL_version(server.ssl);
1257     ret->client_protocol = SSL_version(client.ssl);
1258     ret->servername = server_ex_data.servername;
1259     if ((sess = SSL_get0_session(client.ssl)) != NULL)
1260         SSL_SESSION_get0_ticket(sess, &tick, &tick_len);
1261     if (tick == NULL || tick_len == 0)
1262         ret->session_ticket = SSL_TEST_SESSION_TICKET_NO;
1263     else
1264         ret->session_ticket = SSL_TEST_SESSION_TICKET_YES;
1265     ret->compression = (SSL_get_current_compression(client.ssl) == NULL)
1266                        ? SSL_TEST_COMPRESSION_NO
1267                        : SSL_TEST_COMPRESSION_YES;
1268     ret->session_ticket_do_not_call = server_ex_data.session_ticket_do_not_call;
1269
1270 #ifndef OPENSSL_NO_NEXTPROTONEG
1271     SSL_get0_next_proto_negotiated(client.ssl, &proto, &proto_len);
1272     ret->client_npn_negotiated = dup_str(proto, proto_len);
1273
1274     SSL_get0_next_proto_negotiated(server.ssl, &proto, &proto_len);
1275     ret->server_npn_negotiated = dup_str(proto, proto_len);
1276 #endif
1277
1278     SSL_get0_alpn_selected(client.ssl, &proto, &proto_len);
1279     ret->client_alpn_negotiated = dup_str(proto, proto_len);
1280
1281     SSL_get0_alpn_selected(server.ssl, &proto, &proto_len);
1282     ret->server_alpn_negotiated = dup_str(proto, proto_len);
1283
1284     ret->client_resumed = SSL_session_reused(client.ssl);
1285     ret->server_resumed = SSL_session_reused(server.ssl);
1286
1287     if (session_out != NULL)
1288         *session_out = SSL_get1_session(client.ssl);
1289
1290     if (SSL_get_server_tmp_key(client.ssl, &tmp_key)) {
1291         ret->tmp_key_type = pkey_type(tmp_key);
1292         EVP_PKEY_free(tmp_key);
1293     }
1294
1295     SSL_get_peer_signature_nid(client.ssl, &ret->server_sign_hash);
1296     SSL_get_peer_signature_nid(server.ssl, &ret->client_sign_hash);
1297
1298     SSL_get_peer_signature_type_nid(client.ssl, &ret->server_sign_type);
1299     SSL_get_peer_signature_type_nid(server.ssl, &ret->client_sign_type);
1300
1301     names = SSL_get0_peer_CA_list(client.ssl);
1302     if (names == NULL)
1303         ret->client_ca_names = NULL;
1304     else
1305         ret->client_ca_names = SSL_dup_CA_list(names);
1306
1307     names = SSL_get0_peer_CA_list(server.ssl);
1308     if (names == NULL)
1309         ret->server_ca_names = NULL;
1310     else
1311         ret->server_ca_names = SSL_dup_CA_list(names);
1312
1313     ret->server_cert_type = peer_pkey_type(client.ssl);
1314     ret->client_cert_type = peer_pkey_type(server.ssl);
1315
1316     ctx_data_free_data(&server_ctx_data);
1317     ctx_data_free_data(&server2_ctx_data);
1318     ctx_data_free_data(&client_ctx_data);
1319
1320     peer_free_data(&server);
1321     peer_free_data(&client);
1322     return ret;
1323 }
1324
1325 HANDSHAKE_RESULT *do_handshake(SSL_CTX *server_ctx, SSL_CTX *server2_ctx,
1326                                SSL_CTX *client_ctx, SSL_CTX *resume_server_ctx,
1327                                SSL_CTX *resume_client_ctx,
1328                                const SSL_TEST_CTX *test_ctx)
1329 {
1330     HANDSHAKE_RESULT *result;
1331     SSL_SESSION *session = NULL;
1332
1333     result = do_handshake_internal(server_ctx, server2_ctx, client_ctx,
1334                                    test_ctx, &test_ctx->extra,
1335                                    NULL, &session);
1336     if (test_ctx->handshake_mode != SSL_TEST_HANDSHAKE_RESUME)
1337         goto end;
1338
1339     if (result->result != SSL_TEST_SUCCESS) {
1340         result->result = SSL_TEST_FIRST_HANDSHAKE_FAILED;
1341         goto end;
1342     }
1343
1344     HANDSHAKE_RESULT_free(result);
1345     /* We don't support SNI on second handshake yet, so server2_ctx is NULL. */
1346     result = do_handshake_internal(resume_server_ctx, NULL, resume_client_ctx,
1347                                    test_ctx, &test_ctx->resume_extra,
1348                                    session, NULL);
1349  end:
1350     SSL_SESSION_free(session);
1351     return result;
1352 }