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