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