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