udp_proxy.c 18.9 KB
Newer Older
1 2 3
/*
 *  UDP proxy: emulate an unreliable UDP connexion for DTLS testing
 *
4
 *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5
 *  SPDX-License-Identifier: Apache-2.0
6
 *
7 8 9
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
 *  not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
10
 *
11
 *  http://www.apache.org/licenses/LICENSE-2.0
12
 *
13 14 15 16 17
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
18
 *
19
 *  This file is part of mbed TLS (https://tls.mbed.org)
20 21
 */

22 23 24 25 26 27
/*
 * Warning: this is an internal utility program we use for tests.
 * It does break some abstractions from the NET layer, and is thus NOT an
 * example of good general usage.
 */

28
#if !defined(MBEDTLS_CONFIG_FILE)
29
#include "mbedtls/config.h"
30
#else
31
#include MBEDTLS_CONFIG_FILE
32 33
#endif

34
#if defined(MBEDTLS_PLATFORM_C)
35
#include "mbedtls/platform.h"
36
#else
37 38 39 40 41
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define mbedtls_time       time
#define mbedtls_time_t     time_t
42
#define mbedtls_printf     printf
43 44
#endif

45
#if !defined(MBEDTLS_NET_C)
46 47
int main( void )
{
48
    mbedtls_printf( "MBEDTLS_NET_C not defined.\n" );
49 50 51 52
    return( 0 );
}
#else

53 54 55
#include "mbedtls/net.h"
#include "mbedtls/error.h"
#include "mbedtls/ssl.h"
56

57
#include <string.h>
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

/* For select() */
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
    !defined(EFI32)
#include <winsock2.h>
#include <windows.h>
#if defined(_MSC_VER)
#if defined(_WIN32_WCE)
#pragma comment( lib, "ws2.lib" )
#else
#pragma comment( lib, "ws2_32.lib" )
#endif
#endif /* _MSC_VER */
#else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */

77 78 79 80 81
/* For gettimeofday() */
#if !defined(_WIN32)
#include <sys/time.h>
#endif

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

89 90 91
#define USAGE                                                               \
    "\n usage: udp_proxy param=<>...\n"                                     \
    "\n acceptable parameters:\n"                                           \
92
    "    server_addr=%%s      default: localhost\n"                         \
93
    "    server_port=%%d      default: 4433\n"                              \
94
    "    listen_addr=%%s      default: localhost\n"                         \
95
    "    listen_port=%%d      default: 4433\n"                              \
96 97
    "\n"                                                                    \
    "    duplicate=%%d        default: 0 (no duplication)\n"                \
98
    "                        duplicate about 1:N packets randomly\n"        \
99
    "    delay=%%d            default: 0 (no delayed packets)\n"            \
100
    "                        delay about 1:N packets randomly\n"            \
101
    "    delay_ccs=0/1       default: 0 (don't delay ChangeCipherSpec)\n"   \
102
    "    drop=%%d             default: 0 (no dropped packets)\n"            \
103
    "                        drop about 1:N packets randomly\n"             \
104 105
    "    mtu=%%d              default: 0 (unlimited)\n"                     \
    "                        drop packets larger than N bytes\n"            \
106 107
    "    bad_ad=0/1          default: 0 (don't add bad ApplicationData)\n"  \
    "    protect_hvr=0/1     default: 0 (don't protect HelloVerifyRequest)\n" \
108
    "    protect_len=%%d     default: (don't protect packets of this size)\n" \
109 110
    "\n"                                                                    \
    "    seed=%%d             default: (use current time)\n"                \
111 112
    "\n"

113 114 115
/*
 * global options
 */
116
static struct options
117 118
{
    const char *server_addr;    /* address to forward packets to            */
119
    const char *server_port;    /* port to forward packets to               */
120
    const char *listen_addr;    /* address for accepting client connections */
121
    const char *listen_port;    /* port for accepting client connections    */
122 123

    int duplicate;              /* duplicate 1 in N packets (none if 0)     */
124
    int delay;                  /* delay 1 packet in N (none if 0)          */
125
    int delay_ccs;              /* delay ChangeCipherSpec                   */
126
    int drop;                   /* drop 1 packet in N (none if 0)           */
127
    int mtu;                    /* drop packets larger than this            */
128
    int bad_ad;                 /* inject corrupted ApplicationData record  */
129
    int protect_hvr;            /* never drop or delay HelloVerifyRequest   */
130
    int protect_len;            /* never drop/delay packet of the given size*/
131

132 133
    unsigned int seed;          /* seed for "random" events                 */
} opt;
134

