레이블이 NET-NAT인 게시물을 표시합니다. 모든 게시물 표시
레이블이 NET-NAT인 게시물을 표시합니다. 모든 게시물 표시

4/20/2020

firewall 설정 및 Service 등록

1. firewall 기본이해  

Linux의 firewall 기능은 기본적으로 iptables 와 firewalld가 존재하며, 기존부터 사용하던 것이 iptables 이라고 한다.
기존의 RTOS를 제외하고 Linux의 경우 firewall 기능을 거의 사용해본적이 없어 관련내용을 새롭게 알게되었다.

  • Linux에서 지원되는 Firewall Package
  1. firewalld:  GUI Interface를 제공하며, Kernel Netffilter 부분이용
  2. iptables: GUI Interface를 미제공하며, Kernel Netfilter 부분이용

iptables은 쉽게 command 형식으로 동작가능하며, firewalld는 iptables과 기능이 비슷한 nftables 기반으로 동작되어진다고 한다.
세부적으로 잘 모르겠지만, 간단히 비교하자면, firewalld는 편이성을 목적을 둔 것 같으며, iptables은 이전부터 사용하던 command 방식인것 같다.

Firewalld 관련사항
  https://en.wikipedia.org/wiki/Firewalld

1.1 Netfilter 의 기능 

firewalld를 사용하던 iptables을 사용하던 Kernel Netfilter 설정은 필수이며 이부분은 어쩔수 없다.
두 기능을 제대로 사용하고자 한다면 Kernel의 설정은 필수이지만, iptables을 사용하는지 nftables을 사용하는지에 따라 Kernel 설정은 달라지는 것 같다.

Netfilter 관련사항
  https://en.wikipedia.org/wiki/Netfilter

Firewalld 사용하는 nftables 기능
  https://wiki.gentoo.org/wiki/Nftables

Netfilter 관련 Project 정보
  https://netfilter.org/

1.2 Kernel 의 Netfilter 설정

현재 nftables 대신에 iptables을 사용할 것이며, 가급적 필요없는 기능은 빼도록 하자.
Kernel 옵션과 iptables의 설명서의 세부옵션을 자세히 보면 설정은 이해가 대충간다.
nftables 관련부분은 설정하지 않았지만, 유사할 것이라고 생각이 든다.

  • nftables의 kernel 기본설정 
[*] Networking support  --->
    Networking options  --->
        [*] Network packet filtering framework (Netfilter)  --->
            Core Netfilter Configuration  --->
                 Netfilter nf_tables support
                   Netfilter nf_tables conntrack module
                   Netfilter nf_tables counter module
                   Netfilter nf_tables log module
                   Netfilter nf_tables limit module
                   Netfilter nf_tables masquerade support
                   Netfilter nf_tables nat module
            IP: Netfilter Configuration  --->
                 IPv4 nf_tables support
                   IPv4 nf_tables route chain support
                 IPv4 packet rejection
                 IPv4 NAT
                   IPv4 nf_tables nat chain support
                   IPv4 masquerade support
                   IPv4 masquerading support for nf_tables

  https://wiki.gentoo.org/wiki/Nftables
  https://wiki.nftables.org/wiki-nftables/index.php/Building_and_installing_nftables_from_sources

NAT 설정시 상위 Kernel 설정필수

  • iptables kernel 기본설정 
[*] Networking support  --->                                          [CONFIG_NET]
      Networking Options  --->
        [*] Network packet filtering framework (Netfilter) --->       [CONFIG_NETFILTER]
          [*] Advanced netfilter configuration                        [CONFIG_NETFILTER_ADVANCED]   // iptables의 세부옵션까지 설정가능 (현재 불필요)
          Core Netfilter Configuration --->
            <*/M> Netfilter connection tracking support               [CONFIG_NF_CONNTRACK]  // iptables의 옵션의 conntrack 기능 설정 
            <*/M> Netfilter Xtables support (required for ip_tables)  [CONFIG_NETFILTER_XTABLES]
            <*/M> LOG target support                                  [CONFIG_NETFILTER_XT_TARGET_LOG]  // iptables의 기능 중 LOG로 남길수 있는 기능 
          IP: Netfilter Configuration --->
            <*/M> IP tables support (required for filtering/masq/NAT) [CONFIG_IP_NF_IPTABLES]

