1 /*
2  *  UDP proxy: emulate an unreliable UDP connection for DTLS testing
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 /*
21  * Warning: this is an internal utility program we use for tests.
22  * It does break some abstractions from the NET layer, and is thus NOT an
23  * example of good general usage.
24  */
25 
26 #define MBEDTLS_ALLOW_PRIVATE_ACCESS
27 
28 #include "mbedtls/build_info.h"
29 
30 #if defined(MBEDTLS_PLATFORM_C)
31 #include "mbedtls/platform.h"
32 #else
33 #include <stdio.h>
34 #include <stdlib.h>
35 #if defined(MBEDTLS_HAVE_TIME)
36 #include <time.h>
37 #define mbedtls_time            time
38 #define mbedtls_time_t          time_t
39 #endif
40 #define mbedtls_printf          printf
41 #define mbedtls_calloc          calloc
42 #define mbedtls_free            free
43 #define mbedtls_exit            exit
44 #define MBEDTLS_EXIT_SUCCESS    EXIT_SUCCESS
45 #define MBEDTLS_EXIT_FAILURE    EXIT_FAILURE
46 #endif /* MBEDTLS_PLATFORM_C */
47 
48 #if !defined(MBEDTLS_NET_C)
main(void)49 int main(void)
50 {
51     mbedtls_printf("MBEDTLS_NET_C not defined.\n");
52     mbedtls_exit(0);
53 }
54 #else
55 
56 #include "mbedtls/net_sockets.h"
57 #include "mbedtls/error.h"
58 #include "mbedtls/ssl.h"
59 #include "mbedtls/timing.h"
60 
61 #include <string.h>
62 
63 /* For select() */
64 #if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
65     !defined(EFI32)
66 #include <winsock2.h>
67 #include <windows.h>
68 #if defined(_MSC_VER)
69 #if defined(_WIN32_WCE)
70 #pragma comment( lib, "ws2.lib" )
71 #else
72 #pragma comment( lib, "ws2_32.lib" )
73 #endif
74 #endif /* _MSC_VER */
75 #else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
76 #if defined(MBEDTLS_HAVE_TIME) || (defined(MBEDTLS_TIMING_C) && !defined(MBEDTLS_TIMING_ALT))
77 #include <sys/time.h>
78 #endif
79 #include <sys/select.h>
80 #include <sys/types.h>
81 #include <unistd.h>
82 #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
83 
84 #define MAX_MSG_SIZE            16384 + 2048 /* max record/datagram size */
85 
86 #define DFL_SERVER_ADDR         "localhost"
87 #define DFL_SERVER_PORT         "4433"
88 #define DFL_LISTEN_ADDR         "localhost"
89 #define DFL_LISTEN_PORT         "5556"
90 #define DFL_PACK                0
91 
92 #if defined(MBEDTLS_TIMING_C)
93 #define USAGE_PACK                                                          \
94     "    pack=%%d             default: 0     (don't pack)\n"                \
95     "                         options: t > 0 (pack for t milliseconds)\n"
96 #else
97 #define USAGE_PACK
98 #endif
99 
100 #define USAGE                                                               \
101     "\n usage: udp_proxy param=<>...\n"                                     \
102     "\n acceptable parameters:\n"                                           \
103     "    server_addr=%%s      default: localhost\n"                         \
104     "    server_port=%%d      default: 4433\n"                              \
105     "    listen_addr=%%s      default: localhost\n"                         \
106     "    listen_port=%%d      default: 4433\n"                              \
107     "\n"                                                                    \
108     "    duplicate=%%d        default: 0 (no duplication)\n"                \
109     "                        duplicate about 1:N packets randomly\n"        \
110     "    delay=%%d            default: 0 (no delayed packets)\n"            \
111     "                        delay about 1:N packets randomly\n"            \
112     "    delay_ccs=0/1       default: 0 (don't delay ChangeCipherSpec)\n"   \
113     "    delay_cli=%%s        Handshake message from client that should be\n" \
114     "                        delayed. Possible values are 'ClientHello',\n" \
115     "                        'Certificate', 'CertificateVerify', and\n"     \
116     "                        'ClientKeyExchange'.\n"                        \
117     "                        May be used multiple times, even for the same\n" \
118     "                        message, in which case the respective message\n" \
119     "                        gets delayed multiple times.\n"                 \
120     "    delay_srv=%%s        Handshake message from server that should be\n" \
121     "                        delayed. Possible values are 'HelloRequest',\n" \
122     "                        'ServerHello', 'ServerHelloDone', 'Certificate'\n" \
123     "                        'ServerKeyExchange', 'NewSessionTicket',\n" \
124     "                        'HelloVerifyRequest' and ''CertificateRequest'.\n" \
125     "                        May be used multiple times, even for the same\n" \
126     "                        message, in which case the respective message\n" \
127     "                        gets delayed multiple times.\n"                 \
128     "    drop=%%d             default: 0 (no dropped packets)\n"            \
129     "                        drop about 1:N packets randomly\n"             \
130     "    mtu=%%d              default: 0 (unlimited)\n"                     \
131     "                        drop packets larger than N bytes\n"            \
132     "    bad_ad=0/1          default: 0 (don't add bad ApplicationData)\n"  \
133     "    bad_cid=%%d          default: 0 (don't corrupt Connection IDs)\n"   \
134     "                        duplicate 1:N packets containing a CID,\n" \
135     "                        modifying CID in first instance of the packet.\n" \
136     "    protect_hvr=0/1     default: 0 (don't protect HelloVerifyRequest)\n" \
137     "    protect_len=%%d      default: (don't protect packets of this size)\n" \
138     "    inject_clihlo=0/1   default: 0 (don't inject fake ClientHello)\n"  \
139     "\n"                                                                    \
140     "    seed=%%d             default: (use current time)\n"                \
141     USAGE_PACK                                                              \
142     "\n"
143 
144 /*
145  * global options
146  */
147 
148 #define MAX_DELAYED_HS 10
149 
150 static struct options {
151     const char *server_addr;    /* address to forward packets to            */
152     const char *server_port;    /* port to forward packets to               */
153     const char *listen_addr;    /* address for accepting client connections */
154     const char *listen_port;    /* port for accepting client connections    */
155 
156     int duplicate;              /* duplicate 1 in N packets (none if 0)     */
157     int delay;                  /* delay 1 packet in N (none if 0)          */
158     int delay_ccs;              /* delay ChangeCipherSpec                   */
159     char *delay_cli[MAX_DELAYED_HS];  /* handshake types of messages from
160                                        * client that should be delayed.     */
161     uint8_t delay_cli_cnt;      /* Number of entries in delay_cli.          */
162     char *delay_srv[MAX_DELAYED_HS];  /* handshake types of messages from
163                                        * server that should be delayed.     */
164     uint8_t delay_srv_cnt;      /* Number of entries in delay_srv.          */
165     int drop;                   /* drop 1 packet in N (none if 0)           */
166     int mtu;                    /* drop packets larger than this            */
167     int bad_ad;                 /* inject corrupted ApplicationData record  */
168     unsigned bad_cid;           /* inject corrupted CID record              */
169     int protect_hvr;            /* never drop or delay HelloVerifyRequest   */
170     int protect_len;            /* never drop/delay packet of the given size*/
171     int inject_clihlo;          /* inject fake ClientHello after handshake  */
172     unsigned pack;              /* merge packets into single datagram for
173                                  * at most \c merge milliseconds if > 0     */
174     unsigned int seed;          /* seed for "random" events                 */
175 } opt;
176 
exit_usage(const char * name,const char * value)177 static void exit_usage(const char *name, const char *value)
178 {
179     if (value == NULL) {
180         mbedtls_printf(" unknown option or missing value: %s\n", name);
181     } else {
182         mbedtls_printf(" option %s: illegal value: %s\n", name, value);
183     }
184 
185     mbedtls_printf(USAGE);
186     mbedtls_exit(1);
187 }
188 
get_options(int argc,char * argv[])189 static void get_options(int argc, char *argv[])
190 {
191     int i;
192     char *p, *q;
193 
194     opt.server_addr    = DFL_SERVER_ADDR;
195     opt.server_port    = DFL_SERVER_PORT;
196     opt.listen_addr    = DFL_LISTEN_ADDR;
197     opt.listen_port    = DFL_LISTEN_PORT;
198     opt.pack           = DFL_PACK;
199     /* Other members default to 0 */
200 
201     opt.delay_cli_cnt = 0;
202     opt.delay_srv_cnt = 0;
203     memset(opt.delay_cli, 0, sizeof(opt.delay_cli));
204     memset(opt.delay_srv, 0, sizeof(opt.delay_srv));
205 
206     for (i = 1; i < argc; i++) {
207         p = argv[i];
208         if ((q = strchr(p, '=')) == NULL) {
209             exit_usage(p, NULL);
210         }
211         *q++ = '\0';
212 
213         if (strcmp(p, "server_addr") == 0) {
214             opt.server_addr = q;
215         } else if (strcmp(p, "server_port") == 0) {
216             opt.server_port = q;
217         } else if (strcmp(p, "listen_addr") == 0) {
218             opt.listen_addr = q;
219         } else if (strcmp(p, "listen_port") == 0) {
220             opt.listen_port = q;
221         } else if (strcmp(p, "duplicate") == 0) {
222             opt.duplicate = atoi(q);
223             if (opt.duplicate < 0 || opt.duplicate > 20) {
224                 exit_usage(p, q);
225             }
226         } else if (strcmp(p, "delay") == 0) {
227             opt.delay = atoi(q);
228             if (opt.delay < 0 || opt.delay > 20 || opt.delay == 1) {
229                 exit_usage(p, q);
230             }
231         } else if (strcmp(p, "delay_ccs") == 0) {
232             opt.delay_ccs = atoi(q);
233             if (opt.delay_ccs < 0 || opt.delay_ccs > 1) {
234                 exit_usage(p, q);
235             }
236         } else if (strcmp(p, "delay_cli") == 0 ||
237                    strcmp(p, "delay_srv") == 0) {
238             uint8_t *delay_cnt;
239             char **delay_list;
240             size_t len;
241             char *buf;
242 
243             if (strcmp(p, "delay_cli") == 0) {
244                 delay_cnt  = &opt.delay_cli_cnt;
245                 delay_list = opt.delay_cli;
246             } else {
247                 delay_cnt  = &opt.delay_srv_cnt;
248                 delay_list = opt.delay_srv;
249             }
250 
251             if (*delay_cnt == MAX_DELAYED_HS) {
252                 mbedtls_printf(" too many uses of %s: only %d allowed\n",
253                                p, MAX_DELAYED_HS);
254                 exit_usage(p, NULL);
255             }
256 
257             len = strlen(q);
258             buf = mbedtls_calloc(1, len + 1);
259             if (buf == NULL) {
260                 mbedtls_printf(" Allocation failure\n");
261                 exit(1);
262             }
263             memcpy(buf, q, len + 1);
264 
265             delay_list[(*delay_cnt)++] = buf;
266         } else if (strcmp(p, "drop") == 0) {
267             opt.drop = atoi(q);
268             if (opt.drop < 0 || opt.drop > 20 || opt.drop == 1) {
269                 exit_usage(p, q);
270             }
271         } else if (strcmp(p, "pack") == 0) {
272 #if defined(MBEDTLS_TIMING_C)
273             opt.pack = (unsigned) atoi(q);
274 #else
275             mbedtls_printf(" option pack only defined if MBEDTLS_TIMING_C is enabled\n");
276             exit(1);
277 #endif
278         } else if (strcmp(p, "mtu") == 0) {
279             opt.mtu = atoi(q);
280             if (opt.mtu < 0 || opt.mtu > MAX_MSG_SIZE) {
281                 exit_usage(p, q);
282             }
283         } else if (strcmp(p, "bad_ad") == 0) {
284             opt.bad_ad = atoi(q);
285             if (opt.bad_ad < 0 || opt.bad_ad > 1) {
286                 exit_usage(p, q);
287             }
288         }
289 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
290         else if (strcmp(p, "bad_cid") == 0) {
291             opt.bad_cid = (unsigned) atoi(q);
292         }
293 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
294         else if (strcmp(p, "protect_hvr") == 0) {
295             opt.protect_hvr = atoi(q);
296             if (opt.protect_hvr < 0 || opt.protect_hvr > 1) {
297                 exit_usage(p, q);
298             }
299         } else if (strcmp(p, "protect_len") == 0) {
300             opt.protect_len = atoi(q);
301             if (opt.protect_len < 0) {
302                 exit_usage(p, q);
303             }
304         } else if (strcmp(p, "inject_clihlo") == 0) {
305             opt.inject_clihlo = atoi(q);
306             if (opt.inject_clihlo < 0 || opt.inject_clihlo > 1) {
307                 exit_usage(p, q);
308             }
309         } else if (strcmp(p, "seed") == 0) {
310             opt.seed = atoi(q);
311             if (opt.seed == 0) {
312                 exit_usage(p, q);
313             }
314         } else {
315             exit_usage(p, NULL);
316         }
317     }
318 }
319 
msg_type(unsigned char * msg,size_t len)320 static const char *msg_type(unsigned char *msg, size_t len)
321 {
322     if (len < 1) {
323         return "Invalid";
324     }
325     switch (msg[0]) {
326         case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:    return "ChangeCipherSpec";
327         case MBEDTLS_SSL_MSG_ALERT:                 return "Alert";
328         case MBEDTLS_SSL_MSG_APPLICATION_DATA:      return "ApplicationData";
329         case MBEDTLS_SSL_MSG_CID:                   return "CID";
330         case MBEDTLS_SSL_MSG_HANDSHAKE:             break; /* See below */
331         default:                            return "Unknown";
332     }
333 
334     if (len < 13 + 12) {
335         return "Invalid handshake";
336     }
337 
338     /*
339      * Our handshake message are less than 2^16 bytes long, so they should
340      * have 0 as the first byte of length, frag_offset and frag_length.
341      * Otherwise, assume they are encrypted.
342      */
343     if (msg[14] || msg[19] || msg[22]) {
344         return "Encrypted handshake";
345     }
346 
347     switch (msg[13]) {
348         case MBEDTLS_SSL_HS_HELLO_REQUEST:          return "HelloRequest";
349         case MBEDTLS_SSL_HS_CLIENT_HELLO:           return "ClientHello";
350         case MBEDTLS_SSL_HS_SERVER_HELLO:           return "ServerHello";
351         case MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST:   return "HelloVerifyRequest";
352         case MBEDTLS_SSL_HS_NEW_SESSION_TICKET:     return "NewSessionTicket";
353         case MBEDTLS_SSL_HS_CERTIFICATE:            return "Certificate";
354         case MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE:    return "ServerKeyExchange";
355         case MBEDTLS_SSL_HS_CERTIFICATE_REQUEST:    return "CertificateRequest";
356         case MBEDTLS_SSL_HS_SERVER_HELLO_DONE:      return "ServerHelloDone";
357         case MBEDTLS_SSL_HS_CERTIFICATE_VERIFY:     return "CertificateVerify";
358         case MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE:    return "ClientKeyExchange";
359         case MBEDTLS_SSL_HS_FINISHED:               return "Finished";
360         default:                            return "Unknown handshake";
361     }
362 }
363 
364 #if defined(MBEDTLS_TIMING_C)
365 /* Return elapsed time in milliseconds since the first call */
elapsed_time(void)366 static unsigned elapsed_time(void)
367 {
368     static int initialized = 0;
369     static struct mbedtls_timing_hr_time hires;
370 
371     if (initialized == 0) {
372         (void) mbedtls_timing_get_timer(&hires, 1);
373         initialized = 1;
374         return 0;
375     }
376 
377     return mbedtls_timing_get_timer(&hires, 0);
378 }
379 
380 typedef struct {
381     mbedtls_net_context *ctx;
382 
383     const char *description;
384 
385     unsigned packet_lifetime;
386     unsigned num_datagrams;
387 
388     unsigned char data[MAX_MSG_SIZE];
389     size_t len;
390 
391 } ctx_buffer;
392 
393 static ctx_buffer outbuf[2];
394 
ctx_buffer_flush(ctx_buffer * buf)395 static int ctx_buffer_flush(ctx_buffer *buf)
396 {
397     int ret;
398 
399     mbedtls_printf("  %05u flush    %s: %u bytes, %u datagrams, last %u ms\n",
400                    elapsed_time(), buf->description,
401                    (unsigned) buf->len, buf->num_datagrams,
402                    elapsed_time() - buf->packet_lifetime);
403 
404     ret = mbedtls_net_send(buf->ctx, buf->data, buf->len);
405 
406     buf->len           = 0;
407     buf->num_datagrams = 0;
408 
409     return ret;
410 }
411 
ctx_buffer_time_remaining(ctx_buffer * buf)412 static unsigned ctx_buffer_time_remaining(ctx_buffer *buf)
413 {
414     unsigned const cur_time = elapsed_time();
415 
416     if (buf->num_datagrams == 0) {
417         return (unsigned) -1;
418     }
419 
420     if (cur_time - buf->packet_lifetime >= opt.pack) {
421         return 0;
422     }
423 
424     return opt.pack - (cur_time - buf->packet_lifetime);
425 }
426 
ctx_buffer_append(ctx_buffer * buf,const unsigned char * data,size_t len)427 static int ctx_buffer_append(ctx_buffer *buf,
428                              const unsigned char *data,
429                              size_t len)
430 {
431     int ret;
432 
433     if (len > (size_t) INT_MAX) {
434         return -1;
435     }
436 
437     if (len > sizeof(buf->data)) {
438         mbedtls_printf("  ! buffer size %u too large (max %u)\n",
439                        (unsigned) len, (unsigned) sizeof(buf->data));
440         return -1;
441     }
442 
443     if (sizeof(buf->data) - buf->len < len) {
444         if ((ret = ctx_buffer_flush(buf)) <= 0) {
445             mbedtls_printf("ctx_buffer_flush failed with -%#04x", (unsigned int) -ret);
446             return ret;
447         }
448     }
449 
450     memcpy(buf->data + buf->len, data, len);
451 
452     buf->len += len;
453     if (++buf->num_datagrams == 1) {
454         buf->packet_lifetime = elapsed_time();
455     }
456 
457     return (int) len;
458 }
459 #endif /* MBEDTLS_TIMING_C */
460 
dispatch_data(mbedtls_net_context * ctx,const unsigned char * data,size_t len)461 static int dispatch_data(mbedtls_net_context *ctx,
462                          const unsigned char *data,
463                          size_t len)
464 {
465     int ret;
466 #if defined(MBEDTLS_TIMING_C)
467     ctx_buffer *buf = NULL;
468     if (opt.pack > 0) {
469         if (outbuf[0].ctx == ctx) {
470             buf = &outbuf[0];
471         } else if (outbuf[1].ctx == ctx) {
472             buf = &outbuf[1];
473         }
474 
475         if (buf == NULL) {
476             return -1;
477         }
478 
479         return ctx_buffer_append(buf, data, len);
480     }
481 #endif /* MBEDTLS_TIMING_C */
482 
483     ret = mbedtls_net_send(ctx, data, len);
484     if (ret < 0) {
485         mbedtls_printf("net_send returned -%#04x\n", (unsigned int) -ret);
486     }
487     return ret;
488 }
489 
490 typedef struct {
491     mbedtls_net_context *dst;
492     const char *way;
493     const char *type;
494     unsigned len;
495     unsigned char buf[MAX_MSG_SIZE];
496 } packet;
497 
498 /* Print packet. Outgoing packets come with a reason (forward, dupl, etc.) */
print_packet(const packet * p,const char * why)499 void print_packet(const packet *p, const char *why)
500 {
501 #if defined(MBEDTLS_TIMING_C)
502     if (why == NULL) {
503         mbedtls_printf("  %05u dispatch %s %s (%u bytes)\n",
504                        elapsed_time(), p->way, p->type, p->len);
505     } else {
506         mbedtls_printf("  %05u dispatch %s %s (%u bytes): %s\n",
507                        elapsed_time(), p->way, p->type, p->len, why);
508     }
509 #else
510     if (why == NULL) {
511         mbedtls_printf("        dispatch %s %s (%u bytes)\n",
512                        p->way, p->type, p->len);
513     } else {
514         mbedtls_printf("        dispatch %s %s (%u bytes): %s\n",
515                        p->way, p->type, p->len, why);
516     }
517 #endif
518 
519     fflush(stdout);
520 }
521 
522 /*
523  * In order to test the server's behaviour when receiving a ClientHello after
524  * the connection is established (this could be a hard reset from the client,
525  * but the server must not drop the existing connection before establishing
526  * client reachability, see RFC 6347 Section 4.2.8), we memorize the first
527  * ClientHello we see (which can't have a cookie), then replay it after the
528  * first ApplicationData record - then we're done.
529  *
530  * This is controlled by the inject_clihlo option.
531  *
532  * We want an explicit state and a place to store the packet.
533  */
534 typedef enum {
535     ICH_INIT,       /* haven't seen the first ClientHello yet */
536     ICH_CACHED,     /* cached the initial ClientHello */
537     ICH_INJECTED,   /* ClientHello already injected, done */
538 } inject_clihlo_state_t;
539 
540 static inject_clihlo_state_t inject_clihlo_state;
541 static packet initial_clihlo;
542 
send_packet(const packet * p,const char * why)543 int send_packet(const packet *p, const char *why)
544 {
545     int ret;
546     mbedtls_net_context *dst = p->dst;
547 
548     /* save initial ClientHello? */
549     if (opt.inject_clihlo != 0 &&
550         inject_clihlo_state == ICH_INIT &&
551         strcmp(p->type, "ClientHello") == 0) {
552         memcpy(&initial_clihlo, p, sizeof(packet));
553         inject_clihlo_state = ICH_CACHED;
554     }
555 
556     /* insert corrupted CID record? */
557     if (opt.bad_cid != 0 &&
558         strcmp(p->type, "CID") == 0 &&
559         (rand() % opt.bad_cid) == 0) {
560         unsigned char buf[MAX_MSG_SIZE];
561         memcpy(buf, p->buf, p->len);
562 
563         /* The CID resides at offset 11 in the DTLS record header. */
564         buf[11] ^= 1;
565         print_packet(p, "modified CID");
566 
567         if ((ret = dispatch_data(dst, buf, p->len)) <= 0) {
568             mbedtls_printf("  ! dispatch returned %d\n", ret);
569             return ret;
570         }
571     }
572 
573     /* insert corrupted ApplicationData record? */
574     if (opt.bad_ad &&
575         strcmp(p->type, "ApplicationData") == 0) {
576         unsigned char buf[MAX_MSG_SIZE];
577         memcpy(buf, p->buf, p->len);
578 
579         if (p->len <= 13) {
580             mbedtls_printf("  ! can't corrupt empty AD record");
581         } else {
582             ++buf[13];
583             print_packet(p, "corrupted");
584         }
585 
586         if ((ret = dispatch_data(dst, buf, p->len)) <= 0) {
587             mbedtls_printf("  ! dispatch returned %d\n", ret);
588             return ret;
589         }
590     }
591 
592     print_packet(p, why);
593     if ((ret = dispatch_data(dst, p->buf, p->len)) <= 0) {
594         mbedtls_printf("  ! dispatch returned %d\n", ret);
595         return ret;
596     }
597 
598     /* Don't duplicate Application Data, only handshake covered */
599     if (opt.duplicate != 0 &&
600         strcmp(p->type, "ApplicationData") != 0 &&
601         rand() % opt.duplicate == 0) {
602         print_packet(p, "duplicated");
603 
604         if ((ret = dispatch_data(dst, p->buf, p->len)) <= 0) {
605             mbedtls_printf("  ! dispatch returned %d\n", ret);
606             return ret;
607         }
608     }
609 
610     /* Inject ClientHello after first ApplicationData */
611     if (opt.inject_clihlo != 0 &&
612         inject_clihlo_state == ICH_CACHED &&
613         strcmp(p->type, "ApplicationData") == 0) {
614         print_packet(&initial_clihlo, "injected");
615 
616         if ((ret = dispatch_data(dst, initial_clihlo.buf,
617                                  initial_clihlo.len)) <= 0) {
618             mbedtls_printf("  ! dispatch returned %d\n", ret);
619             return ret;
620         }
621 
622         inject_clihlo_state = ICH_INJECTED;
623     }
624 
625     return 0;
626 }
627 
628 #define MAX_DELAYED_MSG 5
629 static size_t prev_len;
630 static packet prev[MAX_DELAYED_MSG];
631 
clear_pending(void)632 void clear_pending(void)
633 {
634     memset(&prev, 0, sizeof(prev));
635     prev_len = 0;
636 }
637 
delay_packet(packet * delay)638 void delay_packet(packet *delay)
639 {
640     if (prev_len == MAX_DELAYED_MSG) {
641         return;
642     }
643 
644     memcpy(&prev[prev_len++], delay, sizeof(packet));
645 }
646 
send_delayed()647 int send_delayed()
648 {
649     uint8_t offset;
650     int ret;
651     for (offset = 0; offset < prev_len; offset++) {
652         ret = send_packet(&prev[offset], "delayed");
653         if (ret != 0) {
654             return ret;
655         }
656     }
657 
658     clear_pending();
659     return 0;
660 }
661 
662 /*
663  * Avoid dropping or delaying a packet that was already dropped or delayed
664  * ("held") twice: this only results in uninteresting timeouts. We can't rely
665  * on type to identify packets, since during renegotiation they're all
666  * encrypted. So, rely on size mod 2048 (which is usually just size).
667  *
668  * We only hold packets at the level of entire datagrams, not at the level
669  * of records. In particular, if the peer changes the way it packs multiple
670  * records into a single datagram, we don't necessarily count the number of
671  * times a record has been held correctly. However, the only known reason
672  * why a peer would change datagram packing is disabling the latter on
673  * retransmission, in which case we'd hold involved records at most
674  * HOLD_MAX + 1 times.
675  */
676 static unsigned char held[2048] = { 0 };
677 #define HOLD_MAX 2
678 
handle_message(const char * way,mbedtls_net_context * dst,mbedtls_net_context * src)679 int handle_message(const char *way,
680                    mbedtls_net_context *dst,
681                    mbedtls_net_context *src)
682 {
683     int ret;
684     packet cur;
685     size_t id;
686 
687     uint8_t delay_idx;
688     char **delay_list;
689     uint8_t delay_list_len;
690 
691     /* receive packet */
692     if ((ret = mbedtls_net_recv(src, cur.buf, sizeof(cur.buf))) <= 0) {
693         mbedtls_printf("  ! mbedtls_net_recv returned %d\n", ret);
694         return ret;
695     }
696 
697     cur.len  = ret;
698     cur.type = msg_type(cur.buf, cur.len);
699     cur.way  = way;
700     cur.dst  = dst;
701     print_packet(&cur, NULL);
702 
703     id = cur.len % sizeof(held);
704 
705     if (strcmp(way, "S <- C") == 0) {
706         delay_list     = opt.delay_cli;
707         delay_list_len = opt.delay_cli_cnt;
708     } else {
709         delay_list     = opt.delay_srv;
710         delay_list_len = opt.delay_srv_cnt;
711     }
712 
713     /* Check if message type is in the list of messages
714      * that should be delayed */
715     for (delay_idx = 0; delay_idx < delay_list_len; delay_idx++) {
716         if (delay_list[delay_idx] == NULL) {
717             continue;
718         }
719 
720         if (strcmp(delay_list[delay_idx], cur.type) == 0) {
721             /* Delay message */
722             delay_packet(&cur);
723 
724             /* Remove entry from list */
725             mbedtls_free(delay_list[delay_idx]);
726             delay_list[delay_idx] = NULL;
727 
728             return 0;
729         }
730     }
731 
732     /* do we want to drop, delay, or forward it? */
733     if ((opt.mtu != 0 &&
734          cur.len > (unsigned) opt.mtu) ||
735         (opt.drop != 0 &&
736          strcmp(cur.type, "CID") != 0             &&
737          strcmp(cur.type, "ApplicationData") != 0 &&
738          !(opt.protect_hvr &&
739            strcmp(cur.type, "HelloVerifyRequest") == 0) &&
740          cur.len != (size_t) opt.protect_len &&
741          held[id] < HOLD_MAX &&
742          rand() % opt.drop == 0)) {
743         ++held[id];
744     } else if ((opt.delay_ccs == 1 &&
745                 strcmp(cur.type, "ChangeCipherSpec") == 0) ||
746                (opt.delay != 0 &&
747                 strcmp(cur.type, "CID") != 0             &&
748                 strcmp(cur.type, "ApplicationData") != 0 &&
749                 !(opt.protect_hvr &&
750                   strcmp(cur.type, "HelloVerifyRequest") == 0) &&
751                 cur.len != (size_t) opt.protect_len &&
752                 held[id] < HOLD_MAX &&
753                 rand() % opt.delay == 0)) {
754         ++held[id];
755         delay_packet(&cur);
756     } else {
757         /* forward and possibly duplicate */
758         if ((ret = send_packet(&cur, "forwarded")) != 0) {
759             return ret;
760         }
761 
762         /* send previously delayed messages if any */
763         ret = send_delayed();
764         if (ret != 0) {
765             return ret;
766         }
767     }
768 
769     return 0;
770 }
771 
main(int argc,char * argv[])772 int main(int argc, char *argv[])
773 {
774     int ret = 1;
775     int exit_code = MBEDTLS_EXIT_FAILURE;
776     uint8_t delay_idx;
777 
778     mbedtls_net_context listen_fd, client_fd, server_fd;
779 
780 #if defined(MBEDTLS_TIMING_C)
781     struct timeval tm;
782 #endif
783 
784     struct timeval *tm_ptr = NULL;
785 
786     int nb_fds;
787     fd_set read_fds;
788 
789     mbedtls_net_init(&listen_fd);
790     mbedtls_net_init(&client_fd);
791     mbedtls_net_init(&server_fd);
792 
793     get_options(argc, argv);
794 
795     /*
796      * Decisions to drop/delay/duplicate packets are pseudo-random: dropping
797      * exactly 1 in N packets would lead to problems when a flight has exactly
798      * N packets: the same packet would be dropped on every resend.
799      *
800      * In order to be able to reproduce problems reliably, the seed may be
801      * specified explicitly.
802      */
803     if (opt.seed == 0) {
804 #if defined(MBEDTLS_HAVE_TIME)
805         opt.seed = (unsigned int) mbedtls_time(NULL);
806 #else
807         opt.seed = 1;
808 #endif /* MBEDTLS_HAVE_TIME */
809         mbedtls_printf("  . Pseudo-random seed: %u\n", opt.seed);
810     }
811 
812     srand(opt.seed);
813 
814     /*
815      * 0. "Connect" to the server
816      */
817     mbedtls_printf("  . Connect to server on UDP/%s/%s ...",
818                    opt.server_addr, opt.server_port);
819     fflush(stdout);
820 
821     if ((ret = mbedtls_net_connect(&server_fd, opt.server_addr, opt.server_port,
822                                    MBEDTLS_NET_PROTO_UDP)) != 0) {
823         mbedtls_printf(" failed\n  ! mbedtls_net_connect returned %d\n\n", ret);
824         goto exit;
825     }
826 
827     mbedtls_printf(" ok\n");
828 
829     /*
830      * 1. Setup the "listening" UDP socket
831      */
832     mbedtls_printf("  . Bind on UDP/%s/%s ...",
833                    opt.listen_addr, opt.listen_port);
834     fflush(stdout);
835 
836     if ((ret = mbedtls_net_bind(&listen_fd, opt.listen_addr, opt.listen_port,
837                                 MBEDTLS_NET_PROTO_UDP)) != 0) {
838         mbedtls_printf(" failed\n  ! mbedtls_net_bind returned %d\n\n", ret);
839         goto exit;
840     }
841 
842     mbedtls_printf(" ok\n");
843 
844     /*
845      * 2. Wait until a client connects
846      */
847 accept:
848     mbedtls_net_free(&client_fd);
849 
850     mbedtls_printf("  . Waiting for a remote connection ...");
851     fflush(stdout);
852 
853     if ((ret = mbedtls_net_accept(&listen_fd, &client_fd,
854                                   NULL, 0, NULL)) != 0) {
855         mbedtls_printf(" failed\n  ! mbedtls_net_accept returned %d\n\n", ret);
856         goto exit;
857     }
858 
859     mbedtls_printf(" ok\n");
860 
861     /*
862      * 3. Forward packets forever (kill the process to terminate it)
863      */
864     clear_pending();
865     memset(held, 0, sizeof(held));
866 
867     nb_fds = client_fd.fd;
868     if (nb_fds < server_fd.fd) {
869         nb_fds = server_fd.fd;
870     }
871     if (nb_fds < listen_fd.fd) {
872         nb_fds = listen_fd.fd;
873     }
874     ++nb_fds;
875 
876 #if defined(MBEDTLS_TIMING_C)
877     if (opt.pack > 0) {
878         outbuf[0].ctx = &server_fd;
879         outbuf[0].description = "S <- C";
880         outbuf[0].num_datagrams = 0;
881         outbuf[0].len = 0;
882 
883         outbuf[1].ctx = &client_fd;
884         outbuf[1].description = "S -> C";
885         outbuf[1].num_datagrams = 0;
886         outbuf[1].len = 0;
887     }
888 #endif /* MBEDTLS_TIMING_C */
889 
890     while (1) {
891 #if defined(MBEDTLS_TIMING_C)
892         if (opt.pack > 0) {
893             unsigned max_wait_server, max_wait_client, max_wait;
894             max_wait_server = ctx_buffer_time_remaining(&outbuf[0]);
895             max_wait_client = ctx_buffer_time_remaining(&outbuf[1]);
896 
897             max_wait = (unsigned) -1;
898 
899             if (max_wait_server == 0) {
900                 ctx_buffer_flush(&outbuf[0]);
901             } else {
902                 max_wait = max_wait_server;
903             }
904 
905             if (max_wait_client == 0) {
906                 ctx_buffer_flush(&outbuf[1]);
907             } else {
908                 if (max_wait_client < max_wait) {
909                     max_wait = max_wait_client;
910                 }
911             }
912 
913             if (max_wait != (unsigned) -1) {
914                 tm.tv_sec  = max_wait / 1000;
915                 tm.tv_usec = (max_wait % 1000) * 1000;
916 
917                 tm_ptr = &tm;
918             } else {
919                 tm_ptr = NULL;
920             }
921         }
922 #endif /* MBEDTLS_TIMING_C */
923 
924         FD_ZERO(&read_fds);
925         FD_SET(server_fd.fd, &read_fds);
926         FD_SET(client_fd.fd, &read_fds);
927         FD_SET(listen_fd.fd, &read_fds);
928 
929         if ((ret = select(nb_fds, &read_fds, NULL, NULL, tm_ptr)) < 0) {
930             perror("select");
931             goto exit;
932         }
933 
934         if (FD_ISSET(listen_fd.fd, &read_fds)) {
935             goto accept;
936         }
937 
938         if (FD_ISSET(client_fd.fd, &read_fds)) {
939             if ((ret = handle_message("S <- C",
940                                       &server_fd, &client_fd)) != 0) {
941                 goto accept;
942             }
943         }
944 
945         if (FD_ISSET(server_fd.fd, &read_fds)) {
946             if ((ret = handle_message("S -> C",
947                                       &client_fd, &server_fd)) != 0) {
948                 goto accept;
949             }
950         }
951 
952     }
953 
954     exit_code = MBEDTLS_EXIT_SUCCESS;
955 
956 exit:
957 
958 #ifdef MBEDTLS_ERROR_C
959     if (exit_code != MBEDTLS_EXIT_SUCCESS) {
960         char error_buf[100];
961         mbedtls_strerror(ret, error_buf, 100);
962         mbedtls_printf("Last error was: -0x%04X - %s\n\n", (unsigned int) -ret, error_buf);
963         fflush(stdout);
964     }
965 #endif
966 
967     for (delay_idx = 0; delay_idx < MAX_DELAYED_HS; delay_idx++) {
968         mbedtls_free(opt.delay_cli[delay_idx]);
969         mbedtls_free(opt.delay_srv[delay_idx]);
970     }
971 
972     mbedtls_net_free(&client_fd);
973     mbedtls_net_free(&server_fd);
974     mbedtls_net_free(&listen_fd);
975 
976     mbedtls_exit(exit_code);
977 }
978 
979 #endif /* MBEDTLS_NET_C */
980