135
static void exit_usage( const char *name, const char *value )
136
{
137
    if( value == NULL )
138
        mbedtls_printf( " unknown option or missing value: %s\n", name );
139
    else
140
        mbedtls_printf( " option %s: illegal value: %s\n", name, value );
141

142
    mbedtls_printf( USAGE );
143 144 145 146 147 148 149 150 151 152 153 154
    exit( 1 );
}

static void get_options( int argc, char *argv[] )
{
    int i;
    char *p, *q;

    opt.server_addr    = DFL_SERVER_ADDR;
    opt.server_port    = DFL_SERVER_PORT;
    opt.listen_addr    = DFL_LISTEN_ADDR;
    opt.listen_port    = DFL_LISTEN_PORT;
155
    /* Other members default to 0 */
156 157 158 159 160

    for( i = 1; i < argc; i++ )
    {
        p = argv[i];
        if( ( q = strchr( p, '=' ) ) == NULL )
161
            exit_usage( p, NULL );
162 163 164 165 166
        *q++ = '\0';

        if( strcmp( p, "server_addr" ) == 0 )
            opt.server_addr = q;
        else if( strcmp( p, "server_port" ) == 0 )
167
            opt.server_port = q;
168 169 170
        else if( strcmp( p, "listen_addr" ) == 0 )
            opt.listen_addr = q;
        else if( strcmp( p, "listen_port" ) == 0 )
171
            opt.listen_port = q;
172 173 174
        else if( strcmp( p, "duplicate" ) == 0 )
        {
            opt.duplicate = atoi( q );
175
            if( opt.duplicate < 0 || opt.duplicate > 20 )
176 177
                exit_usage( p, q );
        }
178 179 180
        else if( strcmp( p, "delay" ) == 0 )
        {
            opt.delay = atoi( q );
181
            if( opt.delay < 0 || opt.delay > 20 || opt.delay == 1 )
182 183
                exit_usage( p, q );
        }
184 185 186 187 188 189
        else if( strcmp( p, "delay_ccs" ) == 0 )
        {
            opt.delay_ccs = atoi( q );
            if( opt.delay_ccs < 0 || opt.delay_ccs > 1 )
                exit_usage( p, q );
        }
190 191 192
        else if( strcmp( p, "drop" ) == 0 )
        {
            opt.drop = atoi( q );
193
            if( opt.drop < 0 || opt.drop > 20 || opt.drop == 1 )
194 195
                exit_usage( p, q );
        }
196 197 198 199 200 201
        else if( strcmp( p, "mtu" ) == 0 )
        {
            opt.mtu = atoi( q );
            if( opt.mtu < 0 || opt.mtu > MAX_MSG_SIZE )
                exit_usage( p, q );
        }
202 203 204 205 206 207
        else if( strcmp( p, "bad_ad" ) == 0 )
        {
            opt.bad_ad = atoi( q );
            if( opt.bad_ad < 0 || opt.bad_ad > 1 )
                exit_usage( p, q );
        }
208 209 210 211 212 213
        else if( strcmp( p, "protect_hvr" ) == 0 )
        {
            opt.protect_hvr = atoi( q );
            if( opt.protect_hvr < 0 || opt.protect_hvr > 1 )
                exit_usage( p, q );
        }
214 215 216 217 218 219
        else if( strcmp( p, "protect_len" ) == 0 )
        {
            opt.protect_len = atoi( q );
            if( opt.protect_len < 0 )
                exit_usage( p, q );
        }
220 221 222 223 224 225
        else if( strcmp( p, "seed" ) == 0 )
        {
            opt.seed = atoi( q );
            if( opt.seed == 0 )
                exit_usage( p, q );
        }
226
        else
227 228 229 230 231 232 233 234 235
            exit_usage( p, NULL );
    }
}

