IOC HUNT
134 / 134 query visibili

IOC HUNT

INTELLIGENCE · OPERATIONS · CYBERSECURITY
KNOW. HUNT. DEFEND.
ADVANCED HUNTING & OPERATIONAL KQL PLAYBOOK · KNOW. HUNT. DEFEND.
IOC HUNTer APP — PLAYBOOK & CATALOGO INTEGRALE KQL (134 QUERY)
Archivio interattivo 100% client-side con la raccolta integrale e sanitizzata di 134 query KQL per Microsoft Defender XDR e Sentinel, divise in 4 sezioni:
1. Sezione 1 (01 – 80): Tutte le 80 query esportate da ambienti enterprise Microsoft Defender XDR (70 query divise nelle sottocartelle + 10 query schedulate/root).
2. Sezione 2 (Q01 – Q42): Tutte le 42 query operative e metodologiche del manuale SOC L1/L2 MDE.
3. Sezione 3 & 4 (C01 – C12 + Export): 12 query derivate da casi reali di Incident Response (file .lnk, fix schema IdentityLogonEvents, manutenzione log, correlazione USB/Alert, post-sandbox) + script JS universale per esportare le query da Defender.

🔍 Indice Rapido delle Parole Chiave (Ctrl + F o Clicca su un Tag per filtrare)

SEZIONE 1: LE 80 QUERY ESPORTATE DA DEFENDER (01 – 80)

1.1 Ricerca Globale IOC

01. Ricerca Globale IOC nelle Tabelle (ID: 32384)
  • Percorso: Root Condivisa
  • Keywords: #IOC #GlobalSearch #TableDiscovery #IP
// The following query allows you to identify where the data is located in the available telemetry. Once you know which table it is in, you can search for the data needed for the analysis.
search "8.8.8.8"
| summarize Count=count() by $table 
| order by Count desc

1.2 Pulizia Log di Sicurezza Windows (Rule027_Windows logs audit cleared)

02. Rule027_Query01 — Evento SecurityLogCleared (ID: 32385)
  • Percorso: Rule027_Windows logs audit cleared
  • Keywords: #LogCleared #DefenseEvasion #SecurityEvent
//Search for event with action type "SecurityLogCleared"

DeviceEvents
| where ActionType == "SecurityLogCleared"
| where DeviceName contains "DEVICE"
| sort by Timestamp desc
03. Rule027_Query02 — Comandi di cancellazione Event Log (ID: 32386)
  • Percorso: Rule027_Windows logs audit cleared
  • Keywords: #LogCleared #DefenseEvasion #SecurityEvent #Wevtutil #Process #CommandLine
//This query checks the device for commands that might indicate the deletion of Windows logs (for example, using `wevtutil cl`, `Clear-EventLog`, or `Remove-EventLog`).

DeviceProcessEvents
| where DeviceName contains "DEVICE"
| where ProcessCommandLine has_any (
    "wevtutil",
    "Clear-EventLog",
    "Remove-EventLog",
    "clear-log"
)
| project Timestamp,
          DeviceName,
          AccountName,
          FileName,
          ProcessCommandLine,
          InitiatingProcessFileName,
          InitiatingProcessCommandLine
| order by Timestamp desc
04. Rule027_Query03 — Ricerca Event ID 4612 (ID: 32387)
  • Percorso: Rule027_Windows logs audit cleared
  • Keywords: #LogCleared #DefenseEvasion #SecurityEvent #Event4612
//Search for Event ID 4612. 4612 = Internal resources allocated for the queuing of audit messages have been exhausted, leading to loss of some audits.

SecurityEvent
| where Computer contains "DEVICE"
| where EventID == 4612
| project TimeGenerated,
          Computer,
          Account,
          Activity,
          EventID
| order by TimeGenerated desc
05. Rule027_Query04 — Verifica Event ID 4612 sull'host (ID: 32389)
  • Percorso: Rule027_Windows logs audit cleared
  • Keywords: #LogCleared #DefenseEvasion #SecurityEvent #Event4612
// Search for Event ID 4612. 4612 = Internal resources allocated for the queuing of audit messages have been exhausted, leading to loss of some audits.

SecurityEvent
| where Computer contains "DEVICE"
| where EventID == 4612
| project TimeGenerated,
          Computer,
          Account,
          Activity,
          EventID
| order by TimeGenerated desc
06. Rule027_Query05 — Parsing XML dell'evento 4612 (ID: 32390)
  • Percorso: Rule027_Windows logs audit cleared
  • Keywords: #LogCleared #DefenseEvasion #SecurityEvent #Event4612 #XMLParse
//Parsing the XML details of event 4612

SecurityEvent
| where Computer contains "DEVICE"
| where EventID == 4612
| extend ParsedData = parse_xml(EventData)
| project TimeGenerated, ParsedData

1.3 Dispositivi USB e Supporti Rimovibili (USB mounted on device)

07. USB_Query01 — Identificazione dispositivo USB collegato (ID: 32391)
  • Percorso: Dispositivi USB montati sull'endpoint
  • Keywords: #USB #RemovableDrive #Exfiltration #UsbMounted #DeviceEvents
//Identify a USB that was plugged on a device to retreive product name, serianN etc..-and check was the correct one
DeviceEvents
| where DeviceName contains "xxxxx"
| where ActionType contains "UsbDriveMounted"
08. USB_Query02 — Lettere di unità rimovibili rilevate (ID: 32392)
  • Percorso: Dispositivi USB montati sull'endpoint
  • Keywords: #USB #RemovableDrive #Exfiltration #DeviceFileEvents #DriveLetter
//Other queries
DeviceFileEvents
| where Timestamp > ago(30d)
| where DeviceName == "[DEVICE_NAME]"
| extend DriveLetter = tostring(split(FolderPath, "\\")[0])
| where DriveLetter !in ("C:", "D:")  // Assuming C: and D: are internal
| summarize RemovableDrives = make_set(DriveLetter) by DeviceName
| project DeviceName, RemovableDrives
09. USB_Query03 — Riepilogo unità interne e rimovibili per Hostname (ID: 32393)
  • Percorso: Dispositivi USB montati sull'endpoint
  • Keywords: #USB #RemovableDrive #Exfiltration #DeviceFileEvents #DriveLetter
//Other queries
DeviceFileEvents
| where Timestamp > ago(30d)
| where DeviceName == "[DEVICE_NAME]"
| extend DriveLetter = tostring(split(FolderPath, "\\")[0])
| summarize
    AllDrives = make_set(DriveLetter),
    InternalDrives = make_set(iff(DriveLetter in ("C:", "D:"), DriveLetter, "")),
    RemovableDrives = make_set(iff(DriveLetter !in ("C:", "D:"), DriveLetter, "")),
    DriveCount = dcount(DriveLetter)
    by DeviceName
| project DeviceName, DriveCount, AllDrives, InternalDrives, RemovableDrives
10. USB_Query04 — Riepilogo unità interne e rimovibili per FQDN (ID: 32394)
  • Percorso: Dispositivi USB montati sull'endpoint
  • Keywords: #USB #RemovableDrive #Exfiltration #DeviceFileEvents #DriveLetter
//Other queries
DeviceFileEvents
| where Timestamp > ago(30d)
| where DeviceName == "[DEVICE_NAME].[INTERNAL_DOMAIN]"
| extend DriveLetter = tostring(split(FolderPath, "\\")[0])
| summarize
    AllDrives = make_set(DriveLetter),
    InternalDrives = make_set(iff(DriveLetter in ("C:", "D:"), DriveLetter, "")),
    RemovableDrives = make_set(iff(DriveLetter !in ("C:", "D:"), DriveLetter, "")),
    DriveCount = dcount(DriveLetter)
    by DeviceName
| project DeviceName, DriveCount, AllDrives, InternalDrives, RemovableDrives
11. USB_Query05 — Elenco file e operazioni sulle unità disco (ID: 32395)
  • Percorso: Dispositivi USB montati sull'endpoint
  • Keywords: #USB #RemovableDrive #Exfiltration #DeviceFileEvents #DriveLetter
//Other queries
DeviceFileEvents
| where Timestamp > ago(2d)
| where DeviceName == "[DEVICE_NAME].[INTERNAL_DOMAIN]"
| extend DriveLetter = tostring(split(FolderPath, "\\")[0])
| distinct Timestamp, DeviceName, FolderPath, FileName, ActionType, DriveLetter
| order by Timestamp desc

1.4 Analisi WAF Akamai (Rule017_AKAMAI)

12. AKAMAI_Query01 — Dettaglio eventi WAF Akamai per IP sorgente (ID: 32396)
  • Percorso: Rule017_AKAMAI
  • Keywords: #Akamai #WAF #Network
//To log the events that triggered the rule, including key fields such as status code, target, and action:

CommonSecurityLogDL_CL
| where DeviceVendor == "Akamai"
| where DeviceProduct == "akamai_siem"
| where SourceIP == "IP_MALEVOLO"
| extend HttpStatusCode = extract(@'.*AkamaiSiemResponseStatus=(.*?);', 1, AdditionalExtensions)
| project
    TimeGenerated,
    SourceIP,
    DestinationHostName,
    HttpStatusCode,
    DeviceCustomString2,
    DeviceAction,
    RequestMethod,
    AdditionalExtensions
| order by TimeGenerated desc
13. AKAMAI_Query02 — Riepilogo target e Status Code HTTP (ID: 32397)
  • Percorso: Rule017_AKAMAI
  • Keywords: #Akamai #WAF #Network
//To understand the targets and the returned status codes:

CommonSecurityLogDL_CL
| where DeviceVendor == "Akamai"
| where DeviceProduct == "akamai_siem"
| where SourceIP == "IP_MALEVOLO"
| extend HttpStatusCode = extract(@'.*AkamaiSiemResponseStatus=(.*?);', 1,
AdditionalExtensions)
| summarize Count=count() by DestinationHostName, HttpStatusCode
| order by Count desc
14. Filtra eventi WAF per Content-Type con Status 200 (ID: 32428)
  • Percorso: Rule017_AKAMAI
  • Keywords: #Akamai #WAF #Network #HTTP200
//Filter events by Content-Type. 

CommonSecurityLogDL_CL
| where DeviceVendor == "Akamai"
| where DeviceProduct == "akamai_siem"
| where SourceIP == "[MALICIOUS_IP]"
| extend HttpStatusCode = extract(@"AkamaiSiemResponseStatus=(.*?);", 1, AdditionalExtensions)
| where HttpStatusCode == "200"
| extend ContentType = extract(@"Content-Type:\+([^\\n;]+)", 1, AdditionalExtensions)
| summarize Count=count() by ContentType
| order by Count desc
15. Ispezione singolo evento WAF con Status 200 (ID: 32429)
  • Percorso: Rule017_AKAMAI
  • Keywords: #Akamai #WAF #Network #HTTP200
//Expansion of a single field, survey 200. 

CommonSecurityLogDL_CL
| where DeviceVendor == "Akamai"
| where DeviceProduct == "akamai_siem"
| where SourceIP == "[MALICIOUS_IP]"
| extend HttpStatusCode = extract(@"AkamaiSiemResponseStatus=(.*?);", 1, AdditionalExtensions)
| where HttpStatusCode == "200"
| order by TimeGenerated desc
| take 1
16. Raggruppa le risposte HTTP 200 per percorso URL (ID: 32430)
  • Percorso: Rule017_AKAMAI
  • Keywords: #Akamai #WAF #Network #HTTP200
//Group the 200 by path 
CommonSecurityLogDL_CL
| where DeviceVendor == "Akamai"
| where DeviceProduct == "akamai_siem"
| where SourceIP == "[MALICIOUS_IP]"
| extend HttpStatusCode = extract(@"AkamaiSiemResponseStatus=(.*?);", 1, AdditionalExtensions)
| where HttpStatusCode == "200"
| extend UrlPath = tostring(parse_url(RequestURL).Path)
| extend QueryString = extract(@"\?(.*)$", 1, RequestURL)
| extend DecodedQuery = url_decode(QueryString)
| summarize
    Hits=count(),
    FirstSeen=min(TimeGenerated),
    LastSeen=max(TimeGenerated),
    Queries=make_set(DecodedQuery, 20)
    by DestinationHostName, RequestMethod, UrlPath
| order by Hits desc
17. Dettaglio richieste WAF con Status Code 200 (ID: 32431)
  • Percorso: Rule017_AKAMAI
  • Keywords: #Akamai #WAF #Network #HTTP200
//Status Code 200 
CommonSecurityLogDL_CL
| where DeviceVendor == "Akamai"
| where DeviceProduct == "akamai_siem"
| where SourceIP == "[MALICIOUS_IP]"
| extend HttpStatusCode = extract(@"AkamaiSiemResponseStatus=(.*?);", 1, AdditionalExtensions)
| where HttpStatusCode == "200"
| extend UrlPath = tostring(parse_url(RequestURL).Path)
| extend QueryString = extract(@"\?(.*)$", 1, RequestURL)
| extend DecodedQuery = url_decode(QueryString)
| project
    TimeGenerated,
    SourceIP,
    DestinationHostName,
    RequestMethod,
    HttpStatusCode,
    DeviceAction,
    UrlPath,
    QueryString,
    DecodedQuery,
    DeviceCustomString1,
    DeviceCustomString2,
    RequestURL
| order by TimeGenerated desc
18. Richieste HTTP POST con Status Code 200 (ID: 32432)
  • Percorso: Rule017_AKAMAI
  • Keywords: #Akamai #WAF #Network #HTTP200 #POST
//POST whit 200
CommonSecurityLogDL_CL
| where DeviceVendor == "Akamai"
| where DeviceProduct == "akamai_siem"
| where SourceIP == "[MALICIOUS_IP]"
| extend HttpStatusCode = extract(@"AkamaiSiemResponseStatus=(.*?);", 1, AdditionalExtensions)
| where HttpStatusCode == "200"
| where RequestMethod == "POST"
| extend
    ResponseContentType = extract(@"AkamaiSiemResponseHeaders=Content-Type:\+([^\\n;]+)", 1, AdditionalExtensions),
    ContentLength = extract(@"Content-Length:\+(\d+)", 1, AdditionalExtensions),
    RuleTags = extract(@"AkamaiSiemRuleTags=([^;]+)", 1, AdditionalExtensions)
| project
    TimeGenerated,
    RequestMethod,
    RequestURL,
    ResponseContentType,
    ContentLength,
    SentBytes,
    DeviceAction,
    RuleTags,
    DeviceCustomString1,
    DeviceCustomString2
| order by TimeGenerated asc

1.5 Indagini su URL, Domini e Navigazione (URL Search)

19. Ricerca URL all'interno delle Email (ID: 32398)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #Email #Phishing
//To detect URLs in emails

EmailEvents
// | where RecipientEmailAddress contains "@xxx.xxx"
|join EmailUrlInfo on NetworkMessageId
|where Url contains "xxx"
20. Utenti e dispositivi che hanno contattato un URL (ID: 32399)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network
//check who contacted an URL, i.e. clicked on a phishing link

DeviceNetworkEvents
| where RemoteUrl contains "xxxx"
// retrieve user from device name u can delete this part if no needed
| join IdentityInfo on $left.InitiatingProcessAccountSid == $right.OnPremSid
| project Timestamp, RemoteUrl,ActionType,InitiatingProcessAccountName,EmailAddress,JobTitle,Department, DeviceName,  InitiatingProcessFileName
| summarize  count() by EmailAddress, JobTitle, Department, DeviceName, ActionType
21. Ricerca multi-tabella di un dominio sospetto (ID: 32400)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network
//This query searches for evidence of interaction with the domain [SUSPICIOUS_DOMAIN] in various MDE telemetry tables, then filters the results to three specific internal IP addresses.

let url = "[SUSPICIOUS_DOMAIN]";
search in (EmailUrlInfo, UrlClickEvents, DeviceNetworkEvents, DeviceFileEvents, DeviceEvents)
(
    RemoteUrl has url
    or FileOriginUrl has url
    or FileOriginReferrerUrl has url
    or Url has url
)
| where LocalIP in ("[INTERNAL_IP_1]", "[INTERNAL_IP_2]", "[INTERNAL_IP_3]")
| summarize EventCount=count(), LastSeen=max(Timestamp)
    by DeviceName, AccountName, Url
| order by LastSeen desc
22. Dispositivi distinti che hanno contattato il dominio (ID: 32401)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network
//This query returns the various devices that have contacted the domain

