一、ELK安装

1.2 elk配置

logstash自定义配置文件,取名为filebeat_log.conf :

  1. input {
  2. beats {
  3. port => 5044
  4. client_inactivity_timeout => 90
  5. codec => json
  6. }
  7. }
  8. filter {
  9. date {
  10. match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ]
  11. target => ["datetime"]
  12. }
  13. geoip {
  14. source => "remote_addr"
  15. }
  16. mutate {
  17. remove_field => ["tags", "beat"]
  18. }
  19. }
  20. output {
  21. stdout {
  22. codec => rubydebug
  23. }
  24. elasticsearch {
  25. hosts => "localhost:9200"
  26. index => "logstash-%{+YYYY.MM.dd}"
  27. }
  28. }

1.3 启动方法

logstash启动

进入/usr/share/logstash/bin:

  1. nohup ./logstash -f filebeat_log.conf> /dev/null 2>&1 &

二、使用filebeat进行分布式收集

下面以tomcat为例子,分享我的配置文件filebeat.yml(nginx的话,修改paths的路径):

  1. filebeat.prospectors:
  2. - type: log
  3. enabled: true
  4. paths:
  5. - /home/qy/apache-tomcat-9.0.1/logs/localhost_access_log.*.txt
  6. document_type: tomcat-log
  7. scan_frequency: 15s
  8. ignore_older: 20m
  9. close_inactive: 12m
  10. clean_inactive: 30m
  11. close_removed: true
  12. clean_removed: true
  13. ....
  14. #----------------------------- Logstash output --------------------------------
  15. output.logstash:
  16. hosts: ["188.88.88.88:5044"]

直接解压下载的tar包,进入目录修改配置文件。然后启动filebeat:nohup ./filebeat -e -c filebeat.yml >/dev/null 2>&1 &

三、日志格式转json

为方便kibana分析和elastalert的取值,日志的格式要为json格式,上述的logstash配置文件已适配json格式。

公司的应用服务器中均为nginx和tomcat,故本文只介绍tomcat及nginx的json格式配置方法,其他服务器配置方法请自行搜索。

3.1 tomcat的json格式配置

打开config/server.xml,在最后的位置修改log的输出配置为:

  1. <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log" suffix=".txt" pattern="{&quot;time&quot;:&quot;%t&quot;,&quot;remote_addr&quot;:&quot;%h&quot;,&quot;remote_user&quot;:&quot;%l&quot;,&quot;request&quot;:&quot;%r&quot;,&quot;status&quot;:&quot;%s&quot;,&quot;body_bytes_sent&quot;:&quot;%b&quot;,&quot;http_referer&quot;:&quot;%{Referer}i&quot;,&quot;http_user_agent&quot;:&quot;%{User-Agent}i&quot;,&quot;http_x_forwarded_for&quot;:&quot; %{X-Forwarded-For}i&quot;,&quot;request_time&quot;:&quot;%T&quot;,&quot;host&quot;:&quot;%v&quot;,&quot;port&quot;:&quot;%p&quot;}"/>

然后重启tomcat,即生效。

3.2 nginx的json格式配置

  1. 进入`/etc/nginx`打开`nginx.conf`,加入如下配置:
  2. http {
  3. ##
  4. # Basic Settings
  5. ##
  6. sendfile on;
  7. tcp_nopush on;
  8. tcp_nodelay on;
  9. keepalive_timeout 65;
  10. types_hash_max_size 2048;
  11. # server_tokens off;
  12. log_format logstash_json '{"time": "$time_local", '
  13. '"remote_addr": "$remote_addr", '
  14. '"remote_user": "$remote_user", '
  15. '"request": "$request", '
  16. '"status": "$status", '
  17. '"body_bytes_sent": "$body_bytes_sent", '
  18. '"http_referer": "$http_referer", '
  19. '"http_user_agent": "$http_user_agent", '
  20. '"http_x_forwarded_for": "$http_x_forwarded_for", '
  21. '"request_time": "$request_time", '
  22. '"request_length": "$request_length", '
  23. '"host": "$http_host"}';
  24. }

最后nginx -s reload即可

四、使用elastalert进行告警

ElastAlert使用python编写,具有容易上手、文档全等特点,虽然这个工具拥有如此多的优点,在搭建过程还是遇到了很多很多的未知错误,主要原因是网上的资料大多是针对es5.x以前的版本而没什么现成的资料可供参考。

4.1 安装elastalert

  1. git clone https://github.com/Yelp/elastalert.git
  2. cd elastalert
  3. python setup.py install //可能需要sudo
  4. Pip install -r requirements.txt //可能需要sudo
  5. cp config.yaml.example config.yaml