static const char *msg_type( unsigned char *msg, size_t len )
{
    if( len < 1 )                           return( "Invalid" );
    switch( msg[0] )
    {
236 237 238 239
        case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:    return( "ChangeCipherSpec" );
        case MBEDTLS_SSL_MSG_ALERT:                 return( "Alert" );
        case MBEDTLS_SSL_MSG_APPLICATION_DATA:      return( "ApplicationData" );
        case MBEDTLS_SSL_MSG_HANDSHAKE:             break; /* See below */
240 241 242
        default:                            return( "Unknown" );
    }

243 244 245 246 247 248 249 250 251
    if( len < 13 + 12 )                     return( "Invalid handshake" );

    /*
     * Our handshake message are less than 2^16 bytes long, so they should
     * have 0 as the first byte of length, frag_offset and frag_length.
     * Otherwise, assume they are encrypted.
     */
    if( msg[14] || msg[19] || msg[22] )     return( "Encrypted handshake" );

252 253
    switch( msg[13] )
    {
254 255 256 257 258 259 260 261 262 263 264 265
        case MBEDTLS_SSL_HS_HELLO_REQUEST:          return( "HelloRequest" );
        case MBEDTLS_SSL_HS_CLIENT_HELLO:           return( "ClientHello" );
        case MBEDTLS_SSL_HS_SERVER_HELLO:           return( "ServerHello" );
        case MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST:   return( "HelloVerifyRequest" );
        case MBEDTLS_SSL_HS_NEW_SESSION_TICKET:     return( "NewSessionTicket" );
        case MBEDTLS_SSL_HS_CERTIFICATE:            return( "Certificate" );
        case MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE:    return( "ServerKeyExchange" );
        case MBEDTLS_SSL_HS_CERTIFICATE_REQUEST:    return( "CertificateRequest" );
        case MBEDTLS_SSL_HS_SERVER_HELLO_DONE:      return( "ServerHelloDone" );
        case MBEDTLS_SSL_HS_CERTIFICATE_VERIFY:     return( "CertificateVerify" );
        case MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE:    return( "ClientKeyExchange" );
        case MBEDTLS_SSL_HS_FINISHED:               return( "Finished" );
266
        default:                            return( "Unknown handshake" );
267 268 269
    }
}

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
/* Return elapsed time in milliseconds since the first call */
static unsigned long ellapsed_time( void )
{
#if defined(_WIN32)
    return( 0 );
#else
    static struct timeval ref = { 0, 0 };
    struct timeval now;

    if( ref.tv_sec == 0 && ref.tv_usec == 0 )
    {
        gettimeofday( &ref, NULL );
        return( 0 );
    }

    gettimeofday( &now, NULL );
    return( 1000 * ( now.tv_sec  - ref.tv_sec )
                 + ( now.tv_usec - ref.tv_usec ) / 1000 );
#endif
}

291
typedef struct
292
{
293
    mbedtls_net_context *dst;
294
    const char *way;
295
    const char *type;
296 297 298 299 300 301 302 303
    unsigned len;
    unsigned char buf[MAX_MSG_SIZE];
} packet;

/* Print packet. Outgoing packets come with a reason (forward, dupl, etc.) */
void print_packet( const packet *p, const char *why )
{
    if( why == NULL )
304
        mbedtls_printf( "  %05lu %s %s (%u bytes)\n",
305
                ellapsed_time(), p->way, p->type, p->len );
306
    else
307
        mbedtls_printf( "        %s %s (%u bytes): %s\n",
308
                p->way, p->type, p->len, why );
309 310 311 312 313 314
    fflush( stdout );
}

int send_packet( const packet *p, const char *why )
{
    int ret;
315
    mbedtls_net_context *dst = p->dst;
316

317 318 319 320 321 322 323 324 325
    /* insert corrupted ApplicationData record? */
    if( opt.bad_ad &&
        strcmp( p->type, "ApplicationData" ) == 0 )
    {
        unsigned char buf[MAX_MSG_SIZE];
        memcpy( buf, p->buf, p->len );
        ++buf[p->len - 1];

        print_packet( p, "corrupted" );
326
        if( ( ret = mbedtls_net_send( dst, buf, p->len ) ) <= 0 )
327
        {
328
            mbedtls_printf( "  ! mbedtls_net_send returned %d\n", ret );
329 330 331 332
            return( ret );
        }
    }

333
    print_packet( p, why );
334
    if( ( ret = mbedtls_net_send( dst, p->buf, p->len ) ) <= 0 )
335
    {
336
        mbedtls_printf( "  ! mbedtls_net_send returned %d\n", ret );
337 338 339
        return( ret );
    }

340 341
    /* Don't duplicate Application Data, only handshake covered */
    if( opt.duplicate != 0 &&
342
        strcmp( p->type, "ApplicationData" ) != 0 &&
343
        rand() % opt.duplicate == 0 )
344
    {
345
        print_packet( p, "duplicated" );
346

347
        if( ( ret = mbedtls_net_send( dst, p->buf, p->len ) ) <= 0 )
348
        {
349
            mbedtls_printf( "  ! mbedtls_net_send returned %d\n", ret );
350 351 352
            return( ret );
        }
    }
353

354 355 356
    return( 0 );
}

357 358 359 360 361 362 363
static packet prev;

void clear_pending( void )
{
    memset( &prev, 0, sizeof( packet ) );
}

