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