별의 공부 블로그 🧑🏻‍💻
728x90
728x170

iptables

iptables

  • 패킷 필터링(Packet Filtering) 도구
  • 방화벽 구성이나 NAT(Network Translation Address)에 사용된다.
  • 5개의 테이블이 있다.
    • FILTER
      • iptables의 기본 테이블
      • 패킷 필터링을 담당한다.
    • NAT
      • Network Address Translation 의 약자
      • IP 주소를 변환시키는 역할을 수행한다.
      • 다음의 경우에 사용된다.
        • 1개의 공인 IP 주소로 여러 대 컴퓨터를 사용하고자 할 때
        • 1개의 공인 IP 주소로 여러 대 서버를 운영하고자 할 때
    • MANGLE
      • 패킷 데이터를 변경하는 특수 규칙을 적용하는 테이블
      • 성능 향상을 위해 TOS(Type of Service)를 설정한다.
    • RAW
      • 넷필터의 연결 추적 하위 시스템과 독립적으로 동작해야 하는 규칙을 설정하는 테이블
    • SECURITY 
      • 리눅스 보안 모듈인 SELinux에 의해 사용되는 MAC(Mandatory Access Control) 네트워크 관련 규칙이 적용된다.
      • SECMARK  CONNSECMARK에 의해 활성화된 규칙이 등록된다.
      • 현재 이 테이블은 FILTER 테이블 다음에 호출된다.
        • DAC(Discretionary Access Control) 규칙이 MAC 규칙보다 먼저 적용될 수 있다.

 

iptables의 테이블과 사슬

  • 커널 2.6.34 버전부터 nat 테이블에 INPUT 사슬이 추가되었다.
  • 패킷 필터링 및 방화벽 구성
    • 기본 테이블인 FILTER 3개의 사슬에 정책을 설정하면 된다.
  • 다수의 서버 관리를 할 때
    • filter 테이블 및 nat 테이블을 연동해서 사용한다.
    • NAT 테이블의 PREROUTING POSTROUTING 사슬
      • 커널 내부에서 IP 라우팅 계산 수행 전과 후 패킷 헤더를 수정하기 위해 사용한다.

FILTER 테이블의 사슬 및 기능

  • INPUT
    • 패킷 필터링 및 방화벽 관련 정책들을 설정하는 사슬
    • 실제적인 접근 통제를 담당하는 역할을 수행한다.
    • 커널 내부에서 라우팅 계산을 마친 후, 로컬 리눅스 시스템이 목적지인 패킷(로컬 소켓이 목적지인 패킷)에 적용된다.
  • OUTPUT
    • 다른 시스템으로의 접근을 차단할 때 사용하는 사슬
    • 리눅스 시스템 자체가 생성하는 패킷을 제어하는 사슬
  • FORWARD
    • 리눅스 시스템을 통과하는 패킷을 관리하는 사슬
    • 한 네트워크를 다른 네트워크와 연결하기 위해 iptables 방화벽을 사용
      • 두 네트워크 간의 패킷이 방화벽을 통과하는 경우에 사용된다.
    • 사설 IP를 사용하는 시스템의 접근 제어 정책을 설정할 때 사용된다.
      • NAT 테이블 기반으로, 하나의 공인 IP를 여러 대의 사설 IP를 사용하는 시스템들과 공유해서 사용할 경우

 

사용법

# iptables [-t table] action chain match [-j target]
  • 테이블(Table)의 기본 설정 : Filter
  • 다른 테이블을 지정할 때 -t 옵션을 사용함.
  • action
    • 사슬 지정, 설정, 제어할 때 사용함.
    • 주로 -N, -A와 같은 대문자 옵션을 사용함.
  • chain
    • 사슬(Chain)을 명시함.
      • 예) INPUT, OUTPUT
    • 대소문자를 구분함.
  • 마지막으로 실질적인 룰에 해당하는 매치(match)  타겟(target)을 지정하면 됨.
    • 매치 -d, -p와 같은 소문자 옵션을 사용하여 설정함.
    • 타겟 -j(--jump) 옵션을 사용하여 설정함.

 

주요 액션(action)

액션 설명
-N - 새로운(New) 사용자 정의 사슬을 만듦.
- (
--new-chain)
-X - 비어 있는 사슬을 제거함.
- 단, 기본 사슬은 제거할 수 없음.
- (--delete-chain)
-P - 사슬의 기본 정책을 설정함.
- (
--policy)
-L - 현재 사슬의 규칙을 나열함.
- (
--list)
-F - 사슬로부터 (모든) 규칙을 제거함.
- (
--flush)
-Z - 사슬 내의 모든 규칙들의 패킷 바이트 카운트를 0으로 만듦.
- (
--zero)
-A - 사슬에 새로운 규칙을 추가함.
- 해당 사슬의 맨 마지막 규칙으로 등록됨.
- (--append)
-I - 사슬의 규칙을 맨 첫 부분에 삽입함.
- 룰 넘버를 사용하여 특정 부분에 삽입할 수도 있음.
- (--insert)
-R - 사슬의 규칙을 교환함.
- (
--replace)
-D - 사슬의 규칙을 제거함.
- (
--delete)

 

주요 매치(match)

