Skip to main content

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 direct nftables across 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)
  • IPv6 behavior is controlled by /etc/default/ufw (IPV6=yes/no) and IPv6 rule files.

Lockout risk

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

  1. The theoretical foundation and purpose of UFW in Linux systems.
  2. Core syntax and command structure.
  3. Explanation of every available option and flag.
  4. The concept of default policies, rule sets, and logging modes.
  5. Understanding the internal configuration and system files associated with UFW.
  6. Relationship of UFW with iptables and other firewall frameworks.
  7. 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.conf for startup enablement.

  • /etc/ufw/before.rules and /etc/ufw/after.rules for pre- and post-processing chains.

  • /etc/ufw/applications.d/ for application-specific profiles.

    Logging outputs are stored under /var/log/ufw.log or system logs.

Core Syntax Formula

ufw [global-options] <command> [parameters]

ComponentDescription
ufwThe 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 / FlagPurposeRemarks
--helpDisplays UFW help information and available commands.Used for reference or troubleshooting.
--versionPrints the current installed version of UFW.Helpful for compatibility checks.
--forceSuppresses interactive confirmation prompts.Essential for automation and scripting.
--verboseUsed 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.
--resetResets 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

CommandPurposeTheoretical Description
enableActivates UFW and loads configured rules into the kernel firewall subsystem.When enabled, UFW translates all stored rules into kernel-level iptables chains.
disableDeactivates UFW, flushing or bypassing the kernel rules managed by it.Stops packet filtering based on UFW configuration.
reloadRe-applies all current rules without disabling the firewall.Useful when modifying rules on a live system.
resetRemoves all existing user rules and returns to default deny/allow policies.Equivalent to re-initializing the firewall.
statusDisplays current operational status (active/inactive).Provides summary view of applied rules.
status verboseDisplays extended information including logging mode, IPv6 usage, and default policies.Used for audit and verification.
status numberedShows 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.

CommandDefault DirectionPurpose / Theoretical Function
default allow incomingIncomingPermits all inbound connections by default. Rarely used for secure environments.
default deny incomingIncomingBlocks all inbound traffic unless explicitly allowed. Most common for servers.
default reject incomingIncomingRejects inbound connections with a response packet rather than silently dropping.
default allow outgoingOutgoingAllows all outbound connections. Standard behavior for most systems.
default deny outgoingOutgoingBlocks all outbound traffic unless specifically permitted. Used in restricted networks.
default allow routedRoutedAllows forwarded traffic through the host (for routing scenarios).
default deny routedRoutedDenies 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

CommandTheoretical BehaviorPurpose
allowCreates a permit rule that accepts matching packets.Enables legitimate service access (e.g., HTTP, SSH).
denyDrops packets silently without response.Reduces system exposure; no feedback to sender.
rejectDrops packets but sends a rejection message (ICMP/TCP RST).Useful for transparency; informs sender of rejection.
limitAccepts limited number of new connections per time interval.Rate-limits excessive attempts, commonly for SSH.
route allow / route denyApplies the same principles but to forwarded packets (router contexts).Controls traffic passing through the system.

2. Rule Direction Modifiers

ParameterEffect on RuleTheoretical Purpose
inApplies to incoming traffic directed to the host.Used for protecting services.
outApplies to outgoing traffic from the host.Used for controlling data exfiltration.

3. Interface Modifiers

ParameterExplanation
on <interface>Binds the rule to a specific network interface (e.g., eth0, ens3).
from anyApplies rule to packets from all sources.
to anyApplies rule to packets going to any destination.

4. Address & Subnet Modifiers

ParameterPurpose
from <IP>Defines the source address or network (e.g., 192.168.1.0/24).
to <IP>Defines the destination address or network.
anyWildcard for all IPs.
::/0Represents all IPv6 addresses.

5. Port & Protocol Modifiers

ParameterPurpose / 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 udpRestricts the rule to a specific protocol family.

6. Commenting & Labeling

