正则表达式与测试字符串不匹配

时间:2018-07-16 15:50:29

标签: python regex apache fail2ban

为什么以下正则表达式与以下文本不匹配?

正则表达式:

\[\]\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似乎在用引号引起来的特定字符方面存在问题。)

我对正则表达式或多或少是新的,所以感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

你很近。当您为多个客户端添加重复组时,您没有在其中包含将其分隔的空格。

\[\]\s\[(:?error|\S+:\S+)\]( \[pid \d+(:\S+ \d+)?\])?( \[client <HOST>(:\d{1,5})?\])+ ModSecurity:\s+(?:\[(?:\w+ \"[^\"]*\"|[^\]]*)\]\s*)*Access denied with code [45]\d\d

DEMO