액션 설명
-s - 출발지 IP 주소나 네트워크와 매칭, 도메인, IP 주소, 넷마스크 값을 이용하여 표기
- (
--source--src)
-d - 목적지 IP 주소나 네트워크와 매칭, 도메인, IP 주소, 넷마스크 값을 이용하여 표기
- (
--destination--dst)
-p - 특정 프로토콜과 매칭
- TCP, UDP, ICMP 와 같은 이름 사용
- 대소문자는 구분하지 않음.
- 이 옵션을 사용하지 않으면 모든 프로토콜이 대상이 됨.
- (--protocol)
-i - 입력 인터페이스와 매칭
- (
--in-interface)
-o - 출력 인터페이스와 매칭
- (
--out-interface)
! - 아닌(NOT)의 의미로 사용
- 특정 매칭을 제외할 때 사용
-m - 좀 더 세밀하게 제어할 때 사용하는 매칭 옵션
- (
--match)
--state - 연결 상태와 매칭
- INVALID, ESTABLISHED, NEW, RELATED를 사용
--string 특정한 패턴과 매칭

 

기타 옵션

옵션 설명
-n - 다른 옵션과 같이 사용
- 출력 정보를 숫자값으로 표현
- (--numeric)
-v - 다른 옵션과 같이 사용
- 패킷, 바이트수 등을 추가하여 정보를 자세히 출력
- (--verbose)
--line-number - 정책 앞에 번호를 붙여 출력
- 삭제 삽입할 때 유용함.

 

주요 타겟(target) (-j, --jump)

옵션 설명
ACCEPT - 패킷을 허가하는 것
- 본래 라우팅대로 진행
DROP - 패킷을 거부하는 것
- 더 이상 어떤 처리도 수행하지 않고 버림.
LOG - 패킷을 syslog에 전달하여 기록
- 일반적으로 /var/log/messages에 저장
REJECT - 패킷을 버리고 동시에 적당한 응답 패킷을 전달함.
- 예)
 TCP 인 경우, TCP 재설정(Reset) 패킷
 UDP 인 경우, ICMP 포트 도달 불가(Port Unreachable) 메시지 전송
RETURN 호출 사슬 내에서 패킷 처리를 계속 진행

iptables의 설정 규칙 저장

  • 명령행에서 iptables로 설정한 정책들은 시스템이 재부팅되면 초기화된다.
  • 해당 정책을 지속적으로 반영하려면 설정 규칙을 저장해야 한다.
    • 관련 명령어를 사용한 저장 방법
    • 스크립트를 사용한 저장 방법
    • 직접 셸 스크립트를 작성하여 저장하는 방법

 

(1) 관련 명령어 사용

 iptables-save

  • iptables로 설정된 정책을 표준 출력(stdout) 에 출력해주는 명령
  • 출력 전환 리다이렉션 기호인 >와 조합해서 현재 설정된 정책을 파일로 저장할 수 있다.

 

사용법

# iptables-save [option]

 

주요 옵션

옵션 설명
-t - 특정 테이블에 설정된 정책만 출력한다.
- --table
-c - 출력되는 정책 앞부분에 패킷수바이트(Byte)를 표시해준다.
- --counters

 

사용 예

  • 현재 설정된 정책을 화면에 출력함.
# iptables-save

 

  • NAT 테이블에 설정된 정책만 출력함.
# iptables-save -t nat

 

  • 설정된 정책의 앞부분에 관련된 패킷수와 바이트(Byte)를 함께 출력함.
# iptables-save -c

 

  • 현재 설정된 정책을 firewall.sh로 저장함.
# iptables-save > firewall.sh

 

 iptables-restore

  • iptables의 정책 설정을 반영하는 명령
  • 입력 전환 리다이렉션 기호인 <를 이용해서 iptables-save로 저장된 파일을 불러들일 때 사용한다.

사용법

# iptables-restore [option]

 

주요 옵션

옵션 설명
-n - 현재 설정된 정책을 초기화하지 않고 추가하는 형식으로 저장한다.
- --noflush
-c - 출력되는 정책 앞부분에 패킷수 바이트(Byte)를 표시해준다.
- --counters

 

사용 예

  • firewall.sh에 저장된 정책을 불러들여서 반영함.
# iptables-restore < firewall.sh>

 

(2) 셸 스크립트 사용

  • 사용자가 직접 셸 스크립트를 만들어 저장한 후에 반영하는 방법
  • 다음의 문제점을 해소할 수 있다.
    • iptables-save 로 저장한 내용들이 직관적이지 못함.
    • 불러올 때는 iptables-restore 명령을 사용해야 하는 불편함
  • 해당 파일을 /etc/rc.d/rc.local 파일에 등록하면, 재부팅하더라도 계속적으로 반영시킬 수 있다.

 

작성 예

# vi /etc/firewall.sh
#!/bin/bash
/sbin/iptables -F             // filter table 초기화
/sbin/iptables -t nat -F      // nat table 초기화

# 접근 차단
/sbin/iptables -A INPUT -s 192.168.4.20 -j DROp

... (중략)

# NAT 설정
/sbin/iptables -t nat -A PREROUTING -p tcp -d 203.247.50.224 --dport 80 -j DNAT \ --to 192.168.1.2:80

... (중략)

 

실행 권한 부여 및 실행 예

  • 실행 권한 부여
# chmod 755 /etc/firewall.sh
  • /etc/firewall.sh 를 실행하여 방화벽 정책을 적용함.
