
Building Threat Hunt Hypothesis Framework
- 143 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
building-threat-hunt-hypothesis-framework is a Claude Code skill in the AI & Agent Building category.
- building-threat-hunt-hypothesis-framework
- AI & Agent Building
- AI-coding skill
Building Threat Hunt Hypothesis Framework by the numbers
- 143 all-time installs (skills.sh)
- +2 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,463 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill building-threat-hunt-hypothesis-frameworkAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 143 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Building Threat Hunt Hypothesis Framework
When to Use
- When proactively hunting for indicators of building threat hunt hypothesis framework in the environment
- After threat intelligence indicates active campaigns using these techniques
- During incident response to scope compromise related to these techniques
- When EDR or SIEM alerts trigger on related indicators
- During periodic security assessments and purple team exercises
Prerequisites
- EDR platform with process and network telemetry (CrowdStrike, MDE, SentinelOne)
- SIEM with relevant log data ingested (Splunk, Elastic, Sentinel)
- Sysmon deployed with comprehensive configuration
- Windows Security Event Log forwarding enabled
- Threat intelligence feeds for IOC correlation
Workflow
1. Formulate Hypothesis: Define a testable hypothesis based on threat intelligence or ATT&CK gap analysis. 2. Identify Data Sources: Determine which logs and telemetry are needed to validate or refute the hypothesis. 3. Execute Queries: Run detection queries against SIEM and EDR platforms to collect relevant events. 4. Analyze Results: Examine query results for anomalies, correlating across multiple data sources. 5. Validate Findings: Distinguish true positives from false positives through contextual analysis. 6. Correlate Activity: Link findings to broader attack chains and threat actor TTPs. 7. Document and Report: Record findings, update detection rules, and recommend response actions.
Key Concepts
| Concept | Description |
|---|---|
| TA0001 | Initial Access |
| TA0003 | Persistence |
| TA0008 | Lateral Movement |
| TA0010 | Exfiltration |
Tools & Systems
| Tool | Purpose |
|---|---|
| CrowdStrike Falcon | EDR telemetry and threat detection |
| Microsoft Defender for Endpoint | Advanced hunting with KQL |
| Splunk Enterprise | SIEM log analysis with SPL queries |
| Elastic Security | Detection rules and investigation timeline |
| Sysmon | Detailed Windows event monitoring |
| Velociraptor | Endpoint artifact collection and hunting |
| Sigma Rules | Cross-platform detection rule format |
Common Scenarios
1. Scenario 1: Intelligence-driven hunt based on APT campaign report 2. Scenario 2: ATT&CK coverage gap analysis driving hypothesis creation 3. Scenario 3: Anomaly-driven hypothesis from UEBA alert investigation 4. Scenario 4: Situational awareness hunt based on industry sector threats
Output Format
Hunt ID: TH-BUILDI-[DATE]-[SEQ]
Technique: TA0001
Host: [Hostname]
User: [Account context]
Evidence: [Log entries, process trees, network data]
Risk Level: [Critical/High/Medium/Low]
Confidence: [High/Medium/Low]
Recommended Action: [Containment, investigation, monitoring]Building Threat Hunt Hypothesis Framework - Hunt Template
Hunt Metadata
| Field | Value |
|---|---|
| Hunt ID | TH-BUILDI-YYYY-MM-DD-NNN |
| Analyst | |
| Date Started | |
| Date Completed | |
| Status | [ ] In Progress / [ ] Complete |
| Priority | [ ] Critical / [ ] High / [ ] Medium / [ ] Low |
Hypothesis
Statement: [Formulate a clear, testable hypothesis]
>
Basis: [ ] Threat Intel / [ ] ATT&CK Gap / [ ] Anomaly / [ ] Incident Follow-up
Target Techniques
- [ ] TA0001 - Initial Access
- [ ] TA0003 - Persistence
- [ ] TA0008 - Lateral Movement
- [ ] TA0010 - Exfiltration
Data Sources
- [ ] Sysmon Event Logs
- [ ] Windows Security Event Logs
- [ ] EDR Telemetry (Platform: _____________)
- [ ] SIEM (Platform: _____________)
- [ ] Network Logs (Proxy/Firewall/DNS)
- [ ] Cloud Audit Logs
- [ ] Email Gateway Logs
- [ ] Application Logs
Queries Executed
Query 1: [Description]
[Query text]Results: [Count] events | Execution Time: [Duration]
Query 2: [Description]
[Query text]Results: [Count] events | Execution Time: [Duration]
Findings
| # | Timestamp | Host | User | Technique | Evidence Summary | Risk | Verdict |
|---|---|---|---|---|---|---|---|
| 1 | TP / FP / BTP | ||||||
| 2 | TP / FP / BTP | ||||||
| 3 | TP / FP / BTP |
IOCs Discovered
Network IOCs
| Type | Value | Context | Confidence |
|---|---|---|---|
| IP | |||
| Domain | |||
| URL |
Host IOCs
| Type | Value | Context | Confidence |
|---|---|---|---|
| SHA256 | |||
| Filename | |||
| Registry Key | |||
| Scheduled Task |
Hunt Results Summary
| Metric | Count |
|---|---|
| Total Events Analyzed | |
| Anomalies Identified | |
| True Positives | |
| False Positives | |
| Benign True Positives | |
| New IOCs Discovered | |
| Detection Rules Created | |
| Detection Rules Updated |
Hypothesis Outcome
- [ ] Confirmed: Evidence supports the hypothesis
- [ ] Partially Confirmed: Some evidence found, further investigation needed
- [ ] Refuted: No evidence found
- [ ] Inconclusive: Insufficient data
Recommendations
1. Immediate Actions: [Containment, remediation steps] 2. Detection Improvements: [New rules, tuning recommendations] 3. Visibility Gaps: [Missing data sources, coverage needs] 4. Security Hardening: [Configuration changes, policy updates] 5. Follow-up Hunts: [Related hypotheses to investigate]
Analyst Notes
[Free-form notes, observations, and lessons learned]
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Threat Hunt Hypothesis Framework
Hypothesis Structure
| Field | Description |
|---|---|
| hypothesis_id | Unique identifier (HYP-XXXXXXXX) |
| technique_id | MITRE ATT&CK technique (e.g. T1059.001) |
| hypothesis_statement | Natural language hypothesis |
| data_sources | Required log sources |
| priority | high / medium / low |
| status | planned / in_progress / completed |
MITRE ATT&CK Data Sources
# Download ATT&CK STIX bundle
curl -O https://raw.githubusercontent.com/mitre/cti/master/enterprise-attack/enterprise-attack.json
# Filter attack-pattern objects for technique data sources
python3 -c "
import json
bundle = json.load(open('enterprise-attack.json'))
for obj in bundle['objects']:
if obj.get('type') == 'attack-pattern' and not obj.get('x_mitre_deprecated'):
eid = obj['external_references'][0]['external_id']
ds = [d['source_name'] for d in obj.get('x_mitre_data_sources', [])]
print(f'{eid}: {ds}')
"Hunt Maturity Model (HMM)
| Level | Name | Description |
|---|---|---|
| HM0 | Initial | Ad hoc, no documented procedures |
| HM1 | Minimal | Basic procedures, limited data sources |
| HM2 | Procedural | Documented hypotheses, repeatable hunts |
| HM3 | Innovative | Custom analytics, TI-driven hypotheses |
| HM4 | Leading | Automated, ML-assisted, continuous hunting |
Key Windows Event IDs for Hunting
| Event ID | Source | Use Case |
|---|---|---|
| 4104 | PowerShell | Script block logging |
| 4688 | Security | Process creation |
| 4624/4625 | Security | Logon success/failure |
| 4698 | Security | Scheduled task created |
| 1 (Sysmon) | Sysmon | Process create with hashes |
| 3 (Sysmon) | Sysmon | Network connection |
| 10 (Sysmon) | Sysmon | Process access (LSASS) |
| 11 (Sysmon) | Sysmon | File create |
Sigma Rule Integration
title: Suspicious PowerShell Execution
status: experimental
logsource:
product: windows
service: powershell
detection:
selection:
EventID: 4104
ScriptBlockText|contains:
- 'Invoke-Mimikatz'
- 'Invoke-Expression'
condition: selection
level: highStandards and References - Building Threat Hunt Hypothesis Framework
MITRE ATT&CK Mappings
| Technique | Name | Description |
|---|---|---|
| TA0001 | Initial Access | See attack.mitre.org/techniques/TA0001 |
| TA0003 | Persistence | See attack.mitre.org/techniques/TA0003 |
| TA0008 | Lateral Movement | See attack.mitre.org/techniques/TA0008 |
| TA0010 | Exfiltration | See attack.mitre.org/techniques/TA0010 |
Detection Data Sources
| Source | Event ID | Purpose |
|---|---|---|
| Sysmon | 1 | Process creation with command line |
| Sysmon | 3 | Network connection initiated |
| Sysmon | 7 | Image loaded (DLL) |
| Sysmon | 10 | Process access (LSASS) |
| Sysmon | 11 | File creation |
| Sysmon | 12/13 | Registry create/set |
| Sysmon | 22 | DNS query |
| Sysmon | 25 | Process tampering |
| Windows Security | 4624 | Successful logon |
| Windows Security | 4625 | Failed logon |
| Windows Security | 4648 | Explicit credential logon |
| Windows Security | 4672 | Special privileges assigned |
| Windows Security | 4688 | Process creation |
| Windows Security | 4697 | Service installed |
| Windows Security | 4698 | Scheduled task created |
| Windows Security | 4769 | Kerberos TGS requested |
| Windows Security | 5140 | Network share accessed |
References
- MITRE ATT&CK Framework: https://attack.mitre.org/
- Sigma Detection Rules: https://github.com/SigmaHQ/sigma
- LOLBAS Project: https://lolbas-project.github.io/
- Atomic Red Team Tests: https://github.com/redcanaryco/atomic-red-team
- Red Canary Threat Detection Report
- SANS Threat Hunting Summit Resources
Detailed Hunting Workflow - Building Threat Hunt Hypothesis Framework
Phase 1: Data Collection and Querying
Splunk SPL Query
| makeresults
| eval hypothesis="Adversaries may be using [TECHNIQUE] to [OBJECTIVE] against [TARGET] via [VECTOR]"
| eval data_sources="[List required data sources]"
| eval queries="[Specific SPL queries to test hypothesis]"
| eval success_criteria="[What constitutes confirming/refuting hypothesis]"KQL Query (Microsoft Defender for Endpoint)
let HuntHypothesis = datatable(Component:string, Description:string)
[
"Technique", "MITRE ATT&CK technique being hunted",
"Target", "Systems or accounts in scope",
"Data Sources", "Logs and telemetry required",
"Indicators", "Observable evidence of technique",
"Success Criteria", "What confirms or refutes hypothesis"
];
HuntHypothesisPhase 2: Baseline and Anomaly Detection
Step 2.1 - Establish Normal Behavior Baseline
- Collect 30 days of historical data for the targeted technique
- Document expected patterns, frequencies, and legitimate use cases
- Identify known false positive sources and document exceptions
- Build statistical baseline (mean, standard deviation) for key metrics
Step 2.2 - Identify Anomalies
- Compare current activity against the 30-day baseline
- Flag events exceeding 3 standard deviations from normal
- Prioritize anomalies by risk score and potential business impact
- Cross-reference with threat intelligence for known IOCs
Phase 3: Investigation and Correlation
Step 3.1 - Deep Dive Analysis
- For each anomaly, collect full process tree context
- Correlate with network activity, file operations, and authentication events
- Check binary signatures, file hashes, and certificate validity
- Review user account context and access patterns
Step 3.2 - Attack Chain Reconstruction
- Map findings to MITRE ATT&CK kill chain stages
- Identify initial access vector if applicable
- Trace lateral movement and privilege escalation paths
- Determine data access and potential exfiltration
Phase 4: Validation and Response
Step 4.1 - True/False Positive Determination
- Verify findings with system owners and IT operations
- Check change management records for authorized activities
- Validate user context (authorized actions vs. compromised account)
- Document determination rationale for each finding
Step 4.2 - Response Actions
- For confirmed threats: initiate incident response procedures
- For detection gaps: create or update detection rules
- For false positives: tune existing rules and update exclusions
- Update threat hunting playbook with lessons learned
Phase 5: Documentation and Reporting
Step 5.1 - Hunt Report
- Summarize hypothesis, methodology, and findings
- Include all queries executed and their results
- Document IOCs discovered and detection rules created
- Provide recommendations for security improvements
Step 5.2 - Knowledge Base Update
- Add findings to threat intelligence platform
- Update MITRE ATT&CK coverage heatmap
- Share detection rules via Sigma format
- Schedule follow-up hunts for related techniques
#!/usr/bin/env python3
"""Threat hunt hypothesis framework builder.
Generates structured threat hunting hypotheses from MITRE ATT&CK techniques,
maps data sources, defines detection logic, and tracks hunt outcomes.
"""
import sys
import json
import datetime
import hashlib
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
HUNT_MATURITY_LEVELS = {
0: "Initial - ad hoc, no documentation",
1: "Minimal - basic procedures, limited data",
2: "Procedural - documented hypotheses, repeatable",
3: "Innovative - custom analytics, threat intel driven",
4: "Leading - automated, ML-assisted, continuous",
}
DATA_SOURCE_MAP = {
"T1059.001": {"name": "PowerShell", "sources": ["Script Block Logging (4104)", "Module Logging (4103)",
"Process Creation (4688/Sysmon 1)"], "log_channel": "Microsoft-Windows-PowerShell/Operational"},
"T1053.005": {"name": "Scheduled Task", "sources": ["Task Scheduler (4698/4702)", "Sysmon Event 1"],
"log_channel": "Microsoft-Windows-TaskScheduler/Operational"},
"T1078": {"name": "Valid Accounts", "sources": ["Logon Events (4624/4625)", "Kerberos (4768/4769)"],
"log_channel": "Security"},
"T1003.001": {"name": "LSASS Memory", "sources": ["Sysmon Event 10 (ProcessAccess)", "Windows Defender alerts"],
"log_channel": "Microsoft-Windows-Sysmon/Operational"},
"T1071.001": {"name": "Web Protocols C2", "sources": ["Proxy logs", "DNS query logs", "Zeek http.log"],
"log_channel": "Proxy/DNS"},
"T1486": {"name": "Data Encrypted for Impact", "sources": ["File creation burst (Sysmon 11)",
"Canary file triggers", "VSS deletion (Sysmon 1)"], "log_channel": "Sysmon"},
"T1021.001": {"name": "Remote Desktop Protocol", "sources": ["Logon Type 10 (4624)",
"RDP connection (1149)"], "log_channel": "Security / TerminalServices-RemoteConnectionManager"},
}
def generate_hypothesis(technique_id, threat_actor=None, environment=None):
"""Generate a structured threat hunting hypothesis."""
ds = DATA_SOURCE_MAP.get(technique_id, {})
technique_name = ds.get("name", technique_id)
hyp_id = "HYP-" + hashlib.md5(
(technique_id + str(datetime.datetime.utcnow())).encode()
).hexdigest()[:8].upper()
hypothesis = {
"hypothesis_id": hyp_id,
"created": datetime.datetime.utcnow().isoformat() + "Z",
"technique_id": technique_id,
"technique_name": technique_name,
"hypothesis_statement": (
"An adversary{} may be using {} ({}) within our environment{}. "
"Evidence of this activity can be found in {}.".format(
" (" + threat_actor + ")" if threat_actor else "",
technique_name,
technique_id,
" targeting " + environment if environment else "",
", ".join(ds.get("sources", ["endpoint telemetry"])),
)
),
"data_sources": ds.get("sources", []),
"log_channel": ds.get("log_channel", "Unknown"),
"priority": "high" if technique_id in ["T1003.001", "T1486", "T1059.001"] else "medium",
"status": "planned",
}
return hypothesis
def build_hunt_plan(hypotheses, analyst="SOC Analyst"):
"""Build a hunt plan from a list of hypotheses."""
plan = {
"plan_id": "PLAN-" + datetime.datetime.utcnow().strftime("%Y%m%d"),
"created": datetime.datetime.utcnow().isoformat() + "Z",
"analyst": analyst,
"maturity_level": 2,
"maturity_description": HUNT_MATURITY_LEVELS[2],
"hypothesis_count": len(hypotheses),
"hypotheses": hypotheses,
"data_coverage": list(set(
src for h in hypotheses for src in h.get("data_sources", [])
)),
"estimated_hours": len(hypotheses) * 4,
}
return plan
def evaluate_hunt_results(hypothesis, findings_count, true_positives, false_positives):
"""Evaluate hunt execution results and update hypothesis."""
hypothesis["status"] = "completed"
hypothesis["results"] = {
"total_findings": findings_count,
"true_positives": true_positives,
"false_positives": false_positives,
"precision": round(true_positives / max(findings_count, 1), 3),
"outcome": "confirmed" if true_positives > 0 else "not_confirmed",
"recommendation": (
"Create detection rule" if true_positives > 0
else "Refine hypothesis and re-hunt with broader data"
),
}
return hypothesis
def fetch_attack_techniques():
"""Fetch MITRE ATT&CK technique list."""
if not HAS_REQUESTS:
return list(DATA_SOURCE_MAP.keys())
try:
url = "https://raw.githubusercontent.com/mitre/cti/master/enterprise-attack/enterprise-attack.json"
resp = requests.get(url, timeout=30)
bundle = resp.json()
techniques = [
obj["external_references"][0]["external_id"]
for obj in bundle.get("objects", [])
if obj.get("type") == "attack-pattern"
and obj.get("external_references")
and not obj.get("x_mitre_deprecated", False)
]
return techniques[:50]
except Exception:
return list(DATA_SOURCE_MAP.keys())
if __name__ == "__main__":
print("=" * 60)
print("Threat Hunt Hypothesis Framework")
print("Hypothesis generation, hunt planning, result tracking")
print("=" * 60)
techniques = sys.argv[1:] if len(sys.argv) > 1 else ["T1059.001", "T1078", "T1003.001", "T1486"]
actor = "APT29"
hypotheses = []
for t in techniques:
h = generate_hypothesis(t, threat_actor=actor)
hypotheses.append(h)
plan = build_hunt_plan(hypotheses)
print("\nHunt Plan: {} ({} hypotheses, ~{} hours)".format(
plan["plan_id"], plan["hypothesis_count"], plan["estimated_hours"]))
print("Maturity: {}".format(plan["maturity_description"]))
print("\n--- Hypotheses ---")
for h in hypotheses:
print(" [{}] {} - {}".format(h["priority"].upper(), h["technique_id"], h["technique_name"]))
print(" {}".format(h["hypothesis_statement"][:120] + "..."))
print(" Sources: {}".format(", ".join(h["data_sources"][:3])))
evaluated = evaluate_hunt_results(hypotheses[0], findings_count=12, true_positives=3, false_positives=9)
print("\n--- Sample Result ---")
print(" {} precision: {} -> {}".format(
evaluated["technique_id"],
evaluated["results"]["precision"],
evaluated["results"]["recommendation"]))
print("\n" + json.dumps({"hypotheses_generated": len(hypotheses)}, indent=2))
#!/usr/bin/env python3
"""Threat Hunt Hypothesis Detection - Analyzes logs for TA0001 indicators."""
import json, csv, argparse, datetime, re
from collections import defaultdict
from pathlib import Path
DETECTION_PATTERNS = [
# Framework skill - no detection patterns
]
def parse_logs(path):
p = Path(path)
if p.suffix == ".json":
with open(p, encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, list) else data.get("events", [])
elif p.suffix == ".csv":
with open(p, encoding="utf-8-sig") as f:
return [dict(r) for r in csv.DictReader(f)]
return []
def analyze_event(event):
cmd = event.get("CommandLine", event.get("command_line", event.get("ProcessCommandLine", "")))
content = event.get("Task_Content", event.get("Parameters", event.get("RawEventData", "")))
search_text = f"{cmd} {content}"
risk = 0
indicators = []
for pattern in DETECTION_PATTERNS:
if re.search(pattern, search_text, re.IGNORECASE):
risk += 25
indicators.append(f"Pattern match: {pattern}")
if not indicators:
return None
risk = min(risk, 100)
return {
"technique": "TA0001",
"command_line": cmd[:500] if cmd else content[:500],
"hostname": event.get("Computer", event.get("DeviceName", event.get("hostname", "unknown"))),
"user": event.get("User", event.get("AccountName", event.get("UserId", "unknown"))),
"timestamp": event.get("_time", event.get("timestamp", event.get("UtcTime", event.get("Timestamp", "")))),
"risk_score": risk,
"risk_level": "CRITICAL" if risk >= 75 else "HIGH" if risk >= 50 else "MEDIUM" if risk >= 25 else "LOW",
"indicators": indicators,
}
def run_hunt(input_path, output_dir):
print(f"[*] Threat Hunt Hypothesis Hunt - {datetime.datetime.now().isoformat()}")
events = parse_logs(input_path)
findings = [f for f in (analyze_event(e) for e in events) if f]
Path(output_dir).mkdir(parents=True, exist_ok=True)
slug = "building_threat_hunt"
with open(Path(output_dir) / f"{slug}_findings.json", "w", encoding="utf-8") as f:
json.dump({"hunt_id": f"TH-{datetime.date.today()}", "total_events": len(events), "findings": findings}, f, indent=2)
with open(Path(output_dir) / "hunt_report.md", "w", encoding="utf-8") as f:
f.write(f"# Threat Hunt Hypothesis Hunt Report\n\n")
f.write(f"**Date**: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"**Findings**: {len(findings)}\n\n")
for finding in sorted(findings, key=lambda x: x["risk_score"], reverse=True)[:20]:
f.write(f"### [{finding['risk_level']}] {finding['technique']}\n")
f.write(f"- **Host**: {finding['hostname']}\n")
f.write(f"- **Indicators**: {', '.join(finding['indicators'])}\n\n")
print(f"[+] {len(findings)} findings written to {output_dir}")
def main():
p = argparse.ArgumentParser(description="Threat Hunt Hypothesis Detection")
sp = p.add_subparsers(dest="cmd")
h = sp.add_parser("hunt"); h.add_argument("--input", "-i", required=True); h.add_argument("--output", "-o", default="./building_threat_output")
sp.add_parser("queries")
args = p.parse_args()
if args.cmd == "hunt": run_hunt(args.input, args.output)
elif args.cmd == "queries":
print("=== Detection Queries ===")
print("See references/workflows.md for platform-specific queries")
else: p.print_help()
if __name__ == "__main__": main()