KaiWhat
    • 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
    - Book mode: https://hackmd.io/@ncnu-opensource/book # IP Firewall [TOC] --- ## Netfilter ![image](https://hackmd.io/_uploads/rJTFtEQG1e.png) ## iptables - iptable架構 由table、chain、rule所組成 - <font color=#f00>Filter</font> 表:最常用,負責基本的封包過濾。這是 iptables 的預設表,主要處理進出和轉發的封包。 - <font color=#f00>NAT</font> 表:也很常用,負責網路位址轉換(Network Address Translation),例如改變封包的來源或目的 IP 位址,通常用於讓內部網路設備連接到外部網路。 - <font color=#f00>Mangle</font> 表:不太常用的table,用於修改封包的特定標頭資訊,如改變 TTL(Time To Live)。適合在需要深層修改封包屬性的情境下使用。 ### raw - 不常用的 table - 用於控制哪些封包需要進行連線追蹤 ### filter - 常用的 table - 專門用於封包過濾,根據定義的規則來允許、阻擋封包,是防火牆功能的核心 ### nat - 常用的 table - 專門用於網路位址轉譯 (NAT) 的 table ### mangle - 不常用的 table - 常用於修改封包的標頭或屬性 ### security - 不常用的 table - 專門與 SELinux (Security-Enhanced Linux) 或 AppArmor 等 Linux 安全模組 (Linux Security Modules, LSM) 配合使用 ## Chains iptables 中有五個預先定義好的chain - Prerouting - Input - Forward - Output - Postrouting ### filter table 的 chain ![image](https://hackmd.io/_uploads/B10Qs4Qz1e.png) - `sudo iptables -t filter -L` 系統會顯示 filter 表中所有的chain和rules,包含每個規則的條件、匹配的封包數量、來源與目的地 IP 地址等資訊。 | chain | 用途 | | -------- | -------- | | `INPUT` | 過濾進入的封包 | | `OUTPUT` | 過濾送出的封包 | | `FORWARD` | 過濾要轉送的封包 | ### nat table | chain | 用途 | | -------- | -------- | | `PREROUTING` | 在封包進入 routing decision 之前,對其進行目的地位址轉譯(DNAT) | | `INPUT` | 因為已經過了 routing decision,所以僅能對封包進行本機的 port 轉發,僅在特殊情況使用 | | `OUTPUT` | 特殊情況下,修改本機生成封包的目的地位址 (DNAT),可用來做透明代理 (transparent proxy) | | `POSTROUTING` | 在封包離開系統後、發送到網路之前,對其進行來源地位址轉譯 (SNAT) | ### Rules - user 對 iptables 設定的規則,有符合才會有對應的動作 - 一條一條往下看 - 一有符合的就 break,後面的規則就不會跑到了 (short circuit) #### policy policy 設定了一種「預設行為」,可以理解為鏈的最後防線。當封包在鏈中的所有規則都無法匹配,最終會使用 policy 所定義的處理方式。 #### Target | Target | 用途 | | -------- | -------- | | `ACCEPT` | 允許封包 | | `REJECT` | 拒絕封包,且會透過回傳 RST 封包通知發送封包的人連線被拒絕,也因為會有回應所以發送者會知道主機存在 | | `DROP` | 丟棄封包,不會對發送封包的人有任何回應,會讓連線自己 timeout,因為沒有回應所以發送者也無法判定主機是否存在。攻擊者會等待更多時間(老師推薦) | `DNAT` | 修改封包的目的地位址 | | `SNAT` | 修改封包的來源地位址 | | `REDIRECT` | 修改封包的目的地的 port | | `MASQUERADE` | 動態的 SNAT | | `LOG` | 記錄到 `syslog` | #### 跟 filter table 相關 -> 要做什麼操作? ACCEPT:接受 REJECT:拒絕 DROP:丟棄 LOG:紀錄 #### 跟 nat table 相關 - DNAT:修改封包的目的位址 - SNAT:修改封包的來源位址 - REDIRECT:修改封包目的地的 port - MASQUERADE:動態的 SNAT ## 運作流程 ![image](https://hackmd.io/_uploads/HJEIyBmzkl.png) ![image](https://hackmd.io/_uploads/r1AP1SQzkg.png) #### 可以使用以下幾個指令來查看路由表(Routing Table) - ==route==: 顯示當前設備路由表 - ==route -n==: 查看路由表,以數字格式顯示,不解析 IP 為主機名稱 - ==ip route 或 ip r==: 顯示路由表(使用 iproute2 套件) - #### 查詢各種log記錄檔 - ls /var/log: 列出記錄系統和應用程序的各種活動和事件的文件 Search domain: `cat /etc/resolv.conf` ## 指令操作 - `iptables [-t table] {-A\|-C\|-D...} chain rule [options...]`: |指令|說明| |---|---| |`-t table`|指定 iptables 所使用的表。常見的表有:<br> `filter`(預設表):用於過濾封包。<br> `nat`:用於網路位址轉換(如 SNAT、DNAT)。<br> `mangle`:用於改變封包內容。<br> `raw`:用於封包處理的更低層次操作。| |`-A`| 新增規則到指定的鏈(例如 INPUT、OUTPUT、FORWARD)。| |`-C`|檢查是否有規則存在於指定鏈中。| |`-D`|刪除規則。| |`chain`|規則鏈的名稱,例如:<br> `INPUT`:針對進入的封包。<br> `OUTPUT`:針對發出的封包。<br> `FORWARD`:針對轉發的封包。| |`rule`|定義封包匹配條件的規則(如來源 IP、目標 IP、協定等)。| |`[options...]`|額外的選項,如指定封包處理的動作(-j ACCEPT、-j DROP 等)。||`-t table`|指定 iptables 所使用的表。常見的表有:<br> `filter`(預設表):用於過濾封包。<br> `nat`:用於網路位址轉換(如 SNAT、DNAT)。<br> `mangle`:用於改變封包內容。<br> `raw`:用於封包處理的更低層次操作。| :::success 好文分享 - [DROP vs. REJECT](https://www.chiark.greenend.org.uk/~peterb/network/drop-vs-reject) ([中文翻譯](https://www.jyh.im/2024/11/01/Drop-versus-Reject/)) - [iptables REDIRECT vs. DNAT vs. TPROXY](https://gsoc-blog.ecklm.com/iptables-redirect-vs.-dnat-vs.-tproxy/) ::: - `sudo iptables -t filter -L`:查看 filter table 內有哪些 chains 跟 rules - `sudo iptables -t nat -L`:查看 nat table內的chains & rules - `sudo iptables -t mangle -L PREROUTING`:查看 mangle table 的 PREROUTING chain 內的規則的指令 - `sudo iptables -t filter -L`:修改filter table INPUT chain 的policy - `sudo iptables -nL --line-numbers`: | 選項 | 說明 | |---|---| | `-n` | 禁止解析 IP 地址、端口號等信息,直接顯示數字形式的 IP 和端口,這樣可以加速查詢過程。| | `-L` | 列出所有的鏈(chains)及其中的規則,例如 `INPUT`、`OUTPUT`、`FORWARD` 等。 | | `--line-numbers`| 在每條規則前顯示行號,這對於修改或刪除特定規則非常有幫助。 | #### 其他的參數 - -n 不嘗試把 IP 位址解析成域名 ex:`sudo iptables -t nat -L -n` - -v 更多的資訊 ## 設定rule `sudo iptables [-t table] {-A|-I}` - `-A, --append`: 會將規則加在舊有規則的後面 - `-I, --insert`: 會將規則加在舊有規則的前面 - `-D, --delete`: 刪除指定的 rule - `-R, --replace`: 取代指定的 rule - `-F, --flush`: 刪除指定的 chain 或是 table 內的所有 rules - `-j, --jump`: 指定符合規則時會執行哪個 target # filter 用來處理封包的過濾,用來判斷封包是否應該被接受或丟棄 一般用來使用的chains有: - `INPUT`:控制進入本機的封包 - `FORWARD`:控制通過本機、但不進入或離開本機的封包(例如路由封包) - `OUTPUT`: 控制由本機發出的封包。 (Paco93720是我郭方朔) 針對網路介面卡設定規則 - `-i,-in-interface `:封包進入系统時經過的網卡名稱 `sudo iptables -t filter -I INPUT -i eth0 -j ACCEPT` - `-o,--out-interface:封包傳出系統時經過的網卡名稱` `sudo iptables -t filter -I OUTPUT -o eth0 -j ACCEPT` ## 針對IP位址設定規則 - `-s,--source`:封包的來源IP位址 `sudo iptables -t filter -I INPUT -s 192.168.56.11 -j DROP` # NAT 用來進行網路位址轉換,有時候配合 accept 或轉發動作進行位址改寫 ### SNAT(Source NAT,源地址轉換) - 用於內部網路設備發送請求到外部網路時,將內部設備的私有 IP 地址轉換為公共 IP 地址。 ### DNAT (Destination NAT,目標地址轉換) ### 統整 | | SNAT | DNAT | | -------- | -------- | -------- | | 功能 | 更改封包的來源 IP | 更改封包的目的 IP | | 使用場景 | 讓內網主機可以連線外網 | 讓外網能主動連線內網主機 | |類型|說明|用途|例子| |----|----|----|----| |**SNAT**|**Source NAT**:將內部設備的私有 IP 轉換為公共 IP。|內部設備發送請求到外部網路時,使用公共 IP 進行通信。|內部設備 `192.168.1.2` 通過路由器發送請求,源 IP 轉換為 `203.0.113.1`。| |**DNAT**|**Destination NAT**:將外部請求轉發到內部網路設備。|用於端口轉發或公開內部服務,如 Web 伺服器。|外部設備通過公共 IP `203.0.113.1` 發送請求,轉發給內部的 Web 伺服器 `192.168.1.100`。| |**PAT**|**Port Address Translation**:轉換源 IP 並且修改端口號。|多個內部設備共享同一公共 IP,使用不同端口。|內部設備 `192.168.1.2` 和 `192.168.1.3` 共用公共 IP `203.0.113.1`,但使用不同端口(如 80 和 443)。| <div style="background-color: #d0e7ff; padding: 10px; border-radius: 5px; color: purple;"> ### 範例情境 #### 情境設定 - 你家裡的電腦有一個私有 IP 地址,假設是 192.168.1.2,這個 IP 只在你家裡的網路內有效。 - 你家裡有一個路由器,它有一個公共 IP,假設是 203.0.113.1,這個 IP 可以在互聯網上被識別。 - 你想連接 Google 的伺服器 8.8.8.8,但 Google 伺服器只會知道 203.0.113.1,而無法直接識別 192.168.1.2。 #### 過程一:從內部網路出發(MASQUERADE / SNAT) 1. 你的電腦 192.168.1.2 想要連接 8.8.8.8(Google)。 2. 你的路由器會檢查這個請求,並將來源 IP 地址 192.168.1.2 轉換成它的公共 IP 203.0.113.1。 3. 這個步驟會使用 MASQUERADE(即動態 SNAT),路由器會自動選擇一個端口,並將這個請求的來源地址和端口變更為 203.0.113.1:端口號。這個端口號是路由器用來標識這個請求的。 - 這是 SNAT 的一種特定情況,主要用於情境中你的公共 IP 是動態分配的,並且你不希望每次 IP 改變時都要重新設置路由規則。 4. 然後這個修改過的請求會送出去到 8.8.8.8,Google 就會看到來自 203.0.113.1 的請求,並會回傳給 203.0.113.1。 #### 過程二:從外部伺服器回傳(PAT / NAT) 5. Google 伺服器 8.8.8.8 收到你的請求後,它會回傳一個響應,這個回應會發送到 203.0.113.1(這是路由器的公共 IP)。 6. 路由器的 NAT 會通過查看 NAT 映射表(NAT Table),來得知「這個請求是哪個內部 IP 發出的」來確定把回應發送到哪個內部設備。 - 路由器會用 PAT(端口地址轉換)來識別是哪台內部設備發送的請求,這是根據請求的端口號來匹配回應的。 - 假設你家的電腦發出的請求被路由器映射為 203.0.113.1:1001,那麼路由器就會知道回應應該發送給 192.168.1.2(這是內部設備的私有 IP)。 7. 路由器會根據記錄將回應發送到 192.168.1.2,你的電腦就收到了 Google 的回應。 #### 總結 - MASQUERADE 用來動態地將內部設備的私有 IP 轉換為路由器的公共 IP,並選擇一個端口來區分不同的請求。 - SNAT 是一個更廣泛的術語,指的是任何將內部 IP 轉換為公共 IP 的過程。 - PAT 是在同一個公共 IP 下,通過端口來區分不同內部設備的技術。 </div> ## MASQUERADE 有時候,防火牆(Firewall)取得的外網 IP 並非固定 IP,可能會隨時間變動。在這種情況下,頻繁地更新 SNAT(Source Network Address Translation)的規則可能會很麻煩。MASQUERADE 針對此問題進行優化: - 自動尋找:自動尋找能連接到外網的網路介面卡。 - 自動設定:使用該介面卡的 IP 位址作為 SNAT 的來源 IP。 這樣一來即使外網 IP 發生變動,也能有效應對,減少手動調整的需求。 ## DMZ ![image](https://hackmd.io/_uploads/S1Bquw7GJe.png) 一個子網路,為組織的內部網路與外部網路(如網際網路)之間增加了一層額外的安全保護 **功能要求** - 外網可以直接連線 DMZ,但不能直接連線 LAN - DMZ 可以直接連線外網,但不能直接連線 LAN - LAN 可以直接連線外網,也可以直接連線 DMZ **環境** - Firewall 主機上設定防火牆 - DMZ 中有一台**對外開放**的 Web Server 主機,80 port 上有 web service - LAN 中有一台**不對外開放**的 Student 主機 - 外網透過連線到 Firewall 主機的 8080 port,可以連線到 Web Server 主機的 80 port - `INPUT`、`FORWARD`、`OUTPUT` 的 policy 都是 `ACCEPT`

    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