# /etc/firewall.sh

 

부팅 시 적용 예

  • 재부팅 후에도 계속 반영되도록 설정
# echo "/etc/firewall.sh" >> /etc/rc.d/rc.local
# chmod a+x /etc/firewall.sh

 

iptables의 로그 기록

  • iptables 관련 로그를 남기려면 정책을 설정해야 한다.
    • -j LOG 로 선언하면 된다.
  • 로그 기록은 /var/log/messages 에 남긴다.
  • 특히 선언되는 위치가 중요하며, 보통 선언된 이후의 정책들만 로그로 남긴다.

 

사용 예

  • INPUT 사슬의 3번째에 등록되는데, 그 이후 관련 로그들만 /var/log/messages에 기록함.
# iptables -I INPUT 3 -j LOG

 

iptables에서 NAT 의 분류 및 설정

  • iptables에서 NAT 의 구분
    • SNAT(Source NAT) : 공인 IP 주소 1개로 다수의 컴퓨터가 인터넷 접속이 가능하도록 하는 경우
    • DNAT(Destination NAT) : 1개의 공인 IP 주소로 다수의 서버를 운영하는 경우

 

① SNAT(Source NAT)

  • 패킷의 소스 주소인 발신지를 변경한다는 의미이다.
  • 예) 방화벽 내부의 사설 IP 주소를 사용하는 192.168.1.2인 컴퓨터가 www.ihd.or.kr과 같은 웹 사이트를 방문하기 위해선느 공인 IP 주소가 필요하다.
    • SNAT 정책을 설정하여 방화벽을 통과할 때 공인 IP 주소가 부여되도록 설정한다.
  • SNAT는 라우팅 경로가 결정된 이후에 설정된다고 하여 NAT 테이블의 POSTROUTING 사슬에 정책 설정을 한다.

 

설정 예

  • eth0 장치를 통해 나가는 패킷에 203.247.50.3번 주소를 부여함.
# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 203.247.50.3

 

  • eth0 장치를 통해 나가는 패킷에 203.247.50.3번 부터 203.247.50.7번 사이의 주소를 부여함.
# iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to 203.247.50.3-203.247.50.7

 

  • etho0 장치를 통해 나가는 패킷에 대해 할당된 공인 IP 주소를 부여함.
  • MASQUERADE 는 유동 IP 주소를 사용하는 경우에 설정함.
# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

 

② DNAT(Destination NAT)

  • 패킷의 도착지 주소를 변경한다는 의미이다.
  • 패킷의 목적지 주소가 먼저 변경되고, 그 변경된 주소로 새로운 라우팅 경로를 찾는다.
  • 라우팅 이전 단계에서 작용된다고 하여 NAT 타입 PREROUTING 사슬에 정책을 설정한다.

 

설정 예

  • 목적지 주소 203.247.50.3의 80번 포트인 경우에 192.168.1.11의 80번 포트로 연결함.
# iptables -A PREROUTING -t nat -p tcp -d 203.247.50.3 --dport 80 -j DNAT --to 192.168.1.11:80

 

  • 목적지 주소 203.247.50.3의 25번 포트인 경우에 192.168.1.12의 25번 포트로 연결함.
# iptables -A PREROUTING -t nat -p tcp -d 203.247.50.3 --dport 25 -j DNAT --to 192.168.1.12:25

 

  • 목적지 주소 203.247.50.3의 53번 포트인 경우에 192.168.1.10의 53번 포트로 연결함.
# iptables -A PREROUTING -t nat -p udp -d 203.247.50.3 --dport 53 -j DNAT --to 192.168.1.10:53

 

(참고) 투명 프록시 설정 예

# iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j REDIRECT --to-port 3128

 

iptables를 이용한 공격 대비 설정 예

(1) ICMP Flooding 대비

  • ICMP 라는 이름의 사슬 생성
# iptables -N ICMP
  • ICMP 프로토콜 관련 패킷은 ICMP 사슬로 보냄.
# iptables -A INPUT -p icmp -j ICMP
  • icmp echo request 요청은 DROP 시킴.
# iptables -A ICMP -p icmp --icmp-type echo-request -j DROP

 

(2) UDP Flooding 대비

  • UDP 라는 이름의 사슬 생성
# iptables -N UDP
  • UDP 프로토콜 관련 패킷은 UDP 사슬로 보냄.
# iptables -A INPUT -p udp -j UDP
  • 같은 IP 주소 에서 1초에 10개 이상 UDP 패킷이 들어오면 DROP 시키는 정책을 UDP 사슬에 추가
# iptables -A UDP -p udp --dport 80 -m recent --update --seconds 1 --hitcount 10 -j DROP
  • UDP 사슬 로그에 "UDP FLOOD" 라고 기록함.
# iptables -A UDP -j LOG --log-prefix "UDP FLOOD"

 

(3) TCP Flooding 대비

  • 서버에서 제공되는 서비스들의 대부분이 TCP 프로토콜 기반으로 제공되므로, 운영 중인 서비스의 상황에 맞게 설정해야 한다.
  • 가장 많이 사용되는 정책
    • 초 당 허용되는 접속 개수 제한
    • IP 주소 당 허용되는 접속 개수 제한
    • 특정 IP 주소에서 오는 초 당 요구 수 제한

 

