惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
Security Latest
Security Latest
P
Privacy International News Feed
T
Threat Research - Cisco Blogs
H
Help Net Security
T
The Exploit Database - CXSecurity.com
Know Your Adversary
Know Your Adversary
博客园_首页
S
Securelist
S
Schneier on Security
G
GRAHAM CLULEY
Cisco Talos Blog
Cisco Talos Blog
V
Visual Studio Blog
博客园 - 叶小钗
C
Cybersecurity and Infrastructure Security Agency CISA
有赞技术团队
有赞技术团队
Recent Announcements
Recent Announcements
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Azure Blog
Microsoft Azure Blog
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Stack Overflow Blog
Stack Overflow Blog
量子位
L
Lohrmann on Cybersecurity
Hugging Face - Blog
Hugging Face - Blog
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
C
CXSECURITY Database RSS Feed - CXSecurity.com
A
Arctic Wolf
P
Privacy & Cybersecurity Law Blog
Simon Willison's Weblog
Simon Willison's Weblog
S
SegmentFault 最新的问题
The Hacker News
The Hacker News
罗磊的独立博客
博客园 - 司徒正美
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 【当耐特】
Microsoft Security Blog
Microsoft Security Blog
K
Kaspersky official blog
人人都是产品经理
人人都是产品经理
博客园 - 聂微东
L
LINUX DO - 热门话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
V2EX
V
Vulnerabilities – Threatpost
AWS News Blog
AWS News Blog
小众软件
小众软件
Project Zero
Project Zero

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Linux Firewall Configuration with UFW and iptables
Big Mazzy · 2026-05-02 · via DEV Community

Protecting your servers from unauthorized access is a fundamental responsibility for any developer or system administrator. This article will guide you through configuring Linux firewalls using two powerful tools: UFW (Uncomplicated Firewall) and iptables. You'll learn how to set up basic rules, manage common ports, and understand the underlying concepts to secure your applications and data.

Why a Linux Firewall Matters

Imagine your server is a house. Without a firewall, every door and window is wide open, inviting anyone to come in, see what they want, or even cause damage. A firewall acts as a security guard, controlling who can enter and leave your server, ensuring only legitimate traffic gets through. This is crucial for preventing data breaches, service disruptions, and unauthorized modifications to your systems.

Understanding the Basics: Ports and Protocols

Before diving into configuration, it's essential to grasp a couple of key concepts.

Ports are like specific doors on your server, each assigned a number. Different services use different ports. For example, web servers typically listen on port 80 for HTTP traffic and port 443 for HTTPS traffic. SSH, used for remote command-line access, commonly uses port 22.

Protocols are the languages traffic speaks. The two most common are:

  • TCP (Transmission Control Protocol): This is a connection-oriented protocol. Think of it like a phone call where a connection is established before data is sent, and a confirmation is sent back to ensure everything arrived. It's reliable but can be a bit slower.
  • UDP (User Datagram Protocol): This is a connectionless protocol. It's like sending a postcard – you send it and hope it gets there, but there's no guarantee or confirmation. It's faster than TCP but less reliable.

UFW: The Uncomplicated Firewall

UFW is designed to be a user-friendly front-end for iptables. It simplifies common firewall tasks, making it an excellent choice for beginners and those who want quick, effective protection.

Installing UFW

UFW is often pre-installed on Debian-based systems like Ubuntu. If it's not, you can install it with:

sudo apt update
sudo apt install ufw

Enter fullscreen mode Exit fullscreen mode

Enabling and Disabling UFW

Before you start adding rules, it's a good idea to disable UFW if it's already running to avoid locking yourself out.

sudo ufw disable

Enter fullscreen mode Exit fullscreen mode

Once you've configured your rules, you can enable it:

sudo ufw enable

Enter fullscreen mode Exit fullscreen mode

When you enable UFW, it will prompt you to confirm. Type y and press Enter. It's crucial to have SSH access allowed before enabling UFW if you're connected remotely.

Setting Default Policies

The first step in hardening your server is to set default policies. This determines what happens to traffic that doesn't match any specific rules.

  • Deny incoming traffic: This is the safest default. It means only traffic you explicitly allow will get in.
  • Allow outgoing traffic: This is generally safe, allowing your server to connect to external resources.
