1. Pengenalan Threat Hunting
Threat Hunting adalah proses proaktif untuk mencari indikator serangan tersembunyi yang tidak terdeteksi tools otomatis. Mengasumsikan attacker sudah ada di dalam jaringan.
- Hypothesis-driven threat hunting
- MITRE ATT&CK framework mapping
- IOC dan IOA hunting
- Behavioral analytics
- Membangun hunting program
Rata-rata waktu deteksi breach adalah 197 hari. Automated tools hanya mendeteksi sebagian ancaman. Threat hunting menutup gap ini dengan pendekatan proaktif yang dipimpin analis manusia.
2. Hypothesis-Driven Hunting
Pendekatan dimulai dengan hipotesis tentang bagaimana attacker beroperasi, lalu mengumpulkan data untuk membuktikan atau menyanggah.
# ============================================= +# Threat Hunting Hypothesis Template +# ============================================= +# HYPOTHESIS 1: Lateral Movement via PsExec +# ------------------------------------------------ +# Premise: Attacker menggunakan PsExec untuk +# bergerak lateral setelah akses awal +# +# Expected Evidence: +# - Event ID 7045 (service installation) PsExec +# - Event ID 4624 Type 3 logon dari unusual source +# - Named pipe \*\pipe\psexecsvc +# +# Query: +index=windows (EventCode=7045 AND Image="*PSEXESVC*") + OR (EventCode=4624 AND Logon_Type=3) +| stats count by ComputerName, Account_Name, IpAddress +| where count > 3 +# HYPOTHESIS 2: DNS Tunneling for Exfiltration +# ------------------------------------------------ +# Premise: Attacker menggunakan DNS untuk C2/exfil +# +# Query: +index=dns +| eval query_len=len(query) +| where query_len > 50 +| stats count avg(query_len) as avg_len + by dest +| where count > 100 AND avg_len > 50
3. MITRE ATT&CK Mapping
MITRE ATT&CK mendokumentasikan TTP (Tactics, Techniques, Procedures) attacker. Mapping hunting ke ATT&CK memastikan coverage komprehensif.
| Tactic | Technique | Hunting Focus |
|---|---|---|
| Initial Access | T1566 Phishing | Email attachments, URLs |
| Execution | T1059 Command/Script | PowerShell, WMI |
| Persistence | T1053 Scheduled Task | New tasks, registry keys |
| Priv Escalation | T1068 Exploitation | Unusual process parents |
| Defense Evasion | T1070 Indicator Removal | Log clearing, timestomping |
| Credential Access | T1003 Credential Dump | LSASS access |
| Lateral Movement | T1021 Remote Services | RDP, SMB, PsExec |
| Exfiltration | T1048 Exfiltration | Large outbound, DNS tunnel |
4. IOC-Based Hunting
IOC hunting mencari artifact spesifik yang terkait serangan — IP, domain, file hash, atau registry key.
# =============================================
+# IOC Hunting Queries
+# =============================================
+# 1. Known malicious IPs
+| inputlookup threat_intel_ips.csv
+| join type=inner ip [
+ search index=network sourcetype=firewall
+ | fields src_ip, dest_ip
+ | rename dest_ip as ip
+ ]
+# 2. File hash hunting
+index=sysmon EventCode=1
+| where hash IN ("abc123...", "def456...")
+| table _time, Computer, User, Image, hash
+# 3. Registry persistence
+index=sysmon EventCode=13
+| where TargetObject LIKE "%CurrentVersion\Run%"
+| table _time, Computer, TargetObject, Details
+# 4. PowerShell encoded command
+index=windows EventCode=4104
+| where ScriptBlockText LIKE "%-enc%"
+ OR ScriptBlockText LIKE "%FromBase64String%"
+| table _time, Computer, ScriptBlockText
5. Behavioral Analytics
Mencari anomali perilaku yang menyimpang dari baseline, mengindikasikan kompromi tanpa IOC yang diketahui.
# ============================================= +# Behavioral Analytics Hunting +# ============================================= +# 1. Impossible travel detection +index=auth sourcetype=* +| iplocation src_ip +| stats earliest(_time) as first, + latest(_time) as last, + values(Country) as countries + by user +| where mvcount(countries) > 1 +| eval time_diff = last - first +| where time_diff < 3600 +# 2. Unusual process tree +index=sysmon EventCode=1 +| stats values(ParentImage) as parents by Image +| where mvcount(parents) > 1 +| where match(Image, "cmd|powershell|wscript") +# 3. Beaconing detection +index=proxy +| bin _time span=1h +| stats count by _time, dest_domain +| eventstats avg(count) as avg_count, + stdev(count) as std_count by dest_domain +| where count > avg_count + (3 * std_count)
6. Hunting Techniques
Stacking (Frequency Analysis)
Menemukan anomali dengan menghitung frekuensi kemunculan. Nilai yang sangat jarang layak diperiksa.
# ============================================= +# Stacking Analysis +# ============================================= +# Rare process names +index=sysmon EventCode=1 +| rare limit=20 Image by Computer +# Rare parent-child combinations +index=sysmon EventCode=1 +| eval combo=ParentImage." -> ".Image +| rare limit=20 combo +# Rare user-agent strings +index=proxy +| rare limit=20 user_agent +# Rare service installations +index=windows EventCode=7045 +| rare limit=20 ServiceName, ImagePath
7. Hunting Tools & Infrastructure
| Category | Tools | Purpose |
|---|---|---|
| SIEM | Splunk, Elastic, Sentinel | Centralized log & query |
| Threat Intel | MISP, OpenCTI, OTX | IOC feeds & enrichment |
| Endpoint | Sysmon, OSQuery, Velociraptor | Deep endpoint visibility |
| Network | Zeek, Suricata, RITA | Network traffic analysis |
| Sandbox | Cuckoo, ANY.RUN, CAPE | Malware analysis |
8. Hunting Maturity Model
| Level | Description | Capabilities |
|---|---|---|
| HM0 | Initial | Hanya automated alert, no hunting |
| HM1 | Minimal | IOC-based, minimal data |
| HM2 | Procedural | Documented procedures, regular hunts |
| HM3 | Innovative | Hypothesis-driven, custom analytics |
| HM4 | Leading | ML-assisted, automated, continuous |
Hunting with YARA Rules
YARA adalah pattern matching tool yang sangat powerful untuk mengidentifikasi dan mengkategorikan malware samples. Dalam threat hunting, YARA digunakan untuk scanning endpoint dan memory.
# =============================================
+# YARA Rules untuk Threat Hunting
+# =============================================
+# Detect Cobalt Strike Beacon
+rule CobaltStrike_Beacon {
+ meta:
+ description = "Detects Cobalt Strike Beacon"
+ author = "Threat Hunter"
+ severity = "high"
+ strings:
+ $beacon_config = { 00 01 00 01 00 02 ?? ?? 00 02 00 01 00 02 ?? ?? }
+ $pipe = "\\.\pipe\msagent_" ascii
+ $sleep_mask = { 4C 8B 53 08 45 8B 0A 45 8B 5A 04 4D 8D 52 08 45 85 C9 }
+ condition:
+ uint16(0) == 0x5A4D and 2 of them
+}
+# Detect suspicious PowerShell patterns
+rule Suspicious_PowerShell_Hunting {
+ meta:
+ description = "Suspicious PowerShell for hunting"
+ strings:
+ $enc1 = "-EncodedCommand" nocase
+ $enc2 = "-enc " nocase
+ $bypass = "Set-ExecutionPolicy Bypass" nocase
+ $download = "DownloadString" nocase
+ $download2 = "DownloadFile" nocase
+ $invoke = "IEX" nocase
+ $hidden = "-WindowStyle Hidden" nocase
+ $amsi = "AmsiUtils" nocase
+ $etw = "ETW" nocase
+ condition:
+ 3 of them
+}
+# Hunting on endpoints with YARA
+# Scan running processes
+yara64 -p 20 rules.yar /proc/*/mem
+# Scan files on disk
+yara64 -r rules.yar /home/ /tmp/ /var/
+# Scan with Velociraptor
+# VQL: SELECT * FROM glob(globs="/**/*.{exe,dll,sys}")
+# WHERE yara(file=FullPath, rules=yara_rules)
Memory Forensics for Hunting
Memory forensik sangat penting untuk threat hunting karena banyak malware yang hanya hidup di memory (fileless malware). Tool seperti Volatility memungkinkan analisis memory dump.
# ============================================= +# Memory Forensics untuk Threat Hunting +# ============================================= +# 1. Capture memory (Windows) +# Using WinPmem +winpmem_mini_x64.exe memdump.raw +# Using DumpIt +DumpIt.exe +# 2. Capture memory (Linux) +sudo dd if=/dev/mem of=/tmp/memdump.raw bs=1M +# Or using AVML +sudo ./avml /tmp/memdump.raw +# 3. Analyze with Volatility 3 +# List processes +vol -f memdump.raw windows.pslist +# Detect hidden processes +vol -f memdump.raw windows.psscan +# Network connections +vol -f memdump.raw windows.netscan +# Command line arguments +vol -f memdump.raw windows.cmdline +# DLLs loaded by process +vol -f memdump.raw windows.dlls --pid 1234 +# Injected code detection +vol -f memdump.raw windows.malfind +# Extract suspicious process +vol -f memdump.raw windows.memmap --pid 1234 --dump +# 4. Scan memory dump with YARA +vol -f memdump.raw windows.vadyarascan \ + --yara-rules hunting_rules.yar
Network-Based Hunting
Network traffic analysis mengungkap komunikasi C2, data exfiltration, dan lateral movement yang mungkin tidak terlihat di endpoint logs.
# =============================================
+# Network Hunting dengan Zeek (Bro)
+# =============================================
+# 1. Detect DNS tunneling
+zeek -r capture.pcap dns_tunnel_detect.zeek
+# dns_tunnel_detect.zeek content:
+# @load base/frameworks/notice
+# module DNS_TUNNEL;
+# export {
+# redef enum Notice::Type += {
+# Long_DNS_Query,
+# High_DNS_Volume
+# };
+# }
+# event dns_request(c: connection, msg: dns_msg, query: string) {
+# if (|query| > 50) {
+# NOTICE([
+# $note=Long_DNS_Query,
+# $conn=c,
+# $msg=fmt("Long DNS query: %s", query)
+# ]);
+# }
+# }
+# 2. JA3/JA3S fingerprinting (TLS)
+# Detect C2 frameworks by TLS fingerprint
+zeek -r capture.pcap ja3.zeek
+# Compare JA3 hashes against known C2 hashes
+# 3. Beaconing detection with RITA
+rita import capture.pcap hunting_db
+rita show-beacons hunting_db
+# High scores indicate regular communication patterns (C2)
+# 4. Analyze with tshark
+# DNS query analysis
+tshark -r capture.pcap -Y "dns" \
+ -T fields -e dns.qry.name -e dns.qry.type \
+ | sort | uniq -c | sort -rn | head -50
Hunting Playbooks
+Hunting playbook mendokumentasikan prosedur berburu yang dapat direplikasi. Setiap playbook terdiri dari hipotesis, data sources, queries, dan triage criteria.
+# ============================================= +# Hunting Playbook: Credential Dumping +# ============================================= +# PLAYBOOK ID: HP-001 +# TITLE: LSASS Memory Access Detection +# ATT&CK: T1003.001 (OS Credential Dumping) +# PRIORITY: High +# ESTIMATED TIME: 2-4 hours +# HYPOTHESIS: +# Attacker yang sudah mendapatkan akses ke endpoint +# mungkin menggunakan credential dumping tools untuk +# mencumpah LSASS memory dan mendapatkan NTLM hashes. +# DATA SOURCES: +# 1. Sysmon Event ID 10 (Process Access) +# 2. Windows Security Event ID 4688 (Process Create) +# 3. EDR telemetry (CrowdStrike, SentinelOne) +# DETECTION QUERIES: +# Query 1: Sysmon LSASS access +index=sysmon EventCode=10 + TargetImage="*\lsass.exe" +| where SourceImage != "*\svchost.exe" + AND SourceImage != "*\csrss.exe" + AND SourceImage != "*\services.exe" +| table _time, Computer, SourceImage, GrantedAccess +# Query 2: Suspicious parent processes +index=windows EventCode=4688 + NewProcessName="*\lsass.exe" +| where ParentProcessName != "wininit.exe" +| table _time, Computer, NewProcessName, ParentProcessName +# Query 3: Known tool signatures +index=* (mimikatz OR sekurlsa OR pypykatz + OR "dumpert" OR "handlekatz") +| table _time, Computer, _raw +# TRIAGE CRITERIA: +# CONFIRMED if: +# - GrantedAccess contains 0x1010 or 0x1410 +# - SourceImage is not a known legitimate process +# - Correlated with EDR credential access alert +# +# FALSE POSITIVE if: +# - SourceImage is antivirus/EDR scanner +# - Occurs during scheduled security scan +# - SourceImage is legitimate admin tool with audit trail +# RESPONSE ACTIONS: +# 1. Isolate affected endpoint +# 2. Capture memory dump for analysis +# 3. Force password reset for all accounts +# that were logged into the endpoint +# 4. Check for lateral movement using +# compromised credentials+
Automating Hunts with Jupyter Notebooks
+Jupyter Notebooks sangat baik untuk threat hunting karena mendukung iteraktif data analysis, visualisasi, dan dokumentasi dalam satu file.
+# =============================================
+# Threat Hunting Jupyter Notebook
+# =============================================
+# Cell 1: Import libraries
+import pandas as pd
+import matplotlib.pyplot as plt
+from datetime import datetime, timedelta
+import numpy as np
+# Cell 2: Load data from SIEM export
+df = pd.read_csv('windows_logons_30d.csv',
+ parse_dates=['timestamp'])
+# Cell 3: Impossible travel detection
+# Group by user, find logons from different countries
+def detect_impossible_travel(df, max_hours=2):
+ users = df.groupby('username')
+ alerts = []
+ for user, group in users:
+ group = group.sort_values('timestamp')
+ for i in range(1, len(group)):
+ curr = group.iloc[i]
+ prev = group.iloc[i-1]
+ time_diff = (curr['timestamp'] -
+ prev['timestamp']).total_seconds() / 3600
+ if (curr['country'] != prev['country']
+ and time_diff < max_hours):
+ alerts.append({
+ 'user': user,
+ 'from': prev['country'],
+ 'to': curr['country'],
+ 'hours': round(time_diff, 1),
+ 'risk': 'HIGH'
+ })
+ return pd.DataFrame(alerts)
+alerts = detect_impossible_travel(df)
+print(f"Found {len(alerts)} impossible travel alerts")
+alerts.head(20)
+# Cell 4: Visualize logon patterns
+df.groupby(df['timestamp'].dt.hour).size().plot(
+ kind='bar', title='Logons by Hour')
+plt.xlabel('Hour')
+plt.ylabel('Count')
+plt.show()
+# Cell 5: Rare process execution
+process_counts = df['process_name'].value_counts()
+rare = process_counts[process_counts < 5]
+print(f"Rare processes (<5 occurrences): {len(rare)}")
+rare.head(20)
+ Hunting Metrics & Reporting
+| Metric | Description | Target |
|---|---|---|
| Hunts/month | Jumlah hunting yang dilakukan | >= 4 per bulan |
| True positive rate | % hunts yang menemukan ancaman nyata | >= 20% |
| Time to hunt | Rata-rata waktu per hunting session | 2-4 jam |
| New detections | Detection baru yang dibuat dari hunting | >= 2 per bulan |
| ATT&CK coverage | % teknik yang sudah di-hunt | >= 50% |
9. Quiz Pemahaman
1. Perbedaan threat hunting dan SOC monitoring?
2. Apa itu MITRE ATT&CK?
3. Teknik 'stacking' dalam hunting?
4. Perbedaan IOC dan IOA?
5. Level hypothesis-driven approach di HMM?
Rangkuman
- Proaktif — Mengasumsikan attacker sudah di dalam, tidak menunggu alert
- Hypothesis — Pendekatan dimulai dari hipotesis tentang TTP attacker
- MITRE ATT&CK — Framework mapping untuk coverage komprehensif
- Behavioral — Anomali detection tanpa IOC — impossible travel, beaconing
- Maturity — HM0-HM4 — progres dari automated-only ke ML-assisted hunting