From 0d08dde62e79e293a56b3d64f4e73a25beb75d76 Mon Sep 17 00:00:00 2001 From: Nick Moore Date: Fri, 10 May 2019 13:56:33 +1000 Subject: [PATCH] randomize tcp source port for adafruit/circuitpython#1800 --- shared-module/network/__init__.c | 4 ++++ shared-module/network/__init__.h | 5 +++-- shared-module/wiznet/wiznet5k.c | 6 +++++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/shared-module/network/__init__.c b/shared-module/network/__init__.c index bf33fef7a8..96648b260c 100644 --- a/shared-module/network/__init__.c +++ b/shared-module/network/__init__.c @@ -99,3 +99,7 @@ void network_module_create_random_mac_address(uint8_t *mac) { mac[4] = (uint8_t)(rb2 >> 8); mac[5] = (uint8_t)(rb2); } + +uint16_t network_module_create_random_source_tcp_port(void) { + return 0xc000 | shared_modules_random_getrandbits(14); +} diff --git a/shared-module/network/__init__.h b/shared-module/network/__init__.h index 504065979c..f4eb05bb51 100644 --- a/shared-module/network/__init__.h +++ b/shared-module/network/__init__.h @@ -25,11 +25,12 @@ * THE SOFTWARE. */ -void network_module_create_random_mac_address(uint8_t *mac); - #ifndef MICROPY_INCLUDED_SHARED_MODULE_NETWORK___INIT___H #define MICROPY_INCLUDED_SHARED_MODULE_NETWORK___INIT___H +void network_module_create_random_mac_address(uint8_t *mac); +uint16_t network_module_create_random_source_tcp_port(void); + #define MOD_NETWORK_IPADDR_BUF_SIZE (4) #define MOD_NETWORK_AF_INET (2) diff --git a/shared-module/wiznet/wiznet5k.c b/shared-module/wiznet/wiznet5k.c index dbd4834519..3c5c5f0c83 100644 --- a/shared-module/wiznet/wiznet5k.c +++ b/shared-module/wiznet/wiznet5k.c @@ -203,8 +203,12 @@ int wiznet5k_socket_accept(mod_network_socket_obj_t *socket, mod_network_socket_ } int wiznet5k_socket_connect(mod_network_socket_obj_t *socket, byte *ip, mp_uint_t port, int *_errno) { + uint16_t src_port = network_module_create_random_source_tcp_port(); + // make sure same outgoing port number can't be in use by two different sockets. + src_port = (src_port & ~(_WIZCHIP_SOCK_NUM_ - 1)) | socket->u_param.fileno; + // use "bind" function to open the socket in client mode - if (wiznet5k_socket_bind(socket, ip, 0, _errno) != 0) { + if (wiznet5k_socket_bind(socket, NULL, src_port, _errno) != 0) { return -1; }