xref: /openssl/test/helpers/ssltestlib.c (revision 279754d4)
1 /*
2  * Copyright 2016-2022 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 "internal/e_os.h" /* for ossl_sleep() etc. */
16 
17 #ifdef OPENSSL_SYS_UNIX
18 # include <unistd.h>
19 # ifndef OPENSSL_NO_KTLS
20 #  include <netinet/in.h>
21 #  include <netinet/in.h>
22 #  include <arpa/inet.h>
23 #  include <sys/socket.h>
24 #  include <unistd.h>
25 #  include <fcntl.h>
26 # endif
27 #endif
28 
29 static int tls_dump_new(BIO *bi);
30 static int tls_dump_free(BIO *a);
31 static int tls_dump_read(BIO *b, char *out, int outl);
32 static int tls_dump_write(BIO *b, const char *in, int inl);
33 static long tls_dump_ctrl(BIO *b, int cmd, long num, void *ptr);
34 static int tls_dump_gets(BIO *bp, char *buf, int size);
35 static int tls_dump_puts(BIO *bp, const char *str);
36 
37 /* Choose a sufficiently large type likely to be unused for this custom BIO */
38 #define BIO_TYPE_TLS_DUMP_FILTER  (0x80 | BIO_TYPE_FILTER)
39 #define BIO_TYPE_MEMPACKET_TEST    0x81
40 #define BIO_TYPE_ALWAYS_RETRY      0x82
41 
42 static BIO_METHOD *method_tls_dump = NULL;
43 static BIO_METHOD *meth_mem = NULL;
44 static BIO_METHOD *meth_always_retry = NULL;
45 
46 /* Note: Not thread safe! */
bio_f_tls_dump_filter(void)47 const 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 
bio_f_tls_dump_filter_free(void)65 void bio_f_tls_dump_filter_free(void)
66 {
67     BIO_meth_free(method_tls_dump);
68 }
69 
tls_dump_new(BIO * bio)70 static int tls_dump_new(BIO *bio)
71 {
72     BIO_set_init(bio, 1);
73     return 1;
74 }
75 
tls_dump_free(BIO * bio)76 static int tls_dump_free(BIO *bio)
77 {
78     BIO_set_init(bio, 0);
79 
80     return 1;
81 }
82 
copy_flags(BIO * bio)83 static 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 
dump_data(const char * data,int len)117 static 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 
tls_dump_read(BIO * bio,char * out,int outl)193 static 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 
tls_dump_write(BIO * bio,const char * in,int inl)208 static 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 
tls_dump_ctrl(BIO * bio,int cmd,long num,void * ptr)219 static 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 
tls_dump_gets(BIO * bio,char * buf,int size)238 static 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 
tls_dump_puts(BIO * bio,const char * str)244 static int tls_dump_puts(BIO *bio, const char *str)
245 {
246     return tls_dump_write(bio, str, strlen(str));
247 }
248 
249 
250 struct mempacket_st {
251     unsigned char *data;
252     int len;
253     unsigned int num;
254     unsigned int type;
255 };
256 
mempacket_free(MEMPACKET * pkt)257 static void mempacket_free(MEMPACKET *pkt)
258 {
259     if (pkt->data != NULL)
260         OPENSSL_free(pkt->data);
261     OPENSSL_free(pkt);
262 }
263 
264 typedef struct mempacket_test_ctx_st {
265     STACK_OF(MEMPACKET) *pkts;
266     uint16_t 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 
277 static int mempacket_test_new(BIO *bi);
278 static int mempacket_test_free(BIO *a);
279 static int mempacket_test_read(BIO *b, char *out, int outl);
280 static int mempacket_test_write(BIO *b, const char *in, int inl);
281 static long mempacket_test_ctrl(BIO *b, int cmd, long num, void *ptr);
282 static int mempacket_test_gets(BIO *bp, char *buf, int size);
283 static int mempacket_test_puts(BIO *bp, const char *str);
284 
bio_s_mempacket_test(void)285 const 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 
bio_s_mempacket_test_free(void)302 void bio_s_mempacket_test_free(void)
303 {
304     BIO_meth_free(meth_mem);
305 }
306 
mempacket_test_new(BIO * bio)307 static 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 
mempacket_test_free(BIO * bio)324 static 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 
mempacket_test_read(BIO * bio,char * out,int outl)344 static 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     thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
354     if (thispkt == NULL || 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 
410     mempacket_free(thispkt);
411     return outl;
412 }
413 
414 /*
415  * Look for records from different epochs and swap them around
416  */
mempacket_swap_epoch(BIO * bio)417 int 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 /* Take the last and penultimate packets and swap them around */
mempacket_swap_recent(BIO * bio)497 int mempacket_swap_recent(BIO *bio)
498 {
499     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
500     MEMPACKET *thispkt;
501     int numpkts = sk_MEMPACKET_num(ctx->pkts);
502 
503     /* We need at least 2 packets to be able to swap them */
504     if (numpkts <= 1)
505         return 0;
506 
507     /* Get the penultimate packet */
508     thispkt = sk_MEMPACKET_value(ctx->pkts, numpkts - 2);
509     if (thispkt == NULL)
510         return 0;
511 
512     if (sk_MEMPACKET_delete(ctx->pkts, numpkts - 2) != thispkt)
513         return 0;
514 
515     /* Re-add it to the end of the list */
516     thispkt->num++;
517     if (sk_MEMPACKET_insert(ctx->pkts, thispkt, numpkts - 1) <= 0)
518         return 0;
519 
520     /* We also have to adjust the packet number of the other packet */
521     thispkt = sk_MEMPACKET_value(ctx->pkts, numpkts - 2);
522     if (thispkt == NULL)
523         return 0;
524     thispkt->num--;
525 
526     return 1;
527 }
528 
mempacket_test_inject(BIO * bio,const char * in,int inl,int pktnum,int type)529 int mempacket_test_inject(BIO *bio, const char *in, int inl, int pktnum,
530                           int type)
531 {
532     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
533     MEMPACKET *thispkt = NULL, *looppkt, *nextpkt, *allpkts[3];
534     int i, duprec;
535     const unsigned char *inu = (const unsigned char *)in;
536     size_t len = ((inu[RECORD_LEN_HI] << 8) | inu[RECORD_LEN_LO])
537                  + DTLS1_RT_HEADER_LENGTH;
538 
539     if (ctx == NULL)
540         return -1;
541 
542     if ((size_t)inl < len)
543         return -1;
544 
545     if ((size_t)inl == len)
546         duprec = 0;
547     else
548         duprec = ctx->duprec > 0;
549 
550     /* We don't support arbitrary injection when duplicating records */
551     if (duprec && pktnum != -1)
552         return -1;
553 
554     /* We only allow injection before we've started writing any data */
555     if (pktnum >= 0) {
556         if (ctx->noinject)
557             return -1;
558         ctx->injected  = 1;
559     } else {
560         ctx->noinject = 1;
561     }
562 
563     for (i = 0; i < (duprec ? 3 : 1); i++) {
564         if (!TEST_ptr(allpkts[i] = OPENSSL_malloc(sizeof(*thispkt))))
565             goto err;
566         thispkt = allpkts[i];
567 
568         if (!TEST_ptr(thispkt->data = OPENSSL_malloc(inl)))
569             goto err;
570         /*
571          * If we are duplicating the packet, we duplicate it three times. The
572          * first two times we drop the first record if there are more than one.
573          * In this way we know that libssl will not be able to make progress
574          * until it receives the last packet, and hence will be forced to
575          * buffer these records.
576          */
577         if (duprec && i != 2) {
578             memcpy(thispkt->data, in + len, inl - len);
579             thispkt->len = inl - len;
580         } else {
581             memcpy(thispkt->data, in, inl);
582             thispkt->len = inl;
583         }
584         thispkt->num = (pktnum >= 0) ? (unsigned int)pktnum : ctx->lastpkt + i;
585         thispkt->type = type;
586     }
587 
588     for (i = 0; (looppkt = sk_MEMPACKET_value(ctx->pkts, i)) != NULL; i++) {
589         /* Check if we found the right place to insert this packet */
590         if (looppkt->num > thispkt->num) {
591             if (sk_MEMPACKET_insert(ctx->pkts, thispkt, i) == 0)
592                 goto err;
593             /* If we're doing up front injection then we're done */
594             if (pktnum >= 0)
595                 return inl;
596             /*
597              * We need to do some accounting on lastpkt. We increment it first,
598              * but it might now equal the value of injected packets, so we need
599              * to skip over those
600              */
601             ctx->lastpkt++;
602             do {
603                 i++;
604                 nextpkt = sk_MEMPACKET_value(ctx->pkts, i);
605                 if (nextpkt != NULL && nextpkt->num == ctx->lastpkt)
606                     ctx->lastpkt++;
607                 else
608                     return inl;
609             } while(1);
610         } else if (looppkt->num == thispkt->num) {
611             if (!ctx->noinject) {
612                 /* We injected two packets with the same packet number! */
613                 goto err;
614             }
615             ctx->lastpkt++;
616             thispkt->num++;
617         }
618     }
619     /*
620      * We didn't find any packets with a packet number equal to or greater than
621      * this one, so we just add it onto the end
622      */
623     for (i = 0; i < (duprec ? 3 : 1); i++) {
624         thispkt = allpkts[i];
625         if (!sk_MEMPACKET_push(ctx->pkts, thispkt))
626             goto err;
627 
628         if (pktnum < 0)
629             ctx->lastpkt++;
630     }
631 
632     return inl;
633 
634  err:
635     for (i = 0; i < (ctx->duprec > 0 ? 3 : 1); i++)
636         mempacket_free(allpkts[i]);
637     return -1;
638 }
639 
mempacket_test_write(BIO * bio,const char * in,int inl)640 static int mempacket_test_write(BIO *bio, const char *in, int inl)
641 {
642     return mempacket_test_inject(bio, in, inl, -1, STANDARD_PACKET);
643 }
644 
mempacket_test_ctrl(BIO * bio,int cmd,long num,void * ptr)645 static long mempacket_test_ctrl(BIO *bio, int cmd, long num, void *ptr)
646 {
647     long ret = 1;
648     MEMPACKET_TEST_CTX *ctx = BIO_get_data(bio);
649     MEMPACKET *thispkt;
650 
651     switch (cmd) {
652     case BIO_CTRL_EOF:
653         ret = (long)(sk_MEMPACKET_num(ctx->pkts) == 0);
654         break;
655     case BIO_CTRL_GET_CLOSE:
656         ret = BIO_get_shutdown(bio);
657         break;
658     case BIO_CTRL_SET_CLOSE:
659         BIO_set_shutdown(bio, (int)num);
660         break;
661     case BIO_CTRL_WPENDING:
662         ret = 0L;
663         break;
664     case BIO_CTRL_PENDING:
665         thispkt = sk_MEMPACKET_value(ctx->pkts, 0);
666         if (thispkt == NULL)
667             ret = 0;
668         else
669             ret = thispkt->len;
670         break;
671     case BIO_CTRL_FLUSH:
672         ret = 1;
673         break;
674     case MEMPACKET_CTRL_SET_DROP_EPOCH:
675         ctx->dropepoch = (unsigned int)num;
676         break;
677     case MEMPACKET_CTRL_SET_DROP_REC:
678         ctx->droprec = (int)num;
679         break;
680     case MEMPACKET_CTRL_GET_DROP_REC:
681         ret = ctx->droprec;
682         break;
683     case MEMPACKET_CTRL_SET_DUPLICATE_REC:
684         ctx->duprec = (int)num;
685         break;
686     case BIO_CTRL_RESET:
687     case BIO_CTRL_DUP:
688     case BIO_CTRL_PUSH:
689     case BIO_CTRL_POP:
690     default:
691         ret = 0;
692         break;
693     }
694     return ret;
695 }
696 
mempacket_test_gets(BIO * bio,char * buf,int size)697 static int mempacket_test_gets(BIO *bio, char *buf, int size)
698 {
699     /* We don't support this - not needed anyway */
700     return -1;
701 }
702 
mempacket_test_puts(BIO * bio,const char * str)703 static int mempacket_test_puts(BIO *bio, const char *str)
704 {
705     return mempacket_test_write(bio, str, strlen(str));
706 }
707 
708 static int always_retry_new(BIO *bi);
709 static int always_retry_free(BIO *a);
710 static int always_retry_read(BIO *b, char *out, int outl);
711 static int always_retry_write(BIO *b, const char *in, int inl);
712 static long always_retry_ctrl(BIO *b, int cmd, long num, void *ptr);
713 static int always_retry_gets(BIO *bp, char *buf, int size);
714 static int always_retry_puts(BIO *bp, const char *str);
715 
bio_s_always_retry(void)716 const BIO_METHOD *bio_s_always_retry(void)
717 {
718     if (meth_always_retry == NULL) {
719         if (!TEST_ptr(meth_always_retry = BIO_meth_new(BIO_TYPE_ALWAYS_RETRY,
720                                                        "Always Retry"))
721             || !TEST_true(BIO_meth_set_write(meth_always_retry,
722                                              always_retry_write))
723             || !TEST_true(BIO_meth_set_read(meth_always_retry,
724                                             always_retry_read))
725             || !TEST_true(BIO_meth_set_puts(meth_always_retry,
726                                             always_retry_puts))
727             || !TEST_true(BIO_meth_set_gets(meth_always_retry,
728                                             always_retry_gets))
729             || !TEST_true(BIO_meth_set_ctrl(meth_always_retry,
730                                             always_retry_ctrl))
731             || !TEST_true(BIO_meth_set_create(meth_always_retry,
732                                               always_retry_new))
733             || !TEST_true(BIO_meth_set_destroy(meth_always_retry,
734                                                always_retry_free)))
735             return NULL;
736     }
737     return meth_always_retry;
738 }
739 
bio_s_always_retry_free(void)740 void bio_s_always_retry_free(void)
741 {
742     BIO_meth_free(meth_always_retry);
743 }
744 
always_retry_new(BIO * bio)745 static int always_retry_new(BIO *bio)
746 {
747     BIO_set_init(bio, 1);
748     return 1;
749 }
750 
always_retry_free(BIO * bio)751 static int always_retry_free(BIO *bio)
752 {
753     BIO_set_data(bio, NULL);
754     BIO_set_init(bio, 0);
755     return 1;
756 }
757 
always_retry_read(BIO * bio,char * out,int outl)758 static int always_retry_read(BIO *bio, char *out, int outl)
759 {
760     BIO_set_retry_read(bio);
761     return -1;
762 }
763 
always_retry_write(BIO * bio,const char * in,int inl)764 static int always_retry_write(BIO *bio, const char *in, int inl)
765 {
766     BIO_set_retry_write(bio);
767     return -1;
768 }
769 
always_retry_ctrl(BIO * bio,int cmd,long num,void * ptr)770 static long always_retry_ctrl(BIO *bio, int cmd, long num, void *ptr)
771 {
772     long ret = 1;
773 
774     switch (cmd) {
775     case BIO_CTRL_FLUSH:
776         BIO_set_retry_write(bio);
777         /* fall through */
778     case BIO_CTRL_EOF:
779     case BIO_CTRL_RESET:
780     case BIO_CTRL_DUP:
781     case BIO_CTRL_PUSH:
782     case BIO_CTRL_POP:
783     default:
784         ret = 0;
785         break;
786     }
787     return ret;
788 }
789 
always_retry_gets(BIO * bio,char * buf,int size)790 static int always_retry_gets(BIO *bio, char *buf, int size)
791 {
792     BIO_set_retry_read(bio);
793     return -1;
794 }
795 
always_retry_puts(BIO * bio,const char * str)796 static int always_retry_puts(BIO *bio, const char *str)
797 {
798     BIO_set_retry_write(bio);
799     return -1;
800 }
801 
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)802 int create_ssl_ctx_pair(OSSL_LIB_CTX *libctx, const SSL_METHOD *sm,
803                         const SSL_METHOD *cm, int min_proto_version,
804                         int max_proto_version, SSL_CTX **sctx, SSL_CTX **cctx,
805                         char *certfile, char *privkeyfile)
806 {
807     SSL_CTX *serverctx = NULL;
808     SSL_CTX *clientctx = NULL;
809 
810     if (sctx != NULL) {
811         if (*sctx != NULL)
812             serverctx = *sctx;
813         else if (!TEST_ptr(serverctx = SSL_CTX_new_ex(libctx, NULL, sm))
814             || !TEST_true(SSL_CTX_set_options(serverctx,
815                                               SSL_OP_ALLOW_CLIENT_RENEGOTIATION)))
816             goto err;
817     }
818 
819     if (cctx != NULL) {
820         if (*cctx != NULL)
821             clientctx = *cctx;
822         else if (!TEST_ptr(clientctx = SSL_CTX_new_ex(libctx, NULL, cm)))
823             goto err;
824     }
825 
826 #if !defined(OPENSSL_NO_TLS1_3) \
827     && defined(OPENSSL_NO_EC) \
828     && defined(OPENSSL_NO_DH)
829     /*
830      * There are no usable built-in TLSv1.3 groups if ec and dh are both
831      * disabled
832      */
833     if (max_proto_version == 0
834             && (sm == TLS_server_method() || cm == TLS_client_method()))
835         max_proto_version = TLS1_2_VERSION;
836 #endif
837 
838     if (serverctx != NULL
839             && ((min_proto_version > 0
840                  && !TEST_true(SSL_CTX_set_min_proto_version(serverctx,
841                                                             min_proto_version)))
842                 || (max_proto_version > 0
843                     && !TEST_true(SSL_CTX_set_max_proto_version(serverctx,
844                                                                 max_proto_version)))))
845         goto err;
846     if (clientctx != NULL
847         && ((min_proto_version > 0
848              && !TEST_true(SSL_CTX_set_min_proto_version(clientctx,
849                                                          min_proto_version)))
850             || (max_proto_version > 0
851                 && !TEST_true(SSL_CTX_set_max_proto_version(clientctx,
852                                                             max_proto_version)))))
853         goto err;
854 
855     if (serverctx != NULL && certfile != NULL && privkeyfile != NULL) {
856         if (!TEST_int_eq(SSL_CTX_use_certificate_file(serverctx, certfile,
857                                                       SSL_FILETYPE_PEM), 1)
858                 || !TEST_int_eq(SSL_CTX_use_PrivateKey_file(serverctx,
859                                                             privkeyfile,
860                                                             SSL_FILETYPE_PEM), 1)
861                 || !TEST_int_eq(SSL_CTX_check_private_key(serverctx), 1))
862             goto err;
863     }
864 
865     if (sctx != NULL)
866         *sctx = serverctx;
867     if (cctx != NULL)
868         *cctx = clientctx;
869     return 1;
870 
871  err:
872     if (sctx != NULL && *sctx == NULL)
873         SSL_CTX_free(serverctx);
874     if (cctx != NULL && *cctx == NULL)
875         SSL_CTX_free(clientctx);
876     return 0;
877 }
878 
879 #define MAXLOOPS    1000000
880 
881 #if !defined(OPENSSL_NO_KTLS) && !defined(OPENSSL_NO_SOCK)
set_nb(int fd)882 static int set_nb(int fd)
883 {
884     int flags;
885 
886     flags = fcntl(fd, F_GETFL, 0);
887     if (flags == -1)
888         return flags;
889     flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
890     return flags;
891 }
892 
create_test_sockets(int * cfdp,int * sfdp)893 int create_test_sockets(int *cfdp, int *sfdp)
894 {
895     struct sockaddr_in sin;
896     const char *host = "127.0.0.1";
897     int cfd_connected = 0, ret = 0;
898     socklen_t slen = sizeof(sin);
899     int afd = -1, cfd = -1, sfd = -1;
900 
901     memset ((char *) &sin, 0, sizeof(sin));
902     sin.sin_family = AF_INET;
903     sin.sin_addr.s_addr = inet_addr(host);
904 
905     afd = socket(AF_INET, SOCK_STREAM, 0);
906     if (afd < 0)
907         return 0;
908 
909     if (bind(afd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
910         goto out;
911 
912     if (getsockname(afd, (struct sockaddr*)&sin, &slen) < 0)
913         goto out;
914 
915     if (listen(afd, 1) < 0)
916         goto out;
917 
918     cfd = socket(AF_INET, SOCK_STREAM, 0);
919     if (cfd < 0)
920         goto out;
921 
922     if (set_nb(afd) == -1)
923         goto out;
924 
925     while (sfd == -1 || !cfd_connected) {
926         sfd = accept(afd, NULL, 0);
927         if (sfd == -1 && errno != EAGAIN)
928             goto out;
929 
930         if (!cfd_connected && connect(cfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
931             goto out;
932         else
933             cfd_connected = 1;
934     }
935 
936     if (set_nb(cfd) == -1 || set_nb(sfd) == -1)
937         goto out;
938     ret = 1;
939     *cfdp = cfd;
940     *sfdp = sfd;
941     goto success;
942 
943 out:
944     if (cfd != -1)
945         close(cfd);
946     if (sfd != -1)
947         close(sfd);
948 success:
949     if (afd != -1)
950         close(afd);
951     return ret;
952 }
953 
create_ssl_objects2(SSL_CTX * serverctx,SSL_CTX * clientctx,SSL ** sssl,SSL ** cssl,int sfd,int cfd)954 int create_ssl_objects2(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
955                           SSL **cssl, int sfd, int cfd)
956 {
957     SSL *serverssl = NULL, *clientssl = NULL;
958     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
959 
960     if (*sssl != NULL)
961         serverssl = *sssl;
962     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
963         goto error;
964     if (*cssl != NULL)
965         clientssl = *cssl;
966     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
967         goto error;
968 
969     if (!TEST_ptr(s_to_c_bio = BIO_new_socket(sfd, BIO_NOCLOSE))
970             || !TEST_ptr(c_to_s_bio = BIO_new_socket(cfd, BIO_NOCLOSE)))
971         goto error;
972 
973     SSL_set_bio(clientssl, c_to_s_bio, c_to_s_bio);
974     SSL_set_bio(serverssl, s_to_c_bio, s_to_c_bio);
975     *sssl = serverssl;
976     *cssl = clientssl;
977     return 1;
978 
979  error:
980     SSL_free(serverssl);
981     SSL_free(clientssl);
982     BIO_free(s_to_c_bio);
983     BIO_free(c_to_s_bio);
984     return 0;
985 }
986 #endif
987 
988 /*
989  * NOTE: Transfers control of the BIOs - this function will free them on error
990  */
create_ssl_objects(SSL_CTX * serverctx,SSL_CTX * clientctx,SSL ** sssl,SSL ** cssl,BIO * s_to_c_fbio,BIO * c_to_s_fbio)991 int create_ssl_objects(SSL_CTX *serverctx, SSL_CTX *clientctx, SSL **sssl,
992                           SSL **cssl, BIO *s_to_c_fbio, BIO *c_to_s_fbio)
993 {
994     SSL *serverssl = NULL, *clientssl = NULL;
995     BIO *s_to_c_bio = NULL, *c_to_s_bio = NULL;
996 
997     if (*sssl != NULL)
998         serverssl = *sssl;
999     else if (!TEST_ptr(serverssl = SSL_new(serverctx)))
1000         goto error;
1001     if (*cssl != NULL)
1002         clientssl = *cssl;
1003     else if (!TEST_ptr(clientssl = SSL_new(clientctx)))
1004         goto error;
1005 
1006     if (SSL_is_dtls(clientssl)) {
1007         if (!TEST_ptr(s_to_c_bio = BIO_new(bio_s_mempacket_test()))
1008                 || !TEST_ptr(c_to_s_bio = BIO_new(bio_s_mempacket_test())))
1009             goto error;
1010     } else {
1011         if (!TEST_ptr(s_to_c_bio = BIO_new(BIO_s_mem()))
1012                 || !TEST_ptr(c_to_s_bio = BIO_new(BIO_s_mem())))
1013             goto error;
1014     }
1015 
1016     if (s_to_c_fbio != NULL
1017             && !TEST_ptr(s_to_c_bio = BIO_push(s_to_c_fbio, s_to_c_bio)))
1018         goto error;
1019     if (c_to_s_fbio != NULL
1020             && !TEST_ptr(c_to_s_bio = BIO_push(c_to_s_fbio, c_to_s_bio)))
1021         goto error;
1022 
1023     /* Set Non-blocking IO behaviour */
1024     BIO_set_mem_eof_return(s_to_c_bio, -1);
1025     BIO_set_mem_eof_return(c_to_s_bio, -1);
1026 
1027     /* Up ref these as we are passing them to two SSL objects */
1028     SSL_set_bio(serverssl, c_to_s_bio, s_to_c_bio);
1029     BIO_up_ref(s_to_c_bio);
1030     BIO_up_ref(c_to_s_bio);
1031     SSL_set_bio(clientssl, s_to_c_bio, c_to_s_bio);
1032     *sssl = serverssl;
1033     *cssl = clientssl;
1034     return 1;
1035 
1036  error:
1037     SSL_free(serverssl);
1038     SSL_free(clientssl);
1039     BIO_free(s_to_c_bio);
1040     BIO_free(c_to_s_bio);
1041     BIO_free(s_to_c_fbio);
1042     BIO_free(c_to_s_fbio);
1043 
1044     return 0;
1045 }
1046 
1047 /*
1048  * Create an SSL connection, but does not read any post-handshake
1049  * NewSessionTicket messages.
1050  * If |read| is set and we're using DTLS then we will attempt to SSL_read on
1051  * the connection once we've completed one half of it, to ensure any retransmits
1052  * get triggered.
1053  * We stop the connection attempt (and return a failure value) if either peer
1054  * has SSL_get_error() return the value in the |want| parameter. The connection
1055  * attempt could be restarted by a subsequent call to this function.
1056  */
create_bare_ssl_connection(SSL * serverssl,SSL * clientssl,int want,int read,int listen)1057 int create_bare_ssl_connection(SSL *serverssl, SSL *clientssl, int want,
1058                                int read, int listen)
1059 {
1060     int retc = -1, rets = -1, err, abortctr = 0, ret = 0;
1061     int clienterr = 0, servererr = 0;
1062     int isdtls = SSL_is_dtls(serverssl);
1063 #ifndef OPENSSL_NO_SOCK
1064     BIO_ADDR *peer = NULL;
1065 
1066     if (listen) {
1067         if (!isdtls) {
1068             TEST_error("DTLSv1_listen requested for non-DTLS object\n");
1069             return 0;
1070         }
1071         peer = BIO_ADDR_new();
1072         if (!TEST_ptr(peer))
1073             return 0;
1074     }
1075 #else
1076     if (listen) {
1077         TEST_error("DTLSv1_listen requested in a no-sock build\n");
1078         return 0;
1079     }
1080 #endif
1081 
1082     do {
1083         err = SSL_ERROR_WANT_WRITE;
1084         while (!clienterr && retc <= 0 && err == SSL_ERROR_WANT_WRITE) {
1085             retc = SSL_connect(clientssl);
1086             if (retc <= 0)
1087                 err = SSL_get_error(clientssl, retc);
1088         }
1089 
1090         if (!clienterr && retc <= 0 && err != SSL_ERROR_WANT_READ) {
1091             TEST_info("SSL_connect() failed %d, %d", retc, err);
1092             if (want != SSL_ERROR_SSL)
1093                 TEST_openssl_errors();
1094             clienterr = 1;
1095         }
1096         if (want != SSL_ERROR_NONE && err == want)
1097             goto err;
1098 
1099         err = SSL_ERROR_WANT_WRITE;
1100         while (!servererr && rets <= 0 && err == SSL_ERROR_WANT_WRITE) {
1101 #ifndef OPENSSL_NO_SOCK
1102             if (listen) {
1103                 rets = DTLSv1_listen(serverssl, peer);
1104                 if (rets < 0) {
1105                     err = SSL_ERROR_SSL;
1106                 } else if (rets == 0) {
1107                     err = SSL_ERROR_WANT_READ;
1108                 } else {
1109                     /* Success - stop listening and call SSL_accept from now on */
1110                     listen = 0;
1111                     rets = 0;
1112                 }
1113             } else
1114 #endif
1115             {
1116                 rets = SSL_accept(serverssl);
1117                 if (rets <= 0)
1118                     err = SSL_get_error(serverssl, rets);
1119             }
1120         }
1121 
1122         if (!servererr && rets <= 0
1123                 && err != SSL_ERROR_WANT_READ
1124                 && err != SSL_ERROR_WANT_X509_LOOKUP) {
1125             TEST_info("SSL_accept() failed %d, %d", rets, err);
1126             if (want != SSL_ERROR_SSL)
1127                 TEST_openssl_errors();
1128             servererr = 1;
1129         }
1130         if (want != SSL_ERROR_NONE && err == want)
1131             goto err;
1132         if (clienterr && servererr)
1133             goto err;
1134         if (isdtls && read) {
1135             unsigned char buf[20];
1136 
1137             /* Trigger any retransmits that may be appropriate */
1138             if (rets > 0 && retc <= 0) {
1139                 if (SSL_read(serverssl, buf, sizeof(buf)) > 0) {
1140                     /* We don't expect this to succeed! */
1141                     TEST_info("Unexpected SSL_read() success!");
1142                     goto err;
1143                 }
1144             }
1145             if (retc > 0 && rets <= 0) {
1146                 if (SSL_read(clientssl, buf, sizeof(buf)) > 0) {
1147                     /* We don't expect this to succeed! */
1148                     TEST_info("Unexpected SSL_read() success!");
1149                     goto err;
1150                 }
1151             }
1152         }
1153         if (++abortctr == MAXLOOPS) {
1154             TEST_info("No progress made");
1155             goto err;
1156         }
1157         if (isdtls && abortctr <= 50 && (abortctr % 10) == 0) {
1158             /*
1159              * It looks like we're just spinning. Pause for a short period to
1160              * give the DTLS timer a chance to do something. We only do this for
1161              * the first few times to prevent hangs.
1162              */
1163             ossl_sleep(50);
1164         }
1165     } while (retc <=0 || rets <= 0);
1166 
1167     ret = 1;
1168  err:
1169 #ifndef OPENSSL_NO_SOCK
1170     BIO_ADDR_free(peer);
1171 #endif
1172     return ret;
1173 }
1174 
1175 /*
1176  * Create an SSL connection including any post handshake NewSessionTicket
1177  * messages.
1178  */
create_ssl_connection(SSL * serverssl,SSL * clientssl,int want)1179 int create_ssl_connection(SSL *serverssl, SSL *clientssl, int want)
1180 {
1181     int i;
1182     unsigned char buf;
1183     size_t readbytes;
1184 
1185     if (!create_bare_ssl_connection(serverssl, clientssl, want, 1, 0))
1186         return 0;
1187 
1188     /*
1189      * We attempt to read some data on the client side which we expect to fail.
1190      * This will ensure we have received the NewSessionTicket in TLSv1.3 where
1191      * appropriate. We do this twice because there are 2 NewSessionTickets.
1192      */
1193     for (i = 0; i < 2; i++) {
1194         if (SSL_read_ex(clientssl, &buf, sizeof(buf), &readbytes) > 0) {
1195             if (!TEST_ulong_eq(readbytes, 0))
1196                 return 0;
1197         } else if (!TEST_int_eq(SSL_get_error(clientssl, 0),
1198                                 SSL_ERROR_WANT_READ)) {
1199             return 0;
1200         }
1201     }
1202 
1203     return 1;
1204 }
1205 
shutdown_ssl_connection(SSL * serverssl,SSL * clientssl)1206 void shutdown_ssl_connection(SSL *serverssl, SSL *clientssl)
1207 {
1208     SSL_shutdown(clientssl);
1209     SSL_shutdown(serverssl);
1210     SSL_free(serverssl);
1211     SSL_free(clientssl);
1212 }
1213