Explore plans starting at ₹699/mo →
Linux & System Administration

Linux Firewall Configuration: Mastering ufw and iptables on Cloud Servers

S
ServerRaja
9 min read
#Linux#Ubuntu#Networking#Security#Tutorial#CentOS#Best Practices#Firewall
Linux Firewall Configuration: Mastering ufw and iptables on Cloud Servers

A properly configured firewall is your server's gatekeeper, controlling exactly which traffic enters and leaves. On a ServerRaja cloud server exposed to the internet, firewall misconfiguration is one of the most common security vulnerabilities. This guide covers both ufw (the simple front-end for Ubuntu/Debian) and iptables (the powerful low-level tool used on CentOS and for advanced configurations), with practical rules for real-world server security.

Understanding Linux Firewall Concepts

The Linux kernel's netfilter framework processes network packets through a set of rules organized into tables and chains:

  • **Tables**: filter (default), nat, mangle, raw
  • **Chains**: INPUT (incoming), OUTPUT (outgoing), FORWARD (routed)
  • **Rules**: Checked in order; first match wins
  • **Default Policy**: ACCEPT or DROP for packets that match no rule

A secure server uses a default DROP policy on the INPUT chain and explicitly allows only the traffic you need.

Firewall with UFW (Ubuntu/Debian)

UFW (Uncomplicated Firewall) is the recommended firewall tool for Ubuntu and Debian servers on ServerRaja. It provides a human-friendly interface over iptables.

Basic UFW Setup

# Install UFW (usually pre-installed on Ubuntu)
apt install ufw

# IMPORTANT: Before enabling, make sure SSH is allowed! ufw allow 22/tcp

# Or if you use a custom SSH port ufw allow 2222/tcp

# Set default policies ufw default deny incoming ufw default allow outgoing

# Enable the firewall ufw enable

# Check status ufw status verbose ufw status numbered ```

Common UFW Rules

# Allow HTTP and HTTPS
ufw allow 80/tcp
ufw allow 443/tcp

# Allow both at once ufw allow proto tcp from any to any port 80,443

# Allow a specific IP address (your office/home IP) ufw allow from 203.0.113.50

# Allow a specific IP to access a specific port ufw allow from 203.0.113.50 to any port 3306

# Allow an entire subnet ufw allow from 10.0.0.0/24

# Allow MySQL only from localhost ufw allow from 127.0.0.1 to any port 3306

# Allow Redis only from application subnet ufw allow from 10.0.1.0/24 to any port 6379

# Deny a specific IP (block an attacker) ufw deny from 198.51.100.0/24

# Allow a port range ufw allow 30000:31000/tcp

# Delete a rule (use the number from 'ufw status numbered') ufw delete 3

# Delete by specifying the full rule ufw delete allow 80/tcp ```

UFW Rate Limiting

UFW has built-in rate limiting that blocks IPs attempting more than 6 connections in 30 seconds — perfect for SSH brute-force protection:

# Rate limit SSH (much better than plain allow)
ufw limit 22/tcp

# Rate limit custom SSH port ufw limit 2222/tcp comment 'SSH rate limit' ```

Advanced UFW with Application Profiles

# List available application profiles
ufw app list

# Allow by application name ufw allow 'Nginx Full' ufw allow 'OpenSSH'

# Create a custom application profile nano /etc/ufw/applications.d/myapp ```

[MyApp]
title=My Application Server
description=Custom Node.js application
ports=3000/tcp|4000:4100/tcp
# Reload and use the new profile
ufw app update MyApp
ufw allow MyApp

Firewall with iptables (CentOS/RHEL)

On CentOS and RHEL, iptables is the traditional firewall tool. While firewalld is now the default, many administrators still prefer direct iptables for fine-grained control.

Basic iptables Concepts

# View current rules
iptables -L -n -v
iptables -L -n -v --line-numbers

# Flush all rules (start clean) iptables -F

# Set default policies iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT ```

