How to Restrict Remote Access Using TCP Wrappers in Linux

Understanding TCP Wrappers

While modern Linux distributions rely heavily on iptables or firewalld for network security, TCP Wrappers provide a simple, host-based access control system at the application layer. By editing two simple text files, administrators can quickly permit or deny connections to services (like SSH, FTP, or Telnet) based on the IP address or hostname of the requesting client, before the application even processes the request.

Step 1: Verify Service Compatibility

Not all network services support TCP Wrappers. The service must be compiled with the libwrap library. You can verify if a service (for example, the SSH daemon) supports TCP Wrappers using the ldd command:

ldd /usr/sbin/sshd | grep libwrap

If the command outputs a path to libwrap.so, the service is compatible and can be restricted.

Step 2: Understand the Rule Files

TCP Wrappers rely on two configuration files:

  1. /etc/hosts.allow: Processed first. If a matching rule is found here, access is granted.
  2. /etc/hosts.deny: Processed second. If no match was found in hosts.allow, and a rule matches here, access is denied.

If no rules match in either file, access is implicitly granted.

Step 3: Configure hosts.deny (The Default Deny Strategy)

The most secure way to configure TCP Wrappers is to deny all connections by default, and explicitly allow only what is necessary. Open the deny file:

sudo nano /etc/hosts.deny

To block all traffic to all wrapped services, add the following line to the end of the file:

ALL: ALL

Save and close the file. Warning: Do not do this over an active SSH session unless you have already configured the hosts.allow file, or you will lock yourself out!

Step 4: Configure hosts.allow

Now, open the allow file to punch holes for your trusted IP addresses:

sudo nano /etc/hosts.allow

The syntax is daemon_list : client_list. For example, to allow SSH access only from your office IP (e.g., 203.0.113.50) and a specific internal subnet (e.g., 192.168.1.0/24), add the following line:

sshd : 203.0.113.50, 192.168.1.

Notice that for subnets, you can omit the trailing zero (192.168.1. matches all IPs in that range).

Step 5: Test the Restrictions

TCP Wrappers do not run as a daemon; the rules are read dynamically by the libwrap library every time a connection attempt is made. Therefore, you do not need to restart any services after modifying the files.

Test your configuration by attempting to connect to the SSH service from an unauthorized IP address. The connection should be immediately closed by the remote host, and a corresponding denial log will be generated in /var/log/auth.log or /var/log/secure.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.