ParameterDescription
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 / ParameterPurpose
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.

CommandFunctionConceptual Explanation
app listLists 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

CommandPurposeTheoretical Description
statusProvides summary of firewall activity.Indicates whether UFW is active and lists major rules.
status verboseShows extended configuration details.Displays logging, IPv6 state, and default policy.
status numberedLists all rules with numeric identifiers.Used for referencing rules when deleting.
show addedDisplays rules added since last restart.Helps identify changes made during runtime.
show rawDisplays raw iptables or nftables syntax behind UFW rules.Useful for low-level auditing or debugging.
show listeningLists currently open ports on the system.Reveals network exposure points.
logging on/offEnables or disables logging globally.Activates packet logging to /var/log/ufw.log.
`logging lowmediumhigh

Rule Parameter Components (Detailed Theoretical Reference)

Below is a breakdown of the internal logic and meaning of parameters used within rule definitions.

ComponentMeaningExample (Theoretical)
ActionDetermines the rule type (allow, deny, reject, limit).“Allow incoming TCP packets on port 22.”
DirectionSpecifies whether the rule applies to incoming or outgoing traffic.“Allow in” or “Deny out.”
InterfaceBinds rule to a network interface.“on eth0” applies only to that NIC.
Source AddressOrigin IP or subnet.“from 192.168.1.0/24.”
Destination AddressTarget IP or subnet.“to any port 443.”
ProtocolType of connection (TCP/UDP/ICMP).“proto tcp.”
PortTarget port number.“port 3306.”
CommentAnnotation for administrative clarity.“comment 'database access rule'.”

Logging and Monitoring Modes (Theory)

ModePurposeInformation Level
offDisables packet logging completely.No records kept.
lowLogs only blocked connections.Minimal performance impact.
mediumLogs both accepted and denied connections with summary detail.Balanced for audit purposes.
highLogs every packet decision event.Suitable for debugging.
fullEnables 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 / DirectoryRoleDetails
/etc/ufw/ufw.confMain configuration file controlling whether UFW starts at boot.Defines ENABLED=yes/no.
/etc/default/ufwHolds default IPv6 toggle and base policies.Contains key variables used during initialization.
/etc/ufw/before.rulesSet of iptables rules applied before user-defined ones.Handles loopback and essential system traffic.
/etc/ufw/after.rulesRules applied after user-defined rules.Often used for NAT or post-processing.
/etc/ufw/before6.rules / after6.rulesIPv6 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.logDedicated log file for UFW logging.Managed by rsyslog; controlled by logging setting.

Internal Operation (Conceptual Overview)

StageProcessDescription
1. InitializationUFW loads default configuration files.Establishes kernel chain structures.
2. Policy SetupDefault deny/allow behavior is established.Defines system security baseline.
3. Rule TranslationHuman-readable rules are converted into iptables/nftables entries.Maps to kernel packet filters.
4. ActivationKernel applies all configured rules.Firewall becomes active and enforces filtering.
5. MonitoringLogging and counters begin recording traffic matches.Maintains visibility and auditing.

Theoretical Relationships

LayerComponentFunction
User LayerUFW CLIHuman-readable interface.
Translation LayerUFW ParserConverts syntax to iptables/nft commands.
Kernel LayerNetfilter FrameworkExecutes packet filtering.
System LayerLogging & Service ManagementProvides audit and service persistence.

Summary of Theoretical Principles

  • Abstraction: UFW abstracts iptables complexity 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 limit action 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:

  • medium level 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 iptables chains.
  • 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 default commands 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

PhaseActionCommand(s)
1. PreparationAllow SSH & required portsufw allow 22,80,443/tcp
2. Policy setupDefine defaultsufw default deny incoming
3. ActivationEnable firewallufw --force enable
4. VerificationCheck statusufw status verbose
5. OptimizationLimit or block unwanted ports/IPsufw limit ssh, ufw deny 3306
6. MaintenanceLog and auditufw logging medium, tail -f /var/log/ufw.log

Quick Command Cheat Sheet

GoalCommand
Enable Firewallsudo ufw enable
Disable Firewallsudo ufw disable
Allow Portsudo ufw allow 80/tcp
Deny Portsudo ufw deny 3306
Allow IPsudo ufw allow from 192.168.1.5
Deny IPsudo ufw deny from 203.0.113.5
Delete Rulesudo ufw delete <rule>
View Numbered Rulessudo ufw status numbered
Insert Rule at Topsudo ufw insert 1 allow 8080/tcp
Enable Loggingsudo ufw logging on
Reset to Defaultsudo 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 numbered to 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_config and re-enable access:

    sudo systemctl restart ssh
    sudo ufw enable

Verification Checklist

CheckCommandExpected Result
SSH daemon runningsudo systemctl status sshactive (running)
UFW rules appliedsudo ufw status verboseShows new port allowed
SSH access via new portssh -p 2222 user@ipSuccessful login
Old port closednmap -p 22 your_server_ip“Filtered” or “closed”

Summary

ActionCommandPurpose
Open new SSH portufw allow 2222/tcpPrevent lockout before change
Edit SSH confignano /etc/ssh/sshd_configChange Port 222222
Restart SSHsystemctl restart sshApply change
Verify accessssh -p 2222 user@serverConfirm new port works
Remove old ruleufw delete allow 22/tcpClose unused port
Verify finalufw status numberedEnsure 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)

QuestionExplanation
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).
LimitationsNo 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

PurposeCommand
Enable UFWsudo ufw enable
Disable UFWsudo ufw disable
Check statussudo ufw status
Verbose statussudo ufw status verbose
Show numbered rulessudo ufw status numbered
Reload firewallsudo ufw reload
Reset firewallsudo 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

PurposeCommand
Allow SSHsudo ufw allow 22/tcp
Allow custom SSHsudo ufw allow 2581/tcp
Allow HTTPsudo ufw allow 80/tcp
Allow HTTPSsudo ufw allow 443/tcp
Allow specific IPsudo ufw allow from 203.0.113.10
Block IPsudo 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:

PortPurpose
80HTTP traffic
443HTTPS traffic
7080OLS Admin Panel
3306MySQL (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 TypeExample
Allow by Portufw allow 80/tcp
Allow by Service Nameufw allow http
Allow by IPufw allow from 203.0.113.5
Allow by IP + Portufw allow from 203.0.113.5 to any port 22
Allow Subnet (CIDR)ufw allow from 192.168.1.0/24
Deny Ruleufw deny 25/tcp
Reject Ruleufw reject 25/tcp
Delete Ruleufw delete allow 80/tcp
Outgoing Ruleufw 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)

RuleExample
Incoming rule onlyufw allow in 80/tcp
Outgoing rule onlyufw 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

ProblemSolution
Cannot SSH after enabling UFWAllow SSH first: ufw allow 22/tcp
Firewall rules not applyingRun: ufw reload
Website not loadingOpen ports 80, 443
OLS Panel blockedAllow port 7080
MySQL remote deniedAllow 3306 from specific IP
Still blocked after ruleCheck rule priority: ufw status numbered
Fail2Ban banned IPfail2ban-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)

CategoryCommand
Enable/Disableufw enable, ufw disable
Statusufw status, ufw status numbered
Allow Portsufw allow 80/tcp, ufw allow 443/tcp
Deny Portsufw deny 23/tcp
Allow IPufw allow from 203.0.113.10
Limitufw limit ssh
Delete Ruleufw delete 2
Resetufw reset
Loggingufw 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)

  1. What is UFW used for?
  2. What is default UFW incoming policy?
  3. Command to enable UFW?
  4. How to allow HTTP traffic?
  5. How to protect SSH from brute-force?
  6. How to allow access only from one IP?
  7. How to remove rule #3?
  8. What happens if you forget ufw allow ssh?
  9. Why use limit instead of allow?
  10. 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