Essential iptables Rules

# Allow loopback interface
iptables -A INPUT -i lo -j ACCEPT

# Allow established and related connections (critical!) iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow SSH iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP and HTTPS iptables -A INPUT -p tcp --dport 80 -j ACCEPT iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow ICMP (ping) iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

# Allow DNS responses iptables -A INPUT -p udp --sport 53 -j ACCEPT

# Log dropped packets (rate limited to prevent log flood) iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "IPTables-Dropped: " --log-level 4

# Drop everything else (matches the default policy) iptables -A INPUT -j DROP ```

iptables Rate Limiting

# Limit SSH to 3 new connections per minute per IP
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name SSH
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT

# Limit HTTP connections (anti-DDoS basic protection) iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 50 --connlimit-mask 32 -j REJECT ```

Blocking Specific Threats

# Block an IP range
iptables -A INPUT -s 198.51.100.0/24 -j DROP

# Block port scanning iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP iptables -A INPUT -p tcp --tcp-flags ALL FIN,URG,PSH -j DROP iptables -A INPUT -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP iptables -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP iptables -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP

# Block null packets iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

# Block XMAS packets iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP ```

Saving and Restoring iptables Rules

iptables rules are lost on reboot unless saved:

# Ubuntu/Debian - install persistent package
apt install iptables-persistent
netfilter-persistent save

# CentOS/RHEL service iptables save # Or manually iptables-save > /etc/sysconfig/iptables

# Restore from backup iptables-restore < /etc/sysconfig/iptables ```

Using firewalld (CentOS/RHEL Alternative)

# Check status
firewall-cmd --state

# List all rules firewall-cmd --list-all

# Add a permanent rule firewall-cmd --permanent --add-service=http firewall-cmd --permanent --add-service=https firewall-cmd --permanent --add-port=2222/tcp

# Reload to apply changes firewall-cmd --reload

# Remove a rule firewall-cmd --permanent --remove-service=http

# Add rich rules for rate limiting firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="0.0.0.0/0" service name="ssh" accept limit value="3/m"' ```

Firewall Best Practices for ServerRaja Servers

**Default deny, explicit allow**: Start by blocking everything and only open what you need. Every open port is a potential attack vector.

**Restrict database ports**: MySQL (3306), PostgreSQL (5432), and Redis (6379) should never be open to the internet. Allow them only from localhost or specific application server IPs.

**Use rate limiting on all public ports**: Even web servers benefit from connection rate limits to mitigate DDoS attempts.

**Document your rules**: Add comments to rules so future administrators understand their purpose. In ufw: `ufw allow 80/tcp comment 'Nginx HTTP'`. In iptables: add `-m comment --comment "description"`.

**Monitor firewall logs**: Review dropped packet logs regularly to spot attack patterns and adjust rules accordingly.

**Test after every change**: After modifying rules, verify you can still access SSH and your services. Getting locked out of a remote server requires console access through the ServerRaja control panel to fix.

A well-configured firewall is invisible when everything works and invaluable when something goes wrong. Take the time to set it up correctly on your ServerRaja server — it is the most cost-effective security investment you can make.

Key Takeaways

  • **Set default policies to deny incoming, allow outgoing** — then explicitly allow only the ports your services need; this is the single most important firewall rule.
  • **UFW is the recommended starting point** for Ubuntu servers — it provides a simple interface over iptables with sensible defaults and application profiles.
  • **Rate-limit SSH access** instead of simply allowing it — `ufw limit ssh` or iptables rate limiting prevents brute-force attempts at the network layer.
  • **Always allow established/related connections** (`-m conntrack --ctstate ESTABLISHED,RELATED`) before your allow rules — without this, return traffic for legitimate connections gets dropped.
  • **After every firewall change, test SSH access from a second session** before closing your current one — a misconfigured rule can lock you out of a remote server permanently.
Linux Firewall: ufw & iptables Guide | ServerRaja