Communitygithub.com

使用Splunk SPL构建检测规则

使用Splunk搜索处理语言构建有效的检测规则,以便在Splunk Enterprise Security中关联、聚合和丰富安全事件,生成可处理的重要事件。

使用Splunk SPL构建检测规则 是什么?

该技能详细介绍了如何使用Splunk搜索处理语言(SPL)构建检测规则,主要面向在Splunk Enterprise Security环境中工作的安全分析师。内容包括多种核心SPL检测规则模式(如基于阈值、序列、异常、横向移动、数据泄露和PowerShell可疑执行的检测),以及构建关联搜索的逐步流程、性能优化技巧和测试验证方法。该技能还涵盖了将检测映射到MITRE ATT&CK框架的必要性,并提供了丰富的代码示例。它适用于需要部署或配置Splunk检测能力的场景,满足合规要求,以及改善安全架构。使用前需要具备Splunk ES部署、CIM数据模型和MITRE ATT&CK的基础知识。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mukul975/Anthropic-Cybersecurity-Skills/tree/main/skills/building-detection-rule-with-splunk-spl

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

使用Splunk SPL构建检测规则 是做什么的?

概述

Splunk搜索处理语言(SPL)是Splunk Enterprise Security中用于构建关联搜索的主要查询语言,用于检测可疑事件和模式。精心编写的检测规则能够聚合、关联和增强安全事件,为SOC分析师生成可操作的重要事件。企业SIEM平均仅覆盖MITRE ATT&CK技术的21%,因此熟练编写SPL规则对于填补检测空白至关重要。

使用场景

  • 在环境中部署或配置Splunk SPL检测规则功能时
  • 建立符合合规要求的安全控制时
  • 构建或改进此领域的安全架构时
  • 需要进行需要此实现的安全评估时

前提条件

  • 已部署并配置Splunk Enterprise Security(ES)
  • 拥有Splunk搜索和报告应用的访问权限及适当角色
  • 理解通用信息模型(CIM)数据模型
  • 熟悉MITRE ATT&CK框架技术
  • 了解组织的日志源和数据流

核心SPL检测规则模式

1. 基于阈值的检测

检测时间窗口内超过定义计数的事件。

index=wineventlog sourcetype=WinEventLog:Security EventCode=4625
| stats count as failed_logins dc(TargetUserName) as unique_users by src_ip
| where failed_logins > 10 AND unique_users > 3
| eval severity="high"
| eval description="Brute force attack detected from ".src_ip." with ".failed_logins." failed logins across ".unique_users." accounts"

2. 基于序列的检测(登录失败后成功)

关联一系列事件,指示成功的暴力破解攻击。

index=wineventlog sourcetype=WinEventLog:Security (EventCode=4625 OR EventCode=4624)
| eval login_status=case(EventCode=4625, "failure", EventCode=4624, "success")
| stats count(eval(login_status="failure")) as failures count(eval(login_status="success")) as successes latest(_time) as last_event by src_ip, TargetUserName
| where failures > 5 AND successes > 0
| eval description="Account ".TargetUserName." compromised via brute force from ".src_ip
| eval urgency="critical"

3. 基于基线比较的异常检测

将当前活动与基线时段进行比较,检测峰值。

index=proxy sourcetype=squid
| bin _time span=1h
| stats count as current_count by src_ip, _time
| join src_ip type=left [
    search index=proxy sourcetype=squid earliest=-7d@d latest=-1d@d
    | stats avg(count) as avg_count stdev(count) as stdev_count by src_ip
]
| eval threshold=avg_count + (3 * stdev_count)
| where current_count > threshold
| eval deviation=round((current_count - avg_count) / stdev_count, 2)
| eval description="Anomalous web traffic from ".src_ip." - ".deviation." standard deviations above baseline"

4. 横向移动检测

使用Windows登录事件识别潜在的横向移动。

index=wineventlog sourcetype=WinEventLog:Security EventCode=4624 Logon_Type=3
| where NOT match(TargetUserName, ".*\$$")
| stats dc(dest) as unique_hosts values(dest) as hosts by src_ip, TargetUserName
| where unique_hosts > 5
| eval severity=case(unique_hosts > 20, "critical", unique_hosts > 10, "high", true(), "medium")
| eval description=TargetUserName." accessed ".unique_hosts." unique hosts from ".src_ip." via network logon"

5. 数据泄露检测

监控大量出站数据传输。

index=firewall sourcetype=pan:traffic action=allowed direction=outbound
| stats sum(bytes_out) as total_bytes_out dc(dest_ip) as unique_destinations by src_ip, user
| eval total_mb=round(total_bytes_out/1048576, 2)
| where total_mb > 500 OR unique_destinations > 50
| lookup asset_lookup ip as src_ip OUTPUT asset_category, asset_owner
| eval severity=case(total_mb > 2000, "critical", total_mb > 1000, "high", true(), "medium")
| eval description=user." transferred ".total_mb."MB to ".unique_destinations." unique destinations"

