modSecurity規則學習(三)——SecRule


通用格式
SecRule VARIABLES OPERATOR [TRANSFORMATION_FUNCTIONS, ACTIONS]
 
階段phase
(1)request headers
(2)request body
(3)response headers
(4)response body
(5) logging
 

一、變量variable

綠色:請求變量  藍色:server變量  紫色:響應變量 紅色:請求體解析變量 黑色:時間變量 橙色:實體變量
ModSecurity

Request variables 請求變量
Request variables are those extracted from the request part of the transaction that is being
inspected. The variables that describe the request line (request method, URI and protocol
information) and the request headers become available as early as phase 1 and the complete
information will be available for phase 2.

ARGS 請求參數,類型read-only collection
ARGS_COMBINED_SIZE 請求參數的總大小
ARGS_NAMES 請求參數的名字, 類型read-only collection
ARGS_GET 查詢字符串參數,類型read-only collection
ARGS_GET_NAMES 查詢字符串參數,類型read-only collection
ARGS_POST 請求體參數,類型read-only collection
ARGS_POST_NAMES 請求體參數的名字,類型read-only collection
FILES 上傳文件域,類型read-only collection
FILES_COMBINED_SIZE 上傳文件大小
FILES_NAMES 上傳文件表單文件域參數的名字,類型read-only collection
FILES_SIZES 上傳文件的大小,類型read-only collection
FILES_TMPNAMES 文件臨時名字,類型read-only collection
PATH_INFO  URI path
QUERY_STRING 查詢字符串
REQUESET_BASENAME URI basename,同時支持/與\這兩種文件分隔符
REQUEST_BODY 請求體,默認處理application/x-www-form-urlencoded 請求
REQUEST_COOKIES cookie參數
REQUEST_COOKIES_NAMES cookie參數的名字,類型read-only collection
REQUEST_FILENAME URI filename/path 
REQUEST_HEADERS 請求頭,類型read-only collection
REQUEST_HEADERS_NAMES 請求頭參數的名字, 類型read-only collection
REQUEST_LINE  請求行
REQUEST_METHOD 請求方法
REQUEST_PROTOCOL 請求協議
REQUEST_URI   請求URI,但不包括hostname
REQUEST_URI_RAW 請求URI,包括hostname

Server variables
Server variables contain the pieces of information available to the server, most of them valid
only for the transaction being processed at the moment they are evaluated.

AUTH_TYPE  認證類型,代理模式下非本地認證,需要指定Authorization頭
REMOTE_ADDR 遠程地址, 訪問者ip
REMOTE_HOST 遠程host,訪問者hostname,當HostnameLookUps開啟時,為dns解析的域名,否則為ip地址
REMOTE_PORT 遠程端口,訪問者端口
REMOTE_USER 訪問者用戶名
SERVER_ADDR 服務端地址
SERVER_NAME 服務端hostname,取值Host請求頭
SERVER_PORT 服務端端口
SCRIPT_BASENAME 腳本basename, 代理模式不可用
SCRIPT_FILENAME 腳本 filename,代理模式不可用
SCRIPT_GID 腳本group ID,代理模式不可用
SCRIPT_GROUPNAME 腳本 group name,代理模式不可用
SCRIPT_MODE 腳本權限 ,代理模式不可用
1 表示可執行
2 表示可寫
4 表示可讀
7 表示可寫可讀可執行
SCRIPT_UID 腳本 user ID,代理模式不可用
SCRIPT_USERNAME 腳本 user name,代理模式不可用

Response variables
Response variables are those extracted from the response part of the transaction that is being
inspected. Most response variables will be available in phase 3. The arguably most important
response variable, RESPONSE_BODY, is only available in phase 4 (the phase is also called
RESPONSE_BODY).

RESPONSE_BODY 響應體
RESPONSE_CONTENT_LENGTH 響應實體長度,單位bytes
RESPONSE_CONTENT_TYPE 響應實體類型,僅僅在phase3可用
RESPONSE_HEADERS 響應頭,類型read-only collection
在內嵌模式中,像那種會優先將數據發送給客戶端的響應頭是不可獲得的,例如Server,Date,Connection,Content-Type
在代理模式中,階段5可用
RESPONSE_HEADERS_NAMES 響應頭參數的名字,類型read-only collection
在內嵌模式中,像那種會優先將數據發送給客戶端的響應頭是不可獲得的,例如Server,Date,Connection,Content-Type
在代理模式中,階段5可用
RESPONSE_PROTOCOL 響應協議

