---
# System prepended metadata

title: 流量監控工具使用說明
tags: [補充內容]

---

---
tags: 補充內容 
---
# 流量監控工具使用說明
此處使用流量偵測IDS工具-Suricata
Suricata服務的控制元件大多可以從設定檔(Suricata.yaml)進行調整，主要4大主力功能為：封包捕捉(Packet Capture)、封包解析(Packet Decodeing)、偵測特徵是否觸發規則(Detection)、輸出告警日誌(Outputs)，下面會介紹使用到的設定以及如何從調整效能
## 1 Suricata.yaml
此設定檔中，其主要分成幾大部分的設定
1. 流量(Mirror Traffic)控管
2. 輸出(Outputs)內容設定
3. 封包捕捉(Packet Capture)設定
4. 應用層解析設定
5. 進階服務控管設定

## 1.1 監控流量控管
設定內部網段及外部網段及各種服務的網段區別以利於Suricata更明確對流量進行監控。
```
vars:
  # more specific is better for alert accuracy and performance
  address-groups:
    HOME_NET: "[192.168.0.0/16,10.0.0.0/8,172.16.0.0/12]"
    #HOME_NET: "[192.168.0.0/16]"
    #HOME_NET: "[10.0.0.0/8]"
    #HOME_NET: "[172.16.0.0/12]"
    #HOME_NET: "any"

    EXTERNAL_NET: "!$HOME_NET"
    #EXTERNAL_NET: "any"

    HTTP_SERVERS: "$HOME_NET"
    SMTP_SERVERS: "$HOME_NET"
    SQL_SERVERS: "$HOME_NET"
    DNS_SERVERS: "$HOME_NET"
    TELNET_SERVERS: "$HOME_NET"
    AIM_SERVERS: "$EXTERNAL_NET"
    DC_SERVERS: "$HOME_NET"
    DNP3_SERVER: "$HOME_NET"
    DNP3_CLIENT: "$HOME_NET"
    MODBUS_CLIENT: "$HOME_NET"
    MODBUS_SERVER: "$HOME_NET"
    ENIP_CLIENT: "$HOME_NET"
    ENIP_SERVER: "$HOME_NET"

  port-groups:
    HTTP_PORTS: "80"
    SHELLCODE_PORTS: "!80"
    ORACLE_PORTS: 1521
    SSH_PORTS: 22
    DNP3_PORTS: 20000
    MODBUS_PORTS: 502
    FILE_DATA_PORTS: "[$HTTP_PORTS,110,143]"
    FTP_PORTS: 21
    GENEVE_PORTS: 6081
    VXLAN_PORTS: 4789
    TEREDO_PORTS: 3544
```
## 1.2 輸出內容設定(Outputs)
Outputs設定中有很多輸出的方式配置選項、包含了告警、檢測的數據包以及產生的結果等，此配置中可配置所需要得輸出內容、無須每項皆開起

Suricata默認預設日誌存取的目錄，在此配置文件中可以直接更改存的目錄，另也能在運行時使用參數(-l)進行設定
`default-log-dir: /var/log/suricata/`
### 1.2.1 Suricata監控的狀態日誌
記錄Suricata封包處裡的事件次數包含處理成功以及丟棄等
```
stats:
  ＃enabled yes為啟動、no為不啟動
  enabled: yes
  # 狀態日誌更新週期：幾秒一次
  interval: 8
```
產出日誌的日誌
```
state log picture
```
### 1.2.2 告警輸出(fast.log)
快速且輕便產出的單行僅告警訊息，不需在另外轉格式，負擔小但日誌內容相對簡單
```
- fast:
    enabled: no
    filename: fast.log
    append: yes
    #filetype: regular # 'regular', 'unix_stream' or 'unix_dgram'
```
### 1.2.3 事件輸出(eve.log)
當Suricata匹配了一條規則後則會記錄一則信息，此信息包含了封包的時間戳記、告警的輸出內容、相對應的簽名及ID等，格式為json格式因此可以再透過其他的程序對其加工處裡產生進一步的輸出，下列對其中參數進行簡單的介紹
- enable 預設啟動(yes)或關閉(no) 
- filetype 輸出的類型 regular|syslog|unix_dgram|unix_stream|redis
- filename 檔案名稱(可支援時間格式%Y%m%d%H%M)
- threaded (on)相同thread處裡的告警事件於獨立一個eve日誌
- rotate-interval 自動創建日誌週期
- filemode eve日誌權限
- alert 告警事件記錄設定，例如生成警報的應用層記錄（HTTP、DNS 等）和規則的元素。