364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
/*
 * Avoid dropping or delaying a packet that was already dropped twice: this
 * only results in uninteresting timeouts. We can't rely on type to identify
 * packets, since during renegotiation they're all encrypted.  So, rely on
 * size mod 2048 (which is usually just size).
 */
static unsigned char dropped[2048] = { 0 };
#define DROP_MAX 2

/*
 * OpenSSL groups packets in a datagram the first time it sends them, but not
 * when it resends them. Count every record as seen the first time.
 */
void update_dropped( const packet *p )
{
    size_t id = p->len % sizeof( dropped );
    const unsigned char *end = p->buf + p->len;
    const unsigned char *cur = p->buf;
    size_t len = ( ( cur[11] << 8 ) | cur[12] ) + 13;

384 385
    ++dropped[id];

386 387 388 389 390 391
    /* Avoid counting single record twice */
    if( len == p->len )
        return;

    while( cur < end )
    {
392
        len = ( ( cur[11] << 8 ) | cur[12] ) + 13;
393 394 395 396 397 398 399 400

        id = len % sizeof( dropped );
        ++dropped[id];

        cur += len;
    }
}

401 402 403
int handle_message( const char *way,
                    mbedtls_net_context *dst,
                    mbedtls_net_context *src )
404 405 406
{
    int ret;
    packet cur;
407
    size_t id;
408

409
    /* receive packet */
410
    if( ( ret = mbedtls_net_recv( src, cur.buf, sizeof( cur.buf ) ) ) <= 0 )
411
    {
412
        mbedtls_printf( "  ! mbedtls_net_recv returned %d\n", ret );
413 414 415
        return( ret );
    }

416 417 418
    cur.len  = ret;
    cur.type = msg_type( cur.buf, cur.len );
    cur.way  = way;
419
    cur.dst  = dst;
420 421
    print_packet( &cur, NULL );

422 423
    id = cur.len % sizeof( dropped );

424
    /* do we want to drop, delay, or forward it? */
425 426 427 428
    if( ( opt.mtu != 0 &&
          cur.len > (unsigned) opt.mtu ) ||
        ( opt.drop != 0 &&
          strcmp( cur.type, "ApplicationData" ) != 0 &&
429 430
          ! ( opt.protect_hvr &&
              strcmp( cur.type, "HelloVerifyRequest" ) == 0 ) &&
431
          cur.len != (size_t) opt.protect_len &&
432
          dropped[id] < DROP_MAX &&
433
          rand() % opt.drop == 0 ) )
434
    {
435
        update_dropped( &cur );
436
    }
437 438 439 440
    else if( ( opt.delay_ccs == 1 &&
               strcmp( cur.type, "ChangeCipherSpec" ) == 0 ) ||
             ( opt.delay != 0 &&
               strcmp( cur.type, "ApplicationData" ) != 0 &&
441 442
               ! ( opt.protect_hvr &&
                   strcmp( cur.type, "HelloVerifyRequest" ) == 0 ) &&
443
               prev.dst == NULL &&
444
               cur.len != (size_t) opt.protect_len &&
445
               dropped[id] < DROP_MAX &&
446
               rand() % opt.delay == 0 ) )
447 448 449 450 451
    {
        memcpy( &prev, &cur, sizeof( packet ) );
    }
    else
    {
452
        /* forward and possibly duplicate */
453 454 455 456
        if( ( ret = send_packet( &cur, "forwarded" ) ) != 0 )
            return( ret );

        /* send previously delayed message if any */
457
        if( prev.dst != NULL )
458 459 460 461 462 463 464 465
        {
            ret = send_packet( &prev, "delayed" );
            memset( &prev, 0, sizeof( packet ) );
            if( ret != 0 )
                return( ret );
        }
    }

466 467 468 469 470 471 472
    return( 0 );
}

