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