事件輸出類型可以有非常多種類，包含文件、系統日誌、輸出到socket等，其內容種類匹配包括有alert、http、dns等規則的封包信息，舉例來說某一的規則action為alert，當檢測到有一封包觸發此條規則，那封包及規則的相關信息會儲存至事件日誌當中
```
- eve-log:
    enabled: yes
    filetype: regular #regular|syslog|unix_dgram|unix_stream|redis
    filename: eve.json
    types:
      - alert:
      - http:
      - dns:
      - tls:
      - files:
      .
      .
      .
      
```
另可以將不同信息配置輸出到不同的事件告警日誌如下配置alert及drop輸出至eve-ips.json；http、dns及tls等協定輸出到名為eve-nsm.json
```
outputs:
  - eve-log:
      enabled: yes
      type: file
      filename: eve-ips.json
      types:
        - alert
        - drop

  - eve-log:
      enabled: yes
      type: file
      filename: eve-nsm.json
      types:
        - http
        - dns
        - tls
```
### 1.2.4 anomaly
此記錄記錄異常值封包產生，包含不正確的協定長度或值以及使其封包異常的特定條件
```
- anomaly:
    types:
      #decode: no
      #stream: no
      #applayer: yes
    #packethdr: no
```
### 1.2.5 HTTP日誌輸出(http.log)
Http日誌記錄了所有http流量的信息包含了request、header、HOST字段、URI字段及User-agent字段也能設置extended以輸出更多的信息，另用戶可利用customformat來自定義輸出的格式
```
 # a line based log of HTTP requests (no alerts)
  - http-log:
      enabled: yes
      filename: http.log
      append: yes        # If this option is set to yes, the last filled http.log-file will not be
                         # overwritten while restarting Suricata.
      #extended: yes     # enable this for extended logging information
      #custom: yes       # enabled the custom logging format (defined by customformat)
      #customformat: "%{%D-%H:%M:%S}t.%z %{X-Forwarded-For}i %H %m %h %u %s %B %a:%p -> %A:%P"
      #filetype: regular # 'regular', 'unix_stream' or 'unix_dgram'
```

### 1.2.6 封包日誌（pcap-log)
藉由pcap-log設定可以包存所有監控的封包，如此即可於檢測到有惡意行為封包時可更容易找到當時的流量以便利對整個事件進行分析和確認，pcap檔案可以限定內容量大小及文件的個數，當達到限制的檔案大小則會創建一個新的文件，另配置的mode有兩種模式，於普通模式下會將日誌存取於預設的日誌目錄(default-log-dir)而sguil模式須指定目錄(sguil_base_dir:)並儲存日誌會依照日期歸類，並加上時間的戳記
```
 - pcap-log:
      enabled: yes
      filename: log.pcap

      # File size limit.  Can be specified in kb, mb, gb.  Just a number
      # is parsed as bytes.
      limit: 1000mb

      # If set to a value will enable ring buffer mode. Will keep Maximum of "max-files" of size "limit"
      max-files: 2000

      mode: normal # normal, multi or sguil.

      # Directory to place pcap files. If not provided the default log
      # directory will be used. Required for "sguil" mode.
      #dir: /nsm_data/

      #ts-format: usec # sec or usec second format (default) is filename.sec usec is filename.sec.usec
      use-stream-depth: no #If set to "yes" packets seen after reaching stream inspection depth are ignored. "no" logs all packets
      honor-pass-rules: no # If set to "yes", flows in which a pass rule matched will stopped being logged.
```
### 1.2.7 詳細的警告日誌（alert-debug.log）
開啟此設定Suricata會記錄每筆告警產生的詳細信息，包含封包、規則等完整信息，能使維護人員更快的篩選是否為誤報，檢查規則是否有問題等，另雖此功能非常有用但因信息大量所以在檢測監控處裡時，會消耗大量的性能於此，所以默認為不開啟
```
 - alert-debug:
      enabled: no
      filename: alert-debug.log
      append: yes        # If this option is set to yes, the last filled fast.log-file will not be
                         # overwritten while restarting Suricata. 
      #filetype: regular # 'regular', 'unix_stream' or 'unix_dgram'
```
### 1.2.7 Syslog
此選項設定是否將Suricata的告警輸出至syslog中
```
- syslog:
      enabled: no
      #identity: "suricata"
      facility: local5  ## In this option you can set a syslog facility
      #level: Info      ## possible levels: Emergency, Alert, Critical,
                        ## Error, Warning, Notice, Info, Debug
```
### 1.2.8 Drop.log
當使用IPS模式下，使用了drop操作的規則後，這些被drop的封包信息則會存取於drop.log之中
```
  - drop:
      enabled: no
      filename: drop.log
      append: yes                                       
      #filetype: regular # 'regular', 'unix_stream' or 'unix_dgram'
```
## 1.3 Suricata服務日誌控管(Logging)
並非設定IDS告警或事件日誌，為Suricata引擎本身日誌信息 LIKE.(啟動時的錯誤訊息)
```
logging: 
  default-log-level: notice
```
default-log-level 控制Suricata日誌級別預設為notice，控制顯示日誌信息的嚴重性級別 ，當日誌的事件信息級別低於設定值則不會顯示如 ( 設定值為info，日誌則只會顯示error、warning、notice and info 其餘則不顯示 )，另可藉由環境變數SC_LOG_LEVEL設定此值。
日誌級別由高到低為：error  > warning > notice > info > perf > config > debug。

