2

Generally whenever source port is selected by a network application, it is selected in a sequential manner among the free ports like 32000, 32001 and so on. I want to randomize the source port selection. I tried this using iptables as follows but this didn't help.

 Chain POSTROUTING (policy ACCEPT 462 packets, 31025 bytes)
 743 44580 MASQUERADE  tcp  --  *      !lo     0.0.0.0/0            0.0.0.0/0           masq ports: 32768-61000 random

Can someone help me in solving this?

2

The range of the ephemeral ports is easily tunable with sysctl net.ipv4.ip_local_port_range="32768 61000" , and you can exclude ports as well with the net.ipv4.ip_local_reserved_ports parameter.

For more customization I would start by looking at the kernel source, AFAIK a start would be net/ipv4/inet_connection_sock.c where my first impression is that the assignment is random and not sequential.

# net/ipv4/inet_connection_sock.c
...
/* Obtain a reference to a local port for the given sock,
 * if snum is zero it means select any available local port.
 */
int inet_csk_get_port(struct sock *sk, unsigned short snum)
{
...
            inet_get_local_port_range(net, &low, &high);
            remaining = (high - low) + 1;
            smallest_rover = rover = net_random() % remaining + low;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.