// ARTEX-style intrusion stack: one row per entity (server host, source address or app) with 2+ behaviours or 1 decisive one.
// Written for Microsoft Sentinel (Log Analytics), where every table, the Device* copies included, has TimeGenerated. In Defender XDR
// advanced hunting, edit the DeviceFileEvents, DeviceProcessEvents and DeviceNetworkEvents legs only: filter on Timestamp and project
// TimeGenerated = Timestamp, EndTime = Timestamp. W3CIISLog, SigninLogs, AADServicePrincipalSignInLogs, AuditLogs and AWSCloudTrail
// exist there only when a Sentinel workspace is onboarded, and they keep TimeGenerated. Without a workspace, union isfuzzy=true
// skips those legs with a warning and only B7-B9 run. If the Defender tables are also streamed to that workspace with filtered
// ingestion, Microsoft advises setting the range with the portal time filter instead of in the query (a time filter in the query
// reads the streamed, filtered copy and "might generate incomplete results"): then drop the time filter from the Device legs.
// B1 and B2 read IIS logs only (W3CIISLog); nginx or Apache access logs need their own leg of the same shape.
let lookback = 1d;
let web_bin = 10m; let web_min_requests = 300; let web_min_paths = 100; let web_min_error_ratio = 0.3;
let harvest_min_objects = 50; let harvest_min_new_ratio = 0.8; let object_rx = @"/[A-Za-z_-]+/[0-9]{3,12}(/|$)";
let static_rx = @"(?i)\.(jpe?g|png|gif|webp|svg|ico|css|js|map|woff2?|ttf)$"; let dated_rx = @"/(19|20)[0-9][0-9]/[01][0-9]/";
let spray_bin = 1m; let spray_min_failures = 30; let spray_min_users = 10; let spray_codes = dynamic(["50126", "50053", "50034"]);
let sp_bin = 1h; let sp_min_principals = 3; let secret_codes = dynamic(["7000215", "7000222"]);
let probe_bin = 5m; let probe_min_denied = 10; let probe_min_apis = 25;
let probe_rx = @"AccessDenied|UnauthorizedOperation|DryRunOperation";
let secret_bin = 30m; let secret_min_distinct = 10;
let secret_apis = dynamic(["GetSecretValue", "BatchGetSecretValue", "GetParameter", "GetParameters", "GetParametersByPath"]);
let audit_bin = 1h; let audit_min_ops = 3; let audit_min_kinds = 2; let ip_rx = @"^[0-9A-Fa-f:.]*[.:][0-9A-Fa-f:.]*$";
let cred_rx = @"Add service principal credentials|Certificates and secrets management"; let role_rx = @"^Add (eligible )?member to role";
let priv_role_rx = @"Global Administrator|Privileged Role Administrator|Application Administrator";
let grant_rx = strcat(@"^(Add app role assignment to service principal|Add delegated permission grant|Consent to application",
    @"|Add owner to (service principal|application))");
let web_proc_rx = @"(?i)^(w3wp|httpd|nginx|apache2|php-(fpm|cgi)[0-9.]*|lsphp[0-9]*|frankenphp|tomcat[0-9]*)(\.exe)?$";
let db_proc_rx = @"(?i)^(mysqld|mariadbd)(\.exe)?$"; let script_rx = @"(?i)\.(aspx|ashx|asmx|asp|jspx?|php[0-9]?|phtml|phar|war)$";
let cache_rx = @"(?i)Temporary ASP\.NET Files|[\\/](cache|templates_c|storage[\\/]framework[\\/]views|wp-content[\\/]upgrade)([\\/]|$)";
let parent_rx = strcat(@"(?i)^(w3wp|httpd|nginx|apache2|lshttpd|php-(fpm|cgi)[0-9.]*|lsphp[0-9]*|frankenphp|tomcat[0-9]*|sqlservr)",
    @"(\.exe)?$");
let child_rx = strcat(@"(?i)^(cmd|powershell|pwsh|whoami|certutil|bitsadmin|net1?|nltest|wmic|schtasks|sh|bash|dash|zsh|curl|wget",
    @"|nc|ncat|socat|nmap|masscan|python[0-9.]*|perl|ruby[0-9.]*)(\.exe)?$");
