블로그 이미지
22Hz 22Hz

카테고리

분류 전체보기 (109)
모의해킹 침해대응 전문가 과정 (99)
리눅스 설정 (10)
Total
Today
Yesterday

달력

« » 2025.7
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

공지사항

태그목록

최근에 올라온 글


1

iptables 기본 구조

 

iptables넷필터(netfilter) 프로젝트에서 개발했으며 광범위한

프로토콜 상태 추적,

패킷 애플리케이션 계층검사,

속도 제한,

필터링 정책을

명시하기 위한 강력한 매커니즘을 제공한다.

 

 

리눅스 2.4 커널 버전이상에서 사용하는 서버 방화벽(iptables)이다.

리눅스 2.2 커널 버전에서는 ipchains 사용하였는데 구조와 사용하는 방법은 비슷하다.kernel 2.2(ipchains) -> kernel 2.4(iptables) -> kernel 2.6(iptables)# uname -a Linux linux249.example.com 2.6.18-164.el5 #1 SMP Thu Sep 3 03:33:56 EDT 2009 i686 athlon i386 GNU/Linux

(주의) iptables/ipchains 동시에 사용하면 안된다.

 


라우팅 결정패킷의 목적지 주소가 로컬 시스템에 해당되면, 패킷은 로컬 프로세스에 의해 처리되도록 라우팅된다. 패킷이 다른 시스템에 전달될 때 커널에서 패킷 포워딩이 활성화되어 있으면(/proc/sys/net/ipv4/ip_forward), 패킷은 라우팅 테이블 정보에 따라 목적지로 전달된다.

패킷 필터링 지점패킷 필터링은 커널 안의 다섯 개의 필터링 지점에서 발생한다. 필터링 지점 이름은 대소문자를 구별하며 모두 대문자로 이루어진 것에 주의하여야 한다.

 

 

PREROUTING처음 전달 받은 패킷을 처리하는 필터링 지점(nat)

 

FORWARD

로컬 시스템을 통해 경유되는 패킷을 처리하는 필터링 지점(filter)

 

INPUT

라우팅 결정 후에 로컬 시스템으로 향하는 패킷을 처리하는 필터링 지점(filter)

 

OUTPUT

보내기 프로세스를 떠난 패킷을 POSTROUTING 전에 처리하는 필터링 지점(nat/filter)

 

POSTROUTING

시스템을 떠나기 바로 전의 패킷을 처리하는 필터링 지점(nat)

[그림] iptables Packet Filtering Process

 

 

 

 

 

[참고] iptables 관련 용어 정리

테이블(tables)

우선 iptables에는 테이블이라는 광범위한 범주가 있는데 이 테이블은

filter,

nat,

mangle,

raw

같은 4개의 테이블로 구성되며 이중에서 우리에게 필요한 것은 필터링 규칙을 세우는 filter 테이블이다.

 

 

체인(chain)

iptables에는 filter 테이블에 미리 정의된 세가지의 체인이 존재하는데 이는

INPUT,

OUTPUT,

FORWARD

이다. 이 체인들은 어떠한 네트워크 트래픽(IP 패킷)에 대하여 정해진 규칙들을 수행한다.

가령 들어오는 패킷(INPUT)에 대하여 허용(ACCEPT)할 것인지, 거부(REJECT)할 것인지, 버릴(DROP)것인지를 결정한다.

 

INPUT : 호스트 컴퓨터를 향한 모든 패킷

OUTPUT : 호스트 컴퓨터에서 발생하는 모든 패킷

FORWARD: 호스트 컴퓨터가 목적지가 아닌 모든 패킷, 즉 라우터로 사용되는 호스트 컴퓨터를 통과하는 패킷

 

 

 

 

 

 

 

 

 

 

(1) iptables 개요

 

iptables 논리적인 3개의 사슬(chains)으로 구성되어 있고, 각각 INPUT, OUTPUT, FORWARD 라는 이름을 가지고 있다.

또한 관리자가 정의하여 새로운 사슬도 생성할 수 있다. (기본 사슬의 이름은 대문자이다.)

 

 

# iptables -L (# iptables -L -t filter)

Chain INPUT (policy ACCEPT)

target prot opt source destination

 

Chain FORWARD (policy ACCEPT)

target prot opt source destination

 

Chain OUTPUT (policy ACCEPT)

target prot opt source destination

-> 방화벽 설정은 꺼져 있는 상태이다.

 

 

 

(2) iptables 구성

 

INPUT 사슬 : 리눅스 박스를 향해 들어오는 패킷들이 거치는 체인

FORWARD 사슬 : 리눅스 박스를 거쳐 OUTPUT 체인을 향하는 체인

OUTPUT 사슬 : 리눅스 박스를 나가는 패킷들이 들어가는 체인




2

