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