🔒 Security

Firewall

Firewall

A security device that filters network traffic. Controls access with inbound/outbound rules. Protects the network by blocking unauthorized access and allowing only trusted traffic.

📖 Detailed Explanation

A firewall is a security system that serves as the first line of defense in network security, monitoring and controlling traffic between a trusted internal network and an untrusted external network (mainly the internet).

The name "firewall" originates from architecture. Just as a fire wall in a building prevents fire from spreading, a network firewall prevents malicious traffic from penetrating the internal network. After the Morris Worm incident in 1988, as the need for network security emerged, the first commercial firewall appeared.

Core Principles of a Firewall

Network Security Architecture

🌐 Internet
Untrusted zone
⬇️
🔥 Firewall
Traffic filtering
⬇️
🖥️ DMZ
Web server, mail server
⬇️
🏢 Internal Network
Internal systems, DB

OSI Layers and Firewalls

L7 Application WAF, NGFW - HTTP, SQL, malware inspection
L6 Presentation SSL/TLS decryption (NGFW)
L5 Session -
L4 Transport Stateful firewall - TCP/UDP port based
L3 Network Packet filtering - IP address based
L2 Data Link MAC filtering (switch)
L1 Physical -

🔥 Types of Firewalls

Packet Filtering Firewall

OSI L3-L4 (Network/Transport)

Inspects and blocks individual packets based on IP address, port number, and protocol. It is the most basic form.

✓ Fast speed ✗ Not state-aware

Stateful Inspection Firewall

OSI L3-L4 (State Tracking)

Tracks connection state and allows only packets that belong to legitimate sessions. It is the most common form today.

✓ Dynamic rules ✗ No L7 inspection

Application Gateway

OSI L7 (Application)

Operates as a proxy server and inspects even the content of application protocols (HTTP, FTP, etc.).

✓ Deep inspection ✗ Performance degradation

Next-Generation Firewall (NGFW)

OSI L3-L7 (Integrated)

A modern solution that integrates a traditional firewall + IPS + application awareness + SSL inspection + threat intelligence.

✓ Integrated security ✗ High cost

Firewall Comparison Table

Type Inspection Level Performance Security Level Use case
Packet Filtering IP, port Very high Basic Router ACL
Stateful Connection state High Medium General enterprise
WAF HTTP/SQL Medium High (web) Web application
NGFW L3-L7 all Medium Very high Enterprise

💻 Code Example

#!/bin/bash
# Linux iptables 방화벽 설정 예제

# 기본 정책: 모든 INPUT 거부, OUTPUT 허용
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# 로컬호스트 허용
iptables -A INPUT -i lo -j ACCEPT

# 확립된 연결 허용 (상태 기반)
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# SSH 허용 (포트 22, 특정 IP만)
iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT

# HTTP/HTTPS 허용 (모든 IP)
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# MySQL 허용 (내부 네트워크만)
iptables -A INPUT -p tcp --dport 3306 -s 192.168.0.0/16 -j ACCEPT

# ICMP (ping) 제한 (초당 1회)
iptables -A INPUT -p icmp --icmp-type echo-request \
    -m limit --limit 1/second -j ACCEPT

# 나머지 모두 로깅 후 거부
iptables -A INPUT -j LOG --log-prefix "DROPPED: "
iptables -A INPUT -j DROP
# Ubuntu UFW (Uncomplicated Firewall) 설정
# iptables의 간편한 래퍼

# UFW 활성화
sudo ufw enable

# 기본 정책 설정
sudo ufw default deny incoming
sudo ufw default allow outgoing

# SSH 허용 (기본 포트)
sudo ufw allow ssh
# 또는 특정 포트 지정
sudo ufw allow 22/tcp

# 웹 서버 허용
sudo ufw allow 'Nginx Full'
# 또는
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# 특정 IP에서만 MySQL 허용
sudo ufw allow from 192.168.1.0/24 to any port 3306

# 특정 IP 완전 차단
sudo ufw deny from 203.0.113.100

# 포트 범위 허용
sudo ufw allow 6000:6007/tcp

# 상태 확인
sudo ufw status verbose

# 규칙 번호로 삭제
sudo ufw status numbered
sudo ufw delete 3
# Terraform으로 AWS Security Group 정의
# 클라우드 방화벽의 대표적인 예

