まず、elastalertをインストール
環境
- CentOSの:7.4
- Pythonの:3.6.9
- PIP:19.3
- elastalert:0.2.1
- ヘラジカ:7.3.2
2、設定Python3.6.9環境
インストールの依存関係
yum -y install wget openssl openssl-devel gcc gcc-c++
ダウンロードパッケージ
wget https://www.python.org/ftp/python/3.6.9/Python-3.6.9.tgz
インストール
tar xf Python-3.6.9.tgz
cd Python-3.6.9./configure --prefix=/usr/local/python --with-openssl
make && make install
コンフィギュレーション
mv /usr/bin/python /usr/bin/python_old
ln -s /usr/local/python/bin/python3 /usr/bin/python
ln -s /usr/local/python/bin/pip3 /usr/bin/pip
pip install --upgrade pip
たとえば、すべてのスクリプトがpython2を依存していること#注意、python2.7に変更する必要があり、なぜなら、デフォルトのpython 3.6、
sed -i '1s/python/python2.7/g' /usr/bin/yum
sed -i '1s/python/python2.7/g' /usr/libexec/urlgrabber-ext-down
検証
$ python -V
Python 3.6.9
$ pip -V
pip 19.3 from /usr/local/python/lib/python3.6/site-packages/pip (python 3.6)
3、インストールelastalert
ダウンロードパッケージ
git clone https://github.com/Yelp/elastalert.git
cd elastalert
インストール
pip install "elasticsearch<7,>6"
pip install -r requirements.txt
python setup.py install
インストールが成功した後、次の4つのコマンドを見ることができます
ll /usr/local/python/bin/elastalert*
/usr/local/python/bin/elastalert
/usr/local/python/bin/elastalert-create-index
/usr/local/python/bin/elastalert-rule-from-kibana
/usr/local/python/bin/elastalert-test-rule
ln -s /usr/local/python/bin/elastalert* /usr/bin
- elastalert作成・インデックスは、インデックスを作成し、ElastAlertは、デフォルトでは、インデックスに格納されているレコード、elastalert_statusという名前のインデックスを実行します。これらの_typeの四、自分の@timestampフィールドを持っているので、同じ缶も、このインデックスのログ・レコード・kibanaケースを表示するために使用されます。
- Kibana3はヘルプが構成でconfig.yamlを生成し、ダッシュボードに保存されてからelastalert-ルールから-kibanaは、フィルタリングの設定をお読みください。しかし、それだけでクエリを含まない、フィルタリング読まれることに注意してください。
- elastalertテスト・ルールのテストカスタム構成ルールセット。
第二に、使用
公式文書:https://elastalert.readthedocs.io
ルールドキュメント:https://elastalert.readthedocs.io/en/latest/ruletypes.html
1、メインの設定ファイル
最初は、グローバルコンフィギュレーション生成、config.yaml.exampleのメインの設定ファイルのテンプレートです
vimのconfig.yamlを
# 用来加载rule的目录,默认是example_rules
rules_folder: rules
# 用来设置定时向elasticsearch发送请求,也就是告警执行的频率
run_every:
seconds: 30
# 用来设置请求里时间字段的范围
buffer_time:
seconds: 30
# elasticsearch的host地址,端口
es_host: 10.2.13.3
es_port: 9200
# elastalert产生的日志在elasticsearch中的创建的索引
writeback_index: elastalert_status
writeback_alias: elastalert_alerts
# 失败重试的时间限制
alert_time_limit:
days: 2
アラートのインデックスを作成します。2.
ESにインデックスを作成するために実行elastalert作成-indexコマンド、これは必要なステップではありませんが、強くあなたが作成することをお勧めします。監査と便利のためのテスト、および再起動回数やESには影響しませんので、警告を送りました。
Elastic Version: 7.3.2
Reading Elastic 6 index mappings:
Reading index mapping 'es_mappings/6/silence.json'
Reading index mapping 'es_mappings/6/elastalert_status.json'
Reading index mapping 'es_mappings/6/elastalert.json'
Reading index mapping 'es_mappings/6/past_elastalert.json'
Reading index mapping 'es_mappings/6/elastalert_error.json'
New index elastalert_status created
Done!
この出力を参照してください、成功の作成手順について、あなたはそれを要求して見ることができます。
カール127.0.0.1:9200/_cat/indices?v
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
green open elastalert_status_status lh8LL4iCQeSn0afyzxBX7w 1 1 0 0 460b 230b
green open elastalert_status i7B7IfCuSb2Sex8U5KoTZg 1 1 0 0 460b 230b
green open elastalert_status_past et2aF44VR4WQnxB8T7zD4Q 1 1 0 0 460b 230b
green open elastalert_status_silence lhXHEsuUQeGZaW3cRLp5pQ 1 1 0 0 460b 230b
green open elastalert_status_error zykwk4KtSyyOY7ckxQTrkA 1 1 0 0 460b 230b
3、ルールの設定
すべてのアラームルールは、プロファイルを作成することで、プレゼンテーションの作成など、ルールヘッド、シンプルで定義されています。
まず、私はヘラジカnginxのログ収集パイプラインでクラスタを設定する必要があり、すべての、今検索ルールを使用してkibanaを行く、私が欲しいのアラーム内容アウトフィルタは、例えば、私はアラーム通知をトリガー、要求のステータスコードで404にしたい、使用次の文のクエリ:
response: 404
グループは、グループ定義カフカの内部であり、条件コードの後ろに、また、より多くの基準の一致を書き込むことができます。
その後、サーバは、ルールを追加してきました:
vimのnginx_404.yaml
name: Nginx_err
use_strftine_index: true
index: nginx_info*
type: any
aggregation:
seconds: 10
filter:
- query:
query_string:
query: "groups: nginx AND response: 404"
alert:
- "email"
email:
- "[email protected]"
smtp_host: smtp.163.com
smtp_port: 25
smtp_auth_file: /opt/elastalert/smtp_auth_file.yaml
from_addr: [email protected]
email_reply_to: [email protected]
電子メール通知を設定する際に内部の注意は、このファイルがメールボックスに対応するユーザー名とパスワードを格納するために使用され、外部ファイルへの参照が必要です。
vimの/opt/elastalert/smtp_auth_file.yaml
user: "[email protected]"
password: "xxxxxxx"
4、テストルール
ただ、ルールを追加している、あなたは今、あなたが追加したルールをテストするために、独自のコマンドを使用することができます。
elastalert-テストルール--config config.yaml nginx_404.yaml
INFO:elastalert:Note: In debug mode, alerts will be logged to console but NOT actually sent.
To send them but remain verbose, use --verbose instead.
Didn't get any results.
INFO:elastalert:Note: In debug mode, alerts will be logged to console but NOT actually sent.
To send them but remain verbose, use --verbose instead.
1 rules loaded
.........
elastalert_status - {'rule_name': 'Nginx_err', 'endtime': datetime.datetime(2020, 1, 11, 7, 30, 59, 793352, tzinfo=tzutc()), 'starttime': datetime.datetime(2020, 1, 10, 7, 30, 59, 793352, tzinfo=tzutc()), 'matches': 0, 'hits': 0, '@timestamp': datetime.datetime(2020, 1, 11, 7, 31, 0, 76042, tzinfo=tzutc()), 'time_taken': 0.24003815650939941}
エラーがない場合には、利用できます。
5、スタート
開始するには、2つの方法があります。
(1)ルールファイルのパスを指定します
python -m elastalert.elastalert --verbose --config config.yaml --rule rules/nginx_404.yaml
ルールディレクトリローディング規則に格納されたグローバルパスconfig.yaml、構成規則(2)
python -m elastalert.elastalert --verbose
確認してください6。
サービスが開始した後、ログは明らかに、アラームが発行され、あなたは、それから、ログの説明を参照してくださいする必要があり、ちょうど起源インデックスには存在しないいくつかのインタフェースを要求する404の状態のいくつかを作ったことができ、プロセス全体を見ることができ、メールボックスまた、受信しなければなりません。
第三に、最適化
1、起動モード
Startコマンドのトップがちょうどフォアグラウンドで起動し、強制することはありません、あなたはnohupをを使用して起動することができ、またはsupervisord管理により、より便利になります。
supervisordインストール方法は言えません。
プロファイルを作成します。
$cat /etc/supervisord.d/elastalert1.ini
[program:elastalert1]
directory=/data/elastalert1/
command=python -m elastalert.elastalert --verbose --config /data/elastalert1/config.yaml
process_name=elastalert1
autorestart=true
startsecs=15
stopsignal=INT
stopasgroup=true
killasgroup=true
redirect_stderr=true
stdout_logfile=/data/log/elastalert1.log
stdout_logfile_maxbytes=5MB
次に、あなたが開始することができます
supervisorctl update
supervisorctl start elastalert1
2、アラーム
など、電子メール、マイクロ文字、爪、ポスト、同様に、我々は次のような共通の導入elastalertアラーム、多くの方法があります。
(1)電子メールアラート
alert:
- "email"
email:
- "[email protected]"
smtp_host: smtp.163.com
smtp_port: 25
smtp_auth_file: /opt/elastalert/smtp_auth_file.yaml
from_addr: [email protected]
email_reply_to: [email protected]
修正/opt/elastalert/smtp_auth_file.yaml情報
(2)マイクロチャネルアラームロボット
git clone https://github.com/anjia0532/elastalert-wechat-plugin.git
cd elastalert-wechat-plugin/elastalert_modules/* elastalert_modules/
アラームを追加
alert:
- "elastalert_modules.wechat_qiye_alert.WeChatAlerter"
#后台登陆后【设置】->【权限管理】->【普通管理组】->【创建并设置通讯录和应用权限】->【CorpID,Secret】
#设置微信企业号的appid
corp_id: xxx
#设置微信企业号的Secret
secret: xxx
#后台登陆后【应用中心】->【选择应用】->【应用id】
#设置微信企业号应用id
agent_id: xx
#部门id
party_id: xx
#用户微信号
user_id: xx
# 标签id,多个用 | 分隔
(3)アラーム釘打
git clone https://github.com/xuyaoqiang/elastalert-dingtalk-plugin.git
cp elastalert-dingtalk-plugin/elastalert_modules/dingtalk_alert.py elastalert_modules/
アラームを追加
alert:
- "elastalert_modules.dingtalk_alert.DingTalkAlerter"
dingtalk_webhook: "https://oapi.dingtalk.com/robot/send?access_token=fb6500f4c85b8cfe66fa9586870f3ce16c848eab1e1cb23110388d6d443f1e"
dingtalk_msgtype: text
3、警報頻度
#限定时间内,发生事件次数
num_events: 3
#与上面参数结合使用,表示在2分钟内发生3次就报警
timeframe:
minutes: 2
繰り返しアラームを回避するために4、
、あなたが設定することができ、一定期間で繰り返しアラームを避けるrealert
とexponential_realert
二つのオプション:
# 5分钟内相同的报警不会重复发送
realert:
minutes: 5
# 指数级扩大 realert 时间,中间如果有报警,
# 则按照5->10->20->40->60不断增大报警时间到制定的最大时间,
# 如果之后报警减少,则会慢慢恢复原始realert时间
exponential_realert:
hours: 1
5、同じ重合警報
# 根据报警的内容将相同的报警按照 name 来聚合
aggregation_key: name
# 聚合报警的内容,只展示 name 与 message
summary_table_fields:
- name
- message
6、アラームのコンテンツフォーマット
あなたは、内部が使用され、アラームの内容をカスタマイズすることができますPython
がformat
実現します。
alert_subject: "Error {1} @{2}"
alert_subject_args:
- name
- "@timestamp"
alert_text_type: alert_text_only
alert_text: |
> Name: {1}
> Message: {2}
> Host: {3} ({4})
alert_text_args:
- name
- message
- hostname
- host
最後に、比較的完全なプロフィールを仕上げ
name: test_err
use_strftine_index: true
index: filebeat-7.3.2-*
type: any
#将多个匹配项汇总到一个警报中。每次找到匹配项时,ElastAlert将等待该aggregation时间段,并将特定规则在该时间段内发生的所有匹配项一起发送。
aggregation:
seconds: 10
#限定时间内,发生事件次数
num_events: 3
#与上面参数结合使用,在几分钟内
timeframe:
minutes: 2
realert:
# 5分钟内相同的报警不会重复发送
minutes: 5
# 指数级扩大 realert 时间,中间如果有报警,
# 则按照5->10->20->40->60不断增大报警时间到制定的最大时间,
# 如果之后报警减少,则会慢慢恢复原始realert时间
exponential_realert:
hours: 1
filter:
- query:
query_string:
query: "404"
alert:
- "email"
#在邮件正文会显示你定义的alert_text
alert_text: "You have a err message!"
#用户认证文件,需要user和password两个属性
smtp_host: smtp.163.com
smtp_port: 25
smtp_auth_file: /opt/elastalert/smtp_auth_file.yaml
#从哪个邮箱发送
from_addr: [email protected]
#回复给那个邮箱
email_reply_to: [email protected]
email:
#接收报警邮件的邮箱
- "[email protected]"
第四に、例えば、
1、ログのWeb攻撃を監視
1.1 nginxのログ形式を変更します
log_format logstash_json '{"time": "$time_local", '
'"remote_addr": "$remote_addr", '
'"remote_user": "$remote_user", '
'"request": "$request", '
'"status": "$status", '
'"body_bytes_sent": "$body_bytes_sent", '
'"http_referer": "$http_referer", '
'"http_user_agent": "$http_user_agent", '
'"http_x_forwarded_for": "$http_x_forwarded_for", '
'"request_time": "$request_time", '
'"request_length": "$request_length", '
'"host": "$http_host"}';
ルールを書く監視1.2
name: web attack
realert:
minutes: 5
index: logstash-*
type: frequency
num_events: 10
timeframe:
minutes: 1
query_key:
- name
realert:
minutes: 5
exponential_realert:
hours: 1
filter:
- query_string:
# sql insert xss detect
query: "request: select.+(from|limit) OR request: union(.*?)select OR request: into.+(dump|out)file OR
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
request: (iframe|script|body|img|layer|div|meta|style|base|object|input|onmouseover|onerror|onload) OR
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
status: (400|404|500|501)
NOT (request:_health.html OR remote_addr:222.222.222.222 )
"
smtp_host: smtp.qiye.163.com
smtp_port: 25
smtp_auth_file: /opt/elastalert/smtp_auth_file.yaml
email_reply_to: [email protected]
from_addr: [email protected]
alert:
- "email"
email:
- "[email protected]"
alert_subject: "web attack may be by {0} at @{1}"
alert_subject_args:
- remote_addr
- time
alert_text_type: alert_text_only
alert_text: |
你好,服务器({})可能正在受到web攻击,请采取手段阻止!!!!
### 截止发邮件前匹配到的请求数:{}
> 发生时间: {}
> timestamp:{}
> attacker's ip: {}
> request: {}
> status:{}
> UA头:{}
>>> 参考来源:{}
alert_text_args:
- host
- num_hits
- time
- "@timestamp"
- remote_addr
- request
- status
- http_user_agent
- source
2、流量は、メールでの5分の合計を超える200M
run_every:
minutes: 5
name: flow
type: metric_aggregation
index: nginx_info
buffer_time:
minutes: 5
metric_agg_key: body_bytes_sent
metric_agg_type: sum
max_threshold: 209715200
use_run_every_query_size: true
alert_text_type: alert_text_only
alert_subject: "Alter 最近五分钟流量超200M,请注意!!!"
alert_text: |
最近五分钟总流量: {0} B
kibana url: http://xxxxx
alert_text_args:
- metric_body_bytes_sent_sum
smtp_host: smtp.qq.com
smtp_port: 25
smtp_auth_file: /opt/elastalert/smtp_auth_file.yaml
from_addr: "[email protected]"
alert:
- "email"
email:
- "[email protected]"
3、メール要求を送信するために3秒以上の後端
es_host: 192.168.20.6
es_port: 9200
run_every:
seconds: 30
name: xxx_reponse_time
index: n-xxx-*
type: whitelist
compare_key: "request"
ignore_null: true
whitelist:
- /index.html
- /siteapp/ecsAuthentication/hasAuthentication
type: frequency
num_events: 1
timeframe:
seconds: 30
filter:
- query_string:
query: "upstream_response_time: >3 "
alert_text_type: alert_text_only
alert_subject: "Alter {0} 接口后端处理超过3秒!!!"
alert_subject_args:
- _index
html_table_title: "<h2>This is a heading</h2>"
alert_text: |
timestamp: {0}
request_method: {1}
request: {2}
request_body: {3}
request_time: {4} s
upstream_response_time: {5} s
body_bytes_sent: {6} B
status: {7}
remote_addr: {8}
http_x_forwarded_for: {9}
upstream_addr: {10}
agent: {11}
alert_text_args:
- timestamp
- request_method
- request
- request_body
- request_time
- upstream_response_time
- body_bytes_sent
- status
- remote_addr
- http_x_forwarded_for
- upstream_addr
- agent
smtp_host: smtp.qq.com
smtp_port: 25
smtp_auth_file: /opt/elastalert/rule_templates/smtp_auth_file.yaml
from_addr: "[email protected]"
alert:
- "email"
email:
- "[email protected]"