① 초 당 허용되는 접속 개수 제한

# iptables -A INPUT -p tcp --dport 80 --syn -m limit --limit 100/s -j ACCEPT

② IP 주소 당 허용되는 접속 개수 제한

# iptables -A INPUT -p tcp --dport 80 --syn -m connlimit --limit -above 30 -j DROP

③ 특정 IP 주소에서 오는 초 당 요구 수 제한

# iptables -A INPUT -p tcp --dport 80 -m recent --update --seconds 1 --hitcount 10 -j DROP

 

(4) SSH 무작위 대입 공격 대비

  • SSH라는 이름의 사슬 생성
# iptables -N SSH
  • 22번 포트로 접속하는 패킷은 SSH 사슬로 보냄.
# iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j SSH
  • 같은 IP 주소에서 60초 동안에 15번 이상 SSH 접속을 시도하면 DROP 시가는 정책을 SSH 사슬에 추가
# iptables -A SSH -p udp --dport 22 -m recent --update --seconds 60 --hitcount 15 -j DROP
  • SSH 사슬 로그에 "SSH Brute"라고 기록함.
# iptables -A SSH -j LOG --log-prefix "SSH Brute"

 

(참고) iptables를 이용한 제한

  • 시간에 따른 접속 횟수 제한
    • 60초 동안 5회로 제한
# iptables -A INPUT -p tcp --dport 22 -m recent --set --name ssh --rsource
# iptables -A INPUT -p tcp --dport 22 -m recent ! --rcheck --second 60 --hitcount 5 --name ssh --rsource -j ACCEPT
  • 분당 3번으로 접속 커넥션 수 제한
# iptables -A INPUT -p tcp --dport 22 --syn -m limit --limit-burst 3 -j ACCEPT
# iptables -A INPUT -p tcp --dport 22 --syn -j DROP

 

문제 해결 전략

  • iptables의 정책을 조건에 따라 변경하는 문제가 출제된다.
  • iptables의 사용법은 'man iptables'를 이용한다.
더보기
$ man iptables
IPTABLES(8)                                  iptables 1.4.21                                  IPTABLES(8)



NAME
       iptables/ip6tables — administration tool for IPv4/IPv6 packet filtering and NAT

SYNOPSIS
       iptables [-t table] {-A|-C|-D} chain rule-specification

       ip6tables [-t table] {-A|-C|-D} chain rule-specification

       iptables [-t table] -I chain [rulenum] rule-specification

       iptables [-t table] -R chain rulenum rule-specification

       iptables [-t table] -D chain rulenum

       iptables [-t table] -S [chain [rulenum]]

       iptables [-t table] {-F|-L|-Z} [chain [rulenum]] [options...]

       iptables [-t table] -N chain

       iptables [-t table] -X [chain]

       iptables [-t table] -P chain target

       iptables [-t table] -E old-chain-name new-chain-name

       rule-specification = [matches...] [target]

       match = -m matchname [per-match-options]

       target = -j targetname [per-target-options]

