bio: Linux TLS Rx Offload
[openssl.git] / test / ssltestlib.c
1 /*
2  * Copyright 2016-2019 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 "internal/nelem.h"
13 #include "ssltestlib.h"
14 #include "testutil.h"
15 #include "e_os.h"
16
17 #ifdef OPENSSL_SYS_UNIX
18 # include <unistd.h>
19 #ifndef OPENSSL_NO_KTLS
20 # include <netinet/in.h>
21 # include <netinet/in.h>
22 # include <arpa/inet.h>
23 # include <sys/socket.h>
24 # include <unistd.h>
25 # include <fcntl.h>
26 #endif
27
28 static ossl_inline void ossl_sleep(unsigned int millis)
29 {
30 # ifdef OPENSSL_SYS_VXWORKS
31     struct timespec ts;
32     ts.tv_sec = (long int) (millis / 1000);
33     ts.tv_nsec = (long int) (millis % 1000) * 1000000ul;
34     nanosleep(&ts, NULL);
35 # else
36     usleep(millis * 1000);
37 # endif
38 }
39 #elif defined(_WIN32)
40 # include <windows.h>
41
42 static ossl_inline void ossl_sleep(unsigned int millis)
43 {
44     Sleep(millis);
45 }
46 #else
47 /* Fallback to a busy wait */
48 static ossl_inline void ossl_sleep(unsigned int millis)
49 {
50     struct timeval start, now;
51     unsigned int elapsedms;
52
53     gettimeofday(&start, NULL);
54     do {
55         gettimeofday(&now, NULL);
56         elapsedms = (((now.tv_sec - start.tv_sec) * 1000000)
57                      + now.tv_usec - start.tv_usec) / 1000;
58     } while (elapsedms < millis);
59 }
60 #endif
61
62 static int tls_dump_new(BIO *bi);
63 static int tls_dump_free(BIO *a);
64 static int tls_dump_read(BIO *b, char *out, int outl);
65 static int tls_dump_write(BIO *b, const char *in, int inl);
66 static long tls_dump_ctrl(BIO *b, int cmd, long num, void *ptr);
67 static int tls_dump_gets(BIO *bp, char *buf, int size);
68 static int tls_dump_puts(BIO *bp, const char *str);
69
70 /* Choose a sufficiently large type likely to be unused for this custom BIO */
71 #define BIO_TYPE_TLS_DUMP_FILTER  (0x80 | BIO_TYPE_FILTER)
72 #define BIO_TYPE_MEMPACKET_TEST    0x81
73
74 static BIO_METHOD *method_tls_dump = NULL;
75 static BIO_METHOD *meth_mem = NULL;
76
77 /* Note: Not thread safe! */
78 const BIO_METHOD *bio_f_tls_dump_filter(void)
79 {
80     if (method_tls_dump == NULL) {
81         method_tls_dump = BIO_meth_new(BIO_TYPE_TLS_DUMP_FILTER,
82                                         "TLS dump filter");
83         if (   method_tls_dump == NULL
84             || !BIO_meth_set_write(method_tls_dump, tls_dump_write)
85             || !BIO_meth_set_read(method_tls_dump, tls_dump_read)
86             || !BIO_meth_set_puts(method_tls_dump, tls_dump_puts)
87             || !BIO_meth_set_gets(method_tls_dump, tls_dump_gets)
88             || !BIO_meth_set_ctrl(method_tls_dump, tls_dump_ctrl)
89             || !BIO_meth_set_create(method_tls_dump, tls_dump_new)
90             || !BIO_meth_set_destroy(method_tls_dump, tls_dump_free))
91             return NULL;
92     }
93     return method_tls_dump;
94 }
95
96 void bio_f_tls_dump_filter_free(void)
97 {
98     BIO_meth_free(method_tls_dump);
99 }
100
101 static int tls_dump_new(BIO *bio)
102 {
103     BIO_set_init(bio, 1);
104     return 1;
105 }
106
107 static int tls_dump_free(BIO *bio)
108 {
109     BIO_set_init(bio, 0);
110
111     return 1;
112 }
113
114 static void copy_flags(BIO *bio)
115 {
116     int flags;
117     BIO *next = BIO_next(bio);
118
119     flags = BIO_test_flags(next, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
120     BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
121     BIO_set_flags(bio, flags);
122 }
123
124 #define RECORD_CONTENT_TYPE     0
125 #define RECORD_VERSION_HI       1
126 #define RECORD_VERSION_LO       2
127 #define RECORD_EPOCH_HI         3
128 #define RECORD_EPOCH_LO         4
129 #define RECORD_SEQUENCE_START   5
130 #define RECORD_SEQUENCE_END     10
131 #define RECORD_LEN_HI           11
132 #define RECORD_LEN_LO           12
133
134 #define MSG_TYPE                0
135 #define MSG_LEN_HI              1
136 #define MSG_LEN_MID             2
137 #define MSG_LEN_LO              3
138 #define MSG_SEQ_HI              4
139 #define MSG_SEQ_LO              5
140 #define MSG_FRAG_OFF_HI         6
141 #define MSG_FRAG_OFF_MID        7
142 #define MSG_FRAG_OFF_LO         8
143 #define MSG_FRAG_LEN_HI         9
144 #define MSG_FRAG_LEN_MID        10
145 #define MSG_FRAG_LEN_LO         11
146
147
148 static void dump_data(const char *data, int len)
149 {
150     int rem, i, content, reclen, msglen, fragoff, fraglen, epoch;
151     unsigned char *rec;
152
153     printf("---- START OF PACKET ----\n");
154
155     rem = len;
156     rec = (unsigned char *)data;
157
158     while (rem > 0) {
159         if (rem != len)
160             printf("*\n");
161         printf("*---- START OF RECORD ----\n");
162         if (rem < DTLS1_RT_HEADER_LENGTH) {
163             printf("*---- RECORD TRUNCATED ----\n");
164             break;
165         }
166         content = rec[RECORD_CONTENT_TYPE];
167         printf("** Record Content-type: %d\n", content);
168         printf("** Record Version: %02x%02x\n",
169                rec[RECORD_VERSION_HI], rec[RECORD_VERSION_LO]);
170         epoch = (rec[RECORD_EPOCH_HI] << 8) | rec[RECORD_EPOCH_LO];
171         printf("** Record Epoch: %d\n", epoch);
172         printf("** Record Sequence: ");
173         for (i = RECORD_SEQUENCE_START; i <= RECORD_SEQUENCE_END; i++)
174             printf("%02x", rec[i]);
175         reclen = (rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO];
176         printf("\n** Record Length: %d\n", reclen);
177
178         /* Now look at message */
179         rec += DTLS1_RT_HEADER_LENGTH;
180         rem -= DTLS1_RT_HEADER_LENGTH;
181         if (content == SSL3_RT_HANDSHAKE) {
182             printf("**---- START OF HANDSHAKE MESSAGE FRAGMENT ----\n");
183             if (epoch > 0) {
184                 printf("**---- HANDSHAKE MESSAGE FRAGMENT ENCRYPTED ----\n");
185             } else if (rem < DTLS1_HM_HEADER_LENGTH
186                     || reclen < DTLS1_HM_HEADER_LENGTH) {
187                 printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
188             } else {
189                 printf("*** Message Type: %d\n", rec[MSG_TYPE]);
190                 msglen = (rec[MSG_LEN_HI] << 16) | (rec[MSG_LEN_MID] << 8)
191                          | rec[MSG_LEN_LO];
192                 printf("*** Message Length: %d\n", msglen);
193                 printf("*** Message sequence: %d\n",
194                        (rec[MSG_SEQ_HI] << 8) | rec[MSG_SEQ_LO]);
195                 fragoff = (rec[MSG_FRAG_OFF_HI] << 16)
196                           | (rec[MSG_FRAG_OFF_MID] << 8)
197                           | rec[MSG_FRAG_OFF_LO];
198                 printf("*** Message Fragment offset: %d\n", fragoff);
199                 fraglen = (rec[MSG_FRAG_LEN_HI] << 16)
200                           | (rec[MSG_FRAG_LEN_MID] << 8)
201                           | rec[MSG_FRAG_LEN_LO];
202                 printf("*** Message Fragment len: %d\n", fraglen);
203                 if (fragoff + fraglen > msglen)
204                     printf("***---- HANDSHAKE MESSAGE FRAGMENT INVALID ----\n");
205                 else if (reclen < fraglen)
206                     printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
207                 else
208                     printf("**---- END OF HANDSHAKE MESSAGE FRAGMENT ----\n");
209             }
210         }
211         if (rem < reclen) {
212             printf("*---- RECORD TRUNCATED ----\n");
213             rem = 0;
214         } else {
215             rec += reclen;
216             rem -= reclen;
217             printf("*---- END OF RECORD ----\n");
218         }
219     }
220     printf("---- END OF PACKET ----\n\n");
221     fflush(stdout);
222 }
223
224 static int tls_dump_read(BIO *bio, char *out, int outl)
225 {
226     int ret;
227     BIO *next = BIO_next(bio);
228
229     ret = BIO_read(next, out, outl);
230     copy_flags(bio);
231
232     if (ret > 0) {
233         dump_data(out, ret);
234     }
235
236     return ret;
237 }
238
239 static int tls_dump_write(BIO *bio, const char *in, int inl)
240 {
241     int ret;
242     BIO *next = BIO_next(bio);
243
244     ret = BIO_write(next, in, inl);
245     copy_flags(bio);
246
247     return ret;
248 }
249
250 static long tls_dump_ctrl(BIO *bio, int cmd, long num, void *ptr)
251 {
252     long ret;
253     BIO *next = BIO_next(bio);
254
255     if (next == NULL)
256         return 0;
257
258     switch (cmd) {
259     case BIO_CTRL_DUP:
260         ret = 0L;
261         break;
262     default:
263         ret = BIO_ctrl(next, cmd, num, ptr);
264         break;
265     }
266     return ret;
267 }
268
269 static int tls_dump_gets(BIO *bio, char *buf, int size)
270 {
271     /* We don't support this - not needed anyway */
272     return -1;
273 }
274
275 static int tls_dump_puts(BIO *bio, const char *str)
276 {
277     return tls_dump_write(bio, str, strlen(str));
278 }
279
280
281 struct mempacket_st {
282     unsigned char *data;
283     int len;
284     unsigned int num;
285     unsigned int type;
286 };
287
288 static void mempacket_free(MEMPACKET *pkt)
289 {
290     if (pkt->data != NULL)
291         OPENSSL_free(pkt->data);
292     OPENSSL_free(pkt);
293 }
294
295 typedef struct mempacket_test_ctx_st {
296     STACK_OF(MEMPACKET) *pkts;
297     unsigned int epoch;
298     unsigned int currrec;
299     unsigned int currpkt;
300     unsigned int lastpkt;
301     unsigned int injected;
302     unsigned int noinject;
303     unsigned int dropepoch;
304     int droprec;
305     int duprec;
306 } MEMPACKET_TEST_CTX;
307
308 static int mempacket_test_new(BIO *bi);
309 static int mempacket_test_free(BIO *a);
310 static int mempacket_test_read(BIO *b, char *out, int outl);
311 static int mempacket_test_write(BIO *b, const char *in, int inl);
312 static long mempacket_test_ctrl(BIO *b, int cmd, long num, void *ptr);
313 static int mempacket_test_gets(BIO *bp, char *buf, int size);
314 static int mempacket_test_puts(BIO *bp, const char *str);
315
316 const BIO_METHOD *bio_s_mempacket_test(void)
317 {
318     if (meth_mem == NULL) {
319         if (!TEST_ptr(meth_mem = BIO_meth_new(BIO_TYPE_MEMPACKET_TEST,
320                                               "Mem Packet Test"))
321             || !TEST_true(BIO_meth_set_write(meth_mem, mempacket_test_write))
322             || !TEST_true(BIO_meth_set_read(meth_mem, mempacket_test_read))
323             || !TEST_true(BIO_meth_set_puts(meth_mem, mempacket_test_puts))
324             || !TEST_true(BIO_meth_set_gets(meth_mem, mempacket_test_gets))
325             || !TEST_true(BIO_meth_set_ctrl(meth_mem, mempacket_test_ctrl))
326             || !TEST_true(BIO_meth_set_create(meth_mem, mempacket_test_new))
327             || !TEST_true(BIO_meth_set_destroy(meth_mem, mempacket_test_free)))
328             return NULL;
329     }
330     return meth_mem;
331 }
332
333 void bio_s_mempacket_test_free(void)
334 {
335     BIO_meth_free(meth_mem);
336 }
337
338 static int mempacket_test_new(BIO *bio)
339 {
340     MEMPACKET_TEST_CTX *ctx;
341
342     if (!TEST_ptr(ctx = OPENSSL_zalloc(sizeof(*ctx))))
343         return 0;
344     if (!TEST_ptr(ctx->pkts = sk_MEMPACKET_new_null())) {
345         OPENSSL_free(ctx);
346         return 0;
347     }
348     ctx->dropepoch = 0;
349     ctx->droprec = -1;
350     BIO_set_init(bio, 1);
351     BIO_set_data(bio, ctx);
352     return 1;
353 }
354
355 static int mempacket_test_free(BIO *bio)
356 {
357     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
358
359     sk_MEMPACKET_pop_free(ctx->pkts, mempacket_free);
360     OPENSSL_free(ctx);
361     BIO_set_data(bio, NULL);
362     BIO_set_init(bio, 0);
363     return 1;
364 }
365
366 /* Record Header values */
367 #define EPOCH_HI        3
368 #define EPOCH_LO        4
369 #define RECORD_SEQUENCE 10
370 #define RECORD_LEN_HI   11
371 #define RECORD_LEN_LO   12
372
373 #define STANDARD_PACKET                 0
374
375 static int mempacket_test_read(BIO *bio, char *out, int outl)
376 {
377     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
378     MEMPACKET *thispkt;
379     unsigned char *rec;
380     int rem;
381     unsigned int seq, offset, len, epoch;
382
383     BIO_clear_retry_flags(bio);
384     thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
385     if (thispkt == NULL || thispkt->num != ctx->currpkt) {
386         /* Probably run out of data */
387         BIO_set_retry_read(bio);
388         return -1;
389     }
390     (void)sk_MEMPACKET_shift(ctx->pkts);
391     ctx->currpkt++;
392
393     if (outl > thispkt->len)
394         outl = thispkt->len;
395
396     if (thispkt->type != INJECT_PACKET_IGNORE_REC_SEQ
397             && (ctx->injected || ctx->droprec >= 0)) {
398         /*
399          * Overwrite the record sequence number. We strictly number them in
400          * the order received. Since we are actually a reliable transport
401          * we know that there won't be any re-ordering. We overwrite to deal
402          * with any packets that have been injected
403          */
404         for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len) {
405             if (rem < DTLS1_RT_HEADER_LENGTH)
406                 return -1;
407             epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO];
408             if (epoch != ctx->epoch) {
409                 ctx->epoch = epoch;
410                 ctx->currrec = 0;
411             }
412             seq = ctx->currrec;
413             offset = 0;
414             do {
415                 rec[RECORD_SEQUENCE - offset] = seq & 0xFF;
416                 seq >>= 8;
417                 offset++;
418             } while (seq > 0);
419
420             len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO])
421                   + DTLS1_RT_HEADER_LENGTH;
422             if (rem < (int)len)
423                 return -1;
424             if (ctx->droprec == (int)ctx->currrec && ctx->dropepoch == epoch) {
425                 if (rem > (int)len)
426                     memmove(rec, rec + len, rem - len);
427                 outl -= len;
428                 ctx->droprec = -1;
429                 if (outl == 0)
430                     BIO_set_retry_read(bio);
431             } else {
432                 rec += len;
433             }
434
435             ctx->currrec++;
436         }
437     }
438
439     memcpy(out, thispkt->data, outl);
440     mempacket_free(thispkt);
441     return outl;
442 }
443
444 int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum,
445                           int type)
446 {
447     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
448     MEMPACKET *thispkt = NULL, *looppkt, *nextpkt, *allpkts[3];
449     int i, duprec;
450     const unsigned char *inu = (const unsigned char *)in;
451     size_t len = ((inu[RECORD_LEN_HI] << 8) | inu[RECORD_LEN_LO])
452                  + DTLS1_RT_HEADER_LENGTH;
453
454     if (ctx == NULL)
455         return -1;
456
457     if ((size_t)inl < len)
458         return -1;
459
460     if ((size_t)inl == len)
461         duprec = 0;
462     else
463         duprec = ctx->duprec > 0;
464
465     /* We don't support arbitrary injection when duplicating records */
466     if (duprec && pktnum != -1)
467         return -1;
468
469     /* We only allow injection before we've started writing any data */
470     if (pktnum >= 0) {
471         if (ctx->noinject)
472             return -1;
473         ctx->injected  = 1;
474     } else {
475         ctx->noinject = 1;
476     }
477
478     for (i = 0; i < (duprec ? 3 : 1); i++) {
479         if (!TEST_ptr(allpkts[i] = OPENSSL_malloc(sizeof(*thispkt))))
480             goto err;
481         thispkt = allpkts[i];
482
483         if (!TEST_ptr(thispkt->data = OPENSSL_malloc(inl)))
484             goto err;
485         /*
486          * If we are duplicating the packet, we duplicate it three times. The
487          * first two times we drop the first record if there are more than one.
488          * In this way we know that libssl will not be able to make progress
489          * until it receives the last packet, and hence will be forced to
490          * buffer these records.
491          */
492         if (duprec && i != 2) {
493             memcpy(thispkt->data, in + len, inl - len);
494             thispkt->len = inl - len;
495         } else {
496             memcpy(thispkt->data, in, inl);
497             thispkt->len = inl;
498         }
499         thispkt->num = (pktnum >= 0) ? (unsigned int)pktnum : ctx->lastpkt + i;
500         thispkt->type = type;
501     }
502
503     for(i = 0; (looppkt = sk_MEMPACKET_value(ctx->pkts, i)) != NULL; i++) {
504         /* Check if we found the right place to insert this packet */
505         if (looppkt->num > thispkt->num) {
506             if (sk_MEMPACKET_insert(ctx->pkts, thispkt, i) == 0)
507                 goto err;
508             /* If we're doing up front injection then we're done */
509             if (pktnum >= 0)
510                 return inl;
511             /*
512              * We need to do some accounting on lastpkt. We increment it first,
513              * but it might now equal the value of injected packets, so we need
514              * to skip over those
515              */
516             ctx->lastpkt++;
517             do {
518                 i++;
519                 nextpkt = sk_MEMPACKET_value(ctx->pkts, i);
520                 if (nextpkt != NULL && nextpkt->num == ctx->lastpkt)
521                     ctx->lastpkt++;
522                 else
523                     return inl;
524             } while(1);
525         } else if (looppkt->num == thispkt->num) {
526             if (!ctx->noinject) {
527                 /* We injected two packets with the same packet number! */
528                 goto err;
529             }
530             ctx->lastpkt++;
531             thispkt->num++;
532         }
533     }
534     /*
535      * We didn't find any packets with a packet number equal to or greater than
536      * this one, so we just add it onto the end
537      */
538     for (i = 0; i < (duprec ? 3 : 1); i++) {
539         thispkt = allpkts[i];
540         if (!sk_MEMPACKET_push(ctx->pkts, thispkt))
541             goto err;
542
543         if (pktnum < 0)
544             ctx->lastpkt++;
545     }
546
547     return inl;
548
549  err:
550     for (i = 0; i < (ctx->duprec > 0 ? 3 : 1); i++)
551         mempacket_free(allpkts[i]);
552     return -1;
553 }
554
555 static int mempacket_test_write(BIO *bio, const char *in, int inl)
556 {
557     return mempacket_test_inject(bio, in, inl, -1, STANDARD_PACKET);
558 }
559
560 static long mempacket_test_ctrl(BIO *bio, int cmd, long num, void *ptr)
561 {
562     long ret = 1;
563     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
564     MEMPACKET *thispkt;
565
566     switch (cmd) {
567     case BIO_CTRL_EOF:
568         ret = (long)(sk_MEMPACKET_num(ctx->pkts) == 0);
569         break;
570     case BIO_CTRL_GET_CLOSE:
571         ret = BIO_get_shutdown(bio);
572         break;
573     case BIO_CTRL_SET_CLOSE:
574         BIO_set_shutdown(bio, (int)num);
575         break;
576     case BIO_CTRL_WPENDING:
577         ret = 0L;
578         break;
579     case BIO_CTRL_PENDING:
580         thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
581         if (thispkt == NULL)
582             ret = 0;
583         else
584             ret = thispkt->len;
585         break;
586     case BIO_CTRL_FLUSH:
587         ret = 1;
588         break;
589     case MEMPACKET_CTRL_SET_DROP_EPOCH:
590         ctx->dropepoch = (unsigned int)num;
591         break;
592     case MEMPACKET_CTRL_SET_DROP_REC:
593         ctx->droprec = (int)num;
594         break;
595     case MEMPACKET_CTRL_GET_DROP_REC:
596         ret = ctx->droprec;
597         break;
598     case MEMPACKET_CTRL_SET_DUPLICATE_REC:
599         ctx->duprec = (int)num;
600         break;
601     case BIO_CTRL_RESET:
602     case BIO_CTRL_DUP:
603     case BIO_CTRL_PUSH:
604     case BIO_CTRL_POP:
605     default:
606         ret = 0;
607         break;
608     }
609     return ret;
610 }
611
612 static int mempacket_test_gets(BIO *bio, char *buf, int size)
613 {
614     /* We don't support this - not needed anyway */
615     return -1;
616 }
617
618 static int mempacket_test_puts(BIO *bio, const char *str)
619 {
620     return mempacket_test_write(bio, str, strlen(str));
621 }
622
623 int create_ssl_ctx_pair(const SSL_METHOD *sm, const SSL_METHOD *cm,
624                         int min_proto_version, int max_proto_version,
625                         SSL_CTX **sctx, SSL_CTX **cctx, char *certfile,
626                         char *privkeyfile)
627 {
628     SSL_CTX *serverctx = NULL;
629     SSL_CTX *clientctx = NULL;
630
631     if (!TEST_ptr(serverctx = SSL_CTX_new(sm))
632             || (cctx != NULL && !TEST_ptr(clientctx = SSL_CTX_new(cm))))
633         goto err;
634
635     if ((min_proto_version > 0
636          && !TEST_true(SSL_CTX_set_min_proto_version(serverctx,
637                                                      min_proto_version)))
638         || (max_proto_version > 0
639             && !TEST_true(SSL_CTX_set_max_proto_version(serverctx,
640                                                         max_proto_version))))
641         goto err;
642     if (clientctx != NULL
643         && ((min_proto_version > 0
644              && !TEST_true(SSL_CTX_set_min_proto_version(clientctx,
645                                                          min_proto_version)))
646             || (max_proto_version > 0
647                 && !TEST_true(SSL_CTX_set_max_proto_version(clientctx,
648                                                             max_proto_version)))))
649         goto err;
650
651     if (certfile != NULL && privkeyfile != NULL) {
652         if (!TEST_int_eq(SSL_CTX_use_certificate_file(serverctx, certfile,
653                                                       SSL_FILETYPE_PEM), 1)
654                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(serverctx,
655                                                             privkeyfile,
656                                                             SSL_FILETYPE_PEM), 1)
657                 || !TEST_int_eq(SSL_CTX_check_private_key(serverctx), 1))
658             goto err;
659     }
660
661 #ifndef OPENSSL_NO_DH
662     SSL_CTX_set_dh_auto(serverctx, 1);
663 #endif
664
665     *sctx = serverctx;
666     if (cctx != NULL)
667         *cctx = clientctx;
668     return 1;
669
670  err:
671     SSL_CTX_free(serverctx);
672     SSL_CTX_free(clientctx);
673     return 0;
674 }
675
676 #define MAXLOOPS    1000000
677
678 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
679 static int set_nb(int fd)
680 {
681     int flags;
682
683     flags = fcntl(fd,F_GETFL,0);
684     if (flags == -1)
685         return flags;
686     flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
687     return flags;
688 }
689
690 int create_test_sockets(int *cfd, int *sfd)
691 {
692     struct sockaddr_in sin;
693     const char *host = "127.0.0.1";
694     int cfd_connected = 0, ret = 0;
695     socklen_t slen = sizeof(sin);
696     int afd = -1;
697
698     *cfd = -1;
699     *sfd = -1;
700
701     memset ((char *) &sin, 0, sizeof(sin));
702     sin.sin_family = AF_INET;
703     sin.sin_addr.s_addr = inet_addr(host);
704
705     afd = socket(AF_INET, SOCK_STREAM, 0);
706     if (afd < 0)
707         return 0;
708
709     if (bind(afd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
710         goto out;
711
712     if (getsockname(afd, (struct sockaddr*)&sin, &slen) < 0)
713         goto out;
714
715     if (listen(afd, 1) < 0)
716         goto out;
717
718     *cfd = socket(AF_INET, SOCK_STREAM, 0);
719     if (*cfd < 0)
720         goto out;
721
722     if (set_nb(afd) == -1)
723         goto out;
724
725     while (*sfd == -1 || !cfd_connected ) {
726         *sfd = accept(afd, NULL, 0);
727         if (*sfd == -1 && errno != EAGAIN)
728             goto out;
729
730         if (!cfd_connected && connect(*cfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
731             goto out;
732         else
733             cfd_connected = 1;
734     }
735
736     if (set_nb(*cfd) == -1 || set_nb(*sfd) == -1)
737         goto out;
738     ret = 1;
739     goto success;
740
741 out:
742         if (*cfd != -1)
743             close(*cfd);
744         if (*sfd != -1)
745             close(*sfd);
746 success:
747         if (afd != -1)
748             close(afd);
749     return ret;
750 }
751
752 int create_ssl_objects2(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
753                           SSL **cssl, int sfd, int cfd)
754 {
755     SSL *serverssl = NULL, *clientssl = NULL;
756     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
757
758     if (*sssl != NULL)
759         serverssl = *sssl;
760     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
761         goto error;
762     if (*cssl != NULL)
763         clientssl = *cssl;
764     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
765         goto error;
766
767     if (!TEST_ptr(s_to_c_bio = BIO_new_socket(sfd, BIO_NOCLOSE))
768             || !TEST_ptr(c_to_s_bio = BIO_new_socket(cfd, BIO_NOCLOSE)))
769         goto error;
770
771     SSL_set_bio(clientssl, c_to_s_bio, c_to_s_bio);
772     SSL_set_bio(serverssl, s_to_c_bio, s_to_c_bio);
773     *sssl = serverssl;
774     *cssl = clientssl;
775     return 1;
776
777  error:
778     SSL_free(serverssl);
779     SSL_free(clientssl);
780     BIO_free(s_to_c_bio);
781     BIO_free(c_to_s_bio);
782     return 0;
783 }
784 #endif
785
786 /*
787  * NOTE: Transfers control of the BIOs - this function will free them on error
788  */
789 int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
790                           SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio)
791 {
792     SSL *serverssl = NULL, *clientssl = NULL;
793     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
794
795     if (*sssl != NULL)
796         serverssl = *sssl;
797     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
798         goto error;
799     if (*cssl != NULL)
800         clientssl = *cssl;
801     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
802         goto error;
803
804     if (SSL_is_dtls(clientssl)) {
805         if (!TEST_ptr(s_to_c_bio = BIO_new(bio_s_mempacket_test()))
806                 || !TEST_ptr(c_to_s_bio = BIO_new(bio_s_mempacket_test())))
807             goto error;
808     } else {
809         if (!TEST_ptr(s_to_c_bio = BIO_new(BIO_s_mem()))
810                 || !TEST_ptr(c_to_s_bio = BIO_new(BIO_s_mem())))
811             goto error;
812     }
813
814     if (s_to_c_fbio != NULL
815             && !TEST_ptr(s_to_c_bio = BIO_push(s_to_c_fbio, s_to_c_bio)))
816         goto error;
817     if (c_to_s_fbio != NULL
818             && !TEST_ptr(c_to_s_bio = BIO_push(c_to_s_fbio, c_to_s_bio)))
819         goto error;
820
821     /* Set Non-blocking IO behaviour */
822     BIO_set_mem_eof_return(s_to_c_bio, -1);
823     BIO_set_mem_eof_return(c_to_s_bio, -1);
824
825     /* Up ref these as we are passing them to two SSL objects */
826     SSL_set_bio(serverssl, c_to_s_bio, s_to_c_bio);
827     BIO_up_ref(s_to_c_bio);
828     BIO_up_ref(c_to_s_bio);
829     SSL_set_bio(clientssl, s_to_c_bio, c_to_s_bio);
830     *sssl = serverssl;
831     *cssl = clientssl;
832     return 1;
833
834  error:
835     SSL_free(serverssl);
836     SSL_free(clientssl);
837     BIO_free(s_to_c_bio);
838     BIO_free(c_to_s_bio);
839     BIO_free(s_to_c_fbio);
840     BIO_free(c_to_s_fbio);
841
842     return 0;
843 }
844
845 /*
846  * Create an SSL connection, but does not ready any post-handshake
847  * NewSessionTicket messages.
848  * If |read| is set and we're using DTLS then we will attempt to SSL_read on
849  * the connection once we've completed one half of it, to ensure any retransmits
850  * get triggered.
851  */
852 int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want,
853                                int read)
854 {
855     int retc = -1, rets = -1, err, abortctr = 0;
856     int clienterr = 0, servererr = 0;
857     int isdtls = SSL_is_dtls(serverssl);
858
859     do {
860         err = SSL_ERROR_WANT_WRITE;
861         while (!clienterr && retc <= 0 && err == SSL_ERROR_WANT_WRITE) {
862             retc = SSL_connect(clientssl);
863             if (retc <= 0)
864                 err = SSL_get_error(clientssl, retc);
865         }
866
867         if (!clienterr && retc <= 0 && err != SSL_ERROR_WANT_READ) {
868             TEST_info("SSL_connect() failed %d, %d", retc, err);
869             clienterr = 1;
870         }
871         if (want != SSL_ERROR_NONE && err == want)
872             return 0;
873
874         err = SSL_ERROR_WANT_WRITE;
875         while (!servererr && rets <= 0 && err == SSL_ERROR_WANT_WRITE) {
876             rets = SSL_accept(serverssl);
877             if (rets <= 0)
878                 err = SSL_get_error(serverssl, rets);
879         }
880
881         if (!servererr && rets <= 0
882                 && err != SSL_ERROR_WANT_READ
883                 && err != SSL_ERROR_WANT_X509_LOOKUP) {
884             TEST_info("SSL_accept() failed %d, %d", rets, err);
885             servererr = 1;
886         }
887         if (want != SSL_ERROR_NONE && err == want)
888             return 0;
889         if (clienterr && servererr)
890             return 0;
891         if (isdtls && read) {
892             unsigned char buf[20];
893
894             /* Trigger any retransmits that may be appropriate */
895             if (rets > 0 && retc <= 0) {
896                 if (SSL_read(serverssl, buf, sizeof(buf)) > 0) {
897                     /* We don't expect this to succeed! */
898                     TEST_info("Unexpected SSL_read() success!");
899                     return 0;
900                 }
901             }
902             if (retc > 0 && rets <= 0) {
903                 if (SSL_read(clientssl, buf, sizeof(buf)) > 0) {
904                     /* We don't expect this to succeed! */
905                     TEST_info("Unexpected SSL_read() success!");
906                     return 0;
907                 }
908             }
909         }
910         if (++abortctr == MAXLOOPS) {
911             TEST_info("No progress made");
912             return 0;
913         }
914         if (isdtls && abortctr <= 50 && (abortctr % 10) == 0) {
915             /*
916              * It looks like we're just spinning. Pause for a short period to
917              * give the DTLS timer a chance to do something. We only do this for
918              * the first few times to prevent hangs.
919              */
920             ossl_sleep(50);
921         }
922     } while (retc <=0 || rets <= 0);
923
924     return 1;
925 }
926
927 /*
928  * Create an SSL connection including any post handshake NewSessionTicket
929  * messages.
930  */
931 int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want)
932 {
933     int i;
934     unsigned char buf;
935     size_t readbytes;
936
937     if (!create_bare_ssl_connection(serverssl, clientssl, want, 1))
938         return 0;
939
940     /*
941      * We attempt to read some data on the client side which we expect to fail.
942      * This will ensure we have received the NewSessionTicket in TLSv1.3 where
943      * appropriate. We do this twice because there are 2 NewSesionTickets.
944      */
945     for (i = 0; i < 2; i++) {
946         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
947             if (!TEST_ulong_eq(readbytes, 0))
948                 return 0;
949         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
950                                 SSL_ERROR_WANT_READ)) {
951             return 0;
952         }
953     }
954
955     return 1;
956 }
957
958 void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl)
959 {
960     SSL_shutdown(clientssl);
961     SSL_shutdown(serverssl);
962     SSL_free(serverssl);
963     SSL_free(clientssl);
964 }