具体的功能本文就不一一介绍了,请自行前往官方文档了解

4.2 创建索引

安装完成后会系统中会自带三个命令:

elastalert-create-indexelastalert-rule-from-kibanaelastalert-test-rule

使用elastalert-create-index,根据提示设置es后按回车默认即可。

​ 配置完索引及配置文件后,可以使用elastalert-test-rule进行测试。这里有个bug,如果出现TransportError(400, u'search_phase_execution_exception', u'No mapping found for [alert_time] in order to sort on')之类的错误,在确认没有其他的问题时,可以先删除索引curl -XDELETE http://localhost:9200/*,再使用elastalert-create-index重新生成索引。

4.3 配置config.yaml

  1. rules_folder: example_rules
  2. # How often ElastAlert will query Elasticsearch
  3. # The unit can be anything from weeks to seconds
  4. run_every:
  5. seconds: 3 #每三秒向es请求数据
  6. # ElastAlert will buffer results from the most recent
  7. # period of time, in case some log sources are not in real time
  8. buffer_time:
  9. minutes: 15
  10. #日志会延迟进入es,这里是配置query的向前的时间范围,这是15分钟,即查询 time[now-15m, now]
  11. # The Elasticsearch hostname for metadata writeback
  12. # Note that every rule can have its own Elasticsearch host
  13. es_host: 188.88.88.88
  14. # The Elasticsearch port
  15. es_port: 9200
  16. # Optional URL prefix for Elasticsearch
  17. #es_url_prefix: elasticsearch
  18. # Connect with TLS to Elasticsearch
  19. #use_ssl: True
  20. # Verify TLS certificates
  21. #verify_certs: True
  22. # GET request with body is the default option for Elasticsearch.
  23. # If it fails for some reason, you can pass 'GET', 'POST' or 'source'.
  24. # See http://elasticsearch-py.readthedocs.io/en/master/connection.html?highlight=send_get_body_as#transport
  25. # for details
  26. #es_send_get_body_as: GET
  27. # Option basic-auth username and password for Elasticsearch
  28. #es_username: someusername
  29. #es_password: somepassword
  30. # The index on es_host which is used for metadata storage
  31. # This can be a unmapped index, but it is recommended that you run
  32. # elastalert-create-index to set a mapping
  33. writeback_index: elastalert_status
  34. # If an alert fails for some reason, ElastAlert will retry
  35. # sending the alert until this time period has elapsed
  36. alert_time_limit:
  37. days: 1

以上各字段的解释:

Rules_folder:用来加载下一阶段rule的设置,默认是example_rules

Run_every:用来设置定时向elasticsearch发送请求

Buffer_time:用来设置请求里时间字段的范围,默认是45分钟

Es_host:elasticsearch的host地址

Es_port:elasticsearch 对应的端口号

Use_ssl:可选的,选择是否用SSL连接es,true或者false

Verify_certs:可选的,是否验证TLS证书,设置为true或者false,默认为- true

Es_username:es认证的username

Es_password:es认证的password

Es_url_prefix:可选的,es的url前缀(我的理解是https或者http)

Es_send_get_body_as:可选的,查询es的方式,默认的是GET

Writeback_index:elastalert产生的日志在elasticsearch中的创建的索引

Alert_time_limit:失败重试的时间限制

4.4 告警配置介绍

example_rules目录中新建yaml配置文件 webattack_frequency.yaml,下面分开介绍这个配置文件的内容(下个小节将分享我的配置文件,此小节仅解释其中的必要设置项):

1、告警规则

ElastAlert支持11种告警规则,本文不一一介绍了,为响应web攻击行为,本文选用的告警规则是frequency

  1. name: web attack
  2. # (Required)
  3. # Type of alert.
  4. # the frequency rule type alerts when num_events events occur with timeframe time
  5. type: frequency
  6. # (Required, frequency specific)
  7. # Alert when this many documents matching the query occur within a timeframe
  8. num_events: 10
  9. # (Required, frequency specific)
  10. # num_events must occur within this amount of time to trigger an alert
  11. timeframe:
  12. minutes: 1
  13. # (Required)
  14. # Index to search, wildcard supported
  15. index: logstash-* #对应logstash的配置文件中output的elasticsearch index前缀
  16. filter:
  17. - query_string:
  18. # sql insert xss detect
  19. query: "request: select.+(from|limit) OR request: union(.*?)select OR request: into.+(dump|out)file "

上述配置文件的意图即是:在一分钟内将匹配query里面的sql注入规则,若匹配次数达到10次,即进行报警。