default-log-format 設定日誌輸出的格式另可由SC_LOG_FORMAT環境變數控制。
預設格式如下：
```
[27708] 15/10/2010 -- 11:40:07 - (suricata.c:425) <Info> (main) – This is Suricata version 1.0.2
"[%i]             [%t]         -     (%f:%l)       <%d>   (%n)  --"     
```
設定日誌輸出的方式

|輸出位置|輸出方式|參數|用法|
|--------|--------|--------|--------|
|console|直接顯示於螢幕|enabled|開啟此設定與否 (yes/no)|
|file|輸出至某個檔案|type|輸出日誌的型態 ，(json)|
|syslog|輸出至系統日誌|level|決定此輸出的日誌級別，如(info)|
|||format|輸出日誌的格式，如("[%i] %t - (%f:%l) <%d> (%n) -- ")|
|||filename|欲指定輸出的檔案位置。(only file use)|
|||facility|In this option you can set a syslog facility|

```
  outputs:
  - console:
      enabled: yes
      # type: json
  - file:
      enabled: yes
      level: info
      filename: suricata.log
      # type: json
  - syslog:
      enabled: no
      facility: local5
      format: "[%i] <%d> -- "
      # type: json
```
## 1.4 封包捕捉設定
Suricata用於封包捕捉的元件(linux上預設使用)，此為單線程模塊獲取封包及解碼，多線程的模塊檢測及單模塊的輸出，如下圖所示，當僅用IDS建議開啟tpacket-v3，反之需IPS功能建議使用tpacket-v2即可，為減少有丟包情況可以開以mmap-locked功能並增加ring-size的值(預設為2048)
![af-packet capture](https://i.imgur.com/ISC27KP.png)

```
af-packet:
  - interface: eno1
    #threads: auto
    cluster-id: 99
    cluster-type: cluster_flow
    defrag: yes
    #use-mmap: yes
    mmap-locked: yes
    tpacket-v3: yes
    ring-size: 2048
    #block-size: 32768
    #block-timeout: 10
    #use-emergency-flush: yes
    # buffer-size: 32768
    # disable-promisc: no
    #checksum-checks: kernel
    #bpf-filter: port 80 or udp
    #copy-mode: ips
    #copy-iface: eth1

  - interface: default
    #threads: auto
    #use-mmap: no
    #tpacket-v3: yes
```
## 1.5 應用層解析設定

## 1.6 進階服務控管設定

### 1.6.1 用戶群組
配置啟動Suricata的用戶及群組
```
# Run Suricata with a specific user-id and group-id:
#run-as:
#  user: suri
#  group: suri
```
### 1.6.2 最大處裡封包數
此配置設定了Suricata於同一個thread可以同時處裡的封包數量，其值為(1-65500)之間預設值為1024，其大小與內存及thread處裡能力相關，並非越大越好
```
# Number of packets preallocated per thread. The default is 1024. A higher number 
# will make sure each CPU will be more easily kept busy, but may negatively 
# impact caching.
#max-pending-packets: 1024
```
### 1.6.3 Runmode
此選項設定了Suricata的運行方式，共有三種模式預設為autofp，另外為single、workers模式
```
# Runmode the engine should use. Please check --list-runmodes to get the available
# runmodes for each packet acquisition method. Default depends on selected capture
# method. 'workers' generally gives best performance.
runmode: workers
```
- single模式
單一thread處裡完成所有工作，當第一個module完成抓包動作，其他module依次處裡，如下圖
![single mode](https://i.imgur.com/D3GseSr.png)
- workers模式
依據監聽的網卡數量及單網卡可啟用的捕捉封包thread數量，另也可於(threading)指定欲執行thread及優先度，其後續與single模式相同為單一thread完成工作，互不影響，與single不同是多個thread捕捉
![workers mode](https://i.imgur.com/EVnhqtA.png)

- autofp模式
切割成兩個部分分別是捕捉封包線程及檢測線程，捕捉封包線程通過PacketQueue傳遞給檢測封包進行處裡，會依據現行的線程運行狀況分配，當有多個檢測線程需透過PacketQueue確保列隊同一個封包傳遞同一個檢測線程
![autofp mode](https://i.imgur.com/gVgq5Of.png)

```
# Specifies the kind of flow load balancer used by the flow pinned autofp mode.
#
# Supported schedulers are:
#
# hash     - Flow assigned to threads using the 5-7 tuple hash.
# ippair   - Flow assigned to threads using addresses only.
#
#autofp-scheduler: hash
```
### 1.6.3 監控流量的每個封包大小上限
預設值為 1514
```
# Preallocated size for each packet. Default is 1514 which is the classical
# size for pcap on Ethernet. You should adjust this value to the highest
# packet size (MTU + hardware header) on your system.
#default-packet-size: 1514
```
### 1.6.4 開啟使用suricatasc套件
需先下載suricatasc及開始設定enable:on
```
sudo python setup.py install
```
```
# Unix command socket that can be used to pass commands to Suricata.
# An external tool can then connect to get information from Suricata
# or trigger some modifications of the engine. Set enabled to yes
# to activate the feature. In auto mode, the feature will only be
# activated in live capture mode. You can use the filename variable to set
# the file name of the socket.
unix-command:
  enabled: auto
  #filename: custom.socket
```
其可使用功能如下
- command-list: list available commands
- shutdown: shutdown Suricata
- iface-list: list interfaces where Suricata is sniffing packets
- iface-stat: list statistics for an interface
- help: alias of command-list
- version: display Suricata’s version
- uptime: display Suricata’s uptime
- running-mode: display running mode (workers, autofp, simple)
- capture-mode: display capture system used
- conf-get: get configuration item (see example below)
- dump-counters: dump Suricata’s performance counters
- reopen-log-files: reopen log files (to be run after external log rotation)
- ruleset-reload-rules: reload ruleset and wait for completion
- ruleset-reload-nonblocking: reload ruleset and proceed without waiting
- ruleset-reload-time: return time of last reload
- ruleset-stats: display the number of rules loaded and failed
- ruleset-failed-rules: display the list of failed rules
- memcap-set: update memcap value of the specified item
- memcap-show: show memcap value of the specified item
- memcap-list: list all memcap values available
- reload-rules: alias of ruleset-reload-rules
- register-tenant-handler: register a tenant handler with the specified mapping
- unregister-tenant-handler: unregister a tenant handler with the specified mapping
- register-tenant: register tenant with a particular ID and filename
- unregister-tenant: unregister tenant with a particular ID
- reload-tenant: reload a tenant with specified ID and filename
- add-hostbit: add hostbit on a host IP with a particular bit name and time of expiry
- remove-hostbit: remove hostbit on a host IP with specified bit name
- list-hostbit: list hostbit for a particular host IP

### 1.6.5 action-order
此指定義每條規則觸發時須執行的操作，而當前action-order字段為多條規則同時觸發時的執行順序，共有四種:pass、drop、reject、alert
- pass 指的是處理封包觸發當前規則時直接跳過後面的所有規則，也就是說不觸發後面的規則
- drop 只能工作在IPS模式下，當封包觸發到drop的規則時則會被丟棄並且產生一個警告
- reject 會給封包的發送和接收端都發生一個拒絕的數據包，如果原本的協議是TCP，則發生reset數據包，否則發送ICMP錯誤的數據包，同時產生一個警告。在IPS模式下也會丟棄匹配到的數據包 
- alert 則對發送和接收者都沒有影響，只會生成一個警告
```
# action-order:
#   - pass
#   - drop
#   - reject
#   - alert
```
Suricata會依照規則出現順序依次加載，此順序會根據配置文件中設定的重要程度來判斷，如上最優先為pass其次drop然後reject最後alert

### 1.6.6 IP分片重組
當超過的MTU的封包會產生出許多碎片，在網卡端口時進行重組，假如網路流量中存在了封包分片，那Suricata會對這些分段進行重組，可透過提高配置加速處裡過程
```
defrag:
  memcap: 32mb
  hash-size: 65536
  trackers: 65535 # number of defragmented flows to follow
  max-frags: 65535 # number of fragments to keep (higher than trackers)
  prealloc: yes
  timeout: 60
```
### 1.6.7 Suricata的flow
flow在此定義包含(協定、來源IP、目標IP、來源端口、目標端口)，其運作示意圖如下
![flow](https://i.imgur.com/1eeIXWS.png)
Suricata持續追蹤flow，其效能依據分配的記憶體所不同，調高其記憶體會也會加速處裡封包效率
```
flow:
  memcap: 128mb
  hash-size: 65536
  prealloc: 10000
  emergency-recovery: 30
  #managers: 1 # default to one flow manager
  #recyclers: 1 # default to one flow recycler thread

# This option controls the use of VLAN ids in the flow (and defrag)
# hashing. Normally this should be enabled, but in some (broken)
# setups where both sides of a flow are not tagged with the same VLAN
# tag, we can ignore the VLAN id's in the flow hashing.
vlan:
  use-for-tracking: true

# Specific timeouts for flows. Here you can specify the timeouts that the
# active flows will wait to transit from the current state to another, on each
# protocol. The value of "new" determines the seconds to wait after a handshake or
# stream startup before the engine frees the data of that flow it doesn't
# change the state to established (usually if we don't receive more packets
# of that flow). The value of "established" is the amount of
# seconds that the engine will wait to free the flow if that time elapses
# without receiving new packets or closing the connection. "closed" is the
# amount of time to wait after a flow is closed (usually zero). "bypassed"
# timeout controls locally bypassed flows. For these flows we don't do any other
# tracking. If no packets have been seen after this timeout, the flow is discarded.
#
# There's an emergency mode that will become active under attack circumstances,
# making the engine to check flow status faster. This configuration variables
# use the prefix "emergency-" and work similar as the normal ones.
# Some timeouts doesn't apply to all the protocols, like "closed", for udp and
# icmp.
```
### 1.6.8 於記憶體中flow釋放的時間
設定flow在記憶體timeout的時間
```
flow-timeouts:

  default:
    new: 30
    established: 300
    closed: 0
    bypassed: 100
    emergency-new: 10
    emergency-established: 100
    emergency-closed: 0
    emergency-bypassed: 50
  tcp:
    new: 60
    established: 600
    closed: 60
    bypassed: 100
    emergency-new: 5
    emergency-established: 100
    emergency-closed: 10
    emergency-bypassed: 50
  udp:
    new: 30
    established: 300
    bypassed: 100
    emergency-new: 10
    emergency-established: 100
    emergency-bypassed: 50
  icmp:
    new: 30
    established: 300
    bypassed: 100
    emergency-new: 10
    emergency-established: 100
    emergency-bypassed: 50
```
### 1.6.9 Stream-engine
此功能用追蹤TCP的連接狀況，一是用於保存flow中的狀態、序列編號及資訊，另是用於檢查封包是否有錯誤檢查以及完整性，當不完整會進行封包重組，但超過限制會直接進行丟棄
```
stream:
  memcap: 64mb
  checksum-validation: yes      # reject incorrect csums
  inline: auto                  # auto will use inline mode in IPS mode, yes or no set it statically
  reassembly:
    memcap: 256mb
    depth: 1mb                  # reassemble 1mb into a stream
    toserver-chunk-size: 2560
    toclient-chunk-size: 2560
    randomize-chunk-size: yes
    #randomize-chunk-range: 10
    #raw: yes
    #segment-prealloc: 2048
    #check-overlap-different-data: true
```

### 1.6.9 Decoder
解碼的設定
```
decoder:
  # Teredo decoder is known to not be completely accurate
  # as it will sometimes detect non-teredo as teredo.
  teredo:
    enabled: true
    # ports to look for Teredo. Max 4 ports. If no ports are given, or
    # the value is set to 'any', Teredo detection runs on _all_ UDP packets.
    ports: $TEREDO_PORTS # syntax: '[3544, 1234]' or '3533' or 'any'.

  # VXLAN decoder is assigned to up to 4 UDP ports. By default only the
  # IANA assigned port 4789 is enabled.
  vxlan:
    enabled: true
    ports: $VXLAN_PORTS # syntax: '[8472, 4789]' or '4789'.

  # Geneve decoder is assigned to up to 4 UDP ports. By default only the
  # IANA assigned port 6081 is enabled.
  geneve:
    enabled: true
    ports: $GENEVE_PORTS # syntax: '[6081, 1234]' or '6081'.
```
### 1.6.10 檢測引擎相關設定
Suricata在對流量檢測之前需要將所有的規則簽名加載到內存，而數據包在匹配規則時並不需要匹配所有的規則，事實上大量的規則是完全沒必要匹 配的，比如當前數據包時基於UDP協議的，那TCP的所有規則都是沒有必要匹配的。因此需要根據一定的依據對所有的規則進行分組，這樣數據包只需要與符合 條件的分組內的所有規則進行匹配即可。而需要如何分組則是一個關鍵的問題。

下面是detect-engine的一種配置。profile選項有custom、high、low和medium三種。high表示分組較多，但是會佔用更多的 內存，性能也會更好；low則正好相反，佔用更少的內存，性能也相對較差；medium是默認配置，是性能和內存使用的折中選擇。除此之外高級用戶可以在 custom-values字段自定義分組的配置，在使用custom的时候，custom-values中的配置才会生效，最大值为65000。
```
detect:
  profile: medium
  custom-values:
    toclient-groups: 3
    toserver-groups: 25
  sgh-mpm-context: auto
  inspection-recursion-limit: 3000
```
數據包檢測規則之分組圖
![detect-engine](https://i.imgur.com/JAA12OY.png)
接下來是sgh-mpm-context，這個字段指明MPM算法使用的content是否公用。當其值爲auto時，是否公用取決於配置文件中指 定MPM的算法，若爲ac或ac-gfbs，則使用single模式，表示所有的規則分組使用單個MPM-content，其餘算法則使用full模式， 每個分組擁有自己的MPM-content。而當sgh-mpm-context字段的值爲single或full時則不受MPM算法的影響。關於 suricata的MPM機制可以參考fast_parttern，後面的配置也會做進一步的說明

最後的inspection-recursion-limit則是爲了減少suricata的出錯次數，因爲網絡流量狀況非常複雜，suricata難免會遇上無限循環或是遞歸地處理數據包的情況，這時指定一個最大值，當循環或遞歸次數大於這個值則停止處理當前數據包

### 1.6.11 mpm演算法
之前已經瞭解過，suricata在content的多模匹配支持很多算法，不同的算法有不同的優缺點。設置如下，可選的算法包括ac, ac-bs, ac-cuda, ac-ks和hs，如cpu支援可安裝性能更加的Hyperscan(hs)，此為較高性能的正規匹配表達庫
```
# Select the multi pattern algorithm you want to run for scan/search the
# in the engine.
#
# The supported algorithms are:
# "ac"      - Aho-Corasick, default implementation
# "ac-bs"   - Aho-Corasick, reduced memory implementation
# "ac-ks"   - Aho-Corasick, "Ken Steele" variant
# "hs"      - Hyperscan, available when built with Hyperscan support
#
# The default mpm-algo value of "auto" will use "hs" if Hyperscan is
# available, "ac" otherwise.
#
# The mpm you choose also decides the distribution of mpm contexts for
# signature groups, specified by the conf - "detect.sgh-mpm-context".
# Selecting "ac" as the mpm would require "detect.sgh-mpm-context"
# to be set to "single", because of ac's memory requirements, unless the
# ruleset is small enough to fit in memory, in which case one can
# use "full" with "ac".  The rest of the mpms can be run in "full" mode.

mpm-algo: auto

# Select the matching algorithm you want to use for single-pattern searches.
#
# Supported algorithms are "bm" (Boyer-Moore) and "hs" (Hyperscan, only
# available if Suricata has been built with Hyperscan support).
#
# The default of "auto" will use "hs" if available, otherwise "bm".

spm-algo: auto
```
### 1.6.12 threading分配計算
Suricata可以為每個module進行cpu的配置設定，兩個runmode模式分別為:
- autofp模式
    - pcaket capture thread 對應 receive-cpu-set 用於捕捉封包
    - management thread 對應 management-cpu-set 用於flow的管理及回送
    - pcaket process thread 對應 worker-cpu-set 此塊佔據最多資源用於detect以及output預設為all
- workers模式
    - management thread 對應 management-cpu-set 用於flow的管理及回送
    - pcaket process thread 對應 worker-cpu-set 將捕捉解析檢測輸出都指定交由此線程執行，當集中處裡可以減少封包的分發能更有效率處裡
- verdict-cpu-set Suricata於cpu線程的優先執行序
- detect-thread-ratio: 1.0 用於單一實體線程能夠被當成幾個虛擬線程使用
```
# Suricata is multi-threaded. Here the threading can be influenced.
threading:
  set-cpu-affinity: no
  # Tune cpu affinity of threads. Each family of threads can be bound
  # to specific CPUs.
  #
  # These 2 apply to the all runmodes:
  # management-cpu-set is used for flow timeout handling, counters
  # worker-cpu-set is used for 'worker' threads
  #
  # Additionally, for autofp these apply:
  # receive-cpu-set is used for capture threads
  # verdict-cpu-set is used for IPS verdict threads
  #
  cpu-affinity:
    - management-cpu-set:
        cpu: [ 0 ]  # include only these CPUs in affinity settings
    - receive-cpu-set:
        cpu: [ 0 ]  # include only these CPUs in affinity settings
    - worker-cpu-set:
        cpu: [ "all" ]
        mode: "exclusive"
        # Use explicitly 3 threads and don't compute number by using
        # detect-thread-ratio variable:
        # threads: 3
        prio:
          low: [ 0 ]
          medium: [ "1-2" ]
          high: [ 3 ]
          default: "medium"
    #- verdict-cpu-set:
    #    cpu: [ 0 ]
    #    prio:
    #      default: "high"
  #
  # By default Suricata creates one "detect" thread per available CPU/CPU core.
  # This setting allows controlling this behaviour. A ratio setting of 2 will
  # create 2 detect threads for each CPU/CPU core. So for a dual core CPU this
  # will result in 4 detect threads. If values below 1 are used, less threads
  # are created. So on a dual core CPU a setting of 0.5 results in 1 detect
  # thread being created. Regardless of the setting at a minimum 1 detect
  # thread will always be created.
  #
  detect-thread-ratio: 1.0
```
### 1.6.13 高性能的封包捕捉-PF_RING
與預設捕捉封包的單線程模塊的不同於此由多模塊獲取及解碼封包再透過queue分別至多個檢測模塊進行檢測相對於單一獲取效率來的高，運作模式如下圖
![pfring](https://i.imgur.com/RgtNeBj.png)

```
# PF_RING configuration: for use with native PF_RING support
# for more info see http://www.ntop.org/products/pf_ring/
pfring:
  - interface: eth0
    # Number of receive threads. If set to 'auto' Suricata will first try
    # to use CPU (core) count and otherwise RSS queue count.
    threads: auto

    # Default clusterid.  PF_RING will load balance packets based on flow.
    # All threads/processes that will participate need to have the same
    # clusterid.
    cluster-id: 99

    # Default PF_RING cluster type. PF_RING can load balance per flow.
    # Possible values are cluster_flow or cluster_round_robin.
    cluster-type: cluster_flow

    # bpf filter for this interface
    #bpf-filter: tcp

    # If bypass is set then the PF_RING hw bypass is activated, when supported
    # by the network interface. Suricata will instruct the interface to bypass
    # all future packets for a flow that need to be bypassed.
    #bypass: yes

    # Choose checksum verification mode for the interface. At the moment
    # of the capture, some packets may have an invalid checksum due to
    # the checksum computation being offloaded to the network card.
    # Possible values are:
    #  - rxonly: only compute checksum for packets received by network card.
    #  - yes: checksum validation is forced
    #  - no: checksum validation is disabled
    #  - auto: Suricata uses a statistical approach to detect when
    #  checksum off-loading is used. (default)
    # Warning: 'checksum-validation' must be set to yes to have any validation
    #checksum-checks: auto
  # Second interface
  #- interface: eth1
  #  threads: 3
  #  cluster-id: 93
  #  cluster-type: cluster_flow
  # Put default values here
  - interface: default
    #threads: 2
```
### 1.6.14 Rules規則讀取目錄

```
default-rule-path: /etc/suricata/rules

rule-files:
  - *.rules
```
### 1.6.15 Auxiliary configuration files
介紹classification.config(待補)
```
classification-file: /etc/suricata/classification.config
reference-config-file: /etc/suricata/reference.config
# threshold-file: /etc/suricata/threshold.config
```
### 1.6.16 Include other configs

可包含其它的 Suricata設定檔( include: 設定檔.yaml)
```
# Includes:  Files included here will be handled as if they were in-lined
# in this configuration file. Files with relative pathnames will be
# searched for in the same directory as this configuration file. You may
# use absolute pathnames too.
# You can specify more than 2 configuration files, if needed.
#include: include1.yaml
#include: include2.yaml
```
## 2 Suricata規則

基本格式:
- 動作(Action)
- 標頭(header)
    - 協定(Protocal)
    - 來源位址(Src_ip)
    - 來源埠(Src_port)
    - 方向(Direction)
    - 目的位址(Dst_ip)
    - 目的埠(Dst_port)
- 規則內容(Rule options)

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

### 2.1 動作(Action)
此參數告訴Suricata對於其匹配的封包進行何種動作，其有效操作包括為:

- alert-生成告警，並對封包放行(大多為此)
- pass-停止對封包進行進一步的檢查
- drop-丟棄該封包並生成告警，其接收端將未收到正發生的信息，因而導致timeout
- reject-將RST/ICMP未送達錯誤信息回傳至封包的送出者
- rejectsrc-與reject相同
- rejectdst-將RST/ICMP錯誤封包送至匹配的接收者
- rejectboth-將RST/ICMP錯誤封包送給此對話的兩端


### 2.2 協定(Protocal)
這部分keywords再告訴Suricata匹配的規則包含為何種協定
基本協定:
- tcp
- udp
- icmp
- ip
應用層協定:
- http
- ftp
- tls
- dns
- smtp
.
.
.

### 2.3 來源及目的位址

|Operator|Description|
|--------|--------|
| ../.. |IP的範圍(CIDR表示法)|
|!|除此之外|
|[..,..]|分組|

|Example|Meaning|
|--------|--------|
|!1.1.1.1|除了1.1.1.1之外的每一IP位址|
|$HOME_NET|於yaml設定檔設定的HOME_NET值|
|[$EXTERNAL_NET,!$HOME_NET]|為EXTERNAL_NET且非HOME_NET|
|[10.0.0.0/24,!10.0.0.5]|10.0.0.0/24網段，除了10.0.0.5之外
|
### 2.4 來源及目的埠
|Operator|Description|
|--------|--------|
| .. |port範圍|
|!|除此之外|
|[..,..]|分組|

|Example|Meaning|
|--------|--------|
|[80,81,82]|81,82,83三個port|
|[80:84]|80~84包含範圍的port|
|[1024:]|1024~最高的port|
|!80|除80之外的port|
|[80:100,!99]|80~100,除了99|
|1:80,![2,4]|1~80的範，但不包含2及4|

### 2.5 方向(Direction)
方向性有向右箭頭及雙向箭頭，雙向箭頭表示雙向接匹配規則，並沒有向左的箭頭(<-)單向一律往右

source(來源) -> destination(目的)
source <> destination(目的)

### 2.6 規則內容(Rule options)
規則內容由()中撰寫其內容為如下格式方式編寫
```
(<keyword>:<settings>;<keyword>:<settings>;.....)
```
由於(")雙引號及(;)分號再Suricata特殊意義，如需加進規則中需使用跳脫字源的方式來表示(\)
```
(msg:"Message with example\;";)
```




