Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
integrations: Fix Thinkst Canary integration.
David Woodf1c9d9c2fedb
diff --git a/static/images/integrations/logos/thinkst.svg b/static/images/integrations/logos/thinkst.svgindex 9a1af49dec5..6bd4dff7fd7 100644--- a/static/images/integrations/logos/thinkst.svg+++ b/static/images/integrations/logos/thinkst.svg@@ -1,102 +1 @@-<?xml version="1.0" encoding="UTF-8" standalone="no"?>-<svg- xmlns:dc="http://purl.org/dc/elements/1.1/"- xmlns:cc="http://creativecommons.org/ns#"- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"- xmlns:svg="http://www.w3.org/2000/svg"- xmlns="http://www.w3.org/2000/svg"- xmlns:xlink="http://www.w3.org/1999/xlink"- height="38.599998"- width="38.400002"- xml:space="preserve"- viewBox="0 0 38.400002 38.599998"- y="0px"- x="0px"- id="Camada_1"- version="1.1"><metadata- id="metadata3867"><rdf:RDF><cc:Work- rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type- rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs- id="defs3865" />-<style- id="style3810"- type="text/css">- .st0{clip-path:url(#SVGID_2_);fill:#36D27E;}- .st1{clip-path:url(#SVGID_4_);fill:#FF2D2F;}- .st2{clip-path:url(#SVGID_6_);}- .st3{clip-path:url(#SVGID_8_);fill:#525252;}-</style>-<g- transform="translate(-16.9,-120.7)"- id="g3860">- <g- id="g3822">- <g- id="g3820">- <defs- id="defs3813">- <path- d="m 16.9,152.2 v -30.6 c 0,-0.5 0.4,-0.8 0.8,-0.8 h 30.5 c -0.9,0.9 -1.5,2.2 -1.5,3.5 0,2.8 2.3,5.1 5.1,5.1 1.4,0 2.6,-0.6 3.5,-1.4 v 30.5 c 0,0.5 -0.4,0.8 -0.8,0.8 H 34.7 v 0 c 8,-4.9 9.6,-12.1 8.5,-15 -1.4,-3.9 1.4,-9.9 1.4,-9.9 0,0 4.6,-1.7 4.6,-2.3 0,-0.3 -4.5,-0.2 -4.5,-0.2 -10.8,-7.7 -15,4 -16,8.2 -2.5,0.3 -9.2,9.9 -9.2,9.9 -0.8,0.3 -1.7,1 -2.6,2.2 z"- id="SVGID_1_" />- </defs>- <clipPath- id="SVGID_2_">- <use- height="100%"- width="100%"- y="0"- x="0"- id="use3815"- style="overflow:visible"- xlink:href="#SVGID_1_" />- </clipPath>- <rect- style="fill:#36d27e"- id="rect3818"- clip-path="url(#SVGID_2_)"- height="41.5"- width="41.299999"- class="st0"- y="119.3"- x="15.5" />- </g>- </g>- <g- id="g3834">- <g- id="g3832">- <defs- id="defs3825">- <path- d="m 51.8,127.7 c 1.9,0 3.5,-1.6 3.5,-3.5 0,-1.9 -1.6,-3.5 -3.5,-3.5 -1.9,0 -3.5,1.6 -3.5,3.5 0.1,2 1.6,3.5 3.5,3.5 z"- id="SVGID_3_" />- </defs>- <clipPath- id="SVGID_4_">- <use- height="100%"- width="100%"- y="0"- x="0"- id="use3827"- style="overflow:visible"- xlink:href="#SVGID_3_" />- </clipPath>- <rect- style="fill:#ff2d2f"- id="rect3830"- clip-path="url(#SVGID_4_)"- height="9.8000002"- width="9.8000002"- class="st1"- y="119.3"- x="46.900002" />- </g>- </g>-- <g- id="g3858">-- </g>-</g>-</svg>\ No newline at end of file+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="38.6" width="38.4" xml:space="preserve" y="0" x="0" id="Camada_1" version="1.1"><style id="style3810" type="text/css"/><g transform="translate(-16.9 -120.7)" id="g3860"><g id="g3822"><g id="g3820"><defs id="defs3813"><path d="M16.9 152.2v-30.6c0-.5.4-.8.8-.8h30.5c-.9.9-1.5 2.2-1.5 3.5 0 2.8 2.3 5.1 5.1 5.1 1.4 0 2.6-.6 3.5-1.4v30.5c0 .5-.4.8-.8.8H34.7c8-4.9 9.6-12.1 8.5-15-1.4-3.9 1.4-9.9 1.4-9.9s4.6-1.7 4.6-2.3c0-.3-4.5-.2-4.5-.2-10.8-7.7-15 4-16 8.2-2.5.3-9.2 9.9-9.2 9.9-.8.3-1.7 1-2.6 2.2z" id="SVGID_1_"/></defs><clipPath id="SVGID_2_"><use height="100%" width="100%" y="0" x="0" id="use3815" xlink:href="#SVGID_1_" overflow="visible"/></clipPath><path id="rect3818" clip-path="url(#SVGID_2_)" fill="#36d27e" d="M15.5 119.3h41.3v41.5H15.5z"/></g></g><g id="g3834"><g id="g3832"><defs id="defs3825"><path d="M51.8 127.7c1.9 0 3.5-1.6 3.5-3.5s-1.6-3.5-3.5-3.5-3.5 1.6-3.5 3.5c.1 2 1.6 3.5 3.5 3.5z" id="SVGID_3_"/></defs><clipPath id="SVGID_4_"><use height="100%" width="100%" y="0" x="0" id="use3827" xlink:href="#SVGID_3_" overflow="visible"/></clipPath><path id="rect3830" clip-path="url(#SVGID_4_)" fill="#ff2d2f" d="M46.9 119.3h9.8v9.8h-9.8z"/></g></g></g></svg>\ No newline at end of filediff --git a/static/images/integrations/thinkst/001.png b/static/images/integrations/thinkst/001.pngindex 618d92c76c4..0195f08e93a 100644Binary files a/static/images/integrations/thinkst/001.png and b/static/images/integrations/thinkst/001.png differdiff --git a/zerver/lib/integrations.py b/zerver/lib/integrations.pyindex a4d69e03e8b..7fcf3c7e000 100644--- a/zerver/lib/integrations.py+++ b/zerver/lib/integrations.py@@ -613,7 +613,7 @@ DOC_SCREENSHOT_CONFIG: Dict[str, List[ScreenshotConfig]] = {'stripe': [ScreenshotConfig('charge_succeeded__card.json')],'taiga': [ScreenshotConfig('userstory_changed_status.json')],'teamcity': [ScreenshotConfig('success.json'), ScreenshotConfig('personal.json', '002.png')],- 'thinkst': [ScreenshotConfig('canarytoken_real.json')],+ 'thinkst': [ScreenshotConfig('canary_consolidated_port_scan.json')],'transifex': [ScreenshotConfig('', extra_params={'project': 'Zulip Mobile','language': 'en','resource': 'file',diff --git a/zerver/webhooks/thinkst/fixtures/canary_alert_no_reverse_dns.json b/zerver/webhooks/thinkst/fixtures/canary_alert_no_reverse_dns.jsondeleted file mode 100644index af2f08a808c..00000000000--- a/zerver/webhooks/thinkst/fixtures/canary_alert_no_reverse_dns.json+++ /dev/null@@ -1,26 +0,0 @@-{- "CanaryName": "0000000testnode",- "Description": "Dummy Incident",- "Timestamp": "2020-06-09 13:59:38 (UTC)",- "CanaryIP": "1.1.1.1",- "AlertType": "CanaryIncident",- "Intro": "This is a dummy incident.",- "IncidentHash": "aa875f255f94e3ffe40dc85cf1a8b1e0",- "CanaryPort": 8080,- "SourceIP": "2.2.2.2",- "AdditionalDetails": [- [- "Field1",- "VALUE1"- ],- [- "Field2",- "VALUE2"- ],- [- "Field3",- "VALUE3"- ]- ],- "CanaryID": "0000000testnode"-}diff --git a/zerver/webhooks/thinkst/fixtures/canary_consolidated_port_scan.json b/zerver/webhooks/thinkst/fixtures/canary_consolidated_port_scan.jsonnew file mode 100644index 00000000000..407402c3811--- /dev/null+++ b/zerver/webhooks/thinkst/fixtures/canary_consolidated_port_scan.json@@ -0,0 +1,32 @@+{+ "ReverseDNS": "attacker.local",+ "CanaryName": "foo-bar",+ "Description": "Consolidated Network Port Scan",+ "CanaryPort": "443",+ "Timestamp": "2020-07-20 16:18:40 (UTC)",+ "CanaryIP": "1.1.1.1",+ "AlertType": "CanaryIncident",+ "Intro": "A portscan has been done on several of your canaries by the host 1.1.1.1.",+ "IncidentHash": "3f25fec9e18c7673dcc468800b7af0a6",+ "CanaryLocation": "dining room",+ "SourceIP": "1.1.1.1",+ "AdditionalDetails": [+ [+ "Incident",+ "Consolidated Network Port Scan"+ ],+ [+ "Source",+ "1.1.1.1"+ ],+ [+ "Targets",+ "1.0.0.1, 1.0.0.2"+ ],+ [+ "Background Context",+ "You have had 8 incidents from 1.0.0.1 previously."+ ]+ ],+ "CanaryID": "00000000aa8a310e"+}diff --git a/zerver/webhooks/thinkst/fixtures/canary_alert.json b/zerver/webhooks/thinkst/fixtures/canary_dummy.jsonsimilarity index 100%rename from zerver/webhooks/thinkst/fixtures/canary_alert.jsonrename to zerver/webhooks/thinkst/fixtures/canary_dummy.jsondiff --git a/zerver/webhooks/thinkst/fixtures/canary_file_access.json b/zerver/webhooks/thinkst/fixtures/canary_file_access.jsonnew file mode 100644index 00000000000..386fe8f129d--- /dev/null+++ b/zerver/webhooks/thinkst/fixtures/canary_file_access.json@@ -0,0 +1,32 @@+{+ "ReverseDNS": "",+ "CanaryName": "bar-foo",+ "Description": "Shared File (Re)Opened",+ "CanaryPort": 445,+ "Timestamp": "2020-07-20 16:27:20 (UTC)",+ "CanaryIP": "1.1.1.1",+ "AlertType": "CanaryIncident",+ "Intro": "Shared File (Re)Opened has been detected against one of your Canaries (bar-foo) at 1.1.1.1.",+ "IncidentHash": "a7bb317ba2072415462233cef3bc615a",+ "CanaryLocation": "dining room",+ "SourceIP": "1.1.1.1",+ "AdditionalDetails": [+ [+ "User",+ "guest"+ ],+ [+ "Filename",+ "secret/bar.doc"+ ],+ [+ "Additional Information",+ "This file 'secret/bar.doc' was previously opened by the host 'zulip-dev' on 2020-07-20 16:18:56.\n\nIt was also opened 2 times before by the same host, on 2020-06-10 14:33:50, 2020-06-18 19:02:33."+ ],+ [+ "Background Context",+ "You have had 20 incidents from 1.1.1.1 previously."+ ]+ ],+ "CanaryID": "00000000aa8a310e"+}diff --git a/zerver/webhooks/thinkst/fixtures/canary_host_port_scan.json b/zerver/webhooks/thinkst/fixtures/canary_host_port_scan.jsonnew file mode 100644index 00000000000..9d102278325--- /dev/null+++ b/zerver/webhooks/thinkst/fixtures/canary_host_port_scan.json@@ -0,0 +1,20 @@+{+ "ReverseDNS": "attacker.local",+ "CanaryName": "foo-bar",+ "Description": "Host Port Scan",+ "CanaryPort": "1723",+ "Timestamp": "2020-07-20 16:26:30 (UTC)",+ "CanaryIP": "1.1.1.1",+ "AlertType": "CanaryIncident",+ "Intro": "Host Port Scan has been detected against one of your Canaries (foo-bar) at 1.1.1.1.",+ "IncidentHash": "9060473d2da98afe494adad648495620",+ "CanaryLocation": "dining room",+ "SourceIP": "1.1.1.1",+ "AdditionalDetails": [+ [+ "Partial Ports",+ "443, 554, 80, 1723, 22"+ ]+ ],+ "CanaryID": "00024808d6c2f7e5"+}diff --git a/zerver/webhooks/thinkst/fixtures/canary_http_login.json b/zerver/webhooks/thinkst/fixtures/canary_http_login.jsonnew file mode 100644index 00000000000..0aee1aeb307--- /dev/null+++ b/zerver/webhooks/thinkst/fixtures/canary_http_login.json@@ -0,0 +1,32 @@+{+ "ReverseDNS": "",+ "CanaryName": "foo-bar",+ "Description": "HTTP Login Attempt",+ "CanaryPort": 80,+ "Timestamp": "2020-07-20 14:55:45 (UTC)",+ "CanaryIP": "1.1.1.1",+ "AlertType": "CanaryIncident",+ "Intro": "HTTP Login Attempt has been detected against one of your Canaries (foo-bar) at 1.1.1.1.",+ "IncidentHash": "1ef86f5cf4090a5252c6f453c5cd46bd",+ "CanaryLocation": "dining room",+ "SourceIP": "1.1.1.1",+ "AdditionalDetails": [+ [+ "Username",+ "regular"+ ],+ [+ "Password",+ "*******"+ ],+ [+ "User-Agent",+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15"+ ],+ [+ "Background Context",+ "You have had 14 incidents from 1.1.1.1 previously."+ ]+ ],+ "CanaryID": "00000000d9febd04"+}diff --git a/zerver/webhooks/thinkst/fixtures/canary_ssh_login.json b/zerver/webhooks/thinkst/fixtures/canary_ssh_login.jsonnew file mode 100644index 00000000000..da6b62ad679--- /dev/null+++ b/zerver/webhooks/thinkst/fixtures/canary_ssh_login.json@@ -0,0 +1,28 @@+{+ "ReverseDNS": "attacker.local",+ "CanaryName": "foo-bar",+ "Description": "SSH Login Attempt",+ "CanaryPort": 22,+ "Timestamp": "2020-07-20 16:26:22 (UTC)",+ "CanaryIP": "1.1.1.1",+ "AlertType": "CanaryIncident",+ "Intro": "SSH Login Attempt has been detected against one of your Canaries (foo-bar) at 1.1.1.1.",+ "IncidentHash": "4ef51a936d05e0a6b4846378c8c38d2c",+ "CanaryLocation": "dining room",+ "SourceIP": "1.1.1.1",+ "AdditionalDetails": [+ [+ "Username",+ "foo"+ ],+ [+ "Key",+ "*******"+ ],+ [+ "Background Context",+ "You have had 9 incidents from 1.1.1.1 previously."+ ]+ ],+ "CanaryID": "00024808d6c2f7e5"+}diff --git a/zerver/webhooks/thinkst/fixtures/canarytoken_msword.json b/zerver/webhooks/thinkst/fixtures/canarytoken_msword.jsonnew file mode 100644index 00000000000..a85ed683e4b--- /dev/null+++ b/zerver/webhooks/thinkst/fixtures/canarytoken_msword.json@@ -0,0 +1,40 @@+{+ "Token": "dbwx4d68flwh2u5zku56nogu6",+ "Intro": "A MS Word .docx Document Canarytoken has been triggered over doc-msword by the source IP 1.1.1.1.",+ "Description": "MS Word .docx Document",+ "Triggered": 5,+ "AdditionalDetails": [+ [+ "Accept",+ "*/*"+ ],+ [+ "Accept-Encoding",+ "gzip, deflate"+ ],+ [+ "Accept-Language",+ "en-gb"+ ],+ [+ "Background Context",+ "You have had 21 incidents from 1.1.1.1 previously."+ ],+ [+ "Connection",+ "keep-alive"+ ],+ [+ "Dst Port",+ 80+ ],+ [+ "User-Agent",+ "Mozilla/4.0 (compatible; ms-office; MSOffice 16)"+ ]+ ],+ "Timestamp": "2020-07-20 14:40:15 (UTC)",+ "Reminder": "test document",+ "IncidentHash": "db6f9b5528c6c6c385cb3bb63f5949c8",+ "AlertType": "CanarytokenIncident"+}diff --git a/zerver/webhooks/thinkst/fixtures/canarytoken_new.json b/zerver/webhooks/thinkst/fixtures/canarytoken_new.jsondeleted file mode 100644index 564812d6dd8..00000000000--- a/zerver/webhooks/thinkst/fixtures/canarytoken_new.json+++ /dev/null@@ -1,12 +0,0 @@-{- "manage_url": "http://example.com/test/url/for/webhook",- "memo": "Congrats! The newly saved webhook works",- "additional_data": {- "src_ip": "1.1.1.1",- "useragent": "Mozilla/5.0...",- "referer": "http://example.com/referrer",- "location": "http://example.com/location"- },- "channel": "HTTP",- "time": "2020-06-09 14:04:39"-}diff --git a/zerver/webhooks/thinkst/fixtures/canarytoken_real.json b/zerver/webhooks/thinkst/fixtures/canarytoken_real.jsondeleted file mode 100644index 0dcac91ef3d..00000000000--- a/zerver/webhooks/thinkst/fixtures/canarytoken_real.json+++ /dev/null@@ -1,12 +0,0 @@-{- "manage_url": "https://canarytokens.org/manage?token=foo&auth=bar",- "memo": "Canarytoken example",- "additional_data": {- "src_ip": "81.151.13.3",- "useragent": "Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0",- "referer": null,- "location": null- },- "channel": "HTTP",- "time": "2020-06-09 14:04:47 (UTC)"-}diff --git a/zerver/webhooks/thinkst/fixtures/canarytoken_remote_image.json b/zerver/webhooks/thinkst/fixtures/canarytoken_remote_image.jsonnew file mode 100644index 00000000000..50ec1aa9747--- /dev/null+++ b/zerver/webhooks/thinkst/fixtures/canarytoken_remote_image.json@@ -0,0 +1,48 @@+{+ "Token": "ew5n8gqtb82m4uegrttarn2zu",+ "Intro": "A Remote Web Image Canarytoken has been triggered over web-image by the source IP 1.1.1.1.",+ "Description": "Remote Web Image",+ "Triggered": 37,+ "AdditionalDetails": [+ [+ "Accept",+ "image/webp,*/*"+ ],+ [+ "Accept-Encoding",+ "gzip, deflate"+ ],+ [+ "Accept-Language",+ "en-US,en;q=0.5"+ ],+ [+ "Background Context",+ "You have had 12 incidents from 1.1.1.1 previously."+ ],+ [+ "Cache-Control",+ "max-age=0"+ ],+ [+ "Connection",+ "keep-alive"+ ],+ [+ "Dnt",+ "1"+ ],+ [+ "Dst Port",+ 80+ ],+ [+ "User-Agent",+ "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0"+ ]+ ],+ "Timestamp": "2020-07-20 16:33:12 (UTC)",+ "Reminder": "test image",+ "IncidentHash": "533395067f6d655cd19384bc6991cc0f",+ "AlertType": "CanarytokenIncident"+}diff --git a/zerver/webhooks/thinkst/tests.py b/zerver/webhooks/thinkst/tests.pyindex 24b524e1fbe..645c781b8ce 100644--- a/zerver/webhooks/thinkst/tests.py+++ b/zerver/webhooks/thinkst/tests.py@@ -2,100 +2,258 @@ from zerver.lib.test_classes import WebhookTestCaseclass ThinkstHookTests(WebhookTestCase):- STREAM_NAME = 'travis'+ STREAM_NAME = 'thinkst'URL_TEMPLATE = "/api/v1/external/thinkst?stream={stream}&api_key={api_key}"FIXTURE_DIR_NAME = 'thinkst'- def test_canary_alert(self) -> None:- """- Canary alerts are generated by Thinkst's hardware or virtual canaries.- """- expected_message = ('**:alert: Canary has been triggered!**\n\n'- 'On 2020-06-09 13:59:38 (UTC), `0000000testnode` was triggered '- 'from `2.2.2.2` (`attacker-ip.local`):\n\n'- '> This is a dummy incident.')+ def test_canary_dummy(self) -> None:+ expected_message = (+ "**:alert: Canary *0000000testnode* has been triggered!**\n\n"+ "This is a dummy incident.\n\n"+ "**Incident Id:** `aa875f255f94e3ffe40dc85cf1a8b1e0`\n"+ "**Kind:** Dummy Incident\n"+ "**Timestamp:** 2020-06-09 13:59:38 (UTC)\n"+ "**Canary IP:** `1.1.1.1`\n"+ "**Source IP:** `2.2.2.2`\n"+ "**Reverse DNS:** `attacker-ip.local`\n"+ "**Field1:** VALUE1\n"+ "**Field2:** VALUE2\n"+ "**Field3:** VALUE3"+ )self.send_and_test_stream_message(- 'canary_alert',+ 'canary_dummy','canary alert - 0000000testnode',expected_message,content_type="application/x-www-form-urlencoded",)- def test_canary_alert_no_reverse_dns(self) -> None:- """- Canary alerts are generated by Thinkst's hardware or virtual canaries.- """- expected_message = ('**:alert: Canary has been triggered!**\n\n'- 'On 2020-06-09 13:59:38 (UTC), `0000000testnode` was triggered '- 'from `2.2.2.2`:\n\n'- '> This is a dummy incident.')+ def test_canary_consolidated_port_scan(self) -> None:+ expected_message = (+ "**:alert: Canary *foo-bar* has been triggered!**\n\n"+ "A portscan has been done on several of your canaries by the host "+ "1.1.1.1.\n\n"+ "**Incident Id:** `3f25fec9e18c7673dcc468800b7af0a6`\n"+ "**Kind:** Consolidated Network Port Scan\n"+ "**Timestamp:** 2020-07-20 16:18:40 (UTC)\n"+ "**Canary IP:** `1.1.1.1`\n"+ "**Canary Location:** dining room\n"+ "**Source IP:** `1.1.1.1`\n"+ "**Reverse DNS:** `attacker.local`\n"+ "**Incident:** Consolidated Network Port Scan\n"+ "**Source:** 1.1.1.1\n"+ "**Targets:** 1.0.0.1, 1.0.0.2\n"+ "**Background Context:** You have had 8 incidents from 1.0.0.1 previously."+ )self.send_and_test_stream_message(- 'canary_alert_no_reverse_dns',- 'canary alert - 0000000testnode',+ 'canary_consolidated_port_scan',+ 'canary alert - foo-bar',+ expected_message,+ content_type="application/x-www-form-urlencoded",+ )++ def test_canary_file_access(self) -> None:+ expected_message = (+ "**:alert: Canary *bar-foo* has been triggered!**\n\n"+ "Shared File (Re)Opened has been detected against one of your Canaries "+ "(bar-foo) at 1.1.1.1.\n\n"+ "**Incident Id:** `a7bb317ba2072415462233cef3bc615a`\n"+ "**Kind:** Shared File (Re)Opened\n"+ "**Timestamp:** 2020-07-20 16:27:20 (UTC)\n"+ "**Canary IP:** `1.1.1.1`\n"+ "**Canary Location:** dining room\n"+ "**Source IP:** `1.1.1.1`\n"+ "**User:** guest\n"+ "**Filename:** secret/bar.doc\n"+ "**Additional Information:** This file 'secret/bar.doc' was "+ "previously opened by the host 'zulip-dev' on 2020-07-20 16:18:56.\n\n"+ "It was also opened 2 times before by the same host, on 2020-06-10 "+ "14:33:50, 2020-06-18 19:02:33.\n"+ "**Background Context:** You have had 20 incidents from 1.1.1.1 previously."+ )++ self.send_and_test_stream_message(+ 'canary_file_access',+ 'canary alert - bar-foo',expected_message,content_type="application/x-www-form-urlencoded",)- def test_canary_alert_with_specific_topic(self) -> None:- """- Canary alerts are generated by Thinkst's hardware or virtual canaries.- """+ def test_canary_host_port_scan(self) -> None:+ expected_message = (+ "**:alert: Canary *foo-bar* has been triggered!**\n\n"+ "Host Port Scan has been detected against one of your Canaries "+ "(foo-bar) at 1.1.1.1.\n\n"+ "**Incident Id:** `9060473d2da98afe494adad648495620`\n"+ "**Kind:** Host Port Scan\n"+ "**Timestamp:** 2020-07-20 16:26:30 (UTC)\n"+ "**Canary IP:** `1.1.1.1`\n"+ "**Canary Location:** dining room\n"+ "**Source IP:** `1.1.1.1`\n"+ "**Reverse DNS:** `attacker.local`\n"+ "**Partial Ports:** 443, 554, 80, 1723, 22"+ )++ self.send_and_test_stream_message(+ 'canary_host_port_scan',+ 'canary alert - foo-bar',+ expected_message,+ content_type="application/x-www-form-urlencoded",+ )++ def test_canary_http_login(self) -> None:+ expected_message = (+ "**:alert: Canary *foo-bar* has been triggered!**\n\n"+ "HTTP Login Attempt has been detected against one of your Canaries "+ "(foo-bar) at 1.1.1.1.\n\n"+ "**Incident Id:** `1ef86f5cf4090a5252c6f453c5cd46bd`\n"+ "**Kind:** HTTP Login Attempt\n"+ "**Timestamp:** 2020-07-20 14:55:45 (UTC)\n"+ "**Canary IP:** `1.1.1.1`\n"+ "**Canary Location:** dining room\n"+ "**Source IP:** `1.1.1.1`\n"+ "**Username:** regular\n"+ "**Password:** `*******`\n"+ "**User-Agent:** Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) "+ "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15\n"+ "**Background Context:** You have had 14 incidents from 1.1.1.1 previously."+ )++ self.send_and_test_stream_message(+ 'canary_http_login',+ 'canary alert - foo-bar',+ expected_message,+ content_type="application/x-www-form-urlencoded",+ )++ def test_canary_ssh_login(self) -> None:+ expected_message = (+ "**:alert: Canary *foo-bar* has been triggered!**\n\n"+ "SSH Login Attempt has been detected against one of your Canaries "+ "(foo-bar) at 1.1.1.1.\n\n"+ "**Incident Id:** `4ef51a936d05e0a6b4846378c8c38d2c`\n"+ "**Kind:** SSH Login Attempt\n"+ "**Timestamp:** 2020-07-20 16:26:22 (UTC)\n"+ "**Canary IP:** `1.1.1.1`\n"+ "**Canary Location:** dining room\n"+ "**Source IP:** `1.1.1.1`\n"+ "**Reverse DNS:** `attacker.local`\n"+ "**Username:** foo\n"+ "**Key:** `*******`\n"+ "**Background Context:** You have had 9 incidents from 1.1.1.1 previously."+ )++ self.send_and_test_stream_message(+ 'canary_ssh_login',+ 'canary alert - foo-bar',+ expected_message,+ content_type="application/x-www-form-urlencoded",+ )++ def test_canary_with_specific_topic(self) -> None:self.url = self.build_webhook_url(topic='foo')- expected_message = ('**:alert: Canary `0000000testnode` has been triggered!**\n\n'- 'On 2020-06-09 13:59:38 (UTC), `0000000testnode` was triggered '- 'from `2.2.2.2` (`attacker-ip.local`):\n\n'- '> This is a dummy incident.')+ expected_message = (+ "**:alert: Canary *0000000testnode* has been triggered!**\n\n"+ "This is a dummy incident.\n\n"+ "**Incident Id:** `aa875f255f94e3ffe40dc85cf1a8b1e0`\n"+ "**Kind:** Dummy Incident\n"+ "**Timestamp:** 2020-06-09 13:59:38 (UTC)\n"+ "**Canary IP:** `1.1.1.1`\n"+ "**Source IP:** `2.2.2.2`\n"+ "**Reverse DNS:** `attacker-ip.local`\n"+ "**Field1:** VALUE1\n"+ "**Field2:** VALUE2\n"+ "**Field3:** VALUE3"+ )self.send_and_test_stream_message(- 'canary_alert',+ 'canary_dummy','foo',expected_message,content_type="application/x-www-form-urlencoded",)- def test_canarytoken_new(self) -> None:- """- Thinkst Canarytokens are simple tripwires for detecting when resources have been accessed.- """- expected_message = ('**:alert: Canarytoken has been triggered on 2020-06-09 14:04:39!**\n\n'- '> Congrats! The newly saved webhook works \n\n'- '[Manage this canarytoken](http://example.com/test/url/for/webhook)')+ def test_canarytoken_msword(self) -> None:+ expected_message = (+ "**:alert: Canarytoken *test document* has been triggered!**\n\n"+ "A MS Word .docx Document Canarytoken has been triggered over doc-msword "+ "by the source IP 1.1.1.1.\n\n"+ "**Incident Id:** `db6f9b5528c6c6c385cb3bb63f5949c8`\n"+ "**Token:** `dbwx4d68flwh2u5zku56nogu6`\n"+ "**Kind:** MS Word .docx Document\n"+ "**Timestamp:** 2020-07-20 14:40:15 (UTC)\n"+ "**Triggered:** 5 times\n"+ "**Accept:** `*/*`\n"+ "**Accept-Encoding:** gzip, deflate\n"+ "**Accept-Language:** en-gb\n"+ "**Background Context:** You have had 21 incidents from 1.1.1.1 "+ "previously.\n"+ "**Connection:** keep-alive\n"+ "**Dst Port:** 80\n"+ "**User-Agent:** Mozilla/4.0 (compatible; ms-office; MSOffice 16)"+ )self.send_and_test_stream_message(- 'canarytoken_new',- 'canarytoken alert',+ 'canarytoken_msword',+ 'canarytoken alert - test document',expected_message,content_type="application/x-www-form-urlencoded",)- def test_canarytoken_real(self) -> None:- """- Thinkst Canarytokens are simple tripwires for detecting when resources have been accessed.- """- expected_message = ('**:alert: Canarytoken has been triggered on 2020-06-09 14:04:47 (UTC)!**\n\n'- '> Canarytoken example \n\n'- '[Manage this canarytoken](https://canarytokens.org/manage?token=foo&auth=bar)')+ def test_canarytoken_remote_image(self) -> None:+ expected_message = (+ "**:alert: Canarytoken *test image* has been triggered!**\n\n"+ "A Remote Web Image Canarytoken has been triggered over web-image by the "+ "source IP 1.1.1.1.\n\n"+ "**Incident Id:** `533395067f6d655cd19384bc6991cc0f`\n"+ "**Token:** `ew5n8gqtb82m4uegrttarn2zu`\n"+ "**Kind:** Remote Web Image\n"+ "**Timestamp:** 2020-07-20 16:33:12 (UTC)\n"+ "**Triggered:** 37 times\n"+ "**Accept:** `image/webp,*/*`\n"+ "**Accept-Encoding:** gzip, deflate\n"+ "**Accept-Language:** en-US,en;q=0.5\n"+ "**Background Context:** You have had 12 incidents from 1.1.1.1 "+ "previously.\n"+ "**Cache-Control:** max-age=0\n"+ "**Connection:** keep-alive\n"+ "**Dnt:** 1\n"+ "**Dst Port:** 80\n"+ "**User-Agent:** Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 "+ "Firefox/78.0"+ )self.send_and_test_stream_message(- 'canarytoken_real',- 'canarytoken alert',+ 'canarytoken_remote_image',+ 'canarytoken alert - test image',expected_message,content_type="application/x-www-form-urlencoded",)def test_canarytoken_with_specific_topic(self) -> None:- """- Thinkst Canarytokens are simple tripwires for detecting when resources have been accessed.- """self.url = self.build_webhook_url(topic='foo')- expected_message = ('**:alert: Canarytoken has been triggered on 2020-06-09 14:04:47 (UTC)!**\n\n'- '> Canarytoken example \n\n'- '[Manage this canarytoken](https://canarytokens.org/manage?token=foo&auth=bar)')+ expected_message = (+ "**:alert: Canarytoken *test document* has been triggered!**\n\n"+ "A MS Word .docx Document Canarytoken has been triggered over doc-msword "+ "by the source IP 1.1.1.1.\n\n"+ "**Incident Id:** `db6f9b5528c6c6c385cb3bb63f5949c8`\n"+ "**Token:** `dbwx4d68flwh2u5zku56nogu6`\n"+ "**Kind:** MS Word .docx Document\n"+ "**Timestamp:** 2020-07-20 14:40:15 (UTC)\n"+ "**Triggered:** 5 times\n"+ "**Accept:** `*/*`\n"+ "**Accept-Encoding:** gzip, deflate\n"+ "**Accept-Language:** en-gb\n"+ "**Background Context:** You have had 21 incidents from 1.1.1.1 "+ "previously.\n"+ "**Connection:** keep-alive\n"+ "**Dst Port:** 80\n"+ "**User-Agent:** Mozilla/4.0 (compatible; ms-office; MSOffice 16)"+ )self.send_and_test_stream_message(- 'canarytoken_real',+ 'canarytoken_msword','foo',expected_message,content_type="application/x-www-form-urlencoded",diff --git a/zerver/webhooks/thinkst/view.py b/zerver/webhooks/thinkst/view.pyindex b13772ba964..dc75bc0d195 100644--- a/zerver/webhooks/thinkst/view.py+++ b/zerver/webhooks/thinkst/view.py@@ -12,68 +12,130 @@ from zerver.models import UserProfiledef is_canarytoken(message: Dict[str, Any]) -> bool:"""- There are two types of requests that Thinkst will send - depending on whether it is- a canary or a canarytoken. Unfortunately, there isn't a great way to differentiate other- than look at the contents.+ Requests sent from Thinkst canaries are either from canarytokens or+ canaries, which can be differentiated by the value of the `AlertType`+ field."""- return 'Timestamp' not in message+ return message['AlertType'] == 'CanarytokenIncident'-def canarytoken_message(message: Dict[str, Any]) -> Tuple[str, str]:+def canary_name(message: Dict[str, Any]) -> str:"""- Construct the message for a canarytoken-type request.+ Returns the name of the canary or canarytoken."""- topic = 'canarytoken alert'- body = (f"**:alert: Canarytoken has been triggered on {message['time']}!**\n\n"- f"> {message['memo']} \n\n"- f"[Manage this canarytoken]({message['manage_url']})")+ if is_canarytoken(message):+ return message['Reminder']+ else:+ return message['CanaryName']- return (topic, body)++def canary_kind(message: Dict[str, Any]) -> str:+ """+ Returns a description of the kind of request - canary or canarytoken.+ """+ if is_canarytoken(message):+ return 'canarytoken'+ else:+ return 'canary'-def canary_message(message: Dict[str, Any], user_specified_topic: Optional[str]) -> Tuple[str, str]:+def source_ip_and_reverse_dns(+ message: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]:"""- Construct the message for a canary-type request.+ Extract the source IP and reverse DNS information from a canary request."""- topic = f"canary alert - {message['CanaryName']}"+ reverse_dns, source_ip = (None, None)- reverse_dns = ''- if 'ReverseDNS' in message:- reverse_dns = f" (`{message['ReverseDNS']}`)"+ if 'SourceIP' in message:+ source_ip = message['SourceIP']+ # `ReverseDNS` can sometimes exist and still be empty.+ if 'ReverseDNS' in message and message['ReverseDNS']:+ reverse_dns = message['ReverseDNS']- name = ''- if user_specified_topic:- name = f" `{message['CanaryName']}`"+ return (source_ip, reverse_dns)+++def body(message: Dict[str, Any]) -> str:+ """+ Construct the response to a canary or canarytoken request.+ """++ title = canary_kind(message).title()+ name = canary_name(message)+ body = (f"**:alert: {title} *{name}* has been triggered!**\n\n"+ f"{message['Intro']}\n\n")++ if 'IncidentHash' in message:+ body += f"**Incident Id:** `{message['IncidentHash']}`\n"++ if 'Token' in message:+ body += f"**Token:** `{message['Token']}`\n"- body = (f"**:alert: Canary{name} has been triggered!**\n\n"- f"On {message['Timestamp']}, `{message['CanaryName']}` was triggered "- f"from `{message['SourceIP']}`{reverse_dns}:\n\n"- f"> {message['Intro']}")+ if 'Description' in message:+ body += f"**Kind:** {message['Description']}\n"- return (topic, body)+ if 'Timestamp' in message:+ body += f"**Timestamp:** {message['Timestamp']}\n"++ if 'CanaryIP' in message:+ body += f"**Canary IP:** `{message['CanaryIP']}`\n"++ if 'CanaryLocation' in message:+ body += f"**Canary Location:** {message['CanaryLocation']}\n"++ if 'Triggered' in message:+ unit = 'times' if message['Triggered'] > 1 else 'time'+ body += f"**Triggered:** {message['Triggered']} {unit}\n"++ source_ip, reverse_dns = source_ip_and_reverse_dns(message)+ if source_ip:+ body += f"**Source IP:** `{source_ip}`\n"+ if reverse_dns:+ body += f"**Reverse DNS:** `{reverse_dns}`\n"++ if 'AdditionalDetails' in message:+ for detail in message['AdditionalDetails']:+ if isinstance(detail[1], str) and '*' in detail[1]:+ # Thinkst sends passwords as a series of stars which can mess with+ # formatting, so wrap these in backticks.+ body += f"**{detail[0]}:** `{detail[1]}`\n"+ else:+ body += f"**{detail[0]}:** {detail[1]}\n"++ return body@api_key_only_webhook_view('Thinkst')@has_request_variables-def api_thinkst_webhook(request: HttpRequest, user_profile: UserProfile,- message: Dict[str, Any]=REQ(argument_type='body'),- user_specified_topic: Optional[str]=REQ('topic', default=None)) -> HttpResponse:+def api_thinkst_webhook(+ request: HttpRequest, user_profile: UserProfile,+ message: Dict[str, Any] = REQ(argument_type='body'),+ user_specified_topic: Optional[str] = REQ('topic', default=None)+) -> HttpResponse:"""- Construct a response to a webhook event from a Thinkst canary or canarytoken, see- linked documentation below for a schema:+ Construct a response to a webhook event from a Thinkst canary or canarytoken.++ Thinkst offers public canarytokens with canarytokens.org and with their canary+ product, but the schema returned by these identically named services are+ completely different - canarytokens from canarytokens.org are handled by a+ different Zulip integration.++ Thinkst's documentation for the schema is linked below, but in practice the JSON+ received doesn't always conform.https://help.canary.tools/hc/en-gb/articles/360002426577-How-do-I-configure-notifications-for-a-Generic-Webhook-"""- body = None- topic = None- if is_canarytoken(message):- topic, body = canarytoken_message(message)- else:- topic, body = canary_message(message, user_specified_topic)+ response = body(message)+ topic = Noneif user_specified_topic:topic = user_specified_topic+ else:+ name = canary_name(message)+ kind = canary_kind(message)++ topic = f"{kind} alert - {name}"- check_send_webhook_message(request, user_profile, topic, body)+ check_send_webhook_message(request, user_profile, topic, response)return json_success()