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