---
# System prepended metadata

title: Firewall & NAT Service

---

# Firewall & NAT Service


[TOC]

# Packet 進入主機流程


![](https://hackmd.io/_uploads/SkgX3_eP3.png)

IP Filtering 或 Net Filter (第一層防火牆)

tcp_warppers -> 處理Port 部分 (第二層防火牆)


HTTP
samba 給(windows <--> Linux 傳東西 )  -> 登入檔(互動)

SElinux -> 進階權限管控  <-> 登入檔(互動)




## Firewall 

基本會有兩層防火牆

![](https://hackmd.io/_uploads/HJPTadgP3.png)

TCP Wrappers -> 處理 (daemon) 服務存取限制 

![](https://hackmd.io/_uploads/BysEAOgD2.png =500x)


## 服務 (daemon) 的限制

我們可以 控管某些目錄可以進入 某些目錄則無法使用

e.g. httpd.conf 

可以進行限制  某些 IP 來源不能使用 httpd 這個服務來取得主機的資料


## SELinux

Security Enhanced Linux 

細部權限控制

能對Proccess 能進行的動作進行限制
程序使用的是 root 的權限也一樣

e.g.

SELinux -> httpd /var/www/html 控制在裡面

# Linux 系統上防火牆的主要類別


## Packet filter 

![](https://hackmd.io/_uploads/BJnDBFevh.png)


## TCP wrapper 

![](https://hackmd.io/_uploads/Bko_HtgD3.png)

有關 tcp_wrappers 的信息，請參閱“man tcpd”

tcpd - access control facility for internet services(互聯網服務的訪問控制設施)


可以管

-   由 super daemon (xinetd) 所管理的服務；
-   有支援 libwrap.so 模組的服務。

支援 tcp wrappers 的服務必定包含 libwrap 這一個動態函式庫

### 找可以被 tcp wrapper 設定的 sofeware

Way1 
```shell
for name in rsyslogd sshd xinetd httpd;do echo $name;ldd $(which $name) | grep libwrap;done
```

```shell
[root@localhost scirpt]# for name in rsyslogd sshd xinetd httpd;\
> do \
> echo $name;\
> ldd $(which $name) | grep libwrap;\
> done
rsyslogd
sshd
	libwrap.so.0 => /lib64/libwrap.so.0 (0x00007f8e252fb000)
xinetd
	libwrap.so.0 => /lib64/libwrap.so.0 (0x00007f2fd6eb5000)
httpd

```

Ldd（List Dynamic Dependencies，意譯為**列出動態庫依賴關係**

Conclusion:
"sshd,xinetd -> 可以被 tcp wrappers 支援"



### /etc/hosts.{allow|deny} Configuration (設定)


Permission 由兩個這file 進行controll 

- 先看 /etc/hosts.allow  Match -> 放行 (whitelist)
- 再看 /etc/hosts.deny (blocklist)
- Policy -> 皆不符合 放行


設定檔格式
```
<service(program_name)> : <IP, domain, hostname> 
<服務   (亦即程式名稱)\> : <IP 或領域 或主機名稱>
```


#### /etc/hosts.allow 



```
[root@localhost centos]# cat /etc/hosts.allow
#
# hosts.allow	This file contains access rules which are used to
#		allow or deny connections to network services that
#		either use the tcp_wrappers library or that have been
#		started through a tcp_wrappers-enabled xinetd.
#
#		See 'man 5 hosts_options' and 'man 5 hosts_access'
#		for information on rule syntax.
#		See 'man tcpd' for information on tcp_wrappers
#

```

#### /etc/hosts.deny

```
[root@localhost centos]# cat /etc/hosts.deny 
#
# hosts.deny	This file contains access rules which are used to
#		deny connections to network services that either use
#		the tcp_wrappers library or that have been
#		started through a tcp_wrappers-enabled xinetd.
#
#		The rules in this file can also be set up in
#		/etc/hosts.allow with a 'deny' option instead.
#
#		See 'man 5 hosts_options' and 'man 5 hosts_access'
#		for information on rule syntax.
#		See 'man tcpd' for information on tcp_wrappers
#

```

#### sample 

```
[root@www ~]# vim /etc/hosts.allow
ALL: 127.0.0.1    <==這就是本機全部的服務都接受！
rsync: 192.168.1.0/255.255.255.0 10.0.0.100

[root@www ~]# vim /etc/hosts.deny
rsync: ALL
```

## Proxy 

Proxcy 會掌控連線部份

![](https://hackmd.io/_uploads/B1nLUYgwh.png)

Protected 部份

proxy 可以分析使用者的 IP 來源是否合法

proxy 通常會放在 Router 上 開 21, 20 , 80 (掌控區域網路內的對外連線
)

### Proxy Chains 

Internet 上看到的SRC 會是Proxy IP --> 故有 Proxcy Chain  這種隱藏IP 的方式



# Firewall 佈置


## Single Domain/Router  (單一網域 僅有一個路由器)

![](https://hackmd.io/_uploads/Hk7qdKlPh.png)

內外網域分開

### Router Traffic Monitoring 

MRTG (可以分析流量)


## LAN 裡面再放一個 FireWall 

避免外人透過AP進入LAN 裡面 對機密Server 進行存取 

![](https://hackmd.io/_uploads/Bk4k2Fxv2.png)

## 防火牆的後面架 Server (FTP, maill, web)(DMZ)

可以透過 Port Forwarding 來實現 

![](https://hackmd.io/_uploads/SJwS6KlPn.png)

這張圖結合了 之前提到的2種技術 

# Linux packet filter (iptable) 


## 規則順序(flow sequence)

![](https://hackmd.io/_uploads/BkyGk2gPn.png)

他很急XD -> 只要符合 Rule -> 就會馬上 Action 

## iptable (Table/chain)

主要是 Table 跟 Chain 


### filter (Table)

他的chain 

- input (inbound)
- ouput (outbound)
- forward 

![](https://hackmd.io/_uploads/B1gwlnew2.png)


### Nat (Table)

他的chain 

- preroution (DNAT/REDIRECT) 重定向
- ouput (SNAT/MASQUERADE) 化裝舞會
- postrouting


![](https://hackmd.io/_uploads/BJ3ag2ew3.png)

### 表格(Table)跟鏈結(Chain)關係


![](https://hackmd.io/_uploads/ryx6-3gD2.png)

Nat prerouting -> filter(Input || forward )-> linux host -> nat postrouting -> filter output - > target 

![](https://hackmd.io/_uploads/SJ0tz3lw2.png)


## iptable 規則的觀察與清除

Common flags 

```
- t table 
- L display rules of the table !!
- A append Rule 加到最後
- I insert Rule "?" default = 1 
- v verbose 
```
 

### Delete 特定 Rules 

```
iptables -t filter -D INPUT 1
```

---

### 顯示 filter table 的　flows 

```
[root@localhost ~]# iptables -L -n
Chain INPUT (policy ACCEPT) #iput chain
target     prot opt source               destination  #description        
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:53 #rule 1
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:53 #rule 2 
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:67
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:67

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  0.0.0.0/0            192.168.122.0/24     ctstate RELATED,ESTABLISHED
ACCEPT     all  --  192.168.122.0/24     0.0.0.0/0           
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           
REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable
REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:68

```

### 查看 Nat Table
```
[root@localhost ~]# iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination         

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination         
RETURN     all  --  192.168.122.0/24     224.0.0.0/24        
RETURN     all  --  192.168.122.0/24     255.255.255.255     
MASQUERADE  tcp  --  192.168.122.0/24    !192.168.122.0/24     masq ports: 1024-65535
MASQUERADE  udp  --  192.168.122.0/24    !192.168.122.0/24     masq ports: 1024-65535
MASQUERADE  all  --  192.168.122.0/24    !192.168.122.0/24    

```


## iptable-save (會列出完整的防火牆規則)

```
[root@localhost ~]# iptables-save  -t filter
# Generated by iptables-save v1.4.21 on Fri Jun  9 08:16:57 2023
*filter  # Table 
:INPUT ACCEPT [754:245162]  # 冒號 -> chain (Policy -> accept )
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [604:51955]
-A INPUT -i virbr0 -p udp -m udp --dport 53 -j ACCEPT
-A INPUT -i virbr0 -p tcp -m tcp --dport 53 -j ACCEPT
-A INPUT -i virbr0 -p udp -m udp --dport 67 -j ACCEPT
-A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT
-A FORWARD -d 192.168.122.0/24 -o virbr0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 
-A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT
-A FORWARD -i virbr0 -o virbr0 -j ACCEPT
-A FORWARD -o virbr0 -j REJECT --reject-with icmp-port-unreachable
-A FORWARD -i virbr0 -j REJECT --reject-with icmp-port-unreachable
-A OUTPUT -o virbr0 -p udp -m udp --dport 68 -j ACCEPT
COMMIT
# Completed on Fri Jun  9 08:16:57 2023

```

### 清除本機防火牆 (filter) 的規則

重新定義防火牆的時候 都會先將規則給他清除掉 會比較好設定


-F ：清除所有的已訂定的規則；
-X ：殺掉所有使用者 "自訂" 的 chain (應該說的是 tables ）
-Z ：將所有的 chain 的計數與流量統計都歸零

```
[root@localhost ~]# iptables -F
[root@localhost ~]# iptables -X
[root@localhost ~]# iptables -Z
```

### Setting Default Policy 

一般會把 filter(input) policy -> DROP
FORWARD 與 OUTPUT -> ACCEPT (對於內部的使用者有信心的話)

```
[root@localhost ~]# iptables -P INPUT DROP
[root@localhost ~]# iptables -P OUTPUT ACCEPT
[root@localhost ~]# iptables -P FORWARD ACCEPT

[root@localhost ~]# iptables-save -t filter
# Generated by iptables-save v1.4.21 on Fri Jun  9 08:30:03 2023
*filter
:INPUT DROP [0:0] # Acetion 變成DROP 
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]

```
## Rule setting (IP/domain/interface)

syntax 

```
iptables [-t tableName] [-AI chainName] \
> [-io interface] [-p protocol] \
> [-s source IP/domain] [-d destination IP/domain] \ 
> [-j ACCEPT|DROP|REJECT|LOG]
```

- io 網路介面：設定封包進出的介面規範
    - i ：封包所進入的那個網路介面，例如 eth0, lo 等介面。需與 INPUT 鏈配合；
    - o ：封包所傳出的那個網路介面，需與 OUTPUT 鏈配合；

- s ! 192.168.100.0/24 表示不許 192.168.100.0/24 之封包來源；


### Interface Rules (看interface)

lo interface -> 進來的都ACCEPT  (可信任 Device)

不論封包來自何處或去到哪裡 只要是來自 lo 這個介面 就接受

```shell
[root@localhost ~]# iptables -t filter -A INPUT -i lo -j ACCEPT


[root@localhost ~]# iptables-save -t filter
# Generated by iptables-save v1.4.21 on Fri Jun  9 08:43:58 2023
*filter
:INPUT DROP [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i virbr0 -p udp -m udp --dport 53 -j ACCEPT
-A INPUT -i virbr0 -p tcp -m tcp --dport 53 -j ACCEPT
-A INPUT -i virbr0 -p udp -m udp --dport 67 -j ACCEPT
-A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT
-A INPUT -i lo -j ACCEPT
```

--- 

假設 有兩張 interface: eth0 -> 外網 eth1 ->內網 (信任)

```
iptables -A INPUT -i eth1 -s 192.168.100.0/24 -j ACCEPT
```
192.168.100.0/24 "內網 網段"



192.168.100.230 內網這台機器 會被 DROP 掉, ohter HOSt 則不會


```
[root@localhost xinetd.d]# iptables -A INPUT -i eth1 -s 192.168.100.230 -j DROP
[root@localhost xinetd.d]# iptables -A INPUT -i eth1 -s 192.168.100.10 -j ACCEPT
[root@localhost xinetd.d]# iptables -A INPUT -i eth1 -s 192.168.100.0/24 -j ACCEPT


[root@localhost xinetd.d]# iptables-save -t filter
# Generated by iptables-save v1.4.21 on Fri Jun  9 09:09:08 2023
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i virbr0 -p udp -m udp --dport 53 -j ACCEPT
-A INPUT -i virbr0 -p tcp -m tcp --dport 53 -j ACCEPT
-A INPUT -i virbr0 -p udp -m udp --dport 67 -j ACCEPT
-A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT
-A INPUT -s 192.168.100.230/32 -i eth1 -j DROP
-A INPUT -s 192.168.100.10/32 -i eth1 -j ACCEPT
-A INPUT -s 192.168.100.0/24 -i eth1 -j ACCEPT


```

### LOG 

Action 如果是log  則進去的packet info 會放到 /var/log/message


```
[root@localhost xinetd.d]# iptables -A INPUT -s 192.168.2.200 -j LOG
[root@localhost xinetd.d]# iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:53
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:53
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:67
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:67
DROP       all  --  192.168.100.230      0.0.0.0/0           
ACCEPT     all  --  192.168.100.10       0.0.0.0/0           
ACCEPT     all  --  192.168.100.0/24     0.0.0.0/0           
LOG        all  --  192.168.2.200        0.0.0.0/0            LOG flags 0 level 4

```


## Rule setting (TCP/UDP)


syntax 
```
iptables [-AI chain] [-io interface ] [-p tcp,udp] \
> [-s source IP/domain] [--sport portRange] \
> [-d destination IP/domain] [--dport portRange] -j [ACCEPT|DROP|REJECT]
```
-p tcp 或 -p udp "一定要加"

要DROP 盡量使用 -I 插在第一條

```
[root@localhost xinetd.d]# iptables -I INPUT 1 -i ens33 -p tcp --dport 21 -j DROP 
[root@localhost xinetd.d]# iptables-save -t filter
# Generated by iptables-save v1.4.21 on Fri Jun  9 09:32:48 2023
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i ens33 -p tcp -m tcp --dport 21 -j DROP

```


打開網路芳鄰服務
```
[root@localhost xinetd.d]# iptables -A INPUT -i ens33 -p tcp --dport 139 -j ACCEPT
[root@localhost xinetd.d]# iptables -A INPUT -i ens33 -p tcp --dport 445 -j ACCEPT

```


### Port Number (可以是一個範圍)

DROP 對方 1024~655534 clinet 連線
```
[root@localhost xinetd.d]# iptables -A INPUT -i ens33 -p tcp -s 192.168.1.0/24 \
> --sport 1024:65534 --dport ssh -j DROP

```


### TCP Flager 

DROP SYN packet

```
iptables -A INPUT -i ens33 -p tcp --sport 1:1023 \
> --dport 1:1023 --syn -j DROP
```


## iptables 額外模組 (mac 與 state)

- m ：一些 iptables 的外掛模組，主要常見的有：
     state ：狀態模組
     mac   ：網路卡硬體位址 (hardware address)


### State 

狀態模組來分析 『這個想要進入的封包是否為剛剛我發出去的回應？』 如果是剛剛我發出去的回應，那麼就可以予以接受放行

- -\-state ：一些封包的狀態，主要有：
     - INVALID    ：無效的封包，例如資料破損的封包狀態
     - ESTABLISHED：已經連線成功的連線狀態；
     - NEW        ：想要新建立連線的封包狀態；
     - RELATED    ：這個最常用！表示這個封包是與我們主機發送出去的封包有關

```
[root@localhost xinetd.d]# iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

[root@localhost xinetd.d]# iptables -A INPUT -m state --state INVALID -j DROP

```

iptables 就會主動分析出該封包是否為回應狀態 若是的話 就直接予以接受



### Mac filter (MAC 過濾)

(有效)
```
iptables -A INPUT -m mac --mac-source 00:0c:29:45:2d:c2 -j DROP
```

Noting 可以透過某些軟體來修改網卡的 MAC


### Add New Rules (Filter Table) 





```
iptables -t filter -A INPUT -j DROP -p tcp --dport 80
```

在過濾表中append 一個 packet 的 Dst port 是 80 全部 Drop掉

![](https://i.imgur.com/wn1UQSF.png)




## Output chain (out bound 出站)

ping 192.168.203.151
PING 192.168.203.151 (192.168.203.151) 56(84) bytes of data.
64 bytes from 192.168.203.151: icmp_seq=1 ttl=64 time=5.23 ms
64 bytes from 192.168.203.151: icmp_seq=2 ttl=64 time=1.02 ms

```
iptables -t filter -A OUTPUT -j DROP -p icmp -d 192.168.203.151
```
root@ubuntu:/home/user# ping 192.168.203.151PING 192.168.203.151 (192.168.203.151) 56(84) bytes of data.
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted




## Nat Table (NAT 設定)

show

```
iptables -t nat -L
```

Nat Table 會有4個chain

### PreRouting(Before Routing)

改 destination IP or Address 
可以進行轉發(Forward)


### PostRouting(After Routing)

改 Source IP or Address (常用在 private IP 轉 Public IP 時)



## FirewallD

(Dynamic configure)

多個ZONE

ALL zone
```
[centos@meowhecker accountScript]$ firewall-cmd --get-zones
block dmz drop external home internal public trusted work

```

Current zone 

```
[centos@meowhecker accountScript]$ firewall-cmd --get-active-zones

```

lookup Rule
```
[centos@meowhecker accountScript]$ firewall-cmd --zone=public --list-all
public
  target: default
  icmp-block-inversion: no
  interfaces: 
  sources: 
  services: dhcpv6-client ssh
  ports: 
  protocols: 
  masquerade: no
  forward-ports: 
  source-ports: 
  icmp-blocks: 
  rich rules: 

```

services: dhcpv6-client ssh  -->　白名單機制


---

[centos@meowhecker accountScript]$ systemctl status firewalld.service
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
   Active: inactive (dead)
     Docs: man:firewalld(1)



### Remote service 
