Spaces:
Running
Running
File size: 9,723 Bytes
567eb03 c43a9f9 567eb03 c43a9f9 567eb03 54559aa 567eb03 c43a9f9 dd1eee1 c43a9f9 dd1eee1 c43a9f9 dd1eee1 c43a9f9 dd1eee1 c43a9f9 dd1eee1 c43a9f9 dd1eee1 c43a9f9 dd1eee1 c43a9f9 dd1eee1 c43a9f9 567eb03 c43a9f9 567eb03 c43a9f9 567eb03 c43a9f9 567eb03 54559aa 567eb03 54559aa 567eb03 dd1eee1 c43a9f9 567eb03 c43a9f9 567eb03 c43a9f9 dd1eee1 c43a9f9 567eb03 c43a9f9 567eb03 c43a9f9 567eb03 c43a9f9 567eb03 c43a9f9 567eb03 54559aa 567eb03 c43a9f9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | """MalwareBazaar threat intelligence service from abuse.ch."""
import logging
import re
from typing import Any
import requests
from src.config import settings
from src.exceptions import ExternalAPIError
from src.services.base import BaseThreatIntelService
logger = logging.getLogger(__name__)
# MITRE technique pattern
MITRE_PATTERN = re.compile(r"\bT\d{4}(?:\.\d{3})?\b")
# APT patterns
APT_PATTERNS = [
r"\bAPT[-\s]?\d+\b",
r"\bFIN\d+\b",
r"\bTA\d+\b",
r"\bUNC\d+\b",
r"\bLazarus\b",
r"\bKimsuky\b",
r"\bConti\b",
r"\bREvil\b",
r"\bLockBit\b",
r"\bBlackCat\b",
r"\bALPHV\b",
]
class MalwareBazaarService(BaseThreatIntelService):
"""
Service for interacting with MalwareBazaar API.
MalwareBazaar is a project from abuse.ch that shares malware samples
with the security community. Supports hash lookups (MD5, SHA1, SHA256).
"""
def __init__(self, api_key: str | None = None):
"""
Initialize MalwareBazaar service.
Args:
api_key: abuse.ch API key (optional but recommended for higher rate limits)
"""
api_key = api_key or settings.ABUSE_CH_API_KEY
super().__init__(api_key=api_key)
@property
def provider_name(self) -> str:
return "MalwareBazaar"
@property
def base_url(self) -> str:
return "https://mb-api.abuse.ch/api/v1"
def _get_headers(self) -> dict[str, str]:
"""Get headers for MalwareBazaar API."""
headers = {"Content-Type": "application/x-www-form-urlencoded"}
if self.api_key:
headers["Auth-Key"] = self.api_key
return headers
def _extract_threat_context(
self,
signature: str | None,
tags: list[str],
yara_rules: list[dict],
vendor_intel: dict,
) -> dict[str, Any]:
"""Extract APT, MITRE, and malware context from MalwareBazaar data."""
threat_actors = set()
mitre_techniques = set()
# Combine all searchable text
searchable_parts = [signature or ""]
searchable_parts.extend(tags)
# Parse YARA rules for threat actor hints
for rule in yara_rules[:10]:
rule_name = rule.get("rule_name", "")
description = rule.get("description", "") or ""
searchable_parts.append(rule_name)
searchable_parts.append(description)
# Parse vendor intel for additional context
for _vendor, intel in vendor_intel.items():
if isinstance(intel, dict):
verdict = intel.get("malware_family") or intel.get("verdict") or ""
searchable_parts.append(verdict)
searchable = " ".join(searchable_parts)
# Extract APT groups
for pattern in APT_PATTERNS:
for match in re.findall(pattern, searchable, re.IGNORECASE):
normalized = re.sub(r"[-\s]+", "", match.upper())
threat_actors.add(normalized)
# Extract MITRE techniques
for match in MITRE_PATTERN.findall(searchable):
mitre_techniques.add(match)
return {
"threat_actors": sorted(threat_actors),
"mitre_techniques": sorted(mitre_techniques),
}
def lookup_hash(self, file_hash: str) -> dict[str, Any]:
"""
Look up a file hash on MalwareBazaar.
Args:
file_hash: MD5, SHA1, or SHA256 hash to look up
Returns:
Dictionary containing malware sample data with threat context
Raises:
ExternalAPIError: If the API request fails
"""
logger.info(f"Looking up hash on MalwareBazaar: {file_hash}")
try:
response = self._make_request(
method="POST",
endpoint="",
headers=self._get_headers(),
data={
"query": "get_info",
"hash": file_hash,
},
)
except requests.exceptions.ConnectionError as e:
logger.error(f"MalwareBazaar API unreachable: {e}")
raise ExternalAPIError(
self.provider_name,
message="API unreachable - connection failed",
) from e
except requests.exceptions.Timeout as e:
logger.error(f"MalwareBazaar API timeout: {e}")
raise ExternalAPIError(
self.provider_name,
message="API timeout - server not responding",
) from e
# Check HTTP status code
if response.status_code != 200:
logger.error(f"MalwareBazaar returned HTTP {response.status_code}")
raise ExternalAPIError(
self.provider_name,
status_code=response.status_code,
message=f"API returned HTTP {response.status_code}",
)
# Try to parse JSON response
try:
response_data = response.json()
except ValueError as e:
logger.error(f"MalwareBazaar returned invalid JSON: {e}")
raise ExternalAPIError(
self.provider_name,
message="Invalid response from API - could not parse JSON",
) from e
query_status = response_data.get("query_status", "")
# Handle "hash_not_found" - hash not in database (legitimate clean result)
if query_status in ["hash_not_found", "no_results"]:
return {
"hash": file_hash,
"found": False,
"status": "not_found",
"status_message": "Hash not found in MalwareBazaar database",
"signature": None,
"malware_family": None,
"file_type": None,
"file_size": None,
"first_seen": None,
"tags": [],
"threat_actors": [],
"mitre_techniques": [],
"vendor_intel": {},
"raw_response": response_data,
}
# Handle API errors
if query_status != "ok":
error_messages = {
"illegal_hash": "Invalid hash format - must be MD5, SHA1, or SHA256",
"rate_limit_exceeded": "Rate limit exceeded - try again later",
"server_error": "MalwareBazaar server error",
}
error_msg = error_messages.get(query_status, f"API error: {query_status}")
logger.warning(f"MalwareBazaar query failed: {query_status}")
raise ExternalAPIError(
self.provider_name,
message=error_msg,
)
# Parse results - get the first matching entry
data = response_data.get("data", [])
if not data:
return {
"hash": file_hash,
"found": False,
"status": "not_found",
"status_message": "Hash not found in MalwareBazaar database",
"raw_response": response_data,
}
# Use the first result
entry = data[0]
# Extract raw fields
signature = entry.get("signature")
tags = entry.get("tags") or []
yara_rules = entry.get("yara_rules") or []
raw_vendor_intel = entry.get("vendor_intel") or {}
# Build vendor intel summary
vendor_intel = {}
for vendor, intel in raw_vendor_intel.items():
if isinstance(intel, dict):
verdict = intel.get("verdict") or intel.get("malware_family") or intel.get("detection")
if verdict:
vendor_intel[vendor] = verdict
# Extract threat context
threat_context = self._extract_threat_context(signature, tags, yara_rules, raw_vendor_intel)
# Normalize malware family from signature
malware_family = None
if signature:
# Common pattern: "FamilyName.Variant" or just "FamilyName"
malware_family = signature.split(".")[0] if "." in signature else signature
return {
"hash": file_hash,
"found": True,
"status": "malicious",
"status_message": f"Malware sample found - {signature or 'Unknown malware'}",
"sha256": entry.get("sha256_hash"),
"sha1": entry.get("sha1_hash"),
"md5": entry.get("md5_hash"),
"signature": signature,
"malware_family": malware_family,
"file_name": entry.get("file_name"),
"file_type": entry.get("file_type"),
"file_type_mime": entry.get("file_type_mime"),
"file_size": entry.get("file_size"),
"first_seen": entry.get("first_seen"),
"last_seen": entry.get("last_seen"),
"origin_country": entry.get("origin_country"),
"reporter": entry.get("reporter"),
"delivery_method": entry.get("delivery_method"),
"tags": tags,
# Threat context (NEW)
"threat_actors": threat_context["threat_actors"],
"mitre_techniques": threat_context["mitre_techniques"],
"vendor_intel": vendor_intel,
"yara_rules": [
{
"rule_name": rule.get("rule_name"),
"author": rule.get("author"),
"description": rule.get("description"),
}
for rule in yara_rules[:5]
],
"imphash": entry.get("imphash"),
"ssdeep": entry.get("ssdeep"),
"tlsh": entry.get("tlsh"),
# Complete raw response for AI analysis
"raw_response": response_data,
}
|