DeviceNetworkEvents
| where RemoteUrl contains "[SUSPICIOUS_DOMAIN]"
| distinct DeviceName
23. Tentativi di connessione verso uno specifico dominio (ID: 32402)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network
//Search for access attempts to a specific domain

DeviceNetworkEvents
| where RemoteUrl contains "evil-domain.com"
| project Timestamp,
          DeviceName,
          InitiatingProcessAccountName,
          InitiatingProcessFileName,
          RemoteUrl,
          RemoteIP
| order by Timestamp desc
24. Tutti i domini contattati da un singolo host (ID: 32403)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network
//All domains contacted by a host

DeviceNetworkEvents
| where DeviceName contains "DEVICE"
| summarize Count=count() by RemoteUrl
| order by Count desc
25. Domini contattati tramite PowerShell (ID: 32404)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #PowerShell
//Domains Contacted by PowerShell

DeviceNetworkEvents
| where InitiatingProcessFileName =~ "powershell.exe"
| project Timestamp,
          DeviceName,
          RemoteUrl,
          RemoteIP,
          InitiatingProcessCommandLine
| order by Timestamp desc
26. URL contattati da interpreti e script sospetti (ID: 32405)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #LOLBin
//Domains contacted by suspicious scripts

DeviceNetworkEvents
| where InitiatingProcessFileName in~ (
    "powershell.exe",
    "cmd.exe",
    "wscript.exe",
    "cscript.exe",
    "mshta.exe"
)
| project Timestamp,
          DeviceName,
          RemoteUrl,
          RemoteIP,
          InitiatingProcessFileName,
          InitiatingProcessCommandLine
27. File scaricati da Internet (FileOriginUrl) (ID: 32406)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #Download
//Downloading Files from the Internet

DeviceFileEvents
| where FileOriginUrl != ""
| project Timestamp,
          DeviceName,
          FileName,
          FileOriginUrl,
          FolderPath
| order by Timestamp desc
28. File scaricati da uno specifico dominio (ID: 32407)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #Download
//Downloading Files from specific domain

DeviceFileEvents
| where FileOriginUrl contains "evil-domain.com"
| project Timestamp,
          DeviceName,
          FileName,
          FileOriginUrl
29. Navigazione browser verso uno specifico dominio (ID: 32408)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #Browser
//Browsers that have visited a domain

DeviceNetworkEvents
| where RemoteUrl contains "evil-domain.com"
| where InitiatingProcessFileName in~ (
    "chrome.exe",
    "msedge.exe",
    "firefox.exe",
    "iexplore.exe"
)
| project Timestamp,
          DeviceName,
          InitiatingProcessFileName,
          RemoteUrl
30. Top 50 domini più contattati nelle ultime 24 ore (ID: 32409)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network
//Top 50 domains last 24h

DeviceNetworkEvents
| where Timestamp > ago(24h)
| summarize Connections=count() by RemoteUrl
| top 50 by Connections
31. Possibile Command & Control (Domini rari nel tenant) (ID: 32410)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #C2 #RareDomain
//Possible Command & Control (rare domains)

DeviceNetworkEvents
| where Timestamp > ago(30d)
| summarize Devices=dcount(DeviceName) by RemoteUrl
| where Devices <= 2
| order by Devices asc
32. Domini contattati in concomitanza di un Alert (ID: 32411)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network
//Domains contacted immediately before an alert

AlertEvidence
| where DeviceName contains "[DEVICE_NAME]"
| join kind=inner (
    DeviceNetworkEvents
) on DeviceId
| project AlertTitle,
          Timestamp,
          DeviceName,
          RemoteUrl,
          RemoteIP
| order by Timestamp desc
33. Domini contattati da applicazioni Microsoft Office (ID: 32412)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #Office #Phishing
//Domains Contacted by Office (phishing)

DeviceNetworkEvents
| where InitiatingProcessFileName in~ (
    "winword.exe",
    "excel.exe",
    "powerpnt.exe",
    "outlook.exe"
)
| project Timestamp,
          DeviceName,
          RemoteUrl,
          InitiatingProcessFileName
| order by Timestamp desc
34. Ricerca combinata IOC di rete (Dominio + IP + URL) (ID: 32413)
  • Percorso: Ricerca URL e Domini
  • Keywords: #URL #Domain #Network #IOC
//Complete IOC Search (Domain + IP + URL)

DeviceNetworkEvents
| where RemoteUrl contains "evil-domain.com"
   or RemoteIP == "1.2.3.4"
| project Timestamp,
          DeviceName,
          RemoteUrl,
          RemoteIP,
          InitiatingProcessFileName,
          InitiatingProcessAccountName
| order by Timestamp desc

1.6 Monitoraggio Storage Account Azure Blob (Storage Account Azure Blob)

35. Accessi e connessioni verso Azure Blob Storage (ID: 32414)
  • Percorso: Storage Account Azure Blob
  • Keywords: #AzureBlob #CloudApps #Exfiltration
//Who has signed in to the storage account? 

DeviceNetworkEvents
| where RemoteUrl contains "blob.core.windows.net"
| where RemoteUrl contains "[STORAGE_ACCOUNT_NAME]"
| project TimeGenerated,
    DeviceName,
    InitiatingProcessAccountName,
    RemoteUrl,
    RemoteIP,
    LocalIP
| order by TimeGenerated desc
36. Attività di uno specifico dispositivo verso lo Storage Account (ID: 32415)
  • Percorso: Storage Account Azure Blob
  • Keywords: #AzureBlob #CloudApps #Exfiltration
//Activities of a Specific Device 

DeviceNetworkEvents
| where DeviceName startswith "[DEVICE_NAME]"
| where RemoteUrl contains "[STORAGE_ACCOUNT_NAME]"
| project
    TimeGenerated,
    InitiatingProcessAccountName,
    InitiatingProcessFileName,
    RemoteUrl
| order by TimeGenerated desc
37. Utilizzo del client Azure Storage Explorer (ID: 32416)
  • Percorso: Storage Account Azure Blob
  • Keywords: #AzureBlob #CloudApps #Exfiltration #StorageExplorer #Process
//Check the usage of Azure Storage Explorer 

DeviceProcessEvents
| where DeviceName startswith "[DEVICE_NAME]"
| where FileName contains "Storage"
    or ProcessCommandLine contains "StorageExplorer"
| project
    TimeGenerated,
    DeviceName,
    InitiatingProcessAccountName,
    FileName,
    ProcessCommandLine
| order by TimeGenerated desc

1.7 Analisi Completa per Hash (HASH Search)

38. Ricerca generica di Hash SHA256 nei file (ID: 32417)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC
let hashList = dynamic([
  "[SHA256_HASH]"
]);
DeviceFileEvents
| where SHA256 in (hashList)
| summarize MacchineCoinvolte = make_set(DeviceName) by SHA256
39. Verifica esecuzione di un file tramite Hash (ID: 32418)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC
//This is very useful for determining whether the file simply exists or has actually been launched.

let Hash = "INSERISCI_HASH";
DeviceProcessEvents
| where Timestamp > ago(30d)
| where SHA1 =~ Hash or SHA256 =~ Hash or MD5 =~ Hash
| project Timestamp,
          DeviceName,
          AccountName,
          FileName,
          FolderPath,
          ProcessCommandLine,
          SHA1,
          SHA256,
          InitiatingProcessFileName,
          InitiatingProcessCommandLine
| order by Timestamp desc
40. Creazione o modifica di file corrispondenti all'Hash (ID: 32419)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC
//Search for file creation/editing

let Hash = "INSERISCI_HASH";
DeviceFileEvents
| where Timestamp > ago(30d)
| where SHA1 =~ Hash or SHA256 =~ Hash or MD5 =~ Hash
| project Timestamp,
          DeviceName,
          ActionType,
          FileName,
          FolderPath,
          FileSize,
          SHA1,
          SHA256,
          InitiatingProcessFileName,
          InitiatingProcessCommandLine
| order by Timestamp desc
41. Provenienza del download per uno specifico Hash (ID: 32420)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC
//Find out where it was downloaded from

let Hash = "INSERISCI_HASH";
DeviceFileEvents
| where Timestamp > ago(30d)
| where SHA1 =~ Hash or SHA256 =~ Hash or MD5 =~ Hash
| where isnotempty(FileOriginUrl)
       or isnotempty(FileOriginIP)
       or isnotempty(FileOriginReferrerUrl)
| project Timestamp,
          DeviceName,
          FileName,
          FolderPath,
          SHA1,
          SHA256,
          FileOriginUrl,
          FileOriginReferrerUrl,
          FileOriginIP,
          InitiatingProcessFileName
| order by Timestamp desc
42. Diffusione del file: quante postazioni lo hanno avuto? (ID: 32421)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC
//How many workstations have accessed that file?

let Hash = "INSERISCI_HASH";
DeviceFileEvents
| where Timestamp > ago(30d)
| where SHA1 =~ Hash or SHA256 =~ Hash or MD5 =~ Hash
| summarize
    FirstSeen = min(Timestamp),
    LastSeen = max(Timestamp),
    DeviceCount = dcount(DeviceId),
    Devices = make_set(DeviceName, 100),
    Paths = make_set(FolderPath, 100),
    Actions = make_set(ActionType, 100)
    by SHA1, SHA256, FileName
| order by DeviceCount desc
43. Verifica della firma digitale e del certificato del file (ID: 32422)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC #Signature
//Verify the file's digital signature

let Hash = "SHA1_HERE";
DeviceProcessEvents
| where Timestamp > ago(30d)
| where SHA1 =~ Hash
| join kind=leftouter (
    DeviceFileCertificateInfo
    | summarize arg_max(Timestamp, *) by SHA1
    | project SHA1,
              IsSigned,
              IsTrusted,
              Signer,
              Issuer,
              CertificateCreationTime,
              CertificateExpirationTime
) on SHA1
| project Timestamp,
          DeviceName,
          FileName,
          FolderPath,
          ProcessCommandLine,
          SHA1,
          IsSigned,
          IsTrusted,
          Signer,
          Issuer
44. Connessioni di rete generate dal file sospetto (ID: 32423)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC #Network
//Connections made by the suspicious file

let Hash = "INSERISCI_HASH";
DeviceNetworkEvents
| where Timestamp > ago(30d)
| where InitiatingProcessSHA1 =~ Hash
    or InitiatingProcessSHA256 =~ Hash
    or InitiatingProcessMD5 =~ Hash
| project Timestamp,
          DeviceName,
          InitiatingProcessFileName,
          InitiatingProcessCommandLine,
          RemoteUrl,
          RemoteIP,
          RemotePort,
          Protocol,
          LocalIP
| order by Timestamp desc
45. Modifiche al Registro di Sistema effettuate dal file (ID: 32424)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC #Registry
//Changes to the registry made by the file

let Hash = "INSERISCI_HASH";
DeviceRegistryEvents
| where Timestamp > ago(30d)
| where InitiatingProcessSHA1 =~ Hash
    or InitiatingProcessSHA256 =~ Hash
    or InitiatingProcessMD5 =~ Hash
| project Timestamp,
          DeviceName,
          ActionType,
          RegistryKey,
          RegistryValueName,
          RegistryValueData,
          InitiatingProcessFileName,
          InitiatingProcessCommandLine
| order by Timestamp desc
46. Timeline completa dell'Hash: File → Esecuzione → Rete (ID: 32425)
  • Percorso: Ricerca e Analisi Hash
  • Keywords: #Hash #SHA256 #SHA1 #IOC #Timeline
//This reconstructs the following sequence in a single timeline: file presence → execution → network activity

let Hash = "INSERISCI_HASH";
union
(
    DeviceFileEvents
    | where SHA1 =~ Hash or SHA256 =~ Hash or MD5 =~ Hash
    | project Timestamp,
              DeviceName,
              EventType="FILE",
              ActionType,
              FileName,
              FolderPath,
              SHA1,
              SHA256,
              Info=strcat(
                    "Parent: ", InitiatingProcessFileName,
                    " | CMD: ", InitiatingProcessCommandLine,
                    " | Origin: ", FileOriginUrl
              )
),
(
    DeviceProcessEvents
    | where SHA1 =~ Hash or SHA256 =~ Hash or MD5 =~ Hash
    | project Timestamp,
              DeviceName,
              EventType="PROCESS",
              ActionType,
              FileName,
              FolderPath,
              SHA1,
              SHA256,
              Info=strcat(
                    "CMD: ", ProcessCommandLine,
                    " | Parent: ", InitiatingProcessFileName,
                    " | Parent CMD: ", InitiatingProcessCommandLine
              )
),
(
    DeviceNetworkEvents
    | where InitiatingProcessSHA1 =~ Hash
        or InitiatingProcessSHA256 =~ Hash
        or InitiatingProcessMD5 =~ Hash
    | project Timestamp,
              DeviceName,
              EventType="NETWORK",
              ActionType,
              FileName=InitiatingProcessFileName,
              FolderPath=InitiatingProcessFolderPath,
              SHA1=InitiatingProcessSHA1,
              SHA256=InitiatingProcessSHA256,
              Info=strcat(
                    "RemoteUrl: ", RemoteUrl,
                    " | RemoteIP: ", RemoteIP,
                    ":", tostring(RemotePort)
              )
)
| order by Timestamp asc

1.8 Analisi Errori HTTP 5xx su Syslog (Rule031_statuscode5XX)

47. Identificazione degli Application Host impattati (ID: 32426)
  • Percorso: Rule031_statuscode5XX
  • Keywords: #HTTP5XX #Syslog #JSONParse #Network
//Identify the affected application hosts 

search "[CLIENT_IP]"
| extend StringaPulita = extract(@"(\{.*\})", 1, SyslogMessage)
| extend json_p = parse_json(StringaPulita)
| summarize Count=count() by apphost=tostring(json_p.apphost)
| order by Count desc
48. Quali URL stanno generando errori HTTP 5xx (ID: 32427)
  • Percorso: Rule031_statuscode5XX
  • Keywords: #HTTP5XX #Syslog #JSONParse #Network
//Identifying Which URLs Are Generating 5xx HTTP Errors 

search "[CLIENT_IP]"
| extend StringaPulita = extract(@"(\{.*\})", 1, SyslogMessage)
| extend json_p = parse_json(StringaPulita)
| where toint(json_p.status_code) between (500 .. 599)
| summarize Count=count() by url=tostring(json_p.url_path)
| order by Count desc
49. Estrazione e conversione del payload JSON da Syslog (ID: 32433)
  • Percorso: Rule031_statuscode5XX
  • Keywords: #HTTP5XX #Syslog #JSONParse #Network
//This query simply converts the raw JSON into readable columns. 

search "[CLIENT_IP]"
| extend StringaPulita = extract(@"(\{.*\})", 1, SyslogMessage)
| extend json_p = parse_json(StringaPulita)
| extend
    datetime_p = tostring(json_p.local_datetime),
    clientip_p = tostring(json_p.clientip),
    apphost_p = tostring(json_p.apphost),
    url_path_p = tostring(json_p.url_path),
    status_code_p = toint(json_p.status_code),
    username_p = tostring(json_p.username)
| project datetime_p, clientip_p, apphost_p, url_path_p, status_code_p, username_p
50. Quali Client IP generano errori HTTP 5xx sul portale (ID: 32434)
  • Percorso: Rule031_statuscode5XX
  • Keywords: #HTTP5XX #Syslog #JSONParse #Network
//Which IP clients generate 5xx errors on the portal? 

search "[APP_HOSTNAME]"
| extend StringaPulita = extract(@"(\{.*\})", 1, SyslogMessage)
| extend json_p = parse_json(StringaPulita)
| where toint(json_p.status_code) between (500 .. 599)
| summarize Count=count() by clientip=tostring(json_p.clientip)
| order by Count desc
51. Timeline completa delle richieste ed errori HTTP 5xx (ID: 32435)
  • Percorso: Rule031_statuscode5XX
  • Keywords: #HTTP5XX #Syslog #JSONParse #Network
//Complete Timeline. It is helpful for understanding how the service performed before, during, and after the malfunction.  

Syslog
| where SyslogMessage contains "[CLIENT_IP]"
| extend json_p = parse_json(
extract(@"(\{.*\})", 1, SyslogMessage)
)
| extend
Ora = coalesce(todatetime(json_p["datetime"]), TimeGenerated),
ClientIP = tostring(json_p["clientip"]),
AppHost = tostring(json_p["apphost"]),
Path = tostring(json_p["url_path"]),
Status = toint(json_p["status_code"]),
Username = tostring(json_p["username"])
| where ClientIP == "[CLIENT_IP]"
| where AppHost =~ "[APP_HOSTNAME]"
| where Path in (
"/api/jobs?page=1&pageSize=20",
"/api/notifications?page=1&pageSize=50",
"/api/notifications?unreadCount=true"
)
| where Status between (100 .. 599)
| summarize
Totale = count(),
HTTP200 = countif(Status == 200),
HTTP500 = countif(Status == 500),
HTTP503 = countif(Status == 503),
Errori5xx = countif(Status between (500 .. 599))
by bin(Ora, 1m), Path, Username
| order by Ora asc, Path asc, Username asc
52. Identificazione picchi di errore HTTP 5xx e impatto (ID: 32436)
  • Percorso: Rule031_statuscode5XX
  • Keywords: #HTTP5XX #Syslog #JSONParse #Network
//To quickly identify error spikes, determine which APIs or users are most affected, and quantify the impact of the errors.  

Syslog
| where SyslogMessage contains "[CLIENT_IP]"
| extend json_p = parse_json(
extract(@"(\{.*\})", 1, SyslogMessage)
)
| extend
Ora = coalesce(todatetime(json_p["datetime"]), TimeGenerated),
ClientIP = tostring(json_p["clientip"]),
AppHost = tostring(json_p["apphost"]),
Path = tostring(json_p["url_path"]),
Status = toint(json_p["status_code"]),
Username = tostring(json_p["username"])
| where ClientIP == "[CLIENT_IP]"
| where AppHost =~ "[APP_HOSTNAME]"
| where Path in (
"/api/jobs?page=1&pageSize=20",
"/api/notifications?page=1&pageSize=50",
"/api/notifications?unreadCount=true"
)
| where Status between (100 .. 599)
| summarize
Totale = count(),
HTTP200 = countif(Status == 200),
HTTP500 = countif(Status == 500),
HTTP503 = countif(Status == 503),
Errori5xx = countif(Status between (500 .. 599))
by bin(Ora, 1m), Path, Username
| where Errori5xx > 0
| extend Percentuale5xx = round(100.0 * Errori5xx / Totale, 2)
| order by Errori5xx desc, Ora asc

1.9 Modifica Permessi Caselle di Posta (Rule051_Mailbox Permission)

53. Dettaglio completo operazioni su Mailbox in OfficeActivity (ID: 32437)
  • Percorso: Rule051_Mailbox Permission
  • Keywords: #MailboxPermission #Exchange #CloudApps #Identity
//Full Event Details
OfficeActivity
| where UserId =~ "[GUEST_USER_UPN]"
| where Operation contains "Mailbox"
| project
    TimeGenerated,
    UserId,
    UserType,
    Operation,
    OfficeObjectId,
    ClientIP,
    Parameters,
    ResultStatus,
    ExternalAccess,
    OriginatingServer
| order by TimeGenerated asc
54. Dettagli operazione Add-MailboxPermission in CloudAppEvents (ID: 32438)
  • Percorso: Rule051_Mailbox Permission
  • Keywords: #MailboxPermission #Exchange #CloudApps #Identity
//CloudApps Details
CloudAppEvents
| where Timestamp between (datetime(2026-09-16 06:00:00) .. datetime(2026-09-16 09:00:00))
| where ActionType =~ "Add-MailboxPermission"
| where AccountId =~ "[ACTOR_ACCOUNT_UPN]"
    or tostring(RawEventData) contains "[ACTOR_ACCOUNT_NAME]"
| project
    Timestamp,
    ActionType,
    AccountDisplayName,
    AccountId,
    IPAddress,
    ObjectName,
    ObjectId,
    IsAdminOperation,
    RawEventData
| order by Timestamp asc
55. Attività eseguite dall'attore nell'intorno dell'evento (ID: 32439)
  • Percorso: Rule051_Mailbox Permission
  • Keywords: #MailboxPermission #Exchange #CloudApps #Identity
//What did the actor do around the time of the event?
CloudAppEvents
| where Timestamp between (datetime(2026-09-16 05:00:00) .. datetime(2026-09-16 10:00:00))
| where AccountId =~ "[ACTOR_ACCOUNT_UPN]"
    or tostring(RawEventData) contains "[ACTOR_ACCOUNT_UPN]"
| project
    Timestamp,
    ActionType,
    IPAddress,
    ObjectName,
    IsAdminOperation,
    RawEventData
| order by Timestamp asc
56. Storico modifiche effettuate sulla Mailbox target (ID: 32440)
  • Percorso: Rule051_Mailbox Permission
  • Keywords: #MailboxPermission #Exchange #CloudApps #Identity
//Changes made to targets
CloudAppEvents
| where Timestamp between (datetime(2026-09-15 00:00:00) .. datetime(2026-09-17 00:00:00))
| where ObjectName contains "[TARGET_MAILBOX_ID]"
    or ObjectId contains "[TARGET_MAILBOX_ID]"
    or tostring(RawEventData) contains "[TARGET_MAILBOX_ID]"
| project
    Timestamp,
    ActionType,
    AccountId,
    IPAddress,
    ObjectName,
    ObjectId,
    RawEventData
| order by Timestamp asc

1.10 Esecuzione PowerShell Remota Sospetta (Suspicious remote PowerShell execution)

57. Catena completa di esecuzione PowerShell e sessione remota (ID: 32441)
  • Percorso: Suspicious remote PowerShell execution
  • Keywords: #PowerShell #RDP #RemoteSession #Process
//Complete Chain
DeviceProcessEvents
| where DeviceName startswith "[DEVICE_NAME]"
| where FileName in~ (
    "powershell.exe",
    "cmd.exe",
    "Code.exe",
    "explorer.exe",
    "svchost.exe",
    "chcp.com"
)
| project
    Timestamp,
    DeviceName,
    AccountDomain,
    AccountName,
    FileName,
    ProcessCommandLine,
    ProcessId,
    InitiatingProcessFileName,
    InitiatingProcessCommandLine,
    InitiatingProcessId,
    InitiatingProcessParentFileName,
    IsProcessRemoteSession,
    ProcessRemoteSessionIP,
    ProcessRemoteSessionDeviceName,
    InitiatingProcessRemoteSessionIP,
    InitiatingProcessRemoteSessionDeviceName
| order by Timestamp asc
58. Esecuzione di processi in sessione remota o DcomLaunch (ID: 32442)
  • Percorso: Suspicious remote PowerShell execution
  • Keywords: #PowerShell #RDP #RemoteSession #Process
//Remote Process Execution
DeviceProcessEvents
| where DeviceName contains "[DEVICE_NAME]"
| where Timestamp > ago(1d)
| where FileName in~ ("cmd.exe", "powershell.exe", "explorer.exe")
| where
    IsProcessRemoteSession == true
    or isnotempty(ProcessRemoteSessionIP)
    or isnotempty(InitiatingProcessRemoteSessionIP)
    or InitiatingProcessCommandLine has "DcomLaunch"
| project
    Timestamp,
    DeviceName,
    AccountDomain,
    AccountName,
    FileName,
    ProcessCommandLine,
    InitiatingProcessFileName,
    InitiatingProcessCommandLine,
    ProcessRemoteSessionIP,
    ProcessRemoteSessionDeviceName,
    InitiatingProcessRemoteSessionIP,
    InitiatingProcessRemoteSessionDeviceName,
    LogonId
| order by Timestamp asc
59. Verifica accessi e connessioni RDP sull'host (ID: 32443)
  • Percorso: Suspicious remote PowerShell execution
  • Keywords: #PowerShell #RDP #RemoteSession #Process
//RDP connections
DeviceLogonEvents
| where DeviceName startswith "[DEVICE_NAME]"
| where AccountName =~ "[ACCOUNT_NAME]"
    or RemoteIP == "[SOURCE_IP]"
| project
    Timestamp,
    DeviceName,
    AccountDomain,
    AccountName,
    LogonType,
    ActionType,
    RemoteIP,
    RemoteDeviceName,
    Protocol,
    FailureReason
| order by Timestamp asc

1.11 Indagini su Connessioni RDP e Porte Aperte (Rule059 - RDP Connections)

60. Eventi di autenticazione sul dispositivo (DeviceLogonEvents) (ID: 32444)
  • Percorso: Rule059 - RDP Connections
  • Keywords: #RDP #Port3389 #OpenPorts #Logon #Network
//Device Logon Events
DeviceLogonEvents
| where DeviceName contains "[DEVICE_NAME]"
| sort by Timestamp
61. Connessioni e tentativi di accesso RDP su porta 3389 (ID: 32445)
  • Percorso: Rule059 - RDP Connections
  • Keywords: #RDP #Port3389 #OpenPorts #Logon #Network
//RDP Connection/ Attempts
DeviceNetworkEvents
| where LocalIP contains "[LOCAL_IP]"
| where LocalPort == 3389
62. Mappatura porte in ascolto (Listening Ports) sul dispositivo (ID: 32446)
  • Percorso: Rule059 - RDP Connections
  • Keywords: #RDP #Port3389 #OpenPorts #Logon #Network
//Determine which ports are open on the device
DeviceNetworkEvents
| where DeviceName contains "[DEVICE_NAME]"
| where ActionType == "ListeningConnectionCreated"
| summarize LastSeen=max(Timestamp)
    by LocalPort,
    Protocol,
    InitiatingProcessFileName
| order by LocalPort asc

1.12 Eseguibile di Sistema Rinominato e Avviato (System executable renamed and launched)

63. Dettagli completi sull'eseguibile di sistema rinominato (ID: 32451)
  • Percorso: System executable renamed and launched
  • Keywords: #RenamedExe #Masquerading #Process #Hash
// All file details
DeviceFileEvents
| where DeviceName contains "[DEVICE_NAME_1]" or DeviceName contains "[DEVICE_NAME_2]" 
| where FileName contains "[RENAMED_EXE_NAME].exe"
| project
    Timestamp,
    DeviceName,
    ActionType,
    FileName,
    FolderPath,
    FileSize,
    SHA1,
    SHA256,
    InitiatingProcessAccountName,
    InitiatingProcessFileName,
    InitiatingProcessCommandLine
| order by Timestamp asc
64. Analisi dell'esecuzione e riga di comando del file rinominato (ID: 32452)
  • Percorso: System executable renamed and launched
  • Keywords: #RenamedExe #Masquerading #Process #Hash
//How is the file executed?
DeviceProcessEvents
| where DeviceName contains "[DEVICE_NAME_1]" or DeviceName contains "[DEVICE_NAME_2]" 
| where FileName =~ "[RENAMED_EXE_NAME].exe"
    or ProcessCommandLine has "[RENAMED_EXE_NAME]"
| project
    Timestamp,
    DeviceName,
    AccountDomain,
    AccountName,
    FileName,
    FolderPath,
    SHA1,
    SHA256,
    ProcessCommandLine,
    InitiatingProcessFileName,
    InitiatingProcessCommandLine,
    InitiatingProcessParentFileName
| order by Timestamp asc
65. Confronto Hash tra il file rinominato e l'eseguibile originale (ID: 32453)
  • Percorso: System executable renamed and launched
  • Keywords: #RenamedExe #Masquerading #Process #Hash
//Compare the hash with the genuine powershell.exe file on the machine
DeviceProcessEvents
| where DeviceName contains "[DEVICE_NAME_1]"
| where FileName in~ ("powershell.exe", "[RENAMED_EXE_NAME].exe")
| summarize
    FirstSeen=min(Timestamp),
    LastSeen=max(Timestamp),
    Commands=make_set(ProcessCommandLine, 10)
    by FileName, SHA1, SHA256, FolderPath
66. Verifica diffusione dell'attività su altri host del tenant (ID: 32454)
  • Percorso: System executable renamed and launched
  • Keywords: #RenamedExe #Masquerading #Process #Hash
//Does this activity occur on multiple hosts?
DeviceProcessEvents
| where Timestamp > ago(30d)
| where ProcessCommandLine has @"D:\[TOOL_FOLDER_PATH]"
    or InitiatingProcessCommandLine has @"D:\[TOOL_FOLDER_PATH]"
| summarize
    Count=count(),
    Devices=make_set(DeviceName, 100),
    Accounts=make_set(AccountName, 100)
    by FileName, InitiatingProcessFileName
| order by Count desc

1.13 Modifiche ai Gruppi di Sicurezza AD (013 - User added or removed from groups)

67. 01 - Chi ha aggiunto o rimosso utenti dai gruppi di sicurezza? (ID: 32458)
  • Percorso: 013 - User added or removed from CERT groups
  • Keywords: #ADGroups #Event4728 #Event4729 #Identity
// To check who added you and to which CERT groups 
let CertGroups = dynamic([
"[SECURITY_GROUP_1]",
"[SECURITY_GROUP_2]",
"[SECURITY_GROUP_2]",
"[VDI_GROUP]",
"WDATP_ReadOnly",
"splunk_ess_analyst"
]);
SecurityEvent
| where EventID in (4728,4729)
| where TargetUserName in (CertGroups)
| extend Action =
case(
EventID == 4728, "Add member",
EventID == 4729, "Remove member",
"Other"
)
| project
TimeGenerated,
Action,
GroupName = TargetUserName,
MemberName,
PerformedBy = SubjectUserName,
Computer
| order by TimeGenerated desc
68. 02 - Tutti i gruppi AD modificati per uno specifico utente (ID: 32459)
  • Percorso: 013 - User added or removed from CERT groups
  • Keywords: #ADGroups #Event4728 #Event4729 #Identity
//To view all the groups to which the user has been added
SecurityEvent
| where EventID in (4728,4729)
| where MemberName contains "[USER_ACCOUNT_ID]"

1.14 Processi e Connessioni Azure Guest Agent (RDP Connections Azure Guest Agent)

69. Esecuzione processi di Azure Guest Agent sulle VM (ID: 32461)
  • Percorso: RDP Connections Azure Guest Agent
  • Keywords: #AzureGuestAgent #AzureIP #RDP #Network
// Esecuzione processi Azure Guest Agent e telemetria
DeviceProcessEvents
| where DeviceName has_any("[VM_NAME_1]", "[VM_NAME_2]")
| where FileName in~ ("WindowsAzureGuestAgent.exe", "WaAppAgent.exe", "CollectGuestLogs.exe", "WaSecAgentProv.exe")
| project Timestamp, DeviceName, ActionType, FileName, FolderPath, AccountName, ProcessCommandLine, SHA256, InitiatingProcessFileName
| sort by Timestamp desc
70. Connessioni di rete verso l'IP virtuale di Azure (168.63.129.16) (ID: 32462)
  • Percorso: RDP Connections Azure Guest Agent
  • Keywords: #AzureGuestAgent #AzureIP #RDP #Network
// Connessioni verso l'IP Virtuale di Azure (168.63.129.16)
DeviceNetworkEvents
| where RemoteIP == "168.63.129.16"
| where DeviceName has_any("[VM_NAME_1]", "[VM_NAME_2]")
| project Timestamp, DeviceName, ActionType, RemoteIP, RemotePort, InitiatingProcessFileName, InitiatingProcessAccountName, InitiatingProcessCommandLine
| sort by Timestamp desc

1.15 Query Schedulate e Root Condivisa (71 – 80)

71. Rilevamento massivo di file messi in quarantena su più host per Hash (ID: 32224)
  • Percorso: Regole Schedulate / Root
  • Keywords: #Quarantine #DefenderAV #Hash
DeviceEvents
| where ActionType == "AntivirusDetection" and isnotempty(SHA1) and TimeGenerated > ago(3h)
| extend ThreatName = tostring(parse_json(AdditionalFields)["ThreatName"])
| extend Action = tostring(parse_json(AdditionalFields)["Action"])
| extend Action = case(
Action == 2, "Quarantined",
Action == 3, "Removed",
Action == 0, "Detected",
Action)
| where Action == "Quarantined"
| extend DeviceId = "QuarantineCheck"
| summarize (Timestamp, ReportId) = arg_max(Timestamp, ReportId), AssetList = make_set(DeviceName), UniqueAssets = dcount(DeviceName) by DeviceId, FileName, ThreatName, SHA1
| where UniqueAssets >= 100
72. Rilevamento pattern JNDI di sfruttamento vulnerabilità Log4j (Regex) (ID: 32084)
  • Percorso: Regole Schedulate / Root
  • Keywords: #Log4j #Exploit #Process #CommandLine