6. PowerShell可疑执行检测

检测经过编码或混淆的PowerShell命令。

index=wineventlog sourcetype=WinEventLog:Security EventCode=4104
| where match(ScriptBlockText, "(?i)(encodedcommand|invoke-expression|iex|downloadstring|frombase64string|net\.webclient|invoke-webrequest|bitstransfer|invoke-mimikatz|invoke-shellcode)")
| eval decoded_length=len(ScriptBlockText)
| stats count values(ScriptBlockText) as commands by Computer, UserName
| where count > 0
| eval severity="high"
| eval mitre_technique="T1059.001"
| eval description="Suspicious PowerShell execution on ".Computer." by ".UserName

在Splunk ES中构建关联搜索

分步流程

  1. 定义用例:映射到MITRE ATT&CK技术并定义要检测的行为
  2. 识别数据源:确定包含相关事件的索引和sourcetype
  3. 编写基础搜索:构建提取相关事件的SPL
  4. 添加聚合:使用 stats、eventstats 或 streamstats 进行汇总
  5. 应用阈值:使用 where 子句设置条件,区分正常行为与异常行为
  6. 丰富上下文:添加资产信息、身份数据和威胁情报的查找
  7. 配置重要事件:设置严重级别、紧急程度和描述字段
  8. 调度和测试:针对历史数据运行并验证检测准确性

关联搜索配置模板

| tstats summariesonly=true count from datamodel=Authentication
    where Authentication.action=failure
    by Authentication.src, Authentication.user, _time span=5m
| rename "Authentication.*" as *
| stats count as total_failures dc(user) as unique_users values(user) as targeted_users by src
| where total_failures > 20 AND unique_users > 5
| lookup dnslookup clientip as src OUTPUT clienthost as src_dns
| lookup asset_lookup ip as src OUTPUT priority as asset_priority, category as asset_category
| eval urgency=case(asset_priority=="critical", "critical", asset_priority=="high", "high", true(), "medium")
| eval rule_name="Brute Force Against Multiple Accounts"
| eval rule_description="Multiple authentication failures from ".src." targeting ".unique_users." unique accounts"
| eval mitre_attack="T1110.001 - Password Guessing"

丰富最佳实践

| lookup identity_lookup identity as user OUTPUT department, manager, risk_score as user_risk
| lookup asset_lookup ip as src_ip OUTPUT asset_name, asset_category, asset_priority, asset_owner
| lookup threatintel_lookup ip as src_ip OUTPUT threat_type, threat_confidence, threat_source
| eval context=case(
    isnotnull(threat_type), "Known threat: ".threat_type,
    user_risk > 80, "High-risk user: risk score ".user_risk,
    asset_priority=="critical", "Critical asset: ".asset_name,
    true(), "Standard context"
)

性能优化

使用数据模型结合tstats

| tstats summariesonly=true count from datamodel=Network_Traffic
    where All_Traffic.action=allowed
    by All_Traffic.src_ip, All_Traffic.dest_ip, All_Traffic.dest_port, _time span=1h
| rename "All_Traffic.*" as *

限制时间范围并使用索引字段

index=wineventlog source="WinEventLog:Security" EventCode=4688
    earliest=-15m latest=now()
| where NOT match(New_Process_Name, "(?i)(svchost|csrss|lsass|services)")

使用汇总索引建立历史基线

| tstats count from datamodel=Authentication where Authentication.action=failure by Authentication.src, _time span=1h
| collect index=summary source="auth_failure_baseline" marker="report_name=auth_failure_hourly"

测试与验证

针对已知攻击模式进行测试

| makeresults count=1
| eval src_ip="10.0.0.50", failed_logins=25, unique_users=8, severity="high"
| eval description="Test brute force detection"
| append [
    search index=wineventlog sourcetype=WinEventLog:Security EventCode=4625
    earliest=-24h latest=now()
    | stats count as failed_logins dc(TargetUserName) as unique_users by src_ip
    | where failed_logins > 10 AND unique_users > 3
    | eval severity="high"
]

计算检测指标

index=notable
| search rule_name="Brute Force*"
| stats count as total_alerts count(eval(status_label="Closed - True Positive")) as true_positives count(eval(status_label="Closed - False Positive")) as false_positives by rule_name
| eval precision=round(true_positives / (true_positives + false_positives) * 100, 2)
| eval fpr=round(false_positives / total_alerts * 100, 2)

MITRE ATT&CK映射

技术ID技术名称SPL检测方法
T1110.001密码猜测对EventCode 4625按src_ip设置阈值
T1059.001PowerShell对EventCode 4104 ScriptBlockText进行模式匹配
T1021.002SMB/Windows管理共享登录类型3配合dc(dest)阈值
T1048通过C2通道泄露按时间窗口聚合bytes_out
T1053.005计划任务EventCode 4698配合可疑命令模式
T1003.001LSASS内存转储通过Sysmon EventCode 10检测对lsass.exe的进程访问

