udp_proxy.c 32 KB

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