A program I'm writing binds to several (UDP) ports , and as such, the port I need open is nondeterministic. However, once obtained, I need to ensure the local firewall allows all traffic to and from that port.

IPTables is preferred in this use case, as it underlies higher-level firewalls like UFW, which will allow me to write only one version of a command for all linux distros.

This command will be called from the program executable. The windows version of this command allows me to merely specify the executable path, and viola. However, the linux version is not as trivial unless I specify each individual port I need opened. I'd prefer to allow traffic for an executable instead of individual ports. How can this be done? Or, what method would you use?

  • Is it possible to have this program run under a dedicated user account or in a separate namespace? Jul 28 '20 at 18:14
  • Yes, it is possible. For a command-line user that may or may not have sudo access, what is the most convenient method? Would sudo access be necessary? Jul 28 '20 at 18:18
  • can you grep/awk the output of lsof to get the UDP ports that were opened by your program?
    – bat
    Jul 28 '20 at 18:18
  • bat: in the case of the program, binding to :0 will return a UdpSocket abstraction which has the port info inside its memory. This is the easy way of getting the reserved port Jul 28 '20 at 18:19
  • 1
    nftables's socket expression can match a socket's mark (iptables' equivalent socket match can't do exactly this). This would allow to have the application reserve a fixed mark for itself for all its listening ports, but this is also a privileged operation. That would require the application to use some setuid root helper each time a port is opened (performance hit if not only at startup), in addition to using nftables instead (or in addition) of iptables. Since setuid root is required, using a namespace is the easiest then (& sudo etc.).
    – A.B
    Jul 28 '20 at 22:09

Your Answer

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

Browse other questions tagged or ask your own question.