Thiết Lập Firewall VPS: UFW và iptables
Firewall là lớp bảo vệ đầu tiên cho VPS của bạn. Không có firewall, mọi port trên server đều có thể bị tấn công. Hướng dẫn này giúp bạn cấu hình UFW (Uncomplicated Firewall) và iptables trên VPS offshore AnubizHost để kiểm soát chặt chẽ traffic vào và ra.
Need this done for your project?
We implement, you ship. Async, documented, done in days.
Cài Đặt và Cấu Hình UFW
UFW là interface đơn giản của iptables, dễ dùng hơn nhưng vẫn mạnh mẽ:
apt install -y ufw
# Đặt policy mặc định: từ chối tất cả incoming, cho phép tất cả outgoing
ufw default deny incoming
ufw default allow outgoing
# Cho phép SSH (thay 2222 bằng port SSH của bạn)
ufw allow 2222/tcp
# Cho phép HTTP và HTTPS
ufw allow 80/tcp
ufw allow 443/tcp
# Kích hoạt firewall
ufw enable
# Xem trạng thái
ufw status verboseQuan trọng: Luôn cho phép SSH trước khi enable UFW, nếu không bạn sẽ bị lock out khỏi server.
Quản Lý Rules UFW Nâng Cao
Các lệnh UFW hữu ích:
# Cho phép IP cụ thể truy cập port
ufw allow from 192.168.1.100 to any port 3306
# Chặn IP cụ thể
ufw deny from 203.0.113.0/24
# Rate limiting (chặn brute force)
ufw limit 2222/tcp
# Xóa rule
ufw status numbered
ufw delete 3
# Cho phép dải IP
ufw allow from 10.0.0.0/8
# Cho phép port range
ufw allow 8000:8080/tcpXem log firewall:
ufw logging on
tail -f /var/log/ufw.logCấu Hình iptables Nâng Cao
iptables cho phép kiểm soát chi tiết hơn UFW. Các rules phổ biến:
# Bảo vệ khỏi SYN flood
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT
iptables -A INPUT -p tcp --syn -j DROP
# Chặn ping (ICMP) từ bên ngoài
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
# Cho phép các kết nối đã được thiết lập
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Log và drop invalid packets
iptables -A INPUT -m state --state INVALID -j LOG --log-prefix "DROP INVALID: "
iptables -A INPUT -m state --state INVALID -j DROPLưu rules để tồn tại sau reboot:
apt install -y iptables-persistent
iptables-save > /etc/iptables/rules.v4Fail2ban Kết Hợp Firewall
Fail2ban tự động cập nhật iptables khi phát hiện tấn công:
apt install -y fail2ban
nano /etc/fail2ban/jail.local[DEFAULT]
backend = auto
bantime = 86400
findtime = 3600
maxretry = 5
banaction = ufw
[sshd]
enabled = true
port = 2222
maxretry = 3
[nginx-http-auth]
enabled = true
[nginx-limit-req]
enabled = true
filter = nginx-limit-req
logpath = /var/log/nginx/error.log
maxretry = 10systemctl restart fail2ban
fail2ban-client statusRelated Services
Why Anubiz Host
Ready to get started?
Skip the research. Tell us what you need, and we'll scope it, implement it, and hand it back — fully documented and production-ready.