DESCRIPTION
       Iptables  and  ip6tables  are  used  to  set up, maintain, and inspect the tables of IPv4 and IPv6
       packet filter rules in the Linux kernel.  Several different tables may  be  defined.   Each  table
       contains a number of built-in chains and may also contain user-defined chains.

       Each  chain  is  a list of rules which can match a set of packets.  Each rule specifies what to do
       with a packet that matches.  This is called a `target', which may be  a  jump  to  a  user-defined
       chain in the same table.

TARGETS
       A  firewall  rule specifies criteria for a packet and a target.  If the packet does not match, the
       next rule in the chain is examined; if it does match, then the next rule is specified by the value
       of the target, which can be the name of a user-defined chain, one of the targets described in ipt‐
       ables-extensions(8), or one of the special values ACCEPT, DROP or RETURN.

       ACCEPT means to let the packet through.  DROP means to drop the packet on the floor.  RETURN means
       stop  traversing  this  chain and resume at the next rule in the previous (calling) chain.  If the
       end of a built-in chain is reached or a rule in a built-in chain with target  RETURN  is  matched,
       the target specified by the chain policy determines the fate of the packet.

TABLES
       There  are  currently five independent tables (which tables are present at any time depends on the
       kernel configuration options and which modules are present).

       -t, --table table
              This option specifies the packet matching table which the command should  operate  on.   If
              the kernel is configured with automatic module loading, an attempt will be made to load the
              appropriate module for that table if it is not already there.

              The tables are as follows:

              filter:
                  This is the default table (if no -t option is passed). It contains the built-in  chains
                  INPUT  (for  packets  destined  to  local  sockets),  FORWARD (for packets being routed
                  through the box), and OUTPUT (for locally-generated packets).

              nat:
                  This table is consulted when a packet that creates a new connection is encountered.  It
                  consists of three built-ins: PREROUTING (for altering packets as soon as they come in),
                  OUTPUT (for altering locally-generated packets before routing),  and  POSTROUTING  (for
                  altering  packets  as  they  are about to go out).  IPv6 NAT support is available since
                  kernel 3.7.

              mangle:
                  This table is used for specialized packet alteration.  Until kernel 2.4.17 it  had  two
                  built-in  chains:  PREROUTING (for altering incoming packets before routing) and OUTPUT
                  (for altering locally-generated packets before routing).  Since  kernel  2.4.18,  three
                  other  built-in  chains  are  also  supported:  INPUT  (for packets coming into the box
                  itself), FORWARD (for altering packets being routed through the box),  and  POSTROUTING
                  (for altering packets as they are about to go out).

              raw:
                  This table is used mainly for configuring exemptions from connection tracking in combi‐
                  nation with the NOTRACK target.  It registers at the netfilter hooks with higher prior‐
                  ity  and  is  thus called before ip_conntrack, or any other IP tables.  It provides the
                  following built-in chains: PREROUTING (for packets arriving via any network  interface)
                  OUTPUT (for packets generated by local processes)

              security:
                  This  table  is used for Mandatory Access Control (MAC) networking rules, such as those
                  enabled by the SECMARK and CONNSECMARK targets.  Mandatory  Access  Control  is  imple‐
                  mented  by  Linux Security Modules such as SELinux.  The security table is called after
                  the filter table, allowing any Discretionary Access Control (DAC) rules in  the  filter
                  table  to  take  effect  before  MAC rules.  This table provides the following built-in
                  chains: INPUT (for packets coming into the box itself), OUTPUT (for  altering  locally-
                  generated  packets  before  routing),  and  FORWARD  (for altering packets being routed
                  through the box).

OPTIONS
       The options that are recognized by iptables and ip6tables can be divided  into  several  different
       groups.

   COMMANDS
       These options specify the desired action to perform. Only one of them can be specified on the com‐
       mand line unless otherwise stated below. For long versions of the command and  option  names,  you
       need  to  use  only  enough  letters  to  ensure that iptables can differentiate it from all other
       options.

       -A, --append chain rule-specification
              Append one or more rules to the end of the selected chain.  When the source and/or destina‐
              tion names resolve to more than one address, a rule will be added for each possible address
              combination.

       -C, --check chain rule-specification
              Check whether a rule matching the specification does exist in the selected chain. This com‐
              mand  uses  the  same logic as -D to find a matching entry, but does not alter the existing
              iptables configuration and uses its exit code to indicate success or failure.

       -D, --delete chain rule-specification
       -D, --delete chain rulenum
              Delete one or more rules from the selected chain.  There are two versions of this  command:
              the  rule can be specified as a number in the chain (starting at 1 for the first rule) or a
              rule to match.

       -I, --insert chain [rulenum] rule-specification
              Insert one or more rules in the selected chain as the given rule number.  So, if  the  rule
              number  is  1,  the  rule or rules are inserted at the head of the chain.  This is also the
              default if no rule number is specified.

       -R, --replace chain rulenum rule-specification
              Replace a rule in the selected chain.  If the source and/or destination  names  resolve  to
              multiple addresses, the command will fail.  Rules are numbered starting at 1.

       -L, --list [chain]
              List all rules in the selected chain.  If no chain is selected, all chains are listed. Like
              every other iptables command, it applies to the specified table (filter is the default), so
              NAT rules get listed by
               iptables -t nat -n -L
              Please  note  that  it is often used with the -n option, in order to avoid long reverse DNS
              lookups.  It is legal to specify the -Z (zero) option as well, in which case  the  chain(s)
              will  be atomically listed and zeroed.  The exact output is affected by the other arguments
              given. The exact rules are suppressed until you use
               iptables -L -v

       -S, --list-rules [chain]
              Print all rules in the selected chain.  If no chain is selected,  all  chains  are  printed
              like  iptables-save.  Like  every other iptables command, it applies to the specified table
              (filter is the default).

       -F, --flush [chain]
              Flush the selected chain (all the chains in the table if none is given).  This  is  equiva‐
              lent to deleting all the rules one by one.

       -Z, --zero [chain [rulenum]]
              Zero the packet and byte counters in all chains, or only the given chain, or only the given
              rule in a chain. It is legal to specify the -L, --list (list) option as well,  to  see  the
              counters immediately before they are cleared. (See above.)

       -N, --new-chain chain
              Create  a  new  user-defined chain by the given name.  There must be no target of that name
              already.

       -X, --delete-chain [chain]
              Delete the optional user-defined chain specified.  There  must  be  no  references  to  the
              chain.   If  there are, you must delete or replace the referring rules before the chain can
              be deleted.  The chain must be empty, i.e. not contain any rules.  If no argument is given,
              it will attempt to delete every non-builtin chain in the table.

       -P, --policy chain target
              Set  the  policy  for the chain to the given target.  See the section TARGETS for the legal
              targets.  Only built-in (non-user-defined) chains can have policies, and  neither  built-in
              nor user-defined chains can be policy targets.

       -E, --rename-chain old-chain new-chain
              Rename  the  user  specified chain to the user supplied name.  This is cosmetic, and has no
              effect on the structure of the table.

       -h     Help.  Give a (currently very brief) description of the command syntax.

   PARAMETERS
       The following parameters make up a rule specification (as used in the add, delete, insert, replace
       and append commands).

       -4, --ipv4
              This  option has no effect in iptables and iptables-restore.  If a rule using the -4 option
              is inserted with (and only with) ip6tables-restore, it will be silently ignored. Any  other
              uses  will  throw  an error. This option allows to put both IPv4 and IPv6 rules in a single
              rule file for use with both iptables-restore and ip6tables-restore.

       -6, --ipv6
              If a rule using the -6 option is inserted with (and only with) iptables-restore, it will be
              silently  ignored.  Any other uses will throw an error. This option allows to put both IPv4
              and IPv6 rules in a single rule file for use  with  both  iptables-restore  and  ip6tables-
              restore.  This option has no effect in ip6tables and ip6tables-restore.

       [!] -p, --protocol protocol
              The  protocol  of the rule or of the packet to check.  The specified protocol can be one of
              tcp, udp, udplite, icmp, icmpv6,esp, ah, sctp, mh or the special keyword "all", or  it  can
              be  a  numeric  value,  representing one of these protocols or a different one.  A protocol
              name from /etc/protocols is also allowed.  A "!" argument before the protocol  inverts  the
              test.   The  number  zero  is equivalent to all. "all" will match with all protocols and is
              taken as default when this option is omitted.  Note  that,  in  ip6tables,  IPv6  extension
              headers  except  esp  are not allowed.  esp and ipv6-nonext can be used with Kernel version
              2.6.11 or later.  The number zero is equivalent to all, which means that  you  cannot  test
              the  protocol field for the value 0 directly. To match on a HBH header, even if it were the
              last, you cannot use -p 0, but always need -m hbh.

       [!] -s, --source address[/mask][,...]
              Source specification. Address can be either a  network  name,  a  hostname,  a  network  IP
              address  (with  /mask), or a plain IP address. Hostnames will be resolved once only, before
              the rule is submitted to the kernel.  Please note that specifying any name to  be  resolved
              with  a remote query such as DNS is a really bad idea.  The mask can be either an ipv4 net‐
              work mask (for iptables) or a plain number, specifying the number of 1's at the  left  side
              of  the  network mask.  Thus, an iptables mask of 24 is equivalent to 255.255.255.0.  A "!"
              argument before the address specification inverts the sense of the address. The flag  --src
              is  an alias for this option.  Multiple addresses can be specified, but this will expand to
              multiple rules (when adding with -A), or will cause multiple rules to be deleted (with -D).

       [!] -d, --destination address[/mask][,...]
              Destination specification.  See the description of the -s  (source)  flag  for  a  detailed
              description of the syntax.  The flag --dst is an alias for this option.

       -m, --match match
              Specifies  a match to use, that is, an extension module that tests for a specific property.
              The set of matches make up the condition under which a target is invoked. Matches are eval‐
              uated  first  to  last  as specified on the command line and work in short-circuit fashion,
              i.e. if one extension yields false, evaluation will stop.

       -j, --jump target
              This specifies the target of the rule; i.e., what to do if the packet matches it.  The tar‐
              get  can  be  a user-defined chain (other than the one this rule is in), one of the special
              builtin targets which decide the fate of the  packet  immediately,  or  an  extension  (see
              EXTENSIONS below).  If this option is omitted in a rule (and -g is not used), then matching
              the rule will have no effect on the packet's fate, but the counters on  the  rule  will  be
              incremented.

       -g, --goto chain
              This  specifies  that  the processing should continue in a user specified chain. Unlike the
              --jump option return will not continue processing in this chain but instead  in  the  chain
              that called us via --jump.

       [!] -i, --in-interface name
              Name  of an interface via which a packet was received (only for packets entering the INPUT,
              FORWARD and PREROUTING chains).  When the "!" argument is used before the  interface  name,
              the  sense  is  inverted.   If  the  interface name ends in a "+", then any interface which
              begins with this name will match.  If this option  is  omitted,  any  interface  name  will
              match.

       [!] -o, --out-interface name
              Name  of an interface via which a packet is going to be sent (for packets entering the FOR‐
              WARD, OUTPUT and POSTROUTING chains).  When the "!" argument is used before  the  interface
              name, the sense is inverted.  If the interface name ends in a "+", then any interface which
              begins with this name will match.  If this option  is  omitted,  any  interface  name  will
              match.

       [!] -f, --fragment
              This  means  that  the  rule only refers to second and further IPv4 fragments of fragmented
              packets.  Since there is no way to tell the source or destination ports of  such  a  packet
              (or  ICMP  type),  such a packet will not match any rules which specify them.  When the "!"
              argument precedes the "-f" flag, the rule will only match head fragments,  or  unfragmented
              packets. This option is IPv4 specific, it is not available in ip6tables.

       -c, --set-counters packets bytes
              This enables the administrator to initialize the packet and byte counters of a rule (during
              INSERT, APPEND, REPLACE operations).

   OTHER OPTIONS
       The following additional options can be specified:

       -v, --verbose
              Verbose output.  This option makes the list command  show  the  interface  name,  the  rule
              options  (if  any),  and the TOS masks.  The packet and byte counters are also listed, with
              the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000  multipliers  respectively
              (but  see the -x flag to change this).  For appending, insertion, deletion and replacement,
              this causes detailed information on the rule or rules to be printed. -v  may  be  specified
              multiple times to possibly emit more detailed debug statements.

       -w, --wait [seconds]
              Wait  for the xtables lock.  To prevent multiple instances of the program from running con‐
              currently, an attempt will be made to obtain an exclusive lock at launch.  By default,  the
              program  will  exit if the lock cannot be obtained.  This option will make the program wait
              (indefinitely or for optional seconds) until the exclusive lock can be obtained.

       -W, --wait-interval microseconds
              Interval to wait per each iteration.  When running latency sensitive applications,  waiting
              for  the  xtables  lock for extended durations may not be acceptable. This option will make
              each iteration take the amount of time specified. The default interval is  1  second.  This
              option only works with -w.

       -n, --numeric
              Numeric  output.   IP  addresses  and  port  numbers will be printed in numeric format.  By
              default, the program will try to display them as host names,  network  names,  or  services
              (whenever applicable).

       -x, --exact
              Expand  numbers.   Display the exact value of the packet and byte counters, instead of only
              the rounded number in K's (multiples of 1000) M's (multiples of 1000K) or G's (multiples of
              1000M).  This option is only relevant for the -L command.

       --line-numbers
              When  listing  rules, add line numbers to the beginning of each rule, corresponding to that
              rule's position in the chain.

       --modprobe=command
              When adding or inserting rules into a chain, use command  to  load  any  necessary  modules
              (targets, match extensions, etc).

MATCH AND TARGET EXTENSIONS
       iptables can use extended packet matching and target modules.  A list of these is available in the
       iptables-extensions(8) manpage.

DIAGNOSTICS
       Various error messages are printed to standard error.  The exit code is 0 for correct functioning.
       Errors  which  appear to be caused by invalid or abused command line parameters cause an exit code
       of 2, and other errors cause an exit code of 1.

BUGS
       Bugs?  What's this? ;-) Well, you might want to have a look at http://bugzilla.netfilter.org/

COMPATIBILITY WITH IPCHAINS
       This iptables is very similar to ipchains by Rusty Russell.   The  main  difference  is  that  the
       chains  INPUT and OUTPUT are only traversed for packets coming into the local host and originating
       from the local host respectively.  Hence every packet only passes through one of the three  chains
       (except  loopback  traffic,  which  involves both INPUT and OUTPUT chains); previously a forwarded
       packet would pass through all three.

       The other main difference is that -i refers to the input interface; -o refers to the output inter‐
       face, and both are available for packets entering the FORWARD chain.

       The  various forms of NAT have been separated out; iptables is a pure packet filter when using the
       default `filter' table, with optional extension modules.  This should simplify much of the  previ‐
       ous  confusion  over  the combination of IP masquerading and packet filtering seen previously.  So
       the following options are handled differently:
        -j MASQ
        -M -S
        -M -L
       There are several other changes in iptables.