iptables 정책

 

 

(1) iptables 정책 개요

 

방화벽 = 패킷 필터링 + NAT/PAT + (VPN + QoS + ....)

 

패킷 필터링 규칙(Packet Filtering Rule)() 들어 오는 패킷을 순서대로 정의된 규칙(Rule)들을 점검하고 처음 일치되는 규칙을 적용한다.() 하나의 필터링 규칙에 여러가지 조건으로 지정하면 모든 조건에 일치해야 규칙 적용이 된다.() 내장된 체인(Chain) 안을 모두 검사했지만 일치 항목이 없을 경우에는 체인의 기본 정책이 적용된다. "사용자 정의 체인"의 경우 일치 항목이 없을 경우에는 제어권은 "사용자 정의 체인"이 호출되었던 체인으 로 다시 돌아간다.

 

패킷에 대한 동작은 위에서 부터 차례로 각 규칙에 대해 검사하고, 그 규칙과 일치하는 패킷에 대하여 타겟에 지정한 ACCEPT,DROP등을 수행한다.

 

규칙이 일치하고 작업이 수행되면, 그 패킷은 해당 규칙의 결과에 따리 처리하고 체인에서 추가 규칙을 무시한다.

패킷이 체인의 모든 규칙과 매치하지 않아 규칙의 바닥에 도달하면 정해진 기본정책(policy)이 수행된다.

기본 정책은 policy ACCEPT , policy DROP 으로 설정할 수 있다.

 

일반적으로 기본정책은 모든 패킷에 대해 DROP을 설정하고 특별히 지정된 포트와 IP주소등에 대해 ACCEPT를 수행하게 만든다.

 

 

규칙 타겟(Rule Target) : iptables는 패킷이 규칙과 일치할 때 동작을 취하는 타겟을 지원한다.

내장 타겟

ACCEPT : 패킷을 허용하는 옵션이다. (Allow)

DROP : 패킷을 완전히 무시한다. (Deny)

확장 타겟

REJECT : 패킷을 허용하지 않는다는 메세지를 보내면서 거부한다. 사슬 전체 정책 설정(-P)에서는 사용할 수 없. 패킷을 버리고 이와 동시에 적절한 응답 패킷을 전송한다.

LOG : 시스템 로그 커널 장치로 연결한다. 패킷을 syslog에 기록한다.

사용자 정의 체인 : 사용자가 정의하는 체인이다.

 

 

REJECT는 서비스에 접속하려는 사용자의 액세스를 거부하고 connection refused라는 오류 메시지를 보여주는 반면 DROP은 말 그대로 telnet 사용자에게 어떠한 경고 메시지도 보여주지 않은 채 패킷을 드롭한다.

관리자의 재량껏 이러한 규칙을 사용할 수 있지만 사용자가 혼란스러워하며 계속해서 접속을 시도하는 것을 방지하려면 REJECT를 사용하는 것이 좋다.

 

 


 

[그림] 패킷 허용/차단

 



연결 추적(Connection Tracking)

iptables는 연결 추적(connection tracking)이라는 방법을 사용하여 내부 네트워크 상 서비스 연결 상태에 따라서 그 연결을 감시하고 제한할 수 있게 해준다.

연결 추적 방식은 연결 상태를 표에 저장하기 때문에, 다음과 같은 연결 상태에 따라서 시스템 관리자가 연결을 허용하거나 거부할 수 있다

 

NEW 새로운 연결을 요청하는 패킷, , HTTP 요청

ESTABLISHED 기존 연결의 일부인 패킷

RELATED 기존 연결에 속하지만 새로운 연결을 요청하는 패킷, 예를 들면 접속 포트가 20인 수동 FTP 경우 전송 포트는 사용되지 않은 1024 이상의 어느 포트라도 사용 가능하다.

INVALID 연결 추적표에서 어디 연결에도 속하지 않은 패킷

 

상태에 기반(stateful)iptables 연결 추적 기능은 어느 네트워크 프로토콜에서나 사용 가능하다.

UDP와 같이 상태를 저장하지 않는 (stateless) 프로토콜에서도 사용할 수 있다.

 

 

 


 

3

iptables 명령어

 

iptables 설정- 전체 사슬(chains)에 대한 설정(대문자 옵션 사용: -P, -L, -N, -X )- 각 사슬(chains)에 대한 규칙(Rules)을 설정(소문자 옵션 사용: -s, -d, -p )

 

(명령어 형식)

# iptables [-t <table-name>] <command> <chain-name> <parameter-1><option-1> <parameter-n><option-n>

 

 

(1) 전체 사슬에 대한 작동(명령어)

옵 션

설 명

-N

-N, --new-chain chain

Create a new user-defined chain by the given name. There must

be no target of that name already.

 