2、使用邮箱进行告警

ElastAlert提供了 10 多种通知的类型,本文选用的是邮箱告警,还有微信告警钉钉告警,若有需要,请自行配置。

  1. smtp_host: smtp.qiye.163.com
  2. smtp_port: 25
  3. smtp_auth_file: /Users/qy/Downloads/work/elastalert/example_rules/smtp_auth_file.yaml
  4. #回复给那个邮箱
  5. email_reply_to: xxx@163.com
  6. #从哪个邮箱发送
  7. from_addr: xxx@163.com
  8. # (Required)
  9. # The alert is use when a match is found
  10. alert:
  11. - "email"
  12. # (required, email specific)
  13. # a list of email addresses to send alerts to
  14. email:
  15. - "shystartree@163.com"
  16. alert_subject: "web attack may be by {} at @{}"
  17. alert_subject_args:
  18. - remote_addr
  19. - time
  20. alert_text_type: alert_text_only
  21. alert_text: |
  22. 你好,服务器({})可能正在受到web攻击,请采取手段阻止!!!!
  23. ### 截止发邮件前匹配到的请求数:{}
  24. > 发生时间: {}
  25. > timestamp:{}
  26. > attacker's ip: {}
  27. > request: {}
  28. > status:{}
  29. > UA头:{}
  30. >>> 参考来源:{}
  31. alert_text_args:
  32. - host
  33. - num_hits
  34. - time
  35. - "@timestamp"
  36. - remote_addr
  37. - request
  38. - status
  39. - http_user_agent
  40. - source

smtp_auth_file.yaml的配置内容会在下个小节给出,在这个配置中,我自定义了 alert 的内容,更为精确地突出了攻击者ip、受攻击的服务器、攻击事件等信息。

3、减少重复告警的频率

在实际的使用中,若使用上述的配置,受到攻击的时候邮箱将不断地收到邮件,而这些邮件都对应着同一个攻击实例,根本没必要重复收取,于是,我使用了如下的配置:

  1. # 用来区分报警,跟 realert 配合使用,在这里意味着,
  2. # 5 分钟内如果有重复报警,那么当 name 不同时,会当做不同的报警处理,可以是数组
  3. query_key:
  4. - name
  5. # 5 分钟内相同的报警不会重复发送
  6. realert:
  7. minutes: 5
  8. # 指数级扩大 realert 时间,中间如果有报警,
  9. # 则按照 5 -> 10 -> 20 -> 40 -> 60 不断增大报警时间到制定的最大时间,
  10. # 如果之后报警减少,则会慢慢恢复原始 realert 时间
  11. exponential_realert:
  12. hours: 1

在本人实际测试的攻击场景中,发现使用了exponential_realert后,会错过很多告警(这些告警并不是同一个攻击实例),暂时不确定原因,还请读者们自行确定是否开启该设置。

4.5webattack_frequency.yaml及smtp_auth_file.yaml配置文件内容

