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