Array
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    ###### tags: `1121` `lsa` `ncnu` # Week 14 (2023/12/14) TCP/IP & iptables - Book mode: https://hackmd.io/@ncnu-opensource/book [TOC] ## 5. Transport Layer :::info - 傳輸層多了port的概念,讓同一台電腦擁有多個對外的出口,區分不同服務(UDP) - TCP更提供可靠的傳輸機制,保證封包準確送達、順序正確 - 協議數據單元(Protocol Data Unit,PDU),為Segment ::: :::info ### Port > Review: SSH - 如果只有 IP 位址,若有不同的軟體要同時進行傳輸,所有的資料就會從同一個出口一起通過,會產生碰撞。 - 連接埠:讓同一台電腦擁有多個對外的出口,讓網路傳輸有多工的能力 - 每個 Port 對應到不同的網路 #### port 相關指令 * `cat /etc/ services`:查看 port 的使用狀況 * `grep -w /etc/services`:查詢指定port #### 常見服務對應port ::: ### 5.1 UDP (User Datagram Protocol) - 僅提供傳輸基本功能,負負責處裡封包要傳送到哪個 Port - 適用場景 - 通常用於遊戲、P2P 打洞 - Connectionless:不可靠的傳輸方式 - 接收端在收到資料後不會回傳確認訊息給發送端 - 追求即時性且能容忍一些封包丟失的情況(盡力傳遞) - 串流服務、視訊、音訊 ![image](https://hackmd.io/_uploads/ByttcBOL6.png) ### 5.2 TCP( Transmission Control Protocol) > 網路層協定使用不可靠的傳送機制 - 可靠的傳輸方式—>保障資料完整性 - 連線導向 (Connection-Oriented):傳輸資料前先建立連線,協調參數(用於資料確認與重送、流量控制) > 利用三項交握建立連線 - 資料確認與重送:確認目的端是否收到已送出的資料 - 流量控制:視情況調整資料傳輸的狀況,盡量減少資料的流失 >利用滑動視窗(Sliding Window) - TCP Header ![image](https://hackmd.io/_uploads/rJuLsS_L6.png) - 三項交握建立連線 ![image](https://hackmd.io/_uploads/r1fD2SuUp.png) - 資料確認與重送 - A 傳送 packet1 給 B - B 回應 ACK 封包給 A - 如果A在時間內沒有收到B的ACK封包A就會重新傳送 packet 給 B ### 5.3 TCP vs. UDP ![image](https://hackmd.io/_uploads/SykVpHdI6.png) ## 6. Application Layer ### 6.1 HTTP(Hyper Transfer Protocol ,超文本傳輸協定) - 全球資訊網( www )的網路通訊的基礎 - 用於網頁前後端溝通,瀏覽器向伺服器發送請求,伺服器回傳相應的資料 :::info HTTP Request Method - Get: - 較 post 不安全 - 訊息會顯示在head,body 不傳資料 - 傳遞的參數會在URL上顯示 - 流程: - 瀏覽器發出Get請求,只產生一個TCP封包 - 伺服器回應200 ,表示請求成功,同時返回資料 - Post: - 較Get安全 - 將參數放至body中再發送request - 不會在 URL 看到參數,適合用於隱密性較高的資料, EX: 登入的帳號、密碼等 - 流程: - 瀏覽器發送 Get 請求,只產生一個 TCP 封包 - 伺服器回應 200 ,表示請求成功,同時返回資料 - Put:新增一項資料,如果存在就覆蓋過去(維持一筆資料) - Patch:附加新的資料在已經存在的資料後面(資料必須已存在) - Delete:刪除資料 - Head:只會取得 HTTP header 的資料 - Option:可以了解 server 提供哪些溝通方法 ::: ### 6.2 DNS(Domain Name System,網域名稱系統) - 將Domain Name 轉換成 IP Address - Domain Name: moodle.ncnu.edu.tw - IP address: 163.22.5.234 - 暨大(Domain Name)-> google map 査詢地址(DNS Server)-> 南投縣埔里鎮大學路1號(IP address) - nslookup ‹Domain Name> ![image](https://hackmd.io/_uploads/H1vDkL_UT.png) :::info ### 樹狀階層式架構 ![image](https://hackmd.io/_uploads/Hy2klPOLp.png) ![image](https://hackmd.io/_uploads/H1oQlvu8T.png) 如何查找DNS - FQDN(Fully Qualified Domain Main,完整網域名稱) = Host Name + Domain Name - ex. www.google.com、www.youtube.com - `/etc/nsswitch.conf` - 定義了解析的依序優先順序,決定先要使用 /etc/hosts 還是 /etc/resolv.conf 的設定 - files (本機檔案): ex. /etc/hosts 、 /etc/passwd - `/etc/hosts` - hostname 對應到IP 的檔案 - > /etc/hosts 加上`1.2.3.4 google.com` 後輸入 `google.com` 會連到IP位置 `1.2.3.4` 的電腦上 - `/etc/resolv.conf` - 解析時使用的 DNS Server 的IP - > `nameserver 8.8.8.8` DNS 查詢發送到 Google 的 DNS server ![image](https://hackmd.io/_uploads/BymjxLOI6.png) ::: ### 6.3 FTP( File Transfer Protocol) - 用於檔案傳輸,將共享檔案存放在FTP Server,讓一般使用者可以透過網路來下載或上傳。他的重點是在異質性電腦之間、以及遠距離的檔案共享使用 - Client-Server 模型 - FTP Server :提供檔案的 Server 端。 - FTP Client :透過 FTP 連接到 Server ,執行上傳或下載操作的 CIient 裝置 - 20 port:傳遞資料 - 用於實際的檔案資料傳輸(下載或上傳檔案) - 21 port:傳輸流程控制 - 進行身分驗證,輸入帳號、密碼等指令 :::info Active MODE - 由 Server ==主動==向 Client 發起傳送資料請求 - ![image](https://hackmd.io/_uploads/rkLs-8uI6.png) - Client 透過 Command Port (1026)向 Server 的 Command Port (通常是 21 )發送連線請求,同時告知 Server 自己的 Data Port 是 1027 (N+I) - Server同一個ACK到Client的Command Port(通常是21)發送連線請求,同時告知Server自己的Data是1027(N+1) - Server 從自己的 Data Port (20) 向 Client 在 Step 1 指定的 Data Port ( 1027 )建立連線 - **當連線建立成功後**, Client 會向 Server 的 Data Port ( 20 )發送一個確認 (ACK) ::: ::: warning ### 發生的問題 - FTP的主動模式可能受到防火牆的阻擋,因為它需要在外部網路和內部網路之間建立一個由Client指定的隨機port(1026)的連線。 ::: :::info ### Passive Mode 被動模式 - PASV 模式 - Server==被動==等Client來連線(Client主動連線) - 讓Server開啟一個port,Client主動連線至Server > 在 active mode 下,client 會告訴 Server:「我用port N 當作 data port」 > 在 passive mode 下,client 會告訴 Server:「我是使用passive mode 喔」 ![image](https://hackmd.io/_uploads/B1iSELOUT.png) - Client主動跟Server連線後,告訴Server使用passive mode - Sever 回 ACK 並告訴 Client 自己開了一個 Data port(2024) - Client主動跟剛才Server指定的data port連線 - 最後Server回一個ACK給Client的data port ::: ### 6.4 DHCP(Dynamic Host Configuration Protocol,動態主機組態協定) - DHCP 使裝置能夠在連接到網路時自動獲取相關配置(IP Address 、子網路遮罩、 DNS sever address 等) > DHCP Server(餐廳服務生):主動詢問裝置需要多少個IP地址,然後提供相應的網路配置要連線的裝置(客人):進入網路的設備,ex. 電腦、手機等 > 客人到餐廳之後,餐廳服務生會根據人數安排座位,並提供餐具、菜單...... - 運作步驟 - **DHCP Discover** : Client 發送一個 DHCP Discover 封包(廣播訊息),通知網路上的 DHCP Server :「我需要一個 IP 地址」 - **DHCP Offer** : DHCP Server 收到 Discover 封包後,回應一個 DHCP Offer 封包,其中包含一個可用的 IP 地址、子網路遮罩、網關(gateway)、 DNS 伺服器等 - **DHCP Request** : CIient 收到 DHCP Offer 後,發送一個 DHCP Request 封包,確認要使用的 IP 地址 - **DHCP Ack**: 同意 Client 可以使用這個 IP Address ![image](https://hackmd.io/_uploads/rkqNBIuIp.png) :::success ## Demo ### 以 netplan 設定網路靜態 IP - 更改 `/etc/netplan` 裡面的 `00—installer—config.yaml` - 注意縮排 ![image](https://hackmd.io/_uploads/r1lT8IdUp.png) - `sudo netplan try` - 如果設定正確,嚅要在 120 秒之內按 enter 確認 - `sudo netplan apply` - 完成 ![image](https://hackmd.io/_uploads/BJmzL8uI6.png) ::: ## 7 HTTP 協定版本 ### 7.1 HTTP 1.0 - 簡單的文本設定 - ==無==連線持久性(keep-alive) - 單一請求-回應模型,每個請求都需要建立新的連線,完成後即斷開 - 浪費頻寬、時間延遲 - 單路徑傳輸,一次只能處理一個請求 - 狀態碼 - HTTP 1.0主要使用標頭中的If-Modified-Since和Expires來做為緩存的判斷標準 ### 7.2 HTTP 1.1 - 連線持久性(keep-alive) - 可以使用同一個 TCP 連接來重複多個 HTTP 請求,預設 keep-alive,避免重新建立連線 - 管道化 - 允許在同一連接上並行發送多個請求,但回應還是按照請求的順序返回 - 狀態碼 100 (Continue) - 引入了狀態碼 100,改進了對應 client 端發送正文的機制,避免不必要的頻寬浪費 - 更多請求方法 - 新增了PUT、PATCH、DELETE、CONNECT、TRACE 和 OPTIONS 等請求方法 - Host 標頭 - 支援多虛擬主機,使用Host標頭字段指定伺服器的域名 - > 現在在一台伺服器上可以存在多個虛擬主機,並且會共享同一個IP。所以加上host字段之後,就可以將請求發往同一台伺服器上的不同網站。 - > 後面會有 demo - 快取機制 - 引入更多的緩存策略,例如 Etag、If-Modified-Since...透過這些可以更優化緩存的哀 ### 7.3 HTTP2/SPDY **SP**ee**DY** - 提高網頁載入速度,減少延遲 ![image](https://hackmd.io/_uploads/H1kZOIdIa.png) - 二進制協定 - HTTP/2將資料轉換為二進制格式,而不再使用向HTTP/1那樣的文本格式,使得資料傳輸更加高效。 - Request multiplexing - 允許在同一個連接上並行交換多個請求和回應,避免了在 HTTPY 中的「頭部阻塞 (head-of-line blocking, HOL)」的問題。 - > 如果有任一個請求要操作很久或封包流失,那就會阻塞整個pipeline 的工作。 - Header 壓縮 - 使用 HPACK 壓縮標頭,減少了傳輸的大小。 - 優先請求順序 - 每個請求都有唯一的編號,並可以指定優先級,伺服器可以根據優先級進行回應,提高效能。 - Server Push - server 可以在 client 端需要之前主動推送資源,加快網頁載入速度。 ### 7.4 HTTP3/QUIC :::info ### QUIC - **Q**uick **U**DP **I**nternet **C**onnection - **連線建立(Connection Establishment)** ![image](https://hackmd.io/_uploads/SJ4ytLdUT.png) - **多路複用(Multiplexing)** > TCP Head of Line Blocking (HOL Blocking) 問題:在TCP 連線中,一個封包的遺失會導致整個連線的傳輸被卡住,直到封包被重新傳送。 - 允許在同一連線上進行多個 Stream 的資料傳輸。當某一個 Stream 中的封包遺失時,僅影響該 Stream 的傳輸,其他 Stream 不受影響,有效避免HOL Blocking 的問題 - **封包遺失恢復 (Loss Recovery)** - 在TCP 中,封包遺失恢復策略使用序列號標記封包,接收端回傳帶有相應序列號的ACK - TCP 重傳歧異問題:雖以區分是接收初始封包還是重傳封包的ACK,可能影響RTT和壅塞控制演算法 - QUIC 解決方案:使用唯一的封包編號 (unique packet number),每次傳送都有新的編號,解決了 ACK 的歧異問題,提高了 RTT 準確度,降低封包重傳反應時間 - **流量控制 (Flow Control)** - 流量控制限制 client 端傳輸資料量,接收端只保留相對應大小的接收 buffer - QUIC 使用連線層和 Stream 層流量控制,避免單—Stream佔用過多buffer,防止HOL Blocking - **Connection Migration** - QUIC 使用64位獨立 Connection ID 來識別連線,由 client 端在建立連線時隨機產生。 - Connection ID 允許在 client 端IP變動時,仍能平順處理Connection Migration 問題。 - client 端可以使用舊的 Connection ID 在新IP 位址上傳送封包,接收端透過Connection ID 識別連線,確保封包正確接收 ::: ![image](https://hackmd.io/_uploads/SyE-KLO8a.png) ## Demo :::success #### 使用telnet上網 > Review: Name-based Virtual Host > 在同一個server上架有不同網站,不同網站間依據名稱判定 - 沒有指定host->預設頁面 ![image](https://hackmd.io/_uploads/HkgZqU_Up.png) ::: # IPTABLE - 透過設定規則,保護我們的網路環境主要功能: - 擋掉不想要的封包 - 允許想要的封包 - 轉傳封包 - 沒有防火牆 ![image](https://hackmd.io/_uploads/rkuaKvOLT.png) ## iptable ### 概述 - linux 上的一種防火牆軟體使用者可以下指令操作 iptables - iptables 會根據指令去操作 Linux kernel 中的 Netfilter 模組,來實現防火牆功能 - 因為是操作 kernel 的模組,所以使用 iptables 時需要有超級使用者權限(加 sudo) ### 架構 - 由表 (table) 、鏈 (chain) 、規則 (rule) 組成 - iptable"s" 、顧名思義有多個 table - table 裡有幾個 chain chain 裡可以有很多條 rule ![image](https://hackmd.io/_uploads/HkXXqvdI6.png) ### 運作方式 ![image](https://hackmd.io/_uploads/B1-85vuIa.png) - 封包在不同時機點,會由對應 table 的 chain 負責處理 ### table&chain - 各個 table 也有各自對應的 chain - 常用的 table 與對應的 chain · - filter (過濾器) - 功用:過濾封包(同不同意讓封包通過) - 對應的 chain : - INPUT (管理進入本機的封包) - OUTPUT (管理本機送出的封包) - FORWARD (管理轉送的封包) :::success ```cpp= sudo iptables -A INPUT -j DROP ``` 這指令是甚麼,下了會發生甚麼事? ::: - nat (位址轉換 Network Address Translation) - 功用:對封包來源/目的地的 IP / port 轉換 - 對應的 chain: - PREROUTING (在路由前處理規則) - POSTROUTING (在路由後處理規則) - OUTPUT (更改本機送出的封包要去哪裡) :::success ```cpp= sudo iptables -t nat -A PREROURING \ -d {我的主機 IP} -p tcp --dport 80 \ -j DANT --to {我的主機 IP}:8080 ``` 這指令是甚麼,下了會發生甚麼事? ::: ![image](https://hackmd.io/_uploads/H1KaoDuIa.png) - filter OUTPUT 和 nat OUTPUT 差異 - filter OUTPUT :是否同意封包從本機出去 - nat OUTPUT: 更改本機送出的封包要去哪裡 - table & chain: - ==**nat**== table: 讓封包知道下一步該往哪走(跟流向有關) - **PREROUTING** chain: - 要讓入境的封包知道==入境後==該怎麼走?或轉機的封包去哪裡轉機 - ex. 最終目的地是埔里,線抵達台灣,埔里怎麼去 - **POSTROUTING** chain: - 讓要出境的封包知道==出境後==該往哪走? - ex. 最終目的地是日本,現在人在飛機上,要飛往哪 - **OUTPUT** chain: - 讓在內部準備要出境的封包知道==該去哪個機場==才能出境 - ex. 最終目的地是日本,現在人在埔里,去哪個機場 - ==**filter**== table : 檢查封包能不能往那走( 跟過濾有關) - **INPUT** chain: - 讓不讓封包==入境== - ex. 現抵達台灣想要==去埔里==,海關,要不要放你進台灣 - **OUTPUT** chain: - 讓不讓封包==出境== - ex,現在我要離開台灣==去日本==,海關,能不能放我進日本 - **FORWARD** chain: - 讓不讓封包==轉機== - ex. 我從泰國來,目的要去日本 :::info **其他少用的table** - mangle - 用於修改封包的 header - raw - 用於停止對封包的追蹤 - securlty - 用於設定 SELinux 對封包的處理 ::: ![image](https://hackmd.io/_uploads/ryRdhwdU6.png) > 綠色方塊是table,下方的白色方格是chain - `nat PREROUTING` - 可以更改封包目的地 (ex: IP 、 port) - 藉此可以做到轉送封包的功能 - 就像之前講過的 ssh tunnel、proxy server - ex :連到我的主機 8080 port 的封包,目的地 192.1681.101 的 80 port ```cpp= sudo iptables -t nat -I PREROUTING \ -p tcp --dport 8080 -j DNAT --to 192.168.1.101:80 ``` - 路由判斷 - 決定封包要去哪裡,是要進入主機?還是轉送出去? - 根據routing table 規則 ![image](https://hackmd.io/_uploads/SJBKpvdU6.png) - 路線 A - 在路由判斷後,若封包要進入本機時會走這條 - 會先由 filter table 的 INPUT chain 來決定封包能不能進入本機 - ex:拒絕進來主機的封包 - ```c= sudo iptables -I INPUT -j DROP ``` - 路線 B - 在路由判斷後,若封包沒有要進入本機時會走這條 - 會先由 filter table 的 FORWARD chain 來決定封包能不能?? - ex:拒絕轉送目的是 192.168.56.135 的封包 - 路線 C - 當封包要從本機送出時會走這條 - 路由判斷後可以在 nattable 的 OUTPUTchain 更改封包的目的地(不常用 ) - 再由 filtertable的 OUTPUT chain 決定封包可不可以送出去 ~~- ex : nat OUTPUT 更改封包目的地,從 1 之 3 , 4 改成 8 8 , 8~~ 不太對 - `nat POSTROUTING` - 可以更改封包的來源IP - 比如我在學校內網想要連到外網,需要做來源IP的位址轉換(從我的主機 IP) - ex:從學校防火牆對外網卡 (eth1) 送出的封包,都把來源IP換成防火牆的對外 IP(178.87.12.34) ``` sudo iptables -t nat -I POSTROUTING -o eth1 -j SNAT --to 178.87.12.34 ``` ### rule - 設定給 iptables 的規則,若封包符合該 rule 就會執行相應的動作 - ![image](https://hackmd.io/_uploads/SybN0D_LT.png) - rule 有處理的順序性 - 若符合排在前面的 rule ,就會去執行該 rule 相應的動作,並且不會再往下繼續判斷 (類似 if , else if) ### policy - 封包的預設處理方式,如果都沒有符合的rule時就會執行這裡 ### traget - 符合規則時要進行的動作 - 常見的 target: - ACCEPT :允許 - REJECT: 拒絕,會告知發送者 - 會送 RST 封包,表示連線被拒絕 - 發送者會知道有主機存在 - DROP:丟掉,不會告知發送者 - 不會回傳封包,讓發送者等到 timeout - 發送者沒辦法知道有主機存在 - 對外規則使用 DROP 會較安全 - SNAT:修改封包的來源IP - DNAT:修改封包的目的IP 和 port :::info 補充其他 target - MASQUERADE:動態 SNAT - REDIRECT : 更改封包的目的 port - LOG : 記錄到 log,預設路徑 : `/var/log/kern.log` 和 `/var/log/syslog` ::: ### 指令操作 #### 查看rule `sudo iptables [-t table] -L [-nv --line-numbers]` - `-t`:選擇table,預設是filter table - `-L`:列出 rule - -n:不把IP 位址解析成域名,所以執行速度較快 - 一般都會使用,不然會等 dns 解析很久 - `-v`:列出更多資訊 - `--line-numbers`:顯示編號(刪除 rule 時會需要這個編號) - target:進行的動作 - prot:protocol,使用的封包協定,主要有tcp, udp, icmp - opt:額外選項說明 - source:封包的來源IP - destination:封包的目的地IP和port #### 更改policy > policy是預設的封包處理方式 (default target),當封包都不符合設定的規則時就會依照 policy 設定的方式處理 `sudo iptables-[-t table] -P ‹INPUT, OUTPUT, FORWARD...> ‹ACCEPT, DROP,...>` - `-t`:選擇 table - `-P`:policy・後面接chain 和 target - 小寫`-p` 是`protocal` - 把fiter table 的INPUT policy 更改為 DROP: ![image](https://hackmd.io/_uploads/r15AkduUp.png) ![image](https://hackmd.io/_uploads/SJgVgdd86.png) ![image](https://hackmd.io/_uploads/HJV_euOLT.png) - 為了安全會把 policy 改成 DROP,類似白名單 - ![image](https://hackmd.io/_uploads/r15AkduUp.png) - BlueT 建議不要去改 policy,而是會在規則都確定沒問題後,在 chain 的最後面加 DROP 規則,目的是避免一些操作錯誤的情況 - 例如 ssh 連線到主機設定 iptables、用flush 刪掉所有規則時,若 policy 為DROP,連 線就會被切掉 #### 新增rule `sudo iptables [-t table] [-A or -I] <input, output,FORWARD...> -j <ACCEPT, DROP, REJECT> [-i -o -p -s -d...]` - `-t`:選擇table,後面接table名稱 - `-A` :append,新規則加在舊規則後面,後面接 chain 名稱 - `-I`:insert・新規則加在舊規則前面・後面接chain 名稱 - `-j`:jump・後面接動作(target) - 以類型來分類其他參數: - 網卡 - `-i`:in interface,封包進來的網卡名稱 ```cpp= sudo iptables -I INPUT -i enp0s3 -j ACCEPT ``` - `-o`:out interface 封包出去的網卡名稱 - IP位址 - `-s`:source address,封包來源IP地址 ```cpp= sudo iptables -I INPUT -S 192.168.101.1 -j ACCEPT ``` - `-d`:destination address,封包目的IP 位址 ```cpp= sudo iptables -I INPUT -d 192.168.101.1 -j ACCEPT ``` - `!`:可用在-和-d之前•表示非該IP ```cpp= sudo iptables -I INPUT ! -d 192.168.101.1 -j DROP ``` - 協定: - `p`:protocol ,封包使用甚麼協定(tcp、udp、ICMP) ```cpp= sudo iptables -I INPUT -p ICMP -j DROP ``` - port,當-p指定tcp或udp時可以使用 - `--sport`:source port,封包來源port ```cpp= sudo iptables -I OUTPUT -p tcp --sport 80 -j ACCEPT ``` - `--dport`:destination port,封包目的port ```cpp= sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPT ``` - 模組 - `-m`:呼叫iptables的模組,ex:conntrack模組 ```cpp= sudo iptables -I OUTPUT \ -m conntrack --ctstate "ESTABLISHED,RELATED" -j ACCEPT ``` :::info conntrack 模組 - 記錄連線的狀態: - NEW:新建立的連線 - ESTABLISHED:已建立的連線、NEW封包的回應封包 - RELATED:新的連線,但與已建立的連線相關 - ex: `ftp` `21 port` 建立連線, `20 port` 傳送資料 - INVALID:無效,無法識別狀態的封包 - UNTRACKED: 在raw 表已被關閉追蹤的封包 - ex: `-A PREROUTING -d 172.20.0.10/32 -p tcp -m tcp --dport 53 -j NOTRACK` - 查看conntrack追蹤到的封包 `sudo conntrack -L` ![image](https://hackmd.io/_uploads/H1YOf__La.png) - 缺點:占用記憶體空間 ::: 組合這些參數 ```CPP= sudo iptables -I INPUT \ -i enp0s3 -s 192.168.1.101 \ -p tcp --dport 80 -j ACCEPT sudo iptables -I OUTPUT \ -m contrack --ctstate "ESTABLISHED, RELATED" - j ACCEPT ``` :::success `-A`和`-I`比較 - 一開始設定如下 - ![image](https://hackmd.io/_uploads/rJI9mdOI6.png) ![image](https://hackmd.io/_uploads/H1kiXOdIp.png) ![image](https://hackmd.io/_uploads/BJDsXddUp.png) ::: #### 刪除rule * `-D`:Delete,刪除chain裡對應編號的rule `sudo iptables [-t table] -D <INPUT,OUTPUT,FORWARD...> <rule 編號>` * `-F`:Flush·清除chin或table裡全部的rule `sudo iptables [-t table]-F <INPUT,OUTPUT,FORWARD...` * 不加chain可以删除這個table的所有規則 ![upload_f47a601970550cc458c88ff8cb8a96e0](https://hackmd.io/_uploads/B1pvIdO86.png) * 環境: * 在http server主機上設定iptables·對外網卡是eth1 * INPUT和OUTPUT chain的policy都是DROP * 要求: * Good user可以透過eth1網卡連線到http server * Bad user和其他沒提到的user都無法透過eth1網卡連線到http server * 讓Good user可以透過eth1網卡連線到http server ::: spoiler 解答 ::: * 讓Bad user和其他沒提到的user都無法透過eth1網卡連線到http server ::: spoiler 解答 ::: 同意Good user連進來 ```sudo iptables -A INPUT -i eth1-s 192.168.0.101-j ACCEPT``` 這樣就夠了嗎? 還要同意把封包送回去 ![image](https://hackmd.io/_uploads/HkQ_4u_Up.png) ![image](https://hackmd.io/_uploads/BJViEuuI6.png) ![image](https://hackmd.io/_uploads/ByiNBd_IT.png) ![image](https://hackmd.io/_uploads/ByQPS_OUa.png) :::info **Stateful Firewall** vs **Stateless Firewall** - **Stateful Firewall**無狀態防火牆 - 不記錄封包的狀態 - 例子: - 同意來源地為 A 或 B 的封包進入我的主機,其它都拒絕 - 本機出去的封包 policy 為 DROP - 回傳封包時需要在規則設定**目的地為 A 或 B** 的封包要同意送出 - 特點: - 每個封包進出的規則都需要各寫一次(如前面的做法 1) - **Stateless Firewall**無狀態防火牆 ::: ### 儲存 iptables 設定 - iptables 不會自動保存和載入設定,關機就會消失:cry: - 保存方法: - 先把設定 save 到檔案裡,要用的時候再 restore 回去 1. `iptables-save > 設定檔` 把輸出的結果寫入到設定檔裡 (可以自己決定,不過通常會存到 `/etc/network/iptables.up.rules`) - `iptables-save` 可以輸出目前 iptables 的設定 2. `iptables-restore < 設定檔` 把設定檔的內容載入到 iptables > 直接改 iptables 設定可能會有改錯的風險 > - 如果是用 ssh 連線到主機設定 iptables,設定時不小心把 ssh 連線設定成 DROP,連線就斷了 > - 那測試規則沒問題再套用呢? ### iptables-apply - 測試新的 iptables 規則 - 會詢問使用者 y/N,選 y 就會套用,選 N 或是太長時間沒有回應就會變回舊的規則 - 用 `-t` 可以設定這個時間的長短 - 做法:先把新加的規則寫到設定檔裡,再對設定檔下 `iptables-apply` - 指令: - `sudo iptables-apply 設定檔` - 後面不加設定檔會以預設的路徑 : `/etc/network/iptables.up.rules` > 如果直接把新規則寫到設定檔去 apply,但最後 apply 失敗了需要還原,卻忘記怎麼還原成一開始的設定,設定檔就壞了 :fearful: > - 除了一開始就規劃好**一個正式設定檔**和**一個測試設定檔**,來避免改錯時無法還原之外? > - 如果可以把要測的規則,寫在另一個獨立的檔案? ### iptables-apply -c - 測試iptables command - 把新規則先寫到原本的設定檔再去apply,可能會有無法還原的風險,那可以先把指令寫到其他檔案裡,用`-c`去apply ### iptables-apply -w - 將測試後沒問題的測試設定檔,寫入正式的設定檔 - 指令: - `iptables-apply -w {被寫入的檔案} {要測試的設定檔}` - 只寫一個檔名,要測試的檔案會套用預設路徑: `/etc/network/iptables.up.rules` - 在 apply 成功後,會把後面設定檔的內容,寫到前面的設定檔

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully