index=wineventlog sourcetype=WinEventLog:Security EventCode=4625 user=jsmith
SecurityEvent
| where EventID == 4625
| where TargetUserName =~ "jsmith"
Valores de campo no SPL não diferenciam maiúsculas de minúsculas por padrão, enquanto o == do KQL diferencia, então use =~ (ou has) quando você não controla a capitalização.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4624 earliest=-24h@h latest=now
SecurityEvent
| where TimeGenerated between (ago(24h) .. now())
| where EventID == 4624
O Splunk consegue arredondar o tempo com @h; ago(24h) não arredonda, então use startofday() ou bin() se precisar de limites alinhados, e sempre filtre TimeGenerated primeiro para ganhar desempenho.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4625
| stats count by user, src_ip
| sort - count
SecurityEvent
| where EventID == 4625
| summarize Count = count() by TargetAccount, IpAddress
| sort by Count desc
stats ... by corresponde a summarize ... by; o KQL precisa de um nome de coluna explícito para a agregação se você quiser ordenar por ela sem complicação.
index=sysmon EventCode=1
| top limit=10 Image
index=sysmon EventCode=1
| rare limit=10 Image
DeviceProcessEvents
| summarize Count = count() by FileName
| top 10 by Count desc
DeviceProcessEvents
| summarize Count = count() by FileName
| top 10 by Count asc
top/rare no SPL contam e adicionam uma coluna de percentual para você; o top do KQL só ordena e pega N linhas, então você precisa fazer summarize antes.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4624 Logon_Type=10
| dedup user, src_ip
| table _time, user, src_ip, host
SecurityEvent
| where EventID == 4624 and LogonType == 10
| distinct TargetAccount, IpAddress, Computer
dedup mantém o evento mais recente inteiro, enquanto distinct retorna só as colunas listadas; use summarize arg_max(TimeGenerated, *) by TargetAccount, IpAddress para manter linhas completas como no dedup.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4624
| rename src_ip AS SourceIP, user AS Account
| table _time, Account, SourceIP, host
SecurityEvent
| where EventID == 4624
| project TimeGenerated, Account = TargetAccount, SourceIP = IpAddress, Computer
O project do KQL renomeia e seleciona em um único passo; use project-rename se quiser manter todas as outras colunas.
index=web sourcetype=access_combined
| eval is_error=if(status>=500, 1, 0), uri_len=len(uri)
| stats sum(is_error) AS errors avg(uri_len) AS avg_uri_len by clientip
W3CIISLog
| extend IsError = iff(toint(scStatus) >= 500, 1, 0), UriLen = strlen(csUriStem)
| summarize Errors = sum(IsError), AvgUriLen = avg(UriLen) by cIP
eval corresponde a extend e if() a iff(); em W3CIISLog a coluna scStatus é string, então converta com toint() antes de comparar numericamente.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4625 earliest=-24h
| timechart span=1h count AS failed_logons
SecurityEvent
| where TimeGenerated > ago(24h) and EventID == 4625
| summarize FailedLogons = count() by bin(TimeGenerated, 1h)
| render timechart
timechart preenche buckets vazios com zero, mas summarize by bin() simplesmente os omite; use make-series no KQL quando as lacunas importam para o baseline.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4624
| lookup privileged_accounts.csv user OUTPUT role
| where isnotnull(role)
| table _time, user, role, src_ip, host
let PrivAccounts = _GetWatchlist('PrivilegedAccounts')
| project TargetUserName = tostring(SearchKey), Role = tostring(Role);
SecurityEvent
| where EventID == 4624
| join kind=inner PrivAccounts on TargetUserName
| project TimeGenerated, TargetUserName, Role, IpAddress, Computer
Watchlists do Sentinel substituem os arquivos de lookup do Splunk; lembre que o join padrão do KQL é innerunique, que faz dedup silencioso do lado esquerdo, então declare kind=inner explicitamente.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4625 earliest=-1h
| stats count AS failures dc(user) AS distinct_users values(user) AS targeted by src_ip
| where failures > 20
| sort - failures
SecurityEvent
| where TimeGenerated > ago(1h) and EventID == 4625
| summarize Failures = count(), DistinctUsers = dcount(TargetAccount), Targeted = make_set(TargetAccount, 20) by IpAddress
| where Failures > 20
| sort by Failures desc
dc()/values() correspondem a dcount()/make_set(); uma contagem alta de usuários distintos a partir de um IP indica spraying, uma contagem baixa indica força bruta.
index=wineventlog sourcetype=WinEventLog:Security (EventCode=4625 OR EventCode=4624) earliest=-1h
| eval fail_time=if(EventCode=4625, _time, null()), success_time=if(EventCode=4624, _time, null())
| stats count(fail_time) AS failures min(fail_time) AS first_fail count(success_time) AS successes max(success_time) AS last_success by src_ip, user
| where failures >= 10 AND successes > 0 AND last_success > first_fail
| convert ctime(first_fail) ctime(last_success)
let Failures = SecurityEvent
| where TimeGenerated > ago(1h) and EventID == 4625
| summarize FailCount = count(), FirstFail = min(TimeGenerated) by IpAddress, TargetAccount;
SecurityEvent
| where TimeGenerated > ago(1h) and EventID == 4624
| summarize LastSuccess = max(TimeGenerated) by IpAddress, TargetAccount
| join kind=inner Failures on IpAddress, TargetAccount
| where FailCount >= 10 and LastSuccess > FirstFail
| project IpAddress, TargetAccount, FailCount, FirstFail, LastSuccess
O SPL costuma resolver isso em uma passada com stats condicional, enquanto no KQL fica mais natural como dois conjuntos let unidos por IP e conta.
index=o365 sourcetype=o365:management:activity Workload=AzureActiveDirectory Operation=UserLoggedIn earliest=-24h
| iplocation ClientIP
| stats dc(Country) AS countries values(Country) AS country_list values(ClientIP) AS ips by UserId
| where countries > 1
SigninLogs
| where TimeGenerated > ago(24h) and ResultType == "0"
| extend Country = tostring(LocationDetails.countryOrRegion)
| summarize Countries = dcount(Country), CountryList = make_set(Country), IPs = make_set(IPAddress), Apps = make_set(AppDisplayName) by UserPrincipalName
| where Countries > 1
O Splunk faz a geolocalização no momento da busca com iplocation, enquanto SigninLogs já traz LocationDetails; ResultType é string, então compare com "0" e não com 0.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4740
| stats count values(Caller_Computer_Name) AS caller_computers by user
| sort - count
SecurityEvent
| where EventID == 4740
| summarize Lockouts = count(), CallerComputers = make_set(TargetDomainName) by TargetAccount
| sort by Lockouts desc
Em SecurityEvent, o Caller Computer Name do 4740 vai para a coluna TargetDomainName, uma peculiaridade conhecida que confunde quem está traduzindo queries.
index=wineventlog sourcetype=WinEventLog:Security EventCode=4720
| table _time, host, src_user, user
| rename src_user AS created_by, user AS new_account
SecurityEvent
| where EventID == 4720
| project TimeGenerated, Computer, CreatedBy = SubjectAccount, NewAccount = TargetAccount
O add-on Windows do Splunk normaliza criador e alvo como src_user e user, enquanto SecurityEvent mantém a separação bruta SubjectAccount/TargetAccount.
index=sysmon EventCode=1 (Image="*\\powershell.exe" OR Image="*\\pwsh.exe") (CommandLine="* -e *" OR CommandLine="* -ec *" OR CommandLine="*-enc*")
| table _time, host, User, ParentImage, CommandLine
DeviceProcessEvents
| where TimeGenerated > ago(7d)
| where FileName in~ ("powershell.exe", "pwsh.exe")
| where ProcessCommandLine matches regex @"(?i)\s-(e|ec|en\w*)\s"
| project TimeGenerated, DeviceName, AccountName, InitiatingProcessFileName, ProcessCommandLine
O PowerShell aceita qualquer prefixo de -EncodedCommand, então uma regex é melhor que strings fixas; o payload é Base64 UTF-16LE, então o texto decodificado mostra bytes nulos a menos que você os remova.
index=sysmon EventCode=1 (ParentImage="*\\winword.exe" OR ParentImage="*\\excel.exe" OR ParentImage="*\\powerpnt.exe" OR ParentImage="*\\outlook.exe") (Image="*\\cmd.exe" OR Image="*\\powershell.exe" OR Image="*\\wscript.exe" OR Image="*\\cscript.exe" OR Image="*\\mshta.exe" OR Image="*\\rundll32.exe")
| table _time, host, User, ParentImage, Image, CommandLine
DeviceProcessEvents
| where InitiatingProcessFileName in~ ("winword.exe", "excel.exe", "powerpnt.exe", "outlook.exe")
| where FileName in~ ("cmd.exe", "powershell.exe", "pwsh.exe", "wscript.exe", "cscript.exe", "mshta.exe", "rundll32.exe", "regsvr32.exe")
| project TimeGenerated, DeviceName, AccountName, InitiatingProcessFileName, FileName, ProcessCommandLine
O Sysmon traz caminhos completos, então o SPL precisa de curingas com barras invertidas escapadas, enquanto o MDE separa valores simples de FileName que funcionam bem com uma lista in~ sem diferenciar maiúsculas.
index=sysmon EventCode=1 earliest=-7d
| eval parent=lower(mvindex(split(ParentImage, "\\"), -1)), child=lower(mvindex(split(Image, "\\"), -1))
| stats count dc(host) AS hosts values(host) AS host_list by parent, child
| where count < 5
| sort count
DeviceProcessEvents
| where TimeGenerated > ago(7d)
| summarize Count = count(), Hosts = dcount(DeviceName), HostList = make_set(DeviceName, 10) by Parent = tolower(InitiatingProcessFileName), Child = tolower(FileName)
| where Count < 5
| sort by Count asc
No SPL você precisa extrair o nome do arquivo do caminho com split/mvindex; o KQL consegue calcular chaves de agrupamento inline dentro de summarize ... by.
index=sysmon EventCode=1 (Image="*\\certutil.exe" OR OriginalFileName="CertUtil.exe") (CommandLine="*urlcache*" OR CommandLine="*verifyctl*" OR CommandLine="*-decode*")
| table _time, host, User, ParentImage, CommandLine
DeviceProcessEvents
| where FileName =~ "certutil.exe" or ProcessVersionInfoOriginalFileName =~ "CertUtil.exe"
| where ProcessCommandLine has_any ("urlcache", "verifyctl", "decode")
| project TimeGenerated, DeviceName, AccountName, InitiatingProcessFileName, ProcessCommandLine
Fazer match pelo nome original do arquivo pega cópias renomeadas; has_any no KQL faz match de termos inteiros e é muito mais rápido que contains em tabelas grandes.
index=sysmon EventCode=3 Initiated=true NOT DestinationPort IN (80, 443, 53, 22, 25, 88, 123, 389, 445, 3389)
| where NOT (cidrmatch("10.0.0.0/8", DestinationIp) OR cidrmatch("172.16.0.0/12", DestinationIp) OR cidrmatch("192.168.0.0/16", DestinationIp))
| stats count dc(host) AS hosts values(Image) AS processes by DestinationPort
| where hosts < 3
| sort count
DeviceNetworkEvents
| where TimeGenerated > ago(7d)
| where ActionType == "ConnectionSuccess" and RemoteIPType == "Public"
| where RemotePort !in (80, 443, 53, 22, 25, 88, 123, 389, 445, 3389)
| summarize Count = count(), Hosts = dcount(DeviceName), Processes = make_set(InitiatingProcessFileName, 10) by RemotePort
| where Hosts < 3
| sort by Count asc
O Splunk precisa de cidrmatch() para descartar faixas privadas, enquanto o MDE já classifica os endereços em RemoteIPType; NOT x IN (...) vira !in.
index=sysmon EventCode=22
| eval qlen=len(QueryName)
| where qlen > 60
| rex field=QueryName "(?<domain>[^.]+\.[^.]+)$"
| stats dc(QueryName) AS unique_queries max(qlen) AS max_len values(Image) AS processes by domain, host
| where unique_queries > 50
| sort - unique_queries
DnsEvents
| where TimeGenerated > ago(24h) and SubType == "LookupQuery"
| where strlen(Name) > 60
| extend Domain = extract(@"([^.]+\.[^.]+)$", 1, Name)
| summarize UniqueQueries = dcount(Name), MaxLen = max(strlen(Name)), Clients = make_set(ClientIP, 10) by Domain
| where UniqueQueries > 50
| sort by UniqueQueries desc
rex corresponde a extract(); a regex ingênua dos dois últimos rótulos agrupa errado domínios como co.uk, então trate os resultados como pistas e verifique a contagem de subdomínios únicos por domínio pai.
index=mail sourcetype=ms:o365:reporting:messagetrace earliest=-24h NOT SenderAddress="*@corp.example.com"
| stats dc(RecipientAddress) AS recipients values(Subject) AS subjects values(Status) AS statuses by SenderAddress, FromIP
| where recipients > 20
| sort - recipients
EmailEvents
| where TimeGenerated > ago(24h) and EmailDirection == "Inbound"
| summarize Recipients = dcount(RecipientEmailAddress), Subjects = make_set(Subject, 5), Actions = make_set(DeliveryAction) by SenderFromAddress, SenderIPv4
| where Recipients > 20
| sort by Recipients desc
EmailEvents traz EmailDirection e DeliveryAction diretamente, enquanto nos dados de message trace no Splunk você precisa excluir seu próprio domínio e interpretar o Status de entrega por conta própria.
index=mail sourcetype=ms:o365:reporting:messagetrace Status=Delivered (Subject="*invoice*" OR Subject="*payment*" OR Subject="*wire transfer*")
| table _time, SenderAddress, FromIP, RecipientAddress, Subject
EmailEvents
| where TimeGenerated > ago(7d) and EmailDirection == "Inbound" and DeliveryAction == "Delivered"
| where Subject has_any ("invoice", "payment", "wire transfer")
| extend Auth = parse_json(AuthenticationDetails)
| where tostring(Auth.DMARC) =~ "fail" or tostring(Auth.SPF) =~ "fail"
| project TimeGenerated, SenderFromAddress, SenderIPv4, RecipientEmailAddress, Subject, AuthenticationDetails
O message trace não tem veredictos de SPF/DKIM/DMARC, então no Splunk você pivota para logs do gateway ou de cabeçalhos, enquanto EmailEvents os expõe como JSON em AuthenticationDetails.
index=web sourcetype=access_combined
| eval decoded=urldecode(uri)
| where match(decoded, "(?i)(union\s+(all\s+)?select|or\s+1=1|sleep\(|benchmark\(|information_schema|' or ')")
| stats count values(status) AS statuses values(uri_path) AS paths by clientip
| sort - count
W3CIISLog
| where TimeGenerated > ago(24h)
| extend Q = url_decode(csUriQuery)
| where Q matches regex @"(?i)(union\s+(all\s+)?select|or\s+1=1|sleep\(|benchmark\(|information_schema|' or ')"
| summarize Requests = count(), Statuses = make_set(scStatus), Paths = make_set(csUriStem, 10) by cIP
| sort by Requests desc
Decodifique antes de fazer match (urldecode vs url_decode) ou payloads codificados passam despercebidos; verifique também os status codes, já que um 200 em um payload de injeção importa mais que um 403.
index=o365 sourcetype=o365:management:activity Workload IN (SharePoint, OneDrive) Operation=FileDownloaded earliest=-24h
| bin _time span=1h
| stats dc(ObjectId) AS files values(ClientIP) AS ips by _time, UserId
| where files > 100
| sort - files
OfficeActivity
| where TimeGenerated > ago(24h)
| where OfficeWorkload in ("SharePoint", "OneDrive") and Operation == "FileDownloaded"
| summarize Files = dcount(OfficeObjectId), IPs = make_set(ClientIP, 10) by UserId, bin(TimeGenerated, 1h)
| where Files > 100
| sort by Files desc
O SPL agrupa o tempo com um comando bin separado antes do stats, enquanto o KQL coloca bin() dentro da cláusula summarize ... by.
index=o365 sourcetype=o365:management:activity Workload=Exchange (Operation=New-InboxRule OR Operation=Set-InboxRule OR Operation=UpdateInboxRules)
| search Parameters{}.Name IN (DeleteMessage, MoveToFolder, ForwardTo, RedirectTo, ForwardAsAttachmentTo)
| table _time, UserId, ClientIP, Operation, Parameters{}.Name, Parameters{}.Value
OfficeActivity
| where OfficeWorkload == "Exchange"
| where Operation in~ ("New-InboxRule", "Set-InboxRule", "UpdateInboxRules")
| where Parameters has_any ("DeleteMessage", "MoveToFolder", "ForwardTo", "RedirectTo", "ForwardAsAttachmentTo")
| project TimeGenerated, UserId, ClientIP, Operation, Parameters
O Splunk expõe os parâmetros da regra como campos multivalorados Parameters{}.Name/Value, enquanto OfficeActivity os armazena como uma string JSON que você pode buscar com has_any ou expandir com parse_json.