监控Nginx日志中的恶意访问是保护网站安全的重要措施。以下是几种有效的方法:
Nginx访问日志(通常位于/var/log/nginx/access.log
)包含大量有价值的信息:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 查找频繁访问的IP
cat /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr
# 查找特定攻击模式
grep -i "select.*from" /var/log/nginx/access.log
grep -i "union.*select" /var/log/nginx/access.log
grep -i "etc/passwd" /var/log/nginx/access.log
grep -i "wp-login.php" /var/log/nginx/access.log
Fail2Ban可以自动分析日志并封禁恶意IP:
sudo apt-get install fail2ban # Debian/Ubuntu
sudo yum install fail2ban # CentOS/RHEL
# /etc/fail2ban/jail.local
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
[nginx-badbots]
enabled = true
filter = nginx-badbots
port = http,https
logpath = /var/log/nginx/access.log
maxretry = 2
Elasticsearch + Logstash + Kibana (ELK) 堆栈可以提供强大的日志分析能力:
input {
file {
path => "/var/log/nginx/access.log"
start_position => "beginning"
}
}
filter {
grok {
match => { "message" => "%{COMBINEDAPACHELOG}" }
}
geoip {
source => "clientip"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
}
}
GoAccess是一个实时的Web日志分析器:
goaccess /var/log/nginx/access.log --log-format=COMBINED
编写Python脚本分析日志:
import collections
import re
def analyze_log(logfile):
ip_counter = collections.Counter()
with open(logfile) as f:
for line in f:
ip = line.split()[0]
ip_counter[ip] += 1
# 检测SQL注入尝试
if re.search(r'union.*select|select.*from|insert into|drop table', line, re.I):
print(f"可能的SQL注入尝试: {line.strip()}")
print("\n访问最频繁的IP:")
for ip, count in ip_counter.most_common(10):
print(f"{ip}: {count}次")
analyze_log('/var/log/nginx/access.log')
需要特别关注的日志特征: - 短时间内大量404错误 - 扫描常见漏洞的URL (如/wp-admin, /phpmyadmin) - 异常的User-Agent (如扫描器、自动化工具) - 包含特殊字符的请求 (如../, %, ', ") - 来自单一IP的高频访问 - 非正常时段的访问高峰
通过以上方法,您可以有效地监控和识别Nginx日志中的恶意访问行为,及时采取防护措施。