int main( int argc, char *argv[] )
{
    int ret;

473
    mbedtls_net_context listen_fd, client_fd, server_fd;
474 475 476 477

    int nb_fds;
    fd_set read_fds;

478 479 480 481
    mbedtls_net_init( &listen_fd );
    mbedtls_net_init( &client_fd );
    mbedtls_net_init( &server_fd );

482
    get_options( argc, argv );
483 484 485 486 487 488 489 490 491 492 493

    /*
     * Decisions to drop/delay/duplicate packets are pseudo-random: dropping
     * exactly 1 in N packets would lead to problems when a flight has exactly
     * N packets: the same packet would be dropped on every resend.
     *
     * In order to be able to reproduce problems reliably, the seed may be
     * specified explicitly.
     */
    if( opt.seed == 0 )
    {
494
        opt.seed = (unsigned int) time( NULL );
495
        mbedtls_printf( "  . Pseudo-random seed: %u\n", opt.seed );
496 497 498
    }

    srand( opt.seed );
499 500

    /*
501
     * 0. "Connect" to the server
502
     */
503
    mbedtls_printf( "  . Connect to server on UDP/%s/%s ...",
504 505 506
            opt.server_addr, opt.server_port );
    fflush( stdout );

507 508
    if( ( ret = mbedtls_net_connect( &server_fd, opt.server_addr, opt.server_port,
                             MBEDTLS_NET_PROTO_UDP ) ) != 0 )
509
    {
510
        mbedtls_printf( " failed\n  ! mbedtls_net_connect returned %d\n\n", ret );
511 512 513
        goto exit;
    }

514
    mbedtls_printf( " ok\n" );
515 516 517 518

    /*
     * 1. Setup the "listening" UDP socket
     */
519
    mbedtls_printf( "  . Bind on UDP/%s/%s ...",
520 521 522
            opt.listen_addr, opt.listen_port );
    fflush( stdout );

523 524
    if( ( ret = mbedtls_net_bind( &listen_fd, opt.listen_addr, opt.listen_port,
                          MBEDTLS_NET_PROTO_UDP ) ) != 0 )
525
    {
526
        mbedtls_printf( " failed\n  ! mbedtls_net_bind returned %d\n\n", ret );
527 528 529
        goto exit;
    }

530
    mbedtls_printf( " ok\n" );
531 532 533 534

    /*
     * 2. Wait until a client connects
     */
535
accept:
536 537
    mbedtls_net_free( &client_fd );

538
    mbedtls_printf( "  . Waiting for a remote connection ..." );
539 540
    fflush( stdout );

541
    if( ( ret = mbedtls_net_accept( &listen_fd, &client_fd,
542
                                    NULL, 0, NULL ) ) != 0 )
543
    {
544
        mbedtls_printf( " failed\n  ! mbedtls_net_accept returned %d\n\n", ret );
545 546 547
        goto exit;
    }

548
    mbedtls_printf( " ok\n" );
549

550 551 552
    /*
     * 3. Forward packets forever (kill the process to terminate it)
     */
553 554 555
    clear_pending();
    memset( dropped, 0, sizeof( dropped ) );

556 557 558 559 560
    nb_fds = client_fd.fd;
    if( nb_fds < server_fd.fd )
        nb_fds = server_fd.fd;
    if( nb_fds < listen_fd.fd )
        nb_fds = listen_fd.fd;
561
    ++nb_fds;
562 563 564 565

    while( 1 )
    {
        FD_ZERO( &read_fds );
566 567 568
        FD_SET( server_fd.fd, &read_fds );
        FD_SET( client_fd.fd, &read_fds );
        FD_SET( listen_fd.fd, &read_fds );
569 570 571 572 573 574 575

        if( ( ret = select( nb_fds, &read_fds, NULL, NULL, NULL ) ) <= 0 )
        {
            perror( "select" );
            goto exit;
        }

576
        if( FD_ISSET( listen_fd.fd, &read_fds ) )
577 578
            goto accept;

579
        if( FD_ISSET( client_fd.fd, &read_fds ) )
580
        {
581
            if( ( ret = handle_message( "S <- C",
582
                                        &server_fd, &client_fd ) ) != 0 )
583
                goto accept;
584 585
        }

586
        if( FD_ISSET( server_fd.fd, &read_fds ) )
587
        {
588
            if( ( ret = handle_message( "S -> C",
589
                                        &client_fd, &server_fd ) ) != 0 )
590
                goto accept;
591 592 593 594 595
        }
    }

exit:

596
#ifdef MBEDTLS_ERROR_C
597 598 599
    if( ret != 0 )
    {
        char error_buf[100];
600 601
        mbedtls_strerror( ret, error_buf, 100 );
        mbedtls_printf( "Last error was: -0x%04X - %s\n\n", - ret, error_buf );
602 603 604 605
        fflush( stdout );
    }
#endif

606 607 608
    mbedtls_net_free( &client_fd );
    mbedtls_net_free( &server_fd );
    mbedtls_net_free( &listen_fd );
609 610

#if defined(_WIN32)
611
    mbedtls_printf( "  Press Enter to exit this program.\n" );
612 613 614 615 616 617
    fflush( stdout ); getchar();
#endif

    return( ret != 0 );
}

618
#endif /* MBEDTLS_NET_C */