In network programming, it's common to pass INADDR_ANY
(or IN6ADDR_ANY
) as part of the second argument to bind(), telling the networking stack that you want the socket to receive connections/traffic from any network interface that the machine happens to have. Many programs do this, as it is often the most useful behavior. The other common option is to specify a single network interface to bind to, instead.
However, I have a use-case where I'd like one particular network interface on my Linux machine be "reserved", in the sense that it is not included in the set of network interfaces used by sockets bound to INADDR_ANY
. In particular, I'd like this network interface to be usable only by sockets that have bound themselves to its IP address explicitly (or perhaps have performed some other explicit step to indicate that they are aware of this network interface's special status and wish to use it anyway) -- sort of a "socket whitelist", if you will, to guarantee that only a few hand-picked apps can send/receive traffic over this network interface. (These apps will likely be ones I wrote and personally control, if that matters)
Is there any mechanism to accomplish this in Linux?
Some approaches that I have considered but am not entirely satisfied with:
- Modifying all apps to bind explicitly to the network interfaces they want to use, instead of binding to
INADDR_ANY
, and not including this network interface in the set. (too much work, and I probably don't have access to modify all such apps anyway) - Setting up a firewall on the network interface such that only traffic on certain ports is accepted. (this might sort-of work, but it means I have to specify in advance all ports that I will use on the interface, which precludes software that required dynamic port allocation... and of course there would still be the chance that some unexpected app gets "lucky" and happens to bind to one of the whitelisted ports, which would be undesirable)
- Switch to SELinux or similar security-oriented distribution that has fine-grained ACLs (not a realistic option here, for various reasons I won't get into)
Have you tried or considered iptables (I know its hard to specify precisely the requirements, but it is probably worth trying and trying until success ):
To allow traffic only from IP address 10.0.0.1 and port 80 to be forwarded to the reserved network interface
And then block all other
Or to use the network-manager to create a virtual network interface and move the IP address you want to reserve to the virtual interface, this way the applications will not be able to bind to it by default, you can also use firewall rules on the virtual interface. I will watch this article to see what will the final result.