from pypanther import LogType, Rule, RuleTest, Severity, panther_managed
from pypanther.helpers.panther_base_helpers import crowdstrike_process_alert_context

crowdstrike_fdrlolbas_tests: list[RuleTest] = [
    RuleTest(
        name="At Usage (Positive)",
        expected_result=True,
        log={
            "ConfigBuild": "1007.3.0016606.11",
            "ConfigStateHash": "3799024366",
            "Entitlements": "15",
            "TreeId": "4295752857",
            "aid": "877761efa8db44d792ddc2redacted",
            "aip": "1.1.1.1",
            "cid": "cfe698690964434083fecdredacted",
            "event": {
                "AuthenticationId": "293628",
                "CommandLine": '"C:\\Windows\\System32\\at.exe" at 09:00 /interactive /every:m,t,w,th,f,s,su',
                "ConfigBuild": "1007.3.0016606.11",
                "ConfigStateHash": "3799024366",
                "EffectiveTransmissionClass": "2",
                "Entitlements": "15",
                "ImageFileName": "\\Device\\HarddiskVolume2\\Windows\\System32\\at.exe",
                "ImageSubsystem": "3",
                "IntegrityLevel": "12288",
                "MD5HashData": "5fd22b915c232378e567160d641cc9f2",
                "ParentAuthenticationId": "293628",
                "ParentBaseFileName": "pwsh.exe",
                "ParentProcessId": "4370948876",
                "ProcessCreateFlags": "0",
                "ProcessEndTime": "",
                "ProcessParameterFlags": "24577",
                "ProcessStartTime": "1682106508.209",
                "ProcessSxsFlags": "64",
                "RawProcessId": "2696",
                "SHA1HashData": "0000000000000000000000000000000000000000",
                "SHA256HashData": "488e74e2026d03f21b33f470c23b3de2f466643186c2e06ae7b4883cc2e59377",
                "SessionId": "2",
                "SourceProcessId": "4370948876",
                "SourceThreadId": "6364981533",
                "Tags": "25, 27, 151, 862, 874, 924, 12094627905582, 12094627906234, 237494511599633",
                "TargetProcessId": "4389083225",
                "TokenType": "1",
                "TreeId": "4295752857",
                "UserSid": "S-1-5-21-239183934-720705223-383019856-500",
                "aid": "877761efa8db44d792ddc2redacted",
                "aip": "1.1.1.1",
                "cid": "cfe698690964434083fecdredacted",
                "event_platform": "Win",
                "event_simpleName": "ProcessRollup2",
                "id": "9a920968-f200-4dd8-8696-461217ece967",
                "name": "ProcessRollup2V19",
                "timestamp": "1682106508970",
            },
            "event_platform": "Win",
            "event_simpleName": "ProcessRollup2",
            "fdr_event_type": "ProcessRollup2",
            "id": "9a920968-f200-4dd8-8696-461217ece967",
            "name": "ProcessRollup2V19",
            "p_any_ip_addresses": ["1.1.1.1"],
            "p_any_md5_hashes": [
                "5fd22b915c232378e567160d641cc9f2",
                "877761efa8db44d792ddc2redacted",
                "cfe698690964434083fecdredacted",
            ],
            "p_any_sha1_hashes": ["0000000000000000000000000000000000000000"],
            "p_any_sha256_hashes": ["488e74e2026d03f21b33f470c23b3de2f466643186c2e06ae7b4883cc2e59377"],
            "p_any_trace_ids": ["4295752857", "877761efa8db44d792ddc2redacted", "cfe698690964434083fecdredacted"],
            "p_event_time": "2023-04-21 19:48:28.97",
            "p_log_type": "Crowdstrike.FDREvent",
            "p_parse_time": "2023-04-21 20:00:53.148",
            "p_row_id": "7ac82dbb43a99bfec196bdda17ea7f",
            "p_schema_version": 0,
            "p_source_id": "1f33f64c-124d-413c-a9e3-d51ccedd8e77",
            "p_source_label": "Crowdstrike-FDR-Dev",
            "p_timeline": "2023-04-21 19:48:28.97",
            "timestamp": "2023-04-21 19:48:28.97",
        },
    ),
    RuleTest(
        name="Notepad Usage (Negative)",
        expected_result=False,
        log={
            "ConfigBuild": "1007.3.0016606.11",
            "ConfigStateHash": "3799024366",
            "Entitlements": "15",
            "TreeId": "4295752857",
            "aid": "877761efa8db44d792ddc2redacted",
            "aip": "1.1.1.1",
            "cid": "cfe698690964434083fecdredacted",
            "event": {
                "AuthenticationId": "293628",
                "CommandLine": '"C:\\Windows\\System32\\notepad.exe" /A filename',
                "ConfigBuild": "1007.3.0016606.11",
                "ConfigStateHash": "3799024366",
                "EffectiveTransmissionClass": "2",
                "Entitlements": "15",
                "ImageFileName": "\\Device\\HarddiskVolume2\\Windows\\System32\\notepad.exe",
                "ImageSubsystem": "3",
                "IntegrityLevel": "12288",
                "MD5HashData": "5fd22b915c232378e567160d641cc9f2",
                "ParentAuthenticationId": "293628",
                "ParentBaseFileName": "pwsh.exe",
                "ParentProcessId": "4370948876",
                "ProcessCreateFlags": "0",
                "ProcessEndTime": "",
                "ProcessParameterFlags": "24577",
                "ProcessStartTime": "1682106508.209",
                "ProcessSxsFlags": "64",
                "RawProcessId": "2696",
                "SHA1HashData": "0000000000000000000000000000000000000000",
                "SHA256HashData": "488e74e2026d03f21b33f470c23b3de2f466643186c2e06ae7b4883cc2e59377",
                "SessionId": "2",
                "SourceProcessId": "4370948876",
                "SourceThreadId": "6364981533",
                "Tags": "25, 27, 151, 862, 874, 924, 12094627905582, 12094627906234, 237494511599633",
                "TargetProcessId": "4389083225",
                "TokenType": "1",
                "TreeId": "4295752857",
                "UserSid": "S-1-5-21-239183934-720705223-383019856-500",
                "aid": "877761efa8db44d792ddc2redacted",
                "aip": "1.1.1.1",
                "cid": "cfe698690964434083fecdredacted",
                "event_platform": "Win",
                "event_simpleName": "ProcessRollup2",
                "id": "9a920968-f200-4dd8-8696-461217ece967",
                "name": "ProcessRollup2V19",
                "timestamp": "1682106508970",
            },
            "event_platform": "Win",
            "event_simpleName": "ProcessRollup2",
            "fdr_event_type": "ProcessRollup2",
            "id": "9a920968-f200-4dd8-8696-461217ece967",
            "name": "ProcessRollup2V19",
            "p_any_ip_addresses": ["1.1.1.1"],
            "p_any_md5_hashes": [
                "5fd22b915c232378e567160d641cc9f2",
                "877761efa8db44d792ddc2redacted",
                "cfe698690964434083fecdredacted",
            ],
            "p_any_sha1_hashes": ["0000000000000000000000000000000000000000"],
            "p_any_sha256_hashes": ["488e74e2026d03f21b33f470c23b3de2f466643186c2e06ae7b4883cc2e59377"],
            "p_any_trace_ids": ["4295752857", "877761efa8db44d792ddc2redacted", "cfe698690964434083fecdredacted"],
            "p_event_time": "2023-04-21 19:48:28.97",
            "p_log_type": "Crowdstrike.FDREvent",
            "p_parse_time": "2023-04-21 20:00:53.148",
            "p_row_id": "7ac82dbb43a99bfec196bdda17ea7f",
            "p_schema_version": 0,
            "p_source_id": "1f33f64c-124d-413c-a9e3-d51ccedd8e77",
            "p_source_label": "Crowdstrike-FDR-Dev",
            "p_timeline": "2023-04-21 19:48:28.97",
            "timestamp": "2023-04-21 19:48:28.97",
        },
    ),
]


