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