RESPONSE_STATUS 響應碼,僅代理模式可用

Collections
Collections are the special kind of variables that can contain other variables. With exception
of the persistent collections, all collections are essentially one-offs, special variables that give
access to the information to which ModSecurity has access.

TX  事件內變量, 類型read/write collection
當使用operator @rx或@pm時,TX:0表示capture action捕獲的變量  TX:1-TX:9:表示capture action捕獲的子串 
RULE rule元數據,  類型read/write collection, 用於設置Rule對象的屬性:id,rev,severity,logdata, msg

SESSION session數據,類型read/write collection
僅當setsid action執行后使用, session對象的屬性,SCORE得分, BLOCKED是否阻塞

例如:下面的例子說明了怎么用setsid初始化一個SESSION集合,怎么使用setvar增加session.score的值,怎么設置session.blocked的值,最后怎么拒絕基於session.blocked的值的集合。

SecRule REQUEST_COOKIES:PHPSESSID !^$ chain,nolog,pass

SecAction setsid:%{REQUEST_COOKIES.PHPSESSID}

SecRule REQUEST_URI “^/cgi-bin/finger$” \

“phase:2,t:none,t:lowercase,t:normalizePath,pass,log,setvar:session.score=+10”

SecRule SESSION:SCORE “@gt 50” “pass,log,setvar:session.blocked=q1”

SecRule SESSION:BLOCKED “@eq 1” “log,deny,status:403”

GEO geo信息,類型read-only collection,Geo lookup information from the last @geoLookup invocation (read-only collection)
ENV 環境變量,類型read-only collection,但可以使用setvar來修改變量的值
GLOBAL 全局變量,類型read/write collection
IP  存儲的ip數據 ,類型read/write collection
USER user數據,類型read/write collection
XML xml dom相關的,類型read-only collection

Miscellaneous variables

Miscellaneous variables are exactly what they are called: they are the variables that couldn’t
fit in any other category.

HIGHEST_SEVERITY 嚴重級別,值越小級別越高,255表示未設置嚴重級別

MATCHED_VAR 最近一次匹配的變量
MATCHED_VAR_NAME 最近一次匹配的變量的名字
MODSEC_BUILD modsecurity版本號
SESSION_ID sessionID associated with current transaction
USERID user ID associated with current transaction
WEBAPPID web app ID Web  associated with current transaction
WEBSERVER_ERROR_LOG  server產生的錯誤信息

Time variables
Time variables all represent the moment in time when the transaction that ModSecurity is
processing began.

TIME HH:mm:ss
TIME_DAY 1-31
TIME_EPOCH 
TIME_HOUR 0-23
TIME_MIN 0-59
TIME_MON 0-11
TIME_SEC 0-59
TIME_WDAY 0-6
TIME_YEAR 
DURATION 時間花費,milliseconds

Parsing flags
Parsing flags are used by ModSecurity to signal important parsing events. The idea is to
avoid taking implicit action (e.g., blocking in response to an invalid request), but allow the
rules to decide what to do.

MULTIPART_BOUNDARY_QUOTED  multipart 解析錯誤:boudnary中有引號
MULTIPART_BOUNDARY_WHITESPACE multipart 解析錯誤:boudnary中有空格
MULTIPART_CRLF_LF_LINES multipart 解析錯誤:混合使用\r\n 與\n作為分界線, 當允許使用混合粉各符時設置為1
MULTIPART_DATA_BEFORE multipart 解析錯誤:第一個boudnary前有數據
MULTIPART_DATA_AFTER multipart 解析錯誤:最后一個boudnary后有數據
MUTLIPART_HEADER_FOLDING multipart 解析錯誤:boudnary中
MULTIPART_LF_LINE multipart 解析錯誤:使用\n作為分界線
MULTIPART_SEMICOLON_MISSIONG multipart 解析錯誤:缺少分號
MULTIPART_STRICT_ERROR 當以下值為1時,該值為1; 
REQBODY_PROCESSOR_ERROR
MULTIPART_BOUNDARY_QUOTED
MULTIPART_BOUNDARY_WHITESPACE
MULTIPART_DATA_BEFORE
MULTIPART_DATA_AFTER
MULTIPART_HEADER_FOLDING
MULTIPART_LF_LINE 使用換行做分界線
MULTPART_SEMICOLON_MISSING 分號缺失
MULTPART_INVALID_QUOTING 無效引號
MULTIPART_INVALID_QUOTING  multipart 解析錯誤: 無效引號
MULTIPART_UNMATCHED_BOUDDARY multipart 解析錯誤:不合規范的boudnary,容易漏報
REQBODY_PROCESSOR 處理request解析,內置的解析功能包括URLENCODED, MULTIPART, XML
REQBODY_PROCESSOR_ERROR  request解析錯誤標記,1表示錯誤,0表示ok
REQBODY_PROCESSOR_ERROR_MSG request解析錯誤信息
URLENCODED_ERROR 當解析application/x-www-form-urlencoded格式的請求體出錯時值為1
 