@panther_managed
class CrowdstrikeFDRLOLBAS(Rule):
    log_types = [LogType.CROWDSTRIKE_FDR_EVENT]
    id = "Crowdstrike.FDR.LOLBAS-prototype"
    display_name = "Crowdstrike FDR LOLBAS"
    default_description = "Living off the land binaries and script usage"
    default_reference = "https://lolbas-project.github.io/"
    dedup_period_minutes = 1440
    enabled = False
    default_severity = Severity.INFO
    tags = ["Configuration Required"]
    tests = crowdstrike_fdrlolbas_tests
    LOLBAS_EXE = {
        "AppInstaller.exe",
        "At.exe",
        "Atbroker.exe",
        "Bash.exe",
        "Bitsadmin.exe",
        "CertOC.exe",
        "CertReq.exe",
        "Certutil.exe",
        "Cmd.exe",
        "Cmdkey.exe",
        "cmdl32.exe",
        "Cmstp.exe",
        "ConfigSecurityPolicy.exe",
        "Conhost.exe",
        "Control.exe",
        "Csc.exe",
        "Cscript.exe",
        "CustomShellHost.exe",
        "DataSvcUtil.exe",
        "Desktopimgdownldr.exe",
        "DeviceCredentialDeployment.exe",
        "Dfsvc.exe",
        "Diantz.exe",
        "Diskshadow.exe",
        "Dnscmd.exe",
        "Esentutl.exe",
        "Eventvwr.exe",
        "Expand.exe",
        "Explorer.exe",
        "Extexport.exe",
        "Extrac32.exe",
        "Findstr.exe",
        "Finger.exe",
        "fltMC.exe",
        "Forfiles.exe",
        "Ftp.exe",
        "Gpscript.exe",
        "Hh.exe",
        "IMEWDBLD.exe",
        "Ie4uinit.exe",
        "Ieexec.exe",
        "Ilasm.exe",
        "Infdefaultinstall.exe",
        "Installutil.exe",
        "Jsc.exe",
        "Ldifde.exe",
        "Makecab.exe",
        "Mavinject.exe",
        "Mmc.exe",
        "MpCmdRun.exe",
        "Msbuild.exe",
        "Msconfig.exe",
        "Msdt.exe",
        "Msedge.exe",
        "Mshta.exe",
        "Msiexec.exe",
        "Netsh.exe",
        "Odbcconf.exe",
        "OfflineScannerShell.exe",
        "OneDriveStandaloneUpdater.exe",
        "Pcalua.exe",
        "Pcwrun.exe",
        "Pktmon.exe",
        "Pnputil.exe",
        "Presentationhost.exe",
        "Print.exe",
        "PrintBrm.exe",
        "Psr.exe",
        "Rasautou.exe",
        "rdrleakdiag.exe",
        "Reg.exe",
        "Regasm.exe",
        "Regedit.exe",
        "Regini.exe",
        "Regsvcs.exe",
        "Regsvr32.exe",
        "Replace.exe",
        "Rpcping.exe",
        "Rundll32.exe",
        "Runexehelper.exe",
        "Runonce.exe",
        "Runscripthelper.exe",
        "Sc.exe",
        "Schtasks.exe",
        "Scriptrunner.exe",
        "Setres.exe",
        "SettingSyncHost.exe",
        "ssh.exe",
        "Stordiag.exe",
        "SyncAppvPublishingServer.exe",
        "Ttdinject.exe",
        "Tttracer.exe",
        "Unregmp2.exe",
        "vbc.exe",
        "Verclsid.exe",
        "Wab.exe",
        "winget.exe",
        "Wlrmdr.exe",
        "Wmic.exe",
        "WorkFolders.exe",
        "Wscript.exe",
        "Wsreset.exe",
        "wuauclt.exe",
        "Xwizard.exe",
        "fsutil.exe",
        "wt.exe",
    }

    def rule(self, event):
        if event.deep_get("event", "event_simpleName") == "ProcessRollup2":
            if event.deep_get("event", "event_platform") == "Win":
                exe = event.udm("process_name")
                return bool(exe.lower() in [x.lower() for x in self.LOLBAS_EXE])
        return False

    def title(self, event):
        exe = event.deep_get("event", "ImageFileName").split("\\")[-1]
        return f"Crowdstrike: LOLBAS execution - [{exe}] - [{event.deep_get('event', 'CommandLine')}]"

    def dedup(self, event):
        # dedup string on "{aid}-{exe}"
        exe = event.udm("process_name")
        return f"{event.deep_get('event', 'aid')}-{exe}"

    def alert_context(self, event):
        return crowdstrike_process_alert_context(event)