DeviceProcessEvents 
| where ProcessCommandLine matches regex @'(?i)\$\{jndi:(ldap|http|https|ldaps|dns|rmi|iiop):\/\/(\$\{([a-z]){1,20}:([a-z]){1,20}\})?(([a-zA-Z0-9]|-){2,100})?(\.([a-zA-Z0-9]|-){2,100})?\.([a-zA-Z0-9]|-){2,100}\.([a-z0-9]){2,20}(\/).*}'     or InitiatingProcessCommandLine matches regex @'(?i)\$\{jndi:(ldap|http|https|ldaps|dns|rmi|iiop):\/\/(\$\{([a-z]){1,20}:([a-z]){1,20}\})?(([a-zA-Z0-9]|-){2,100})?(\.([a-zA-Z0-9]|-){2,100})?\.([a-zA-Z0-9]|-){2,100}\.([a-z0-9]){2,20}(\/).*}'
73. Monitoraggio connessioni verso IP sospetto segnalato (ID: 29)
  • Percorso: Regole Schedulate / Root
  • Keywords: #IP #Network #IOC
DeviceNetworkEvents 
| where RemoteIP == "[SUSPICIOUS_IP]"
74. Rilevamento spoolsv.exe che avvia rundll32.exe senza argomenti (PrintNightmare) (ID: 32070)
  • Percorso: Regole Schedulate / Root
  • Keywords: #Spoolsv #PrintNightmare #DLL #Process
DeviceProcessEvents
| where InitiatingProcessParentFileName has "spoolsv.exe"
| where InitiatingProcessFileName =~ "rundll32.exe"
| where isempty(InitiatingProcessCommandLine) or InitiatingProcessCommandLine endswith "rundll32.exe" //either commandline is empty or just "rundll32.exe"
| where FileName !in~ ("WerFault.exe")
75. Monitoraggio esecuzione PowerShell da processo non firmato (ID: 32074)
  • Percorso: Regole Schedulate / Root
  • Keywords: #PowerShell #CommandLine #LOLBin #Signature
DeviceProcessEvents 
| where FileName in~ ("powershell.exe", "powershell_ise.exe")
and ProcessCommandLine has_any ("-v","-version")
and InitiatingProcessSignatureStatus has_any ("Unknown", "Invalid")
and InitiatingProcessIntegrityLevel == "Medium"
76. Rilevamento esecuzione PowerShell offuscata o MSI remoto (Powershell_Isolation) (ID: 32226)
  • Percorso: Regole Schedulate / Root
  • Keywords: #PowerShell #CommandLine #LOLBin #Signature
DeviceProcessEvents
| where (FileName == "powershell.exe" 
and ((ProcessCommandLine contains "hidden" and ProcessCommandLine has_any("Invoke-Webrequest","New-Object System.Net.webClient") or
(ProcessCommandLine contains "Microsoft.VisualBasic" and ProcessCommandLine contains "DownloadString" and ProcessCommandLine contains "iex") or
(ProcessCommandLine startswith "\"Powershell.exe\" -eC") or
(ProcessCommandLine startswith "\"Powershell.exe\" -w Hidden -eC") or
(ProcessCommandLine contains "hidden" and ProcessCommandLine contains "FromBase64String" and ProcessCommandLine contains "iex"))) 
or (FileName has "msiexec" and ProcessCommandLine has "http" and ProcessCommandLine has_all("/fv","/q")))
77. Rilevamento esecuzione software di accesso remoto (RAT / RMM) (ID: 32358)
  • Percorso: Regole Schedulate / Root
  • Keywords: #RAT #Process #CommandLine
DeviceProcessEvents 
| where FileName has_any ("teamviewer", "anydesk", "rustdesk", "manageengine", "fastclient", 
    "logmein", "bomgar", "netviewer", "ultraviewer", "dwrcs", "splashtop", 
    "zerotier", "supremo")
| project 
    DeviceId,
    Timestamp, 
    DeviceName, 
    AccountUpn, 
    FileName, 
    FolderPath, 
    ProcessCommandLine, 
    InitiatingProcessFileName,
    InitiatingProcessCommandLine
| sort by Timestamp desc
78. Sospetto tentativo di sfruttamento vulnerabilità Log4j (ID: 32083)
  • Percorso: Regole Schedulate / Root
  • Keywords: #Log4j #Exploit #Process #CommandLine
DeviceProcessEvents
| where ProcessCommandLine has_all('${jndi') and ProcessCommandLine has_any('ldap', 'ldaps', 'http', 'rmi', 'dns', 'iiop') //Removing FPs 
| where not(ProcessCommandLine has_any('stackstorm', 'homebrew'))
79. Creazione e caricamento di DLL sospette nella cartella Spooler (ID: 32069)
  • Percorso: Regole Schedulate / Root
  • Keywords: #Spoolsv #PrintNightmare #DLL #Process
DeviceFileEvents
| where FolderPath contains @"\system32\spool\drivers\x64\3\"
| where FileName endswith ".dll"
| where ActionType in ("FileCreated", "FileRenamed")
| join kind=inner DeviceImageLoadEvents on DeviceId,DeviceName,FileName,InitiatingProcessFileName
| where Timestamp1 >= Timestamp and FolderPath1 contains @"\system32\spool\drivers\x64\3\Old"
80. Processi figli sospetti generati da spoolsv.exe — CVE-2021-1675 (ID: 32068)
  • Percorso: Regole Schedulate / Root
  • Keywords: #Spoolsv #PrintNightmare #DLL #Process
// Look for file load events for spoolsv
DeviceImageLoadEvents
| where Timestamp > ago(7d)
| where InitiatingProcessFileName =~ "spoolsv.exe"
| where FolderPath has @"spool\drivers"
| extend LoadFileTime = Timestamp
| distinct DeviceId, LoadFileTime, FileName, SHA256
// Join process data associated with spoolsv launching suspicious processes after image load
| join DeviceProcessEvents on $left.DeviceId == $right.DeviceId
| where Timestamp > ago(7d)
| where Timestamp < LoadFileTime +5m
| where InitiatingProcessFileName =~ "spoolsv.exe"
| where ProcessIntegrityLevel =~ 'SYSTEM'
| where (FileName1 in~("gpupdate.exe", "whoami.exe", "nltest.exe", "taskkill.exe",
            "wmic.exe", "taskmgr.exe", "sc.exe", "findstr.exe", "curl.exe", "wget.exe", "certutil.exe", "bitsadmin.exe", "accesschk.exe",
            "wevtutil.exe", "bcdedit.exe", "fsutil.exe", "cipher.exe", "schtasks.exe", "write.exe", "wuauclt.exe") or
// Processes with specific FPs removed          
(FileName1 =~ "net.exe" and ProcessCommandLine !has "start") or
(FileName1 =~ "cmd.exe" and not(ProcessCommandLine has_any(".spl", "route add", "program files"))) or
(FileName1 =~ "netsh.exe" and not(ProcessCommandLine has_any("add portopening", "rule name")))) or
(FileName1 =~ "powershell.exe" and ProcessCommandLine!has ".spl") or
(FileName1 =~ "rundll32.exe" and ProcessCommandLine != "" and ProcessCommandLine !contains " ")

SEZIONE 2: LE 42 QUERY DEL MANUALE SOC L1 MDE (Q01 – Q42)

2.1 Preparazione, Copertura, Alert e Timeline (Q01 – Q05)

Q01. Identificare il dispositivo e lo stato del sensore (File: 01_preparazione_e_copertura/Q01_identificare_il_dispositivo_e_lo_stato_del_sensore.kql)
  • Keywords: #DeviceInfo #SensorHealth
// Q01 | Identificare il dispositivo e lo stato del sensore
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE / multipiattaforma
// Parametri: Host: nome completo copiato dall’alert. Lookback: 7 giorni.
// Scopo: Prima di qualsiasi pivot: risolvere il nome in DeviceId e controllare quanto è recente il contesto disponibile.
// Limite: L’ultimo record disponibile non dimostra che il dispositivo sia online ora. Verificare eventuali ID uniti senza unire indiscriminatamente host omonimi.

let Host = "host.contoso.com";
DeviceInfo
| where Timestamp > ago(7d)
| where DeviceName =~ Host
| summarize arg_max(Timestamp, *) by DeviceId
| project LastDeviceInfo=Timestamp, DeviceId, DeviceName,
    OSPlatform, OSVersion, MachineGroup, OnboardingStatus,
    SensorHealthState, LoggedOnUsers,
    MergedDeviceIds, MergedToDeviceId
| order by LastDeviceInfo desc
Q02. Vedere gli ActionType realmente osservati (File: 01_preparazione_e_copertura/Q02_vedere_gli_actiontype_realmente_osservati.kql)
  • Keywords: #DeviceInfo #SensorHealth
// Q02 | Vedere gli ActionType realmente osservati
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE / multipiattaforma
// Parametri: D: DeviceId. Intervallo: 24 ore, estendibile solo se necessario.
// Scopo: Controllare la presenza degli eventi e recuperare un esempio di AdditionalFields prima di costruire filtri specifici.
// Limite: Gli ActionType osservati non sono il catalogo completo di quelli supportati. La prima o ultima riga di questa query non misura la latenza di ingestione.

let D = "INSERIRE_DEVICE_ID";
DeviceEvents
| where Timestamp > ago(24h)
| where DeviceId == D
| summarize Events=count(), LastSeen=max(Timestamp),
    SampleAdditionalFields=take_any(AdditionalFields)
    by ActionType
| order by Events desc
Q03. Partire da un AlertId (File: 02_alert_ed_evidenze/Q03_partire_da_un_alertid.kql)
  • Keywords: #IOC #AlertEvidence
// Q03 | Partire da un AlertId
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Alert XDR; disponibilità secondo servizi attivi
// Parametri: A: AlertId del portale, non IncidentId. Finestra di recupero: 30 giorni.
// Scopo: Unire la descrizione dell’alert alle entità correlate senza perdere le righe di evidenza.
// Limite: AlertInfo non espone qui una colonna universale IncidentId, Status o Classification. Stato del caso, incidente e azioni vanno verificati nel portale.

let A = "INSERIRE_ALERT_ID";
let Info = AlertInfo
| where Timestamp > ago(30d) and AlertId == A
| summarize arg_max(Timestamp, *) by AlertId
| project AlertId, AlertTime=Timestamp, Title, Severity,
    Category, ServiceSource, DetectionSource, AttackTechniques;
Info
| join kind=leftouter (
    AlertEvidence
    | where Timestamp > ago(30d) and AlertId == A
    | project AlertId, EvidenceTime=Timestamp, EntityType,
        EvidenceRole, EvidenceDirection, DeviceId, DeviceName,
        AccountUpn, AccountSid, FileName, FolderPath,
        SHA1, SHA256, RemoteIP, RemoteUrl, ProcessCommandLine
) on AlertId
| project-away AlertId1
| order by EvidenceTime asc
Q04. Cercare altri alert sullo stesso endpoint (File: 02_alert_ed_evidenze/Q04_cercare_altri_alert_sullo_stesso_endpoint.kql)
  • Keywords: #IOC #AlertEvidence
// Q04 | Cercare altri alert sullo stesso endpoint
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Alert XDR; disponibilità secondo servizi attivi
// Parametri: D: DeviceId. Finestra: 7 giorni.
// Scopo: Capire se il dispositivo presenta una sequenza di alert che richiede una valutazione congiunta.
// Limite: Nessun risultato significa nessun alert associato nei dati visibili, non assenza di compromissione.

let D = "INSERIRE_DEVICE_ID";
let Related = AlertEvidence
| where Timestamp > ago(7d) and DeviceId == D
| distinct AlertId;
Related
| join kind=inner (
    AlertInfo
    | where Timestamp > ago(7d)
    | summarize arg_max(Timestamp, *) by AlertId
) on AlertId
| project Timestamp, AlertId, Title, Severity,
    Category, ServiceSource, DetectionSource, AttackTechniques
| order by Timestamp asc
Q05. Ricostruire la sequenza sull’host (File: 03_timeline/Q05_ricostruire_la_sequenza_sullhost.kql)
  • Keywords: #Timeline #Process #Network
// Q05 | Ricostruire la sequenza sull’host
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. T0: ora dell’evento in UTC, da sostituire.
// Scopo: Allineare processi, rete, file, registro e accessi nello stesso intervallo UTC.
// Limite: Timeline selettiva: non include tutte le tabelle né tutti i campi. Su Linux/macOS rimuovere i rami non supportati; zero righe non dimostra assenza di attività.

let D = "INSERIRE_DEVICE_ID";
let T0 = datetime(2026-09-08T08:00:00Z);
let Start = T0 - 30m;
let End = T0 + 1h;
union
(DeviceProcessEvents
| where Timestamp between (Start .. End) and DeviceId == D
| project Timestamp, DeviceId, DeviceName, ReportId, ActionType,
    Source="Process", Actor=InitiatingProcessFileName,
    Detail=ProcessCommandLine, User=AccountName),
(DeviceNetworkEvents
| where Timestamp between (Start .. End) and DeviceId == D
| project Timestamp, DeviceId, DeviceName, ReportId, ActionType,
    Source="Network", Actor=InitiatingProcessFileName,
    Detail=strcat(RemoteIP, ":", RemotePort, " ", RemoteUrl),
    User=InitiatingProcessAccountName),
(DeviceFileEvents
| where Timestamp between (Start .. End) and DeviceId == D
| project Timestamp, DeviceId, DeviceName, ReportId, ActionType,
    Source="File", Actor=InitiatingProcessFileName,
    Detail=strcat(FolderPath, " | ", FileName),
    User=InitiatingProcessAccountName),
(DeviceRegistryEvents
| where Timestamp between (Start .. End) and DeviceId == D
| project Timestamp, DeviceId, DeviceName, ReportId, ActionType,
    Source="Registry", Actor=InitiatingProcessFileName,
    Detail=strcat(RegistryKey, " | ", RegistryValueData),
    User=InitiatingProcessAccountName),
(DeviceLogonEvents
| where Timestamp between (Start .. End) and DeviceId == D
| project Timestamp, DeviceId, DeviceName, ReportId, ActionType,
    Source="Logon", Actor=InitiatingProcessFileName,
    Detail=strcat(LogonType, " | ", RemoteIP), User=AccountName)
| order by Timestamp asc

2.2 Ricerca IOC, Diffusione e Correlazione Processi (Q06 – Q13)

Q06. Cercare uno o più indirizzi IP (File: 04_ricerca_ioc_e_diffusione/Q06_cercare_uno_o_piu_indirizzi_ip.kql)
  • Keywords: #IOC #IP #Network
// Q06 | Cercare uno o più indirizzi IP
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE / multipiattaforma
// Parametri: IPs: indirizzi reali da investigare, senza defanging. Finestra: 7 giorni.
// Scopo: Individuare endpoint e processi con eventi verso IP di interesse.
// Limite: Il confronto è testuale esatto: IPv6 può richiedere normalizzazione. Nessuna misura dei byte trasferiti o prova di esfiltrazione.

let IPs = dynamic(["203.0.113.10", "198.51.100.20"]);
DeviceNetworkEvents
| where Timestamp > ago(7d)
| where RemoteIP in (IPs)
| project Timestamp, DeviceId, DeviceName, ActionType,
    RemoteIP, RemotePort, RemoteUrl, LocalIP, Protocol,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessSHA1, InitiatingProcessAccountUpn,
    InitiatingProcessUniqueId, InitiatingProcessId,
    InitiatingProcessCreationTime, ReportId
| order by Timestamp asc
Q07. Cercare dominio e sottodomini senza falsi match (File: 04_ricerca_ioc_e_diffusione/Q07_cercare_dominio_e_sottodomini_senza_falsi_match.kql)
  • Keywords: #IOC #Domain #URL #Network
// Q07 | Cercare dominio e sottodomini senza falsi match
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE / multipiattaforma
// Parametri: DomainIOC: solo hostname, senza protocollo, percorso, wildcard o punto finale.
// Scopo: Confrontare l’host dell’URL, evitando corrispondenze come example.com.attacker.invalid.
// Limite: RemoteUrl può essere vuoto o contenere solo un FQDN. Non rappresenta una cronologia completa del browser o un log DNS completo; IDN e URL defanged vanno normalizzati.

let DomainIOC = tolower("example.invalid");
DeviceNetworkEvents
| where Timestamp > ago(7d)
| where isnotempty(RemoteUrl)
| extend U = iff(RemoteUrl contains "://",
    RemoteUrl, strcat("https://", RemoteUrl))
| extend Host = trim_end(@"\.$", tolower(tostring(parse_url(U).Host)))
| where Host == DomainIOC or Host endswith strcat(".", DomainIOC)
| project Timestamp, DeviceId, DeviceName, ActionType,
    Host, RemoteUrl, RemoteIP, RemotePort,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessUniqueId, InitiatingProcessAccountUpn, ReportId
| order by Timestamp asc
Q08. Cercare un hash tra file, processi e DLL (File: 04_ricerca_ioc_e_diffusione/Q08_cercare_un_hash_tra_file_processi_e_dll.kql)
  • Keywords: #IOC #Hash #SHA256 #DLL
// Q08 | Cercare un hash tra file, processi e DLL
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE; DLL principalmente Windows
// Parametri: H: hash. HashType: SHA1, SHA256 o MD5. Ricerca sull’intero perimetro visibile.
// Scopo: Distinguere presenza del file, creazione del processo e caricamento di un modulo.
// Limite: SHA256 può non essere popolato; non si converte SHA256 in SHA1. Per cercare l’eseguibile iniziatore, usare InitiatingProcessSHA1/SHA256 nelle tabelle pertinenti. Caricamenti e file non hanno copertura universale.

let H = "INSERIRE_HASH";
let HashType = "SHA1";
union withsource=SourceTable
    DeviceFileEvents, DeviceProcessEvents, DeviceImageLoadEvents
| where Timestamp > ago(7d)
| where (HashType == "SHA1" and SHA1 =~ H)
    or (HashType == "SHA256" and SHA256 =~ H)
    or (HashType == "MD5" and MD5 =~ H)
| project Timestamp, SourceTable, DeviceId, DeviceName,
    ActionType, FileName, FolderPath, SHA1, SHA256, MD5,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessAccountName, ReportId
| order by Timestamp asc
Q09. Misurare la diffusione di un eseguibile per hash (File: 04_ricerca_ioc_e_diffusione/Q09_misurare_la_diffusione_di_un_eseguibile_per_hash.kql)
  • Keywords: #IOC #Hash #SHA256
// Q09 | Misurare la diffusione di un eseguibile per hash
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE / multipiattaforma
// Parametri: H: SHA1 ottenuto da alert o ricerca precedente. Finestra: 7 giorni.
// Scopo: Contare gli endpoint che hanno avviato il file, con primi e ultimi avvistamenti nel periodo.
// Limite: FirstSeen vale solo per finestra e visibilità correnti. FileProfile arricchisce al massimo 1.000 righe; ProfileAvailability mancante o Error non equivale a file pulito.

let H = "INSERIRE_SHA1";
DeviceProcessEvents
| where Timestamp > ago(7d)
| where SHA1 =~ H and isnotempty(SHA1)
| summarize FirstSeen=min(Timestamp), LastSeen=max(Timestamp),
    Executions=count(), Names=make_set(FileName, 20),
    Paths=make_set(FolderPath, 20),
    Users=make_set(AccountName, 20),
    DeviceNames=make_set(DeviceName, 10)
    by SHA1, DeviceId
| order by FirstSeen asc
// Facoltativo: aggiungere in coda la riga seguente.
// | invoke FileProfile("SHA1", 1000)
Q10. Esaminare una precisa istanza di processo (File: 05_processi_e_correlazioni/Q10_esaminare_una_precisa_istanza_di_processo.kql)
  • Keywords: #Process #CommandLine
// Q10 | Esaminare una precisa istanza di processo
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D e P: DeviceId e ProcessUniqueId. Cercare la creazione fino a 30 giorni prima.
// Scopo: Recuperare eseguibile, account, command line e contesto del processo padre.
// Limite: ProcessUniqueId è preferibile quando presente, soprattutto su Windows. Se la creazione precede la retention, il risultato può mancare anche con eventi recenti di rete.

let D = "INSERIRE_DEVICE_ID";
let P = "INSERIRE_PROCESS_UNIQUE_ID";
DeviceProcessEvents
| where Timestamp > ago(30d)
| where DeviceId == D and ProcessUniqueId == P
| project Timestamp, DeviceId, DeviceName,
    FileName, FolderPath, SHA1, ProcessCommandLine,
    ProcessId, ProcessUniqueId, ProcessCreationTime,
    AccountDomain, AccountName, AccountSid, AccountUpn,
    ProcessIntegrityLevel, ProcessTokenElevation,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessUniqueId, InitiatingProcessCreationTime,
    ReportId
| order by Timestamp asc
Q11. Elencare i figli diretti di un processo (File: 05_processi_e_correlazioni/Q11_elencare_i_figli_diretti_di_un_processo.kql)
  • Keywords: #Process #CommandLine
// Q11 | Elencare i figli diretti di un processo
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Parent: ProcessUniqueId del processo padre.
// Scopo: Individuare cosa è stato avviato dall’istanza sospetta e selezionare il ramo successivo.
// Limite: Non è un albero ricorsivo completo. Se Parent è assente, ricorrere a DeviceId + PID del padre + ora di creazione, come nel principio di Q13.

let D = "INSERIRE_DEVICE_ID";
let Parent = "INSERIRE_PROCESS_UNIQUE_ID_PADRE";
DeviceProcessEvents
| where Timestamp > ago(7d)
| where DeviceId == D and InitiatingProcessUniqueId == Parent
| project Timestamp, DeviceId, DeviceName,
    InitiatingProcessFileName, InitiatingProcessUniqueId,
    FileName, FolderPath, ProcessCommandLine, SHA1,
    ProcessUniqueId, ProcessId, ProcessCreationTime,
    AccountName, AccountSid, ReportId
| order by Timestamp asc
Q12. Collegare rete, file e registro allo stesso processo (File: 05_processi_e_correlazioni/Q12_collegare_rete_file_e_registro_allo_stesso_processo.kql)
  • Keywords: #Process #Network #Registry
// Q12 | Collegare rete, file e registro allo stesso processo
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D e P: DeviceId e ProcessUniqueId del processo responsabile.
// Scopo: Attribuire eventi di più tabelle alla stessa istanza, mantenendo il tipo di evidenza.
// Limite: Non include automaticamente i figli del processo né eventi senza UniqueId. Per i figli ripetere Q11/Q12; per gli ID mancanti usare il fallback Q13.

let D = "INSERIRE_DEVICE_ID";
let P = "INSERIRE_PROCESS_UNIQUE_ID";
union
(DeviceNetworkEvents
| where Timestamp > ago(7d) and DeviceId == D
| where InitiatingProcessUniqueId == P
| project Timestamp, DeviceId, DeviceName, ReportId, ActionType,
    Source="Network",
    Detail=strcat(RemoteIP, ":", RemotePort, " ", RemoteUrl),
    InitiatingProcessFileName, InitiatingProcessCommandLine),
(DeviceFileEvents
| where Timestamp > ago(7d) and DeviceId == D
| where InitiatingProcessUniqueId == P
| project Timestamp, DeviceId, DeviceName, ReportId, ActionType,
    Source="File", Detail=strcat(FolderPath, " | ", FileName),
    InitiatingProcessFileName, InitiatingProcessCommandLine),
(DeviceRegistryEvents
| where Timestamp > ago(7d) and DeviceId == D
| where InitiatingProcessUniqueId == P
| project Timestamp, DeviceId, DeviceName, ReportId, ActionType,
    Source="Registry", Detail=strcat(RegistryKey,
        " | ", RegistryValueName, " = ", RegistryValueData),
    InitiatingProcessFileName, InitiatingProcessCommandLine)
| order by Timestamp asc
Q13. Fallback: correlare PID e ora di creazione (File: 05_processi_e_correlazioni/Q13_fallback_correlare_pid_e_ora_di_creazione.kql)
  • Keywords: #Process #Network
// Q13 | Fallback: correlare PID e ora di creazione
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE / multipiattaforma secondo campi disponibili
// Parametri: D: DeviceId. PID: numero. Created: ProcessCreationTime esatto in UTC.
// Scopo: Collegare rete e processi quando i UniqueId non sono disponibili, evitando il riutilizzo del PID.
// Limite: Non approssimare il timestamp a minuti e non fare join sul solo PID. Created è l’ora di creazione del processo, non Timestamp dell’evento di rete.

let D = "INSERIRE_DEVICE_ID";
let PID = 1234;
let Created = datetime(2026-09-08T08:00:00Z);
let Proc = DeviceProcessEvents
| where Timestamp > ago(30d) and DeviceId == D
| where ProcessId == PID and ProcessCreationTime == Created
| project DeviceId, PID=ProcessId, Created=ProcessCreationTime,
    Executable=FileName, ProcessCommandLine, SHA1
| distinct DeviceId, PID, Created, Executable, ProcessCommandLine, SHA1;
DeviceNetworkEvents
| where Timestamp > ago(7d) and DeviceId == D
| where InitiatingProcessId == PID
    and InitiatingProcessCreationTime == Created
| extend PID=InitiatingProcessId, Created=InitiatingProcessCreationTime
| join kind=leftouter Proc on DeviceId, PID, Created
| project Timestamp, DeviceId, DeviceName, ActionType,
    RemoteIP, RemotePort, RemoteUrl, Executable, ProcessCommandLine,
    InitiatingProcessCommandLine, SHA1, PID, Created, ReportId
| order by Timestamp asc

2.3 Esecuzione Sospetta, Download e Movimento Laterale (Q14 – Q22)

Q14. Office o lettore PDF che avvia interpreti e tool (File: 06_esecuzione_sospetta/Q14_office_o_lettore_pdf_che_avvia_interpreti_e_tool.kql)
  • Keywords: #Office #Phishing #Process #LOLBin
// Q14 | Office o lettore PDF che avvia interpreti e tool
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore. Lista di applicazioni adattabile.
// Scopo: Esaminare figli diretti insoliti di applicazioni comunemente usate per aprire documenti.
// Limite: Trova solo figli diretti e nomi elencati. Una catena con processi intermedi o binari rinominati può sfuggire.

let D = "INSERIRE_DEVICE_ID";
DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where InitiatingProcessFileName in~ (
    "winword.exe", "excel.exe", "powerpnt.exe", "onenote.exe",
    "outlook.exe", "acrord32.exe", "acrobat.exe")
| where FileName in~ ("cmd.exe", "powershell.exe", "pwsh.exe",
    "wscript.exe", "cscript.exe", "mshta.exe", "rundll32.exe",
    "regsvr32.exe", "certutil.exe", "curl.exe")
| project Timestamp, DeviceId, DeviceName, AccountName,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessUniqueId, FileName, ProcessCommandLine,
    FolderPath, SHA1, ProcessUniqueId, ReportId
| order by Timestamp asc
Q15. PowerShell con indicatori da approfondire (File: 06_esecuzione_sospetta/Q15_powershell_con_indicatori_da_approfondire.kql)
  • Keywords: #PowerShell #CommandLine #Process
// Q15 | PowerShell con indicatori da approfondire
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore.
// Scopo: Selezionare command line con codifica, download o esecuzione dinamica per una lettura contestuale.
// Limite: È una selezione euristica, non un rilevatore completo. DeviceProcessEvents non sostituisce lo script block logging e può non mostrare il contenuto di uno script eseguito da file.

let D = "INSERIRE_DEVICE_ID";
DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where FileName in~ ("powershell.exe", "pwsh.exe")
| where ProcessCommandLine has_any (
    "FromBase64String", "DownloadString", "DownloadFile",
    "EncodedCommand", "IEX")
    or ProcessCommandLine contains "-enc"
    or ProcessCommandLine contains "Invoke-WebRequest"
    or ProcessCommandLine contains "Invoke-Expression"
    or ProcessCommandLine contains "-w hidden"
| project Timestamp, DeviceId, DeviceName, AccountUpn,
    ProcessCommandLine, ProcessUniqueId, SHA1,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    ProcessTokenElevation, ReportId
| order by Timestamp asc
Q16. LOLBins con argomenti di interesse (File: 06_esecuzione_sospetta/Q16_lolbins_con_argomenti_di_interesse.kql)
  • Keywords: #LOLBin #CommandLine #Process
// Q16 | LOLBins con argomenti di interesse
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore. Filtri esemplificativi e da tarare.
// Scopo: Individuare alcuni usi potenzialmente anomali di strumenti Windows legittimi.
// Limite: Elenco parziale; non include tutti i LOLBins né tutte le sintassi o i nomi rinominati. Nessuna riga non esclude abuso di binari legittimi.

let D = "INSERIRE_DEVICE_ID";
DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where (FileName =~ "certutil.exe"
    and ProcessCommandLine has_any ("urlcache", "decode", "decodehex"))
    or (FileName =~ "bitsadmin.exe"
        and ProcessCommandLine contains "/transfer")
    or (FileName =~ "mshta.exe"
        and (ProcessCommandLine contains "http"
            or ProcessCommandLine contains "javascript:"))
    or (FileName =~ "regsvr32.exe"
        and ProcessCommandLine contains "scrobj.dll")
    or (FileName =~ "rundll32.exe"
        and ProcessCommandLine has_any ("comsvcs", "javascript"))
| project Timestamp, DeviceId, DeviceName, AccountName,
    FileName, FolderPath, ProcessCommandLine, ProcessUniqueId,
    InitiatingProcessFileName, InitiatingProcessCommandLine, ReportId
| order by Timestamp asc
Q17. Nomi di sistema in percorsi anomali e firma del file (File: 06_esecuzione_sospetta/Q17_nomi_di_sistema_in_percorsi_anomali_e_firma_del_file.kql)
  • Keywords: #Masquerading #RenamedExe #Signature #Process
// Q17 | Nomi di sistema in percorsi anomali e firma del file
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Processi: 24 ore; certificati: 30 giorni.
// Scopo: Esaminare eseguibili con nomi di sistema osservati in cartelle utente o temporanee.
// Limite: Questa query copre solo nomi e percorsi elencati. Anche una firma valida può accompagnare software abusato o malevolo.

let D = "INSERIRE_DEVICE_ID";
let Certs = DeviceFileCertificateInfo
| where Timestamp > ago(30d) and DeviceId == D
| where isnotempty(SHA1)
| summarize arg_max(Timestamp, IsSigned, IsTrusted, Signer)
    by DeviceId, SHA1
| project DeviceId, SHA1, IsSigned, IsTrusted, Signer;
DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where FileName in~ ("svchost.exe", "lsass.exe", "csrss.exe",
    "services.exe", "winlogon.exe", "smss.exe")
| where FolderPath contains @"\Users\"
    or FolderPath contains @"\Temp\"
| join kind=leftouter Certs on DeviceId, SHA1
| project Timestamp, DeviceId, DeviceName, FileName,
    FolderPath, SHA1, ProcessCommandLine, ProcessUniqueId,
    InitiatingProcessFileName, IsSigned, IsTrusted, Signer, ReportId
| order by Timestamp asc
Q18. Ricostruire origine e autore di un download (File: 07_download_e_file/Q18_ricostruire_origine_e_autore_di_un_download.kql)
  • Keywords: #Download #URL
// Q18 | Ricostruire origine e autore di un download
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE / multipiattaforma secondo telemetria
// Parametri: D: DeviceId. Finestra: 24 ore.
// Scopo: Trovare file con metadati di provenienza e il processo responsabile della scrittura.
// Limite: I campi FileOrigin* non sono sempre presenti. La loro assenza non esclude un download; questo elenco non comprende necessariamente tutti i file ricevuti.

let D = "INSERIRE_DEVICE_ID";
DeviceFileEvents
| where Timestamp > ago(24h) and DeviceId == D
| where isnotempty(FileOriginUrl) or isnotempty(FileOriginIP)
| project Timestamp, DeviceId, DeviceName, ActionType,
    FileName, FolderPath, SHA1, SHA256,
    FileOriginUrl, FileOriginReferrerUrl, FileOriginIP,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessUniqueId, InitiatingProcessAccountName, ReportId
| order by Timestamp asc
Q19. File scaricato e processo con lo stesso hash (File: 07_download_e_file/Q19_file_scaricato_e_processo_con_lo_stesso_hash.kql)
  • Keywords: #Download #Hash #SHA256 #Process
// Q19 | File scaricato e processo con lo stesso hash
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore. Join su SHA1 non vuoto.
// Scopo: Cercare esecuzioni entro un’ora dalla creazione di un file con origine Internet nota.
// Limite: Non prova che sia stata eseguita proprio quella copia del file; più download/esecuzioni possono creare più corrispondenze. Non copre script interpretati tramite file, contenuti in memoria, hash assenti o esecuzioni oltre un’ora.

let D = "INSERIRE_DEVICE_ID";
let Downloads = DeviceFileEvents
| where Timestamp > ago(24h) and DeviceId == D
| where ActionType == "FileCreated"
| where isnotempty(FileOriginUrl) and isnotempty(SHA1)
| project DeviceId, SHA1, FileTime=Timestamp,
    DownloadName=FileName, DownloadPath=FolderPath, FileOriginUrl;
Downloads
| join kind=inner (
    DeviceProcessEvents
    | where Timestamp > ago(24h) and DeviceId == D
    | where isnotempty(SHA1)
    | project DeviceId, SHA1, RunTime=Timestamp, DeviceName,
        FileName, FolderPath, ProcessCommandLine,
        ProcessUniqueId, AccountName, ReportId
) on DeviceId, SHA1
| where RunTime between (FileTime .. FileTime + 1h)
| project FileTime, RunTime, DeviceId, DeviceName,
    DownloadName, DownloadPath, FileOriginUrl, FileName,
    FolderPath, SHA1, ProcessCommandLine, ProcessUniqueId,
    AccountName, ReportId
| order by RunTime asc
Q20. Rete pubblica da interpreti o su porte da verificare (File: 08_rete_e_movimento_laterale/Q20_rete_pubblica_da_interpreti_o_su_porte_da_verificare.kql)
  • Keywords: #Network #IP #LOLBin
// Q20 | Rete pubblica da interpreti o su porte da verificare
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE / multipiattaforma; lista processi Windows
// Parametri: D: DeviceId. Finestra: 24 ore. Porte 80/443 escluse solo per processi non elencati.
// Scopo: Ridurre gli eventi di rete dell’endpoint a un insieme utile per il triage manuale.
// Limite: RemoteIPType può essere vuoto e il proxy può nascondere la destinazione. Non è una query completa per C2; traffico malevolo può usare 443 e processi comuni.

let D = "INSERIRE_DEVICE_ID";
DeviceNetworkEvents
| where Timestamp > ago(24h) and DeviceId == D
| where RemoteIPType == "Public"
| where RemotePort !in (80, 443)
    or InitiatingProcessFileName in~ ("powershell.exe", "pwsh.exe",
        "cmd.exe", "wscript.exe", "cscript.exe", "mshta.exe",
        "rundll32.exe", "certutil.exe", "curl.exe")
| project Timestamp, DeviceId, DeviceName, ActionType,
    RemoteIP, RemotePort, RemoteUrl, Protocol,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessUniqueId, InitiatingProcessAccountName, ReportId
| order by Timestamp asc
Q21. Contatti ripetuti nel tempo: candidati da ispezionare (File: 08_rete_e_movimento_laterale/Q21_contatti_ripetuti_nel_tempo_candidati_da_ispezionare.kql)
  • Keywords: #Beaconing #C2 #Network
// Q21 | Contatti ripetuti nel tempo: candidati da ispezionare
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Soglie iniziali: 12 finestre da 5 minuti, almeno 30 eventi.
// Scopo: Trovare una stessa istanza di processo che contatta ripetutamente la stessa destinazione.
// Limite: È un filtro per attività ripetuta, non una detection di beaconing. Soglie dimostrative; esclude UniqueId vuoti e non misura byte o contenuto.

let D = "INSERIRE_DEVICE_ID";
DeviceNetworkEvents
| where Timestamp > ago(24h) and DeviceId == D
| where ActionType == "ConnectionSuccess" and RemoteIPType == "Public"
| where isnotempty(InitiatingProcessUniqueId)
| summarize InBin=count(), BinFirst=min(Timestamp),
    BinLast=max(Timestamp)
    by DeviceId, DeviceName, InitiatingProcessUniqueId,
    InitiatingProcessFileName, RemoteIP, RemotePort,
    Slot=bin(Timestamp, 5m)
| summarize ActiveBins=count(), Connections=sum(InBin),
    FirstSeen=min(BinFirst), LastSeen=max(BinLast)
    by DeviceId, DeviceName, InitiatingProcessUniqueId,
    InitiatingProcessFileName, RemoteIP, RemotePort
| where ActiveBins >= 12 and Connections >= 30
| order by ActiveBins desc, Connections desc
Q22. Un processo raggiunge molte destinazioni amministrative (File: 08_rete_e_movimento_laterale/Q22_un_processo_raggiunge_molte_destinazioni_amministrative.kql)
  • Keywords: #Network #RDP #OpenPorts
// Q22 | Un processo raggiunge molte destinazioni amministrative
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: endpoint sorgente. Soglia di partenza: 10 IP distinti stimati in 15 minuti.
// Scopo: Individuare possibile scansione o espansione su SMB, RDP e WinRM.
// Limite: Porta 445/3389/5985 da sola non prova movimento laterale. Soglia e finestre possono perdere attività lenta o a cavallo dei bin; verificare i timestamp di creazione non vuoti.

let D = "INSERIRE_DEVICE_ID";
DeviceNetworkEvents
| where Timestamp > ago(24h) and DeviceId == D
| where RemotePort in (445, 3389, 5985, 5986)
| where isnotempty(RemoteIP)
| summarize TargetEstimate=dcount(RemoteIP), Events=count(),
    Targets=make_set(RemoteIP, 50), Actions=make_set(ActionType, 10)
    by DeviceId, DeviceName, InitiatingProcessId,
    InitiatingProcessCreationTime, InitiatingProcessFileName,
    InitiatingProcessCommandLine, RemotePort, Slot=bin(Timestamp, 15m)
| where TargetEstimate >= 10
| order by TargetEstimate desc

2.4 Accessi, Persistenza e Credenziali (Q23 – Q30)

Q23. Leggere gli accessi sull’endpoint (File: 09_accessi_e_account/Q23_leggere_gli_accessi_sullendpoint.kql)
  • Keywords: #Identity #Logon
// Q23 | Leggere gli accessi sull’endpoint
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore.
// Scopo: Ricostruire account, tipo di logon, esito e origine osservata.
// Limite: Non è il registro completo di tutte le autenticazioni cloud. LogonId è contestuale al dispositivo e al riavvio; AccountName da solo non identifica univocamente un utente.

let D = "INSERIRE_DEVICE_ID";
DeviceLogonEvents
| where Timestamp > ago(24h) and DeviceId == D
| project Timestamp, DeviceId, DeviceName, ActionType,
    LogonType, AccountDomain, AccountName, AccountSid,
    RemoteIP, RemoteDeviceName, Protocol, FailureReason,
    LogonId, IsLocalAdmin, InitiatingProcessFileName,
    InitiatingProcessCommandLine, ReportId
| order by Timestamp asc
Q24. Fallimenti seguiti da un accesso riuscito (File: 09_accessi_e_account/Q24_fallimenti_seguiti_da_un_accesso_riuscito.kql)
  • Keywords: #BruteForce #Identity #Logon
// Q24 | Fallimenti seguiti da un accesso riuscito
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore. Soglia proposta da tarare.
// Scopo: Trovare almeno 5 fallimenti nei 15 minuti precedenti un successo, dallo stesso IP sullo stesso host e account.
// Limite: Una correlazione non prova brute force riuscito. Non copre password spraying distribuito o cambio IP; il join può crescere molto su host di autenticazione.

let D = "INSERIRE_DEVICE_ID";
let L = materialize(DeviceLogonEvents
| where Timestamp > ago(24h) and DeviceId == D
| where isnotempty(AccountName) and isnotempty(RemoteIP)
| project Timestamp, DeviceId, DeviceName, AccountDomain,
    AccountName, RemoteIP, LogonType, ActionType, ReportId);
L
| where ActionType == "LogonSuccess"
| project DeviceId, DeviceName, AccountDomain, AccountName,
    RemoteIP, LogonType, SuccessTime=Timestamp, SuccessReportId=ReportId
| join kind=inner (
    L
    | where ActionType == "LogonFailed"
    | project DeviceId, AccountDomain, AccountName, RemoteIP,
        LogonType, FailTime=Timestamp
) on DeviceId, AccountDomain, AccountName, RemoteIP, LogonType
| where FailTime between (SuccessTime - 15m .. SuccessTime)
| summarize Failures=count(), FirstFail=min(FailTime),
    LastFail=max(FailTime)
    by DeviceId, DeviceName, AccountDomain, AccountName, RemoteIP,
    LogonType, SuccessTime, SuccessReportId
| where Failures >= 5
| order by SuccessTime desc
Q25. Seguire un account sui dispositivi (File: 09_accessi_e_account/Q25_seguire_un_account_sui_dispositivi.kql)
  • Keywords: #Identity #Logon
// Q25 | Seguire un account sui dispositivi
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE; SID soprattutto Windows
// Parametri: Sid: SID esatto recuperato dalle evidenze. Finestra: 24 ore.
// Scopo: Individuare dove un account identificato da SID ha avviato processi nel periodo.
// Limite: Escludere SID ben noti come SYSTEM dalla lettura come identità personale. Dati mancanti o cambio di identità tra sessioni possono interrompere la ricostruzione.

let Sid = "INSERIRE_ACCOUNT_SID";
DeviceProcessEvents
| where Timestamp > ago(24h)
| where AccountSid == Sid
| summarize FirstSeen=min(Timestamp), LastSeen=max(Timestamp),
    ProcessEvents=count(), Names=make_set(FileName, 30),
    Accounts=make_set(strcat(AccountDomain, "\\", AccountName), 10),
    DeviceNames=make_set(DeviceName, 10)
    by DeviceId
| order by FirstSeen asc
Q26. Processi creati in una sessione RDP (File: 09_accessi_e_account/Q26_processi_creati_in_una_sessione_rdp.kql)
  • Keywords: #RDP #Port3389 #Process
// Q26 | Processi creati in una sessione RDP
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: endpoint destinazione della sessione. Finestra: 24 ore.
// Scopo: Verificare cosa è stato eseguito durante sessioni desktop remote osservate dal sensore.
// Limite: Campi dipendenti da piattaforma e sensore. Non comprende ogni tecnologia di accesso remoto e non sostituisce i log del gateway RDP.

let D = "INSERIRE_DEVICE_ID";
DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where IsProcessRemoteSession == true
| project Timestamp, DeviceId, DeviceName, AccountName,
    AccountSid, ProcessRemoteSessionIP, ProcessRemoteSessionDeviceName,
    CreatedProcessSessionId, FileName, ProcessCommandLine,
    ProcessUniqueId, InitiatingProcessFileName, ReportId
| order by Timestamp asc
Q27. Modifiche alle chiavi Run e RunOnce (File: 10_persistenza/Q27_modifiche_alle_chiavi_run_e_runonce.kql)
  • Keywords: #Registry #Persistence
// Q27 | Modifiche alle chiavi Run e RunOnce
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 7 giorni. Confrontare valore nuovo e precedente.
// Scopo: Esaminare valori che possono avviare programmi all’accesso dell’utente.
// Limite: Una modifica non prova che il comando sia già stato eseguito. Run/RunOnce sono solo due meccanismi di persistenza e l’evento non garantisce il valore attuale.

let D = "INSERIRE_DEVICE_ID";
DeviceRegistryEvents
| where Timestamp > ago(7d) and DeviceId == D
| where RegistryKey endswith @"\CurrentVersion\Run"
    or RegistryKey endswith @"\CurrentVersion\RunOnce"
| project Timestamp, DeviceId, DeviceName, ActionType,
    RegistryKey, RegistryValueName, RegistryValueData,
    PreviousRegistryValueData, InitiatingProcessFileName,
    InitiatingProcessCommandLine, InitiatingProcessUniqueId,
    InitiatingProcessAccountName, ReportId
| order by Timestamp asc
Q28. Comandi per task, servizi e sottoscrizioni WMI (File: 10_persistenza/Q28_comandi_per_task_servizi_e_sottoscrizioni_wmi.kql)
  • Keywords: #Process #CommandLine #Persistence
// Q28 | Comandi per task, servizi e sottoscrizioni WMI
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 7 giorni.
// Scopo: Individuare tentativi di configurare meccanismi di esecuzione persistente.
// Limite: La creazione di un processo con questi argomenti non dimostra che il task, servizio o WMI sia stato creato con successo. API dirette e script da file possono sfuggire.

let D = "INSERIRE_DEVICE_ID";
DeviceProcessEvents
| where Timestamp > ago(7d) and DeviceId == D
| where (FileName =~ "schtasks.exe"
    and (ProcessCommandLine contains "/create"
        or ProcessCommandLine contains "/change"))
    or (FileName =~ "sc.exe"
        and ProcessCommandLine has_any ("create", "config"))
    or (FileName in~ ("powershell.exe", "pwsh.exe", "wmic.exe")
        and (ProcessCommandLine contains "Register-ScheduledTask"
            or ProcessCommandLine contains "New-Service"
            or ProcessCommandLine contains "__EventFilter"
            or ProcessCommandLine contains "CommandLineEventConsumer"))
| project Timestamp, DeviceId, DeviceName, FileName,
    ProcessCommandLine, ProcessUniqueId, AccountName,
    InitiatingProcessFileName, InitiatingProcessCommandLine, ReportId
| order by Timestamp asc
Q29. Eventi di task, servizi e WMI con dettagli estesi (File: 10_persistenza/Q29_eventi_di_task_servizi_e_wmi_con_dettagli_estesi.kql)
  • Keywords: #Persistence #Process
// Q29 | Eventi di task, servizi e WMI con dettagli estesi
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 7 giorni. Affinare gli ActionType dopo Q02.
// Scopo: Consultare gli eventi specializzati disponibili e i loro AdditionalFields senza assumere chiavi JSON universali.
// Limite: I nomi e la disponibilità variano in base alla funzione e alla piattaforma. Le chiavi JSON possono cambiare tra ActionType; non interpretare un campo mancante come valore negativo.

let D = "INSERIRE_DEVICE_ID";
DeviceEvents
| where Timestamp > ago(7d) and DeviceId == D
| where ActionType contains "ScheduledTask"
    or ActionType contains "Service"
    or ActionType contains "Wmi"
| extend Details=parse_json(AdditionalFields)
| project Timestamp, DeviceId, DeviceName, ActionType,
    FileName, FolderPath, InitiatingProcessFileName,
    InitiatingProcessCommandLine, InitiatingProcessUniqueId,
    InitiatingProcessAccountName, Details, ReportId
| order by Timestamp asc
Q30. Indicatori di dump di memoria e accesso agli hive (File: 11_accesso_alle_credenziali/Q30_indicatori_di_dump_di_memoria_e_accesso_agli_hive.kql)
  • Keywords: #Process #CommandLine #Identity
// Q30 | Indicatori di dump di memoria e accesso agli hive
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore.
// Scopo: Esaminare processi con riferimenti a LSASS, strumenti di dump o salvataggio di hive sensibili.
// Limite: Questa query non osserva direttamente ogni accesso alla memoria o il contenuto del dump. Tecniche in memoria, API dirette e nomi rinominati possono non comparire.

let D = "INSERIRE_DEVICE_ID";
DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where ProcessCommandLine contains "lsass"
    or FileName in~ ("procdump.exe", "procdump64.exe")
    or (FileName =~ "rundll32.exe"
        and ProcessCommandLine contains "comsvcs"
        and ProcessCommandLine contains "MiniDump")
    or (FileName =~ "reg.exe" and ProcessCommandLine has "save"
        and (ProcessCommandLine contains @"HKLM\SAM"
            or ProcessCommandLine contains @"HKLM\SECURITY"
            or ProcessCommandLine contains @"HKLM\SYSTEM"))
| project Timestamp, DeviceId, DeviceName, AccountName,
    FileName, ProcessCommandLine, ProcessUniqueId,
    ProcessTokenElevation, InitiatingProcessFileName,
    InitiatingProcessCommandLine, ReportId
| order by Timestamp asc

2.5 Protezioni, Ransomware, Esfiltrazione, Moduli e XDR (Q31 – Q42)

Q31. Antivirus, ASR, tampering e controlli di rete (File: 12_protezioni_e_ransomware/Q31_antivirus_asr_tampering_e_controlli_di_rete.kql)
  • Keywords: #DefenderAV #ASR #Tampering #Quarantine
// Q31 | Antivirus, ASR, tampering e controlli di rete
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore. Confermare il significato degli ActionType nel portale.
// Scopo: Leggere gli eventi delle protezioni e distinguere rilevazione, audit, blocco e azioni successive.
// Limite: L’elenco non prova lo stato attuale di ogni protezione o l’esito completo della remediation. Alcuni controlli richiedono specifiche configurazioni.

let D = "INSERIRE_DEVICE_ID";
DeviceEvents
| where Timestamp > ago(24h) and DeviceId == D
| where ActionType contains "Antivirus"
    or ActionType startswith "Asr"
    or ActionType contains "Tamper"
    or ActionType contains "NetworkProtection"
    or ActionType contains "ControlledFolderAccess"
| extend Details=parse_json(AdditionalFields)
| project Timestamp, DeviceId, DeviceName, ActionType,
    FileName, FolderPath, SHA1, RemoteIP, RemoteUrl,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessUniqueId, Details, ReportId
| order by Timestamp asc
Q32. Comandi che ostacolano ripristino o cancellano log (File: 12_protezioni_e_ransomware/Q32_comandi_che_ostacolano_ripristino_o_cancellano_log.kql)
  • Keywords: #Ransomware #LogCleared #Wevtutil
// Q32 | Comandi che ostacolano ripristino o cancellano log
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore.
// Scopo: Selezionare processi con argomenti compatibili con eliminazione di copie di recupero o log.
// Limite: L’avvio del comando non dimostra il successo dell’operazione; i filtri non coprono ogni tecnica né cancellazioni tramite API.

let D = "INSERIRE_DEVICE_ID";
DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where (FileName =~ "vssadmin.exe"
    and ProcessCommandLine has_all ("delete", "shadows"))
    or (FileName =~ "wmic.exe"
        and ProcessCommandLine has_all ("shadowcopy", "delete"))
    or (FileName =~ "wbadmin.exe"
        and ProcessCommandLine has "delete")
    or (FileName =~ "bcdedit.exe"
        and (ProcessCommandLine has_all ("recoveryenabled", "no")
            or ProcessCommandLine has "ignoreallfailures"))
    or (FileName =~ "wevtutil.exe"
        and (ProcessCommandLine has "cl"
            or ProcessCommandLine contains "clear-log"))
| project Timestamp, DeviceId, DeviceName, AccountName,
    FileName, ProcessCommandLine, ProcessUniqueId,
    InitiatingProcessFileName, ProcessTokenElevation, ReportId
| order by Timestamp asc
Q33. Modifiche o rinomine massive di file (File: 12_protezioni_e_ransomware/Q33_modifiche_o_rinomine_massive_di_file.kql)
  • Keywords: #Ransomware #Exfiltration
// Q33 | Modifiche o rinomine massive di file
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Soglia iniziale: 100 eventi in 5 minuti.
// Scopo: Trovare istanze di processo che producono molte operazioni sui file in poco tempo.
// Limite: Le operazioni riportate non equivalgono a tutte le scritture del filesystem. Volume elevato non prova cifratura; volume basso non esclude ransomware. Soglie da tarare per ruolo host.

let D = "INSERIRE_DEVICE_ID";
DeviceFileEvents
| where Timestamp > ago(24h) and DeviceId == D
| where ActionType in ("FileModified", "FileRenamed")
| summarize Events=count(), FileEstimate=dcount(
        strcat(FolderPath, "|", FileName)),
    Names=make_set(FileName, 15), Paths=make_set(FolderPath, 10)
    by DeviceId, DeviceName, InitiatingProcessId,
    InitiatingProcessCreationTime, InitiatingProcessFileName,
    InitiatingProcessCommandLine, Slot=bin(Timestamp, 5m)
| where Events >= 100
| order by Events desc
Q34. Archiviazione, trasferimento e client cloud (File: 13_raccolta_dati_e_supporti_rimovibili/Q34_archiviazione_trasferimento_e_client_cloud.kql)
  • Keywords: #Exfiltration #Archive #CloudApps
// Q34 | Archiviazione, trasferimento e client cloud
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore. Lista da adattare agli strumenti aziendali.
// Scopo: Esaminare strumenti che possono comprimere o trasferire dati dopo un’attività sospetta.
// Limite: Un client cloud avviato o una connessione riuscita non prova esfiltrazione. DeviceNetworkEvents non offre contatori universali di byte inviati/ricevuti.

let D = "INSERIRE_DEVICE_ID";
DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where FileName in~ ("7z.exe", "7za.exe", "rar.exe",
    "winrar.exe", "rclone.exe", "winscp.exe", "winscp.com",
    "curl.exe", "scp.exe", "sftp.exe", "tar.exe")
    or (FileName in~ ("powershell.exe", "pwsh.exe")
        and ProcessCommandLine contains "Compress-Archive")
| project Timestamp, DeviceId, DeviceName, FileName,
    FolderPath, ProcessCommandLine, ProcessUniqueId,
    AccountName, SHA1, InitiatingProcessFileName, ReportId
| order by Timestamp asc
Q35. USB e supporti rimovibili: contesto del dispositivo (File: 13_raccolta_dati_e_supporti_rimovibili/Q35_usb_e_supporti_rimovibili_contesto_del_dispositivo.kql)
  • Keywords: #USB #RemovableDrive #UsbMounted
// Q35 | USB e supporti rimovibili: contesto del dispositivo
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore. Il filtro è volutamente esplorativo.
// Scopo: Vedere gli eventi relativi a supporti rimovibili e raccogliere i dettagli esposti dal tenant.
// Limite: Inserimento o mount non dimostrano copia di file. Il sensore non fornisce necessariamente un audit completo delle operazioni sul supporto; le policy possono cambiare la copertura.

let D = "INSERIRE_DEVICE_ID";
DeviceEvents
| where Timestamp > ago(24h) and DeviceId == D
| where ActionType contains "Usb" or ActionType contains "Removable"
| extend Details=parse_json(AdditionalFields)
| project Timestamp, DeviceId, DeviceName, ActionType,
    InitiatingProcessFileName, InitiatingProcessCommandLine,
    InitiatingProcessAccountName, Details, ReportId
| order by Timestamp asc
Q36. DLL caricate da cartelle utente o temporanee (File: 14_moduli_e_sistemi_non_windows/Q36_dll_caricate_da_cartelle_utente_o_temporanee.kql)
  • Keywords: #DLL #Process
// Q36 | DLL caricate da cartelle utente o temporanee
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Windows / MDE
// Parametri: D: DeviceId. Finestra: 24 ore.
// Scopo: Esaminare moduli in percorsi da verificare e il processo che li carica.
// Limite: È un filtro per candidati, non prova di DLL side-loading. La telemetria dei caricamenti non è un inventario completo di tutti i moduli.

let D = "INSERIRE_DEVICE_ID";
DeviceImageLoadEvents
| where Timestamp > ago(24h) and DeviceId == D
| where FolderPath contains @"\Users\"
    or FolderPath contains @"\Temp\"
| project Timestamp, DeviceId, DeviceName, ActionType,
    FileName, FolderPath, SHA1, SHA256,
    InitiatingProcessFileName, InitiatingProcessFolderPath,
    InitiatingProcessCommandLine, InitiatingProcessUniqueId,
    InitiatingProcessAccountName, ReportId
| order by Timestamp asc
Q37. Linux e macOS: interpreti e punti di avvio (File: 14_moduli_e_sistemi_non_windows/Q37_linux_e_macos_interpreti_e_punti_di_avvio.kql)
  • Keywords: #Process #CommandLine
// Q37 | Linux e macOS: interpreti e punti di avvio
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: MDE su Linux / macOS; verificare copertura
// Parametri: D: DeviceId Linux/macOS confermato con Q01. Finestra: 24 ore.
// Scopo: Un primo passaggio su shell, download da riga di comando e modifiche a percorsi comunemente usati per avvio o accesso.
// Limite: Copertura indicativa e parziale: supporto, versione sensore e configurazione cambiano per OS. Non applicare automaticamente assunzioni Windows, registro o DLL a questi dispositivi.

let D = "INSERIRE_DEVICE_ID";
union
(DeviceProcessEvents
| where Timestamp > ago(24h) and DeviceId == D
| where FileName in ("curl", "wget", "crontab", "launchctl", "systemctl")
    or (FileName in ("bash", "sh", "zsh", "python", "python3")
        and ProcessCommandLine has_any (
            "curl", "wget", "base64", "chmod", "crontab", "launchctl"))
| project Timestamp, DeviceId, DeviceName, ActionType, ReportId,
    Source="Process", FileName, FolderPath,
    Detail=ProcessCommandLine, Actor=InitiatingProcessFileName),
(DeviceFileEvents
| where Timestamp > ago(24h) and DeviceId == D
| where FolderPath startswith "/etc/cron"
    or FolderPath contains "/.config/autostart/"
    or FolderPath contains "/LaunchAgents"
    or FolderPath contains "/LaunchDaemons"
    or (FolderPath contains "/.ssh" and FileName == "authorized_keys")
| project Timestamp, DeviceId, DeviceName, ActionType, ReportId,
    Source="File", FileName, FolderPath,
    Detail=InitiatingProcessCommandLine, Actor=InitiatingProcessFileName)
| order by Timestamp asc
Q38. Contestualizzare l’host con le vulnerabilità note (File: 15_vulnerabilita_e_inventario/Q38_contestualizzare_lhost_con_le_vulnerabilita_note.kql)
  • Keywords: #TVM #Vulnerability #CVE
// Q38 | Contestualizzare l’host con le vulnerabilità note
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Defender Vulnerability Management / dati TVM disponibili
// Parametri: D: DeviceId. Tabelle TVM disponibili e autorizzate. Query su stato corrente, senza Timestamp.
// Scopo: Aggiungere al triage le vulnerabilità High/Critical visibili e l’eventuale disponibilità pubblica di exploit.
// Limite: Queste tabelle non hanno Timestamp degli eventi e non ricostruiscono automaticamente lo stato storico all’ora dell’incidente. Non aggiungere where Timestamp > ago(...).

let D = "INSERIRE_DEVICE_ID";
DeviceTvmSoftwareVulnerabilities
| where DeviceId == D
| where VulnerabilitySeverityLevel in~ ("High", "Critical")
| join kind=leftouter (
    DeviceTvmSoftwareVulnerabilitiesKB
    | project CveId, Cvss=todouble(CvssScore), IsExploitAvailable
) on CveId
| project DeviceId, DeviceName, SoftwareVendor, SoftwareName,
    SoftwareVersion, CveId, VulnerabilitySeverityLevel,
    Cvss, IsExploitAvailable, RecommendedSecurityUpdate
| order by IsExploitAvailable desc, Cvss desc
Q39. Software installato e strumenti di accesso remoto (File: 15_vulnerabilita_e_inventario/Q39_software_installato_e_strumenti_di_accesso_remoto.kql)
  • Keywords: #SoftwareInventory #TVM #RAT
// Q39 | Software installato e strumenti di accesso remoto
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Defender Vulnerability Management / dati TVM disponibili
// Parametri: D: DeviceId. Product: stringa opzionale; vuota mostra tutto l’inventario dell’host.
// Scopo: Verificare l’inventario visibile, le versioni e il contesto di un prodotto coinvolto nel caso.
// Limite: Inventario corrente, non prova di esecuzione né copertura completa dei tool portabili. La mancanza di un prodotto in questa tabella non ne esclude l’uso.

let D = "INSERIRE_DEVICE_ID";
let Product = "";
DeviceTvmSoftwareInventory
| where DeviceId == D
| where isempty(Product) or SoftwareName contains Product
| project DeviceId, DeviceName, OSPlatform, SoftwareVendor,
    SoftwareName, SoftwareVersion, EndOfSupportStatus,
    EndOfSupportDate
| order by SoftwareName asc
Q40. Email e allegati a partire dal messaggio (File: 16_appendice_xdr_email_e_identita/Q40_email_e_allegati_a_partire_dal_messaggio.kql)
  • Keywords: #Email #Phishing #Attachment
// Q40 | Email e allegati a partire dal messaggio
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Opzionale: Defender for Office 365
// Parametri: M: NetworkMessageId. Richiede dati Defender for Office 365 e permessi email.
// Scopo: Recuperare destinatari, esito di consegna e allegati di un messaggio sospetto.
// Limite: NetworkMessageId non è InternetMessageId. Il join conserva tutti gli allegati, quindi più righe sono attese. Nessun risultato MDE non esclude apertura, clic o phishing senza file.

let M = "INSERIRE_NETWORK_MESSAGE_ID";
EmailEvents
| where Timestamp > ago(7d) and NetworkMessageId == M
| summarize arg_max(Timestamp, *)
    by NetworkMessageId, RecipientEmailAddress
| project MailTime=Timestamp, NetworkMessageId, RecipientEmailAddress,
    SenderFromAddress, SenderMailFromAddress, Subject,
    DeliveryAction, DeliveryLocation, LatestDeliveryAction,
    LatestDeliveryLocation, ThreatTypes, AuthenticationDetails
| join kind=leftouter (
    EmailAttachmentInfo
    | where Timestamp > ago(7d) and NetworkMessageId == M
    | project NetworkMessageId, RecipientEmailAddress,
        FileName, SHA256, FileSize, AttachmentThreats=ThreatTypes
) on NetworkMessageId, RecipientEmailAddress
| project-away NetworkMessageId1, RecipientEmailAddress1
| order by MailTime asc
Q41. Clic Safe Links di un account (File: 16_appendice_xdr_email_e_identita/Q41_clic_safe_links_di_un_account.kql)
  • Keywords: #Email #Phishing #UrlClick #SafeLinks
// Q41 | Clic Safe Links di un account
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Opzionale: Defender for Office 365 / Safe Links
// Parametri: UPN: account verificato. Finestra: 7 giorni. Richiede telemetria Safe Links.
// Scopo: Distinguere clic osservati, blocchi e prosecuzione oltre una pagina di avviso.
// Limite: Non è la cronologia universale di navigazione. Clic consentito non prova inserimento di credenziali né compromissione. Drafts/Sent e alcuni workload possono non offrire un join email valido.

let UPN = "utente@contoso.com";
UrlClickEvents
| where Timestamp > ago(7d) and AccountUpn =~ UPN
| project Timestamp, AccountUpn, Workload, Url, UrlChain,
    ActionType, IsClickedThrough, ThreatTypes, IPAddress,
    NetworkMessageId, ReportId
| order by Timestamp asc
Q42. Autenticazioni dell’identità nei dati disponibili (File: 16_appendice_xdr_email_e_identita/Q42_autenticazioni_dellidentita_nei_dati_disponibili.kql)
  • Keywords: #Identity #Logon
// Q42 | Autenticazioni dell’identità nei dati disponibili
// v1.0 - 2026-09-08
// Stato: revisione documentale/statica; non eseguita nel tenant.
// Ambiente: Opzionale: Identity / Cloud Apps e sorgenti abilitate
// Parametri: UPN: account verificato. Richiede i servizi e le sorgenti che popolano IdentityLogonEvents.
// Scopo: Integrare il triage endpoint con le attività di autenticazione dell’utente.
// Limite: La copertura dipende dalle sorgenti, tra cui Defender for Identity e Defender for Cloud Apps. Questa tabella non sostituisce tutti i log di sign-in Entra, MFA o accesso condizionale.

let UPN = "utente@contoso.com";
IdentityLogonEvents
| where Timestamp > ago(7d) and AccountUpn =~ UPN
| project Timestamp, AccountUpn, AccountSid, AccountObjectId,
    ActionType, LogonType, Application, Protocol, FailureReason,
    IPAddress, DeviceName, DestinationDeviceName,
    DestinationIPAddress, Location, ReportId
| order by Timestamp asc

SEZIONE 3: QUERY DA CASI REALI DI ANALISI E INCIDENT RESPONSE (C01 – C12)

C01. Indagine approfondita su file .lnk specifici e relativi processi
  • Contesto: Analisi di file collegamento sospetti (es. casi pdmsui.lnk / pdmswk.lnk) per tracciare creazione, modifica ed esecuzione tramite Explorer.
  • Keywords: #LNK #Shortcut #DeviceFileEvents #Process #CaseStudy