새로운 사슬을 만든다.# iptables -N NEW # iptables -L

-X

-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.

 

비어있는 사슬을 제거한다. 3개의 기본 사슬(INPUT, OUTPUT, FORWARD)은 제거할 수 없다.# iptables -X NEW # iptables -L

-P

-P, --policy chain target

Set the policy for the chain to the given target. See the sec-

tion 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.

 

사슬의 정책을 설정한다. (EX: ACCEPT, DROP)# iptables -P INPUT DROP ; iptables -L # iptables -P INPUT ACCEPT ; iptables -L

-L

-L, --list [chain]

List all rules in the selected chain. If no chain is selected,

all chains are listed. As 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

 

현재 사슬의 규칙을 나열한다.# iptables -L # iptables -L -v (# iptables -vL, # service iptables status)# iptables -L INPUT # iptables -L INPUT -v

-F

-F, --flush [chain]

Flush the selected chain (all the chains in the table if none is

given). This is equivalent to deleting all the rules one by

one.

 

사슬으로부터 규칙을 제거한다.# iptables -A INPUT -p icmp -j DROP ; iptables -L# iptables -F ; iptables -L # iptables -A INPUT -p icmp -j DROP ; iptables -L# iptables -F INPUT

-Z

-Z, --zero [chain]

Zero the packet and byte counters in all chains. It is legal to

specify the -L, --list (list) option as well, to see the coun-

ters immediately before they are cleared. (See above.)

사슬내의 모든 규칙들의 패킷과 바이트의 카운트를 '0'으로 만든다.# iptables -Z

[참고] 명령어 정리

-A (--append) : 새로운 규칙을 추가한다.

-D (--delete) : 규칙을 삭제한다.

-C (--check) : 패킷을 테스트한다.

-R (--replace) : 새로운 규칙으로 교체한다.

-I (--insert) : 새로운 규칙을 삽입한다.

-L (--list) : 규칙을 출력한다.

-F (--flush) : chain으로부터 규칙을 모두 삭제한다.

-Z (--zero) : 모든 chain의 패킷과 바이트 카운터 값을 0으로 만든다.

-N (--new) : 새로운 chain을 만든다.

-X (--delete-chain) : chain을 삭제한다.

-P (--policy) : 기본정책을 변경한다.

 

(2) 사슬(chain) 내부의 규칙(Rules)에 대한 작동

 

옵 션

설 명

-A

-A, --append chain rule-specification

Append one or more rules to the end of the selected chain. When

the source and/or destination names resolve to more than one

address, a rule will be added for each possible address combina-

tion.

 

사슬에 새로운 규칙을 추가한다. 해당 사슬에 맨 마지막 규칙으로 등록된다.

-I

-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.

 

사슬에 규칙을 맨 첫부분에 설정한다.(i 대문자)

-R

-R, --replace chain rulenum rule-specification

Replace a rule in the selected chain. If the source and/or des-

tination names resolve to multiple addresses, the command will

fail. Rules are numbered starting at 1.

 

사슬의 규칙을 교환한다.

-D

-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.

 

사슬의 규칙을 제거한다.

 

 

 

 

 

(3) 필터링 지정 방법

 

옵션과 관련된 규칙

-s(Source IP), -d(Destination IP)

-j(jump)

-!

-p(Protocol)

-i(In-interface), -o(Out-interface)

-t(Tables)

--sport(Source Port), --dport(Destination Port)

 

 

() -s(발신지), -d(도착지) 사용

옵 션

설 명

-s

-s, --source [!] address[/mask]

Source specification. Address can be either a network name, a

hostname (please note that specifying any name to be resolved

with a remote query such as DNS is a really bad idea), a network

IP address (with /mask), or a plain IP address. The mask can be

either a network mask or a plain number, specifying the number

of 1’s at the left side of the network mask. Thus, a 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.

 

출발지 아이피/네트워크를 지정할 때 사용한다.

(주의) 출발지 주소는 반드시 IP 주소로 지정한다. DNS 이름으로 지정할 수 없다. iptables DNS 전에 시작되기 때문에 DNS 이름을 분석 할 수 없다.

-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.

 

목적지 아이피/네트워크를 지정할 때 사용한다.

(주의) 목적지 주소는 반드시 IP 주소로 지정한다. DNS 이름으로 지정할 수 없다. iptables DNS 전에 시작되기 때문에 DNS 이름을 분석 할 수 없다.

 

(1) IP 주소로 표시하는 방법

-s 192.168.0.5

(2) 넷마스크값으로 표시하는 방법

-s 192.168.1.0/24 -> CIDR(Classless Inter-Domain Routing) 마스크 표기법 허용

-s 192.168.10.0/255.255.255.0 -> VLSM(Variable Length Subnet Mask) 마스크 표기법 허용

 

