Port multi-buffer tests
[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 alert_received;
45     int session_ticket_do_not_call;
46     ssl_servername_t servername;
47 } HANDSHAKE_EX_DATA;
48
49 typedef struct ctx_data_st {
50     unsigned char *npn_protocols;
51     size_t npn_protocols_len;
52     unsigned char *alpn_protocols;
53     size_t alpn_protocols_len;
54 } CTX_DATA;
55
56 /* |ctx_data| itself is stack-allocated. */
57 static void ctx_data_free_data(CTX_DATA *ctx_data)
58 {
59     OPENSSL_free(ctx_data->npn_protocols);
60     ctx_data->npn_protocols = NULL;
61     OPENSSL_free(ctx_data->alpn_protocols);
62     ctx_data->alpn_protocols = NULL;
63 }
64
65 static int ex_data_idx;
66
67 static void info_cb(const SSL *s, int where, int ret)
68 {
69     if (where & SSL_CB_ALERT) {
70         HANDSHAKE_EX_DATA *ex_data =
71             (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
72         if (where & SSL_CB_WRITE) {
73             ex_data->alert_sent = ret;
74         } else {
75             ex_data->alert_received = ret;
76         }
77     }
78 }
79
80 /* Select the appropriate server CTX.
81  * Returns SSL_TLSEXT_ERR_OK if a match was found.
82  * If |ignore| is 1, returns SSL_TLSEXT_ERR_NOACK on mismatch.
83  * Otherwise, returns SSL_TLSEXT_ERR_ALERT_FATAL on mismatch.
84  * An empty SNI extension also returns SSL_TSLEXT_ERR_NOACK.
85  */
86 static int select_server_ctx(SSL *s, void *arg, int ignore)
87 {
88     const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
89     HANDSHAKE_EX_DATA *ex_data =
90         (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
91
92     if (servername == NULL) {
93         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
94         return SSL_TLSEXT_ERR_NOACK;
95     }
96
97     if (strcmp(servername, "server2") == 0) {
98         SSL_CTX *new_ctx = (SSL_CTX*)arg;
99         SSL_set_SSL_CTX(s, new_ctx);
100         /*
101          * Copy over all the SSL_CTX options - reasonable behavior
102          * allows testing of cases where the options between two
103          * contexts differ/conflict
104          */
105         SSL_clear_options(s, 0xFFFFFFFFL);
106         SSL_set_options(s, SSL_CTX_get_options(new_ctx));
107
108         ex_data->servername = SSL_TEST_SERVERNAME_SERVER2;
109         return SSL_TLSEXT_ERR_OK;
110     } else if (strcmp(servername, "server1") == 0) {
111         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
112         return SSL_TLSEXT_ERR_OK;
113     } else if (ignore) {
114         ex_data->servername = SSL_TEST_SERVERNAME_SERVER1;
115         return SSL_TLSEXT_ERR_NOACK;
116     } else {
117         /* Don't set an explicit alert, to test library defaults. */
118         return SSL_TLSEXT_ERR_ALERT_FATAL;
119     }
120 }
121
122 /*
123  * (RFC 6066):
124  *  If the server understood the ClientHello extension but
125  *  does not recognize the server name, the server SHOULD take one of two
126  *  actions: either abort the handshake by sending a fatal-level
127  *  unrecognized_name(112) alert or continue the handshake.
128  *
129  * This behaviour is up to the application to configure; we test both
130  * configurations to ensure the state machine propagates the result
131  * correctly.
132  */
133 static int servername_ignore_cb(SSL *s, int *ad, void *arg)
134 {
135     return select_server_ctx(s, arg, 1);
136 }
137
138 static int servername_reject_cb(SSL *s, int *ad, void *arg)
139 {
140     return select_server_ctx(s, arg, 0);
141 }
142
143 static int verify_reject_cb(X509_STORE_CTX *ctx, void *arg) {
144     X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
145     return 0;
146 }
147
148 static int verify_accept_cb(X509_STORE_CTX *ctx, void *arg) {
149     return 1;
150 }
151
152 static int broken_session_ticket_cb(SSL *s, unsigned char *key_name, unsigned char *iv,
153                                     EVP_CIPHER_CTX *ctx, HMAC_CTX *hctx, int enc)
154 {
155     return 0;
156 }
157
158 static int do_not_call_session_ticket_cb(SSL *s, unsigned char *key_name,
159                                          unsigned char *iv,
160                                          EVP_CIPHER_CTX *ctx,
161                                          HMAC_CTX *hctx, int enc)
162 {
163     HANDSHAKE_EX_DATA *ex_data =
164         (HANDSHAKE_EX_DATA*)(SSL_get_ex_data(s, ex_data_idx));
165     ex_data->session_ticket_do_not_call = 1;
166     return 0;
167 }
168
169 /* Parse the comma-separated list into TLS format. */
170 static void parse_protos(const char *protos, unsigned char **out, size_t *outlen)
171 {
172     size_t len, i, prefix;
173
174     len = strlen(protos);
175
176     /* Should never have reuse. */
177     TEST_check(*out == NULL);
178
179     /* Test values are small, so we omit length limit checks. */
180     *out = OPENSSL_malloc(len + 1);
181     TEST_check(*out != NULL);
182     *outlen = len + 1;
183
184     /*
185      * foo => '3', 'f', 'o', 'o'
186      * foo,bar => '3', 'f', 'o', 'o', '3', 'b', 'a', 'r'
187      */
188     memcpy(*out + 1, protos, len);
189
190     prefix = 0;
191     i = prefix + 1;
192     while (i <= len) {
193         if ((*out)[i] == ',') {
194             TEST_check(i - 1 - prefix > 0);
195             (*out)[prefix] = i - 1 - prefix;
196             prefix = i;
197         }
198         i++;
199     }
200     TEST_check(len - prefix > 0);
201     (*out)[prefix] = len - prefix;
202 }
203
204 #ifndef OPENSSL_NO_NEXTPROTONEG
205 /*
206  * The client SHOULD select the first protocol advertised by the server that it
207  * also supports.  In the event that the client doesn't support any of server's
208  * protocols, or the server doesn't advertise any, it SHOULD select the first
209  * protocol that it supports.
210  */
211 static int client_npn_cb(SSL *s, unsigned char **out, unsigned char *outlen,
212                          const unsigned char *in, unsigned int inlen,
213                          void *arg)
214 {
215     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
216     int ret;
217
218     ret = SSL_select_next_proto(out, outlen, in, inlen,
219                                 ctx_data->npn_protocols,
220                                 ctx_data->npn_protocols_len);
221     /* Accept both OPENSSL_NPN_NEGOTIATED and OPENSSL_NPN_NO_OVERLAP. */
222     TEST_check(ret == OPENSSL_NPN_NEGOTIATED || ret == OPENSSL_NPN_NO_OVERLAP);
223     return SSL_TLSEXT_ERR_OK;
224 }
225
226 static int server_npn_cb(SSL *s, const unsigned char **data,
227                          unsigned int *len, void *arg)
228 {
229     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
230     *data = ctx_data->npn_protocols;
231     *len = ctx_data->npn_protocols_len;
232     return SSL_TLSEXT_ERR_OK;
233 }
234 #endif
235
236 /*
237  * The server SHOULD select the most highly preferred protocol that it supports
238  * and that is also advertised by the client.  In the event that the server
239  * supports no protocols that the client advertises, then the server SHALL
240  * respond with a fatal "no_application_protocol" alert.
241  */
242 static int server_alpn_cb(SSL *s, const unsigned char **out,
243                           unsigned char *outlen, const unsigned char *in,
244                           unsigned int inlen, void *arg)
245 {
246     CTX_DATA *ctx_data = (CTX_DATA*)(arg);
247     int ret;
248
249     /* SSL_select_next_proto isn't const-correct... */
250     unsigned char *tmp_out;
251
252     /*
253      * The result points either to |in| or to |ctx_data->alpn_protocols|.
254      * The callback is allowed to point to |in| or to a long-lived buffer,
255      * so we can return directly without storing a copy.
256      */
257     ret = SSL_select_next_proto(&tmp_out, outlen,
258                                 ctx_data->alpn_protocols,
259                                 ctx_data->alpn_protocols_len, in, inlen);
260
261     *out = tmp_out;
262     /* Unlike NPN, we don't tolerate a mismatch. */
263     return ret == OPENSSL_NPN_NEGOTIATED ? SSL_TLSEXT_ERR_OK
264         : SSL_TLSEXT_ERR_NOACK;
265 }
266
267 /*
268  * Configure callbacks and other properties that can't be set directly
269  * in the server/client CONF.
270  */
271 static void configure_handshake_ctx(SSL_CTX *server_ctx, SSL_CTX *server2_ctx,
272                                     SSL_CTX *client_ctx,
273                                     const SSL_TEST_CTX *test,
274                                     const SSL_TEST_EXTRA_CONF *extra,
275                                     CTX_DATA *server_ctx_data,
276                                     CTX_DATA *server2_ctx_data,
277                                     CTX_DATA *client_ctx_data)
278 {
279     unsigned char *ticket_keys;
280     size_t ticket_key_len;
281
282     TEST_check(SSL_CTX_set_max_send_fragment(server_ctx,
283                                              test->max_fragment_size) == 1);
284     if (server2_ctx != NULL) {
285         TEST_check(SSL_CTX_set_max_send_fragment(server2_ctx,
286                                                  test->max_fragment_size) == 1);
287     }
288     TEST_check(SSL_CTX_set_max_send_fragment(client_ctx,
289                                              test->max_fragment_size) == 1);
290
291     switch (extra->client.verify_callback) {
292     case SSL_TEST_VERIFY_ACCEPT_ALL:
293         SSL_CTX_set_cert_verify_callback(client_ctx, &verify_accept_cb,
294                                          NULL);
295         break;
296     case SSL_TEST_VERIFY_REJECT_ALL:
297         SSL_CTX_set_cert_verify_callback(client_ctx, &verify_reject_cb,
298                                          NULL);
299         break;
300     default:
301         break;
302     }
303
304     /* link the two contexts for SNI purposes */
305     switch (extra->server.servername_callback) {
306     case SSL_TEST_SERVERNAME_IGNORE_MISMATCH:
307         SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_ignore_cb);
308         SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx);
309         break;
310     case SSL_TEST_SERVERNAME_REJECT_MISMATCH:
311         SSL_CTX_set_tlsext_servername_callback(server_ctx, servername_reject_cb);
312         SSL_CTX_set_tlsext_servername_arg(server_ctx, server2_ctx);
313         break;
314     default:
315         break;
316     }
317
318     /*
319      * The initial_ctx/session_ctx always handles the encrypt/decrypt of the
320      * session ticket. This ticket_key callback is assigned to the second
321      * session (assigned via SNI), and should never be invoked
322      */
323     if (server2_ctx != NULL)
324         SSL_CTX_set_tlsext_ticket_key_cb(server2_ctx,
325                                          do_not_call_session_ticket_cb);
326
327     if (extra->server.broken_session_ticket) {
328         SSL_CTX_set_tlsext_ticket_key_cb(server_ctx, broken_session_ticket_cb);
329     }
330 #ifndef OPENSSL_NO_NEXTPROTONEG
331     if (extra->server.npn_protocols != NULL) {
332         parse_protos(extra->server.npn_protocols,
333                      &server_ctx_data->npn_protocols,
334                      &server_ctx_data->npn_protocols_len);
335         SSL_CTX_set_next_protos_advertised_cb(server_ctx, server_npn_cb,
336                                               server_ctx_data);
337     }
338     if (extra->server2.npn_protocols != NULL) {
339         parse_protos(extra->server2.npn_protocols,
340                      &server2_ctx_data->npn_protocols,
341                      &server2_ctx_data->npn_protocols_len);
342         TEST_check(server2_ctx != NULL);
343         SSL_CTX_set_next_protos_advertised_cb(server2_ctx, server_npn_cb,
344                                               server2_ctx_data);
345     }
346     if (extra->client.npn_protocols != NULL) {
347         parse_protos(extra->client.npn_protocols,
348                      &client_ctx_data->npn_protocols,
349                      &client_ctx_data->npn_protocols_len);
350         SSL_CTX_set_next_proto_select_cb(client_ctx, client_npn_cb,
351                                          client_ctx_data);
352     }
353 #endif
354     if (extra->server.alpn_protocols != NULL) {
355         parse_protos(extra->server.alpn_protocols,
356                      &server_ctx_data->alpn_protocols,
357                      &server_ctx_data->alpn_protocols_len);
358         SSL_CTX_set_alpn_select_cb(server_ctx, server_alpn_cb, server_ctx_data);
359     }
360     if (extra->server2.alpn_protocols != NULL) {
361         TEST_check(server2_ctx != NULL);
362         parse_protos(extra->server2.alpn_protocols,
363                      &server2_ctx_data->alpn_protocols,
364                      &server2_ctx_data->alpn_protocols_len);
365         SSL_CTX_set_alpn_select_cb(server2_ctx, server_alpn_cb, server2_ctx_data);
366     }
367     if (extra->client.alpn_protocols != NULL) {
368         unsigned char *alpn_protos = NULL;
369         size_t alpn_protos_len;
370         parse_protos(extra->client.alpn_protocols,
371                      &alpn_protos, &alpn_protos_len);
372         /* Reversed return value convention... */
373         TEST_check(SSL_CTX_set_alpn_protos(client_ctx, alpn_protos,
374                                            alpn_protos_len) == 0);
375         OPENSSL_free(alpn_protos);
376     }
377
378     /*
379      * Use fixed session ticket keys so that we can decrypt a ticket created with
380      * one CTX in another CTX. Don't address server2 for the moment.
381      */
382     ticket_key_len = SSL_CTX_set_tlsext_ticket_keys(server_ctx, NULL, 0);
383     ticket_keys = OPENSSL_zalloc(ticket_key_len);
384     TEST_check(ticket_keys != NULL);
385     TEST_check(SSL_CTX_set_tlsext_ticket_keys(server_ctx, ticket_keys,
386                                               ticket_key_len) == 1);
387     OPENSSL_free(ticket_keys);
388
389     /* The default log list includes EC keys, so CT can't work without EC. */
390 #if !defined(OPENSSL_NO_CT) && !defined(OPENSSL_NO_EC)
391     TEST_check(SSL_CTX_set_default_ctlog_list_file(client_ctx));
392     switch (extra->client.ct_validation) {
393     case SSL_TEST_CT_VALIDATION_PERMISSIVE:
394         TEST_check(SSL_CTX_enable_ct(client_ctx, SSL_CT_VALIDATION_PERMISSIVE));
395         break;
396     case SSL_TEST_CT_VALIDATION_STRICT:
397         TEST_check(SSL_CTX_enable_ct(client_ctx, SSL_CT_VALIDATION_STRICT));
398         break;
399     case SSL_TEST_CT_VALIDATION_NONE:
400         break;
401     }
402 #endif
403 }
404
405 /* Configure per-SSL callbacks and other properties. */
406 static void configure_handshake_ssl(SSL *server, SSL *client,
407                                     const SSL_TEST_EXTRA_CONF *extra)
408 {
409     if (extra->client.servername != SSL_TEST_SERVERNAME_NONE)
410         SSL_set_tlsext_host_name(client,
411                                  ssl_servername_name(extra->client.servername));
412 }
413
414 /* The status for each connection phase. */
415 typedef enum {
416     PEER_SUCCESS,
417     PEER_RETRY,
418     PEER_ERROR
419 } peer_status_t;
420
421 /* An SSL object and associated read-write buffers. */
422 typedef struct peer_st {
423     SSL *ssl;
424     /* Buffer lengths are int to match the SSL read/write API. */
425     unsigned char *write_buf;
426     int write_buf_len;
427     unsigned char *read_buf;
428     int read_buf_len;
429     int bytes_to_write;
430     int bytes_to_read;
431     peer_status_t status;
432 } PEER;
433
434 static void create_peer(PEER *peer, SSL_CTX *ctx)
435 {
436     static const int peer_buffer_size = 64 * 1024;
437
438     peer->ssl = SSL_new(ctx);
439     TEST_check(peer->ssl != NULL);
440     peer->write_buf = OPENSSL_zalloc(peer_buffer_size);
441     TEST_check(peer->write_buf != NULL);
442     peer->read_buf = OPENSSL_zalloc(peer_buffer_size);
443     TEST_check(peer->read_buf != NULL);
444     peer->write_buf_len = peer->read_buf_len = peer_buffer_size;
445 }
446
447 static void peer_free_data(PEER *peer)
448 {
449     SSL_free(peer->ssl);
450     OPENSSL_free(peer->write_buf);
451     OPENSSL_free(peer->read_buf);
452 }
453
454 /*
455  * Note that we could do the handshake transparently under an SSL_write,
456  * but separating the steps is more helpful for debugging test failures.
457  */
458 static void do_handshake_step(PEER *peer)
459 {
460     int ret;
461
462     TEST_check(peer->status == PEER_RETRY);
463     ret = SSL_do_handshake(peer->ssl);
464
465     if (ret == 1) {
466         peer->status = PEER_SUCCESS;
467     } else if (ret == 0) {
468         peer->status = PEER_ERROR;
469     } else {
470         int error = SSL_get_error(peer->ssl, ret);
471         /* Memory bios should never block with SSL_ERROR_WANT_WRITE. */
472         if (error != SSL_ERROR_WANT_READ)
473             peer->status = PEER_ERROR;
474     }
475 }
476
477 /*-
478  * Send/receive some application data. The read-write sequence is
479  * Peer A: (R) W - first read will yield no data
480  * Peer B:  R  W
481  * ...
482  * Peer A:  R  W
483  * Peer B:  R  W
484  * Peer A:  R
485  */
486 static void do_app_data_step(PEER *peer)
487 {
488     int ret = 1, write_bytes;
489
490     TEST_check(peer->status == PEER_RETRY);
491
492     /* We read everything available... */
493     while (ret > 0 && peer->bytes_to_read) {
494         ret = SSL_read(peer->ssl, peer->read_buf, peer->read_buf_len);
495         if (ret > 0) {
496             TEST_check(ret <= peer->bytes_to_read);
497             peer->bytes_to_read -= ret;
498         } else if (ret == 0) {
499             peer->status = PEER_ERROR;
500             return;
501         } else {
502             int error = SSL_get_error(peer->ssl, ret);
503             if (error != SSL_ERROR_WANT_READ) {
504                 peer->status = PEER_ERROR;
505                 return;
506             } /* Else continue with write. */
507         }
508     }
509
510     /* ... but we only write one write-buffer-full of data. */
511     write_bytes = peer->bytes_to_write < peer->write_buf_len ? peer->bytes_to_write :
512         peer->write_buf_len;
513     if (write_bytes) {
514         ret = SSL_write(peer->ssl, peer->write_buf, write_bytes);
515         if (ret > 0) {
516             /* SSL_write will only succeed with a complete write. */
517             TEST_check(ret == write_bytes);
518             peer->bytes_to_write -= ret;
519         } else {
520             /*
521              * We should perhaps check for SSL_ERROR_WANT_READ/WRITE here
522              * but this doesn't yet occur with current app data sizes.
523              */
524             peer->status = PEER_ERROR;
525             return;
526         }
527     }
528
529     /*
530      * We could simply finish when there was nothing to read, and we have
531      * nothing left to write. But keeping track of the expected number of bytes
532      * to read gives us somewhat better guarantees that all data sent is in fact
533      * received.
534      */
535     if (!peer->bytes_to_write && !peer->bytes_to_read) {
536         peer->status = PEER_SUCCESS;
537     }
538 }
539
540 /*
541  * RFC 5246 says:
542  *
543  * Note that as of TLS 1.1,
544  *     failure to properly close a connection no longer requires that a
545  *     session not be resumed.  This is a change from TLS 1.0 to conform
546  *     with widespread implementation practice.
547  *
548  * However,
549  * (a) OpenSSL requires that a connection be shutdown for all protocol versions.
550  * (b) We test lower versions, too.
551  * So we just implement shutdown. We do a full bidirectional shutdown so that we
552  * can compare sent and received close_notify alerts and get some test coverage
553  * for SSL_shutdown as a bonus.
554  */
555 static void do_shutdown_step(PEER *peer)
556 {
557     int ret;
558
559     TEST_check(peer->status == PEER_RETRY);
560     ret = SSL_shutdown(peer->ssl);
561
562     if (ret == 1) {
563         peer->status = PEER_SUCCESS;
564     } else if (ret < 0) { /* On 0, we retry. */
565         int error = SSL_get_error(peer->ssl, ret);
566         /* Memory bios should never block with SSL_ERROR_WANT_WRITE. */
567         if (error != SSL_ERROR_WANT_READ)
568             peer->status = PEER_ERROR;
569     }
570 }
571
572 typedef enum {
573     HANDSHAKE,
574     APPLICATION_DATA,
575     SHUTDOWN,
576     CONNECTION_DONE
577 } connect_phase_t;
578
579 static connect_phase_t next_phase(connect_phase_t phase)
580 {
581     switch (phase) {
582     case HANDSHAKE:
583         return APPLICATION_DATA;
584     case APPLICATION_DATA:
585         return SHUTDOWN;
586     case SHUTDOWN:
587         return CONNECTION_DONE;
588     default:
589         TEST_check(0); /* Should never call next_phase when done. */
590     }
591 }
592
593 static void do_connect_step(PEER *peer, connect_phase_t phase)
594 {
595     switch (phase) {
596     case HANDSHAKE:
597         do_handshake_step(peer);
598         break;
599     case APPLICATION_DATA:
600         do_app_data_step(peer);
601         break;
602     case SHUTDOWN:
603         do_shutdown_step(peer);
604         break;
605     default:
606         TEST_check(0);
607     }
608 }
609
610 typedef enum {
611     /* Both parties succeeded. */
612     HANDSHAKE_SUCCESS,
613     /* Client errored. */
614     CLIENT_ERROR,
615     /* Server errored. */
616     SERVER_ERROR,
617     /* Peers are in inconsistent state. */
618     INTERNAL_ERROR,
619     /* One or both peers not done. */
620     HANDSHAKE_RETRY
621 } handshake_status_t;
622
623 /*
624  * Determine the handshake outcome.
625  * last_status: the status of the peer to have acted last.
626  * previous_status: the status of the peer that didn't act last.
627  * client_spoke_last: 1 if the client went last.
628  */
629 static handshake_status_t handshake_status(peer_status_t last_status,
630                                            peer_status_t previous_status,
631                                            int client_spoke_last)
632 {
633     switch (last_status) {
634     case PEER_SUCCESS:
635         switch (previous_status) {
636         case PEER_SUCCESS:
637             /* Both succeeded. */
638             return HANDSHAKE_SUCCESS;
639         case PEER_RETRY:
640             /* Let the first peer finish. */
641             return HANDSHAKE_RETRY;
642         case PEER_ERROR:
643             /*
644              * Second peer succeeded despite the fact that the first peer
645              * already errored. This shouldn't happen.
646              */
647             return INTERNAL_ERROR;
648         }
649
650     case PEER_RETRY:
651         if (previous_status == PEER_RETRY) {
652             /* Neither peer is done. */
653             return HANDSHAKE_RETRY;
654         } else {
655             /*
656              * Deadlock: second peer is waiting for more input while first
657              * peer thinks they're done (no more input is coming).
658              */
659             return INTERNAL_ERROR;
660         }
661     case PEER_ERROR:
662         switch (previous_status) {
663         case PEER_SUCCESS:
664             /*
665              * First peer succeeded but second peer errored.
666              * TODO(emilia): we should be able to continue here (with some
667              * application data?) to ensure the first peer receives the
668              * alert / close_notify.
669              * (No tests currently exercise this branch.)
670              */
671             return client_spoke_last ? CLIENT_ERROR : SERVER_ERROR;
672         case PEER_RETRY:
673             /* We errored; let the peer finish. */
674             return HANDSHAKE_RETRY;
675         case PEER_ERROR:
676             /* Both peers errored. Return the one that errored first. */
677             return client_spoke_last ? SERVER_ERROR : CLIENT_ERROR;
678         }
679     }
680     /* Control should never reach here. */
681     return INTERNAL_ERROR;
682 }
683
684 /* Convert unsigned char buf's that shouldn't contain any NUL-bytes to char. */
685 static char *dup_str(const unsigned char *in, size_t len)
686 {
687     char *ret;
688
689     if(len == 0)
690         return NULL;
691
692     /* Assert that the string does not contain NUL-bytes. */
693     TEST_check(OPENSSL_strnlen((const char*)(in), len) == len);
694     ret = OPENSSL_strndup((const char*)(in), len);
695     TEST_check(ret != NULL);
696     return ret;
697 }
698
699 /*
700  * Note that |extra| points to the correct client/server configuration
701  * within |test_ctx|. When configuring the handshake, general mode settings
702  * are taken from |test_ctx|, and client/server-specific settings should be
703  * taken from |extra|.
704  *
705  * The configuration code should never reach into |test_ctx->extra| or
706  * |test_ctx->resume_extra| directly.
707  *
708  * (We could refactor test mode settings into a substructure. This would result
709  * in cleaner argument passing but would complicate the test configuration
710  * parsing.)
711  */
712 static HANDSHAKE_RESULT *do_handshake_internal(
713     SSL_CTX *server_ctx, SSL_CTX *server2_ctx, SSL_CTX *client_ctx,
714     const SSL_TEST_CTX *test_ctx, const SSL_TEST_EXTRA_CONF *extra,
715     SSL_SESSION *session_in, SSL_SESSION **session_out)
716 {
717     PEER server, client;
718     BIO *client_to_server, *server_to_client;
719     HANDSHAKE_EX_DATA server_ex_data, client_ex_data;
720     CTX_DATA client_ctx_data, server_ctx_data, server2_ctx_data;
721     HANDSHAKE_RESULT *ret = HANDSHAKE_RESULT_new();
722     int client_turn = 1;
723     connect_phase_t phase = HANDSHAKE;
724     handshake_status_t status = HANDSHAKE_RETRY;
725     const unsigned char* tick = NULL;
726     size_t tick_len = 0;
727     SSL_SESSION* sess = NULL;
728     const unsigned char *proto = NULL;
729     /* API dictates unsigned int rather than size_t. */
730     unsigned int proto_len = 0;
731
732     memset(&server_ctx_data, 0, sizeof(server_ctx_data));
733     memset(&server2_ctx_data, 0, sizeof(server2_ctx_data));
734     memset(&client_ctx_data, 0, sizeof(client_ctx_data));
735     memset(&server, 0, sizeof(server));
736     memset(&client, 0, sizeof(client));
737
738     configure_handshake_ctx(server_ctx, server2_ctx, client_ctx, test_ctx, extra,
739                             &server_ctx_data, &server2_ctx_data, &client_ctx_data);
740
741     /* Setup SSL and buffers; additional configuration happens below. */
742     create_peer(&server, server_ctx);
743     create_peer(&client, client_ctx);
744
745     server.bytes_to_write = client.bytes_to_read = test_ctx->app_data_size;
746     client.bytes_to_write = server.bytes_to_read = test_ctx->app_data_size;
747
748     configure_handshake_ssl(server.ssl, client.ssl, extra);
749     if (session_in != NULL) {
750         /* In case we're testing resumption without tickets. */
751         TEST_check(SSL_CTX_add_session(server_ctx, session_in));
752         TEST_check(SSL_set_session(client.ssl, session_in));
753     }
754
755     memset(&server_ex_data, 0, sizeof(server_ex_data));
756     memset(&client_ex_data, 0, sizeof(client_ex_data));
757
758     ret->result = SSL_TEST_INTERNAL_ERROR;
759
760     client_to_server = BIO_new(BIO_s_mem());
761     server_to_client = BIO_new(BIO_s_mem());
762
763     TEST_check(client_to_server != NULL);
764     TEST_check(server_to_client != NULL);
765
766     /* Non-blocking bio. */
767     BIO_set_nbio(client_to_server, 1);
768     BIO_set_nbio(server_to_client, 1);
769
770     SSL_set_connect_state(client.ssl);
771     SSL_set_accept_state(server.ssl);
772
773     /* The bios are now owned by the SSL object. */
774     SSL_set_bio(client.ssl, server_to_client, client_to_server);
775     TEST_check(BIO_up_ref(server_to_client) > 0);
776     TEST_check(BIO_up_ref(client_to_server) > 0);
777     SSL_set_bio(server.ssl, client_to_server, server_to_client);
778
779     ex_data_idx = SSL_get_ex_new_index(0, "ex data", NULL, NULL, NULL);
780     TEST_check(ex_data_idx >= 0);
781
782     TEST_check(SSL_set_ex_data(server.ssl, ex_data_idx, &server_ex_data) == 1);
783     TEST_check(SSL_set_ex_data(client.ssl, ex_data_idx, &client_ex_data) == 1);
784
785     SSL_set_info_callback(server.ssl, &info_cb);
786     SSL_set_info_callback(client.ssl, &info_cb);
787
788     client.status = server.status = PEER_RETRY;
789
790     /*
791      * Half-duplex handshake loop.
792      * Client and server speak to each other synchronously in the same process.
793      * We use non-blocking BIOs, so whenever one peer blocks for read, it
794      * returns PEER_RETRY to indicate that it's the other peer's turn to write.
795      * The handshake succeeds once both peers have succeeded. If one peer
796      * errors out, we also let the other peer retry (and presumably fail).
797      */
798     for(;;) {
799         if (client_turn) {
800             do_connect_step(&client, phase);
801             status = handshake_status(client.status, server.status,
802                                       1 /* client went last */);
803         } else {
804             do_connect_step(&server, phase);
805             status = handshake_status(server.status, client.status,
806                                       0 /* server went last */);
807         }
808
809         switch (status) {
810         case HANDSHAKE_SUCCESS:
811             phase = next_phase(phase);
812             if (phase == CONNECTION_DONE) {
813                 ret->result = SSL_TEST_SUCCESS;
814                 goto err;
815             } else {
816                 client.status = server.status = PEER_RETRY;
817                 /*
818                  * For now, client starts each phase. Since each phase is
819                  * started separately, we can later control this more
820                  * precisely, for example, to test client-initiated and
821                  * server-initiated shutdown.
822                  */
823                 client_turn = 1;
824                 break;
825             }
826         case CLIENT_ERROR:
827             ret->result = SSL_TEST_CLIENT_FAIL;
828             goto err;
829         case SERVER_ERROR:
830             ret->result = SSL_TEST_SERVER_FAIL;
831             goto err;
832         case INTERNAL_ERROR:
833             ret->result = SSL_TEST_INTERNAL_ERROR;
834             goto err;
835         case HANDSHAKE_RETRY:
836             /* Continue. */
837             client_turn ^= 1;
838             break;
839         }
840     }
841  err:
842     ret->server_alert_sent = server_ex_data.alert_sent;
843     ret->server_alert_received = client_ex_data.alert_received;
844     ret->client_alert_sent = client_ex_data.alert_sent;
845     ret->client_alert_received = server_ex_data.alert_received;
846     ret->server_protocol = SSL_version(server.ssl);
847     ret->client_protocol = SSL_version(client.ssl);
848     ret->servername = server_ex_data.servername;
849     if ((sess = SSL_get0_session(client.ssl)) != NULL)
850         SSL_SESSION_get0_ticket(sess, &tick, &tick_len);
851     if (tick == NULL || tick_len == 0)
852         ret->session_ticket = SSL_TEST_SESSION_TICKET_NO;
853     else
854         ret->session_ticket = SSL_TEST_SESSION_TICKET_YES;
855     ret->session_ticket_do_not_call = server_ex_data.session_ticket_do_not_call;
856
857 #ifndef OPENSSL_NO_NEXTPROTONEG
858     SSL_get0_next_proto_negotiated(client.ssl, &proto, &proto_len);
859     ret->client_npn_negotiated = dup_str(proto, proto_len);
860
861     SSL_get0_next_proto_negotiated(server.ssl, &proto, &proto_len);
862     ret->server_npn_negotiated = dup_str(proto, proto_len);
863 #endif
864
865     SSL_get0_alpn_selected(client.ssl, &proto, &proto_len);
866     ret->client_alpn_negotiated = dup_str(proto, proto_len);
867
868     SSL_get0_alpn_selected(server.ssl, &proto, &proto_len);
869     ret->server_alpn_negotiated = dup_str(proto, proto_len);
870
871     ret->client_resumed = SSL_session_reused(client.ssl);
872     ret->server_resumed = SSL_session_reused(server.ssl);
873
874     if (session_out != NULL)
875         *session_out = SSL_get1_session(client.ssl);
876
877     ctx_data_free_data(&server_ctx_data);
878     ctx_data_free_data(&server2_ctx_data);
879     ctx_data_free_data(&client_ctx_data);
880
881     peer_free_data(&server);
882     peer_free_data(&client);
883     return ret;
884 }
885
886 HANDSHAKE_RESULT *do_handshake(SSL_CTX *server_ctx, SSL_CTX *server2_ctx,
887                                SSL_CTX *client_ctx, SSL_CTX *resume_server_ctx,
888                                SSL_CTX *resume_client_ctx,
889                                const SSL_TEST_CTX *test_ctx)
890 {
891     HANDSHAKE_RESULT *result;
892     SSL_SESSION *session = NULL;
893
894     result = do_handshake_internal(server_ctx, server2_ctx, client_ctx,
895                                    test_ctx, &test_ctx->extra,
896                                    NULL, &session);
897     if (test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_SIMPLE)
898         goto end;
899
900     TEST_check(test_ctx->handshake_mode == SSL_TEST_HANDSHAKE_RESUME);
901
902     if (result->result != SSL_TEST_SUCCESS) {
903         result->result = SSL_TEST_FIRST_HANDSHAKE_FAILED;
904         goto end;
905     }
906
907     HANDSHAKE_RESULT_free(result);
908     /* We don't support SNI on second handshake yet, so server2_ctx is NULL. */
909     result = do_handshake_internal(resume_server_ctx, NULL, resume_client_ctx,
910                                    test_ctx, &test_ctx->resume_extra,
911                                    session, NULL);
912  end:
913     SSL_SESSION_free(session);
914     return result;
915 }