---
title: ModSecurity
tags: Security
---
# ModSecurity
## Sec Rule
- 規則語法
SecRule VARIABLES "OPERATOR" "TRANSFORMATIONS,ACTIONS"
- 1-1 規則範例:URI 網址列包含/index.php,字串轉小寫、阻斷
SecRule REQUEST_URI "@streq /index.php" "id:1,phase:1,t:lowercase,deny"
- 2-1 規則範例:GET 參數值包含 test,字串轉小寫、阻斷
SecRule ARGS_GET "@contains test" "id:1,phase:1,t:lowercase,deny"
- 2-2 規則範例:GET 參數 username 的參數值包含 test,字串轉小寫、阻斷
SecRule ARGS_GET:username "@contains admin" "id:1,phase:1,t:lowercase,deny"
- 3 規則範例:GET 參數值、POST 參數值、COOKIES 包含正規表示式(hello
1|hello 2|hello 3),字串轉小寫、阻斷
SecRule ARGS_GET|ARGS_POST|REQUEST_COOKIES "@rx hello\s\d{1,3}"
"id:2,phase:2,t:lowercase,deny"
- 4-1 規則範例:參數值包含<script>,阻斷(detecting an XSS (Cross Site Scripting) attack)
SecRule ARGS "@contains <script>" "id:1,deny,status:403"
- 4-2 規則範例:參數值包含<script>,字串轉小寫、阻斷
(detecting ?x=<sCript>alert(1);</script>)
SecRule ARGS "@contains <script>" "id:1,deny,status:403,t:lowercase"
- 4-3 規則範例:參數值包含<script>,字串轉小寫、刪除空格、阻斷
(detecting ?x=<sCript >alert(1);</script>)
SecRule ARGS "@contains <script>"
"id:1,deny,status:403,t:lowercase,t:removeWhitespace"
- 4-4 規則範例:參數值包含<script>,字串轉小寫、刪除空格、
htmlEntityDecode、阻斷(detecting ?x=<script>alert(1);</script>
SecRule ARGS "@contains <script>"
"id:1,deny,status:403,t:lowercase,t:removeWhitespace,t:htmlEntityDecode"
SecServerSignature “Microsoft-IIS/5.0“
- 5 規則範例:參數 ip 的參數值包含分號,阻斷
SecRule ARGS:ip ";" "t:none,log,deny,msg:'semi colon test',id:20"
- 6 規則範例:阻斷 SQL injection、阻斷 XSS injection
SecRule ARGS_GET "@detectSQLi" "id:152,log,deny"
SecRule ARGS_POST "@detectSQLi" "id:153,log,deny"
SecRule ARGS_POST "@detectXSS" "id:152,log,deny"
SecRule ARGS_GET "@detectXSS" "id:153,log,deny"
## Exercise
1. 命令列注入攻擊(可以阻擋 8.8.8.8 & uname -a 或 8.8.8.8 && uname -a)
SecRuleEngine On
SecRule ARGS:ip "&"\
"t:none,log,deny,msg:'& deny',id:10"
2. 檔案上傳漏洞攻擊
SecRuleEngine On
SecRule FILES "(?i)\.php$"\
"t:none,log,deny,msg:'PHP file upload blocked',id:1"
3. 基於文件物件模型的跨站腳本攻擊(可以阻擋 GET 參數出現<script>,例如 localhost/hacked/DOM_XSS.phpdefault=English<script>alert('hacked');
</script>)
SecRule ARGS_GET "@contains <script>" "id:1,deny,status:403"
4. 儲存型跨站腳本攻擊(可以阻擋 POST 參數出現<script>,例如<script>alert('hacked');</script>)?
SecRule ARGS_POST "@contains <script>" "id:1,deny,status:403"
---
- Reference:
- https://www.modsecurity.org/CRS/Documentation/making.html
- https://gist.github.com/nopslider/452b652850cf359c3738
- https://cert.tanet.edu.tw/pdf/sub2.pdf
- 屏大課程:資料庫安全實物