from panther_core import PantherEvent

from pypanther import LogType, Rule, RuleTest, Severity, panther_managed
from pypanther.helpers.crowdstrike_event_streams import cs_alert_context


@panther_managed
class CrowdstrikeEppDetectionSummary(Rule):
    id = "Crowdstrike.EppDetectionSummary-prototype"
    display_name = "Crowdstrike Detection Summary"
    log_types = [LogType.CROWDSTRIKE_EVENT_STREAMS]
    default_severity = Severity.MEDIUM
    default_description = "Forwards any alerts generated by CrowdStrike to your Panther destinations."
    default_runbook = "Followup with the alert according to CrowdStrike's recommendations."
    tags = ["Crowdstrike", "Passthrough"]

    def rule(self, event: PantherEvent):
        return event.deep_get("metadata", "eventType") == "EppDetectionSummaryEvent"

    def title(self, event: PantherEvent):
        alert_title = event.deep_get("event", "Name", default="New CrowdStrike Detection")
        alert_desc = event.deep_get("event", "Description")
        return f"{alert_title}: {alert_desc}" if alert_desc else alert_title

    def dedup(self, event: PantherEvent):
        if alert_id := event.deep_get("event", "CompositeId"):
            return alert_id
        # Else, fall back on title string
        return self.title(event)

    def severity(self, event: PantherEvent):
        # First, try returning the severity based on the SeverityName
        sevname = event.deep_get("event", "SeverityName").upper()
        allowed_values = ("INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL")
        if sevname == "INFORMATIONAL":
            sevname = "INFO"
        if sevname in allowed_values:
            return sevname
        # Else, fallback on the numerical value, falling back on MEDIUM if we still don't have a value
        sevval = event.deep_get("event", "Severity") // 20
        return {0: "INFO", 1: "LOW", 2: "MEDIUM", 3: "HIGH", 4: "CRITICAL", 5: "CRITICAL"}.get(sevval, "DEFAULT")

    def reference(self, event: PantherEvent):
        return event.deep_get("event", "FalconHostLink", default="")

    def alert_context(self, event: PantherEvent):
        context = cs_alert_context(event)
        context.update(
            {
                "FalconLink": event.deep_get("event", "FalconHostLink", default="<NO LINK PROVIDED>"),
                "CompositeId": event.deep_get("event", "CompositeId", default="<NO ID PROVIDED>"),
                "FileName": event.deep_get("event", "FileName", default="<NO FILENAME PROVIDED>"),
                "FilePath": event.deep_get("event", "FilePath", default="<NO FILEPATH PROVIDED>"),
                "UserName": event.deep_get("event", "UserName", default="<NO USERNAME PROVIDED>"),
            },
        )
        return context

    tests = [
        RuleTest(
            name="INFO Alert",
            expected_result=True,
            log={
                "p_event_time": "2024-12-03 19:54:30.000000000",
                "p_log_type": "Crowdstrike.EventStreams",
                "p_parse_time": "2024-12-03 19:55:53.866056859",
                "event": {
                    "CommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --type=utility --utility-sub-type=chrome.mojom.UtilWin --lang=en-US --service-sandbox-type=none --string-annotations=is-enterprise-managed=no --field-trial-handle=3832,i,16271085821438557631,11283940248133486999,262144 --variations-seed-version --mojo-platform-channel-handle=3900 /prefetch:8',
                    "CompositeId": "DETECTION ID",
                    "Description": "A process has written a known EICAR test file. Review the files written by the triggered process.",
                    "FalconHostLink": "https://falcon.us-2.crowdstrike.com/activity-v2/detections/DETECTION-ID?_cid=g04000rdir6xllkvfbjftn5dbo67ord4",
                    "FileName": "msedge.exe",
                    "FilePath": "\\Device\\HarddiskVolume1\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
                    "GrandparentCommandLine": "C:\\Windows\\Explorer.EXE",
                    "GrandparentImageFilename": "explorer.exe",
                    "LocalIP": "10.0.6.37",
                    "MACAddress": "06-a7-e1-13-09-0d",
                    "MD5String": "fcde6b30b89cabf7d0460bc5a580cb12",
                    "Name": "Known Malware",
                    "Objective": "Follow Through",
                    "ParentCommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --profile-directory=Default',
                    "ParentImageFileName": "msedge.exe",
                    "ParentProcessId": "90559720124",
                    "PatternDispositionDescription": "Detection, standard detection.",
                    "PatternDispositionFlags": {
                        "BootupSafeguardEnabled": False,
                        "CriticalProcessDisabled": False,
                        "Detect": False,
                        "FsOperationBlocked": False,
                        "InddetMask": False,
                        "Indicator": False,
                        "KillParent": False,
                        "KillProcess": False,
                        "KillSubProcess": False,
                        "OperationBlocked": False,
                        "PolicyDisabled": False,
                        "ProcessBlocked": False,
                        "QuarantineFile": False,
                        "QuarantineMachine": False,
                        "RegistryOperationBlocked": False,
                        "Rooting": False,
                        "SensorOnly": False,
                    },
                    "PatternDispositionValue": 0,
                    "ProcessEndTime": "1970-01-01 00:00:00.000000000",
                    "ProcessId": "90597916092",
                    "ProcessStartTime": "2024-12-03 19:53:19.000000000",
                    "SHA1String": "0000000000000000000000000000000000000000",
                    "SHA256String": "05d8bce07453a2f3e77503797e39365fd78766099ca60968b9f411ce9886d4ae",
                    "Severity": 10,
                    "SeverityName": "Informational",
                    "Tactic": "Execution",
                    "Technique": "User Execution",
                    "UserName": "Administrator",
                },
                "metadata": {
                    "customerIDString": "CUST_ID",
                    "eventCreationTime": "2024-12-03 19:54:30.000000000",
                    "eventType": "EppDetectionSummaryEvent",
                    "offset": 1201171,
                    "version": "1.0",
                },
            },
        ),
        RuleTest(
            name="LOW Alert",
            expected_result=True,
            log={
                "p_event_time": "2024-12-03 19:54:30.000000000",
                "p_log_type": "Crowdstrike.EventStreams",
                "p_parse_time": "2024-12-03 19:55:53.866056859",
                "event": {
                    "CommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --type=utility --utility-sub-type=chrome.mojom.UtilWin --lang=en-US --service-sandbox-type=none --string-annotations=is-enterprise-managed=no --field-trial-handle=3832,i,16271085821438557631,11283940248133486999,262144 --variations-seed-version --mojo-platform-channel-handle=3900 /prefetch:8',
                    "CompositeId": "DETECTION ID",
                    "Description": "A process has written a known EICAR test file. Review the files written by the triggered process.",
                    "FalconHostLink": "https://falcon.us-2.crowdstrike.com/activity-v2/detections/DETECTION-ID?_cid=g04000rdir6xllkvfbjftn5dbo67ord4",
                    "FileName": "msedge.exe",
                    "FilePath": "\\Device\\HarddiskVolume1\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
                    "GrandparentCommandLine": "C:\\Windows\\Explorer.EXE",
                    "GrandparentImageFilename": "explorer.exe",
                    "LocalIP": "10.0.6.37",
                    "MACAddress": "06-a7-e1-13-09-0d",
                    "MD5String": "fcde6b30b89cabf7d0460bc5a580cb12",
                    "Name": "Known Malware",
                    "Objective": "Follow Through",
                    "ParentCommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --profile-directory=Default',
                    "ParentImageFileName": "msedge.exe",
                    "ParentProcessId": "90559720124",
                    "PatternDispositionDescription": "Detection, standard detection.",
                    "PatternDispositionFlags": {
                        "BootupSafeguardEnabled": False,
                        "CriticalProcessDisabled": False,
                        "Detect": False,
                        "FsOperationBlocked": False,
                        "InddetMask": False,
                        "Indicator": False,
                        "KillParent": False,
                        "KillProcess": False,
                        "KillSubProcess": False,
                        "OperationBlocked": False,
                        "PolicyDisabled": False,
                        "ProcessBlocked": False,
                        "QuarantineFile": False,
                        "QuarantineMachine": False,
                        "RegistryOperationBlocked": False,
                        "Rooting": False,
                        "SensorOnly": False,
                    },
                    "PatternDispositionValue": 0,
                    "ProcessEndTime": "1970-01-01 00:00:00.000000000",
                    "ProcessId": "90597916092",
                    "ProcessStartTime": "2024-12-03 19:53:19.000000000",
                    "SHA1String": "0000000000000000000000000000000000000000",
                    "SHA256String": "05d8bce07453a2f3e77503797e39365fd78766099ca60968b9f411ce9886d4ae",
                    "Severity": 20,
                    "SeverityName": "Low",
                    "Tactic": "Execution",
                    "Technique": "User Execution",
                    "UserName": "Administrator",
                },
                "metadata": {
                    "customerIDString": "CUST_ID",
                    "eventCreationTime": "2024-12-03 19:54:30.000000000",
                    "eventType": "EppDetectionSummaryEvent",
                    "offset": 1201171,
                    "version": "1.0",
                },
            },
        ),
        RuleTest(
            name="MEDIUM Alert",
            expected_result=True,
            log={
                "p_event_time": "2024-12-03 19:54:30.000000000",
                "p_log_type": "Crowdstrike.EventStreams",
                "p_parse_time": "2024-12-03 19:55:53.866056859",
                "event": {
                    "CommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --type=utility --utility-sub-type=chrome.mojom.UtilWin --lang=en-US --service-sandbox-type=none --string-annotations=is-enterprise-managed=no --field-trial-handle=3832,i,16271085821438557631,11283940248133486999,262144 --variations-seed-version --mojo-platform-channel-handle=3900 /prefetch:8',
                    "CompositeId": "DETECTION ID",
                    "Description": "A process has written a known EICAR test file. Review the files written by the triggered process.",
                    "FalconHostLink": "https://falcon.us-2.crowdstrike.com/activity-v2/detections/DETECTION-ID?_cid=g04000rdir6xllkvfbjftn5dbo67ord4",
                    "FileName": "msedge.exe",
                    "FilePath": "\\Device\\HarddiskVolume1\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
                    "GrandparentCommandLine": "C:\\Windows\\Explorer.EXE",
                    "GrandparentImageFilename": "explorer.exe",
                    "LocalIP": "10.0.6.37",
                    "MACAddress": "06-a7-e1-13-09-0d",
                    "MD5String": "fcde6b30b89cabf7d0460bc5a580cb12",
                    "Name": "Known Malware",
                    "Objective": "Follow Through",
                    "ParentCommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --profile-directory=Default',
                    "ParentImageFileName": "msedge.exe",
                    "ParentProcessId": "90559720124",
                    "PatternDispositionDescription": "Detection, standard detection.",
                    "PatternDispositionFlags": {
                        "BootupSafeguardEnabled": False,
                        "CriticalProcessDisabled": False,
                        "Detect": False,
                        "FsOperationBlocked": False,
                        "InddetMask": False,
                        "Indicator": False,
                        "KillParent": False,
                        "KillProcess": False,
                        "KillSubProcess": False,
                        "OperationBlocked": False,
                        "PolicyDisabled": False,
                        "ProcessBlocked": False,
                        "QuarantineFile": False,
                        "QuarantineMachine": False,
                        "RegistryOperationBlocked": False,
                        "Rooting": False,
                        "SensorOnly": False,
                    },
                    "PatternDispositionValue": 0,
                    "ProcessEndTime": "1970-01-01 00:00:00.000000000",
                    "ProcessId": "90597916092",
                    "ProcessStartTime": "2024-12-03 19:53:19.000000000",
                    "SHA1String": "0000000000000000000000000000000000000000",
                    "SHA256String": "05d8bce07453a2f3e77503797e39365fd78766099ca60968b9f411ce9886d4ae",
                    "Severity": 50,
                    "SeverityName": "Medium",
                    "Tactic": "Execution",
                    "Technique": "User Execution",
                    "UserName": "Administrator",
                },
                "metadata": {
                    "customerIDString": "CUST_ID",
                    "eventCreationTime": "2024-12-03 19:54:30.000000000",
                    "eventType": "EppDetectionSummaryEvent",
                    "offset": 1201171,
                    "version": "1.0",
                },
            },
        ),
        RuleTest(
            name="HIGH Alert",
            expected_result=True,
            log={
                "p_event_time": "2024-12-03 19:54:30.000000000",
                "p_log_type": "Crowdstrike.EventStreams",
                "p_parse_time": "2024-12-03 19:55:53.866056859",
                "event": {
                    "CommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --type=utility --utility-sub-type=chrome.mojom.UtilWin --lang=en-US --service-sandbox-type=none --string-annotations=is-enterprise-managed=no --field-trial-handle=3832,i,16271085821438557631,11283940248133486999,262144 --variations-seed-version --mojo-platform-channel-handle=3900 /prefetch:8',
                    "CompositeId": "DETECTION ID",
                    "Description": "A process has written a known EICAR test file. Review the files written by the triggered process.",
                    "FalconHostLink": "https://falcon.us-2.crowdstrike.com/activity-v2/detections/DETECTION-ID?_cid=g04000rdir6xllkvfbjftn5dbo67ord4",
                    "FileName": "msedge.exe",
                    "FilePath": "\\Device\\HarddiskVolume1\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
                    "GrandparentCommandLine": "C:\\Windows\\Explorer.EXE",
                    "GrandparentImageFilename": "explorer.exe",
                    "LocalIP": "10.0.6.37",
                    "MACAddress": "06-a7-e1-13-09-0d",
                    "MD5String": "fcde6b30b89cabf7d0460bc5a580cb12",
                    "Name": "Known Malware",
                    "Objective": "Follow Through",
                    "ParentCommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --profile-directory=Default',
                    "ParentImageFileName": "msedge.exe",
                    "ParentProcessId": "90559720124",
                    "PatternDispositionDescription": "Detection, standard detection.",
                    "PatternDispositionFlags": {
                        "BootupSafeguardEnabled": False,
                        "CriticalProcessDisabled": False,
                        "Detect": False,
                        "FsOperationBlocked": False,
                        "InddetMask": False,
                        "Indicator": False,
                        "KillParent": False,
                        "KillProcess": False,
                        "KillSubProcess": False,
                        "OperationBlocked": False,
                        "PolicyDisabled": False,
                        "ProcessBlocked": False,
                        "QuarantineFile": False,
                        "QuarantineMachine": False,
                        "RegistryOperationBlocked": False,
                        "Rooting": False,
                        "SensorOnly": False,
                    },
                    "PatternDispositionValue": 0,
                    "ProcessEndTime": "1970-01-01 00:00:00.000000000",
                    "ProcessId": "90597916092",
                    "ProcessStartTime": "2024-12-03 19:53:19.000000000",
                    "SHA1String": "0000000000000000000000000000000000000000",
                    "SHA256String": "05d8bce07453a2f3e77503797e39365fd78766099ca60968b9f411ce9886d4ae",
                    "Severity": 70,
                    "SeverityName": "High",
                    "Tactic": "Execution",
                    "Technique": "User Execution",
                    "UserName": "Administrator",
                },
                "metadata": {
                    "customerIDString": "CUST_ID",
                    "eventCreationTime": "2024-12-03 19:54:30.000000000",
                    "eventType": "EppDetectionSummaryEvent",
                    "offset": 1201171,
                    "version": "1.0",
                },
            },
        ),
        RuleTest(
            name="CRIT Alert",
            expected_result=True,
            log={
                "p_event_time": "2024-12-03 19:54:30.000000000",
                "p_log_type": "Crowdstrike.EventStreams",
                "p_parse_time": "2024-12-03 19:55:53.866056859",
                "event": {
                    "CommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --type=utility --utility-sub-type=chrome.mojom.UtilWin --lang=en-US --service-sandbox-type=none --string-annotations=is-enterprise-managed=no --field-trial-handle=3832,i,16271085821438557631,11283940248133486999,262144 --variations-seed-version --mojo-platform-channel-handle=3900 /prefetch:8',
                    "CompositeId": "DETECTION ID",
                    "Description": "A process has written a known EICAR test file. Review the files written by the triggered process.",
                    "FalconHostLink": "https://falcon.us-2.crowdstrike.com/activity-v2/detections/DETECTION-ID?_cid=g04000rdir6xllkvfbjftn5dbo67ord4",
                    "FileName": "msedge.exe",
                    "FilePath": "\\Device\\HarddiskVolume1\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
                    "GrandparentCommandLine": "C:\\Windows\\Explorer.EXE",
                    "GrandparentImageFilename": "explorer.exe",
                    "LocalIP": "10.0.6.37",
                    "MACAddress": "06-a7-e1-13-09-0d",
                    "MD5String": "fcde6b30b89cabf7d0460bc5a580cb12",
                    "Name": "Known Malware",
                    "Objective": "Follow Through",
                    "ParentCommandLine": '"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe" --profile-directory=Default',
                    "ParentImageFileName": "msedge.exe",
                    "ParentProcessId": "90559720124",
                    "PatternDispositionDescription": "Detection, standard detection.",
                    "PatternDispositionFlags": {
                        "BootupSafeguardEnabled": False,
                        "CriticalProcessDisabled": False,
                        "Detect": False,
                        "FsOperationBlocked": False,
                        "InddetMask": False,
                        "Indicator": False,
                        "KillParent": False,
                        "KillProcess": False,
                        "KillSubProcess": False,
                        "OperationBlocked": False,
                        "PolicyDisabled": False,
                        "ProcessBlocked": False,
                        "QuarantineFile": False,
                        "QuarantineMachine": False,
                        "RegistryOperationBlocked": False,
                        "Rooting": False,
                        "SensorOnly": False,
                    },
                    "PatternDispositionValue": 0,
                    "ProcessEndTime": "1970-01-01 00:00:00.000000000",
                    "ProcessId": "90597916092",
                    "ProcessStartTime": "2024-12-03 19:53:19.000000000",
                    "SHA1String": "0000000000000000000000000000000000000000",
                    "SHA256String": "05d8bce07453a2f3e77503797e39365fd78766099ca60968b9f411ce9886d4ae",
                    "Severity": 90,
                    "SeverityName": "Critical",
                    "Tactic": "Execution",
                    "Technique": "User Execution",
                    "UserName": "Administrator",
                },
                "metadata": {
                    "customerIDString": "CUST_ID",
                    "eventCreationTime": "2024-12-03 19:54:30.000000000",
                    "eventType": "EppDetectionSummaryEvent",
                    "offset": 1201171,
                    "version": "1.0",
                },
            },
        ),
        RuleTest(
            name="Unrelated Event",
            expected_result=False,
            log={
                "metadata": {
                    "customerIDString": "CUST_ID",
                    "eventCreationTime": "2024-12-03 19:54:30.000000000",
                    "eventType": "AuthActivityAuditEvent",
                    "offset": 1201171,
                    "version": "1.0",
                },
            },
        ),
    ]
