xref: /openssl/test/helpers/ssltestlib.c (revision 2bb83824)
1 /*
2  * Copyright 2016-2024 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 /*
11  * We need access to the deprecated low level ENGINE APIs for legacy purposes
12  * when the deprecated calls are not hidden
13  */
14 #ifndef OPENSSL_NO_DEPRECATED_3_0
15 # define OPENSSL_SUPPRESS_DEPRECATED
16 #endif
17 
18 #include <string.h>
19 
20 #include <openssl/engine.h>
21 #include "internal/e_os.h"
22 #include "internal/nelem.h"
23 #include "ssltestlib.h"
24 #include "../testutil.h"
25 
26 #if (!defined(OPENSSL_NO_KTLS) || !defined(OPENSSL_NO_QUIC)) && !defined(OPENSSL_NO_POSIX_IO) && !defined(OPENSSL_NO_SOCK)
27 # define OSSL_USE_SOCKETS 1
28 # include "internal/e_winsock.h"
29 # include "internal/sockets.h"
30 # include <openssl/bio.h>
31 #endif
32 
33 static int tls_dump_new(BIO *bi);
34 static int tls_dump_free(BIO *a);
35 static int tls_dump_read(BIO *b, char *out, int outl);
36 static int tls_dump_write(BIO *b, const char *in, int inl);
37 static long tls_dump_ctrl(BIO *b, int cmd, long num, void *ptr);
38 static int tls_dump_gets(BIO *bp, char *buf, int size);
39 static int tls_dump_puts(BIO *bp, const char *str);
40 
41 /* Choose a sufficiently large type likely to be unused for this custom BIO */
42 #define BIO_TYPE_TLS_DUMP_FILTER   (0x80 | BIO_TYPE_FILTER)
43 #define BIO_TYPE_MEMPACKET_TEST    0x81
44 #define BIO_TYPE_ALWAYS_RETRY      0x82
45 #define BIO_TYPE_MAYBE_RETRY       (0x83 | BIO_TYPE_FILTER)
46 
47 static BIO_METHOD *method_tls_dump = NULL;
48 static BIO_METHOD *meth_mem = NULL;
49 static BIO_METHOD *meth_always_retry = NULL;
50 static BIO_METHOD *meth_maybe_retry = NULL;
51 static int retry_err = -1;
52 
53 /* Note: Not thread safe! */
bio_f_tls_dump_filter(void)54 const BIO_METHOD *bio_f_tls_dump_filter(void)
55 {
56     if (method_tls_dump == NULL) {
57         method_tls_dump = BIO_meth_new(BIO_TYPE_TLS_DUMP_FILTER,
58                                         "TLS dump filter");
59         if (method_tls_dump == NULL
60             || !BIO_meth_set_write(method_tls_dump, tls_dump_write)
61             || !BIO_meth_set_read(method_tls_dump, tls_dump_read)
62             || !BIO_meth_set_puts(method_tls_dump, tls_dump_puts)
63             || !BIO_meth_set_gets(method_tls_dump, tls_dump_gets)
64             || !BIO_meth_set_ctrl(method_tls_dump, tls_dump_ctrl)
65             || !BIO_meth_set_create(method_tls_dump, tls_dump_new)
66             || !BIO_meth_set_destroy(method_tls_dump, tls_dump_free))
67             return NULL;
68     }
69     return method_tls_dump;
70 }
71 
bio_f_tls_dump_filter_free(void)72 void bio_f_tls_dump_filter_free(void)
73 {
74     BIO_meth_free(method_tls_dump);
75 }
76 
tls_dump_new(BIO * bio)77 static int tls_dump_new(BIO *bio)
78 {
79     BIO_set_init(bio, 1);
80     return 1;
81 }
82 
tls_dump_free(BIO * bio)83 static int tls_dump_free(BIO *bio)
84 {
85     BIO_set_init(bio, 0);
86 
87     return 1;
88 }
89 
copy_flags(BIO * bio)90 static void copy_flags(BIO *bio)
91 {
92     int flags;
93     BIO *next = BIO_next(bio);
94 
95     flags = BIO_test_flags(next, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
96     BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_RWS);
97     BIO_set_flags(bio, flags);
98 }
99 
100 #define RECORD_CONTENT_TYPE     0
101 #define RECORD_VERSION_HI       1
102 #define RECORD_VERSION_LO       2
103 #define RECORD_EPOCH_HI         3
104 #define RECORD_EPOCH_LO         4
105 #define RECORD_SEQUENCE_START   5
106 #define RECORD_SEQUENCE_END     10
107 #define RECORD_LEN_HI           11
108 #define RECORD_LEN_LO           12
109 
110 #define MSG_TYPE                0
111 #define MSG_LEN_HI              1
112 #define MSG_LEN_MID             2
113 #define MSG_LEN_LO              3
114 #define MSG_SEQ_HI              4
115 #define MSG_SEQ_LO              5
116 #define MSG_FRAG_OFF_HI         6
117 #define MSG_FRAG_OFF_MID        7
118 #define MSG_FRAG_OFF_LO         8
119 #define MSG_FRAG_LEN_HI         9
120 #define MSG_FRAG_LEN_MID        10
121 #define MSG_FRAG_LEN_LO         11
122 
123 
dump_data(const char * data,int len)124 static void dump_data(const char *data, int len)
125 {
126     int rem, i, content, reclen, msglen, fragoff, fraglen, epoch;
127     unsigned char *rec;
128 
129     printf("---- START OF PACKET ----\n");
130 
131     rem = len;
132     rec = (unsigned char *)data;
133 
134     while (rem > 0) {
135         if (rem != len)
136             printf("*\n");
137         printf("*---- START OF RECORD ----\n");
138         if (rem < DTLS1_RT_HEADER_LENGTH) {
139             printf("*---- RECORD TRUNCATED ----\n");
140             break;
141         }
142         content = rec[RECORD_CONTENT_TYPE];
143         printf("** Record Content-type: %d\n", content);
144         printf("** Record Version: %02x%02x\n",
145                rec[RECORD_VERSION_HI], rec[RECORD_VERSION_LO]);
146         epoch = (rec[RECORD_EPOCH_HI] << 8) | rec[RECORD_EPOCH_LO];
147         printf("** Record Epoch: %d\n", epoch);
148         printf("** Record Sequence: ");
149         for (i = RECORD_SEQUENCE_START; i <= RECORD_SEQUENCE_END; i++)
150             printf("%02x", rec[i]);
151         reclen = (rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO];
152         printf("\n** Record Length: %d\n", reclen);
153 
154         /* Now look at message */
155         rec += DTLS1_RT_HEADER_LENGTH;
156         rem -= DTLS1_RT_HEADER_LENGTH;
157         if (content == SSL3_RT_HANDSHAKE) {
158             printf("**---- START OF HANDSHAKE MESSAGE FRAGMENT ----\n");
159             if (epoch > 0) {
160                 printf("**---- HANDSHAKE MESSAGE FRAGMENT ENCRYPTED ----\n");
161             } else if (rem < DTLS1_HM_HEADER_LENGTH
162                     || reclen < DTLS1_HM_HEADER_LENGTH) {
163                 printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
164             } else {
165                 printf("*** Message Type: %d\n", rec[MSG_TYPE]);
166                 msglen = (rec[MSG_LEN_HI] << 16) | (rec[MSG_LEN_MID] << 8)
167                          | rec[MSG_LEN_LO];
168                 printf("*** Message Length: %d\n", msglen);
169                 printf("*** Message sequence: %d\n",
170                        (rec[MSG_SEQ_HI] << 8) | rec[MSG_SEQ_LO]);
171                 fragoff = (rec[MSG_FRAG_OFF_HI] << 16)
172                           | (rec[MSG_FRAG_OFF_MID] << 8)
173                           | rec[MSG_FRAG_OFF_LO];
174                 printf("*** Message Fragment offset: %d\n", fragoff);
175                 fraglen = (rec[MSG_FRAG_LEN_HI] << 16)
176                           | (rec[MSG_FRAG_LEN_MID] << 8)
177                           | rec[MSG_FRAG_LEN_LO];
178                 printf("*** Message Fragment len: %d\n", fraglen);
179                 if (fragoff + fraglen > msglen)
180                     printf("***---- HANDSHAKE MESSAGE FRAGMENT INVALID ----\n");
181                 else if (reclen < fraglen)
182                     printf("**---- HANDSHAKE MESSAGE FRAGMENT TRUNCATED ----\n");
183                 else
184                     printf("**---- END OF HANDSHAKE MESSAGE FRAGMENT ----\n");
185             }
186         }
187         if (rem < reclen) {
188             printf("*---- RECORD TRUNCATED ----\n");
189             rem = 0;
190         } else {
191             rec += reclen;
192             rem -= reclen;
193             printf("*---- END OF RECORD ----\n");
194         }
195     }
196     printf("---- END OF PACKET ----\n\n");
197     fflush(stdout);
198 }
199 
tls_dump_read(BIO * bio,char * out,int outl)200 static int tls_dump_read(BIO *bio, char *out, int outl)
201 {
202     int ret;
203     BIO *next = BIO_next(bio);
204 
205     ret = BIO_read(next, out, outl);
206     copy_flags(bio);
207 
208     if (ret > 0) {
209         dump_data(out, ret);
210     }
211 
212     return ret;
213 }
214 
tls_dump_write(BIO * bio,const char * in,int inl)215 static int tls_dump_write(BIO *bio, const char *in, int inl)
216 {
217     int ret;
218     BIO *next = BIO_next(bio);
219 
220     ret = BIO_write(next, in, inl);
221     copy_flags(bio);
222 
223     return ret;
224 }
225 
tls_dump_ctrl(BIO * bio,int cmd,long num,void * ptr)226 static long tls_dump_ctrl(BIO *bio, int cmd, long num, void *ptr)
227 {
228     long ret;
229     BIO *next = BIO_next(bio);
230 
231     if (next == NULL)
232         return 0;
233 
234     switch (cmd) {
235     case BIO_CTRL_DUP:
236         ret = 0L;
237         break;
238     default:
239         ret = BIO_ctrl(next, cmd, num, ptr);
240         break;
241     }
242     return ret;
243 }
244 
tls_dump_gets(BIO * bio,char * buf,int size)245 static int tls_dump_gets(BIO *bio, char *buf, int size)
246 {
247     /* We don't support this - not needed anyway */
248     return -1;
249 }
250 
tls_dump_puts(BIO * bio,const char * str)251 static int tls_dump_puts(BIO *bio, const char *str)
252 {
253     return tls_dump_write(bio, str, strlen(str));
254 }
255 
256 
257 struct mempacket_st {
258     unsigned char *data;
259     int len;
260     unsigned int num;
261     unsigned int type;
262 };
263 
mempacket_free(MEMPACKET * pkt)264 static void mempacket_free(MEMPACKET *pkt)
265 {
266     if (pkt->data != NULL)
267         OPENSSL_free(pkt->data);
268     OPENSSL_free(pkt);
269 }
270 
271 typedef struct mempacket_test_ctx_st {
272     STACK_OF(MEMPACKET) *pkts;
273     uint16_t epoch;
274     unsigned int currrec;
275     unsigned int currpkt;
276     unsigned int lastpkt;
277     unsigned int injected;
278     unsigned int noinject;
279     unsigned int dropepoch;
280     int droprec;
281     int duprec;
282 } MEMPACKET_TEST_CTX;
283 
284 static int mempacket_test_new(BIO *bi);
285 static int mempacket_test_free(BIO *a);
286 static int mempacket_test_read(BIO *b, char *out, int outl);
287 static int mempacket_test_write(BIO *b, const char *in, int inl);
288 static long mempacket_test_ctrl(BIO *b, int cmd, long num, void *ptr);
289 static int mempacket_test_gets(BIO *bp, char *buf, int size);
290 static int mempacket_test_puts(BIO *bp, const char *str);
291 
bio_s_mempacket_test(void)292 const BIO_METHOD *bio_s_mempacket_test(void)
293 {
294     if (meth_mem == NULL) {
295         if (!TEST_ptr(meth_mem = BIO_meth_new(BIO_TYPE_MEMPACKET_TEST,
296                                               "Mem Packet Test"))
297             || !TEST_true(BIO_meth_set_write(meth_mem, mempacket_test_write))
298             || !TEST_true(BIO_meth_set_read(meth_mem, mempacket_test_read))
299             || !TEST_true(BIO_meth_set_puts(meth_mem, mempacket_test_puts))
300             || !TEST_true(BIO_meth_set_gets(meth_mem, mempacket_test_gets))
301             || !TEST_true(BIO_meth_set_ctrl(meth_mem, mempacket_test_ctrl))
302             || !TEST_true(BIO_meth_set_create(meth_mem, mempacket_test_new))
303             || !TEST_true(BIO_meth_set_destroy(meth_mem, mempacket_test_free)))
304             return NULL;
305     }
306     return meth_mem;
307 }
308 
bio_s_mempacket_test_free(void)309 void bio_s_mempacket_test_free(void)
310 {
311     BIO_meth_free(meth_mem);
312 }
313 
mempacket_test_new(BIO * bio)314 static int mempacket_test_new(BIO *bio)
315 {
316     MEMPACKET_TEST_CTX *ctx;
317 
318     if (!TEST_ptr(ctx = OPENSSL_zalloc(sizeof(*ctx))))
319         return 0;
320     if (!TEST_ptr(ctx->pkts = sk_MEMPACKET_new_null())) {
321         OPENSSL_free(ctx);
322         return 0;
323     }
324     ctx->dropepoch = 0;
325     ctx->droprec = -1;
326     BIO_set_init(bio, 1);
327     BIO_set_data(bio, ctx);
328     return 1;
329 }
330 
mempacket_test_free(BIO * bio)331 static int mempacket_test_free(BIO *bio)
332 {
333     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
334 
335     sk_MEMPACKET_pop_free(ctx->pkts, mempacket_free);
336     OPENSSL_free(ctx);
337     BIO_set_data(bio, NULL);
338     BIO_set_init(bio, 0);
339     return 1;
340 }
341 
342 /* Record Header values */
343 #define EPOCH_HI        3
344 #define EPOCH_LO        4
345 #define RECORD_SEQUENCE 10
346 #define RECORD_LEN_HI   11
347 #define RECORD_LEN_LO   12
348 
349 #define STANDARD_PACKET                 0
350 
mempacket_test_read(BIO * bio,char * out,int outl)351 static int mempacket_test_read(BIO *bio, char *out, int outl)
352 {
353     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
354     MEMPACKET *thispkt;
355     unsigned char *rec;
356     int rem;
357     unsigned int seq, offset, len, epoch;
358 
359     BIO_clear_retry_flags(bio);
360     if ((thispkt = sk_MEMPACKET_value(ctx->pkts, 0)) == NULL
361         || thispkt->num != ctx->currpkt) {
362         /* Probably run out of data */
363         BIO_set_retry_read(bio);
364         return -1;
365     }
366     (void)sk_MEMPACKET_shift(ctx->pkts);
367     ctx->currpkt++;
368 
369     if (outl > thispkt->len)
370         outl = thispkt->len;
371 
372     if (thispkt->type != INJECT_PACKET_IGNORE_REC_SEQ
373             && (ctx->injected || ctx->droprec >= 0)) {
374         /*
375          * Overwrite the record sequence number. We strictly number them in
376          * the order received. Since we are actually a reliable transport
377          * we know that there won't be any re-ordering. We overwrite to deal
378          * with any packets that have been injected
379          */
380         for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len) {
381             if (rem < DTLS1_RT_HEADER_LENGTH)
382                 return -1;
383             epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO];
384             if (epoch != ctx->epoch) {
385                 ctx->epoch = epoch;
386                 ctx->currrec = 0;
387             }
388             seq = ctx->currrec;
389             offset = 0;
390             do {
391                 rec[RECORD_SEQUENCE - offset] = seq & 0xFF;
392                 seq >>= 8;
393                 offset++;
394             } while (seq > 0);
395 
396             len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO])
397                   + DTLS1_RT_HEADER_LENGTH;
398             if (rem < (int)len)
399                 return -1;
400             if (ctx->droprec == (int)ctx->currrec && ctx->dropepoch == epoch) {
401                 if (rem > (int)len)
402                     memmove(rec, rec + len, rem - len);
403                 outl -= len;
404                 ctx->droprec = -1;
405                 if (outl == 0)
406                     BIO_set_retry_read(bio);
407             } else {
408                 rec += len;
409             }
410 
411             ctx->currrec++;
412         }
413     }
414 
415     memcpy(out, thispkt->data, outl);
416     mempacket_free(thispkt);
417     return outl;
418 }
419 
420 /*
421  * Look for records from different epochs in the last datagram and swap them
422  * around
423  */
mempacket_swap_epoch(BIO * bio)424 int mempacket_swap_epoch(BIO *bio)
425 {
426     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
427     MEMPACKET *thispkt;
428     int rem, len, prevlen = 0, pktnum;
429     unsigned char *rec, *prevrec = NULL, *tmp;
430     unsigned int epoch;
431     int numpkts = sk_MEMPACKET_num(ctx->pkts);
432 
433     if (numpkts <= 0)
434         return 0;
435 
436     /*
437      * If there are multiple packets we only look in the last one. This should
438      * always be the one where any epoch change occurs.
439      */
440     thispkt = sk_MEMPACKET_value(ctx->pkts, numpkts - 1);
441     if (thispkt == NULL)
442         return 0;
443 
444     for (rem = thispkt->len, rec = thispkt->data; rem > 0; rem -= len, rec += len) {
445         if (rem < DTLS1_RT_HEADER_LENGTH)
446             return 0;
447         epoch = (rec[EPOCH_HI] << 8) | rec[EPOCH_LO];
448         len = ((rec[RECORD_LEN_HI] << 8) | rec[RECORD_LEN_LO])
449                 + DTLS1_RT_HEADER_LENGTH;
450         if (rem < len)
451             return 0;
452 
453         /* Assumes the epoch change does not happen on the first record */
454         if (epoch != ctx->epoch) {
455             if (prevrec == NULL)
456                 return 0;
457 
458             /*
459              * We found 2 records with different epochs. Take a copy of the
460              * earlier record
461              */
462             tmp = OPENSSL_malloc(prevlen);
463             if (tmp == NULL)
464                 return 0;
465 
466             memcpy(tmp, prevrec, prevlen);
467             /*
468              * Move everything from this record onwards, including any trailing
469              * records, and overwrite the earlier record
470              */
471             memmove(prevrec, rec, rem);
472             thispkt->len -= prevlen;
473             pktnum = thispkt->num;
474 
475             /*
476              * Create a new packet for the earlier record that we took out and
477              * add it to the end of the packet list.
478              */
479             thispkt = OPENSSL_malloc(sizeof(*thispkt));
480             if (thispkt == NULL) {
481                 OPENSSL_free(tmp);
482                 return 0;
483             }
484             thispkt->type = INJECT_PACKET;
485             thispkt->data = tmp;
486             thispkt->len = prevlen;
487             thispkt->num = pktnum + 1;
488             if (sk_MEMPACKET_insert(ctx->pkts, thispkt, numpkts) <= 0) {
489                 OPENSSL_free(tmp);
490                 OPENSSL_free(thispkt);
491                 return 0;
492             }
493 
494             return 1;
495         }
496         prevrec = rec;
497         prevlen = len;
498     }
499 
500     return 0;
501 }
502 
503 /* Move packet from position s to position d in the list (d < s) */
mempacket_move_packet(BIO * bio,int d,int s)504 int mempacket_move_packet(BIO *bio, int d, int s)
505 {
506     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
507     MEMPACKET *thispkt;
508     int numpkts = sk_MEMPACKET_num(ctx->pkts);
509     int i;
510 
511     if (d >= s)
512         return 0;
513 
514     /* We need at least s + 1 packets to be able to swap them */
515     if (numpkts <= s)
516         return 0;
517 
518     /* Get the packet at position s */
519     thispkt = sk_MEMPACKET_value(ctx->pkts, s);
520     if (thispkt == NULL)
521         return 0;
522 
523     /* Remove and re-add it */
524     if (sk_MEMPACKET_delete(ctx->pkts, s) != thispkt)
525         return 0;
526 
527     thispkt->num -= (s - d);
528     if (sk_MEMPACKET_insert(ctx->pkts, thispkt, d) <= 0)
529         return 0;
530 
531     /* Increment the packet numbers for moved packets */
532     for (i = d + 1; i <= s; i++) {
533         thispkt = sk_MEMPACKET_value(ctx->pkts, i);
534         thispkt->num++;
535     }
536     return 1;
537 }
538 
mempacket_test_inject(BIO * bio,const char * in,int inl,int pktnum,int type)539 int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum,
540                           int type)
541 {
542     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
543     MEMPACKET *thispkt = NULL, *looppkt, *nextpkt, *allpkts[3];
544     int i, duprec;
545     const unsigned char *inu = (const unsigned char *)in;
546     size_t len = ((inu[RECORD_LEN_HI] << 8) | inu[RECORD_LEN_LO])
547                  + DTLS1_RT_HEADER_LENGTH;
548 
549     if (ctx == NULL)
550         return -1;
551 
552     if ((size_t)inl < len)
553         return -1;
554 
555     if ((size_t)inl == len)
556         duprec = 0;
557     else
558         duprec = ctx->duprec > 0;
559 
560     /* We don't support arbitrary injection when duplicating records */
561     if (duprec && pktnum != -1)
562         return -1;
563 
564     /* We only allow injection before we've started writing any data */
565     if (pktnum >= 0) {
566         if (ctx->noinject)
567             return -1;
568         ctx->injected  = 1;
569     } else {
570         ctx->noinject = 1;
571     }
572 
573     for (i = 0; i < (duprec ? 3 : 1); i++) {
574         if (!TEST_ptr(allpkts[i] = OPENSSL_malloc(sizeof(*thispkt))))
575             goto err;
576         thispkt = allpkts[i];
577 
578         if (!TEST_ptr(thispkt->data = OPENSSL_malloc(inl)))
579             goto err;
580         /*
581          * If we are duplicating the packet, we duplicate it three times. The
582          * first two times we drop the first record if there are more than one.
583          * In this way we know that libssl will not be able to make progress
584          * until it receives the last packet, and hence will be forced to
585          * buffer these records.
586          */
587         if (duprec && i != 2) {
588             memcpy(thispkt->data, in + len, inl - len);
589             thispkt->len = inl - len;
590         } else {
591             memcpy(thispkt->data, in, inl);
592             thispkt->len = inl;
593         }
594         thispkt->num = (pktnum >= 0) ? (unsigned int)pktnum : ctx->lastpkt + i;
595         thispkt->type = type;
596     }
597 
598     for (i = 0; i < sk_MEMPACKET_num(ctx->pkts); i++) {
599         if (!TEST_ptr(looppkt = sk_MEMPACKET_value(ctx->pkts, i)))
600             goto err;
601         /* Check if we found the right place to insert this packet */
602         if (looppkt->num > thispkt->num) {
603             if (sk_MEMPACKET_insert(ctx->pkts, thispkt, i) == 0)
604                 goto err;
605             /* If we're doing up front injection then we're done */
606             if (pktnum >= 0)
607                 return inl;
608             /*
609              * We need to do some accounting on lastpkt. We increment it first,
610              * but it might now equal the value of injected packets, so we need
611              * to skip over those
612              */
613             ctx->lastpkt++;
614             do {
615                 i++;
616                 nextpkt = sk_MEMPACKET_value(ctx->pkts, i);
617                 if (nextpkt != NULL && nextpkt->num == ctx->lastpkt)
618                     ctx->lastpkt++;
619                 else
620                     return inl;
621             } while(1);
622         } else if (looppkt->num == thispkt->num) {
623             if (!ctx->noinject) {
624                 /* We injected two packets with the same packet number! */
625                 goto err;
626             }
627             ctx->lastpkt++;
628             thispkt->num++;
629         }
630     }
631     /*
632      * We didn't find any packets with a packet number equal to or greater than
633      * this one, so we just add it onto the end
634      */
635     for (i = 0; i < (duprec ? 3 : 1); i++) {
636         thispkt = allpkts[i];
637         if (!sk_MEMPACKET_push(ctx->pkts, thispkt))
638             goto err;
639 
640         if (pktnum < 0)
641             ctx->lastpkt++;
642     }
643 
644     return inl;
645 
646  err:
647     for (i = 0; i < (ctx->duprec > 0 ? 3 : 1); i++)
648         mempacket_free(allpkts[i]);
649     return -1;
650 }
651 
mempacket_test_write(BIO * bio,const char * in,int inl)652 static int mempacket_test_write(BIO *bio, const char *in, int inl)
653 {
654     return mempacket_test_inject(bio, in, inl, -1, STANDARD_PACKET);
655 }
656 
mempacket_test_ctrl(BIO * bio,int cmd,long num,void * ptr)657 static long mempacket_test_ctrl(BIO *bio, int cmd, long num, void *ptr)
658 {
659     long ret = 1;
660     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
661     MEMPACKET *thispkt;
662 
663     switch (cmd) {
664     case BIO_CTRL_EOF:
665         ret = (long)(sk_MEMPACKET_num(ctx->pkts) == 0);
666         break;
667     case BIO_CTRL_GET_CLOSE:
668         ret = BIO_get_shutdown(bio);
669         break;
670     case BIO_CTRL_SET_CLOSE:
671         BIO_set_shutdown(bio, (int)num);
672         break;
673     case BIO_CTRL_WPENDING:
674         ret = 0L;
675         break;
676     case BIO_CTRL_PENDING:
677         thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
678         if (thispkt == NULL)
679             ret = 0;
680         else
681             ret = thispkt->len;
682         break;
683     case BIO_CTRL_FLUSH:
684         ret = 1;
685         break;
686     case MEMPACKET_CTRL_SET_DROP_EPOCH:
687         ctx->dropepoch = (unsigned int)num;
688         break;
689     case MEMPACKET_CTRL_SET_DROP_REC:
690         ctx->droprec = (int)num;
691         break;
692     case MEMPACKET_CTRL_GET_DROP_REC:
693         ret = ctx->droprec;
694         break;
695     case MEMPACKET_CTRL_SET_DUPLICATE_REC:
696         ctx->duprec = (int)num;
697         break;
698     case BIO_CTRL_RESET:
699     case BIO_CTRL_DUP:
700     case BIO_CTRL_PUSH:
701     case BIO_CTRL_POP:
702     default:
703         ret = 0;
704         break;
705     }
706     return ret;
707 }
708 
mempacket_test_gets(BIO * bio,char * buf,int size)709 static int mempacket_test_gets(BIO *bio, char *buf, int size)
710 {
711     /* We don't support this - not needed anyway */
712     return -1;
713 }
714 
mempacket_test_puts(BIO * bio,const char * str)715 static int mempacket_test_puts(BIO *bio, const char *str)
716 {
717     return mempacket_test_write(bio, str, strlen(str));
718 }
719 
720 static int always_retry_new(BIO *bi);
721 static int always_retry_free(BIO *a);
722 static int always_retry_read(BIO *b, char *out, int outl);
723 static int always_retry_write(BIO *b, const char *in, int inl);
724 static long always_retry_ctrl(BIO *b, int cmd, long num, void *ptr);
725 static int always_retry_gets(BIO *bp, char *buf, int size);
726 static int always_retry_puts(BIO *bp, const char *str);
727 
bio_s_always_retry(void)728 const BIO_METHOD *bio_s_always_retry(void)
729 {
730     if (meth_always_retry == NULL) {
731         if (!TEST_ptr(meth_always_retry = BIO_meth_new(BIO_TYPE_ALWAYS_RETRY,
732                                                        "Always Retry"))
733             || !TEST_true(BIO_meth_set_write(meth_always_retry,
734                                              always_retry_write))
735             || !TEST_true(BIO_meth_set_read(meth_always_retry,
736                                             always_retry_read))
737             || !TEST_true(BIO_meth_set_puts(meth_always_retry,
738                                             always_retry_puts))
739             || !TEST_true(BIO_meth_set_gets(meth_always_retry,
740                                             always_retry_gets))
741             || !TEST_true(BIO_meth_set_ctrl(meth_always_retry,
742                                             always_retry_ctrl))
743             || !TEST_true(BIO_meth_set_create(meth_always_retry,
744                                               always_retry_new))
745             || !TEST_true(BIO_meth_set_destroy(meth_always_retry,
746                                                always_retry_free)))
747             return NULL;
748     }
749     return meth_always_retry;
750 }
751 
bio_s_always_retry_free(void)752 void bio_s_always_retry_free(void)
753 {
754     BIO_meth_free(meth_always_retry);
755 }
756 
always_retry_new(BIO * bio)757 static int always_retry_new(BIO *bio)
758 {
759     BIO_set_init(bio, 1);
760     return 1;
761 }
762 
always_retry_free(BIO * bio)763 static int always_retry_free(BIO *bio)
764 {
765     BIO_set_data(bio, NULL);
766     BIO_set_init(bio, 0);
767     return 1;
768 }
769 
set_always_retry_err_val(int err)770 void set_always_retry_err_val(int err)
771 {
772     retry_err = err;
773 }
774 
always_retry_read(BIO * bio,char * out,int outl)775 static int always_retry_read(BIO *bio, char *out, int outl)
776 {
777     BIO_set_retry_read(bio);
778     return retry_err;
779 }
780 
always_retry_write(BIO * bio,const char * in,int inl)781 static int always_retry_write(BIO *bio, const char *in, int inl)
782 {
783     BIO_set_retry_write(bio);
784     return retry_err;
785 }
786 
always_retry_ctrl(BIO * bio,int cmd,long num,void * ptr)787 static long always_retry_ctrl(BIO *bio, int cmd, long num, void *ptr)
788 {
789     long ret = 1;
790 
791     switch (cmd) {
792     case BIO_CTRL_FLUSH:
793         BIO_set_retry_write(bio);
794         /* fall through */
795     case BIO_CTRL_EOF:
796     case BIO_CTRL_RESET:
797     case BIO_CTRL_DUP:
798     case BIO_CTRL_PUSH:
799     case BIO_CTRL_POP:
800     default:
801         ret = 0;
802         break;
803     }
804     return ret;
805 }
806 
always_retry_gets(BIO * bio,char * buf,int size)807 static int always_retry_gets(BIO *bio, char *buf, int size)
808 {
809     BIO_set_retry_read(bio);
810     return retry_err;
811 }
812 
always_retry_puts(BIO * bio,const char * str)813 static int always_retry_puts(BIO *bio, const char *str)
814 {
815     BIO_set_retry_write(bio);
816     return retry_err;
817 }
818 
819 struct maybe_retry_data_st {
820     unsigned int retrycnt;
821 };
822 
823 static int maybe_retry_new(BIO *bi);
824 static int maybe_retry_free(BIO *a);
825 static int maybe_retry_write(BIO *b, const char *in, int inl);
826 static long maybe_retry_ctrl(BIO *b, int cmd, long num, void *ptr);
827 
bio_s_maybe_retry(void)828 const BIO_METHOD *bio_s_maybe_retry(void)
829 {
830     if (meth_maybe_retry == NULL) {
831         if (!TEST_ptr(meth_maybe_retry = BIO_meth_new(BIO_TYPE_MAYBE_RETRY,
832                                                       "Maybe Retry"))
833             || !TEST_true(BIO_meth_set_write(meth_maybe_retry,
834                                              maybe_retry_write))
835             || !TEST_true(BIO_meth_set_ctrl(meth_maybe_retry,
836                                             maybe_retry_ctrl))
837             || !TEST_true(BIO_meth_set_create(meth_maybe_retry,
838                                               maybe_retry_new))
839             || !TEST_true(BIO_meth_set_destroy(meth_maybe_retry,
840                                                maybe_retry_free)))
841             return NULL;
842     }
843     return meth_maybe_retry;
844 }
845 
bio_s_maybe_retry_free(void)846 void bio_s_maybe_retry_free(void)
847 {
848     BIO_meth_free(meth_maybe_retry);
849 }
850 
maybe_retry_new(BIO * bio)851 static int maybe_retry_new(BIO *bio)
852 {
853     struct maybe_retry_data_st *data = OPENSSL_zalloc(sizeof(*data));
854 
855     if (data == NULL)
856         return 0;
857 
858     BIO_set_data(bio, data);
859     BIO_set_init(bio, 1);
860     return 1;
861 }
862 
maybe_retry_free(BIO * bio)863 static int maybe_retry_free(BIO *bio)
864 {
865     struct maybe_retry_data_st *data = BIO_get_data(bio);
866 
867     OPENSSL_free(data);
868     BIO_set_data(bio, NULL);
869     BIO_set_init(bio, 0);
870     return 1;
871 }
872 
maybe_retry_write(BIO * bio,const char * in,int inl)873 static int maybe_retry_write(BIO *bio, const char *in, int inl)
874 {
875     struct maybe_retry_data_st *data = BIO_get_data(bio);
876 
877     if (data == NULL)
878         return -1;
879 
880     if (data->retrycnt == 0) {
881         BIO_set_retry_write(bio);
882         return -1;
883     }
884     data->retrycnt--;
885 
886     return BIO_write(BIO_next(bio), in, inl);
887 }
888 
maybe_retry_ctrl(BIO * bio,int cmd,long num,void * ptr)889 static long maybe_retry_ctrl(BIO *bio, int cmd, long num, void *ptr)
890 {
891     struct maybe_retry_data_st *data = BIO_get_data(bio);
892 
893     if (data == NULL)
894         return 0;
895 
896     switch (cmd) {
897     case MAYBE_RETRY_CTRL_SET_RETRY_AFTER_CNT:
898         data->retrycnt = num;
899         return 1;
900 
901     case BIO_CTRL_FLUSH:
902         if (data->retrycnt == 0) {
903             BIO_set_retry_write(bio);
904             return -1;
905         }
906         data->retrycnt--;
907         /* fall through */
908     default:
909         return BIO_ctrl(BIO_next(bio), cmd, num, ptr);
910     }
911 }
912 
create_ssl_ctx_pair(OSSL_LIB_CTX * libctx,const SSL_METHOD * sm,const SSL_METHOD * cm,int min_proto_version,int max_proto_version,SSL_CTX ** sctx,SSL_CTX ** cctx,char * certfile,char * privkeyfile)913 int create_ssl_ctx_pair(OSSL_LIB_CTX *libctx, const SSL_METHOD *sm,
914                         const SSL_METHOD *cm, int min_proto_version,
915                         int max_proto_version, SSL_CTX **sctx, SSL_CTX **cctx,
916                         char *certfile, char *privkeyfile)
917 {
918     SSL_CTX *serverctx = NULL;
919     SSL_CTX *clientctx = NULL;
920 
921     if (sctx != NULL) {
922         if (*sctx != NULL)
923             serverctx = *sctx;
924         else if (!TEST_ptr(serverctx = SSL_CTX_new_ex(libctx, NULL, sm))
925             || !TEST_true(SSL_CTX_set_options(serverctx,
926                                               SSL_OP_ALLOW_CLIENT_RENEGOTIATION)))
927             goto err;
928     }
929 
930     if (cctx != NULL) {
931         if (*cctx != NULL)
932             clientctx = *cctx;
933         else if (!TEST_ptr(clientctx = SSL_CTX_new_ex(libctx, NULL, cm)))
934             goto err;
935     }
936 
937 #if !defined(OPENSSL_NO_TLS1_3) \
938     && defined(OPENSSL_NO_EC) \
939     && defined(OPENSSL_NO_DH)
940     /*
941      * There are no usable built-in TLSv1.3 groups if ec and dh are both
942      * disabled
943      */
944     if (max_proto_version == 0
945             && (sm == TLS_server_method() || cm == TLS_client_method()))
946         max_proto_version = TLS1_2_VERSION;
947 #endif
948 
949     if (serverctx != NULL
950             && ((min_proto_version > 0
951                  && !TEST_true(SSL_CTX_set_min_proto_version(serverctx,
952                                                             min_proto_version)))
953                 || (max_proto_version > 0
954                     && !TEST_true(SSL_CTX_set_max_proto_version(serverctx,
955                                                                 max_proto_version)))))
956         goto err;
957     if (clientctx != NULL
958         && ((min_proto_version > 0
959              && !TEST_true(SSL_CTX_set_min_proto_version(clientctx,
960                                                          min_proto_version)))
961             || (max_proto_version > 0
962                 && !TEST_true(SSL_CTX_set_max_proto_version(clientctx,
963                                                             max_proto_version)))))
964         goto err;
965 
966     if (serverctx != NULL && certfile != NULL && privkeyfile != NULL) {
967         if (!TEST_int_eq(SSL_CTX_use_certificate_file(serverctx, certfile,
968                                                       SSL_FILETYPE_PEM), 1)
969                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(serverctx,
970                                                             privkeyfile,
971                                                             SSL_FILETYPE_PEM), 1)
972                 || !TEST_int_eq(SSL_CTX_check_private_key(serverctx), 1))
973             goto err;
974     }
975 
976     if (sctx != NULL)
977         *sctx = serverctx;
978     if (cctx != NULL)
979         *cctx = clientctx;
980     return 1;
981 
982  err:
983     if (sctx != NULL && *sctx == NULL)
984         SSL_CTX_free(serverctx);
985     if (cctx != NULL && *cctx == NULL)
986         SSL_CTX_free(clientctx);
987     return 0;
988 }
989 
990 #define MAXLOOPS    1000000
991 
992 #if defined(OSSL_USE_SOCKETS)
993 
wait_until_sock_readable(int sock)994 int wait_until_sock_readable(int sock)
995 {
996     fd_set readfds;
997     struct timeval timeout;
998     int width;
999 
1000     width = sock + 1;
1001     FD_ZERO(&readfds);
1002     openssl_fdset(sock, &readfds);
1003     timeout.tv_sec = 10; /* give up after 10 seconds */
1004     timeout.tv_usec = 0;
1005 
1006     select(width, &readfds, NULL, NULL, &timeout);
1007 
1008     return FD_ISSET(sock, &readfds);
1009 }
1010 
create_test_sockets(int * cfdp,int * sfdp,int socktype,BIO_ADDR * saddr)1011 int create_test_sockets(int *cfdp, int *sfdp, int socktype, BIO_ADDR *saddr)
1012 {
1013     struct sockaddr_in sin;
1014     const char *host = "127.0.0.1";
1015     int cfd_connected = 0, ret = 0;
1016     socklen_t slen = sizeof(sin);
1017     int afd = -1, cfd = -1, sfd = -1;
1018 
1019     memset ((char *) &sin, 0, sizeof(sin));
1020     sin.sin_family = AF_INET;
1021     sin.sin_addr.s_addr = inet_addr(host);
1022 
1023     afd = BIO_socket(AF_INET, socktype,
1024                      socktype == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP, 0);
1025     if (afd == INVALID_SOCKET)
1026         return 0;
1027 
1028     if (bind(afd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
1029         goto out;
1030 
1031     if (getsockname(afd, (struct sockaddr*)&sin, &slen) < 0)
1032         goto out;
1033 
1034     if (saddr != NULL
1035             && !BIO_ADDR_rawmake(saddr, sin.sin_family, &sin.sin_addr,
1036                                  sizeof(sin.sin_addr), sin.sin_port))
1037         goto out;
1038 
1039     if (socktype == SOCK_STREAM && listen(afd, 1) < 0)
1040         goto out;
1041 
1042     cfd = BIO_socket(AF_INET, socktype,
1043                      socktype == SOCK_STREAM ? IPPROTO_TCP : IPPROTO_UDP, 0);
1044     if (cfd == INVALID_SOCKET)
1045         goto out;
1046 
1047     if (!BIO_socket_nbio(afd, 1))
1048         goto out;
1049 
1050     /*
1051      * If a DGRAM socket then we don't call "accept" or "connect" - so act like
1052      * we already called them.
1053      */
1054     if (socktype == SOCK_DGRAM) {
1055         cfd_connected = 1;
1056         sfd = afd;
1057         afd = -1;
1058     }
1059 
1060     while (sfd == -1 || !cfd_connected) {
1061         sfd = accept(afd, NULL, 0);
1062         if (sfd == -1 && errno != EAGAIN)
1063             goto out;
1064 
1065         if (!cfd_connected && connect(cfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
1066             goto out;
1067         else
1068             cfd_connected = 1;
1069     }
1070 
1071     if (!BIO_socket_nbio(cfd, 1) || !BIO_socket_nbio(sfd, 1))
1072         goto out;
1073     ret = 1;
1074     *cfdp = cfd;
1075     *sfdp = sfd;
1076     goto success;
1077 
1078 out:
1079     if (cfd != -1)
1080         close(cfd);
1081     if (sfd != -1)
1082         close(sfd);
1083 success:
1084     if (afd != -1)
1085         close(afd);
1086     return ret;
1087 }
1088 
create_ssl_objects2(SSL_CTX * serverctx,SSL_CTX * clientctx,SSL ** sssl,SSL ** cssl,int sfd,int cfd)1089 int create_ssl_objects2(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
1090                           SSL **cssl, int sfd, int cfd)
1091 {
1092     SSL *serverssl = NULL, *clientssl = NULL;
1093     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
1094     BIO_POLL_DESCRIPTOR rdesc = {0}, wdesc = {0};
1095 
1096     if (*sssl != NULL)
1097         serverssl = *sssl;
1098     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
1099         goto error;
1100     if (*cssl != NULL)
1101         clientssl = *cssl;
1102     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
1103         goto error;
1104 
1105     if (!TEST_ptr(s_to_c_bio = BIO_new_socket(sfd, BIO_NOCLOSE))
1106             || !TEST_ptr(c_to_s_bio = BIO_new_socket(cfd, BIO_NOCLOSE)))
1107         goto error;
1108 
1109     if (!TEST_false(SSL_get_rpoll_descriptor(clientssl, &rdesc)
1110         || !TEST_false(SSL_get_wpoll_descriptor(clientssl, &wdesc))))
1111         goto error;
1112 
1113     SSL_set_bio(clientssl, c_to_s_bio, c_to_s_bio);
1114     SSL_set_bio(serverssl, s_to_c_bio, s_to_c_bio);
1115 
1116     if (!TEST_true(SSL_get_rpoll_descriptor(clientssl, &rdesc))
1117         || !TEST_true(SSL_get_wpoll_descriptor(clientssl, &wdesc))
1118         || !TEST_int_eq(rdesc.type, BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD)
1119         || !TEST_int_eq(wdesc.type, BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD)
1120         || !TEST_int_eq(rdesc.value.fd, cfd)
1121         || !TEST_int_eq(wdesc.value.fd, cfd))
1122         goto error;
1123 
1124     if (!TEST_true(SSL_get_rpoll_descriptor(serverssl, &rdesc))
1125         || !TEST_true(SSL_get_wpoll_descriptor(serverssl, &wdesc))
1126         || !TEST_int_eq(rdesc.type, BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD)
1127         || !TEST_int_eq(wdesc.type, BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD)
1128         || !TEST_int_eq(rdesc.value.fd, sfd)
1129         || !TEST_int_eq(wdesc.value.fd, sfd))
1130         goto error;
1131 
1132     *sssl = serverssl;
1133     *cssl = clientssl;
1134     return 1;
1135 
1136  error:
1137     SSL_free(serverssl);
1138     SSL_free(clientssl);
1139     BIO_free(s_to_c_bio);
1140     BIO_free(c_to_s_bio);
1141     return 0;
1142 }
1143 
1144 #else
1145 
wait_until_sock_readable(int sock)1146 int wait_until_sock_readable(int sock)
1147 {
1148     return 0;
1149 }
1150 
1151 #endif /* defined(OSSL_USE_SOCKETS) */
1152 
1153 /*
1154  * NOTE: Transfers control of the BIOs - this function will free them on error
1155  */
create_ssl_objects(SSL_CTX * serverctx,SSL_CTX * clientctx,SSL ** sssl,SSL ** cssl,BIO * s_to_c_fbio,BIO * c_to_s_fbio)1156 int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
1157                           SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio)
1158 {
1159     SSL *serverssl = NULL, *clientssl = NULL;
1160     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
1161 
1162     if (*sssl != NULL)
1163         serverssl = *sssl;
1164     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
1165         goto error;
1166     if (*cssl != NULL)
1167         clientssl = *cssl;
1168     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
1169         goto error;
1170 
1171     if (SSL_is_dtls(clientssl)) {
1172         if (!TEST_ptr(s_to_c_bio = BIO_new(bio_s_mempacket_test()))
1173                 || !TEST_ptr(c_to_s_bio = BIO_new(bio_s_mempacket_test())))
1174             goto error;
1175     } else {
1176         if (!TEST_ptr(s_to_c_bio = BIO_new(BIO_s_mem()))
1177                 || !TEST_ptr(c_to_s_bio = BIO_new(BIO_s_mem())))
1178             goto error;
1179     }
1180 
1181     if (s_to_c_fbio != NULL
1182             && !TEST_ptr(s_to_c_bio = BIO_push(s_to_c_fbio, s_to_c_bio)))
1183         goto error;
1184     if (c_to_s_fbio != NULL
1185             && !TEST_ptr(c_to_s_bio = BIO_push(c_to_s_fbio, c_to_s_bio)))
1186         goto error;
1187 
1188     /* Set Non-blocking IO behaviour */
1189     BIO_set_mem_eof_return(s_to_c_bio, -1);
1190     BIO_set_mem_eof_return(c_to_s_bio, -1);
1191 
1192     /* Up ref these as we are passing them to two SSL objects */
1193     SSL_set_bio(serverssl, c_to_s_bio, s_to_c_bio);
1194     BIO_up_ref(s_to_c_bio);
1195     BIO_up_ref(c_to_s_bio);
1196     SSL_set_bio(clientssl, s_to_c_bio, c_to_s_bio);
1197     *sssl = serverssl;
1198     *cssl = clientssl;
1199     return 1;
1200 
1201  error:
1202     SSL_free(serverssl);
1203     SSL_free(clientssl);
1204     BIO_free(s_to_c_bio);
1205     BIO_free(c_to_s_bio);
1206     BIO_free(s_to_c_fbio);
1207     BIO_free(c_to_s_fbio);
1208 
1209     return 0;
1210 }
1211 
1212 /*
1213  * Create an SSL connection, but does not read any post-handshake
1214  * NewSessionTicket messages.
1215  * If |read| is set and we're using DTLS then we will attempt to SSL_read on
1216  * the connection once we've completed one half of it, to ensure any retransmits
1217  * get triggered.
1218  * We stop the connection attempt (and return a failure value) if either peer
1219  * has SSL_get_error() return the value in the |want| parameter. The connection
1220  * attempt could be restarted by a subsequent call to this function.
1221  */
create_bare_ssl_connection(SSL * serverssl,SSL * clientssl,int want,int read,int listen)1222 int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want,
1223                                int read, int listen)
1224 {
1225     int retc = -1, rets = -1, err, abortctr = 0, ret = 0;
1226     int clienterr = 0, servererr = 0;
1227     int isdtls = SSL_is_dtls(serverssl);
1228 #ifndef OPENSSL_NO_SOCK
1229     BIO_ADDR *peer = NULL;
1230 
1231     if (listen) {
1232         if (!isdtls) {
1233             TEST_error("DTLSv1_listen requested for non-DTLS object\n");
1234             return 0;
1235         }
1236         peer = BIO_ADDR_new();
1237         if (!TEST_ptr(peer))
1238             return 0;
1239     }
1240 #else
1241     if (listen) {
1242         TEST_error("DTLSv1_listen requested in a no-sock build\n");
1243         return 0;
1244     }
1245 #endif
1246 
1247     do {
1248         err = SSL_ERROR_WANT_WRITE;
1249         while (!clienterr && retc <= 0 && err == SSL_ERROR_WANT_WRITE) {
1250             retc = SSL_connect(clientssl);
1251             if (retc <= 0)
1252                 err = SSL_get_error(clientssl, retc);
1253         }
1254 
1255         if (!clienterr && retc <= 0 && err != SSL_ERROR_WANT_READ) {
1256             TEST_info("SSL_connect() failed %d, %d", retc, err);
1257             if (want != SSL_ERROR_SSL)
1258                 TEST_openssl_errors();
1259             clienterr = 1;
1260         }
1261         if (want != SSL_ERROR_NONE && err == want)
1262             goto err;
1263 
1264         err = SSL_ERROR_WANT_WRITE;
1265         while (!servererr && rets <= 0 && err == SSL_ERROR_WANT_WRITE) {
1266 #ifndef OPENSSL_NO_SOCK
1267             if (listen) {
1268                 rets = DTLSv1_listen(serverssl, peer);
1269                 if (rets < 0) {
1270                     err = SSL_ERROR_SSL;
1271                 } else if (rets == 0) {
1272                     err = SSL_ERROR_WANT_READ;
1273                 } else {
1274                     /* Success - stop listening and call SSL_accept from now on */
1275                     listen = 0;
1276                     rets = 0;
1277                 }
1278             } else
1279 #endif
1280             {
1281                 rets = SSL_accept(serverssl);
1282                 if (rets <= 0)
1283                     err = SSL_get_error(serverssl, rets);
1284             }
1285         }
1286 
1287         if (!servererr && rets <= 0
1288                 && err != SSL_ERROR_WANT_READ
1289                 && err != SSL_ERROR_WANT_X509_LOOKUP) {
1290             TEST_info("SSL_accept() failed %d, %d", rets, err);
1291             if (want != SSL_ERROR_SSL)
1292                 TEST_openssl_errors();
1293             servererr = 1;
1294         }
1295         if (want != SSL_ERROR_NONE && err == want)
1296             goto err;
1297         if (clienterr && servererr)
1298             goto err;
1299         if (isdtls && read) {
1300             unsigned char buf[20];
1301 
1302             /* Trigger any retransmits that may be appropriate */
1303             if (rets > 0 && retc <= 0) {
1304                 if (SSL_read(serverssl, buf, sizeof(buf)) > 0) {
1305                     /* We don't expect this to succeed! */
1306                     TEST_info("Unexpected SSL_read() success!");
1307                     goto err;
1308                 }
1309             }
1310             if (retc > 0 && rets <= 0) {
1311                 if (SSL_read(clientssl, buf, sizeof(buf)) > 0) {
1312                     /* We don't expect this to succeed! */
1313                     TEST_info("Unexpected SSL_read() success!");
1314                     goto err;
1315                 }
1316             }
1317         }
1318         if (++abortctr == MAXLOOPS) {
1319             TEST_info("No progress made");
1320             goto err;
1321         }
1322         if (isdtls && abortctr <= 50 && (abortctr % 10) == 0) {
1323             /*
1324              * It looks like we're just spinning. Pause for a short period to
1325              * give the DTLS timer a chance to do something. We only do this for
1326              * the first few times to prevent hangs.
1327              */
1328             OSSL_sleep(50);
1329         }
1330     } while (retc <=0 || rets <= 0);
1331 
1332     ret = 1;
1333  err:
1334 #ifndef OPENSSL_NO_SOCK
1335     BIO_ADDR_free(peer);
1336 #endif
1337     return ret;
1338 }
1339 
1340 /*
1341  * Create an SSL connection including any post handshake NewSessionTicket
1342  * messages.
1343  */
create_ssl_connection(SSL * serverssl,SSL * clientssl,int want)1344 int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want)
1345 {
1346     int i;
1347     unsigned char buf;
1348     size_t readbytes;
1349 
1350     if (!create_bare_ssl_connection(serverssl, clientssl, want, 1, 0))
1351         return 0;
1352 
1353     /*
1354      * We attempt to read some data on the client side which we expect to fail.
1355      * This will ensure we have received the NewSessionTicket in TLSv1.3 where
1356      * appropriate. We do this twice because there are 2 NewSessionTickets.
1357      */
1358     for (i = 0; i < 2; i++) {
1359         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
1360             if (!TEST_ulong_eq(readbytes, 0))
1361                 return 0;
1362         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
1363                                 SSL_ERROR_WANT_READ)) {
1364             return 0;
1365         }
1366     }
1367 
1368     return 1;
1369 }
1370 
shutdown_ssl_connection(SSL * serverssl,SSL * clientssl)1371 void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl)
1372 {
1373     SSL_shutdown(clientssl);
1374     SSL_shutdown(serverssl);
1375     SSL_free(serverssl);
1376     SSL_free(clientssl);
1377 }
1378 
create_a_psk(SSL * ssl,size_t mdsize)1379 SSL_SESSION *create_a_psk(SSL *ssl, size_t mdsize)
1380 {
1381     const SSL_CIPHER *cipher = NULL;
1382     const unsigned char key[SHA384_DIGEST_LENGTH] = {
1383         0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
1384         0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
1385         0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
1386         0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
1387         0x2c, 0x2d, 0x2e, 0x2f
1388     };
1389     SSL_SESSION *sess = NULL;
1390 
1391     if (mdsize == SHA384_DIGEST_LENGTH) {
1392         cipher = SSL_CIPHER_find(ssl, TLS13_AES_256_GCM_SHA384_BYTES);
1393     } else if (mdsize == SHA256_DIGEST_LENGTH) {
1394         /*
1395          * Any ciphersuite using SHA256 will do - it will be compatible with
1396          * the actual ciphersuite selected as long as it too is based on SHA256
1397          */
1398         cipher = SSL_CIPHER_find(ssl, TLS13_AES_128_GCM_SHA256_BYTES);
1399     } else {
1400         /* Should not happen */
1401         return NULL;
1402     }
1403     sess = SSL_SESSION_new();
1404     if (!TEST_ptr(sess)
1405             || !TEST_ptr(cipher)
1406             || !TEST_true(SSL_SESSION_set1_master_key(sess, key, mdsize))
1407             || !TEST_true(SSL_SESSION_set_cipher(sess, cipher))
1408             || !TEST_true(
1409                     SSL_SESSION_set_protocol_version(sess,
1410                                                      TLS1_3_VERSION))) {
1411         SSL_SESSION_free(sess);
1412         return NULL;
1413     }
1414     return sess;
1415 }
1416 
1417 #define NUM_EXTRA_CERTS 40
1418 
ssl_ctx_add_large_cert_chain(OSSL_LIB_CTX * libctx,SSL_CTX * sctx,const char * cert_file)1419 int ssl_ctx_add_large_cert_chain(OSSL_LIB_CTX *libctx, SSL_CTX *sctx,
1420                                  const char *cert_file)
1421 {
1422     BIO *certbio = NULL;
1423     X509 *chaincert = NULL;
1424     int certlen;
1425     int ret = 0;
1426     int i;
1427 
1428     if (!TEST_ptr(certbio = BIO_new_file(cert_file, "r")))
1429         goto end;
1430 
1431     if (!TEST_ptr(chaincert = X509_new_ex(libctx, NULL)))
1432         goto end;
1433 
1434     if (PEM_read_bio_X509(certbio, &chaincert, NULL, NULL) == NULL)
1435         goto end;
1436     BIO_free(certbio);
1437     certbio = NULL;
1438 
1439     /*
1440      * We assume the supplied certificate is big enough so that if we add
1441      * NUM_EXTRA_CERTS it will make the overall message large enough. The
1442      * default buffer size is requested to be 16k, but due to the way BUF_MEM
1443      * works, it ends up allocating a little over 21k (16 * 4/3). So, in this
1444      * test we need to have a message larger than that.
1445      */
1446     certlen = i2d_X509(chaincert, NULL);
1447     OPENSSL_assert(certlen * NUM_EXTRA_CERTS >
1448                    (SSL3_RT_MAX_PLAIN_LENGTH * 4) / 3);
1449     for (i = 0; i < NUM_EXTRA_CERTS; i++) {
1450         if (!X509_up_ref(chaincert))
1451             goto end;
1452         if (!SSL_CTX_add_extra_chain_cert(sctx, chaincert)) {
1453             X509_free(chaincert);
1454             goto end;
1455         }
1456     }
1457 
1458     ret = 1;
1459  end:
1460     BIO_free(certbio);
1461     X509_free(chaincert);
1462     return ret;
1463 }
1464 
load_dasync(void)1465 ENGINE *load_dasync(void)
1466 {
1467 #if !defined(OPENSSL_NO_TLS1_2) && !defined(OPENSSL_NO_DYNAMIC_ENGINE)
1468     ENGINE *e;
1469 
1470     if (!TEST_ptr(e = ENGINE_by_id("dasync")))
1471         return NULL;
1472 
1473     if (!TEST_true(ENGINE_init(e))) {
1474         ENGINE_free(e);
1475         return NULL;
1476     }
1477 
1478     if (!TEST_true(ENGINE_register_ciphers(e))) {
1479         ENGINE_free(e);
1480         return NULL;
1481     }
1482 
1483     return e;
1484 #else
1485     return NULL;
1486 #endif
1487 }
1488