SEE ALSO
       iptables-apply(8), iptables-save(8), iptables-restore(8), iptables-extensions(8),

       The packet-filtering-HOWTO details iptables usage for packet filtering, the NAT-HOWTO details NAT,
       the  netfilter-extensions-HOWTO  details the extensions that are not in the standard distribution,
       and the netfilter-hacking-HOWTO details the netfilter internals.
       See http://www.netfilter.org/.

AUTHORS
       Rusty Russell originally wrote iptables, in early consultation with Michael Neuling.

       Marc Boucher made Rusty abandon ipnatctl by lobbying for a generic packet selection  framework  in
       iptables,  then wrote the mangle table, the owner match, the mark stuff, and ran around doing cool
       stuff everywhere.

       James Morris wrote the TOS target, and tos match.

       Jozsef Kadlecsik wrote the REJECT target.

       Harald Welte wrote the ULOG and NFQUEUE target, the new libiptc, as well as  the  TTL,  DSCP,  ECN
       matches and targets.

       The  Netfilter  Core  Team is: Marc Boucher, Martin Josefsson, Yasuyuki Kozakai, Jozsef Kadlecsik,
       Patrick McHardy, James Morris, Pablo Neira Ayuso, Harald Welte and Rusty Russell.

       Man page originally written by Herve Eychenne <rv@wallfire.org>.