二、操作符 operator
綠色:字符串操作符   藍色:數字操作符  橙色:驗證操作副 
ModSecurity
@beginsWith
@contains
@containsWord
@endsWith
@rx  Regular pattern match 正則
@pm  特征字符串的匹配, 大小不敏感,基於Aho-Corasick匹配算法
@pmFromFile 從文件讀取匹配特征字符串 ,Parallel matching, with arguments from a file
@streq String equal to
@within   Within
@eq 相等 
@ge 大於等於
@gt 大於
@le 小於等於
@lt 小於

Validation operators 驗證操作符
Validation operators, in Table 5.11, “Validation operators”, all validate input in some way.

@validateByteRange 
@validateDTD XML相關
@validateSchema XML相關
@validateUrlEncoding
@validateUtf8Encoding
Miscellaneous operators :雜項操作符
@geoLookup Determines the physical location of an IP address
@inspectFile 使用外部腳本處理 
@rbl  去RBL REAL-TIME BLANKHOLE LISTS反垃圾郵件黑名單里查找ipv4地址,或hostname
@verifyCC  Checks if the parameter is a valid credit card number
 
三、 事件函數transform function
ModSecurity
base64Decode
base64Encode
compressWhitespace
cssDecode
escapeSeqDecode 解碼ANSI C escape 序列
hexDecode
hexEncode
htmlEntityDecode
jsDecode
length
lowercase
md5
none 移除當前rule的所有transformation functions
normalizePath 移除掉多個斜杠
normalizePathWin 移除掉多個斜杠,但首先會將\(win正斜杠) 轉化成 /(linux反斜杠)
parityEven7bit
parityOdd7bit
parityZero7bit
removeNulls 刪除空字節
removeWhiteSpace 刪除空格字符
replaceComments 將c格式的注視語句/*...*/轉換為空格ASCII 32
replaceNulls 將null字節轉換為空格ASCII 32
urlDecode
urlDecodeUni url解碼%uXXXX 編碼范圍FF01 -FF5E
urlEncode
sha1
trimLeft 移除左邊的空格
trimeRight 移除右邊的空格
trim  移除左右兩端的空格
 
 
四、動作action
綠色:disruptive action (每個rule只能有1個disruptive action,如果有多個disruptive action,那么只有最后一個有效,在rule chain中,disruptive action只能出現在第一個rule中)
藍色:flow action 
紫色:metadata action 
紅色 :variable  action
黃色:logging action  
灰色:special action 
黑色:其他
 
ModSecurity
allow 
2.5版本之前是只影響當前階段
 
2.5版本之后,遵守以下規則
(1)如果單獨使用,除了log階段,其他階段都停止處理
(2)如果和參數phase一起使用,allow將停止當前階段的處理,其他階段不受影響
Stop processing of one or more remaining phases
block 相當於占位符,會被上下文的SecDefaultAction 指令中的動作取代
deny 使用錯誤頁面block 當前事務,Block transaction with an error page
drop 斷開網絡連接
pass 繼續執行下一個規則
proxy 代理請求到后端web server
redirect 重定向請求到其他web server

Flow actions
Flow actions (Table 5.14, “Flow actions”) alter the way rules are processed within a phase.

chain 相當於多個規則的and操作
skip 跳過指定的規則,值為跳過的規則個數,不能跳過同一個規則鏈中的規則
skipAfter 調轉到指定的規則

