👉🏻 리눅스에서 방화벽은 iptables를 사용합니다.
In Linux, the firewall uses iptables.
👉🏻 우분투24.04에서는 nftables를 기본으로 사용합니다. 물론 iptables를 사용 할 수 있습니다.
Ubuntu 24.04 uses nftables by default. You can of course use iptables.
👉🏻 많은 분들이 도커를 사용하고 있고 도커가 컨테이너 사용시 iptables를 수정합니다.
Many people use Docker, and Docker modifies iptables when using containers.
👉🏻 도커에서 nftables는 실험적인 기능만 제공하고 정식으로 사용되고 있지 않습니다.
In Docker, nftables provides only experimental features and is not officially used.
👉🏻 그래서 일단 iptables에 대해서 공부를 하고 나중에 다시 nftables에 대해서 공부하시면 될것 같습니다.
So, I think it would be good to study iptables first and then study nftables later.
👉🏻 UFW는 iptables나 nftables의 프론터 엔드 개념입니다. 쉽게 방화벽을 설정해 주는 도구라고 생각하시면 됩니다.
UFW is a front-end concept for iptables and nftables. Think of it as a tool that makes it easy to configure a firewall.
👉🏻 UFW가 잘되는 경우도 있지만 도커를 사용하는 경우 UFW에서 차단해도 포트가 외부에서 접속이 가능하다던가 포트가 열리지 않는다던가 하는 보안이슈가 있습니다.
Although UFW may work well in some cases, when using Docker, there are security issues such as ports being accessible from the outside or ports not being opened even when blocked by UFW.
👉🏻 그래서 UFW가 사용가능하면 UFW를 사용하시고 만약에 문제가 발생하시면 UFW는 disable하고 iptables쓰시면 될것 같습니다
So, if UFW is available, use UFW. If you encounter any problems, disable UFW and use iptables.
👉🏻 도커의 포트 외부접속과 관련된 보안 이슈에 대해서 제가 대응하는 방법은 따로 소개하겠습니다.
I will separately introduce how I deal with security issues related to external access to Docker ports.
👉🏻 아래는 가장 많이 사용되는 iptables사용 방법입니다.
Below are the most commonly used iptables usage methods.
✔️ iptables persistant설치(설치되어 있지 않은 경우)
Install iptables persistant (if not already installed)
— iptables는 셋팅 후 서버가 재부팅되면 초기화 되기 때문에 iptables persistant를 통해서 설정을 저장 해야 합니다.
Since iptables is initialized when the server is rebooted after setting, you must save the settings through iptables persistant.
sudo apt update
sudo apt install iptables-persistent
✔️ 방화벽 설정보기
View firewall settings
sudo iptables -L INPUT --line-numbers -v -n
| –옵션별 상세 의미 / Detailed meaning of each option -L INPUT (List): INPUT 체인에 등록된 규칙들만 리스트 형태로 보여달라는 뜻입니다. (지정하지 않으면 모든 체인 출력) This means that only rules registered in the INPUT chain will be displayed in list form. (If not specified, all chains will be displayed.) –line-numbers: 각 규칙의 맨 앞에 행 번호(1, 2, 3…)를 붙여줍니다. 나중에 특정 규칙을 삭제(-D)하거나 특정 위치에 삽입(-I)할 때 이 번호가 꼭 필요합니다. Add a line number (1, 2, 3…) to the beginning of each rule. This number is essential when you later delete (-D) or insert (-I) a specific rule at a specific location. -v (Verbose): ‘상세히’ 출력하라는 옵션입니다. 단순히 규칙만 보여주는 게 아니라, 해당 규칙에 걸려 통과하거나 차단된 패킷 수(pkts)와 데이터 양(bytes)까지 보여줍니다. This option displays “detailed” output. It doesn’t simply display the rule, but also shows the number of packets (pkts) and the amount of data (bytes) that passed or were blocked by the rule. -n (Numeric): 주소와 포트를 이름(localhost, http 등)이 아닌 숫자(127.0.0.1, 80 등)로 표시합니다. DNS 조회를 생략하기 때문에 결과가 훨씬 빠르게 출력됩니다. Display addresses and ports as numbers (e.g., 127.0.0.1, 80) rather than names (e.g., localhost, http). This skips the DNS lookup, resulting in much faster results. |
✔️ 방화벽 전체 설정 보기
# 설정된 모든 규칙을 명령어 형태로 출력 (가장 명확함)
# Print all set rules in command form (most clear)
sudo iptables -S
# 또는 or
# 모든 체인(INPUT, FORWARD, OUTPUT 등)을 표 형태로 출력
# Print all chains (INPUT, FORWARD, OUTPUT, etc.) in table format
sudo iptables -L -v -n --line-numbers
✔️ iptables에서 기본설정하기 전에 먼저 설정해야 하는 것
What you need to set first before setting the default settings in iptables
— iptables는 순서가 매우 중요하므로 1번과2번에 아래의 규칙을 추가합니다.
Since the order is very important in iptables, add the rules below to 1 and 2.
— 지금 접속된 연결허용 및 로컬호스트 접속 허용설정입니다.
These are the settings to allow currently connected connections and allow local host access.
# 이미 연결된 상태이거나 관련된 패킷은 무조건 통과 (DNS 응답, 패키지 업데이트 등)
# Packets that are already connected or related are unconditionally passed (DNS responses, package updates, etc.)
sudo iptables -I INPUT 1 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# 로컬호스트(127.0.0.1) 통신 허용 (이게 없으면 내부 DB 연결 등이 끊길 수 있음)
# Allow communication with localhost (127.0.0.1) (without this, internal DB connection, etc. may be disconnected)
sudo iptables -I INPUT 2 -i lo -j ACCEPT
✔️ 서비스 포트 오픈
Service port open
— ssh,http,https설정입니다.
These are ssh, http, and https settings.
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
— 우선순위를 지정해서 설정하기(7번에 규칙입력,나머지는 번호가 밀림)
Set by specifying priority (enter rule in number 7, the rest are numbered backwards)
sudo iptables -I INPUT 7 -p tcp --dport 3000 -j ACCEPT
✔️ 규칙 삭제 / Delete rule
sudo iptables -D [체인명 / Chain name] [규칙번호 / rule number]
sudo iptables -D INPUT 7
✔️ iptables 기본정책을 차단(Drop)으로설정(우선 순위에 적용 받지 않음)
Set the iptables default policy to Block (Drop) (not subject to priority)
— iptables는 기존정책을 모두 허용설정되어있습니다.
iptables is set to allow all existing policies.
— 위와 같이 허용설정을하고 다음과 같이 기본설정을 차단으로 설정하면 다른 포트는 모두 막힙니다.
If you set the allow setting as above and block the default setting as below, all other ports will be blocked.
sudo iptables -P INPUT DROP
✔️ 설정 결과 / Setting result
[ubuntu@...]$ sudo iptables -L INPUT --line-numbers -n -v
Chain INPUT (policy DROP 60 packets, 3344 bytes)
num pkts bytes target prot opt in out source destination
1 2708 236K ACCEPT 0 -- * * 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED
2 8 844 ACCEPT 0 -- lo * 0.0.0.0/0 0.0.0.0/0
3 140K 18M ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3306
4 1008K 137M ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
5 2728 130K ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:443
6 350 17148 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8000
7 847 39538 ACCEPT 6 -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:3000
✔️ 규칙저장 / save rule
sudo netfilter-persistent save
⭐️ 특정 아이피 주소 차단하기
Block specific IP addresses
iptables -A INPUT -s 192.168.1.100 -j DROP
👉🏻 iptables 설정 형식
iptables configuration format
✔️ 기본 개념 / basic concepts
–iptables는 트래픽이 이동하는 경로에 따라 체인(Chain)이라는 단계로 구분합니다.
iptables divides traffic into steps called chains based on the path it takes.
| INPUT: 서버로 들어오는 패킷 (가장 많이 설정함) Packets coming into the server (most commonly set) FORWARD: 서버를 거쳐 다른 곳으로 가는 패킷 (라우터 역할 시 사용) Packets that pass through the server to go somewhere else (used when acting as a router) OUTPUT: 서버에서 나가는 패킷 packets leaving the server |
✔️ 기본 명령어 구조 / Basic command structure
–명령어는 보통 다음과 같은 형식을 따릅니다. iptables [테이블] [동작] [체인] [매칭 조건] [타겟]
Commands usually follow this format: iptables [table] [action] [chain] [matching condition] [target]
| 동작: -A(추가), -D(삭제), -L(리스트 확인) Actions: -A (add), -D (delete), -L (check list) 매칭 조건: -p(프로토콜), –dport(포트 번호), -s(출발지 IP) Matching conditions: -p (protocol), –dport (port number), -s (source IP) 타겟: -j ACCEPT(허용), -j DROP(차단), -j REJECT(거절 후 응답) Target: -j ACCEPT, -j DROP, -j REJECT |
✔️ 옵션 / Option
1. 주요 테이블 (-t 옵션) / Main table (-t option)
| 생략할 경우 기본값은 filter 테이블입니다. If omitted, the default is the filter table. filter: 기본 테이블. 패킷 필터링(허용/차단) 담당. Basic table. Responsible for packet filtering (allow/block). nat: 주소 변환(SNAT/DNAT) 담당. 포트 포워딩 등에 사용. Responsible for address translation (SNAT/DNAT). Used for port forwarding, etc. mangle: 패킷의 헤더 정보(TOS, TTL 등)를 수정. Modify the packet header information (TOS, TTL, etc.). raw: 연결 추적(Connection Tracking) 제외 설정. Exclude Connection Tracking settings. |
2.기본 액션 옵션 / Commands
— 체인(Chain)을 관리하거나 규칙을 추가/삭제할 때 사용합니다.
Used to manage chains or add/delete rules.
| 옵션 / optioon | 설명 / description |
| -A (–append) | 체인의 맨 끝에 새로운 규칙을 추가합니다. Add a new rule at the very end of the chain. |
| -I (–insert) | 체인의 특정 번호(기본값 1)에 규칙을 삽입합니다. Inserts a rule at a specific number in the chain (default 1). |
| -D (–delete) | 특정 규칙을 삭제합니다 (번호나 내용 지정). Deletes a specific rule (specify number or content). |
| -R (–replace) | 특정 번호의 규칙을 교체합니다. Replaces a rule with a specific number. |
| -L (–list) | 현재 설정된 모든 규칙을 출력합니다. Prints all currently set rules. |
| -F (–flush) | 해당 체인의 모든 규칙을 삭제합니다. Delete all rules in that chain. |
| -P (–policy) | 기본 정책을 설정합니다 (예: INPUT을 DROP으로 설정). Set the default policy (e.g. set INPUT to DROP). |
| -N (–new-chain) | 사용자 정의 체인을 생성합니다. Create a custom chain. |
| -X (–delete-chain) | 비어 있는 사용자 정의 체인을 삭제합니다. Delete an empty custom chain. |
| -Z (–zero) | 모든 규칙의 패킷/바이트 카운터를 0으로 초기화합니다. Resets the packet/byte counters of all rules to 0. |
3.매칭 및 조건 옵션 / Parameters
어떤 패킷에 규칙을 적용할지 상세히 설정합니다.
Specify in detail which packets the rule will be applied to.
| 옵션 / option | 설명 / description | 예시 / example |
| -p (–protocol) | 특정 프로토콜 지정 Specify a specific protocol | -p tcp, -p udp, -p icmp |
| -s (–source) | 출발지 주소 (IP 또는 네트워크) Source address (IP or network) | -s 192.168.1.0/24 |
| -d (–destination) | 목적지 주소 destination address | -d 8.8.8.8 |
| -i (–in-interface) | 패킷이 들어오는 인터페이스 Interface where packets come in | -i eth0 |
| -o (–out-interface) | 패킷이 나가는 인터페이스 Interface where packets go out | -o wlan0 |
| –sport | 출발지 포트 (명시적 프로토콜 필요) Source port (explicit protocol required) | --sport 80 |
| –dport | 목적지 포트 (명시적 프로토콜 필요) Destination port (explicit protocol required) | --dport 22 |
| ! (not) | 조건을 반전시킴 Invert the conditions | -s ! 127.0.0.1 (로컬 제외 / Except local) |
4.타겟 옵션 (-j Target)
조건에 맞는 패킷을 어떻게 처리할지 결정합니다.
| ACCEPT: 패킷을 허용합니다. Allow packets. DROP: 패킷을 차단합니다 (응답 없음). Block packets (no response). REJECT: 패킷을 차단하고 거부 메시지를 보냅니다. Blocks packets and sends reject messages. LOG: 패킷 정보를 커널 로그( /var/log/messages)에 기록합니다.Logs packet information to the kernel log (/var/log/messages). SNAT / DNAT: 출발지/목적지 주소를 변환합니다 (nat 테이블 전용). Converts source/destination addresses (nat table only). MASQUERADE: 유동 IP 환경에서 SNAT를 적용합니다. Apply SNAT in a dynamic IP environment. RETURN: 현재 체인에서의 처리를 중단하고 이전 체인으로 돌아갑니다. Stops processing on the current chain and returns to the previous chain. |
5.자주 사용하는 기타 옵션
| -v (–verbose): 상세한 정보를 출력합니다 (인터페이스, 카운터 등). Print detailed information (interfaces, counters, etc.). -n (–numeric): IP 주소와 포트 번호를 이름이 아닌 숫자로 표시합니다 (속도가 빠름). Display IP addresses and port numbers as numbers, not names (faster). –line-numbers: 규칙 앞에 번호를 함께 표시합니다 (삭제 시 유용). Number rules before them (useful for deleting). |
✔️ 기타 / etc.
— 이외에도 많은 기능을 가지고 있습니다.
It has many other features as well.
— ddos방어를 위해 ping(ICMP) 차단이나 포트 포워딩 그리고 패킷 발생건수 제한을 하기도 합니다.
To protect against DDoS, ping (ICMP) blocking, port forwarding, and packet generation limiting are also used.
— oci같은 클라우드 서버의 경우는 리눅스 os레벨 이전에 클라우드 자체 방화벽이 있어서 ping같은 차단설정은 이미 되어 있습니다.
In the case of cloud servers such as OCI, there is a cloud firewall before the Linux OS level, so blocking settings such as ping are already in place.
👉🏻 결론 / conclusion
✔️ iptables를 사용하게 되면 위의 설정이 가장 많이 사용됩니다.
If you use iptables, the above settings are the most commonly used.
✔️ 여러가지 보안 설정에 관해서는 나중에 따로 포스팅하겠습니다.
I will post separately about various security settings later.