설정관련사항 및 Download
  http://www.linuxfromscratch.org/blfs/view/svn/postlfs/iptables.html


  • iptables의 client (현재 이 옵션에 맞춰 설정)
[*] Networking support  --->
    Networking options  --->
        ...
        [*] TCP/IP networking
        [ ]   IP: multicasting
        [ ]   IP: advanced router
        [ ]   IP: kernel level autoconfiguration
        < >   IP: tunneling
        < >   IP: GRE demultiplexer
        [ ]   IP: TCP syncookie support
        < >   Virtual (secure) IP: tunneling
        < >   IP: AH transformation
        < >   IP: ESP transformation
        < >   IP: IPComp transformation
        <*>   IP: IPsec transport mode
        <*>   IP: IPsec tunnel mode
        < >   IP: IPsec BEET mode
        < >   Large Receive Offload (ipv4/tcp)
        <*>   INET: socket monitoring interface
        < >     UDP: socket monitoring interface
        [ ]   TCP: advanced congestion control  ----
        [ ]   TCP: MD5 Signature Option support (RFC2385)
        <*>   The IPv6 protocol  --->
        [ ] Security Marking
        [ ] Timestamping in PHY devices
        [*] Network packet filtering framework (Netfilter)  --->
            --- Network packet filtering framework (Netfilter)
            [ ]   Network packet filtering debugging
            [ ]   Advanced netfilter configuration
                  Core Netfilter Configuration  --->
                       Netfilter LOG over NFNETLINK interface
                      <*> Netfilter connection tracking support
                      [ ]   Supply CT list in procfs (OBSOLETE)
                      < >   FTP protocol support
                      < >   IRC protocol support
                      < >   NetBIOS name service protocol support
                      < >   SIP protocol support
                      < >   Connection tracking netlink interface
                      < > Netfilter nf_tables support
                      -*- Netfilter Xtables support (required for ip_tables)
                            *** Xtables combined modules ***
                      < >   nfmark target and match support
                            *** Xtables targets ***
                      < >   LOG target support
                      < >   "NFLOG" target support
                      < >   "TCPMSS" target support
                            *** Xtables matches ***
                      <*>   "conntrack" connection tracking match support   // iptable 의 conntrack option 기능사용
                      < >   IPsec "policy" match support
                      < >   "state" match support
            < >   IP set support  ----
            < >   IP virtual server support  ----
                  IP: Netfilter Configuration  --->
                      <*> IPv4 connection tracking support (required for NAT)
                      <*> IP tables support (required for filtering/masq/NAT)
                      <*>   Packet filtering
                      <*>     REJECT target support
                      < >   ULOG target support (obsolete)
                      < >   IPv4 NAT
                      < >   Packet mangling
                      < >   raw table support (required for NOTRACK/TRACE)
                  IPv6: Netfilter Configuration  --->
                      <*> IPv6 connection tracking support
                      <*> IP6 tables support (required for filtering)
                      < >   "ipv6header" IPv6 Extension Headers Match
                      <*>   Packet filtering
                      <*>     REJECT target support
                      < >   Packet mangling
                      < >   raw table support (required for TRACE)


  • iptables의 router 기준옵션
[*] Networking support  --->
    Networking options  --->
        [*] TCP/IP networking
        [*]   IP: multicasting
        [*]   IP: advanced router
        ...
        [*]   IP: ARP daemon support
        [*]   IP: TCP syncookie support
        <m>   IP: AH transformation
        <m>   IP: ESP transformation
        <m>   IP: IPComp transformation
        <m>   IP: IPsec transport mode
        <m>   IP: IPsec tunnel mode
        <m>   IP: IPsec BEET mode
        <*>   Large Receive Offload (ipv4/tcp)
        <*>   INET: socket monitoring interface
        <m>     UDP: socket monitoring interface
        [ ]   TCP: advanced congestion control  --->
        ...
           The IPv6 protocol  ---&gt;
        ...
        [*] Network packet filtering framework (Netfilter)  --->
            [*]   Advanced netfilter configuration      // 좀 더 많은 iptable 옵션설정가능 
            Core Netfilter Configuration  --->
                <m>   "addrtype" address type match support  // iptable 명령어의 세부옵션
                <m>   "comment" match support                // iptable 명령어의 세부옵션
                <m>   "hl" hoplimit/TTL match support        // iptable 명령어의 세부옵션
                <m>   "limit" match support                  // iptable 명령어의 세부옵션
                <m>   "multiport" Multiple port match support // iptable 명령어의 세부옵션
                <m>   "recent" match support                  // iptable 명령어의 세부옵션

