Skip to content

Commit

Permalink
Merge pull request #628 from nsano-rururu/add_ssl
Browse files Browse the repository at this point in the history
add ms_teams_ca_certs, ms_teams_ignore_ssl_errors
  • Loading branch information
jertel authored Dec 26, 2021
2 parents 17071b6 + 076dcb4 commit 8dabdba
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- Add metric_agg_script to MetricAggregationRule [#558](https://github.com/jertel/elastalert2/pull/558) - @dequis
- [Alertmanager]Add support for basic authentication - [#575](https://github.com/jertel/elastalert2/pull/575) - @nsano-rururu
- Add support for Kibana 7.16 for Kibana Discover - [#612](https://github.com/jertel/elastalert2/pull/612) - @nsano-rururu
- [MS Teams]Add support for verify SSL certificate - [#628](https://github.com/jertel/elastalert2/pull/628) - @nsano-rururu

## Other changes
- sphinx 4.2.0 to 4.3.0 and tzlocal==2.1 - [#561](https://github.com/jertel/elastalert2/pull/561) - @nsano-rururu
Expand Down
4 changes: 4 additions & 0 deletions docs/source/ruletypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2500,6 +2500,10 @@ Optional:

``ms_teams_alert_fixed_width``: By default this is ``False`` and the notification will be sent to MS Teams as-is. Teams supports a partial Markdown implementation, which means asterisk, underscore and other characters may be interpreted as Markdown. Currenlty, Teams does not fully implement code blocks. Setting this attribute to ``True`` will enable line by line code blocks. It is recommended to enable this to get clearer notifications in Teams.

``ms_teams_ca_certs``: Set this option to ``True`` if you want to validate the SSL certificate.

``ms_teams_ignore_ssl_errors``: By default ElastAlert 2 will verify SSL certificate. Set this option to ``False`` if you want to ignore SSL errors.

Example usage::

alert:
Expand Down
13 changes: 12 additions & 1 deletion elastalert/alerters/teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ def __init__(self, rule):
self.ms_teams_alert_summary = self.rule.get('ms_teams_alert_summary', 'ElastAlert Message')
self.ms_teams_alert_fixed_width = self.rule.get('ms_teams_alert_fixed_width', False)
self.ms_teams_theme_color = self.rule.get('ms_teams_theme_color', '')
self.ms_teams_ca_certs = self.rule.get('ms_teams_ca_certs')
self.ms_teams_ignore_ssl_errors = self.rule.get('ms_teams_ignore_ssl_errors', False)

def format_body(self, body):
if self.ms_teams_alert_fixed_width:
Expand All @@ -32,6 +34,14 @@ def alert(self, matches):
body = self.format_body(body)
# post to Teams
headers = {'content-type': 'application/json'}

if self.ms_teams_ca_certs:
verify = self.ms_teams_ca_certs
else:
verify = not self.ms_teams_ignore_ssl_errors
if self.ms_teams_ignore_ssl_errors:
requests.packages.urllib3.disable_warnings()

# set https proxy, if it was provided
proxies = {'https': self.ms_teams_proxy} if self.ms_teams_proxy else None
payload = {
Expand All @@ -46,7 +56,8 @@ def alert(self, matches):

for url in self.ms_teams_webhook_url:
try:
response = requests.post(url, data=json.dumps(payload, cls=DateTimeEncoder), headers=headers, proxies=proxies)
response = requests.post(url, data=json.dumps(payload, cls=DateTimeEncoder),
headers=headers, proxies=proxies, verify=verify)
response.raise_for_status()
except RequestException as e:
raise EAException("Error posting to ms teams: %s" % e)
Expand Down
2 changes: 2 additions & 0 deletions elastalert/schema.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,8 @@ properties:
ms_teams_theme_color: {type: string}
ms_teams_proxy: {type: string}
ms_teams_alert_fixed_width: {type: boolean}
ms_teams_ca_certs: {type: boolean}
ms_teams_ignore_ssl_errors: {type: boolean}

### Opsgenie
opsgenie_key: {type: string}
Expand Down
61 changes: 58 additions & 3 deletions tests/alerters/teams_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ def test_ms_teams(caplog):
rule['ms_teams_webhook_url'],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None
proxies=None,
verify=True
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
assert ('elastalert', logging.INFO, 'Alert sent to MS Teams') == caplog.record_tuples[0]
Expand Down Expand Up @@ -83,7 +84,8 @@ def test_ms_teams_uses_color_and_fixed_width_text():
rule['ms_teams_webhook_url'],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None
proxies=None,
verify=True
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])

Expand Down Expand Up @@ -119,7 +121,8 @@ def test_ms_teams_proxy():
rule['ms_teams_webhook_url'],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies={'https': rule['ms_teams_proxy']}
proxies={'https': rule['ms_teams_proxy']},
verify=True
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])

Expand Down Expand Up @@ -195,3 +198,55 @@ def test_ms_teams_required_error(ms_teams_webhook_url, expected_data):
assert expected_data == actual_data
except Exception as ea:
assert expected_data in str(ea)


@pytest.mark.parametrize('ca_certs, ignore_ssl_errors, excpet_verify', [
('', '', True),
('', True, False),
('', False, True),
(True, '', True),
(True, True, True),
(True, False, True),
(False, '', True),
(False, True, False),
(False, False, True)
])
def test_ms_teams_ca_certs(ca_certs, ignore_ssl_errors, excpet_verify):
rule = {
'name': 'Test Rule',
'type': 'any',
'ms_teams_webhook_url': 'http://test.webhook.url',
'ms_teams_alert_summary': 'Alert from ElastAlert',
'alert_subject': 'Cool subject',
'alert': []
}
if ca_certs:
rule['ms_teams_ca_certs'] = ca_certs

if ignore_ssl_errors:
rule['ms_teams_ignore_ssl_errors'] = ignore_ssl_errors

rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = MsTeamsAlerter(rule)
match = {
'@timestamp': '2016-01-01T00:00:00',
'somefield': 'foobarbaz'
}
with mock.patch('requests.post') as mock_post_request:
alert.alert([match])
expected_data = {
'@type': 'MessageCard',
'@context': 'http://schema.org/extensions',
'summary': rule['ms_teams_alert_summary'],
'title': rule['alert_subject'],
'text': BasicMatchString(rule, match).__str__()
}
mock_post_request.assert_called_once_with(
rule['ms_teams_webhook_url'],
data=mock.ANY,
headers={'content-type': 'application/json'},
proxies=None,
verify=excpet_verify
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])

0 comments on commit 8dabdba

Please sign in to comment.