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