Block user access to port using nftables

In the realm of network administration and security, managing access to services is crucial. One common task is blocking specific users from accessing certain ports. This article will guide you through using nftables to block a user from accessing a port, focusing on port 22 (commonly used by SSH) as an example.

TLDR

tcp dport 22 meta skuid USER drop

What is nftables?

nftables is the successor to the iptables, ip6tables, arptables, and ebtables utilities. It offers a simplified syntax and enhanced performance. Managed by the Netfilter project, nftables allows administrators to configure filtering and classification rules within the Linux kernel’s networking stack.

Step-by-Step Guide

1. Install nftables (if not already installed)

Most modern Linux distributions include nftables by default. However, if it’s not installed, you can install it using your package manager.

For Debian/Ubuntu-based systems:

sudo apt-get update
sudo apt-get install nftables

For Red Hat/CentOS-based systems:

sudo yum install nftables

2. Enable and Start nftables Service

Ensure the nftables service is enabled and running.

sudo systemctl enable nftables
sudo systemctl start nftables

3. Create a New Rule Set

Create a new ruleset or edit an existing one. The ruleset can be stored in a file or entered interactively.

Example using a file:

Create a file called main.nft.

sudo nano /etc/nftables/main.nft

Add the following content:

#!/usr/sbin/nft -f

# Define the table
table inet filter {
    chain input {
        type filter hook input priority 0; policy accept;

        # Block user 'USER' from accessing port 22
        tcp dport 22 meta skuid USER drop
    }
}

Save and close the file.

4. Load the Ruleset

Load your new ruleset into nftables.

sudo nft -f /etc/nftables/main.nft

5. Verify the Rule

To ensure the rule has been applied, list the current rules.

sudo nft list ruleset

You should see output similar to this:

table inet filter {
    chain input {
        type filter hook input priority 0; policy accept;
        tcp dport 22 meta skuid USER counter drop
    }
}

This confirms that traffic to port 22 for the user identified by USER will be dropped.

Follow me on Twitter! It's free!