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