参考

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

abusing-dpapi-for-credential-access

Extract and decrypt Windows DPAPI-protected secrets (Credential Manager, browser logins/cookies, Wi-Fi credentials, KeePass keys) online or offline using SharpDPAPI, SharpChrome, Mimikatz, or Impacket

abusing-shadow-credentials-for-privesc

Take over Active Directory accounts by writing attacker-controlled public keys to msDS-KeyCredentialLink (Shadow Credentials) with pyWhisker, Whisker, or Certipy, then authenticate via PKINIT to recover the target

achieving-cmmc-level-2-compliance

>-

acquiring-disk-image-with-dd-and-dcfldd

Create forensically sound bit-for-bit disk images with dd or dcfldd on a Linux forensic workstation, preserving evidence integrity through hash verification (MD5/SHA) during acquisition. Use when imaging a suspect drive, USB device, or memory card for investigation, preserving volatile disk evidence during incident response, or producing a verified copy for legal or law-enforcement proceedings before any destructive analysis.

analyzing-active-directory-acl-abuse

Detect dangerous ACL misconfigurations in Active Directory using ldap3

analyzing-android-malware-with-apktool

Perform static analysis of Android APK malware using apktool for resource decompilation, jadx for Java source recovery, and androguard for manifest inspection, dangerous permission-combination detection, and identification of obfuscated code, dynamic code loading, and reflection-based API calls. Use to statically triage a suspicious APK without executing it or to build mobile malware detection rules.

analyzing-api-gateway-access-logs

Parses API Gateway access logs (AWS API Gateway, Kong, Nginx) to detect

analyzing-apt-group-with-mitre-navigator

Query ATT&CK data with attackcti, mitreattack-python, and stix2, then build MITRE ATT&CK Navigator layers and multi-layer heatmap overlays mapping one or more APT groups

analyzing-azure-activity-logs-for-threats

Queries Azure Monitor activity logs and sign-in logs via azure-monitor-query

analyzing-bootkit-and-rootkit-samples

Analyzes bootkit and advanced rootkit malware infecting the Master

analyzing-browser-forensics-with-hindsight

Parse Chromium-based browser databases with Hindsight to extract and correlate browsing history, downloads, cookies, cached content, autofill data, saved passwords, and extensions from Chrome, Edge, Brave, Opera, and Vivaldi into a unified timeline (XLSX, JSON, or SQLite output). Use during incident response, insider-threat investigations, or criminal cases when you need to reconstruct a user

analyzing-campaign-attribution-evidence

Systematically evaluate cyber-campaign evidence to attribute an operation to a threat actor, using the Diamond Model and Analysis of Competing Hypotheses (ACH) to weigh infrastructure overlaps, TTP consistency, malware code similarity, and timing/language artifacts into confidence-weighted attribution assessments. Use when an incident investigation needs a defensible attribution confidence level.

analyzing-certificate-transparency-for-phishing

Monitor Certificate Transparency logs using crt.sh and Certstream to

analyzing-cloud-storage-access-patterns

Detect abnormal access in AWS S3, GCS, and Azure Blob Storage by analyzing CloudTrail Data Events, GCS audit logs, and Azure Storage Analytics for after-hours bulk downloads, new-IP access, and API-call spikes (e.g. GetObject) via statistical baselines and time-series anomaly detection. Use when investigating suspected cloud data exfiltration or building related detection rules.

analyzing-cobalt-strike-beacon-configuration

Extract and analyze Cobalt Strike beacon configuration from PE files

analyzing-cobaltstrike-malleable-c2-profiles

Parse and analyze Cobalt Strike Malleable C2 profiles with dissect.cobaltstrike (profiles and beacon-payload configs) and pyMalleableC2 (AST parsing) to extract HTTP/DNS transforms, URIs, headers, sleep/jitter, and injection behavior, then generate network detection signatures. Use when reverse-engineering a captured malleable profile or building detections against Cobalt Strike Beacon traffic.

analyzing-command-and-control-communication

Analyzes malware C2 communication over HTTP, HTTPS, DNS, and custom

analyzing-cyber-kill-chain

Analyzes intrusion activity against the Lockheed Martin Cyber Kill Chain

analyzing-disk-image-with-autopsy

Perform comprehensive forensic analysis of raw (dd), E01, or AFF disk images with Autopsy and The Sleuth Kit, recovering deleted files, examining metadata and embedded artifacts, keyword searching, and building investigation timelines with visual reports. Use for structured analysis of a forensic disk image or when stakeholders need visual reports from evidence.

analyzing-dns-logs-for-exfiltration

Analyzes DNS query logs to detect data exfiltration via DNS tunneling,

相关技能