上述的4.4小节中对每个配置都作了简单的介绍,这里就直接放出web攻击预警的配置文件供各位读者参考。

  1. webattack_frequency.yaml:
  2. # Alert when the rate of events exceeds a threshold
  3. # (Optional)
  4. # Elasticsearch host
  5. #es_host: 188.88.88.88
  6. # (Optional)
  7. # Elasticsearch port
  8. #es_port: 9200
  9. # (OptionaL) Connect with SSL to Elasticsearch
  10. #use_ssl: True
  11. # (Optional) basic-auth username and password for Elasticsearch
  12. #es_username: someusername
  13. #es_password: somepassword
  14. # (Required)
  15. # Rule name, must be unique
  16. name: web attack
  17. realert:
  18. minutes: 5
  19. # (Required)
  20. # Type of alert.
  21. # the frequency rule type alerts when num_events events occur with timeframe time
  22. type: frequency
  23. # (Required)
  24. # Index to search, wildcard supported
  25. index: logstash-*
  26. # (Required, frequency specific)
  27. # Alert when this many documents matching the query occur within a timeframe
  28. num_events: 10
  29. # (Required, frequency specific)
  30. # num_events must occur within this amount of time to trigger an alert
  31. timeframe:
  32. #hours: 4
  33. minutes: 1
  34. # (Required)
  35. # A list of Elasticsearch filters used for find events
  36. # These filters are joined with AND and nested in a filtered query
  37. # For more info: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html
  38. #filter:
  39. #- term:
  40. # some_field: "some_value"
  41. filter:
  42. - query_string:
  43. # sql insert xss detect
  44. query: "request: select.+(from|limit) OR request: union(.*?)select OR request: into.+(dump|out)file OR
  45. request: (base64_decode|sleep|benchmark|and.+1=1|and.+1=2|or%20|exec|information_schema|where%20|union%20|%2ctable_name%20|cmdshell|table_schema) OR
  46. request: (iframe|script|body|img|layer|div|meta|style|base|object|input|onmouseover|onerror|onload) OR
  47. request: .+etc.+passwd OR http_user_agent:(HTTrack|harvest|audit|dirbuster|pangolin|nmap|sqln|-scan|hydra|Parser|libwww|BBBike|sqlmap|w3af|owasp|Nikto|fimap|havij|PycURL|zmeu|BabyKrokodil|netsparker|httperf|bench) OR
  48. status: (400|404|500|501)
  49. NOT (request:_health.html OR remote_addr:222.222.222.222 )
  50. "
  51. smtp_host: smtp.qiye.163.com
  52. smtp_port: 25
  53. smtp_auth_file: /Users/qy/Downloads/work/elastalert/example_rules/smtp_auth_file.yaml
  54. #回复给那个邮箱
  55. email_reply_to: xxx@163.com
  56. #从哪个邮箱发送
  57. from_addr: xxx@163.com
  58. # (Required)
  59. # The alert is use when a match is found
  60. alert:
  61. - "email"
  62. # (required, email specific)
  63. # a list of email addresses to send alerts to
  64. email:
  65. - "shystartree@163.com"
  66. alert_subject: "web attack may be by {} at @{}"
  67. alert_subject_args:
  68. - remote_addr
  69. - time
  70. alert_text_type: alert_text_only
  71. alert_text: |
  72. 你好,服务器({})可能正在受到web攻击,请采取手段阻止!!!!
  73. ### 截止发邮件前匹配到的请求数:{}
  74. > 发生时间: {}
  75. > timestamp:{}
  76. > attacker's ip: {}
  77. > request: {}
  78. > status:{}
  79. > UA头:{}
  80. >>> 参考来源:{}
  81. alert_text_args:
  82. - host
  83. - num_hits
  84. - time
  85. - "@timestamp"
  86. - remote_addr
  87. - request
  88. - status
  89. - http_user_agent
  90. - source
  91. smtp_auth_file.yaml:
  92. user: xxx@163.com
  93. password: password

4.6 运行elastalert

在成功配置完ElastAlert后将生成三个配置文件:

  1. config.yamlwebattack_frequency.yamlsmtp_auth_file.yaml
  • 启动elastalert服务,监听elasticsearch:
  1. nohup python -m elastalert.elastalert --verbose --rule webattack_frequency.yaml >/dev/null 2>&1 &
  • 为实现守护进程的作用,可以配合supervisor进行使用,本文不再阐述。

4.7 运行效果:

当匹配到自定义攻击规则的时候,ElastAlert将会以邮件方式发送告警信息:

  1. web attack may be by 104.38.13.21 at @[13/Jan/2018:16:06:58 +0800]
  2. xxx 发给 shystartree
  3. 你好,服务器(199.222.36.31)可能正在受到web攻击,请采取手段阻止!!!!
  4. ### 截止发邮件前匹配到的请求数:20
  5. > 发生时间: [13/Jan/2018:16:06:58 +0800]
  6. > timestamp:2018-01-13T08:07:04.930Z
  7. > attacker's ip: 184.233.9.121
  8. > request: GET /dbadmin/scripts/setup.php HTTP/1.0
  9. > status:200
  10. > UA头:ZmEu
  11. >>> 参考来源:/log/localhost_access_log.2018-01-13.txt