let php_mail_rx = @"(?i)^(/bin/)?sh -c (-- )?/usr/sbin/sendmail -t -i$"; // PHP mail() through popen: the only B8 exclusion
// Short category lists: the destination category is the behaviour. Extend them with the providers and capture services you see.
let llm_host_rx = @"^(api\.openai\.com|api\.anthropic\.com|api\.deepseek\.com|api\.x\.ai|open\.bigmodel\.cn|openrouter\.ai)$";
let capture_host_rx = @"(^|\.)(webhook\.site|httpbin\.org|httpbun\.com|interact\.sh)$";
// Browser image names, compared case-insensitively: Windows, then Linux, then macOS (Chromium browsers fetch through "<name> Helper")
let browsers = dynamic(["chrome.exe", "msedge.exe", "firefox.exe", "brave.exe", "opera.exe", "vivaldi.exe", "iexplore.exe",
    "chrome", "msedge", "firefox", "firefox-bin", "firefox-esr", "brave", "brave-browser", "google chrome", "google chrome helper",
    "microsoft edge", "microsoft edge helper", "brave browser", "brave browser helper", "safari"]);
let corporate_egress = dynamic([]); // your corporate and NAT egress ranges in CIDR form; empty excludes nothing
let host_key = (h: string) { iff(h matches regex @"^\d{1,3}(\.\d{1,3}){3}$", h, tolower(tostring(split(h, ".")[0]))) };
union isfuzzy=true
    (W3CIISLog // B1 web request burst: one client against one server, 10 min, 300+ requests, 100+ distinct paths, 30%+ 4xx/5xx
    | where TimeGenerated > ago(lookback)
    | summarize Requests = count(), Paths = dcount(csUriStem), Errors = countif(toint(scStatus) >= 400)
              by Entity = host_key(Computer), cIP, bin(TimeGenerated, web_bin)
    | where Requests >= web_min_requests and Paths >= web_min_paths and Errors >= web_min_error_ratio * Requests
    | project TimeGenerated, EndTime = TimeGenerated + web_bin, Entity, EntityType = "host", Behaviour = "B1 web burst", Decisive = 0,
              Stage = "reconnaissance", Client = cIP, Evidence = strcat("client ", cIP, ": ", Requests, " req, ", Paths, " paths, ",
              Errors, " err")),
    (W3CIISLog // B2 bulk object harvest: one client, 10 min, 50+ distinct object-ID paths answered 2xx, 80%+ of those requests new
    | where TimeGenerated > ago(lookback) and toint(scStatus) between (200 .. 299)
    | where csUriStem matches regex object_rx and not(csUriStem matches regex static_rx) and not(csUriStem matches regex dated_rx)
    | summarize Objects = dcount(csUriStem), Hits = count() by Entity = host_key(Computer), cIP, bin(TimeGenerated, web_bin)
    | where Objects >= harvest_min_objects and Objects >= harvest_min_new_ratio * Hits
    | project TimeGenerated, EndTime = TimeGenerated + web_bin, Entity, EntityType = "host", Behaviour = "B2 object harvest",
              Stage = "collection", Decisive = 0, Client = cIP,
              Evidence = strcat("client ", cIP, ": ", Objects, " ids in ", Hits, " 2xx")),
    (SigninLogs // B3 spray: 1 min, 30+ failures over 10+ accounts from one address; success at or after the first spray minute is decisive
    | where TimeGenerated > ago(lookback) and (ResultType in (spray_codes) or ResultType == "0")
    | summarize Failures = countif(ResultType in (spray_codes)), Users = dcountif(UserPrincipalName, ResultType in (spray_codes)),
                Oks = countif(ResultType == "0") by IPAddress, Minute = bin(TimeGenerated, spray_bin)
    | extend IsSpray = Failures >= spray_min_failures and Users >= spray_min_users
    | summarize SprayFrom = minif(Minute, IsSpray), SprayTo = maxif(Minute, IsSpray), SprayMinutes = countif(IsSpray),
                PeakUsers = maxif(Users, IsSpray), LastOk = maxif(Minute, Oks > 0) by IPAddress
    | where SprayMinutes > 0
    | extend OkAfter = isnotnull(LastOk) and LastOk >= SprayFrom
    | project TimeGenerated = SprayFrom, EndTime = iff(OkAfter, max_of(LastOk, SprayTo), SprayTo) + spray_bin, Entity = IPAddress,
              EntityType = "source_ip", Behaviour = "B3 spray or secret validation", Decisive = iff(OkAfter, 1, 0),
              Stage = "initial-access", Evidence = strcat(SprayMinutes, " spray min, ", PeakUsers, " users", iff(OkAfter, ", ok", ""))),
    (AADServicePrincipalSignInLogs // B3 secret validation: 1 h, 3+ apps from one address, a bad secret, then success (decisive)
    | where TimeGenerated > ago(lookback)
    | extend SecretFail = ResultType in (secret_codes) or ResultSignature in (secret_codes), Ok = ResultType in ("0", "Success")
    | summarize Principals = dcount(ServicePrincipalId), SecretFails = countif(SecretFail), Oks = countif(Ok),
                FirstFail = minif(TimeGenerated, SecretFail), LastOk = maxif(TimeGenerated, Ok) by IPAddress, bin(TimeGenerated, sp_bin)
    | where Principals >= sp_min_principals and SecretFails >= 1 and LastOk >= FirstFail
    | project TimeGenerated, EndTime = TimeGenerated + sp_bin, Entity = IPAddress, EntityType = "source_ip",
              Behaviour = "B3 spray or secret validation", Stage = "initial-access", Decisive = 1,
              Evidence = strcat(Principals, " apps, ", SecretFails, " bad secrets, ", Oks, " ok")),
    (AWSCloudTrail // B4 cloud permission probing: 5 min, 25+ read or dry-run APIs and 10+ denied or dry-run calls, one address
    | where TimeGenerated > ago(lookback) and SourceIpAddress matches regex ip_rx
    | where EventName matches regex @"^(List|Describe|Get)" or ErrorCode == "Client.DryRunOperation"
    | where not(EventName in (secret_apis) and isempty(ErrorCode)) // successful secret reads count under B5, as in the SPL
    | summarize Apis = dcount(EventName), DeniedCalls = countif(ErrorCode matches regex probe_rx), Arns = make_set(UserIdentityArn, 5)
                by SourceIpAddress, bin(TimeGenerated, probe_bin)
    | where Apis >= probe_min_apis and DeniedCalls >= probe_min_denied
    | project TimeGenerated, EndTime = TimeGenerated + probe_bin, Entity = SourceIpAddress, EntityType = "source_ip",
              Behaviour = "B4 cloud probing", Stage = "discovery", Decisive = 0,
              Evidence = strcat(Apis, " apis, ", DeniedCalls, " denied/dry-run: ", strcat_array(Arns, ", "))),
    (AWSCloudTrail // B5 bulk secret reads: 30 min, 10+ distinct secrets or parameters read successfully from one address
    | where TimeGenerated > ago(lookback) and EventName in (secret_apis) and isempty(ErrorCode) and SourceIpAddress matches regex ip_rx
    | extend P = parse_json(RequestParameters)
    | extend SecretRef = coalesce(tostring(P.secretId), tostring(P.name), tostring(P.path), EventName)
    | summarize Secrets = dcount(SecretRef), Arns = make_set(UserIdentityArn, 5) by SourceIpAddress, bin(TimeGenerated, secret_bin)
    | where Secrets >= secret_min_distinct
    | project TimeGenerated, EndTime = TimeGenerated + secret_bin, Entity = SourceIpAddress, EntityType = "source_ip",
              Behaviour = "B5 secret reads", Stage = "credential-access", Decisive = 0,
              Evidence = strcat(Secrets, " secrets: ", strcat_array(Arns, ", "))),
    (AuditLogs // B6 app credential, consent, owner or role changes: 1 h, 3+ ops or 2+ kinds; app adds credential + admin role: decisive
    | where TimeGenerated > ago(lookback) and Result =~ "success"
    | extend IsCred = OperationName matches regex cred_rx, IsRole = OperationName matches regex role_rx
    | where IsCred or IsRole or OperationName matches regex grant_rx
    | extend IsPrivRole = IsRole and tostring(TargetResources) matches regex priv_role_rx
    | extend ActorIp = tostring(InitiatedBy.user.ipAddress), ActorSp = tostring(InitiatedBy.app.servicePrincipalId)
    | extend Entity = iff(ActorIp matches regex ip_rx, ActorIp, ActorSp), EntityType = iff(ActorIp matches regex ip_rx, "source_ip", "app")
    | where isnotempty(Entity)
    | summarize Ops = count(), Kinds = dcount(OperationName), Creds = countif(IsCred), PrivRoles = countif(IsPrivRole),
                OpList = make_set(OperationName, 5) by Entity, EntityType, bin(TimeGenerated, audit_bin)
    | where Ops >= audit_min_ops or Kinds >= audit_min_kinds
    | project TimeGenerated, EndTime = TimeGenerated + audit_bin, Entity, EntityType, Behaviour = "B6 app credential or role",
              Stage = "persistence", Decisive = iff(EntityType == "app" and Creds > 0 and PrivRoles > 0, 1, 0),
              Evidence = strcat_array(OpList, "; ")),
    (DeviceFileEvents // B7 web or database server process writes a server-side script file; a database engine as the writer is decisive
    | where TimeGenerated > ago(lookback) and ActionType in ("FileCreated", "FileModified", "FileRenamed")
    | where (InitiatingProcessFileName matches regex web_proc_rx or InitiatingProcessFileName matches regex db_proc_rx)
         and FileName matches regex script_rx and not(FolderPath matches regex cache_rx)
    | project TimeGenerated, EndTime = TimeGenerated, Entity = host_key(DeviceName), EntityType = "host",
              Behaviour = "B7 script write", Stage = "persistence", Evidence = strcat(InitiatingProcessFileName, " wrote ", FolderPath),
              Decisive = iff(InitiatingProcessFileName matches regex db_proc_rx, 1, 0)),
    (DeviceProcessEvents // B8 web, app or database server process spawns a shell, downloader, admin or recon tool
    | where TimeGenerated > ago(lookback) and FileName matches regex child_rx and not(ProcessCommandLine matches regex php_mail_rx)
    | where InitiatingProcessFileName matches regex parent_rx or (InitiatingProcessFileName matches regex @"(?i)^javaw?(\.exe)?$"
         and InitiatingProcessCommandLine matches regex @"(?i)catalina|weblogic")
    | project TimeGenerated, EndTime = TimeGenerated, Entity = host_key(DeviceName), EntityType = "host",
              Behaviour = "B8 shell spawn", Stage = "execution", Decisive = 0,
              Evidence = strcat(InitiatingProcessFileName, " > ", FileName, ": ", substring(ProcessCommandLine, 0, 120))),
    (DeviceNetworkEvents // B9 non-browser process connects to an LLM API or a public request-capture host
    | where TimeGenerated > ago(lookback) and isnotempty(RemoteUrl) and not(InitiatingProcessFileName in~ (browsers))
    | extend UrlHost = extract(@"^(?:[a-z][a-z0-9+.-]*://)?([^/:?#]+)", 1, tolower(RemoteUrl))
    | where UrlHost matches regex llm_host_rx or UrlHost matches regex capture_host_rx
    | project TimeGenerated, EndTime = TimeGenerated, Entity = host_key(DeviceName), EntityType = "host",
              Behaviour = "B9 LLM or request-capture egress", Stage = "command-and-control", Decisive = 0,
              Evidence = strcat(InitiatingProcessFileName, " > ", UrlHost))
| where EntityType != "source_ip" or array_length(corporate_egress) == 0
     or not(coalesce(ipv4_is_in_any_range(Entity, corporate_egress), false))
| summarize behaviours = make_set(Behaviour), stages = make_set(Stage), decisive = max(Decisive), first_seen = min(TimeGenerated),
            last_seen = max(EndTime), evidence = make_set(Evidence, 20), b1_clients = make_set_if(Client, Behaviour == "B1 web burst"),
            b2_clients = make_set_if(Client, Behaviour == "B2 object harvest") by entity = Entity, entity_type = EntityType
| extend split12 = iff(array_length(b1_clients) > 0 and array_length(b2_clients) > 0
                       and array_length(set_intersect(b1_clients, b2_clients)) == 0, 1, 0) // B1 and B2 from different clients count once
| extend behaviour_count = array_length(behaviours) - split12, stage_count = array_length(stages) - split12
| where behaviour_count >= 2 or decisive == 1
| extend behaviours = array_sort_asc(behaviours), score = 10 * behaviour_count + 5 * stage_count + 20 * decisive
| project entity, entity_type, behaviours, stages, score, behaviour_count, stage_count, decisive, first_seen, last_seen, evidence
| order by score desc
