1 /*
2  * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 #include <openssl/core_names.h>
16 
17 #include "../../ssl/ssl_local.h"
18 #include "internal/sockets.h"
19 #include "internal/nelem.h"
20 #include "handshake.h"
21 #include "../testutil.h"
22 
23 #if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK)
24 #include <netinet/sctp.h>
25 #endif
26 
HANDSHAKE_RESULT_new(void)27 HANDSHAKE_RESULT *HANDSHAKE_RESULT_new(void)
28 {
29     HANDSHAKE_RESULT *ret;
30 
31     TEST_ptr(ret = OPENSSL_zalloc(sizeof(*ret)));
32     return ret;
33 }
34 
HANDSHAKE_RESULT_free(HANDSHAKE_RESULT * result)35 void HANDSHAKE_RESULT_free(HANDSHAKE_RESULT *result)
36 {
37     if (result == NULL)
38         return;
39     OPENSSL_free(result->client_npn_negotiated);
40     OPENSSL_free(result->server_npn_negotiated);
41     OPENSSL_free(result->client_alpn_negotiated);
42     OPENSSL_free(result->server_alpn_negotiated);
43     OPENSSL_free(result->result_session_ticket_app_data);
44     sk_X509_NAME_pop_free(result->server_ca_names, X509_NAME_free);
45     sk_X509_NAME_pop_free(result->client_ca_names, X509_NAME_free);
46     OPENSSL_free(result->cipher);
47     OPENSSL_free(result);
48 }
49 
50 /*
51  * Since there appears to be no way to extract the sent/received alert
52  * from the SSL object directly, we use the info callback and stash
53  * the result in ex_data.
54  */
55 typedef struct handshake_ex_data_st {
56     int alert_sent;
57     int num_fatal_alerts_sent;
58     int alert_received;
59     int session_ticket_do_not_call;
60     ssl_servername_t servername;
61 } HANDSHAKE_EX_DATA;
62 
63 /* |ctx_data| itself is stack-allocated. */
ctx_data_free_data(CTX_DATA * ctx_data)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     OPENSSL_free(ctx_data->session_ticket_app_data);
75     ctx_data->session_ticket_app_data = NULL;
76 }
77 
78 static int ex_data_idx;
79 
info_cb(const SSL * s,int where,int ret)80 static void info_cb(const SSL *s, int where, int ret)
81 {
82     if (where & SSL_CB_ALERT) {
83         HANDSHAKE_EX_DATA *ex_data =
84             (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
85         if (where & SSL_CB_WRITE) {
86             ex_data->alert_sent = ret;
87             if (strcmp(SSL_alert_type_string(ret), "F") == 0
88                 || strcmp(SSL_alert_desc_string(ret), "CN") == 0)
89                 ex_data->num_fatal_alerts_sent++;
90         } else {
91             ex_data->alert_received = ret;
92         }
93     }
94 }
95 
96 /* Select the appropriate server CTX.
97  * Returns SSL_TLSEXT_ERR_OK if a match was found.
98  * If |ignore| is 1, returns SSL_TLSEXT_ERR_NOACK on mismatch.
99  * Otherwise, returns SSL_TLSEXT_ERR_ALERT_FATAL on mismatch.
100  * An empty SNI extension also returns SSL_TSLEXT_ERR_NOACK.
101  */
select_server_ctx(SSL * s,void * arg,int ignore)102 static int select_server_ctx(SSL *s, void *arg, int ignore)
103 {
104     const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
105     HANDSHAKE_EX_DATA *ex_data =
106         (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
107 
108     if (servername == NULL) {
109         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
110         return SSL_TLSEXT_ERR_NOACK;
111     }
112 
113     if (strcmp(servername, "server2") == 0) {
114         SSL_CTX *new_ctx = (SSL_CTX*)arg;
115         SSL_set_SSL_CTX(s, new_ctx);
116         /*
117          * Copy over all the SSL_CTX options - reasonable behavior
118          * allows testing of cases where the options between two
119          * contexts differ/conflict
120          */
121         SSL_clear_options(s, 0xFFFFFFFFL);
122         SSL_set_options(s, SSL_CTX_get_options(new_ctx));
123 
124         ex_data->servername = SSL_TEST_SERVERNAME_SERVER2;
125         return SSL_TLSEXT_ERR_OK;
126     } else if (strcmp(servername, "server1") == 0) {
127         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
128         return SSL_TLSEXT_ERR_OK;
129     } else if (ignore) {
130         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
131         return SSL_TLSEXT_ERR_NOACK;
132     } else {
133         /* Don't set an explicit alert, to test library defaults. */
134         return SSL_TLSEXT_ERR_ALERT_FATAL;
135     }
136 }
137 
client_hello_select_server_ctx(SSL * s,void * arg,int ignore)138 static int client_hello_select_server_ctx(SSL *s, void *arg, int ignore)
139 {
140     const char *servername;
141     const unsigned char *p;
142     size_t len, remaining;
143     HANDSHAKE_EX_DATA *ex_data =
144         (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
145 
146     /*
147      * The server_name extension was given too much extensibility when it
148      * was written, so parsing the normal case is a bit complex.
149      */
150     if (!SSL_client_hello_get0_ext(s, TLSEXT_TYPE_server_name, &p,
151                                    &remaining) ||
152         remaining <= 2)
153         return 0;
154     /* Extract the length of the supplied list of names. */
155     len = (*(p++) << 8);
156     len += *(p++);
157     if (len + 2 != remaining)
158         return 0;
159     remaining = len;
160     /*
161      * The list in practice only has a single element, so we only consider
162      * the first one.
163      */
164     if (remaining == 0 || *p++ != TLSEXT_NAMETYPE_host_name)
165         return 0;
166     remaining--;
167     /* Now we can finally pull out the byte array with the actual hostname. */
168     if (remaining <= 2)
169         return 0;
170     len = (*(p++) << 8);
171     len += *(p++);
172     if (len + 2 > remaining)
173         return 0;
174     remaining = len;
175     servername = (const char *)p;
176 
177     if (len == strlen("server2") && strncmp(servername, "server2", len) == 0) {
178         SSL_CTX *new_ctx = arg;
179         SSL_set_SSL_CTX(s, new_ctx);
180         /*
181          * Copy over all the SSL_CTX options - reasonable behavior
182          * allows testing of cases where the options between two
183          * contexts differ/conflict
184          */
185         SSL_clear_options(s, 0xFFFFFFFFL);
186         SSL_set_options(s, SSL_CTX_get_options(new_ctx));
187 
188         ex_data->servername = SSL_TEST_SERVERNAME_SERVER2;
189         return 1;
190     } else if (len == strlen("server1") &&
191                strncmp(servername, "server1", len) == 0) {
192         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
193         return 1;
194     } else if (ignore) {
195         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
196         return 1;
197     }
198     return 0;
199 }
200 /*
201  * (RFC 6066):
202  *  If the server understood the ClientHello extension but
203  *  does not recognize the server name, the server SHOULD take one of two
204  *  actions: either abort the handshake by sending a fatal-level
205  *  unrecognized_name(112) alert or continue the handshake.
206  *
207  * This behaviour is up to the application to configure; we test both
208  * configurations to ensure the state machine propagates the result
209  * correctly.
210  */
servername_ignore_cb(SSL * s,int * ad,void * arg)211 static int servername_ignore_cb(SSL *s, int *ad, void *arg)
212 {
213     return select_server_ctx(s, arg, 1);
214 }
215 
servername_reject_cb(SSL * s,int * ad,void * arg)216 static int servername_reject_cb(SSL *s, int *ad, void *arg)
217 {
218     return select_server_ctx(s, arg, 0);
219 }
220 
client_hello_ignore_cb(SSL * s,int * al,void * arg)221 static int client_hello_ignore_cb(SSL *s, int *al, void *arg)
222 {
223     if (!client_hello_select_server_ctx(s, arg, 1)) {
224         *al = SSL_AD_UNRECOGNIZED_NAME;
225         return SSL_CLIENT_HELLO_ERROR;
226     }
227     return SSL_CLIENT_HELLO_SUCCESS;
228 }
229 
client_hello_reject_cb(SSL * s,int * al,void * arg)230 static int client_hello_reject_cb(SSL *s, int *al, void *arg)
231 {
232     if (!client_hello_select_server_ctx(s, arg, 0)) {
233         *al = SSL_AD_UNRECOGNIZED_NAME;
234         return SSL_CLIENT_HELLO_ERROR;
235     }
236     return SSL_CLIENT_HELLO_SUCCESS;
237 }
238 
client_hello_nov12_cb(SSL * s,int * al,void * arg)239 static int client_hello_nov12_cb(SSL *s, int *al, void *arg)
240 {
241     int ret;
242     unsigned int v;
243     const unsigned char *p;
244 
245     v = SSL_client_hello_get0_legacy_version(s);
246     if (v > TLS1_2_VERSION || v < SSL3_VERSION) {
247         *al = SSL_AD_PROTOCOL_VERSION;
248         return SSL_CLIENT_HELLO_ERROR;
249     }
250     (void)SSL_client_hello_get0_session_id(s, &p);
251     if (p == NULL ||
252         SSL_client_hello_get0_random(s, &p) == 0 ||
253         SSL_client_hello_get0_ciphers(s, &p) == 0 ||
254         SSL_client_hello_get0_compression_methods(s, &p) == 0) {
255         *al = SSL_AD_INTERNAL_ERROR;
256         return SSL_CLIENT_HELLO_ERROR;
257     }
258     ret = client_hello_select_server_ctx(s, arg, 0);
259     SSL_set_max_proto_version(s, TLS1_1_VERSION);
260     if (!ret) {
261         *al = SSL_AD_UNRECOGNIZED_NAME;
262         return SSL_CLIENT_HELLO_ERROR;
263     }
264     return SSL_CLIENT_HELLO_SUCCESS;
265 }
266 
267 static unsigned char dummy_ocsp_resp_good_val = 0xff;
268 static unsigned char dummy_ocsp_resp_bad_val = 0xfe;
269 
server_ocsp_cb(SSL * s,void * arg)270 static int server_ocsp_cb(SSL *s, void *arg)
271 {
272     unsigned char *resp;
273 
274     resp = OPENSSL_malloc(1);
275     if (resp == NULL)
276         return SSL_TLSEXT_ERR_ALERT_FATAL;
277     /*
278      * For the purposes of testing we just send back a dummy OCSP response
279      */
280     *resp = *(unsigned char *)arg;
281     if (!SSL_set_tlsext_status_ocsp_resp(s, resp, 1)) {
282         OPENSSL_free(resp);
283         return SSL_TLSEXT_ERR_ALERT_FATAL;
284     }
285 
286     return SSL_TLSEXT_ERR_OK;
287 }
288 
client_ocsp_cb(SSL * s,void * arg)289 static int client_ocsp_cb(SSL *s, void *arg)
290 {
291     const unsigned char *resp;
292     int len;
293 
294     len = SSL_get_tlsext_status_ocsp_resp(s, &resp);
295     if (len != 1 || *resp != dummy_ocsp_resp_good_val)
296         return 0;
297 
298     return 1;
299 }
300 
verify_reject_cb(X509_STORE_CTX * ctx,void * arg)301 static int verify_reject_cb(X509_STORE_CTX *ctx, void *arg) {
302     X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
303     return 0;
304 }
305 
306 static int n_retries = 0;
verify_retry_cb(X509_STORE_CTX * ctx,void * arg)307 static int verify_retry_cb(X509_STORE_CTX *ctx, void *arg) {
308     if (--n_retries < 0)
309         return 1;
310     X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
311     return -1;
312 }
313 
verify_accept_cb(X509_STORE_CTX * ctx,void * arg)314 static int verify_accept_cb(X509_STORE_CTX *ctx, void *arg) {
315     return 1;
316 }
317 
broken_session_ticket_cb(SSL * s,unsigned char * key_name,unsigned char * iv,EVP_CIPHER_CTX * ctx,EVP_MAC_CTX * hctx,int enc)318 static int broken_session_ticket_cb(SSL *s, unsigned char *key_name,
319                                     unsigned char *iv, EVP_CIPHER_CTX *ctx,
320                                     EVP_MAC_CTX *hctx, int enc)
321 {
322     return 0;
323 }
324 
do_not_call_session_ticket_cb(SSL * s,unsigned char * key_name,unsigned char * iv,EVP_CIPHER_CTX * ctx,EVP_MAC_CTX * hctx,int enc)325 static int do_not_call_session_ticket_cb(SSL *s, unsigned char *key_name,
326                                          unsigned char *iv,
327                                          EVP_CIPHER_CTX *ctx,
328                                          EVP_MAC_CTX *hctx, int enc)
329 {
330     HANDSHAKE_EX_DATA *ex_data =
331         (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
332     ex_data->session_ticket_do_not_call = 1;
333     return 0;
334 }
335 
336 /* Parse the comma-separated list into TLS format. */
parse_protos(const char * protos,unsigned char ** out,size_t * outlen)337 static int parse_protos(const char *protos, unsigned char **out, size_t *outlen)
338 {
339     size_t len, i, prefix;
340 
341     len = strlen(protos);
342 
343     /* Should never have reuse. */
344     if (!TEST_ptr_null(*out)
345             /* Test values are small, so we omit length limit checks. */
346             || !TEST_ptr(*out = OPENSSL_malloc(len + 1)))
347         return 0;
348     *outlen = len + 1;
349 
350     /*
351      * foo => '3', 'f', 'o', 'o'
352      * foo,bar => '3', 'f', 'o', 'o', '3', 'b', 'a', 'r'
353      */
354     memcpy(*out + 1, protos, len);
355 
356     prefix = 0;
357     i = prefix + 1;
358     while (i <= len) {
359         if ((*out)[i] == ',') {
360             if (!TEST_int_gt(i - 1, prefix))
361                 goto err;
362             (*out)[prefix] = (unsigned char)(i - 1 - prefix);
363             prefix = i;
364         }
365         i++;
366     }
367     if (!TEST_int_gt(len, prefix))
368         goto err;
369     (*out)[prefix] = (unsigned char)(len - prefix);
370     return 1;
371 
372 err:
373     OPENSSL_free(*out);
374     *out = NULL;
375     return 0;
376 }
377 
378 #ifndef OPENSSL_NO_NEXTPROTONEG
379 /*
380  * The client SHOULD select the first protocol advertised by the server that it
381  * also supports.  In the event that the client doesn't support any of server's
382  * protocols, or the server doesn't advertise any, it SHOULD select the first
383  * protocol that it supports.
384  */
client_npn_cb(SSL * s,unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)385 static int client_npn_cb(SSL *s, unsigned char **out, unsigned char *outlen,
386                          const unsigned char *in, unsigned int inlen,
387                          void *arg)
388 {
389     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
390     int ret;
391 
392     ret = SSL_select_next_proto(out, outlen, in, inlen,
393                                 ctx_data->npn_protocols,
394                                 ctx_data->npn_protocols_len);
395     /* Accept both OPENSSL_NPN_NEGOTIATED and OPENSSL_NPN_NO_OVERLAP. */
396     return TEST_true(ret == OPENSSL_NPN_NEGOTIATED || ret == OPENSSL_NPN_NO_OVERLAP)
397         ? SSL_TLSEXT_ERR_OK : SSL_TLSEXT_ERR_ALERT_FATAL;
398 }
399 
server_npn_cb(SSL * s,const unsigned char ** data,unsigned int * len,void * arg)400 static int server_npn_cb(SSL *s, const unsigned char **data,
401                          unsigned int *len, void *arg)
402 {
403     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
404     *data = ctx_data->npn_protocols;
405     *len = ctx_data->npn_protocols_len;
406     return SSL_TLSEXT_ERR_OK;
407 }
408 #endif
409 
410 /*
411  * The server SHOULD select the most highly preferred protocol that it supports
412  * and that is also advertised by the client.  In the event that the server
413  * supports no protocols that the client advertises, then the server SHALL
414  * respond with a fatal "no_application_protocol" alert.
415  */
server_alpn_cb(SSL * s,const unsigned char ** out,unsigned char * outlen,const unsigned char * in,unsigned int inlen,void * arg)416 static int server_alpn_cb(SSL *s, const unsigned char **out,
417                           unsigned char *outlen, const unsigned char *in,
418                           unsigned int inlen, void *arg)
419 {
420     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
421     int ret;
422 
423     /* SSL_select_next_proto isn't const-correct... */
424     unsigned char *tmp_out;
425 
426     /*
427      * The result points either to |in| or to |ctx_data->alpn_protocols|.
428      * The callback is allowed to point to |in| or to a long-lived buffer,
429      * so we can return directly without storing a copy.
430      */
431     ret = SSL_select_next_proto(&tmp_out, outlen,
432                                 ctx_data->alpn_protocols,
433                                 ctx_data->alpn_protocols_len, in, inlen);
434 
435     *out = tmp_out;
436     /* Unlike NPN, we don't tolerate a mismatch. */
437     return ret == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
438         : SSL_TLSEXT_ERR_ALERT_FATAL;
439 }
440 
generate_session_ticket_cb(SSL * s,void * arg)441 static int generate_session_ticket_cb(SSL *s, void *arg)
442 {
443     CTX_DATA *server_ctx_data = arg;
444     SSL_SESSION *ss = SSL_get_session(s);
445     char *app_data = server_ctx_data->session_ticket_app_data;
446 
447     if (ss == NULL || app_data == NULL)
448         return 0;
449 
450     return SSL_SESSION_set1_ticket_appdata(ss, app_data, strlen(app_data));
451 }
452 
decrypt_session_ticket_cb(SSL * s,SSL_SESSION * ss,const unsigned char * keyname,size_t keyname_len,SSL_TICKET_STATUS status,void * arg)453 static int decrypt_session_ticket_cb(SSL *s, SSL_SESSION *ss,
454                                      const unsigned char *keyname,
455                                      size_t keyname_len,
456                                      SSL_TICKET_STATUS status,
457                                      void *arg)
458 {
459     switch (status) {
460     case SSL_TICKET_EMPTY:
461     case SSL_TICKET_NO_DECRYPT:
462         return SSL_TICKET_RETURN_IGNORE_RENEW;
463     case SSL_TICKET_SUCCESS:
464         return SSL_TICKET_RETURN_USE;
465     case SSL_TICKET_SUCCESS_RENEW:
466         return SSL_TICKET_RETURN_USE_RENEW;
467     default:
468         break;
469     }
470     return SSL_TICKET_RETURN_ABORT;
471 }
472 
473 /*
474  * Configure callbacks and other properties that can't be set directly
475  * in the server/client CONF.
476  */
configure_handshake_ctx(SSL_CTX * server_ctx,SSL_CTX * server2_ctx,SSL_CTX * client_ctx,const SSL_TEST_CTX * test,const SSL_TEST_EXTRA_CONF * extra,CTX_DATA * server_ctx_data,CTX_DATA * server2_ctx_data,CTX_DATA * client_ctx_data)477 static int configure_handshake_ctx(SSL_CTX *server_ctx, SSL_CTX *server2_ctx,
478                                    SSL_CTX *client_ctx,
479                                    const SSL_TEST_CTX *test,
480                                    const SSL_TEST_EXTRA_CONF *extra,
481                                    CTX_DATA *server_ctx_data,
482                                    CTX_DATA *server2_ctx_data,
483                                    CTX_DATA *client_ctx_data)
484 {
485     unsigned char *ticket_keys;
486     size_t ticket_key_len;
487 
488     if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(server_ctx,
489                                                    test->max_fragment_size), 1))
490         goto err;
491     if (server2_ctx != NULL) {
492         if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(server2_ctx,
493                                                        test->max_fragment_size),
494                          1))
495             goto err;
496     }
497     if (!TEST_int_eq(SSL_CTX_set_max_send_fragment(client_ctx,
498                                                    test->max_fragment_size), 1))
499         goto err;
500 
501     switch (extra->client.verify_callback) {
502     case SSL_TEST_VERIFY_ACCEPT_ALL:
503         SSL_CTX_set_cert_verify_callback(client_ctx, &verify_accept_cb, NULL);
504         break;
505     case SSL_TEST_VERIFY_RETRY_ONCE:
506         n_retries = 1;
507         SSL_CTX_set_cert_verify_callback(client_ctx, &verify_retry_cb, NULL);
508         break;
509     case SSL_TEST_VERIFY_REJECT_ALL:
510         SSL_CTX_set_cert_verify_callback(client_ctx, &verify_reject_cb, NULL);
511         break;
512     case SSL_TEST_VERIFY_NONE:
513         break;
514     }
515 
516     switch (extra->client.max_fragment_len_mode) {
517     case TLSEXT_max_fragment_length_512:
518     case TLSEXT_max_fragment_length_1024:
519     case TLSEXT_max_fragment_length_2048:
520     case TLSEXT_max_fragment_length_4096:
521     case TLSEXT_max_fragment_length_DISABLED:
522         SSL_CTX_set_tlsext_max_fragment_length(
523               client_ctx, extra->client.max_fragment_len_mode);
524         break;
525     }
526 
527     /*
528      * Link the two contexts for SNI purposes.
529      * Also do ClientHello callbacks here, as setting both ClientHello and SNI
530      * is bad.
531      */
532     switch (extra->server.servername_callback) {
533     case SSL_TEST_SERVERNAME_IGNORE_MISMATCH:
534         SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_ignore_cb);
535         SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx);
536         break;
537     case SSL_TEST_SERVERNAME_REJECT_MISMATCH:
538         SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_reject_cb);
539         SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx);
540         break;
541     case SSL_TEST_SERVERNAME_CB_NONE:
542         break;
543     case SSL_TEST_SERVERNAME_CLIENT_HELLO_IGNORE_MISMATCH:
544         SSL_CTX_set_client_hello_cb(server_ctx, client_hello_ignore_cb, server2_ctx);
545         break;
546     case SSL_TEST_SERVERNAME_CLIENT_HELLO_REJECT_MISMATCH:
547         SSL_CTX_set_client_hello_cb(server_ctx, client_hello_reject_cb, server2_ctx);
548         break;
549     case SSL_TEST_SERVERNAME_CLIENT_HELLO_NO_V12:
550         SSL_CTX_set_client_hello_cb(server_ctx, client_hello_nov12_cb, server2_ctx);
551     }
552 
553     if (extra->server.cert_status != SSL_TEST_CERT_STATUS_NONE) {
554         SSL_CTX_set_tlsext_status_type(client_ctx, TLSEXT_STATUSTYPE_ocsp);
555         SSL_CTX_set_tlsext_status_cb(client_ctx, client_ocsp_cb);
556         SSL_CTX_set_tlsext_status_arg(client_ctx, NULL);
557         SSL_CTX_set_tlsext_status_cb(server_ctx, server_ocsp_cb);
558         SSL_CTX_set_tlsext_status_arg(server_ctx,
559             ((extra->server.cert_status == SSL_TEST_CERT_STATUS_GOOD_RESPONSE)
560             ? &dummy_ocsp_resp_good_val : &dummy_ocsp_resp_bad_val));
561     }
562 
563     /*
564      * The initial_ctx/session_ctx always handles the encrypt/decrypt of the
565      * session ticket. This ticket_key callback is assigned to the second
566      * session (assigned via SNI), and should never be invoked
567      */
568     if (server2_ctx != NULL)
569         SSL_CTX_set_tlsext_ticket_key_evp_cb(server2_ctx,
570                                              do_not_call_session_ticket_cb);
571 
572     if (extra->server.broken_session_ticket) {
573         SSL_CTX_set_tlsext_ticket_key_evp_cb(server_ctx,
574                                              broken_session_ticket_cb);
575     }
576 #ifndef OPENSSL_NO_NEXTPROTONEG
577     if (extra->server.npn_protocols != NULL) {
578         if (!TEST_true(parse_protos(extra->server.npn_protocols,
579                                     &server_ctx_data->npn_protocols,
580                                     &server_ctx_data->npn_protocols_len)))
581             goto err;
582         SSL_CTX_set_npn_advertised_cb(server_ctx, server_npn_cb,
583                                       server_ctx_data);
584     }
585     if (extra->server2.npn_protocols != NULL) {
586         if (!TEST_true(parse_protos(extra->server2.npn_protocols,
587                                     &server2_ctx_data->npn_protocols,
588                                     &server2_ctx_data->npn_protocols_len))
589                 || !TEST_ptr(server2_ctx))
590             goto err;
591         SSL_CTX_set_npn_advertised_cb(server2_ctx, server_npn_cb,
592                                       server2_ctx_data);
593     }
594     if (extra->client.npn_protocols != NULL) {
595         if (!TEST_true(parse_protos(extra->client.npn_protocols,
596                                     &client_ctx_data->npn_protocols,
597                                     &client_ctx_data->npn_protocols_len)))
598             goto err;
599         SSL_CTX_set_next_proto_select_cb(client_ctx, client_npn_cb,
600                                          client_ctx_data);
601     }
602 #endif
603     if (extra->server.alpn_protocols != NULL) {
604         if (!TEST_true(parse_protos(extra->server.alpn_protocols,
605                                     &server_ctx_data->alpn_protocols,
606                                     &server_ctx_data->alpn_protocols_len)))
607             goto err;
608         SSL_CTX_set_alpn_select_cb(server_ctx, server_alpn_cb, server_ctx_data);
609     }
610     if (extra->server2.alpn_protocols != NULL) {
611         if (!TEST_ptr(server2_ctx)
612                 || !TEST_true(parse_protos(extra->server2.alpn_protocols,
613                                            &server2_ctx_data->alpn_protocols,
614                                            &server2_ctx_data->alpn_protocols_len
615             )))
616             goto err;
617         SSL_CTX_set_alpn_select_cb(server2_ctx, server_alpn_cb,
618                                    server2_ctx_data);
619     }
620     if (extra->client.alpn_protocols != NULL) {
621         unsigned char *alpn_protos = NULL;
622         size_t alpn_protos_len = 0;
623 
624         if (!TEST_true(parse_protos(extra->client.alpn_protocols,
625                                     &alpn_protos, &alpn_protos_len))
626                 /* Reversed return value convention... */
627                 || !TEST_int_eq(SSL_CTX_set_alpn_protos(client_ctx, alpn_protos,
628                                                         alpn_protos_len), 0))
629             goto err;
630         OPENSSL_free(alpn_protos);
631     }
632 
633     if (extra->server.session_ticket_app_data != NULL) {
634         server_ctx_data->session_ticket_app_data =
635             OPENSSL_strdup(extra->server.session_ticket_app_data);
636         SSL_CTX_set_session_ticket_cb(server_ctx, generate_session_ticket_cb,
637                                       decrypt_session_ticket_cb, server_ctx_data);
638     }
639     if (extra->server2.session_ticket_app_data != NULL) {
640         if (!TEST_ptr(server2_ctx))
641             goto err;
642         server2_ctx_data->session_ticket_app_data =
643             OPENSSL_strdup(extra->server2.session_ticket_app_data);
644         SSL_CTX_set_session_ticket_cb(server2_ctx, NULL,
645                                       decrypt_session_ticket_cb, server2_ctx_data);
646     }
647 
648     /*
649      * Use fixed session ticket keys so that we can decrypt a ticket created with
650      * one CTX in another CTX. Don't address server2 for the moment.
651      */
652     ticket_key_len = SSL_CTX_set_tlsext_ticket_keys(server_ctx, NULL, 0);
653     if (!TEST_ptr(ticket_keys = OPENSSL_zalloc(ticket_key_len))
654             || !TEST_int_eq(SSL_CTX_set_tlsext_ticket_keys(server_ctx,
655                                                            ticket_keys,
656                                                            ticket_key_len), 1)) {
657         OPENSSL_free(ticket_keys);
658         goto err;
659     }
660     OPENSSL_free(ticket_keys);
661 
662     /* The default log list includes EC keys, so CT can't work without EC. */
663 #if !defined(OPENSSL_NO_CT) && !defined(OPENSSL_NO_EC)
664     if (!TEST_true(SSL_CTX_set_default_ctlog_list_file(client_ctx)))
665         goto err;
666     switch (extra->client.ct_validation) {
667     case SSL_TEST_CT_VALIDATION_PERMISSIVE:
668         if (!TEST_true(SSL_CTX_enable_ct(client_ctx,
669                                          SSL_CT_VALIDATION_PERMISSIVE)))
670             goto err;
671         break;
672     case SSL_TEST_CT_VALIDATION_STRICT:
673         if (!TEST_true(SSL_CTX_enable_ct(client_ctx, SSL_CT_VALIDATION_STRICT)))
674             goto err;
675         break;
676     case SSL_TEST_CT_VALIDATION_NONE:
677         break;
678     }
679 #endif
680 #ifndef OPENSSL_NO_SRP
681     if (!configure_handshake_ctx_for_srp(server_ctx, server2_ctx, client_ctx,
682                                          extra, server_ctx_data,
683                                          server2_ctx_data, client_ctx_data))
684         goto err;
685 #endif  /* !OPENSSL_NO_SRP */
686     return 1;
687 err:
688     return 0;
689 }
690 
691 /* Configure per-SSL callbacks and other properties. */
configure_handshake_ssl(SSL * server,SSL * client,const SSL_TEST_EXTRA_CONF * extra)692 static void configure_handshake_ssl(SSL *server, SSL *client,
693                                     const SSL_TEST_EXTRA_CONF *extra)
694 {
695     if (extra->client.servername != SSL_TEST_SERVERNAME_NONE)
696         SSL_set_tlsext_host_name(client,
697                                  ssl_servername_name(extra->client.servername));
698     if (extra->client.enable_pha)
699         SSL_set_post_handshake_auth(client, 1);
700 }
701 
702 /* The status for each connection phase. */
703 typedef enum {
704     PEER_SUCCESS,
705     PEER_RETRY,
706     PEER_ERROR,
707     PEER_WAITING,
708     PEER_TEST_FAILURE
709 } peer_status_t;
710 
711 /* An SSL object and associated read-write buffers. */
712 typedef struct peer_st {
713     SSL *ssl;
714     /* Buffer lengths are int to match the SSL read/write API. */
715     unsigned char *write_buf;
716     int write_buf_len;
717     unsigned char *read_buf;
718     int read_buf_len;
719     int bytes_to_write;
720     int bytes_to_read;
721     peer_status_t status;
722 } PEER;
723 
create_peer(PEER * peer,SSL_CTX * ctx)724 static int create_peer(PEER *peer, SSL_CTX *ctx)
725 {
726     static const int peer_buffer_size = 64 * 1024;
727     SSL *ssl = NULL;
728     unsigned char *read_buf = NULL, *write_buf = NULL;
729 
730     if (!TEST_ptr(ssl = SSL_new(ctx))
731             || !TEST_ptr(write_buf = OPENSSL_zalloc(peer_buffer_size))
732             || !TEST_ptr(read_buf = OPENSSL_zalloc(peer_buffer_size)))
733         goto err;
734 
735     peer->ssl = ssl;
736     peer->write_buf = write_buf;
737     peer->read_buf = read_buf;
738     peer->write_buf_len = peer->read_buf_len = peer_buffer_size;
739     return 1;
740 err:
741     SSL_free(ssl);
742     OPENSSL_free(write_buf);
743     OPENSSL_free(read_buf);
744     return 0;
745 }
746 
peer_free_data(PEER * peer)747 static void peer_free_data(PEER *peer)
748 {
749     SSL_free(peer->ssl);
750     OPENSSL_free(peer->write_buf);
751     OPENSSL_free(peer->read_buf);
752 }
753 
754 /*
755  * Note that we could do the handshake transparently under an SSL_write,
756  * but separating the steps is more helpful for debugging test failures.
757  */
do_handshake_step(PEER * peer)758 static void do_handshake_step(PEER *peer)
759 {
760     if (!TEST_int_eq(peer->status, PEER_RETRY)) {
761         peer->status = PEER_TEST_FAILURE;
762     } else {
763         int ret = SSL_do_handshake(peer->ssl);
764 
765         if (ret == 1) {
766             peer->status = PEER_SUCCESS;
767         } else if (ret == 0) {
768             peer->status = PEER_ERROR;
769         } else {
770             int error = SSL_get_error(peer->ssl, ret);
771 
772             /* Memory bios should never block with SSL_ERROR_WANT_WRITE. */
773             if (error != SSL_ERROR_WANT_READ
774                     && error != SSL_ERROR_WANT_RETRY_VERIFY)
775                 peer->status = PEER_ERROR;
776         }
777     }
778 }
779 
780 /*-
781  * Send/receive some application data. The read-write sequence is
782  * Peer A: (R) W - first read will yield no data
783  * Peer B:  R  W
784  * ...
785  * Peer A:  R  W
786  * Peer B:  R  W
787  * Peer A:  R
788  */
do_app_data_step(PEER * peer)789 static void do_app_data_step(PEER *peer)
790 {
791     int ret = 1, write_bytes;
792 
793     if (!TEST_int_eq(peer->status, PEER_RETRY)) {
794         peer->status = PEER_TEST_FAILURE;
795         return;
796     }
797 
798     /* We read everything available... */
799     while (ret > 0 && peer->bytes_to_read) {
800         ret = SSL_read(peer->ssl, peer->read_buf, peer->read_buf_len);
801         if (ret > 0) {
802             if (!TEST_int_le(ret, peer->bytes_to_read)) {
803                 peer->status = PEER_TEST_FAILURE;
804                 return;
805             }
806             peer->bytes_to_read -= ret;
807         } else if (ret == 0) {
808             peer->status = PEER_ERROR;
809             return;
810         } else {
811             int error = SSL_get_error(peer->ssl, ret);
812             if (error != SSL_ERROR_WANT_READ) {
813                 peer->status = PEER_ERROR;
814                 return;
815             } /* Else continue with write. */
816         }
817     }
818 
819     /* ... but we only write one write-buffer-full of data. */
820     write_bytes = peer->bytes_to_write < peer->write_buf_len ? peer->bytes_to_write :
821         peer->write_buf_len;
822     if (write_bytes) {
823         ret = SSL_write(peer->ssl, peer->write_buf, write_bytes);
824         if (ret > 0) {
825             /* SSL_write will only succeed with a complete write. */
826             if (!TEST_int_eq(ret, write_bytes)) {
827                 peer->status = PEER_TEST_FAILURE;
828                 return;
829             }
830             peer->bytes_to_write -= ret;
831         } else {
832             /*
833              * We should perhaps check for SSL_ERROR_WANT_READ/WRITE here
834              * but this doesn't yet occur with current app data sizes.
835              */
836             peer->status = PEER_ERROR;
837             return;
838         }
839     }
840 
841     /*
842      * We could simply finish when there was nothing to read, and we have
843      * nothing left to write. But keeping track of the expected number of bytes
844      * to read gives us somewhat better guarantees that all data sent is in fact
845      * received.
846      */
847     if (peer->bytes_to_write == 0 && peer->bytes_to_read == 0) {
848         peer->status = PEER_SUCCESS;
849     }
850 }
851 
do_reneg_setup_step(const SSL_TEST_CTX * test_ctx,PEER * peer)852 static void do_reneg_setup_step(const SSL_TEST_CTX *test_ctx, PEER *peer)
853 {
854     int ret;
855     char buf;
856 
857     if (peer->status == PEER_SUCCESS) {
858         /*
859          * We are a client that succeeded this step previously, but the server
860          * wanted to retry. Probably there is a no_renegotiation warning alert
861          * waiting for us. Attempt to continue the handshake.
862          */
863         peer->status = PEER_RETRY;
864         do_handshake_step(peer);
865         return;
866     }
867 
868     if (!TEST_int_eq(peer->status, PEER_RETRY)
869             || !TEST_true(test_ctx->handshake_mode
870                               == SSL_TEST_HANDSHAKE_RENEG_SERVER
871                           || test_ctx->handshake_mode
872                               == SSL_TEST_HANDSHAKE_RENEG_CLIENT
873                           || test_ctx->handshake_mode
874                               == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER
875                           || test_ctx->handshake_mode
876                               == SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT
877                           || test_ctx->handshake_mode
878                               == SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH)) {
879         peer->status = PEER_TEST_FAILURE;
880         return;
881     }
882 
883     /* Reset the count of the amount of app data we need to read/write */
884     peer->bytes_to_write = peer->bytes_to_read = test_ctx->app_data_size;
885 
886     /* Check if we are the peer that is going to initiate */
887     if ((test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_SERVER
888                 && SSL_is_server(peer->ssl))
889             || (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RENEG_CLIENT
890                 && !SSL_is_server(peer->ssl))) {
891         /*
892          * If we already asked for a renegotiation then fall through to the
893          * SSL_read() below.
894          */
895         if (!SSL_renegotiate_pending(peer->ssl)) {
896             /*
897              * If we are the client we will always attempt to resume the
898              * session. The server may or may not resume dependent on the
899              * setting of SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
900              */
901             if (SSL_is_server(peer->ssl)) {
902                 ret = SSL_renegotiate(peer->ssl);
903             } else {
904                 int full_reneg = 0;
905 
906                 if (test_ctx->extra.client.no_extms_on_reneg) {
907                     SSL_set_options(peer->ssl, SSL_OP_NO_EXTENDED_MASTER_SECRET);
908                     full_reneg = 1;
909                 }
910                 if (test_ctx->extra.client.reneg_ciphers != NULL) {
911                     if (!SSL_set_cipher_list(peer->ssl,
912                                 test_ctx->extra.client.reneg_ciphers)) {
913                         peer->status = PEER_ERROR;
914                         return;
915                     }
916                     full_reneg = 1;
917                 }
918                 if (full_reneg)
919                     ret = SSL_renegotiate(peer->ssl);
920                 else
921                     ret = SSL_renegotiate_abbreviated(peer->ssl);
922             }
923             if (!ret) {
924                 peer->status = PEER_ERROR;
925                 return;
926             }
927             do_handshake_step(peer);
928             /*
929              * If status is PEER_RETRY it means we're waiting on the peer to
930              * continue the handshake. As far as setting up the renegotiation is
931              * concerned that is a success. The next step will continue the
932              * handshake to its conclusion.
933              *
934              * If status is PEER_SUCCESS then we are the server and we have
935              * successfully sent the HelloRequest. We need to continue to wait
936              * until the handshake arrives from the client.
937              */
938             if (peer->status == PEER_RETRY)
939                 peer->status = PEER_SUCCESS;
940             else if (peer->status == PEER_SUCCESS)
941                 peer->status = PEER_RETRY;
942             return;
943         }
944     } else if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER
945                || test_ctx->handshake_mode
946                   == SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT) {
947         if (SSL_is_server(peer->ssl)
948                 != (test_ctx->handshake_mode
949                     == SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER)) {
950             peer->status = PEER_SUCCESS;
951             return;
952         }
953 
954         ret = SSL_key_update(peer->ssl, test_ctx->key_update_type);
955         if (!ret) {
956             peer->status = PEER_ERROR;
957             return;
958         }
959         do_handshake_step(peer);
960         /*
961          * This is a one step handshake. We shouldn't get anything other than
962          * PEER_SUCCESS
963          */
964         if (peer->status != PEER_SUCCESS)
965             peer->status = PEER_ERROR;
966         return;
967     } else if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH) {
968         if (SSL_is_server(peer->ssl)) {
969             /* Make the server believe it's received the extension */
970             if (test_ctx->extra.server.force_pha)
971                 peer->ssl->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
972             ret = SSL_verify_client_post_handshake(peer->ssl);
973             if (!ret) {
974                 peer->status = PEER_ERROR;
975                 return;
976             }
977         }
978         do_handshake_step(peer);
979         /*
980          * This is a one step handshake. We shouldn't get anything other than
981          * PEER_SUCCESS
982          */
983         if (peer->status != PEER_SUCCESS)
984             peer->status = PEER_ERROR;
985         return;
986     }
987 
988     /*
989      * The SSL object is still expecting app data, even though it's going to
990      * get a handshake message. We try to read, and it should fail - after which
991      * we should be in a handshake
992      */
993     ret = SSL_read(peer->ssl, &buf, sizeof(buf));
994     if (ret >= 0) {
995         /*
996          * We're not actually expecting data - we're expecting a reneg to
997          * start
998          */
999         peer->status = PEER_ERROR;
1000         return;
1001     } else {
1002         int error = SSL_get_error(peer->ssl, ret);
1003         if (error != SSL_ERROR_WANT_READ) {
1004             peer->status = PEER_ERROR;
1005             return;
1006         }
1007         /* If we're not in init yet then we're not done with setup yet */
1008         if (!SSL_in_init(peer->ssl))
1009             return;
1010     }
1011 
1012     peer->status = PEER_SUCCESS;
1013 }
1014 
1015 
1016 /*
1017  * RFC 5246 says:
1018  *
1019  * Note that as of TLS 1.1,
1020  *     failure to properly close a connection no longer requires that a
1021  *     session not be resumed.  This is a change from TLS 1.0 to conform
1022  *     with widespread implementation practice.
1023  *
1024  * However,
1025  * (a) OpenSSL requires that a connection be shutdown for all protocol versions.
1026  * (b) We test lower versions, too.
1027  * So we just implement shutdown. We do a full bidirectional shutdown so that we
1028  * can compare sent and received close_notify alerts and get some test coverage
1029  * for SSL_shutdown as a bonus.
1030  */
do_shutdown_step(PEER * peer)1031 static void do_shutdown_step(PEER *peer)
1032 {
1033     int ret;
1034 
1035     if (!TEST_int_eq(peer->status, PEER_RETRY)) {
1036         peer->status = PEER_TEST_FAILURE;
1037         return;
1038     }
1039     ret = SSL_shutdown(peer->ssl);
1040 
1041     if (ret == 1) {
1042         peer->status = PEER_SUCCESS;
1043     } else if (ret < 0) { /* On 0, we retry. */
1044         int error = SSL_get_error(peer->ssl, ret);
1045 
1046         if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE)
1047             peer->status = PEER_ERROR;
1048     }
1049 }
1050 
1051 typedef enum {
1052     HANDSHAKE,
1053     RENEG_APPLICATION_DATA,
1054     RENEG_SETUP,
1055     RENEG_HANDSHAKE,
1056     APPLICATION_DATA,
1057     SHUTDOWN,
1058     CONNECTION_DONE
1059 } connect_phase_t;
1060 
1061 
renegotiate_op(const SSL_TEST_CTX * test_ctx)1062 static int renegotiate_op(const SSL_TEST_CTX *test_ctx)
1063 {
1064     switch (test_ctx->handshake_mode) {
1065     case SSL_TEST_HANDSHAKE_RENEG_SERVER:
1066     case SSL_TEST_HANDSHAKE_RENEG_CLIENT:
1067         return 1;
1068     default:
1069         return 0;
1070     }
1071 }
post_handshake_op(const SSL_TEST_CTX * test_ctx)1072 static int post_handshake_op(const SSL_TEST_CTX *test_ctx)
1073 {
1074     switch (test_ctx->handshake_mode) {
1075     case SSL_TEST_HANDSHAKE_KEY_UPDATE_CLIENT:
1076     case SSL_TEST_HANDSHAKE_KEY_UPDATE_SERVER:
1077     case SSL_TEST_HANDSHAKE_POST_HANDSHAKE_AUTH:
1078         return 1;
1079     default:
1080         return 0;
1081     }
1082 }
1083 
next_phase(const SSL_TEST_CTX * test_ctx,connect_phase_t phase)1084 static connect_phase_t next_phase(const SSL_TEST_CTX *test_ctx,
1085                                   connect_phase_t phase)
1086 {
1087     switch (phase) {
1088     case HANDSHAKE:
1089         if (renegotiate_op(test_ctx) || post_handshake_op(test_ctx))
1090             return RENEG_APPLICATION_DATA;
1091         return APPLICATION_DATA;
1092     case RENEG_APPLICATION_DATA:
1093         return RENEG_SETUP;
1094     case RENEG_SETUP:
1095         if (post_handshake_op(test_ctx))
1096             return APPLICATION_DATA;
1097         return RENEG_HANDSHAKE;
1098     case RENEG_HANDSHAKE:
1099         return APPLICATION_DATA;
1100     case APPLICATION_DATA:
1101         return SHUTDOWN;
1102     case SHUTDOWN:
1103         return CONNECTION_DONE;
1104     case CONNECTION_DONE:
1105         TEST_error("Trying to progress after connection done");
1106         break;
1107     }
1108     return -1;
1109 }
1110 
do_connect_step(const SSL_TEST_CTX * test_ctx,PEER * peer,connect_phase_t phase)1111 static void do_connect_step(const SSL_TEST_CTX *test_ctx, PEER *peer,
1112                             connect_phase_t phase)
1113 {
1114     switch (phase) {
1115     case HANDSHAKE:
1116         do_handshake_step(peer);
1117         break;
1118     case RENEG_APPLICATION_DATA:
1119         do_app_data_step(peer);
1120         break;
1121     case RENEG_SETUP:
1122         do_reneg_setup_step(test_ctx, peer);
1123         break;
1124     case RENEG_HANDSHAKE:
1125         do_handshake_step(peer);
1126         break;
1127     case APPLICATION_DATA:
1128         do_app_data_step(peer);
1129         break;
1130     case SHUTDOWN:
1131         do_shutdown_step(peer);
1132         break;
1133     case CONNECTION_DONE:
1134         TEST_error("Action after connection done");
1135         break;
1136     }
1137 }
1138 
1139 typedef enum {
1140     /* Both parties succeeded. */
1141     HANDSHAKE_SUCCESS,
1142     /* Client errored. */
1143     CLIENT_ERROR,
1144     /* Server errored. */
1145     SERVER_ERROR,
1146     /* Peers are in inconsistent state. */
1147     INTERNAL_ERROR,
1148     /* One or both peers not done. */
1149     HANDSHAKE_RETRY
1150 } handshake_status_t;
1151 
1152 /*
1153  * Determine the handshake outcome.
1154  * last_status: the status of the peer to have acted last.
1155  * previous_status: the status of the peer that didn't act last.
1156  * client_spoke_last: 1 if the client went last.
1157  */
handshake_status(peer_status_t last_status,peer_status_t previous_status,int client_spoke_last)1158 static handshake_status_t handshake_status(peer_status_t last_status,
1159                                            peer_status_t previous_status,
1160                                            int client_spoke_last)
1161 {
1162     switch (last_status) {
1163     case PEER_TEST_FAILURE:
1164         return INTERNAL_ERROR;
1165 
1166     case PEER_WAITING:
1167         /* Shouldn't ever happen */
1168         return INTERNAL_ERROR;
1169 
1170     case PEER_SUCCESS:
1171         switch (previous_status) {
1172         case PEER_TEST_FAILURE:
1173             return INTERNAL_ERROR;
1174         case PEER_SUCCESS:
1175             /* Both succeeded. */
1176             return HANDSHAKE_SUCCESS;
1177         case PEER_WAITING:
1178         case PEER_RETRY:
1179             /* Let the first peer finish. */
1180             return HANDSHAKE_RETRY;
1181         case PEER_ERROR:
1182             /*
1183              * Second peer succeeded despite the fact that the first peer
1184              * already errored. This shouldn't happen.
1185              */
1186             return INTERNAL_ERROR;
1187         }
1188         break;
1189 
1190     case PEER_RETRY:
1191         return HANDSHAKE_RETRY;
1192 
1193     case PEER_ERROR:
1194         switch (previous_status) {
1195         case PEER_TEST_FAILURE:
1196             return INTERNAL_ERROR;
1197         case PEER_WAITING:
1198             /* The client failed immediately before sending the ClientHello */
1199             return client_spoke_last ? CLIENT_ERROR : INTERNAL_ERROR;
1200         case PEER_SUCCESS:
1201             /* First peer succeeded but second peer errored. */
1202             return client_spoke_last ? CLIENT_ERROR : SERVER_ERROR;
1203         case PEER_RETRY:
1204             /* We errored; let the peer finish. */
1205             return HANDSHAKE_RETRY;
1206         case PEER_ERROR:
1207             /* Both peers errored. Return the one that errored first. */
1208             return client_spoke_last ? SERVER_ERROR : CLIENT_ERROR;
1209         }
1210     }
1211     /* Control should never reach here. */
1212     return INTERNAL_ERROR;
1213 }
1214 
1215 /* Convert unsigned char buf's that shouldn't contain any NUL-bytes to char. */
dup_str(const unsigned char * in,size_t len)1216 static char *dup_str(const unsigned char *in, size_t len)
1217 {
1218     char *ret = NULL;
1219 
1220     if (len == 0)
1221         return NULL;
1222 
1223     /* Assert that the string does not contain NUL-bytes. */
1224     if (TEST_size_t_eq(OPENSSL_strnlen((const char*)(in), len), len))
1225         TEST_ptr(ret = OPENSSL_strndup((const char*)(in), len));
1226     return ret;
1227 }
1228 
pkey_type(EVP_PKEY * pkey)1229 static int pkey_type(EVP_PKEY *pkey)
1230 {
1231     if (EVP_PKEY_is_a(pkey, "EC")) {
1232         char name[80];
1233         size_t name_len;
1234 
1235         if (!EVP_PKEY_get_group_name(pkey, name, sizeof(name), &name_len))
1236             return NID_undef;
1237         return OBJ_txt2nid(name);
1238     }
1239     return EVP_PKEY_get_id(pkey);
1240 }
1241 
peer_pkey_type(SSL * s)1242 static int peer_pkey_type(SSL *s)
1243 {
1244     X509 *x = SSL_get0_peer_certificate(s);
1245 
1246     if (x != NULL)
1247         return pkey_type(X509_get0_pubkey(x));
1248     return NID_undef;
1249 }
1250 
1251 #if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK)
set_sock_as_sctp(int sock)1252 static int set_sock_as_sctp(int sock)
1253 {
1254     struct sctp_assocparams assocparams;
1255     struct sctp_rtoinfo rto_info;
1256     BIO *tmpbio;
1257 
1258     /*
1259      * To allow tests to fail fast (within a second or so), reduce the
1260      * retransmission timeouts and the number of retransmissions.
1261      */
1262     memset(&rto_info, 0, sizeof(struct sctp_rtoinfo));
1263     rto_info.srto_initial = 100;
1264     rto_info.srto_max = 200;
1265     rto_info.srto_min = 50;
1266     (void)setsockopt(sock, IPPROTO_SCTP, SCTP_RTOINFO,
1267                      (const void *)&rto_info, sizeof(struct sctp_rtoinfo));
1268     memset(&assocparams, 0, sizeof(struct sctp_assocparams));
1269     assocparams.sasoc_asocmaxrxt = 2;
1270     (void)setsockopt(sock, IPPROTO_SCTP, SCTP_ASSOCINFO,
1271                      (const void *)&assocparams,
1272                      sizeof(struct sctp_assocparams));
1273 
1274     /*
1275      * For SCTP we have to set various options on the socket prior to
1276      * connecting. This is done automatically by BIO_new_dgram_sctp().
1277      * We don't actually need the created BIO though so we free it again
1278      * immediately.
1279      */
1280     tmpbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE);
1281 
1282     if (tmpbio == NULL)
1283         return 0;
1284     BIO_free(tmpbio);
1285 
1286     return 1;
1287 }
1288 
create_sctp_socks(int * ssock,int * csock)1289 static int create_sctp_socks(int *ssock, int *csock)
1290 {
1291     BIO_ADDRINFO *res = NULL;
1292     const BIO_ADDRINFO *ai = NULL;
1293     int lsock = INVALID_SOCKET, asock = INVALID_SOCKET;
1294     int consock = INVALID_SOCKET;
1295     int ret = 0;
1296     int family = 0;
1297 
1298     if (BIO_sock_init() != 1)
1299         return 0;
1300 
1301     /*
1302      * Port is 4463. It could be anything. It will fail if it's already being
1303      * used for some other SCTP service. It seems unlikely though so we don't
1304      * worry about it here.
1305      */
1306     if (!BIO_lookup_ex(NULL, "4463", BIO_LOOKUP_SERVER, family, SOCK_STREAM,
1307                        IPPROTO_SCTP, &res))
1308         return 0;
1309 
1310     for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
1311         family = BIO_ADDRINFO_family(ai);
1312         lsock = BIO_socket(family, SOCK_STREAM, IPPROTO_SCTP, 0);
1313         if (lsock == INVALID_SOCKET) {
1314             /* Maybe the kernel doesn't support the socket family, even if
1315              * BIO_lookup() added it in the returned result...
1316              */
1317             continue;
1318         }
1319 
1320         if (!set_sock_as_sctp(lsock)
1321                 || !BIO_listen(lsock, BIO_ADDRINFO_address(ai),
1322                                BIO_SOCK_REUSEADDR)) {
1323             BIO_closesocket(lsock);
1324             lsock = INVALID_SOCKET;
1325             continue;
1326         }
1327 
1328         /* Success, don't try any more addresses */
1329         break;
1330     }
1331 
1332     if (lsock == INVALID_SOCKET)
1333         goto err;
1334 
1335     BIO_ADDRINFO_free(res);
1336     res = NULL;
1337 
1338     if (!BIO_lookup_ex(NULL, "4463", BIO_LOOKUP_CLIENT, family, SOCK_STREAM,
1339                         IPPROTO_SCTP, &res))
1340         goto err;
1341 
1342     consock = BIO_socket(family, SOCK_STREAM, IPPROTO_SCTP, 0);
1343     if (consock == INVALID_SOCKET)
1344         goto err;
1345 
1346     if (!set_sock_as_sctp(consock)
1347             || !BIO_connect(consock, BIO_ADDRINFO_address(res), 0)
1348             || !BIO_socket_nbio(consock, 1))
1349         goto err;
1350 
1351     asock = BIO_accept_ex(lsock, NULL, BIO_SOCK_NONBLOCK);
1352     if (asock == INVALID_SOCKET)
1353         goto err;
1354 
1355     *csock = consock;
1356     *ssock = asock;
1357     consock = asock = INVALID_SOCKET;
1358     ret = 1;
1359 
1360  err:
1361     BIO_ADDRINFO_free(res);
1362     if (consock != INVALID_SOCKET)
1363         BIO_closesocket(consock);
1364     if (lsock != INVALID_SOCKET)
1365         BIO_closesocket(lsock);
1366     if (asock != INVALID_SOCKET)
1367         BIO_closesocket(asock);
1368     return ret;
1369 }
1370 #endif
1371 
1372 /*
1373  * Note that |extra| points to the correct client/server configuration
1374  * within |test_ctx|. When configuring the handshake, general mode settings
1375  * are taken from |test_ctx|, and client/server-specific settings should be
1376  * taken from |extra|.
1377  *
1378  * The configuration code should never reach into |test_ctx->extra| or
1379  * |test_ctx->resume_extra| directly.
1380  *
1381  * (We could refactor test mode settings into a substructure. This would result
1382  * in cleaner argument passing but would complicate the test configuration
1383  * parsing.)
1384  */
do_handshake_internal(SSL_CTX * server_ctx,SSL_CTX * server2_ctx,SSL_CTX * client_ctx,const SSL_TEST_CTX * test_ctx,const SSL_TEST_EXTRA_CONF * extra,SSL_SESSION * session_in,SSL_SESSION * serv_sess_in,SSL_SESSION ** session_out,SSL_SESSION ** serv_sess_out)1385 static HANDSHAKE_RESULT *do_handshake_internal(
1386     SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx,
1387     const SSL_TEST_CTX *test_ctx, const SSL_TEST_EXTRA_CONF *extra,
1388     SSL_SESSION *session_in, SSL_SESSION *serv_sess_in,
1389     SSL_SESSION **session_out, SSL_SESSION **serv_sess_out)
1390 {
1391     PEER server, client;
1392     BIO *client_to_server = NULL, *server_to_client = NULL;
1393     HANDSHAKE_EX_DATA server_ex_data, client_ex_data;
1394     CTX_DATA client_ctx_data, server_ctx_data, server2_ctx_data;
1395     HANDSHAKE_RESULT *ret = HANDSHAKE_RESULT_new();
1396     int client_turn = 1, client_turn_count = 0, client_wait_count = 0;
1397     connect_phase_t phase = HANDSHAKE;
1398     handshake_status_t status = HANDSHAKE_RETRY;
1399     const unsigned char* tick = NULL;
1400     size_t tick_len = 0;
1401     const unsigned char* sess_id = NULL;
1402     unsigned int sess_id_len = 0;
1403     SSL_SESSION* sess = NULL;
1404     const unsigned char *proto = NULL;
1405     /* API dictates unsigned int rather than size_t. */
1406     unsigned int proto_len = 0;
1407     EVP_PKEY *tmp_key;
1408     const STACK_OF(X509_NAME) *names;
1409     time_t start;
1410     const char* cipher;
1411 
1412     if (ret == NULL)
1413         return NULL;
1414 
1415     memset(&server_ctx_data, 0, sizeof(server_ctx_data));
1416     memset(&server2_ctx_data, 0, sizeof(server2_ctx_data));
1417     memset(&client_ctx_data, 0, sizeof(client_ctx_data));
1418     memset(&server, 0, sizeof(server));
1419     memset(&client, 0, sizeof(client));
1420     memset(&server_ex_data, 0, sizeof(server_ex_data));
1421     memset(&client_ex_data, 0, sizeof(client_ex_data));
1422 
1423     if (!configure_handshake_ctx(server_ctx, server2_ctx, client_ctx,
1424                                  test_ctx, extra, &server_ctx_data,
1425                                  &server2_ctx_data, &client_ctx_data)) {
1426         TEST_note("configure_handshake_ctx");
1427         return NULL;
1428     }
1429 
1430 #if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK)
1431     if (test_ctx->enable_client_sctp_label_bug)
1432         SSL_CTX_set_mode(client_ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1433     if (test_ctx->enable_server_sctp_label_bug)
1434         SSL_CTX_set_mode(server_ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG);
1435 #endif
1436 
1437     /* Setup SSL and buffers; additional configuration happens below. */
1438     if (!create_peer(&server, server_ctx)) {
1439         TEST_note("creating server context");
1440         goto err;
1441     }
1442     if (!create_peer(&client, client_ctx)) {
1443         TEST_note("creating client context");
1444         goto err;
1445     }
1446 
1447     server.bytes_to_write = client.bytes_to_read = test_ctx->app_data_size;
1448     client.bytes_to_write = server.bytes_to_read = test_ctx->app_data_size;
1449 
1450     configure_handshake_ssl(server.ssl, client.ssl, extra);
1451     if (session_in != NULL) {
1452         SSL_SESSION_get_id(serv_sess_in, &sess_id_len);
1453         /* In case we're testing resumption without tickets. */
1454         if ((sess_id_len > 0
1455                     && !TEST_true(SSL_CTX_add_session(server_ctx,
1456                                                       serv_sess_in)))
1457                 || !TEST_true(SSL_set_session(client.ssl, session_in)))
1458             goto err;
1459         sess_id_len = 0;
1460     }
1461 
1462     ret->result = SSL_TEST_INTERNAL_ERROR;
1463 
1464     if (test_ctx->use_sctp) {
1465 #if !defined(OPENSSL_NO_SCTP) && !defined(OPENSSL_NO_SOCK)
1466         int csock, ssock;
1467 
1468         if (create_sctp_socks(&ssock, &csock)) {
1469             client_to_server = BIO_new_dgram_sctp(csock, BIO_CLOSE);
1470             server_to_client = BIO_new_dgram_sctp(ssock, BIO_CLOSE);
1471         }
1472 #endif
1473     } else {
1474         client_to_server = BIO_new(BIO_s_mem());
1475         server_to_client = BIO_new(BIO_s_mem());
1476     }
1477 
1478     if (!TEST_ptr(client_to_server)
1479             || !TEST_ptr(server_to_client))
1480         goto err;
1481 
1482     /* Non-blocking bio. */
1483     BIO_set_nbio(client_to_server, 1);
1484     BIO_set_nbio(server_to_client, 1);
1485 
1486     SSL_set_connect_state(client.ssl);
1487     SSL_set_accept_state(server.ssl);
1488 
1489     /* The bios are now owned by the SSL object. */
1490     if (test_ctx->use_sctp) {
1491         SSL_set_bio(client.ssl, client_to_server, client_to_server);
1492         SSL_set_bio(server.ssl, server_to_client, server_to_client);
1493     } else {
1494         SSL_set_bio(client.ssl, server_to_client, client_to_server);
1495         if (!TEST_int_gt(BIO_up_ref(server_to_client), 0)
1496                 || !TEST_int_gt(BIO_up_ref(client_to_server), 0))
1497             goto err;
1498         SSL_set_bio(server.ssl, client_to_server, server_to_client);
1499     }
1500 
1501     ex_data_idx = SSL_get_ex_new_index(0, "ex data", NULL, NULL, NULL);
1502     if (!TEST_int_ge(ex_data_idx, 0)
1503             || !TEST_int_eq(SSL_set_ex_data(server.ssl, ex_data_idx, &server_ex_data), 1)
1504             || !TEST_int_eq(SSL_set_ex_data(client.ssl, ex_data_idx, &client_ex_data), 1))
1505         goto err;
1506 
1507     SSL_set_info_callback(server.ssl, &info_cb);
1508     SSL_set_info_callback(client.ssl, &info_cb);
1509 
1510     client.status = PEER_RETRY;
1511     server.status = PEER_WAITING;
1512 
1513     start = time(NULL);
1514 
1515     /*
1516      * Half-duplex handshake loop.
1517      * Client and server speak to each other synchronously in the same process.
1518      * We use non-blocking BIOs, so whenever one peer blocks for read, it
1519      * returns PEER_RETRY to indicate that it's the other peer's turn to write.
1520      * The handshake succeeds once both peers have succeeded. If one peer
1521      * errors out, we also let the other peer retry (and presumably fail).
1522      */
1523     for(;;) {
1524         if (client_turn) {
1525             do_connect_step(test_ctx, &client, phase);
1526             status = handshake_status(client.status, server.status,
1527                                       1 /* client went last */);
1528             if (server.status == PEER_WAITING)
1529                 server.status = PEER_RETRY;
1530         } else {
1531             do_connect_step(test_ctx, &server, phase);
1532             status = handshake_status(server.status, client.status,
1533                                       0 /* server went last */);
1534         }
1535 
1536         switch (status) {
1537         case HANDSHAKE_SUCCESS:
1538             client_turn_count = 0;
1539             phase = next_phase(test_ctx, phase);
1540             if (phase == CONNECTION_DONE) {
1541                 ret->result = SSL_TEST_SUCCESS;
1542                 goto err;
1543             } else {
1544                 client.status = server.status = PEER_RETRY;
1545                 /*
1546                  * For now, client starts each phase. Since each phase is
1547                  * started separately, we can later control this more
1548                  * precisely, for example, to test client-initiated and
1549                  * server-initiated shutdown.
1550                  */
1551                 client_turn = 1;
1552                 break;
1553             }
1554         case CLIENT_ERROR:
1555             ret->result = SSL_TEST_CLIENT_FAIL;
1556             goto err;
1557         case SERVER_ERROR:
1558             ret->result = SSL_TEST_SERVER_FAIL;
1559             goto err;
1560         case INTERNAL_ERROR:
1561             ret->result = SSL_TEST_INTERNAL_ERROR;
1562             goto err;
1563         case HANDSHAKE_RETRY:
1564             if (test_ctx->use_sctp) {
1565                 if (time(NULL) - start > 3) {
1566                     /*
1567                      * We've waited for too long. Give up.
1568                      */
1569                     ret->result = SSL_TEST_INTERNAL_ERROR;
1570                     goto err;
1571                 }
1572                 /*
1573                  * With "real" sockets we only swap to processing the peer
1574                  * if they are expecting to retry. Otherwise we just retry the
1575                  * same endpoint again.
1576                  */
1577                 if ((client_turn && server.status == PEER_RETRY)
1578                         || (!client_turn && client.status == PEER_RETRY))
1579                     client_turn ^= 1;
1580             } else {
1581                 if (client_turn_count++ >= 2000) {
1582                     /*
1583                      * At this point, there's been so many PEER_RETRY in a row
1584                      * that it's likely both sides are stuck waiting for a read.
1585                      * It's time to give up.
1586                      */
1587                     ret->result = SSL_TEST_INTERNAL_ERROR;
1588                     goto err;
1589                 }
1590                 if (client_turn && server.status == PEER_SUCCESS) {
1591                     /*
1592                      * The server may finish before the client because the
1593                      * client spends some turns processing NewSessionTickets.
1594                      */
1595                     if (client_wait_count++ >= 2) {
1596                         ret->result = SSL_TEST_INTERNAL_ERROR;
1597                         goto err;
1598                     }
1599                 } else {
1600                     /* Continue. */
1601                     client_turn ^= 1;
1602                 }
1603             }
1604             break;
1605         }
1606     }
1607  err:
1608     ret->server_alert_sent = server_ex_data.alert_sent;
1609     ret->server_num_fatal_alerts_sent = server_ex_data.num_fatal_alerts_sent;
1610     ret->server_alert_received = client_ex_data.alert_received;
1611     ret->client_alert_sent = client_ex_data.alert_sent;
1612     ret->client_num_fatal_alerts_sent = client_ex_data.num_fatal_alerts_sent;
1613     ret->client_alert_received = server_ex_data.alert_received;
1614     ret->server_protocol = SSL_version(server.ssl);
1615     ret->client_protocol = SSL_version(client.ssl);
1616     ret->servername = server_ex_data.servername;
1617     if ((sess = SSL_get0_session(client.ssl)) != NULL) {
1618         SSL_SESSION_get0_ticket(sess, &tick, &tick_len);
1619         sess_id = SSL_SESSION_get_id(sess, &sess_id_len);
1620     }
1621     if (tick == NULL || tick_len == 0)
1622         ret->session_ticket = SSL_TEST_SESSION_TICKET_NO;
1623     else
1624         ret->session_ticket = SSL_TEST_SESSION_TICKET_YES;
1625     ret->compression = (SSL_get_current_compression(client.ssl) == NULL)
1626                        ? SSL_TEST_COMPRESSION_NO
1627                        : SSL_TEST_COMPRESSION_YES;
1628     if (sess_id == NULL || sess_id_len == 0)
1629         ret->session_id = SSL_TEST_SESSION_ID_NO;
1630     else
1631         ret->session_id = SSL_TEST_SESSION_ID_YES;
1632     ret->session_ticket_do_not_call = server_ex_data.session_ticket_do_not_call;
1633 
1634     if (extra->client.verify_callback == SSL_TEST_VERIFY_RETRY_ONCE
1635             && n_retries != -1)
1636         ret->result = SSL_TEST_SERVER_FAIL;
1637 
1638 #ifndef OPENSSL_NO_NEXTPROTONEG
1639     SSL_get0_next_proto_negotiated(client.ssl, &proto, &proto_len);
1640     ret->client_npn_negotiated = dup_str(proto, proto_len);
1641 
1642     SSL_get0_next_proto_negotiated(server.ssl, &proto, &proto_len);
1643     ret->server_npn_negotiated = dup_str(proto, proto_len);
1644 #endif
1645 
1646     SSL_get0_alpn_selected(client.ssl, &proto, &proto_len);
1647     ret->client_alpn_negotiated = dup_str(proto, proto_len);
1648 
1649     SSL_get0_alpn_selected(server.ssl, &proto, &proto_len);
1650     ret->server_alpn_negotiated = dup_str(proto, proto_len);
1651 
1652     if ((sess = SSL_get0_session(server.ssl)) != NULL) {
1653         SSL_SESSION_get0_ticket_appdata(sess, (void**)&tick, &tick_len);
1654         ret->result_session_ticket_app_data = OPENSSL_strndup((const char*)tick, tick_len);
1655     }
1656 
1657     ret->client_resumed = SSL_session_reused(client.ssl);
1658     ret->server_resumed = SSL_session_reused(server.ssl);
1659 
1660     cipher = SSL_CIPHER_get_name(SSL_get_current_cipher(client.ssl));
1661     ret->cipher = dup_str((const unsigned char*)cipher, strlen(cipher));
1662 
1663     if (session_out != NULL)
1664         *session_out = SSL_get1_session(client.ssl);
1665     if (serv_sess_out != NULL) {
1666         SSL_SESSION *tmp = SSL_get_session(server.ssl);
1667 
1668         /*
1669          * We create a fresh copy that is not in the server session ctx linked
1670          * list.
1671          */
1672         if (tmp != NULL)
1673             *serv_sess_out = SSL_SESSION_dup(tmp);
1674     }
1675 
1676     if (SSL_get_peer_tmp_key(client.ssl, &tmp_key)) {
1677         ret->tmp_key_type = pkey_type(tmp_key);
1678         EVP_PKEY_free(tmp_key);
1679     }
1680 
1681     SSL_get_peer_signature_nid(client.ssl, &ret->server_sign_hash);
1682     SSL_get_peer_signature_nid(server.ssl, &ret->client_sign_hash);
1683 
1684     SSL_get_peer_signature_type_nid(client.ssl, &ret->server_sign_type);
1685     SSL_get_peer_signature_type_nid(server.ssl, &ret->client_sign_type);
1686 
1687     names = SSL_get0_peer_CA_list(client.ssl);
1688     if (names == NULL)
1689         ret->client_ca_names = NULL;
1690     else
1691         ret->client_ca_names = SSL_dup_CA_list(names);
1692 
1693     names = SSL_get0_peer_CA_list(server.ssl);
1694     if (names == NULL)
1695         ret->server_ca_names = NULL;
1696     else
1697         ret->server_ca_names = SSL_dup_CA_list(names);
1698 
1699     ret->server_cert_type = peer_pkey_type(client.ssl);
1700     ret->client_cert_type = peer_pkey_type(server.ssl);
1701 
1702     ctx_data_free_data(&server_ctx_data);
1703     ctx_data_free_data(&server2_ctx_data);
1704     ctx_data_free_data(&client_ctx_data);
1705 
1706     peer_free_data(&server);
1707     peer_free_data(&client);
1708     return ret;
1709 }
1710 
do_handshake(SSL_CTX * server_ctx,SSL_CTX * server2_ctx,SSL_CTX * client_ctx,SSL_CTX * resume_server_ctx,SSL_CTX * resume_client_ctx,const SSL_TEST_CTX * test_ctx)1711 HANDSHAKE_RESULT *do_handshake(SSL_CTX *server_ctx, SSL_CTX *server2_ctx,
1712                                SSL_CTX *client_ctx, SSL_CTX *resume_server_ctx,
1713                                SSL_CTX *resume_client_ctx,
1714                                const SSL_TEST_CTX *test_ctx)
1715 {
1716     HANDSHAKE_RESULT *result;
1717     SSL_SESSION *session = NULL, *serv_sess = NULL;
1718 
1719     result = do_handshake_internal(server_ctx, server2_ctx, client_ctx,
1720                                    test_ctx, &test_ctx->extra,
1721                                    NULL, NULL, &session, &serv_sess);
1722     if (result == NULL
1723             || test_ctx->handshake_mode != SSL_TEST_HANDSHAKE_RESUME
1724             || result->result == SSL_TEST_INTERNAL_ERROR)
1725         goto end;
1726 
1727     if (result->result != SSL_TEST_SUCCESS) {
1728         result->result = SSL_TEST_FIRST_HANDSHAKE_FAILED;
1729         goto end;
1730     }
1731 
1732     HANDSHAKE_RESULT_free(result);
1733     /* We don't support SNI on second handshake yet, so server2_ctx is NULL. */
1734     result = do_handshake_internal(resume_server_ctx, NULL, resume_client_ctx,
1735                                    test_ctx, &test_ctx->resume_extra,
1736                                    session, serv_sess, NULL, NULL);
1737  end:
1738     SSL_SESSION_free(session);
1739     SSL_SESSION_free(serv_sess);
1740     return result;
1741 }
1742