VERSION
       This manual page applies to iptables/ip6tables @PACKAGE_AND_VERSION@.



iptables 1.4.21                                                                               IPTABLES(8)

 

 

문제 유형

① 조건에 따라 보안을 위해 포워딩(forwarding) 정책을 변경하는 문제

  • 특정 사슬에 대한 기본 정책을 설정하려면 -P(--policy) 옵션을 적용한다.
  • 특정 사슬에 정책을 추가하려면 -A(--apend) 옵션을 사용한다.
  • 특정 인터페이스로 들어오는 패킷에 대한 설정을 위해서는 -i(--in-interface) 옵션을 사용한다.
  • 허가 및 거부 등을 지정할 때는 -j(--jump) 옵션을 사용한다.
# iptables (  -P  ) FORWARD DROP
# iptables (  -A  ) FORWARD (  -i  ) eth1 (  -j  ) ACCEPT
# iptables (  -F  ) INPUT
# iptables -A INPUT (  -i  ) lo -j ACCEPT
# iptables -A INPUT (  -p  ) tcp (  --dport  ) (  22:23  ) -j ACCEPT
# iptables -P INPUT (  DROP  )
# iptables (  -R INPUT 2  ) -s 192.168.12.22 -j DROP
# iptables (  -D INPUT 5  )
# iptables (  -I INPUT 2  )
# iptables (  -t nat -A POSTROUTING  ) -o eth0 (  -j SNAT  ) --to 203.247.5.13
# iptables (  -t nat -A PREROUTING  ) -p tcp -d 203.247.12.22 --dport 80 (  -j DNAT  ) --to 192.168.5.13:80

 

