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