Image

Knowledge base → Limiting and controlling outgoing traffic in Linux via iptables

[Virtual servers]
Date of publication: 21.07.2025

Limiting and controlling outgoing traffic can be useful in many cases, such as:

  • Protection against attacks - when services on the server generate responses
  • Data protection - making it harder to extract information from the server
  • Protection against closed-source scripts that may collect and transmit information without your knowledge

In our example, we will create a virtual machine and assume we need to test some software for data transmission. Thus, we will block everything except one IP address from which we will test the software.

1. Adding rules to iptables

# Clear current rules (be cautious if connected via SSH)
iptables -F OUTPUT

# Allow loopback (localhost)
iptables -A OUTPUT -o lo -j ACCEPT

# Allow DNS queries (if needed, optional)
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

# Allow all outgoing connections to IP 111.222.111.222
iptables -A OUTPUT -d 111.222.111.222 -j ACCEPT

# Block all other outgoing connections
iptables -A OUTPUT -j REJECT

Where 111.222.111.222 is the IP address from which we will test, send, and receive data.

2. Checking rules, verifying via SSH from the server itself

2.1 Checking ping

ping 8.8.8.8

PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
From 79.174.xx.xxx icmp_seq=1 Destination Port Unreachable
ping: sendmsg: Operation not permitted
From 79.174.xx.xxx icmp_seq=2 Destination Port Unreachable
ping: sendmsg: Operation not permitted
From 79.174.xx.xxx icmp_seq=3 Destination Port Unreachable
ping: sendmsg: Operation not permitted

2.2 Checking telnet

telnet google.com 443
Trying 209.85.233.101...
Connection failed: Connection refused
Trying 209.85.233.113...
Connection failed: Connection refused
Trying 209.85.233.139...
Connection failed: Connection refused
Trying 209.85.233.100...

As we can see, the rules are working, and when scripts or services attempt to connect, no data will be transmitted to the internet.

3. Monitoring traffic and connection attempts

3.1 This example will update connection data for PHP every second

watch -n 1 'lsof -i -nP | grep php'

php-fpm8.  445 www-data   11u  IPv4 2405976614      0t0  TCP 127.0.0.1:9000 (LISTEN)
php-fpm8.  448 www-data   12u  IPv4 2405976614      0t0  TCP 127.0.0.1:9000 (LISTEN)
php-fpm8.  449 www-data   14u  IPv4 2405976614      0t0  TCP 127.0.0.1:9000 (LISTEN)
php-fpm8.  453 www-data   16u  IPv4 2405976614      0t0  TCP 127.0.0.1:9000 (LISTEN)

If there are attempts to connect to an external node, the connection will be visible, including the port and IP address.

When monitoring PHP scripts, there are also additional modules, such as xdebug. Do not leave it enabled in production mode; use it only for debugging.

This way, you can quickly create a sandbox on a virtual server for the necessary scripts and monitor network activity without risking data exposure.





No Comments Yet