② 방화벽 설정 문제

  • 프로토콜을 지정하려면 -p(--protocol) 옵션을 사용한다.
# iptables -A INPUT (  -p icmp --icmp-type echo-request  ) -s 192.168.10.1 -d 0/0 -j ACCEPT
# iptables -A INPUT (  -p icmp --icmp-type echo-reply  ) -s 0/0 -d 192.168.10.1 -j ACCEPT
# iptables -A INPUT (  -p icmp --icmp-type destination-unreachable  ) -s 0/0 -d 192.168.10.1 -j ACCEPT
  • ICMP type 관련 항목값은 'iptables -p icmp -h' 명령으로 확인한다.
더보기
# iptables -p icmp -h
iptables v1.4.21

Usage: iptables -[ACD] chain rule-specification [options]
       iptables -I chain [rulenum] rule-specification [options]
       iptables -R chain rulenum rule-specification [options]
       iptables -D chain rulenum [options]
       iptables -[LS] [chain [rulenum]] [options]
       iptables -[FZ] [chain] [options]
       iptables -[NX] chain
       iptables -E old-chain-name new-chain-name
       iptables -P chain target [options]
       iptables -h (print this help information)

Commands:
Either long or short options are allowed.
  --append  -A chain		Append to chain
  --check   -C chain		Check for the existence of a rule
  --delete  -D chain		Delete matching rule from chain
  --delete  -D chain rulenum
				Delete rule rulenum (1 = first) from chain
  --insert  -I chain [rulenum]
				Insert in chain as rulenum (default 1=first)
  --replace -R chain rulenum
				Replace rule rulenum (1 = first) in chain
  --list    -L [chain [rulenum]]
				List the rules in a chain or all chains
  --list-rules -S [chain [rulenum]]
				Print the rules in a chain or all chains
  --flush   -F [chain]		Delete all rules in  chain or all chains
  --zero    -Z [chain [rulenum]]
				Zero counters in chain or all chains
  --new     -N chain		Create a new user-defined chain
  --delete-chain
            -X [chain]		Delete a user-defined chain
  --policy  -P chain target
				Change policy on chain to target
  --rename-chain
            -E old-chain new-chain
				Change chain name, (moving any references)
Options:
    --ipv4	-4		Nothing (line is ignored by ip6tables-restore)
    --ipv6	-6		Error (line is ignored by iptables-restore)
[!] --protocol	-p proto	protocol: by number or name, eg. `tcp'
[!] --source	-s address[/mask][...]
				source specification
[!] --destination -d address[/mask][...]
				destination specification
[!] --in-interface -i input name[+]
				network interface name ([+] for wildcard)
 --jump	-j target
				target for rule (may load target extension)
  --goto      -g chain
                              jump to chain with no return
  --match	-m match
				extended match (may load extension)
  --numeric	-n		numeric output of addresses and ports
[!] --out-interface -o output name[+]
				network interface name ([+] for wildcard)
  --table	-t table	table to manipulate (default: `filter')
  --verbose	-v		verbose mode
  --wait	-w [seconds]	maximum wait to acquire xtables lock before give up
  --wait-interval -W [usecs]	wait time to try to acquire xtables lock
				default is 1 second
  --line-numbers		print line numbers when listing
  --exact	-x		expand numbers (display exact values)
[!] --fragment	-f		match second or further fragments only
  --modprobe=<command>		try to insert modules using this command
  --set-counters PKTS BYTES	set the counter during insert/append
[!] --version	-V		print package version.

icmp match options:
[!] --icmp-type typename	match icmp type
[!] --icmp-type type[/code]	(or numeric type or type/code)
Valid ICMP Types:
any
echo-reply (pong)
destination-unreachable
   network-unreachable
   host-unreachable
   protocol-unreachable
   port-unreachable
   fragmentation-needed
   source-route-failed
   network-unknown
   host-unknown
   network-prohibited
   host-prohibited
   TOS-network-unreachable
   TOS-host-unreachable
   communication-prohibited
   host-precedence-violation
   precedence-cutoff
source-quench
redirect
   network-redirect
   host-redirect
   TOS-network-redirect
   TOS-host-redirect
echo-request (ping)
router-advertisement
router-solicitation
time-exceeded (ttl-exceeded)
   ttl-zero-during-transit
   ttl-zero-during-reassembly
parameter-problem
   ip-header-bad
   required-option-missing
timestamp-request
timestamp-reply
address-mask-request
address-mask-reply

 

TIP) man iptables 명령어를 입력하면 iptables 의 사용법을 확인할 수 있다.

 

③ 현재 설정된 iptables 정책을 저장하는 과정에 대한 문제

가. 관련 명령어를 사용한 정책 저장 및 반영
# (  iptables-save  ) > firewall.sh
# (  iptables-restore  ) < firewall.sh

나. 관련 스크립트를 이용한 저장과 설정된 정책 확인
# service iptables (  save  )
# cat (  /etc/sysconfig/iptables  )

 

728x90
그리드형(광고전용)
⚠️AdBlock이 감지되었습니다. 원할한 페이지 표시를 위해 AdBlock을 꺼주세요.⚠️
starrykss
starrykss
별의 공부 블로그 🧑🏻‍💻


📖 Contents 📖