For reasons beyond my control, I have a binary that binds to TCP "localhost:$PORT". (Unix socket bindings would make this question moot).

If I understand correctly, this means that although no network machine can connect, other users on the machine (including unprivileged daemon users) can connect to this port.

Is there some way for me to specify that only binaries running as $me should be allowed to connect to this port? I can become root in order to specify the configuration, but the listening binary and the connecting binaries both run as the non-root $me user

2 Answers 2


There is an owner match extension in iptables, but it can only be used in OUTPUT and POSTROUTING chains. So you could add two rules in the very beginning of the iptables OUTPUT chain like this (root access needed):

iptables -I OUTPUT 1 -o lo -p tcp --dport $PORT -m owner --uid-owner $me -j ACCEPT
iptables -I OUTPUT 2 -o lo -p tcp --dport $PORT -j DROP
  • Rule 1: if a packet is going out the loopback interface over TCP and has destination port $PORT and packet owner is $me, let it pass (and don't process any further rules in this chain).
  • Rule 2: if a packet is going out the loopback interface over TCP and has destination port $PORT but it did not match rule 1 (i.e. packet is owned by anyone other than $me), drop it.

If your system has some service that manages iptables settings for you (e.g. ufw for Debian/Ubuntu, or firewalld for RedHat/Fedora systems), you will probably need to configure that service to create these iptables rules for you instead of directly manually adding them.


Nftables reference: https://wiki.nftables.org/wiki-nftables/index.php/Matching_packet_metainformation#Matching_by_socket_UID_.2F_GID

In this case is only accessible by root, and not other users

table inet filter {
        # [...]
        chain output {
                type filter hook output priority filter; policy accept;
                oif "lo" tcp dport 8000 meta skuid 0 accept
                oif "lo" tcp dport 8000 drop

You can test with:

# dropped

# accepted
sudo curl

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .