构建自动化恶意软件提交管道 是做什么的?
何时使用
在以下场景中使用此技能:
- 安全运营中心团队面对大量可疑文件告警,需要进行沙箱分析
- 手动沙箱提交成为告警分类工作流的瓶颈
- 端点安全和邮件安全工具隔离了文件,需要自动判定
- 事件响应需要快速识别恶意软件家族和提取失陷指标
不要使用此技能在生产环境中分析真实恶意软件样本——始终使用隔离的沙箱基础设施。
前提条件
- 沙箱环境:Cuckoo Sandbox、Joe Sandbox、Any.Run 或 VMRay
- VirusTotal API 密钥(企业版用于提交,免费版用于查询)
- MalwareBazaar API 访问权限(用于已知恶意软件查询)
- 文件收集机制:EDR 隔离 API、邮件网关导出、网络抓包
- Python 3.8+,并安装
requests、vt-py、pefile库 - 隔离的分析网络,不与生产环境相连
工作流
步骤 1:构建文件收集管道
从多个来源收集可疑文件:
import requests
import hashlib
import os
from pathlib import Path
from datetime import datetime
class MalwareCollector:
def __init__(self, quarantine_dir="/opt/malware_quarantine"):
self.quarantine_dir = Path(quarantine_dir)
self.quarantine_dir.mkdir(exist_ok=True)
def collect_from_edr(self, edr_api_url, api_token):
"""从 CrowdStrike Falcon 拉取隔离文件"""
headers = {"Authorization": f"Bearer {api_token}"}
# 获取最近的隔离事件
response = requests.get(
f"{edr_api_url}/quarantine/queries/quarantined-files/v1",
headers=headers,
params={"filter": "state:'quarantined'", "limit": 50}
)
file_ids = response.json()["resources"]
for file_id in file_ids:
# 下载隔离文件
dl_response = requests.get(
f"{edr_api_url}/quarantine/entities/quarantined-files/v1",
headers=headers,
params={"ids": file_id}
)
file_data = dl_response.content
sha256 = hashlib.sha256(file_data).hexdigest()
filepath = self.quarantine_dir / f"{sha256}.sample"
filepath.write_bytes(file_data)
yield {"sha256": sha256, "path": str(filepath), "source": "edr"}
def collect_from_email_gateway(self, smtp_quarantine_path):
"""从邮件网关隔离区拉取附件"""
import email
from email import policy
for eml_file in Path(smtp_quarantine_path).glob("*.eml"):
msg = email.message_from_binary_file(
eml_file.open("rb"), policy=policy.default
)
for attachment in msg.iter_attachments():
content = attachment.get_content()
if isinstance(content, str):
content = content.encode()
sha256 = hashlib.sha256(content).hexdigest()
filename = attachment.get_filename() or "unknown"
filepath = self.quarantine_dir / f"{sha256}.sample"
filepath.write_bytes(content)
yield {
"sha256": sha256,
"path": str(filepath),
"source": "email",
"original_filename": filename,
"sender": msg["From"],
"subject": msg["Subject"]
}
def compute_hashes(self, filepath):
"""计算文件的 MD5、SHA1、SHA256 哈希值"""
with open(filepath, "rb") as f:
content = f.read()
return {
"md5": hashlib.md5(content).hexdigest(),
"sha1": hashlib.sha1(content).hexdigest(),
"sha256": hashlib.sha256(content).hexdigest(),
"size": len(content)
}
步骤 2:通过哈希查询进行预筛查
在提交沙箱之前,检查文件是否已知:
import vt
class MalwarePreScreener:
def __init__(self, vt_api_key, mb_api_url="https://mb-api.abuse.ch/api/v1/"):
self.vt_client = vt.Client(vt_api_key)
self.mb_api_url = mb_api_url
def check_virustotal(self, sha256):
"""在 VirusTotal 中查找哈希值"""
try:
file_obj = self.vt_client.get_object(f"/files/{sha256}")
stats = file_obj.last_analysis_stats
return {
"found": True,
"malicious": stats.get("malicious", 0),
"suspicious": stats.get("suspicious", 0),
"undetected": stats.get("undetected", 0),
"total": sum(stats.values()),
"threat_label": getattr(file_obj, "popular_threat_classification", {}).get(
"suggested_threat_label", "Unknown"
),
"type": getattr(file_obj, "type_description", "Unknown")
}
except vt.APIError:
return {"found": False}
def check_malwarebazaar(self, sha256):
"""在 MalwareBazaar 中查找哈希值"""
response = requests.post(
self.mb_api_url,
data={"query": "get_info", "hash": sha256}
)
data = response.json()
if data["query_status"] == "ok":
entry = data["data"][0]
return {
"found": True,
"signature": entry.get("signature", "Unknown"),
"tags": entry.get("tags", []),
"file_type": entry.get("file_type", "Unknown"),
"first_seen": entry.get("first_seen", "Unknown")
}
return {"found": False}
def pre_screen(self, sha256):
"""运行所有预筛查检查"""
vt_result = self.check_virustotal(sha256)
mb_result = self.check_malwarebazaar(sha256)
verdict = "UNKNOWN"
if vt_result["found"] and vt_result.get("malicious", 0) > 10:
verdict = "KNOWN_MALICIOUS"
elif vt_result["found"] and vt_result.get("malicious", 0) == 0:
verdict = "LIKELY_CLEAN"
return {
"sha256": sha256,
"virustotal": vt_result,
"malwarebazaar": mb_result,
"pre_screen_verdict": verdict,
"needs_sandbox": verdict == "UNKNOWN"
}
def close(self):
self.vt_client.close()
步骤 3:提交至沙箱进行动态分析
Cuckoo Sandbox 提交:
class SandboxSubmitter:
def __init__(self, cuckoo_url="http://cuckoo.internal:8090"):
self.cuckoo_url = cuckoo_url
def submit_to_cuckoo(self, filepath, timeout=300):
"""提交文件到 Cuckoo Sandbox"""
with open(filepath, "rb") as f:
response = requests.post(
f"{self.cuckoo_url}/tasks/create/file",
files={"file": f},
data={
"timeout": timeout,
"options": "procmemdump=yes,route=none",
"priority": 2,
"machine": "win10_x64"
}
)
task_id = response.json()["task_id"]
return task_id
def wait_for_analysis(self, task_id, poll_interval=30, max_wait=600):
"""等待沙箱分析完成"""
import time
elapsed = 0
while elapsed < max_wait:
response = requests.get(f"{self.cuckoo_url}/tasks/view/{task_id}")
status = response.json()["task"]["status"]
if status == "reported":
return self.get_report(task_id)
elif status == "failed_analysis":
return {"error": "Analysis failed"}
time.sleep(poll_interval)
elapsed += poll_interval
return {"error": "Analysis timed out"}
def get_report(self, task_id):
"""获取分析报告"""
response = requests.get(f"{self.cuckoo_url}/tasks/report/{task_id}")
report = response.json()
# 提取关键指标
return {
"task_id": task_id,
"score": report.get("info", {}).get("score", 0),
"signatures": [
{"name": s["name"], "severity": s["severity"], "description": s["description"]}
for s in report.get("signatures", [])
],
"network": {
"dns": [d["request"] for d in report.get("network", {}).get("dns", [])],
"http": [
{"url": h["uri"], "method": h["method"]}
for h in report.get("network", {}).get("http", [])
],
"hosts": report.get("network", {}).get("hosts", [])
},
"dropped_files": [
{"name": f["name"], "sha256": f["sha256"], "size": f["size"]}
for f in report.get("dropped", [])
],
"processes": [
{"name": p["process_name"], "pid": p["pid"], "command_line": p.get("command_line", "")}
for p in report.get("behavior", {}).get("processes", [])
],
"registry_keys": [
k for k in report.get("behavior", {}).get("summary", {}).get("regkey_written", [])
]
}
def submit_to_joesandbox(self, filepath, joe_api_key, joe_url="https://jbxcloud.joesecurity.org/api"):
"""提交到 Joe Sandbox Cloud"""
with open(filepath, "rb") as f:
response = requests.post(
f"{joe_url}/v2/submission/new",
headers={"Authorization": f"Bearer {joe_api_key}"},
files={"sample": f},
data={
"systems": "w10_64",
"internet-access": False,
"report-cache": True
}
)
return response.json()["data"]["webid"]
步骤 4:提取 IOC 并生成判定
class VerdictGenerator:
def __init__(self):
self.malicious_threshold = 7 # Cuckoo 分数阈值
def generate_verdict(self, pre_screen, sandbox_report):
"""结合预筛查和沙箱结果,生成最终判定"""
iocs = {
"ips": [],
"domains": [],
"urls": [],
"hashes": [],
"registry_keys": [],
"files_dropped": []
}
# 从沙箱提取 IOC
if sandbox_report:
iocs["domains"] = sandbox_report.get("network", {}).get("dns", [])
iocs["ips"] = sandbox_report.get("network", {}).get("hosts", [])
iocs["urls"] = [
h["url"] for h in sandbox_report.get("network", {}).get("http", [])
]
iocs["hashes"] = [
f["sha256"] for f in sandbox_report.get("dropped_files", [])
]
iocs["registry_keys"] = sandbox_report.get("registry_keys", [])[:10]
iocs["files_dropped"] = sandbox_report.get("dropped_files", [])
# 判定
vt_malicious = pre_screen.get("virustotal", {}).get("malicious", 0)
sandbox_score = sandbox_report.get("score", 0) if sandbox_report else 0
sig_count = len(sandbox_report.get("signatures", [])) if sandbox_report else 0
combined_score = (vt_malicious * 2) + (sandbox_score * 10) + (sig_count * 5)
if combined_score >= 100:
verdict = "MALICIOUS"
confidence = "HIGH"
elif combined_score >= 50:
verdict = "SUSPICIOUS"
confidence = "MEDIUM"
elif combined_score >= 20:
verdict = "POTENTIALLY_UNWANTED"
confidence = "LOW"
else:
verdict = "CLEAN"
confidence = "HIGH"
return {
"verdict": verdict,
"confidence": confidence,
"combined_score": combined_score,
"iocs": iocs,
"vt_detections": vt_malicious,
"sandbox_score": sandbox_score,
"signatures": sandbox_report.get("signatures", []) if sandbox_report else []
}
步骤 5:将结果推送到 SIEM
def push_to_splunk(verdict_result, splunk_url, splunk_token):
"""将恶意软件分析判定发送到 Splunk HEC"""
import json
event = {
"sourcetype": "malware_analysis",
"source": "malware_pipeline",
"event": {
"sha256": verdict_result["sha256"],
"verdict": verdict_result["verdict"],
"confidence": verdict_result["confidence"],
"score": verdict_result["combined_score"],
"vt_detections": verdict_result["vt_detections"],
"sandbox_score": verdict_result["sandbox_score"],
"malware_family": verdict_result.get("threat_label", "Unknown"),
"iocs": verdict_result["iocs"],
"signatures": [s["name"] for s in verdict_result["signatures"]]
}
}
response = requests.post(
f"{splunk_url}/services/collector/event",
headers={
"Authorization": f"Splunk {splunk_token}",
"Content-Type": "application/json"
},
json=event,
verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true", # 在实验室环境中使用自签名证书时,设置 SKIP_TLS_VERIFY=true
)
return response.status_code == 200
def push_iocs_to_blocklist(iocs, firewall_api):
"""将提取的 IOC 推送到阻断基础设施"""
for ip in iocs.get("ips", []):
requests.post(
f"{firewall_api}/block",
json={"type": "ip", "value": ip, "action": "block", "source": "malware_pipeline"}
)
for domain in iocs.get("domains", []):
requests.post(
f"{firewall_api}/block",
json={"type": "domain", "value": domain, "action": "sinkhole", "source": "malware_pipeline"}
)
步骤 6:编排完整管道
def run_pipeline():
# 初始化组件
collector = MalwareCollector()
screener = MalwarePreScreener(vt_api_key=os.environ["VT_API_KEY"])
submitter = SandboxSubmitter()
verdict_gen = VerdictGenerator()
# 步骤 1:收集文件
for file_info in collector.collect_from_edr("https://api.crowdstrike.com", "your_token"):
sha256 = file_info["sha256"]
# 步骤 2:预筛查
screen_result = screener.pre_screen(sha256)
if screen_result["needs_sandbox"]:
# 步骤 3:提交到沙箱
task_id = submitter.submit_to_cuckoo(file_info["path"])
sandbox_report = submitter.wait_for_analysis(task_id)
# 步骤 4:生成判定
verdict = verdict_gen.generate_verdict(screen_result, sandbox_report)
# 步骤 5:推送到 SIEM 和阻断
push_to_splunk(verdict, "https://splunk.internal:8088", "your_token")
if verdict["verdict"] in ["MALICIOUS", "SUSPICIOUS"]:
push_iocs_to_blocklist(verdict["iocs"], "https://firewall-api.internal")
screener.close()
if __name__ == "__main__":
run_pipeline()
配置环境变量
export VT_API_KEY="your_virustotal_enterprise_key"
export SPLUNK_HEC_TOKEN="your_splunk_hec_token"
export SPLUNK_URL="https://splunk.internal:8088"
export JOE_API_KEY="your_joesandbox_key"
export MB_API_KEY="your_malwarebazaar_key" # 可选
export SKIP_TLS_VERIFY="false" # 对于实验室中的自签名证书设置为 true
安全注意事项
- 始终在专用的隔离分析环境中运行此管道
- 不要在最终用户系统上处理实时恶意软件
- 使用最小权限原则配置 API 密钥
- 启用 HTTPS 加密所有 API 通信
- 定期轮换 API 密钥和令牌
- 审计所有调用沙箱系统的访问
- 避免将恶意软件样本存储在不安全的共享位置