ElastAlert监控日志告警Web攻击行为---tomcat和nginx日志json格式的更多相关文章

  1. ElastAlert监控日志告警Web攻击行为

    由于公司需要监控web攻击行为,而因某些原因搭不了waf,才不得不用ElastAlert进行告警,此为前提. 一.ELK安装 Elasticsearch 是一个分布式.可扩展.实时的搜索与数据分析引擎 ...

  2. nginx高性能WEB服务器系列之八--nginx日志分析与切割

    nginx系列友情链接:nginx高性能WEB服务器系列之一简介及安装https://www.cnblogs.com/maxtgood/p/9597596.htmlnginx高性能WEB服务器系列之二 ...

  3. 第1节 storm日志告警:1、 - 5、日志监控告警业务需求、代码、集群运行、总结

    如何解决短信或者邮件频繁发送的问题:每次发送的时候都先查询数据库记录,看一下有没有给这个人发送消息,上一次发送消息的时间是什么时候,如果发送时间间隔小于半个小时,就不要再发了 ============ ...

  4. ELK 之三:Kibana 使用与Tomcat、Nginx 日志格式处理

    一:kibana安装: kibana主要是搜索elasticsearch的数据,并进行数据可视化的展现,新版使用nodejs. 1.下载地址: https://www.elastic.co/downl ...

  5. tomcat,nginx日志定时清理

    1. Crontab定时任务 Crontab 基本语法 t1 t2 t3 t4 t5 program 其中 t1 是表示分钟,t2 表示小时,t3 表示一个月份中的第几日,t4 表示月份,t5 表示一 ...

  6. 收集Nginx的json格式日志(五)

    一.配置nginx [root@linux-node1 ~]# vim /etc/nginx/nginx.conf #修改日志格式为json格式,并创建一个nginxweb的网站目录 log_form ...

  7. filebeat收集nginx的json格式日志

    一.在nginx主机上安装filebeat组件 [root@zabbix_server nginx]# cd /usr/local/src/ [root@zabbix_server src]# wge ...

  8. 使用filebeat解析nginx的json格式日志,并且保存原始message字段的值,输出到es中并通过grafana图形化显示

    1.nginx日志调成json样式 log_format json '{"@timestamp":"$time_iso8601",' '"server ...

  9. Logstash动态模板映射收集Nginx的Json格式日志

    Logstash传输给ES的数据会自动映射为5索引,5备份,字段都为text的的索引.这样基本上无法进行数据分析.所以必须将Logstash的数据按照既定的格式存储在ES中,这时候就要使用到ES模板技 ...

随机推荐

  1. 2022徐特立科学营&BIT机器人队电控课程讲义

    目录 \(\cdot\)电控简介 \(\cdot\)认识单片机   什么是单片机   时钟-单片机的脉搏 \(\cdot\)外设及应用   GPIO   PWM   定时器   UART \(\cdo ...

  2. EfficientFormer:轻量化ViT Backbone

    论文:<EfficientFormer: Vision Transformers at MobileNet Speed > Vision Transformers (ViT) 在计算机视觉 ...

  3. .Net CLR R2R编译的原理简析

    前言 躺平了好一段时间了,都懒得动了.本文均为个人理解所述,如有疏漏,请指正. 楔子 金庸武侠天龙八部里面,少林寺至高无上的镇寺之宝,武林人士梦寐以求的内功秘笈易筋经被阿朱偷了,但是少林寺也没有大张旗 ...

  4. go交叉编译,部署到linux上出现cannot execute binray file的解决方案

    写在前面: 了解过常见的项目部署方式后,打算先从最简单的方式开始.没想到踩了大坑.先说下整个部署的过程.    博主是在window上生成linux上的可执行文件.. 具体过程: 1.首先按照网上说的 ...

  5. 第十六天python3 文件IO(二)

    BytesIO操作 io模块中的类 from io import BytesIO 内存中,开辟的一个二进制模式的buffer,可以像文件对象一样操作它: 当close方法被调用的时候,这个buffer ...

  6. python 链表、堆、栈

    简介 很多开发在开发中并没有过多的关注数据结构,当然我也是,因此,我写这篇文章就是想要带大家了解一下这些分别是什么东西. 链表 概念:数据随机存储,并且通过指针表示数据之间的逻辑关系的存储结构. 链表 ...

  7. netdata检测工具的安装与使用

    Netdata 是一款 Linux 性能实时监测工具..以web的可视化方式展示系统及应用程序的实时运行状态(包括cpu.内存.硬盘输入/输出.网络等linux性能的数据). Netdata文档地址: ...

  8. && 和 ||粗解

    可以这么理解 &&是来找假的,如果找到假就返回假,如果找不到,就返回最后一个真 ||是来找真的,如果找到真就返回真,如果找不到,就返回最后一个假 var speed = 12; var ...

  9. 项目操作案例丨西门子PLC通过网关连接ACS800变频器

    本案例控制对象为炉条机.以及蒸汽的控制以及现场数据参数的显示以及报警. PLC 选用西门子 CPU,通过 ET200 IO 模块控制现场设备并监控数据.变频器采用ABB ACS800变频器,将ABB ...

  10. Python 汽车之家 全系车型参数(包含历史停售车型) 最全

    本文仅供学习交流使用,如侵立删!联系方式及demo下载见文末 汽车之家2021 全系车型参数(包含历史停售车型) 2021.10.21更新 增加参数:电动扰流板.无框设计车门.隐藏电动门把手.自动驾驶 ...