【发布时间】:2018-07-16 15:50:29
【问题描述】:
为什么下面的正则表达式与下面的文本不匹配?
正则表达式:
\[\]\s\[(:?error|\S+:\S+)\]( \[pid \d+(:\S+ \d+)?\])? \[client <HOST>(:\d{1,5})?\] ModSecurity:\s+(?:\[(?:\w+ \"[^\"]*\"|[^\]]*)\]\s*)*Access denied with code [45]\d\d
测试字符串:
[Sun Mar 15 22:28:19.733272 2018] [:error] [pid 11954] [client 188.191.122.27:62165] [client 188.191.122.27] ModSecurity: Access denied with code 403 (phase 2). Operator GE matched 4 at TX:anomaly_score. [file ".../modsecurity.d/owasp-modsecurity-crs/rules/REQUEST-949-BLOCKING-EVALUATION.conf"] [line "57"] [id "949110"] [msg "Inbound Anomaly Score Exceeded (Total Score: 5)"] [severity "CRITICAL"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-generic"] [hostname "63.60.128.135"] [uri "/phpmyadmin/phpmyadmin/index.php"] [unique_id "W0uuY3C8AA4EAA5OC7wBAAAH"]
这是一个来自 fail2ban 的预定义规则和一个带有更改地址的随机 apache 日志条目。
一开始以为错误是客户端登录了两次,所以改了客户端行:
(\[client <HOST>(:\d{1,5})?\])+
但这似乎也不起作用。
只是为了弄清楚:
Regular expressions (failregex, ignoreregex) assume that the date/time has been removed from the log line (this is just how fail2ban works internally ATM).
If the format is like „<date...> error 1.2.3.4 is evil“ then you need to match the < at the start so regex should be similar to „^<> <HOST> is evil$„ using <HOST> where the IP/domain name appears in the log line.
(取自 fail2ban 文档:https://fail2ban.readthedocs.io/en/latest/filters.html)(我将其编写为代码,因为 stackoverflow 似乎无法在引号中显示特定字符。)
我对正则表达式或多或少是新手,所以感谢您的帮助。
【问题讨论】:
-
正则表达式以
\[\]开头,但文本不包含[]。 -
那是由于fail2ban。它每行执行两次检查,我不需要检查日期。我认为fail2ban datedetector 会从测试字符串中删除日期。
-
字符串中也没有
<HOST>。 -
如果
fail2ban修改了字符串,您需要发布您尝试匹配的结果字符串,而不是原始字符串。 -
您可以尝试使用 regex101.com 来调试您的正则表达式。
标签: python regex apache fail2ban