resource "aws_security_group" "web_server" {
  name        = "web-server-sg"
  description = "Security group for web servers"
  vpc_id      = aws_vpc.main.id

  # 인바운드 규칙: HTTP/HTTPS 허용
  ingress {
    description = "HTTPS from anywhere"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "HTTP from anywhere"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  # SSH는 VPN/배스천에서만 허용
  ingress {
    description     = "SSH from bastion"
    from_port       = 22
    to_port         = 22
    protocol        = "tcp"
    security_groups = [aws_security_group.bastion.id]
  }

  # 아웃바운드: 모든 트래픽 허용
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name        = "web-server-sg"
    Environment = "production"
  }
}

# DB용 Security Group (웹 서버에서만 접근)
resource "aws_security_group" "database" {
  name   = "database-sg"
  vpc_id = aws_vpc.main.id

  ingress {
    description     = "MySQL from web servers"
    from_port       = 3306
    to_port         = 3306
    protocol        = "tcp"
    security_groups = [aws_security_group.web_server.id]
  }
}

💬 Practical Conversation Example

Junior: I can't connect to the development server via SSH. I think it's a firewall issue. How do I check?
Senior: First, check whether the port is open with `telnet server-IP 22`. If it doesn't connect, it's a firewall issue. Then check the current rules on the server with `iptables -L -n` or `ufw status`.
Junior: I checked, and the SSH port isn't open. Is it okay to open it?
Senior: Don't open it to all IPs. Allow only the office IP or VPN IP, and install fail2ban to block brute-force attacks too. If it's in the cloud, restrict the source IP in the Security Group.
Junior: Do I need to restrict outbound traffic too?
Senior: It depends on the security level. Generally, allow only about HTTP/HTTPS and DNS. That way, even if the server gets hacked, you can prevent data from being leaked externally or connecting to a C2 server.

⚠️ Cautions

⚠️ Rule Order Matters

Firewall rules are applied sequentially from top to bottom. Since rules at the top are matched first, you must place specific rules first and general rules later. If you mistakenly put a block-all rule at the top, the subsequent rules are ignored.

⚠️ Don't Lock Yourself Out (Lock-out)

When configuring a firewall on a remote server, applying a rule that blocks your current SSH connection will leave you unable to access the server. Always secure the SSH rule first, and apply the rules after testing. In the cloud, console access is available, but on-premises requires physical access.

⚠️ A Firewall Alone Is Not Enough

A firewall cannot block malicious traffic (SQL Injection, XSS, etc.) that comes in through allowed ports. Web applications also need a WAF, code-level security, and regular vulnerability scans. A firewall is just one layer of security.

⚠️ Logging and Monitoring Are Essential

If you don't collect and analyze firewall logs, you cannot detect attack attempts. Send blocked traffic logs to a SIEM and set up alerts for abnormal patterns. Logs are also absolutely necessary for post-incident analysis.

📋 Real-World Cases

🔴 Capital One Data Breach (2019)

Data of more than 100 million customers was leaked due to a misconfigured AWS firewall (Security Group). The attacker accessed the metadata service through a misconfigured WAF, stole IAM credentials, and exfiltrated S3 bucket data.

💡 Lesson: Apply the principle of least privilege, conduct regular configuration audits, and SSRF defense is essential

🔴 MongoDB Ransomware Attack (2017)

Tens of thousands of MongoDB servers exposed to the internet with default settings were hit by ransomware attacks. Port 27017 was open to the entire world without a firewall, and authentication was also disabled.

💡 Lesson: Never expose database ports to the internet, change default ports, and authentication is essential

🔴 SSH Brute-Force Attack

SSH (port 22) exposed to the internet receives hundreds of login attempts per minute. If a weak password is used, it can be cracked within a few hours, and the machine is then incorporated into a botnet or abused for cryptocurrency mining.

💡 Lesson: Change the SSH port, use IP whitelisting, key-based authentication, and fail2ban

🧠 Comprehension Quiz

What is the key advantage of a stateful firewall?

It can inspect even the contents (payload) of packets
It tracks connection state and automatically allows response traffic
It blocks application attacks such as SQL Injection
It decrypts encrypted traffic and inspects it

🔗 Related Terms

📚 Learning Resources