상위설정관련내용
  https://wiki.gentoo.org/wiki/Iptables


2. iptables 와 ip6tables설정 

ipv4 는 iptables 이며, ipv6는 당연히 ip6tables로 쉽게 설정가능하다.

  • iptables의 기본사용법
iptables [-t table] {-A|-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

  https://linux.die.net/man/8/iptables
  https://linux.die.net/man/8/ip6tables

  • chain 
  1. INPUT: Host로 들어오는 방향관리
  2. OUTPUT: Host에서 나가는 방향관리
  3. FORWARD: Host에서 Forward해주는 부분관리 
  4. User-defined: -N Command를 이용하여 새로운 Chain 생성가능 

  • target
  1. ACCEPT : Packet의 허용
  2. DROP : Packet을 버림
  3. User-define Chain: 
  4. LOG  ( KERNCONFIG의 상위 LOG설정필요), syslog에 설정 

  • table  (미사용)
  1. filter  (KERNEL CONFIG 의 CONFIG_IP_NF_FILTER  설정필요) 
  2. nat     (KERNEL CONFIG 의 CONFIG_IP_NF_NAT   설정필요)    (option)
  3. mangle  (KERNEL CONFIG 의 CONFIG_IP_NF_MANGLE 설정필요)   (option)
  4. raw     (KERNEL CONFIG 의 CONFIG_IP_NF_RAW 설정필요)   (option)

iptable 기본사용법
  https://brownbears.tistory.com/151
  https://linux.die.net/man/8/iptables


2.1 iptable 기본 사용법 

  • iptable 현재 설정상태 확인
policy가 모두 ACCEPT로 되어있어, 모든 Connection 허락하며 별도로 설정된 설정이 없음

$ iptables -L     // 기본 설정확인 확인  Chain은 기본으로 3개 
or
$ iptables -L  -n  

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

$ iptables -nvL --line-numbers  //기본설정확인 및 세부사항확인 
Chain INPUT (policy ACCEPT 3 packets, 96 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination


  • iptable policy 설정 
기본 정책은 모든 INPUT/ OUTPUT/FORWARD를 전부 막고, ACCEPT 해줄 것을 이후에 별도로 설정하면 됨

$ iptables -P INPUT   DROP
$ iptables -P FORWARD DROP
$ iptables -P OUTPUT  DROP

기본 정책은 모든 INPUT/ FORWARD만 만 막고 OUTPUT은 허용

$ iptables -P INPUT   DROP
$ iptables -P FORWARD DROP
$ iptables -P OUTPUT  ACCEPT 

모두 허용

$ iptables -P INPUT   ACCEPT 
$ iptables -P FORWARD ACCEPT 
$ iptables -P OUTPUT  ACCEPT 


  • local device 허용
$ iptables -A INPUT  -i lo -j ACCEPT
$ iptables -A OUTPUT -o lo -j ACCEPT


  • NAT의 기능 
iptable을 이용하여 NAT기능도 사용가능하며, 상위 커널설정은 반드시 필요 


기본으로 Kernel 에서 Netfilter 부분설정 
# 상위그림 처럼 막음 Disabled by default!  
$  echo "1" > /proc/sys/net/ipv4/ip_forward


$ iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE     // eth1 NAT 설정 

NAT 및 포트포워딩 관련세부사항 아래 참조
  https://www.karlrupp.net/en/computer/nat_tutorial
  http://www.netfilter.org/projects/iptables/index.html

  • Incoming/outcoming 허용
policy를 drop으로 되어있을 경우 아래와 같이 Server의 특정 Port를 연결을 해주어 동작하도록 한다.
보통 Server는 Listeing port 와 communication port가 다르므로 관련부분을 설정

$ iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$ iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

iptables 일반적인 command
  https://www.digitalocean.com/community/tutorials/iptables-essentials-common-firewall-rules-and-commands


iptables 사용법 참조
  https://linux.die.net/man/8/iptables
  https://www.thegeekstuff.com/2011/03/iptables-inbound-and-outbound-rules/
  https://idchowto.com/?p=38658
  https://ko.wikipedia.org/wiki/Iptables
  https://wiki.archlinux.org/index.php/Iptables
  https://linuxstory1.tistory.com/entry/iptables-%EA%B8%B0%EB%B3%B8-%EB%AA%85%EB%A0%B9%EC%96%B4-%EB%B0%8F-%EC%98%B5%EC%85%98-%EB%AA%85%EB%A0%B9%EC%96%B4
  https://pydole.tistory.com/entry/iptables-%EC%B0%A8%EB%8B%A8-%EB%A1%9C%EA%B7%B8-%EB%AA%A8%EB%8B%88%ED%84%B0%EB%A7%81-1-%EB%A1%9C%EA%B7%B8-%EB%82%A8%EA%B8%B0%EA%B8%B0


2.2 iptable 용 systemd service 설정 

  • iptable 설정 script 
service 를 위해서 사용할 iptable용 Shell Script 작성 

$ cat /usr/bin/firewall.sh
#!/bin/bash
# Configure iptables firewall

# Limit PATH
PATH="/sbin:/usr/sbin:/bin:/usr/bin"

firewall_start() {

  # interface lo (loopback)
  # Accept everything on loopback
  iptables -A INPUT  -i lo -j ACCEPT
  iptables -A OUTPUT -o lo -j ACCEPT

  #
  # default setting 
  #
  iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

  #
  # ping 
  #
  iptables -A INPUT -p icmp -j ACCEPT
  iptables -A OUTPUT -p icmp -j ACCEPT

  #
  # SSH Server TCP Destination Port 22 (dport)
  # 
  iptables -A INPUT  -p tcp --dport 22 -j ACCEPT  

  #
  # SSH Client TCP Destination Port 22 
  # 
  iptables -A OUTPUT -p tcp --dport 22  -j ACCEPT

  #
  # Default Policy 
  #
  iptables -P INPUT   DROP
  iptables -P FORWARD DROP
  iptables -P OUTPUT  ACCEPT
  #iptables -P OUTPUT  DROP
}

firewall_stop() {
  # iptable flush setting
  iptables -F
  # iptable delete all of chains
  iptables -X
  # iptable default policy setting 
  iptables -P INPUT   ACCEPT
  iptables -P FORWARD ACCEPT
  iptables -P OUTPUT  ACCEPT
}

# execute action
case "$1" in
  start|restart)
    echo "Start firewall, your setting"
    firewall_stop
    firewall_start
    ;;
  stop)
    echo "Stop firewall, default setting"
    firewall_stop
    ;;
esac


  • systemd service file 설정

$ vi /lib/systemd/system/firewall.service
or 
$ vi /etc/systemd/system/firewall.service     // etc로 추천 

[Unit]
Description=iptables firewall service
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/bin/firewall.sh start
RemainAfterExit=true
ExecStop=/usr/bin/firewall.sh stop
StandardOutput=journal

## multi-user.target 
[Install]
WantedBy=multi-user.target

$ systemctl status firewall.service

$ systemctl enable firewall.service     // enable 시 아래의 주소로 link 생성되며 동작 

$ ls /etc/systemd/system/multi-user.target.wants/firewall.service  // 상위 install 

$ systemctl start firewall.service  
or
$ init 6  // reboot

iptables의 shellscript 관련예제
    https://blog.sleeplessbeastie.eu/2018/10/01/how-to-make-iptables-configuration-persistent-using-systemd/