# iptables -A INPUT -s 0/0 -j DROP

모든 IP 주소(0/0)로 부터 들어오는 패킷들을 모두 DROP 한다.

 

 

 

 

 

 

() -j(점프) 사용

 

옵 션

설 명

-j

-j, --jump target

This specifies the target of the rule; i.e., what to do if the

packet matches it. The target 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.

 

특정한 정책을 설정한다.

 

# iptables -A INPUT -s 192.168.1.20 -j DROP

192.168.1.20로 부터 들어오는 모든 패킷에 대해 거부한다.

 

 

 

() !(not 의미) 사용

 

Not의 의미로 사용한다.

 

# iptables -A INPUT -s ! localhost -d 192.168.0.100 -j ACCEPT

localhost가 아닌 호스트에서 192.168.0.100 호스트로 가는 모든 패킷에 대해 허락한다.

 

 

 

() -p(프로토콜) 사용

 

옵 션

설 명

-p

-p, --protocol [!] protocol

The protocol of the rule or of the packet to check. The speci-

fied protocol can be one of tcp, udp, icmp, or all, or it can be

a numeric value, representing one of these protocols or a dif-

ferent 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. Protocol all will match

with all protocols and is taken as default when this option is

omitted.

 

프로토콜을 설정할 때 사용한다. 보통 TCP, UDP, ICMP 같은 이름들이 사용된다. 대소문자를 구별하지 않는다. !(not)과도 같이 사용할수 있다.

 

# iptables -A INPUT -p tcp --dport 23 -j ACCEPT

TCP 프로토콜에 대한 목적지 포트가 23(TELNET)에 대해서 모든 패킷을 허락한다.

 

 

 

() -i(인바운드 인터페이스) 사용

 

옵 션

설 명

-i

-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.

 

패킷이 들어오는 인터페이스를 설정할 때 사용한다. INPUT, OUTPUT 사슬에서 주로 사용한다.

 

 

 

() -o(아웃바운드 인터페이스) 사용

 

옵 션

설 명

-o

-o, --out-interface [!] name

Name of an interface via which a packet is going to be sent (for

packets entering the FORWARD, 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.

 

패킷이 나가는 네트워크 장치를 지정할 때 사용한다. 보통 OUPUT, FORWARD 사슬에서 사용된다.

 

 

 

() -t(테이블) 사용

 

옵 션

설 명

-t

-t, --table table

This option specifies the packet matching table which the com-

mand should operate on. If the kernel is configured with auto-

matic module loading, an attempt will be made to load the appro-

priate 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 rout-

ing), and POSTROUTING (for altering packets as they are

about to go out).

 

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 sup-

ported: INPUT (for packets coming into the box itself), FOR-

WARD (for altering packets being routed through the box),

and POSTROUTING (for altering packets as they are about to

go out).

 

table을 선택할 때 사용한다. filter, nat, mangle 세가지 중에 선택할 수 있다. 커널에 해당 테이블을 지원하는 코드가 들어 있어야 한다. 모듈 자동적재를 선택하면 그와 관련된 커널 모듈이 적재된다. 기본은 filter이므로 nat 사용하려면 nat라고 지정해야 한다.

 

 

 

(o) --sport, --dport 사용

 

옵 션

설 명

--sport

--source-port,--sport [!] port[:port]

--dport

--destination-port,--dport [!] port[:port]

 

 

[참고] 매칭(match) 규칙에 대한 간단한 정리

iptables에서 패킷을 처리할때 만족해야 하는 조건을 가리킨다.

, 이 조건을 만족시키는 패킷들만 규칙을 적용한다.

 

--source (-s) : 출발지 IP주소나 네트워크와의 매칭

--destination (-d) : 목적지 ip주소나 네트워크와의 매칭

--protocol (-p) : 특정 프로토콜과의 매칭

--in-interface (i) : 입력 인테페이스

--out-interface (-o) : 출력 인터페이스

--state : 연결 상태와의 매칭

--string : 애플리케이션 계층 데이터 바이트 순서와의 매칭

--comment : 커널 메모리 내의 규칙과 연계되는 최대 256바이트 주석

--syn (-y) : SYN 패킷을 허용하지 않는다.

--fragment (-f) : 두 번째 이후의 조각에 대해서 규칙을 명시한다.

--table (-t) : 처리될 테이블

--jump (-j) : 규칙에 맞는 패킷을 어떻게 처리할 것인가를 명시한다.

--match (-m) : 특정 모듈과의 매치

 

 

 


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160801 NTP  (0) 2016.08.01
20160729 방화벽  (0) 2016.07.29
20160728 로그보안  (0) 2016.07.28
20160727 로그보안  (0) 2016.07.27
20160727 리눅스 서버보안  (0) 2016.07.27
Posted by 22Hz
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함