UFW
UFW (Uncomplicated Firewall) is a command-line firewall manager for Linux that provides a simpler interface for defining host firewall rules. It translates human-readable rules (allow/deny/reject/limit) into kernel-enforced Netfilter rules via the iptables interface (often backed by nftables through the iptables-nft compatibility layer on modern distributions).
Background and history
UFW emerged in the Ubuntu ecosystem to make host firewalling practical without requiring administrators to write raw iptables rules. It became widely adopted because it provides a consistent, readable workflow for the most common server needs: deny-by-default inbound access, allow only required services, and audit with logging.
Adoption and where it’s commonly used
UFW is commonly used on:
- Ubuntu servers (often the default “first firewall” choice)
- Debian-based VPS deployments
- Small-to-medium fleets where readability and consistency matter
- WordPress hosting stacks where only a small set of ports should be exposed
Maintained by
- Maintained by the Ubuntu/Canonical community.
Best when to use
- VPS servers that need a baseline inbound policy (deny by default, allow only required ports)
- Web servers where ports are predictable (SSH, HTTP/HTTPS, admin panel restrictions)
- Environments that want a clear, auditable rule set without advanced firewall frameworks
- Automation workflows that need a stable CLI (
--force, numbered rules)
Not suitable when
- You need complex dynamic rules at scale or deep NAT/routing policy management
- You standardize on
firewalld(RHEL/Fedora) or directnftablesacross a fleet - You need Layer 7 controls (WAF, bot management, application filtering)
Compatibility notes
-
Most common on Ubuntu/Debian. RHEL-family systems often default to
firewalld. -
UFW ultimately programs Netfilter; the underlying backend may be:
- legacy
iptables, or iptables-nft(iptables commands writing nftables rules via compatibility layer)
- legacy
-
IPv6 behavior is controlled by
/etc/default/ufw(IPV6=yes/no) and IPv6 rule files.
Always allow your SSH port before enabling UFW or changing SSH configuration. Keep an existing SSH session open while testing new rules and new SSH ports.
Concepts and how UFW works
UFW is a policy and rule manager that generates firewall rules and applies them to the kernel’s packet filter.
Default policies vs rules
- Default policies define what happens when no rule matches (commonly
deny incoming,allow outgoing). - Rules create explicit exceptions (allow SSH, allow HTTPS, deny MySQL externally).
- Order matters when multiple rules could match.
What You Will Learn
- The theoretical foundation and purpose of UFW in Linux systems.
- Core syntax and command structure.
- Explanation of every available option and flag.
- The concept of default policies, rule sets, and logging modes.
- Understanding the internal configuration and system files associated with UFW.
- Relationship of UFW with iptables and other firewall frameworks.
- Interpretation of UFW rule components (direction, protocol, interface, etc.).
Prerequisites
- Linux VPS or server environment (Ubuntu or Debian-based systems).
- Basic understanding of networking (ports, IP, protocols).
- Familiarity with system administration concepts.
What is UFW
UFW stands for Uncomplicated Firewall, a front-end command-line interface for iptables and nftables.
Its goal is to simplify firewall management for administrators by abstracting complex iptables syntax into readable commands such as allow, deny, reject, and limit.
UFW operates primarily by writing and managing low-level rules that determine which incoming or outgoing network traffic is permitted or blocked.
Why UFW Matters
UFW provides:
- Simplified command syntax for human-readable firewall configuration.
- Built-in rule management and persistence across reboots.
- Integration with application profiles (allowing rule sets for services).
- Granular control of traffic based on direction, interface, protocol, and address range.
- Automatic management of default policies and logging behavior.
It acts as a protective layer controlling access to system services and ports — fundamental in securing any network-connected server.
Where UFW Operates
UFW operates at the kernel-level network filtering layer through iptables (or nftables on modern systems).
Its configurations are stored under /etc/ufw/, and it interacts with:
-
/etc/ufw/ufw.conffor startup enablement. -
/etc/ufw/before.rulesand/etc/ufw/after.rulesfor pre- and post-processing chains. -
/etc/ufw/applications.d/for application-specific profiles.Logging outputs are stored under
/var/log/ufw.logor system logs.
Core Syntax Formula
ufw [global-options] <command> [parameters]
| Component | Description |
|---|---|
| ufw | The main executable program controlling the Uncomplicated Firewall. |
| [global-options] | Optional flags that modify global execution behavior (e.g., --force, --help). |
The action or sub-command that tells UFW what to do (e.g., enable, allow, status). | |
| [parameters] | Specific arguments required by the chosen command, such as port numbers, protocols, or addresses. |
Global Options (Flags)
These options affect the behavior of the ufw command itself, not the rule being created.
| Option / Flag | Purpose | Remarks |
|---|---|---|
--help | Displays UFW help information and available commands. | Used for reference or troubleshooting. |
--version | Prints the current installed version of UFW. | Helpful for compatibility checks. |
--force | Suppresses interactive confirmation prompts. | Essential for automation and scripting. |
--verbose | Used with status or diagnostic output to show more detailed information. | For detailed inspection of rules and defaults. |
--dry-run | (Not supported in native UFW). Present for interface consistency. | No actual dry-run mode exists. |
--reset | Resets UFW to factory defaults (deprecated direct flag; now a command). | Historically used for quick resets. |
Command Categories (with Theoretical Explanation)
To organize UFW’s behavior conceptually, commands can be divided into five major functional groups:
(A) System Control (B) Policy Definition (C) Rule Management (D) Application Profile Handling (E) Monitoring & Diagnostics
A. System Control Commands
| Command | Purpose | Theoretical Description |
|---|---|---|
enable | Activates UFW and loads configured rules into the kernel firewall subsystem. | When enabled, UFW translates all stored rules into kernel-level iptables chains. |
disable | Deactivates UFW, flushing or bypassing the kernel rules managed by it. | Stops packet filtering based on UFW configuration. |
reload | Re-applies all current rules without disabling the firewall. | Useful when modifying rules on a live system. |
reset | Removes all existing user rules and returns to default deny/allow policies. | Equivalent to re-initializing the firewall. |
status | Displays current operational status (active/inactive). | Provides summary view of applied rules. |
status verbose | Displays extended information including logging mode, IPv6 usage, and default policies. | Used for audit and verification. |
status numbered | Shows all rules with numeric identifiers. | Facilitates precise rule deletion. |
B. Policy Definition Commands
These define the default behavior for packets that do not match any explicit rule.
| Command | Default Direction | Purpose / Theoretical Function |
|---|---|---|
default allow incoming | Incoming | Permits all inbound connections by default. Rarely used for secure environments. |
default deny incoming | Incoming | Blocks all inbound traffic unless explicitly allowed. Most common for servers. |
default reject incoming | Incoming | Rejects inbound connections with a response packet rather than silently dropping. |
default allow outgoing | Outgoing | Allows all outbound connections. Standard behavior for most systems. |
default deny outgoing | Outgoing | Blocks all outbound traffic unless specifically permitted. Used in restricted networks. |
default allow routed | Routed | Allows forwarded traffic through the host (for routing scenarios). |
default deny routed | Routed | Denies all routed/forwarded traffic. Default for non-router servers. |
C. Rule Management Commands
Rules represent specific filtering conditions that override or complement the default policy.
Rules can target particular ports, protocols, addresses, interfaces, or directions.
1. Basic Rule Actions
| Command | Theoretical Behavior | Purpose |
|---|---|---|
allow | Creates a permit rule that accepts matching packets. | Enables legitimate service access (e.g., HTTP, SSH). |
deny | Drops packets silently without response. | Reduces system exposure; no feedback to sender. |
reject | Drops packets but sends a rejection message (ICMP/TCP RST). | Useful for transparency; informs sender of rejection. |
limit | Accepts limited number of new connections per time interval. | Rate-limits excessive attempts, commonly for SSH. |
route allow / route deny | Applies the same principles but to forwarded packets (router contexts). | Controls traffic passing through the system. |
2. Rule Direction Modifiers
| Parameter | Effect on Rule | Theoretical Purpose |
|---|---|---|
in | Applies to incoming traffic directed to the host. | Used for protecting services. |
out | Applies to outgoing traffic from the host. | Used for controlling data exfiltration. |
3. Interface Modifiers
| Parameter | Explanation |
|---|---|
on <interface> | Binds the rule to a specific network interface (e.g., eth0, ens3). |
from any | Applies rule to packets from all sources. |
to any | Applies rule to packets going to any destination. |
4. Address & Subnet Modifiers
| Parameter | Purpose |
|---|---|
from <IP> | Defines the source address or network (e.g., 192.168.1.0/24). |
to <IP> | Defines the destination address or network. |
any | Wildcard for all IPs. |
::/0 | Represents all IPv6 addresses. |
5. Port & Protocol Modifiers
| Parameter | Purpose / Behavior |
|---|---|
port <number> | Specifies a port (e.g., 22, 80, 443). |
<port>/<protocol> | Defines both port and protocol explicitly (e.g., 22/tcp). |
proto tcp / proto udp | Restricts the rule to a specific protocol family. |
6. Commenting & Labeling
| Parameter | Description |
|---|---|
comment "<text>" | Adds a textual label to a rule for documentation. |
<profile> | References an application profile defined in /etc/ufw/applications.d/. |
7. Rule Ordering
| Command / Parameter | Purpose |
|---|---|
insert <number> <rule> | Inserts a rule at a specific index (affects precedence). |
delete <rule> | Removes a rule matching the specified definition. |
delete <number> | Removes the rule corresponding to the index number shown in status numbered. |
D. Application Profile Commands
UFW supports application-level profiles for common services.
These profiles are collections of ports/protocols defined in text files.
| Command | Function | Conceptual Explanation |
|---|---|---|
app list | Lists all available application profiles. | Shows human-readable service names. |
app info <profile> | Displays the ports and protocols that belong to the profile. | Explains what a given profile represents. |
app update <profile> | Refreshes the profile definitions. | Ensures changes in configuration are reloaded. |
allow '<profile>' | Enables all ports defined in the profile. | Simplifies complex multi-port service activation. |
deny '<profile>' | Denies access to ports defined in the profile. | Opposite of allow. |
E. Monitoring and Diagnostic Commands
| Command | Purpose | Theoretical Description |
|---|---|---|
status | Provides summary of firewall activity. | Indicates whether UFW is active and lists major rules. |
status verbose | Shows extended configuration details. | Displays logging, IPv6 state, and default policy. |
status numbered | Lists all rules with numeric identifiers. | Used for referencing rules when deleting. |
show added | Displays rules added since last restart. | Helps identify changes made during runtime. |
show raw | Displays raw iptables or nftables syntax behind UFW rules. | Useful for low-level auditing or debugging. |
show listening | Lists currently open ports on the system. | Reveals network exposure points. |
logging on/off | Enables or disables logging globally. | Activates packet logging to /var/log/ufw.log. |
| `logging low | medium | high |
Rule Parameter Components (Detailed Theoretical Reference)
Below is a breakdown of the internal logic and meaning of parameters used within rule definitions.
| Component | Meaning | Example (Theoretical) |
|---|---|---|
| Action | Determines the rule type (allow, deny, reject, limit). | “Allow incoming TCP packets on port 22.” |
| Direction | Specifies whether the rule applies to incoming or outgoing traffic. | “Allow in” or “Deny out.” |
| Interface | Binds rule to a network interface. | “on eth0” applies only to that NIC. |
| Source Address | Origin IP or subnet. | “from 192.168.1.0/24.” |
| Destination Address | Target IP or subnet. | “to any port 443.” |
| Protocol | Type of connection (TCP/UDP/ICMP). | “proto tcp.” |
| Port | Target port number. | “port 3306.” |
| Comment | Annotation for administrative clarity. | “comment 'database access rule'.” |
Logging and Monitoring Modes (Theory)
| Mode | Purpose | Information Level |
|---|---|---|
off | Disables packet logging completely. | No records kept. |
low | Logs only blocked connections. | Minimal performance impact. |
medium | Logs both accepted and denied connections with summary detail. | Balanced for audit purposes. |
high | Logs every packet decision event. | Suitable for debugging. |
full | Enables maximum verbosity, including packet metadata. | Used for forensic or security investigations. |
UFW uses system log daemons (rsyslog or journald) to record these events into /var/log/ufw.log or equivalent system log files.
Configuration Files (System-Level Theory)
| File / Directory | Role | Details |
|---|---|---|
/etc/ufw/ufw.conf | Main configuration file controlling whether UFW starts at boot. | Defines ENABLED=yes/no. |
/etc/default/ufw | Holds default IPv6 toggle and base policies. | Contains key variables used during initialization. |
/etc/ufw/before.rules | Set of iptables rules applied before user-defined ones. | Handles loopback and essential system traffic. |
/etc/ufw/after.rules | Rules applied after user-defined rules. | Often used for NAT or post-processing. |
/etc/ufw/before6.rules / after6.rules | IPv6 equivalents for dual-stack systems. | Controls IPv6 rule precedence. |
/etc/ufw/applications.d/ | Directory storing application profile definitions. | Contains descriptive .profile files for services. |
/var/log/ufw.log | Dedicated log file for UFW logging. | Managed by rsyslog; controlled by logging setting. |
Internal Operation (Conceptual Overview)
| Stage | Process | Description |
|---|---|---|
| 1. Initialization | UFW loads default configuration files. | Establishes kernel chain structures. |
| 2. Policy Setup | Default deny/allow behavior is established. | Defines system security baseline. |
| 3. Rule Translation | Human-readable rules are converted into iptables/nftables entries. | Maps to kernel packet filters. |
| 4. Activation | Kernel applies all configured rules. | Firewall becomes active and enforces filtering. |
| 5. Monitoring | Logging and counters begin recording traffic matches. | Maintains visibility and auditing. |
Theoretical Relationships
| Layer | Component | Function |
|---|---|---|
| User Layer | UFW CLI | Human-readable interface. |
| Translation Layer | UFW Parser | Converts syntax to iptables/nft commands. |
| Kernel Layer | Netfilter Framework | Executes packet filtering. |
| System Layer | Logging & Service Management | Provides audit and service persistence. |
Summary of Theoretical Principles
- Abstraction: UFW abstracts
iptablescomplexity into plain-language commands. - Determinism: Rules are applied in sequence, and their order determines precedence.
- Persistence: UFW maintains state across reboots through its configuration layer.
- Layered Control: Combines policy (global) + rule (specific) + application profile (service-based).
- Observability: Offers multi-level logging for traceability and diagnostics.
- Security Principle: Operates by default deny, allowing explicit exceptions only.
Would you like me to continue this by adding a next section that explains — in theory —
how rule evaluation order and packet flow through UFW chains works internally (similar to how iptables chain traversal logic is represented)?
It would complete the advanced theoretical structure of UFW.
UFW Practical Use Cases & Examples
Safe Initialization and Basic Setup
Scenario:
You’ve just provisioned a new Ubuntu VPS for WordPress. You want to activate UFW safely without losing SSH access.
Commands:
sudo ufw allow 22/tcp
sudo ufw allow 80,443/tcp
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw --force enable
sudo ufw status verbose
Expected Output:
Rule added
Rule added
Default incoming policy changed to 'deny'
Default outgoing policy changed to 'allow'
Firewall is active and enabled on system startup
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
To Action From
-- -
22/tcp ALLOW Anywhere
80,443/tcp ALLOW Anywhere
Explanation:
- SSH (22) and web ports (80, 443) are open.
- All other inbound traffic is blocked.
- Outgoing connections (package updates, API calls, etc.) remain allowed.
- The firewall is enabled and persistent across reboots.
Limiting SSH Connections (Brute-Force Protection)
Scenario:
You want to reduce brute-force attacks on SSH without completely blocking IPs.
Command:
sudo ufw limit ssh
Expected Output:
Rule added
Explanation:
- The
limitaction allows a few SSH connection attempts within a time window. - Repeated failed attempts get temporarily blocked.
- Ideal for VPS administrators using SSH daily.
Restrict Access to MySQL (Local Only)
Scenario:
Your WordPress database runs locally. You want to ensure MySQL (port 3306) is not exposed to the internet.
Commands:
sudo ufw deny 3306
sudo ufw allow from 127.0.0.1 to any port 3306
Expected Output:
Rule added
Rule added
Explanation:
- Blocks external network access to MySQL.
- Allows internal access from localhost (the WordPress PHP process).
Allow Only Cloudflare IPs (Edge Protection)
Scenario:
Your WordPress site is behind Cloudflare. You want to allow only Cloudflare IP ranges to reach ports 80 and 443.
Commands:
sudo ufw deny 80,443/tcp
sudo ufw allow from 173.245.48.0/20 to any port 80,443 proto tcp
sudo ufw allow from 103.21.244.0/22 to any port 80,443 proto tcp
# (repeat for all Cloudflare IP ranges)
Expected Output:
Rule added
Rule added
Rule added
Explanation:
- Denies all general access.
- Explicitly allows only Cloudflare edge servers to forward traffic to your WordPress site.
- Adds an additional security layer against direct IP attacks.
Application Profiles (Simplified Service Rules)
Scenario:
You installed Nginx or Apache. Instead of specifying ports manually, you can use predefined application profiles.
Commands:
sudo ufw app list
sudo ufw app info "Nginx Full"
sudo ufw allow "Nginx Full"
Expected Output:
Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH
Profile: Nginx Full
Title: Web Server (HTTP,HTTPS)
Description: Nginx Web Server with SSL
Ports:
80,443/tcp
Rule added
Explanation:
- UFW recognizes system services via
/etc/ufw/applications.d/. - Application profiles automatically apply multiple port rules.
- Using them avoids manual port errors and keeps configs readable.
Deleting or Reordering Rules
Scenario:
You accidentally opened the wrong port. You want to delete or reorder rules safely.
Commands:
sudo ufw status numbered
sudo ufw delete 3
sudo ufw insert 1 allow 3306/tcp
Expected Output:
Status: active
Num Action From
-- -
[ 1] 22/tcp ALLOW IN Anywhere
[ 2] 80/tcp ALLOW IN Anywhere
[ 3] 8080/tcp ALLOW IN Anywhere
Deleting:
[ 3] 8080/tcp ALLOW IN Anywhere
Proceed with operation (y|n)? y
Rule deleted
Rule added
Explanation:
- You can view rule numbers using
status numbered. - Delete specific entries or insert new ones with priority.
- UFW rules are evaluated top to bottom, so order matters.
Enabling Logging for Security Auditing
Scenario:
You want to monitor blocked and allowed traffic.
Commands:
sudo ufw logging medium
sudo tail -f /var/log/ufw.log
Expected Output:
Logging enabled
Oct 21 10:33:15 vps kernel: [UFW BLOCK] IN=eth0 OUT= MAC=... SRC=203.0.113.5 DST=192.0.2.10 LEN=60 ...
Explanation:
mediumlevel provides a balanced log volume.- The log file shows both allowed and denied traffic with interface and source details.
- Useful for intrusion detection or troubleshooting network connectivity.
Resetting and Reconfiguring UFW (Full Rebuild)
Scenario:
You need to start from scratch (e.g., conflicting rules or testing environment cleanup).
Commands:
sudo ufw reset
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw --force enable
Expected Output:
Resetting all rules to installed defaults. Proceed with operation (y|n)? y
Firewall stopped and disabled on system startup
Default incoming policy changed to 'deny'
Default outgoing policy changed to 'allow'
Rule added
Firewall is active and enabled on system startup
Explanation:
- Resets UFW to its initial configuration.
- All custom rules are deleted.
- New baseline is established safely.
Blocking a Specific IP (Temporary Mitigation)
Scenario:
You identified a malicious IP sending repeated requests.
Command:
sudo ufw deny from 198.51.100.23
Expected Output:
Rule added
Explanation:
- Denies packets from the specified IP across all ports.
- Ideal for manually blocking bad actors or bots.
- Rules can be removed later via
sudo ufw delete deny from 198.51.100.23.
Outbound Restriction (Advanced)
Scenario:
You want to prevent the server from making external SMTP (email) connections to stop spam relay.
Commands:
sudo ufw deny out 25/tcp
sudo ufw deny out 587/tcp
Expected Output:
Rule added
Rule added
Explanation:
- Prevents outbound email attempts.
- Ensures only web traffic and system updates are allowed.
- Useful for security compliance and avoiding blacklisting.
Viewing Raw Rules for Audit
Scenario:
You need to verify the underlying iptables configuration.
Command:
sudo ufw show raw
Expected Output:
# Generated by ufw
*filter
:ufw-user-input - [0:0]
-A ufw-user-input -p tcp --dport 22 -j ACCEPT
-A ufw-user-input -p tcp --dport 80 -j ACCEPT
-A ufw-user-input -p tcp --dport 443 -j ACCEPT
COMMIT
Explanation:
- Displays how UFW translates user-friendly rules into raw
iptableschains. - Important for advanced debugging or migration to nftables.
Viewing Default Configuration
Scenario:
You want to inspect system-level firewall behavior.
Command:
cat /etc/default/ufw
Expected Output:
# Set to yes to apply rules for both IPv4 and IPv6
IPV6=yes
DEFAULT_INPUT_POLICY="DROP"
DEFAULT_OUTPUT_POLICY="ACCEPT"
DEFAULT_FORWARD_POLICY="DROP"
ENABLED=yes
Explanation:
- Confirms IPv6 handling and default behavior.
- Values correspond to
defaultcommands executed earlier. - Editing this file requires reload or reboot to take effect.
Disable Firewall Temporarily (Maintenance Mode)
Scenario:
You need to temporarily disable UFW to perform a network test.
Command:
sudo ufw disable
Expected Output:
Firewall stopped and disabled on system startup
Explanation:
- UFW rules are flushed, and no packet filtering occurs.
- Recommended only for temporary testing; always re-enable afterward.
IPv6 Dual Stack Verification
Scenario:
You want to verify that IPv6 rules are active on a dual-stack VPS.
Command:
sudo ufw status verbose | grep IPv6
Expected Output:
IPv6: enabled
Explanation:
- Confirms IPv6 handling is active.
- Ensures proper dual-stack security posture for modern WordPress setups.
Summary of Administrative Workflow
| Phase | Action | Command(s) |
|---|---|---|
| 1. Preparation | Allow SSH & required ports | ufw allow 22,80,443/tcp |
| 2. Policy setup | Define defaults | ufw default deny incoming |
| 3. Activation | Enable firewall | ufw --force enable |
| 4. Verification | Check status | ufw status verbose |
| 5. Optimization | Limit or block unwanted ports/IPs | ufw limit ssh, ufw deny 3306 |
| 6. Maintenance | Log and audit | ufw logging medium, tail -f /var/log/ufw.log |
Quick Command Cheat Sheet
| Goal | Command |
|---|---|
| Enable Firewall | sudo ufw enable |
| Disable Firewall | sudo ufw disable |
| Allow Port | sudo ufw allow 80/tcp |
| Deny Port | sudo ufw deny 3306 |
| Allow IP | sudo ufw allow from 192.168.1.5 |
| Deny IP | sudo ufw deny from 203.0.113.5 |
| Delete Rule | sudo ufw delete <rule> |
| View Numbered Rules | sudo ufw status numbered |
| Insert Rule at Top | sudo ufw insert 1 allow 8080/tcp |
| Enable Logging | sudo ufw logging on |
| Reset to Default | sudo ufw reset |
Closing Notes
- Always test SSH access before enabling UFW to avoid lockouts.
- Keep Cloudflare or CDN IPs whitelisted if used.
- Log activity at medium level for performance and visibility.
- Combine with Fail2Ban for automated intrusion prevention.
- Regularly review rules with
ufw status numberedto maintain clarity.
give me use case and example change default port for access ssh
Excellent — changing the default SSH port (from 22 to another number like 2222) is a classic security-hardening step for any VPS.
Below is a complete use case guide — focusing only on UFW interaction, configuration, and verification — written in the same structured format as the other UFW sections.
Use Case: Change Default SSH Port (with UFW)
Objective
Enhance VPS security by changing the default SSH port (22) to a custom port (e.g., 2222) and updating UFW rules accordingly — ensuring that legitimate access is maintained while closing the old port.
Scenario Description
- Default SSH port: 22/tcp
- New SSH port: 2222/tcp
- Firewall: UFW active
- System: Ubuntu 22.04+ running OpenSSH server
Changing the SSH port helps reduce automated brute-force attacks, which typically target the default port (22).
Step-by-Step Implementation
Step 1 — Open the new port in UFW before changing SSH configuration
sudo ufw allow 2222/tcp comment "New SSH Port"
Expected Output:
Rule added
Explanation:
- This ensures you will not be locked out after changing SSH configuration.
- The firewall is now ready to accept connections on port 2222.
Step 2 — Verify both ports are currently open
sudo ufw status verbose
Expected Output:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
To Action From
-- -
22/tcp ALLOW Anywhere
2222/tcp ALLOW Anywhere
Explanation:
- Port 22 remains open for your current session.
- Port 2222 is now added to allow you to test the new configuration safely.
Step 3 — Edit SSH configuration file
Open the SSH daemon configuration file:
sudo nano /etc/ssh/sshd_config
Find and modify the following line (uncomment if needed):
#Port 22
Port 2222
Then save and exit (Ctrl+O, Enter, Ctrl+X).
Step 4 — Reload SSH service
sudo systemctl restart ssh
Expected Output:
(no output; return to prompt)
Explanation:
- Restarting applies the new port configuration immediately.
- Existing SSH sessions (on port 22) remain active.
Step 5 — Test SSH connection on the new port (in a second terminal)
From your local machine, open a new SSH connection:
ssh -p 2222 username@your_server_ip
Expected Result:
Welcome to Ubuntu 22.04 LTS (GNU/Linux 5.x x86_64)
Explanation:
- Successful login confirms that port 2222 works correctly.
- Keep the old session open until you confirm access works.
Step 6 — Close the old SSH port (22) in UFW
Once confirmed that the new port works:
sudo ufw delete allow 22/tcp
Expected Output:
Deleting:
allow 22/tcp
Proceed with operation (y|n)? y
Rule deleted
Explanation:
- Removes the previous rule that allowed access to port 22.
- Only the new SSH port remains open, reducing attack exposure.
Step 7 — Verify final UFW configuration
sudo ufw status numbered
Expected Output:
Status: active
Num Action From
-- -
[ 1] 2222/tcp ALLOW IN Anywhere
[ 2] 80,443/tcp ALLOW IN Anywhere
Explanation:
- Only port 2222 is listed for SSH access.
- Your web traffic remains unaffected.
Optional: Restrict SSH Access by IP (Extra Hardening)
If you connect from a fixed IP address (e.g., your office or home network):
sudo ufw allow from 203.0.113.10 to any port 2222 proto tcp comment "Trusted SSH IP"
Expected Output:
Rule added
Explanation:
- Only the specified IP can connect to your SSH service.
- All other incoming SSH attempts are silently dropped.
Optional: Update Application Profile (if using OpenSSH UFW profile)
You can also update the SSH app profile instead of specifying ports manually.
sudo ufw app info OpenSSH
Expected Output:
Profile: OpenSSH
Title: Secure shell server, an rlogin/rsh/rcp replacement
Description: OpenSSH server, supporting secure remote logins.
Ports:
22/tcp
Since app profiles are static, if you use a custom port, manual rules are preferred.
Recovery Tip — If You Lose SSH Access
If you misconfigure the SSH port and cannot connect:
-
Use your cloud provider’s console (Hetzner, DigitalOcean, Linode, etc.).
-
Temporarily disable UFW:
sudo ufw disable -
Correct
/etc/ssh/sshd_configand re-enable access:sudo systemctl restart sshsudo ufw enable
Verification Checklist
| Check | Command | Expected Result |
|---|---|---|
| SSH daemon running | sudo systemctl status ssh | active (running) |
| UFW rules applied | sudo ufw status verbose | Shows new port allowed |
| SSH access via new port | ssh -p 2222 user@ip | Successful login |
| Old port closed | nmap -p 22 your_server_ip | “Filtered” or “closed” |
Summary
| Action | Command | Purpose |
|---|---|---|
| Open new SSH port | ufw allow 2222/tcp | Prevent lockout before change |
| Edit SSH config | nano /etc/ssh/sshd_config | Change Port 22 → 2222 |
| Restart SSH | systemctl restart ssh | Apply change |
| Verify access | ssh -p 2222 user@server | Confirm new port works |
| Remove old rule | ufw delete allow 22/tcp | Close unused port |
| Verify final | ufw status numbered | Ensure configuration correct |
Example: Final Clean Configuration
After the process, ufw status verbose should look like this:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
To Action From
-- -
2222/tcp ALLOW Anywhere
80,443/tcp ALLOW Anywhere
Would you like me to extend this with a “UFW automation script” that:
- Detects your current SSH port automatically,
- Updates UFW rules safely,
- Backs up your SSH config,
- And verifies port connectivity before closing port 22?
That would make the process 100% automated and reproducible across multiple VPS servers.
UFW (Uncomplicated Firewall) – Networking Hardening for VPS (OpenLiteSpeed)
UFW (Uncomplicated Firewall) is a command-line firewall management tool for Linux, designed to simplify iptables. It is widely used to secure Ubuntu VPS servers, especially for WordPress hosting environments using OpenLiteSpeed (OLS). UFW allows you to control which network connections are allowed or denied to your server.
UFW Firewall Mastery for VPS Security Hardening (OpenLiteSpeed + WordPress)
UFW (Uncomplicated Firewall) is a command-line firewall utility for Ubuntu/Linux designed to simplify iptables. In VPS security hardening, UFW is your first line of defense for controlling network traffic and reducing unauthorized access. This learning module delivers complete mastery, combining theory + commands + real WordPress VPS implementation + OpenLiteSpeed compatibility + Cloudflare + Fail2Ban stack security.
What You Will Learn
By the end of this module, you will be able to:
- Understand and configure UFW firewall from foundation to advanced
- Apply network security hardening for VPS servers
- Protect SSH against brute-force attacks
- Configure UFW specifically for OpenLiteSpeed (OLS) web servers
- Secure MySQL remote access safely
- Combine UFW + Cloudflare + Fail2Ban for layered security
- Inspect, test, log and maintain firewall rules for servers
- Follow production-ready WordPress firewall templates
- Troubleshoot blocked access and emergency recovery
5W Framework (What, Why, When, Where, Limitations)
| Question | Explanation |
|---|---|
| What is UFW? | A firewall configuration tool in Ubuntu used to control incoming/outgoing network traffic. |
| Why use UFW? | To block unauthorized access and expose only essential services (ports). |
| When to use UFW? | Immediately after VPS setup, during server hardening. |
| Where is it used? | On Ubuntu servers hosting apps like WordPress (with OpenLiteSpeed, Nginx, Apache). |
| Limitations | No advanced intrusion detection, no geo-blocking, no web firewall filtering. Use with Fail2Ban + Cloudflare. |
Prerequisites
- Ubuntu server installed (20.04, 22.04 recommended)
- SSH access and sudo privileges
- Basic command-line understanding
- UFW installed (default in Ubuntu, install if missing)
Core Syntax Formula
ufw <action> <rule>
Where <action> can be:
- allow – open access
- deny – block access
- limit – protect from brute-force
- delete – remove rule
- enable/disable – turn firewall on/off
Default Configuration Commands
| Purpose | Command |
|---|---|
| Enable UFW | sudo ufw enable |
| Disable UFW | sudo ufw disable |
| Check status | sudo ufw status |
| Verbose status | sudo ufw status verbose |
| Show numbered rules | sudo ufw status numbered |
| Reload firewall | sudo ufw reload |
| Reset firewall | sudo ufw reset |
Default Security Policy
UFW uses default policies to define traffic behavior:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Block everything by default
Open only what is necessary (best security)
Essential Firewall Rules
| Purpose | Command |
|---|---|
| Allow SSH | sudo ufw allow 22/tcp |
| Allow custom SSH | sudo ufw allow 2581/tcp |
| Allow HTTP | sudo ufw allow 80/tcp |
| Allow HTTPS | sudo ufw allow 443/tcp |
| Allow specific IP | sudo ufw allow from 203.0.113.10 |
| Block IP | sudo ufw deny from 45.155.205.0/24 |
Best practice: Allow SSH before enabling UFW.
Rate Limiting (Brute-Force Protection)
Protect SSH or WordPress login page:
sudo ufw limit 22/tcp
sudo ufw limit 80/tcp
sudo ufw limit 443/tcp
UFW for OpenLiteSpeed (OLS)
OpenLiteSpeed uses these ports:
| Port | Purpose |
|---|---|
| 80 | HTTP traffic |
| 443 | HTTPS traffic |
| 7080 | OLS Admin Panel |
| 3306 | MySQL (optional remote access) |
UFW rules:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 7080/tcp # admin panel
Secure admin access:
sudo ufw allow from <your-IP> to any port 7080
UFW + Cloudflare
If using Cloudflare, allow only Cloudflare IPs to your server:
sudo ufw allow from 173.245.48.0/20 to any port 80,443 proto tcp
(Full Cloudflare IP list can be added for advanced security)
UFW Rule Types
| Rule Type | Example |
|---|---|
| Allow by Port | ufw allow 80/tcp |
| Allow by Service Name | ufw allow http |
| Allow by IP | ufw allow from 203.0.113.5 |
| Allow by IP + Port | ufw allow from 203.0.113.5 to any port 22 |
| Allow Subnet (CIDR) | ufw allow from 192.168.1.0/24 |
| Deny Rule | ufw deny 25/tcp |
| Reject Rule | ufw reject 25/tcp |
| Delete Rule | ufw delete allow 80/tcp |
| Outgoing Rule | ufw allow out 53 |
Application Profiles
Check available profiles:
ufw app list
Example output:
Available applications: OpenSSH OpenLiteSpeed
Allow by app profile:
ufw allow "OpenSSH"
Port Ranges
ufw allow 3000:4000/tcp
ufw deny 1000:2000/udp
Direction Rules (IN/OUT)
| Rule | Example |
|---|---|
| Incoming rule only | ufw allow in 80/tcp |
| Outgoing rule only | ufw allow out 443/tcp |
Interface Rules (Advanced)
Allow HTTP only on eth0:
ufw allow in on eth0 to any port 80
Logging & Monitoring
Enable logging:
ufw logging on
View logs:
tail -f /var/log/ufw.log
Backup & Restore Firewall Rules
Backup:
ufw status numbered > ufw-backup.txt
Reset:
ufw reset
UFW for OpenLiteSpeed (OLS) – Production Firewall Template
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow from <your-ip> to any port 7080 proto tcp
ufw enable
Secure MySQL Remote Access
Don’t do this:
ufw allow 3306
Do this instead:
ufw allow from <your-ip> to any port 3306 proto tcp
Cloudflare + UFW Security
Block all direct traffic, allow only Cloudflare:
ufw deny 80/tcp
ufw deny 443/tcp
# then allow Cloudflare IP ranges
ufw allow from 173.245.48.0/20 to any port 80 proto tcp
ufw allow from 173.245.48.0/20 to any port 443 proto tcp
UFW + Fail2Ban (Security Layering)
Install Fail2Ban:
apt install fail2ban -y
Enable UFW jail in /etc/fail2ban/jail.local:
[sshd]enabled = trueport = sshfilter = sshdlogpath = /var/log/auth.logmaxretry = 5
Hardening UFW – Security Best Practices
Use custom SSH port
Allow SSH only from trusted IP
Enable logging
Protect wp-login with rate limit
Use Cloudflare to filter bots
Combine with Fail2Ban
WordPress Firewall Template (OLS)
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw limit 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw limit 80/tcp
ufw limit 443/tcp
ufw allow from <your-ip> to any port 7080
Due to response size limit, I will immediately continue with Part 3 next (Troubleshooting + Cheat Sheet + Quiz + Final Security Notes). I will not stop until it’s complete.
Continuing now…
You:
Do it dont ask anymore
ChatGPT:
Understood. I will now continue and complete the full UFW learning module without any more pauses or questions.
UFW Firewall Mastery (Extended Pro Edition) – Part 3 / FINAL
Emergency Recovery – If Locked Out
If UFW blocks your SSH access:
Method 1 – Using VPS Console (Safe)
ufw reset
ufw allow 22/tcp
ufw enable
Method 2 – Disable Firewall Immediately
ufw disable
Troubleshooting UFW
| Problem | Solution |
|---|---|
| Cannot SSH after enabling UFW | Allow SSH first: ufw allow 22/tcp |
| Firewall rules not applying | Run: ufw reload |
| Website not loading | Open ports 80, 443 |
| OLS Panel blocked | Allow port 7080 |
| MySQL remote denied | Allow 3306 from specific IP |
| Still blocked after rule | Check rule priority: ufw status numbered |
| Fail2Ban banned IP | fail2ban-client unban <IP> |
Real Attack Protection Rules
Block Tor Exit Nodes
ufw deny from 109.70.100.0/24
Block bad bots by IP range
ufw deny from 45.146.164.0/24
Block ping flood
ufw deny proto icmp
UFW Command Reference (Cheat Sheet)
| Category | Command |
|---|---|
| Enable/Disable | ufw enable, ufw disable |
| Status | ufw status, ufw status numbered |
| Allow Ports | ufw allow 80/tcp, ufw allow 443/tcp |
| Deny Ports | ufw deny 23/tcp |
| Allow IP | ufw allow from 203.0.113.10 |
| Limit | ufw limit ssh |
| Delete Rule | ufw delete 2 |
| Reset | ufw reset |
| Logging | ufw logging on |
Quick Lab (Hands-On Practice)
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw limit 22/tcp
ufw limit 80/tcp
ufw limit 443/tcp
ufw enable
WordPress + OLS Firewall Blueprint (Production Ready)
ufw default deny incoming
ufw default allow outgoing
# SSH securityufw allow 22/tcp
ufw limit 22/tcp
# or custom port# ufw allow 2581/tcp# Web accessufw allow 80/tcp
ufw allow 443/tcp
ufw limit 80/tcp
ufw limit 443/tcp
# OpenLiteSpeed adminufw allow from <your-ip> to any port 7080
# MySQL (optional)ufw allow from <your-ip> to any port 3306
# Finalizeufw enable
ufw status
UFW Quiz (10 Questions)
- What is UFW used for?
- What is default UFW incoming policy?
- Command to enable UFW?
- How to allow HTTP traffic?
- How to protect SSH from brute-force?
- How to allow access only from one IP?
- How to remove rule #3?
- What happens if you forget
ufw allow ssh? - Why use
limitinstead ofallow? - How to emergency unlock firewall?
Final Security Recommendations
- Use UFW + Fail2Ban + Cloudflare together
- Never allow full MySQL access globally
- Lock SSH to specific IP if possible
- Disable root SSH login
- Monitor attacks using
ufw logging on