Metadata actions 規則屬性
Metadata actions (Table 5.15, “Metadata actions”) provide additional information about
rules. The information is meant to accompany the error messages to make it easier to understand
why they occurred.

id  設置規則ID
phase 指明處理階段
msg
rev  設置版本號
severity 設置rule的嚴重級別,最好用文本來指定,v2.5.0版本已棄用
tag

Variable actions 變量
Variable actions (Table 5.16, “Variable actions”) deal with variables. They allow you to set,
change and remove variables.

capture 將捕獲結果存入TX變量,可以存儲10個變量,tx變量集合的下標為0-9
deprecatevar 設置指定時間內遞減數字型變量
expirevar 設置指定時間內移除過期的變量
initcol 創建持久性collections,通常在階段1中設置
setenv 設置環境變量
setvar 設置變量
setuid 設置當前事務的user ID
setsid 設置當前事務的session ID

Logging actions
Logging actions (Table 5.17, “Logging actions”) influence the way logging is done. The actions
that influence if logging takes place (auditlog, log, noauditlog, and nolog) only control
current rule affects logging if it matches. To control logging for the transaction as a
whole you’ll need to use the ctl action.

auditlog 將當前事務記錄到審計log中
log   Log error message; implies auditlog
logdata  Log supplied data as part of error message
noauditlog Do not log current transaction to audit log
nolog Do not log error message; implies noauditlog
sanitiseArg 在日志中將指定的請求參數替換為*
sanitiseMatched  在日志中將指定的請求參數,請求頭,響應頭替換為*
sanitiseRequestHeader 在日志中將指定的請求頭替換為*
sanitiseResponseHeader 在日志中將指定的響應頭替換為*
ctl 改變當前事務的配置
可以改變以下配置
ModSecurity 安全規則  checklist - 碳基體 - 碳基體
 
multiMatch 每次變量發生變化會進行一次匹配計算
t 在對變量作匹配操作前指定調用的事務處理函數 
append 響應體中注入內容,該action必須開啟SecContentInjection指令
exec 執行外部腳本或二進制文件
pause 暫定事務處理
prepend 響應體中注入內容,該action必須開啟SecContentInjection指令
status  action 為 deny與redirect action時指定響應碼
xmlns XML專用
 
cloudflare 增加了以下action
disabled  DIS exit_blocked(self, "DIS", rulefile, nolog)
simulate SIM exit_blocked(self, "SIM", rulefile, nolog)
 
五、指令directory
ModSecurity
SecRule
SecRuleInheritance 配置當前環境是否繼承父節點環境(大部分情況下都配置成可繼承,你應當查一下文檔的每一個指令,以明確它繼承與否)
SecRuleRemoveById 使用ID方式從上級環境中刪除規則,
備注:這個指令支持多個參數,每個參數可以是一個規則ID,也可以是范圍。帶有空格的參數必須使用雙引號括起來。
SecRuleRemoveById 1 2 5 10-20 "400-556" 673
SecRuleRemoveByMsg 使用規則方式從上級環境中刪除規則
SecRuleUpdateActionById 更新指定RuleID的rule action
SecRuleScript :這個指令創建一個特殊的規則,執行Lua腳本來決定是否匹配,和SecRule主要的不同是這個沒有目的也沒有操作符,這個腳本可以從ModSecurity環境中取到所有的變量,並使用(Lua)操作符來進行測試,第二個參數可選,與SecRule相同,是一些動作列表。
SecMarker
SecAction
SecDefaultAction 設置默認的action


六、常用操作符
| 或者操作符 e.g.REQUEST_URI|REQUEST_PROTOCOL
 
: 數組取值操作符 e.g. ARGS:p
 
! 非操作符  e.g. ARGS|!ARGS:z
 
@ 操作符函數調用  e.g. @rx
 
t 事務函數調用 e.g.  t:lowercase
 
& 取數組個數符 e.g.  &ARGS @ge 1
 
%{COLNAME.VARNAME}變量擴展符  e.g.    SecRule REQUEST_URI_RAW "!@beginsWith http://%{REQUEST_HEADERS.Host}" "drop,tag:'WEB_ATTACK/ILLEGALHTTPPROTOCOL',msg:'host header        
illegal',id:00001,phase:2"
 
 
轉自:http://danqingdani.blog.163.com/blog/static/18609419520146296181531/
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM