elastalert 배치 및 전체 솔루션의 모니터 알람을 구성 할 수

먼저, elastalert 설치

환경

  • CentOS는 : 7.4
  • 파이썬 : 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로 변경하기 이제 기본 파이썬 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

성공적인 설치 후에는 네 개의 명령을 볼 수 있습니다

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 필드가 있습니다.
  • Kibana3 도움 구성에 config.yaml을 생성, 대시 보드에 저장된에서 elastalert - 규칙에서-키바는 필터링 설정을 참조하십시오. 하지만 읽기만하는 것으로 쿼리에 포함되지 않습니다 필터링.
  • elastalert 테스트 규칙 테스트 사용자 정의 구성 규칙 세트입니다.

둘째, 사용

공식 문서 : https://elastalert.readthedocs.io

규칙 문서 : https://elastalert.readthedocs.io/en/latest/ruletypes.html

1 주 설정 파일

먼저 글로벌 구성 생성, config.yaml.example의 주요 구성 파일 템플릿입니다
정력 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

경고 색인을 생성합니다

실행 elastalert 만들 인덱스 명령이 필요한 단계 아니다, ES에서 인덱스를 만들 수 있습니다,하지만 강력하게 만드는 것이 좋습니다. 감사 및 유용에 대한 테스트 및 재시작 횟수에 영향을주지 않고 있기 때문에 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 로그 수집 파이프 라인의 클러스터를 구성하는 모두의, 이제 검색 규칙을 사용하여 키바 가서, 내가 원하는 알람 컨텐츠 필터링, 예를 들어, 내가 알람 통지를 트리거, 요청 상태 코드 404 원 사용 다음 문 쿼리 :

response: 404

그룹이 조건 코드 뒤에 그룹 정의 카프카의 내부가되고, 또한 이상의 기준이 일치 쓸 수 있습니다.

그리고 서버가 규칙을 추가했다 :

정력 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]

전자 메일 알림을 구성 할 때 내부 참고,이 파일이 사서함에 해당하는 사용자 이름과 암호를 저장하는 데 사용되는 외부 파일에 대한 참조가 필요합니다.

정력 /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 시작

시작하는 방법은 두 가지가 있습니다

(1) 규칙 파일의 경로를 지정

python -m elastalert.elastalert --verbose --config config.yaml --rule rules/nginx_404.yaml

(2) 글로벌 경로 config.yaml에서 구성 규칙은 규칙 디렉토리 로딩 규칙에 저장

python -m elastalert.elastalert --verbose

확인 (6)

서비스가 시작되면, 로그가 명확하게, 알람이 발행 한 다음, 다음, 로그에 대한 설명을 볼 수, 바로 기원 인덱스에 존재하지 않는 여러 인터페이스를 요청 (404) 상태의 일부를 만들 수 있으며, 전체 과정을 볼 수 사서함 또한 수신한다.

셋째, 최적화

1, 시동 모드

시작 명령의 최고 단지 전경에서 시작, 힘없는, 당신은 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, 알람 콘텐츠 형식

당신은 알람 내용을 사용자 정의 할 수 있습니다, 내부는 사용하는 것입니다 Pythonformat달성.

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, 모니터링 로그 웹 공격

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 유량 메일 200M 5 분의 합을 초과

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]"

추천

출처www.cnblogs.com/wzxmt/p/12180555.html