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