Imagine this scenario: a particular process on your server is connecting to a host outside your internal network and you don’t like that. On the other hand, you can’t just kill that process because you need it.

The simple script below uses tcpkill and iptables to kill and block outbound connections initiated by processes matching the names you’ve provided. The tcpkill utility is provided by the dsniff package on CentOS/RHEL and can be installed like so:

You can add the script to the cron to run, say, every few minutes. Here’s an example using sudo to source root’s environment (not necessary in this case – just an example):

You may notice that multiple instances of tcpkill are hanging around – one per each blocked IP. This is not an error. This utility will only kill connections if there is traffic.

This means that, if there was no traffic at the moment you ran the command, it will stick around and wait until it sees activity. However, because the script also tells iptables to block traffic to these IPs, the tcpkill instance will remain. You can certainly change this by prepending tcpkill with timeout instead of nohup.

You can download the script here. This is what the script does exactly:

  1. Obtain the PIDs of the processes matching the process names you provided as CLI arguments
  2. Identify the IPs to which those PIDs are currently connected, excluding anything on your private network. Add those IPs to the array.
  3. Cycle through the array and run tcpkill and iptables DROP for each new IP.
  4. Clean up iptables configuration to get rid of duplicate entries.

Leave A Reply

Please enter your comment!
Please enter your name here