Spaces:
Running
Running
Download src/services/malwarebazaar.py from reputeradar/ioc-core: direct link, hf CLI and curl.
- Browser
- Download file 9.72 kB
-
https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/services/malwarebazaar.py
- Command line
-
hf download hf://spaces/reputeradar/ioc-core/src/services/malwarebazaar.py
-
curl -L -o malwarebazaar.py https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/services/malwarebazaar.py
9.72 kB
| """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) | |
| def provider_name(self) -> str: | |
| return "MalwareBazaar" | |
| 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, | |
| } | |