NCNU-OpenSource
      • 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
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners 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
    • 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 Help
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
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners 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
    2
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- tags: 1082, lsa --- - Book mode https://hackmd.io/@ncnu-opensource/By4H6JLNW [TOC] # linux 網路安全管理 - 安全 ## 防護 ### 1. Firewall 防火牆是一個監控傳入和傳出網路流量的網路安全裝置,並依據==規則==對進出流量做存取控制, 在 linux 中常見的就是 iptables 與 TCP wrapper iptables 與 tcp wrapper 的關係( iptables --> tcp wrapper --> service ) ![](https://i.imgur.com/zQwvoQl.png) [圖片來源: readhat - TCP Wrappers and xinetd](https://web.mit.edu/rhel-doc/5/RHEL-5-manual/Deployment_Guide-en-US/ch-tcpwrappers.html) #### 1.1. iptables 操作 linux 核心的 netfilter,可以從底層開始過濾更完全 ##### 1.1.1. iptables 在 linux kernel 核心的運作 ![](https://i.imgur.com/3t8NL20.png) ![](https://i.imgur.com/5tA9yAq.png) [圖片來源: Packet flow in Netfilter and General Networking](https://upload.wikimedia.org/wikipedia/commons/3/37/Netfilter-packet-flow.svg) 參照圖片: [封包進入 kernel 的 dataflow](http://web.archive.org/web/20170905131225if_/https://wiki.linuxfoundation.org/images/1/1c/Network_data_flow_through_kernel.png) ##### 1.1.2. 簡單的操作界面 iptables 設定相對複雜不易於學習,容易對資安或 linux 菜鳥造成心靈創傷 :cry: 所以可以透過較淺顯易懂的操作界面來設定 iptables,以 ufw 為例 **ufw** Uncomplicated Firewall ( ufw ) Ubuntu系統上預設的防火牆套件,規則設定指令簡單易讀 - 通過與否 - `allow` - `deny` - 管控對象 - `{port_num / service_name}`設定 port ```shell= sudo ufw allow 80 # 允許 80 sudo ufw allow 443 # 允許 443 sudo ufw deny 3389 # 封鎖 3389 sudo ufw deny 21 # 封鎖 21 sudo ufw allow ssh # 允許 22 ``` - `{port_num / service_name}/{tcp/udp}`指定 protocol, 沒加 protocol 預設 udp & tcp 一起 ```shell= ufw deny 53/tcp # 阻止通過 53 連接埠使用 tcp 協定連線本機 ``` - `from {ip}` 設定 IP ```shell= sudo ufw allow from 192.168.11.10 # 允許 192.168.11.10 的所有連線 sudo ufw allow from 192.168.11.0/24 # 允許 192.168.11.1~192.168.11.255 的所有連線 sudo ufw deny from 192.168.11.4 # 封鎖 192.168.11.4 的所有連線 ``` 參考:https://noob.tw/ufw/ :::info `uif` Userfriendly Iptables Frontend,也是一種便於設定的 iptables 界面 :arrow_right: 參考:[Ubuntu uif manpage](https://manpages.ubuntu.com/manpages/precise/man8/uif.8.html) ::: #### 1.2. tcp wrapper 由 tcpd 所控制,攔截 inet.d.conf 的內容,只能過濾 application layer 但也因此可以過濾範圍擴至 host name 常見支援之服務: telnet、ssh、sendmail、ftp、pop3 ##### 1.2.1. 設定檔 `/etc/hosts.allow` 設定服務允許通過的來源 IP `/etc/hosts.deny` 設定服務阻擋的來源 IP :::success **判定順序** 1. /etc/hosts.allow: 通過 2. /etc/hosts.deny: 擋掉 3. 兩個檔案規則都不符合: 通過 ::: **規則格式 ( hosts.allow, hosts.deny 通用 )** - 多個來源可用==空格==做區別 - 網域表示法不支援==遮罩== bit 數值表示( ex: 192.168.1.0/24 要用 /255.255.255.0) ```shell= { 服務名稱 }: {IP, hostname, 網域} ``` Ex: (規則) 本機全部的服務都接受, rsync 接受網域 192.168.1.0/24 與 10.0.0.100 其餘皆拒絕 `/etc/hosts.allow` ```shell= ALL: 127.0.0.1 rsync: 192.168.1.0/255.255.255.0 10.0.0.100 ``` `/etc/hosts.deny` ```shell= rsync: ALL ``` ##### 1.2.2 優點與限制 **優點** - 簡單好設定( hosts.allow / deny ) - 可以用 hostname 設定 **限制** - 作用在 application layer 無法往下過濾 - 支援限定的服務 :::info **支援服務的條件** - 由 super daemon (xinetd) 所管理的服務 - 即設定檔在 `/etc/xinetd.d/` 裡面的服務 - 有支援 `libwrap.so` 模組的服務 **libwrap查詢方式** `for name in {要查詢服務名稱}; do echo $name;ldd $(which $name) | grep libwrap; done` EX: ![](https://i.imgur.com/tT7InM8.png) ::: #### 1.3 iptables 與 tcp wrapper 的作用 layer ![](https://i.imgur.com/rE5D8d7.png) ### 2. IDS 通過監測網路流量來偵測惡意攻擊的軟體 當發現有入侵跡象會紀錄並通知系統管理員 #### 2.1. IDS 種類 ##### 2.1.1. HIDS (主機型入侵偵測系統, Host-based IDS) - 位置:安裝於要保護的主機中 - 分析主機內部活動( 系統 log, 系统Process, 文件完整性 ) - 缺點:佔用一定的系統資源 ![](https://i.imgur.com/e2XYCCc.png) ##### 2.1.2 NIDS (網路型入侵偵測系統, Network-based IDS) - 位置:安裝於被保護的網段中( 可以架設在防火牆的: 內 or 外 or 內 + 外 ) - 分析經過這網段的所有封包 - 缺點:需要多一台機器運作 IDS ![](https://i.imgur.com/EfW3B8t.png) :::info `Out-of-Band` 機器外加於原先的網路架構 此圖 IDS 的實現是透過 switch, router 等設備設定 port mirror 把所有流進的複製一份給 NIDS 做偵測用 好處是當 NIDS 主機掛掉,不會癱瘓整個網路,可以降低風險 ::: #### 2.2. 偵測方式 ##### 2.2.1. 不當行為偵測(misuse detection) - 特徵比對(signature-based detection),利用已知的攻擊事件建立出各種==攻擊特徵==資料庫 - 優: 誤判率較低 - 缺: 偵測率較低(新的攻擊入侵型態就抓不到) :::info **常見的 system 入侵徵兆** - 修改系統軟體與設定檔案 - 系統 crash 或 reboot - log 太短或是不完整 - log 有奇怪的 timestamp - log 的 permission 或 owner 很奇怪 - 不熟悉的 process **常見的 network 入侵徵兆** - 不斷的偵測機器上有提供的服務 - 從奇怪的地方連線過來 - 不斷的嘗試從遠端 host 連線過來 ::: ##### 2.2.2. 異常偵測(anomaly detection) - 透過統計模型 or 機器學習的方式建立==正常==行為的模式==基準==, 行為與之差異過大就視為異常行為 - 優缺點與特徵比對相反 ##### 2.2.3. 常見 IDS 介紹 | IDS | HIDS - NIDS | Unix | Linux | Windows | MacOS | | | -------- | -------- | -------- |---|---|---|---| | Snort | NIDS | V |V|V||老牌 IDS,有強大的社群支持| |Suricata|NIDS|V|V|V|V|Snort的替代品,可以繼承 Snort 規則| |Bro|NIDS|V|V||V|陡峭的學習曲線, 能夠檢測其他入侵檢測工具可能會忽略的異常和模式 |OSSEC| HIDS|V|V|V|V|功能最全面的HIDS, 系統資源的占用非常小 |Fail2Ban|HIDS|V|V||V|可以保護電腦伺服器免受蠻力攻擊| ### 3. IPS 入侵防禦系統 ( Intrusion Prevention System ),可視為IDS功能的延伸 用以彌補 IDS 功能不足,偵測到入侵會主動防禦 #### 3.1. 種類 ##### 3.1.1. NIPS 透過偵測流經的網路流量,提供對網路的安全保護,一旦辨識出入侵行為,NIPS 封包到達主機前==切斷連線== ##### 3.1.2. HIPS 主機型入侵防禦,用於保護伺服器和主機系統不受入侵行為的攻擊,會將攻擊==封包丟棄== ### 4. IDS / IPS / Firewall **Firewall** - 管控進出 **IDS** - 偵測,有攻擊會通知 firewall 抵擋 - 可以阻擋合法網路連結 ( DDOS ) - 透過特徵比對,防禦可以不用限定在個別的 IP 封鎖 - 可以分析內網的流量, 防止內部攻擊 **IPS** - 延伸 IDS 優點 - 以 inline 模式運作,可以丟棄封包 ![](https://i.imgur.com/1MW4pCT.png) [圖片來源: 入侵防禦技術與實驗](https://pws.niu.edu.tw/~hbc/IPSTec_Chu.pdf) :::info `inline`裝置本身也是網路架構的組成分子,除非要支援 pass_through 否則掛掉造成網路癱瘓 P.S. 對比 2.1.2 `Out-of-Band` ::: ## 發現問題(分析 log ) ![](https://i.imgur.com/xpIeJ8i.png) [圖片來源: Log Analytics, Log Mining and Anomaly Detection with Deep Learning](https://www.xenonstack.com/blog/log-analytics-mining/) ### Log 的組成要件 - 以時間為主軸 - 發起 process - 事件描述 [參考資料: Log分析入門](https://github.com/sakura26/DADA/blob/master/log_analysis_intro.md) ### syslog 的欄位 rsyslogd 的 syslog 格式 - TIMESTAMP - 根據 RFC 3164 定義格式是 `Mmm dd hh:mm:ss` - `Mmm` 是英文的月份縮寫 - Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec - `hh:mm:ss` local time - `hh` 是 24 小時制,從 00 - 23 - `mm`, `ss` 從 00 - 59 - HOSTNAME - 用於辨別發送訊息的機器 - 一般是 hostname,如果沒有會用 IP address - 如果有多組 IP,則以傳送訊息的 interface 的 IP address 為準 - APP-NAME[PROCID] - 用於辨別發送訊的 devicce 或 application 資訊 - `PROCID` process 在系統的 PID - MSG - 在 RFC 3164 被稱為 Content - 自由格式 - 描述事件的資訊 - 根據 RFC 5424 定義字元集 (character set) 需要是 UNICODE - RFC3629 指定會以 UTF-8 進行編碼(encode) ![](https://i.imgur.com/pZ43fIE.png) [參考資料: RFC5424 - The Syslog Protocol](https://tools.ietf.org/html/rfc5424) [參考資料: RFC3164](https://tools.ietf.org/html/rfc3164) [參考資料: Wiki - syslog](https://en.wikipedia.org/wiki/Syslog) [參考資料: Linux Logging Basics](https://www.loggly.com/ultimate-guide/linux-logging-basics/) [參考資料: syslog 詳解](https://www.itread01.com/content/1548217114.html) :::info RFC5234 定義的 syslog 所有訊息格式 ![](https://i.imgur.com/8Tl5h6Q.png) ![](https://i.imgur.com/kqVLiHM.png) [圖片來源: RFC5424 - The Syslog Protocol](https://tools.ietf.org/html/rfc5424) ::: ### log 會有哪些訊息 以常見的 log 檔案做說明 `/var/log/syslog/` system log,所有訊息的匯集地 ![](https://i.imgur.com/Io7cSqO.png) `/var/log/cron.log` crontab 排程有沒有實際被進行? 進行過程有沒有發生錯誤?你的 /etc/crontab 是否撰寫正確? `/var/log/auth.log` 牽涉到『需要輸入帳號密碼』的軟體,那麼當登入時 (不管登入正確或錯誤) 都會被記錄在此檔案中 ![](https://i.imgur.com/2mPGVaR.png) `/var/log/wtmp`, `/var/log/faillog` 記錄正確登入系統者的帳號資訊 (wtmp) == 指令 `last` 錯誤登入時所使用的帳號資訊 (faillog) ![](https://i.imgur.com/CN4WE56.png) `/var/log/lastlog` 可以記錄系統上面所有的帳號最近一次登入系統時的相關資訊, 對應指令`lastlog` ![](https://i.imgur.com/FS1cltZ.png) `/var/log/utmp` 當前登入系統的情況, 即指令 `who`, `w` ![](https://i.imgur.com/s3udKwf.png) `/var/log/{服務名稱}` 不同的網路服務會使用它們自己的 log 檔 ### log 是怎麼產生的:rsyslogd 在 linux 是以 `rsyslog.service` 來紀錄 log 檔, 產生的各個資訊的登錄 **確定服務開啟** 運行中的程式 `ps aux |grep rsyslog` 服務啟動狀況 `systemctl status rsyslog.service` ![](https://i.imgur.com/2B9NMkZ.png) **rsyslogd 設定檔** 位於`/etc/rsyslog.conf` 與 `/etc/rsyslog.d/*` 設定 服務 產生相關資訊哪些 訊息等級 需要紀錄,以及其 對應位置 服務名稱 ![](https://i.imgur.com/FjywspZ.png) [圖片來源: 鳥哥 - 認識與分析登錄檔](http://linux.vbird.org/linux_basic/0570syslog.php) 訊息等級 訊息嚴重性 0 - 7, 愈嚴重的等級數值愈小 `.` 該訊息等級 & 更嚴重的訊息等級(等級數值 <= ) `.=` 指定的訊息等級(等級數值 =) `.!` 嚴重低於這個等級(等級數值 > ) ![](https://i.imgur.com/On2acN8.png) [圖片來源: 鳥哥 - 認識與分析登錄檔](http://linux.vbird.org/linux_basic/0570syslog.php) 語法 ex: `/etc/rsyslog.d/50-default.conf` ![](https://i.imgur.com/oVw9D5s.png) ### log 好醜整理一下 透過字串處理工具過濾 log 內容,並整理成更適合閱讀的格式 **awk** 以 column 為單位擷取文字,以 `${col_num}` 的格式表現 ![](https://i.imgur.com/eU0gFHS.png) 通常會搭配 `print` 輸出(感覺是類似 echo 就是 awk 中輸出的指令) cat /var/log/nginx/access.log.1 |awk '{print "IP="$1, "\tRequest="$6$7$8$9}' ![](https://i.imgur.com/PR4N36W.png) **Perl** :warning: 待補全 Perl 是由 Practical Extraction Report Language 所組成 以 C 語言開發而成的 Script 開發的目的是為讓報表處理的工作變得更方便 融合了 C、sed、awk 和 sh 的特色 當初開發是在 Unix 的環境可以很好的支援 Unix 體系的作業系統 可以在 shell 直接執行 `perl -E 'say("hello")` > hello `perl -E 'say(100*100)` > 10000 :::info BT 補充 是非常有彈性的語言(就像是詩) 很多程式語言都有其限制,但 Perl 唯一的限制只來自於使用者的想像力 ::: **sed** 可以將輸入資料做編輯 ( 新增, 修改, 刪除, 取代 ) 後輸出 `{line_num}d` 刪掉 ![](https://i.imgur.com/KLAt9e1.png) `{line_num}a {要增加的 txt}` append 在指定行後 ![](https://i.imgur.com/h0VyE8X.png) `{line_num}i {要增加的 txt}` insert 在指定行前 ![](https://i.imgur.com/8G6SF25.png) `{line_num}c {取代內容}` 取代指定行的內容 ![](https://i.imgur.com/pQmZm9u.png) `{line_num}p` 列出指定行的內容(建議加入參數 `-n`) 沒加`-n` ![](https://i.imgur.com/poyqGpO.png) 加`-n` ![](https://i.imgur.com/MoYYHIP.png) **sort** 將輸入內容做排序輸出的工具 `-o {輸出檔案}` 將排序後的資料輸出到檔案 ![](https://i.imgur.com/oZNULjk.png) `-fu` 刪去重複內容(不分大小寫) ![](https://i.imgur.com/0dRnLcw.png) `-t {分隔符號} -k {欄位號碼}` 指定排序欄位 `-M` 按照英文月份排序 非英語系系統要加上參數`LC_ALL=C` ![](https://i.imgur.com/bDUiYIs.png) 合併文件 ![](https://i.imgur.com/v0IkhLr.png) 不排序合併(`-m`) ![](https://i.imgur.com/Bkwg9Yr.png) **uniq** 處理重複的工具 刪去重複後輸出 ![](https://i.imgur.com/YnvuoSu.png) 計算出現次數 ![](https://i.imgur.com/zdW0IzU.png) ## 使用 fail2Ban 抵擋 暴力破解法 與 DNS DDOS ### 暴力破解法 又稱為窮舉攻擊(英語:Exhaustive attack),是一種密碼分析的方法,即將密碼進行逐個推算直到找出真正的密碼為止 #### 方式 - 字典暴力破解:有一個字典檔,裡面包含了一些可能常見的密碼組合,再利用字典檔去進行暴力破解。 - 純粹暴力破解:嘗試所有組合 #### 彩虹表攻擊 常用於破解加密過的密碼雜湊。彩虹表指的是 hash 與 原始值 對照,透過擷取封包或其他途徑取得的密碼 hash 值,對照彩虹表破解密碼 ![](https://i.imgur.com/tFjkQ89.png) ### DNS DDOS 攻擊 DoS (Denial of Service),為駭客利用大量偽造且無意義的封包,藉以消耗被攻擊者的網路頻寬與系統資源,導致網路癱瘓,無法提供正常的服務。DoS是採一對一的攻擊方式 DDoS ( Distributed Denial of Service ,分散式阻斷服務攻擊)為 DoS 的延伸主要利用分散於不同地方的多部電腦主機,發送大量的偽造封包,進而達到癱瘓網路電腦主機伺服器的目的 DNS DDOS 攻擊 - 基本洪水攻擊:這種攻擊會送出許多 DNS 請求到 DNS 伺服器上,企圖耗盡這些伺服器的網域名稱解析器,以及快取資料庫資源。 - 遞迴式洪水攻擊:攻擊者會對 DNS 伺服器,送出並不存在 DNS 快取資料的網域名稱解析請求,增加 DNS 伺服器與網路頻寬的負擔。 - DNS反射(reflection)攻擊: 攻擊者偽造成攻擊目標 IP 不斷向 DNS 發出 request,因為 DNS response 相對 request 是大的,如果攻擊目標一次收到大量 DNS server 的回覆封包,造成攻擊目標癱瘓 ### fail2ban Fail2ban 是一套以 Python 語言所撰寫的 GPLv2 授權軟體,藉由分析系統紀錄檔,並透過設定過濾條件 (filter) 及動作 (action),當符合我們所設定的過濾條件時,將觸發相對動作來達到自動化反應的效果 (如封鎖來源 IP、寄信通知管理者、查詢來源 IP 資訊等) 可以防止一些常見的服務被攻擊 ex: SSH, ftp, apache **原理** - 分析 log 檔案 ( 定義 filter ),把疑似攻擊的連線封鎖( action ) **安裝** `sudo apt install fail2ban` **設定檔結構** - `jail.conf` 設定 filter 與 action 的關聯性, 建議自定義寫在 `jail.local`, `jail.conf` 在系統更新或升級的時候可能會變動 - `filter.d/` 存放 filter 的設定檔, filter 定義攻擊篩選條件 - `action.d/` 存放 action 的設定檔, action 定義後續執行動作 ex: 「sendmail 寄信通知」、「iptables 阻擋來源位址」、「使用 whois 查詢來源 domain 資訊」 ![](https://i.imgur.com/mJJGtLi.png) [圖片來源: 清華大學 - Fail2ban](https://net.nthu.edu.tw/2009/security:fail2ban) #### (lab) 阻擋在 1 min 內 ssh 錯誤嘗試 3 次 `/etc/fail2ban/jail.local` ```shell= [sshd-hello] enabled = true # 啟用 ssh port = ssh filter = sshd logpath = /var/log/auth.log # log檔查詢位置 maxretry = 3 # 最高容忍錯誤嘗試次數 findtime = 60 # 計次期間(s): 通常 1 min, 1s 之內 bantime = 300 # 封鎖時間 ``` 重啟 fail2ban `sudo service fail2ban restart` 查看運行中的所有 jail `sudo fail2ban-client status` ![](https://i.imgur.com/7NNN1pV.png) 運行結果 ![](https://i.imgur.com/oT4erjF.png) 在 `[sshd]` 中沒有對應 action 設定會參照 `[DEFAULT]` ![](https://i.imgur.com/36FkBrM.png) 是使用 iptables 的規則去阻擋入侵, 所以可以在 iptables 的 list 中看到 ![](https://i.imgur.com/LiHRQlG.png) 解除封鎖 IP ( 不小心鎖錯人 :face_palm: ) `sudo fail2ban-client set {jail_nmae} unbanip {要解鎖IP}` ![](https://i.imgur.com/m9h97qb.png) ## 使用 SYN cookie 抵擋 SYN Flood ### SYN Flood TCP 連線時,client 端送 SYN 到伺服器,伺服器會回覆 SYN+ACK,並該 request 放進 Half-Open Queue,此時稱為半連接 ( Half-Open ) 該 request 會在 Queue 中直到伺服器收到 ACK 回覆才算完成(establish) 如果伺服器一直沒有收到 ACK,會在超時重傳 SYN+ACK SYN Flood 則是攻擊者傳送多個 SYN 請求並不給予回覆,直到塞爆 Queue ,導致伺服器無法負荷正常連線,是常見的 DDOS 攻擊 SYN-flood 塞爆 Queue 示意圖 ![](https://i.imgur.com/Po5jg4g.png) [圖片來源 - SYN-floods and SYN-cookies animated](https://www.youtube.com/watch?v=rsVsU6-nfdM) ### SYN Cookie tcp header ![](https://i.imgur.com/p7Se9Zs.png) [圖片來源: NotFalse 技術客 - TCP 三向交握 (Three-way Handshake)](https://notfalse.net/7/three-way-handshake) SYN cookies 技術可以在伺服器半連接 ( Half-Open ) 停佇列已滿的情況下仍能處理新的 SYN 請求 SYN cookie 開啟時,SYN request 並不會被放進 Queue 中,而是將相關訊息做成 cookie 塞進 SYN+ACK 封包 SYN cookies 會將來源 IP, Port, timestamp 等與這次握手相關的訊息進行處理成為回覆 SYN+ACK 封包中的 sequence number 在伺服器收到 client 端 ACK 回覆,再取出 ACK_num - 1 還原 sequence num 進行特定比對,成功即完成三項交握。 - `t` timestamp mod 32 成 5 bit - `m` SYN Queue 中的 MSS (maximum segment size),會 encode 成 3 bit - `s` IP, port, timestamp相關資訊做 hash 成 24 bit,用於收到 ACK 時驗證 ![](https://i.imgur.com/0QBGuj3.png) **收到 ACK 後會做的事情** ![](https://i.imgur.com/RdLdqee.png) [圖片來源: NotFalse 技術客 - TCP 三向交握 (Three-way Handshake)](https://notfalse.net/7/three-way-handshake) 將 ACK_num - 1 還成原本的 SYN 1. 確認 time out 2. s 確認正確性 3. 重建 SYN Queue 開啟 ( 預設已經開啟 ) `echo 1 > /proc/sys/net/ipv4/tcp_syncookies` ![](https://i.imgur.com/e3st1L0.png) ## 使用 PortSentry 抵擋惡意 Port Scanning ### 惡意 port Scanning 目的:找出攻擊目標提供服務的 port 以進行攻擊 判別方式: 通常會以短時間內每個 port 都戳一次(壞) ### PortSentry 透過監聽指定 port 確認是否被惡意 scan,會配合 tcp_wrapper 阻擋惡意 host #### 重要檔案 - `/etc/portsentry/portsentry.conf` 主設定檔 ![](https://i.imgur.com/ZGp2myl.png) ![](https://i.imgur.com/A9wUPLD.png) ![](https://i.imgur.com/juVuhGL.png) - `/etc/portsentry/portsentry.ignore` 要忽略的 IP,設定永遠不會被 ban 的 host (每次 restart 會被 rebulid, 參照 ignore.static 動態產生 ) ![](https://i.imgur.com/ZwsLAbP.png) - `/etc/portsentry/portsentry.ignore.static` static IP ignore,當 restart 的時候,會根據這份檔案設定的子網路( IP/netmask ) 查詢指令 `ifconfig -a` 動態抓取 IP 並 rebuild 要 portsenty.ignore,所以要設定忽略名單是編輯這份檔案 ![](https://i.imgur.com/eGy4tIf.png) - `/etc/default/portsentry` 攸關 portsentry 啟動的選項 ex: portsentry -tcp ![](https://i.imgur.com/nNB8RGG.png) - `/etc/init.d/portsentry` Start 或 Stop portsentry deamon 的 script ( 腳本 ) - 使用方式 - /etc/init.d/portsentry start - /etc/init.d/portsentry stop - /etc/init.d/portsentry restart - `/var/lib/portsentry/portsentry.blocked.tcp` & `/var/lib/portsentry/portsentry.blocked.udp` 被阻擋的 host 名單 ( daemon reload 後會被清空) ![](https://i.imgur.com/dSuuB3W.png) - `/var/lib/portsentry/portsentry.history` 紀錄曾經被 blcok 的 host , 包含 udp 與 tcp #### 設定 portsenrty 的 protocol mode In file `/etc/default/portsentry` ```shell= TCP_MODE= tcp / stcp / atcp UDP_MODE= udp / sudp / audp ``` - tcp/udp ![](https://i.imgur.com/RjOgJfo.png) - stcp / sudp - stealth scan - SYN Scan,這種掃瞄技巧通常稱為 half-open scanning,因為我們通常並不是真的去建立一個連線,只是讓對方以為我們要建立連線 ![](https://i.imgur.com/QuuZ6Wh.png) [圖片來源: 網路安全:理論與實務 第二版](http://crypto.nknu.edu.tw/textbook/chap11.pdf) - atcp/audp - advanced tcp - 監控 " 所有 " 小於設定值的 port ( 官方建議數值不要大於 1024 ) ![](https://i.imgur.com/xbIZdXg.png) - Advanced tcp mode 的排除不掃的名單 ![](https://i.imgur.com/EjWg0Xs.png) :::info **default config 預設不掃的 port 與功用補充** `113` 特定 TCP 連線的使用者認證 ( ident protocol ),舊的伺服器身分辨識系統 `139` netBIOS session service,提供了一個可靠的雙向有序資料給兩個NetBIOS `137` netBIOS name service `138` netBIOS datagram distribution service ( send, recieve, broadcast) `520` routing information protocol for UDP `67` Bootstrap protocol server. Used by DHCP servers to communicate addressing information to remote DHCP clients **指令查詢 port** `/etc/service` ![](https://i.imgur.com/4WAdEHx.png) ::: #### 基本操作 - 啟動 - 法一 `service portsentry start` - 法二 `/etc/init.d/portsentry start` - 查看執行狀況 - 服務運行狀況 `service portsentry status` ![](https://i.imgur.com/eXKcC2P.png) - process 運行狀況 `ps -ef | grep -v grep | grep portsentry` (正確開啟時 ps 狀況如下) ![](https://i.imgur.com/aUFJj75.png) #### (lab) VM 使用 nmap scan 主機 port ==注意 VM 網路不可以選擇 NAT== VM scan 本機 port `nmap -p 1-65535 -T4 -A -v -PE -PS22,25,80 -PA21,23,80 {本機IP}` :::info **nmap參數說明** `-PA` ACK ping `-PS` SYN ping `-PE` Echo ping 防火牆通常會設定阻擋 ICMP ping,所以由外部向內連線的 SYN ping (PS) 會無法通過 而 ACK ping (AP) 會被誤認為回應的 ACK 封包,有時可以通過 但如果有狀態確認 (stateful) 的防火牆會阻擋非預期封包,則該法也會被阻擋 所以通常會採用 `PA` `PS` `PE` 一同使用的方式提高機率 `T{0-5} ` timing template ![](https://i.imgur.com/oqYt157.png) [圖片來源: NMAP.ORG - Timing Templates](https://nmap.org/book/performance-timing-templates.html) ::: VM scan 本機的 port 的結果(沒有開啟 portsentry 防護) ![](https://i.imgur.com/SbHPpT0.png) VM scan 本機的 port 的結果(本機開啟 portsentry) ![](https://i.imgur.com/GXahiv2.png) 開啟主設定檔啟動 block (將 0 --> 1) ` sudo vim +135 /etc/portsentry/portsentry.conf` ![](https://i.imgur.com/xR2REbs.png) port scan 會出現在 `/var/log/syslog` ![](https://i.imgur.com/LUs5d95.png) **被 ban 跡象** 查看 routing table `route -n` ![](https://i.imgur.com/AEfAL22.png) `/var/lib/portsentry/portsentry.blocked.tcp` ![](https://i.imgur.com/ObudJJH.png) `/var/lib/portsentry/portsentry.history` ![](https://i.imgur.com/QLwG6aZ.png) `/etc/hosts.deny` ![](https://i.imgur.com/Gxv6Un2.png) **VM 發出 request 被拒絕** ( ping, ssh, telnet 皆被拒 ) ![](https://i.imgur.com/70zET4F.png) ![](https://i.imgur.com/4brXDP5.png) ![](https://i.imgur.com/QKormzt.png) #### 誤判 ban 錯 host 解除封鎖方式 :face_palm: ( PS: 先 stop service,設定好再 start ) 1. (reload 後紀錄會不見)排除欲解除 IP 複製一份目前 blocked ip list `/var/lib/portsentry/portsentry.blocked.tcp` `grep -v {解封 IP} portsentry.blocked.tcp | sudo tee portsentry.blocked.tcp.new` 2. 直些編輯 hosts.deny 或 排除欲解除 IP 複製一份目前被 deny 的 host `/etc/hosts.deny` `grep -v {解封 IP} hosts.deny |sudo tee hosts.deny.new` 3. 刪除 routing table 中關於封鎖欲解除 IP 的規則 `route del -host {解封 IP} reject`

    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