sudo ufw default deny incoming
sudo ufw default allow outgoing

Enter fullscreen mode Exit fullscreen mode

Allowing Specific Ports and Services

Now, let's open up the necessary doors.

Allowing SSH (Crucial for Remote Access)

If you're managing your server remotely, you must allow SSH traffic before enabling UFW. The default SSH port is 22.

sudo ufw allow ssh

Enter fullscreen mode Exit fullscreen mode

Or, if SSH is running on a different port (e.g., 2222):

sudo ufw allow 2222/tcp

Enter fullscreen mode Exit fullscreen mode

Allowing Web Traffic

For a web server, you'll need to allow HTTP (port 80) and HTTPS (port 443) traffic.

sudo ufw allow http
sudo ufw allow https

Enter fullscreen mode Exit fullscreen mode

Alternatively, using port numbers:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Enter fullscreen mode Exit fullscreen mode

Allowing Other Common Services

  • FTP (Port 21): While generally discouraged due to security concerns, you might need it for legacy systems.

    sudo ufw allow ftp
    
  • SMTP (Port 25): For sending emails.

    sudo ufw allow smtp
    
  • MySQL/MariaDB (Port 3306): If your application needs to connect to a database on the same server.

    sudo ufw allow 3306/tcp
    

Denying Traffic

You can also explicitly deny traffic. This is useful for blocking specific IP addresses or ports.

Denying a Specific IP Address

sudo ufw deny from 192.168.1.100

Enter fullscreen mode Exit fullscreen mode

Denying Traffic to a Specific Port

sudo ufw deny 8080

Enter fullscreen mode Exit fullscreen mode

Deleting Rules

If you make a mistake or no longer need a rule, you can delete it. First, list the rules with numbers:

sudo ufw status numbered

Enter fullscreen mode Exit fullscreen mode

Then, delete the rule by its number:

sudo ufw delete <rule_number>

Enter fullscreen mode Exit fullscreen mode

For example, to delete rule number 5:

sudo ufw delete 5

Enter fullscreen mode Exit fullscreen mode

Advanced UFW Features

  • Rate Limiting: Protect against brute-force attacks by limiting the number of connection attempts from a single IP address. This is excellent for SSH.

    sudo ufw limit ssh
    

    This rule allows SSH connections but denies them if an IP address attempts to initiate 6 or more connections within 30 seconds.

  • Allowing Specific IP Ranges:

    sudo ufw allow from 192.168.1.0/24 to any port 22
    

    This allows SSH access from any IP address within the 192.168.1.x subnet.

  • Application Profiles: UFW can manage rules for specific applications if they provide profiles.

    sudo ufw app list
    sudo ufw allow 'Nginx Full'
    

Checking UFW Status

Always verify your configuration:

sudo ufw status verbose

Enter fullscreen mode Exit fullscreen mode

This command shows you the current status of UFW, its default policies, and all applied rules.

iptables: The Powerhouse Firewall

While UFW is fantastic for its simplicity, iptables is the underlying Linux firewall mechanism. It offers granular control but has a steeper learning curve. Understanding iptables can be beneficial for complex scenarios or when you need fine-tuned control that UFW might not directly expose.

iptables works with tables (e.g., filter, nat, mangle) and chains (e.g., INPUT, OUTPUT, FORWARD).

  • Tables: Different tables handle different types of packet processing. The filter table is used for packet filtering (allowing or denying). The nat table is used for Network Address Translation.
  • Chains: These are sequences of rules that packets traverse.
    • INPUT: For packets destined for the local machine.
    • OUTPUT: For packets originating from the local machine.
    • FORWARD: For packets being routed through the machine to another destination.

Basic iptables Commands

Let's look at some fundamental iptables commands.

Setting Default Policies

Similar to UFW, setting default policies is crucial.

sudo iptables -P INPUT DROP   # Drop all incoming traffic by default
sudo iptables -P FORWARD DROP # Drop all forwarded traffic by default
sudo iptables -P OUTPUT ACCEPT # Allow all outgoing traffic by default