let LnkFiles = dynamic(["[SUSPICIOUS_FILE_1].lnk", "[SUSPICIOUS_FILE_2].lnk"]);
union
(
    DeviceFileEvents
    | where Timestamp > ago(30d)
    | where FileName in~ (LnkFiles) or FileName endswith ".lnk"
    | project Timestamp, DeviceName, Table="FileEvents", ActionType, FileName, FolderPath, SHA256, InitiatingProcessFileName, InitiatingProcessCommandLine, RequestAccountName
),
(
    DeviceProcessEvents
    | where Timestamp > ago(30d)
    | where ProcessCommandLine has_any (LnkFiles)
    | project Timestamp, DeviceName, Table="ProcessEvents", ActionType, FileName, FolderPath, SHA256, InitiatingProcessFileName, InitiatingProcessCommandLine=ProcessCommandLine, RequestAccountName=AccountName
)
| order by Timestamp desc
C02. Verifica autenticazioni IdentityLogonEvents (Fix Schema Location + Whitelist IP Interni NL)
  • Contesto: Le colonne Country e City non esistono in IdentityLogonEvents (si usa Location o AdditionalFields). Include il filtro per escludere gli IP NL legittimi appartenenti alla rete aziendale.
  • Keywords: #Identity #Logon #Location #NL_IP_Whitelist #SchemaFix #CaseStudy
let CorporateNLSubnets = dynamic(["[CORPORATE_NL_SUBNET_1]", "[CORPORATE_NL_SUBNET_2]"]);
IdentityLogonEvents
| where Timestamp > ago(14d)
| where AccountUpn =~ "[USER_UPN]"
// Nota: Country e City non esistono nello schema di IdentityLogonEvents; si utilizza Location
| where not(Location == "NL" and ipv4_is_in_any_range(IPAddress, CorporateNLSubnets))
| project
    Timestamp,
    ActionType,
    Application,
    LogonType,
    Protocol,
    AccountUpn,
    AccountName,
    IPAddress,
    Location,
    DeviceName,
    FailureReason,
    AdditionalFields
| order by Timestamp desc
C03. Autenticazioni Entra ID con dettagli geografici Country/City e Conditional Access (AADSignInEventsBeta)
  • Contesto: Utilizzata quando serve il dettaglio granulare su Country, City, ErrorCode e stato MFA non presenti in IdentityLogonEvents.
  • Keywords: #Identity #Logon #AADSignInEventsBeta #EntraID #GeoLocation #CaseStudy
AADSignInEventsBeta
| where Timestamp > ago(14d)
| where AccountUpn =~ "[USER_UPN]"
| project
    Timestamp,
    AccountUpn,
    Application,
    ClientAppUsed,
    IPAddress,
    Country,
    City,
    ErrorCode,
    ConditionalAccessStatus,
    AuthenticationRequirement,
    RiskLevelAggregated,
    DeviceName,
    OSPlatform
| order by Timestamp desc
C04. Verifica manutenzione IT locale e pulizia Event Log (EventID 1102 + Sessioni Utente)
  • Contesto: Verifica se lo svuotamento dei log di sicurezza (SecurityLogCleared / Event 1102) è stato eseguito da personale di supporto IT locale durante attività di manutenzione sulla workstation.
  • Keywords: #LogCleared #Event1102 #Wevtutil #ITMaintenance #CaseStudy
let TargetHost = "[DEVICE_NAME]";
union
(
    DeviceEvents
    | where Timestamp > ago(7d) and DeviceName has TargetHost
    | where ActionType == "SecurityLogCleared"
    | project Timestamp, DeviceName, Category="LogCleared_Event", AccountName=InitiatingProcessAccountName, Process=InitiatingProcessFileName, Details=InitiatingProcessCommandLine
),
(
    DeviceLogonEvents
    | where Timestamp > ago(7d) and DeviceName has TargetHost
    | where ActionType == "LogonSuccess"
    | project Timestamp, DeviceName, Category="UserLogon", AccountName, Process=LogonType, Details=strcat("RemoteIP: ", RemoteIP, " | Admin: ", tostring(IsLocalAdmin))
),
(
    DeviceProcessEvents
    | where Timestamp > ago(7d) and DeviceName has TargetHost
    | where ProcessCommandLine has_any ("wevtutil", "Clear-EventLog", "eventvwr.msc", "compmgmt.msc", "cleanmgr.exe")
    | project Timestamp, DeviceName, Category="Maintenance_Cmd", AccountName, Process=FileName, Details=ProcessCommandLine
)
| order by Timestamp asc
C05. Correlazione tra Alert generati su una workstation e utilizzo di Storage Esterno USB
  • Contesto: Unisce gli alert generati su una macchina con il montaggio di chiavette USB e i file copiati sulle unità rimovibili.
  • Keywords: #USB #RemovableDrive #UsbMounted #Exfiltration #CaseStudy
let TargetHost = "[DEVICE_NAME]";
union
(
    AlertEvidence
    | where Timestamp > ago(30d) and DeviceName has TargetHost
    | join kind=inner AlertInfo on AlertId
    | project Timestamp, DeviceName, EventSource="ALERT", ActionOrTitle=Title, Details=strcat("Severity: ", Severity, " | File: ", FileName)
),
(
    DeviceEvents
    | where Timestamp > ago(30d) and DeviceName has TargetHost
    | where ActionType == "UsbDriveMounted"
    | project Timestamp, DeviceName, EventSource="USB_MOUNT", ActionOrTitle=ActionType, Details=tostring(AdditionalFields)
),
(
    DeviceFileEvents
    | where Timestamp > ago(30d) and DeviceName has TargetHost
    | extend DriveLetter = tostring(split(FolderPath, "\\")[0])
    | where DriveLetter !in ("C:", "D:")
    | project Timestamp, DeviceName, EventSource="USB_FILE", ActionOrTitle=ActionType, Details=strcat(FolderPath, "\\", FileName)
)
| order by Timestamp asc
C06. Correlazione tra click su link Phishing (UrlClickEvents) e successivo download sull'Endpoint
  • Contesto: Verifica se dopo il click di un utente su un link malevolo si sono verificati download di file sulla sua workstation entro 15 minuti.
  • Keywords: #Phishing #UrlClick #SafeLinks #Email #Download #CaseStudy
let SuspiciousUrlPattern = "[SUSPICIOUS_DOMAIN_OR_URL]";
UrlClickEvents
| where Timestamp > ago(7d)
| where Url has SuspiciousUrlPattern
| project ClickTime=Timestamp, AccountUpn, ClickedUrl=Url, ClickAction=ActionType, IsClickedThrough
| join kind=leftouter (
    DeviceFileEvents
    | where Timestamp > ago(7d) and isnotempty(FileOriginUrl)
    | project FileTime=Timestamp, InitiatingProcessAccountUpn, DeviceName, FileName, FolderPath, FileOriginUrl, SHA256
) on $left.AccountUpn == $right.InitiatingProcessAccountUpn
| where isempty(FileTime) or (FileTime between (ClickTime .. (ClickTime + 15m)))
C07. Tuning Regole di Rilevamento: Analisi di rumorosità (False Positive Baseline)
  • Contesto: Raggruppa i processi e le righe di comando ricorrenti su più host per creare esclusioni mirate e ottimizzare le detection rule.
  • Keywords: #Process #CommandLine #RuleTuning #FalsePositives #CaseStudy
DeviceProcessEvents
| where Timestamp > ago(14d)
| where FileName in~ ("powershell.exe", "cmd.exe", "rundll32.exe")
| summarize Occurrences=count(), DistinctHosts=dcount(DeviceId), SampleHosts=make_set(DeviceName, 5), Accounts=make_set(AccountName, 5)
    by InitiatingProcessFileName, InitiatingProcessFolderPath, FileName, ProcessCommandLine
| where DistinctHosts >= 10
| order by Occurrences desc
C08. Ricostruzione albero genealogico di un processo a 3 livelli (Nonno -> Padre -> Figlio)
  • Contesto: Estrae in un'unica vista tutti i dettagli sui 3 livelli di processo disponibili direttamente in DeviceProcessEvents.
  • Keywords: #Process #CommandLine #ProcessTree #CaseStudy
DeviceProcessEvents
| where Timestamp > ago(7d)
| where DeviceName has "[DEVICE_NAME]"
| project
    Timestamp,
    DeviceName,
    AccountName,
    GrandParent_Exe = InitiatingProcessParentFileName,
    Parent_Exe = InitiatingProcessFileName,
    Parent_PID = InitiatingProcessId,
    Parent_Cmd = InitiatingProcessCommandLine,
    Child_Exe = FileName,
    Child_PID = ProcessId,
    Child_Cmd = ProcessCommandLine,
    Child_SHA256 = SHA256
| order by Timestamp asc
C09. Verifica rapida per Reportistica Strutturata (Summary, Root Cause, Actions, Impact)
  • Contesto: Raccoglie rapidamente tutti i contatori chiave (utenti coinvolti, host impattati, prima/ultima evidenza, tabelle e azioni osservate) per la documentazione strutturata dell'incidente.
  • Keywords: #IOC #GlobalSearch #IncidentReport #Impact #CaseStudy
let TargetIOC = "[HASH_OR_DOMAIN_OR_IP]";
search in (DeviceProcessEvents, DeviceFileEvents, DeviceNetworkEvents, DeviceEvents, AlertEvidence) TargetIOC
| summarize
    FirstSeen = min(Timestamp),
    LastSeen = max(Timestamp),
    TotalEvents = count(),
    ImpactedHostsCount = dcount(DeviceName),
    ImpactedHosts = make_set(DeviceName, 50),
    ImpactedUsers = make_set(AccountName, 50),
    ObservedTables = make_set($table),
    ObservedActions = make_set(ActionType)
C10. Rilevamento esfiltrazione verso servizi di File Sharing o Paste Site esterni
  • Contesto: Monitora il caricamento o il contatto verso domini di file sharing non aziendali da parte degli endpoint.
  • Keywords: #Exfiltration #Network #Domain #CloudApps #CaseStudy
let FileSharingDomains = dynamic(["mega.nz", "wetransfer.com", "transfer.sh", "anonfiles.com", "pastebin.com", "sendspace.com", "gofile.io"]);
DeviceNetworkEvents
| where Timestamp > ago(14d)
| where RemoteUrl has_any (FileSharingDomains)
| project Timestamp, DeviceName, InitiatingProcessAccountName, InitiatingProcessFileName, RemoteUrl, RemoteIP
| order by Timestamp desc
C11. Verifica post-sandbox (ANY.RUN / Analisi Dinamica): Ricerca multipla di IOC estratti
  • Contesto: Permette di cercare contemporaneamente tutti gli indicatori (Hash SHA256, Domini C2, IP) estratti durante l'analisi dinamica in sandbox.
  • Keywords: #IOC #Hash #SHA256 #Domain #IP #C2 #CaseStudy
let SandboxHashes = dynamic(["[SHA256_1]", "[SHA256_2]"]);
let SandboxDomains = dynamic(["[C2_DOMAIN_1]", "[C2_DOMAIN_2]"]);
let SandboxIPs = dynamic(["[C2_IP_1]"]);
union
(DeviceFileEvents | where SHA256 in~ (SandboxHashes) | project Timestamp, DeviceName, MatchType="FileHash", Indicator=SHA256, Context=FolderPath),
(DeviceProcessEvents | where SHA256 in~ (SandboxHashes) | project Timestamp, DeviceName, MatchType="ProcessHash", Indicator=SHA256, Context=ProcessCommandLine),
(DeviceNetworkEvents | where RemoteUrl has_any (SandboxDomains) or RemoteIP in (SandboxIPs) | project Timestamp, DeviceName, MatchType="NetworkC2", Indicator=coalesce(RemoteUrl, RemoteIP), Context=InitiatingProcessFileName)
| order by Timestamp desc
C12. Estrazione delle Custom Detection Rules dai log di audit (CloudAppEvents)
  • Contesto: Recupera il codice KQL delle regole di rilevamento personalizzate create o modificate negli ultimi 180 giorni in Microsoft Defender XDR.
  • Keywords: #CloudApps #CustomDetection #ExportRules #CaseStudy
CloudAppEvents
| where Timestamp > ago(180d)
| where Application == "Microsoft 365 Defender"
| where ActionType in ("CreateCustomDetection", "EditCustomDetection")
| extend RuleName = tostring(RawEventData.RuleName),
         Query = tostring(RawEventData.Query),
         Severity = tostring(RawEventData.AlertSeverity)
| summarize arg_max(Timestamp, Query, Severity, ActionType) by RuleName
| project Timestamp, RuleName, Severity, Query

SEZIONE 4: APPENDICE OPERATIVA — PROCEDURA DI ESPORTAZIONE QUERY DA DEFENDER

Quando aggiungerai nuove query in Microsoft Defender XDR (Hunting > Advanced hunting > Saved queries) e vorrai esportarle tutte in un unico file JSON senza copiarle una per una, segui questi passaggi:

  1. Apri Microsoft Defender XDR e vai in Hunting > Advanced hunting.
  2. Premi F12 per aprire gli Strumenti di sviluppo (DevTools) del browser e seleziona la scheda Console.
  3. (Solo se richiesto dal browser) Se incollando lo script compare un avviso di sicurezza, digita allow pasting (oppure consenti incolla) e premi Invio.
  4. Incolla lo Script Universale qui sotto e premi Invio: lo script individua automaticamente tutte le tue query salvate/schedulate (escludendo quelle Community di default), scarica il codice KQL completo di ciascuna e avvia il download del file Defender_KQL_Export_Completo.json.
(async () => {
  // 1. Individua automaticamente l'endpoint proxy di Defender
  const perfEntries = performance.getEntriesByType('resource').map(r => r.name);
  let baseUrl = '/apiproxy/mtp/huntingService/queries/';
  const sample = perfEntries.find(u => u.includes('queries/?type=') || /\/queries\/\d+/.test(u));
  if (sample) baseUrl = sample.split('queries')[0] + 'queries/';

  // 2. Recupera il token XSRF dalla sessione corrente
  const xsrf = document.cookie.split('; ').find(row => row.startsWith('XSRF-TOKEN='))?.split('=')[1];
  const headers = { 'Accept': 'application/json' };
  if (xsrf) headers['X-XSRF-TOKEN'] = decodeURIComponent(xsrf);

  console.log('1/3 - Recupero elenco query salvate e schedulate...');
  const [sharedRes, schedRes, userRes] = await Promise.all([
    fetch(`${baseUrl}?type=shared`, { headers, credentials: 'include' }).then(r => r.json()).catch(() => []),
    fetch(`${baseUrl}?type=scheduled`, { headers, credentials: 'include' }).then(r => r.json()).catch(() => []),
    fetch(`${baseUrl}?type=user`, { headers, credentials: 'include' }).then(r => r.json()).catch(() => [])
  ]);

  // 3. Filtra le query personalizzate (esclude Community e Suggested di default)
  const targetQueries = [...sharedRes, ...schedRes, ...userRes].filter(q =>
    q.UsxSourceType === 'Defender' &&
    typeof q.Id === 'number' &&
    q.Id > 0 &&
    !(q.Path && (q.Path.startsWith('Community') || q.Path.startsWith('Suggested')))
  );

  const uniqueIds = [...new Set(targetQueries.map(q => q.Id))];
  console.log(`2/3 - Trovate ${uniqueIds.length} query personalizzate. Avvio estrazione del codice KQL...`);

  // 4. Scarica il QueryText completo per ciascun ID
  const results = [];
  for (const id of uniqueIds) {
    try {
      const r = await fetch(`${baseUrl}${id}`, { headers, credentials: 'include' });
      const data = await r.json();
      results.push(data);
      console.log(`Scaricata [${results.length}/${uniqueIds.length}]: ${data.Path ? data.Path + '\\' : ''}${data.Name}`);
    } catch (e) {
      console.error(`Errore su ID ${id}:`, e);
    }
  }

  // 5. Esporta tutto in un unico file JSON
  const blob = new Blob([JSON.stringify(results, null, 2)], { type: 'application/json' });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = 'Defender_KQL_Export_Completo.json';
  a.click();
  console.log('3/3 - Completato! File Defender_KQL_Export_Completo.json scaricato.');
})();