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