Enter fullscreen mode Exit fullscreen mode

Allowing Established Connections

This is a vital rule. It allows packets that are part of an already established connection to pass through. Without this, even your own outgoing requests wouldn't get responses back.

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Enter fullscreen mode Exit fullscreen mode

  • -A INPUT: Appends this rule to the INPUT chain.
  • -m conntrack: Uses the conntrack module to track connection states.
  • --ctstate ESTABLISHED,RELATED: Matches packets that are part of an existing connection (ESTABLISHED) or related to an existing connection (like FTP data transfers) (RELATED).
  • -j ACCEPT: Jumps to the ACCEPT target, meaning the packet is allowed.

Allowing SSH

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Enter fullscreen mode Exit fullscreen mode

  • -p tcp: Specifies the TCP protocol.
  • --dport 22: Specifies the destination port as 22.
  • -j ACCEPT: Accepts the traffic.

Allowing HTTP and HTTPS

sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Enter fullscreen mode Exit fullscreen mode

Allowing Loopback Interface Traffic

The loopback interface (lo) is used for communication within the server itself. It's important to allow traffic on this interface.

sudo iptables -A INPUT -i lo -j ACCEPT

Enter fullscreen mode Exit fullscreen mode

  • -i lo: Specifies the incoming interface as lo.

Saving iptables Rules

iptables rules are volatile; they are lost upon reboot. You need to save them. The method varies slightly between distributions.

On Debian/Ubuntu:

sudo apt install iptables-persistent
sudo netfilter-persistent save

Enter fullscreen mode Exit fullscreen mode

During the installation of iptables-persistent, you'll be asked if you want to save current IPv4 and IPv6 rules. Choose "Yes."

On CentOS/RHEL (using iptables-services):

sudo yum install iptables-services
sudo systemctl enable iptables
sudo systemctl start iptables
sudo iptables-save > /etc/sysconfig/iptables

Enter fullscreen mode Exit fullscreen mode

Listing iptables Rules

To see your current rules:

sudo iptables -L -v -n

Enter fullscreen mode Exit fullscreen mode

  • -L: List rules.
  • -v: Verbose output (shows packet and byte counts).
  • -n: Numeric output (shows IP addresses and port numbers instead of trying to resolve names).

Deleting iptables Rules

You can delete rules by specifying the exact rule with -D or by line number (similar to UFW).

To delete by line number:

sudo iptables -L INPUT --line-numbers
sudo iptables -D INPUT <line_number>

Enter fullscreen mode Exit fullscreen mode

A Note on UFW and iptables

Remember, UFW is a front-end for iptables. If you enable UFW, it will manage iptables rules for you. It's generally best to stick to one or the other to avoid conflicts. If you need the fine-grained control of iptables and want to manage it directly, disable UFW first.

Practical Scenarios and Recommendations

When setting up a new server, whether it's a small VPS from PowerVPS or a more robust cloud instance from Immers Cloud, your first step after initial setup should be firewall configuration.

Scenario 1: A Simple Web Server

You're deploying a basic website.

  • UFW:

    sudo ufw default deny incoming
    sudo ufw default allow outgoing
    sudo ufw allow ssh
    sudo ufw allow http
    sudo ufw allow https
    sudo ufw enable
    
  • iptables:

    sudo iptables -P INPUT DROP
    sudo iptables -P FORWARD DROP
    sudo iptables -P OUTPUT ACCEPT
    sudo iptables -A INPUT -i lo -j ACCEPT
    sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    # Save rules
    

Scenario 2: A Development Server with Database Access

You need to host a web application and its database.

  • UFW:

    sudo ufw default deny incoming
    sudo ufw default allow outgoing
    sudo ufw allow ssh
    sudo ufw allow http
    sudo ufw allow https
    sudo ufw allow 3306/tcp # Assuming database is on the same server
    sudo ufw enable
    
  • iptables:
    (Similar to Scenario 1, but add the database port rule)

    sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
    # ... other rules and save
    

    Important Consideration: If your database is on a separate server, you should not open port 3306 to the entire internet. Instead, you'd restrict access to only the IP addresses of your application servers.

**Scenario 3: Securing SSH with