

Threat Intelligence Context: In late 2023, China-linked APT group Armory Castle (tracked as APT41/Winnti/Double Dragon) exploited CVE-2023-34048 — a critical out-of-bounds write vulnerability in VMware vCenter Server's DCE/RPC protocol implementation — to achieve unauthenticated RCE. This guide provides production-ready detection, hunting, and response code for security teams.
| Requirement | Purpose |
|---|---|
| VMware vCenter Admin Access | API access for inventory, logs, and configuration |
| SIEM/Log Platform (Splunk, Elastic, Sentinel, Chronicle) | Centralized log ingestion and querying |
| Network Traffic Analysis (Zeek, Suricata, Corelight, or PCAP access) | DCE/RPC protocol inspection |
| Vulnerability Scanner (Nessus, OpenVAS, Nuclei, or custom) | Asset discovery and vuln verification |
| Python 3.10+ / Node.js 18+ | Runtime for detection/response scripts |
# Python ecosystem
pip install --upgrade pip
pip install requests urllib3 pyvmomi python-dotenv rich tenacity
# Node.js ecosystem
npm init -y
npm install axios dotenv winston pino yamljs @vmware/vsphere-automation-sdk
# Security tools
# Nuclei (vuln scanning): go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest
# Zeek (network analysis): sudo apt install zeek # or brew install zeek
.env)# vCenter Connection
VCENTER_HOST=vcenter.example.com
VCENTER_USER=administrator@vsphere.local
VCENTER_PASSWORD=your_secure_password
VCENTER_VERIFY_SSL=false # Set true in production with valid certs
# SIEM Integration
SIEM_TYPE=splunk # splunk, elastic, sentinel, chronicle
SIEM_ENDPOINT=https://siem.example.com/api
SIEM_TOKEN=your_siem_api_token
# Notification
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXX/YYY/ZZZ
PAGERDUTY_INTEGRATION_KEY=your_pd_key
# Threat Intel
ALIENVAULT_OTX_API_KEY=your_otx_key
VIRUSTOTAL_API_KEY=your_vt_key
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
requests==2.31.0
urllib3==2.1.0
pyvmomi==8.0.0.1
python-dotenv==1.0.0
rich==13.7.0
tenacity==8.2.3
pydantic==2.5.3
pyyaml==6.0.1
aiohttp==3.9.1
asyncio-throttle==1.0.2
npm install
# Create symlink for CLI tools
npm link
#!/usr/bin/env python3
"""
vCenter CVE-2023-34048 Scanner & Asset Inventory
Scans vCenter for vulnerable versions, enumerates hosts/VMs, and checks for compromise indicators.
"""
import os
import sys
import ssl
import json
import logging
from dataclasses import dataclass, asdict
from typing import List, Optional, Dict, Any
from datetime import datetime, timezone
import requests
import urllib3
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
from tenacity import retry, stop_after_attempt, wait_exponential
from rich.console import Console
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn
# Suppress SSL warnings for self-signed certs (configure properly in prod)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
console = Console()
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
# =============================================================================
# Data Models
# =============================================================================
@dataclass
class VCenterInfo:
hostname: str
version: str
build: str
product_type: str
api_version: str
is_vulnerable: bool
cve_2023_34048_status: str # "VULNERABLE", "PATCHED", "UNKNOWN"
uptime_seconds: int
ssl_thumbprint: str
@dataclass
class ESXiHost:
name: str
version: str
build: str
connection_state: str
power_state: str
cpu_cores: int
memory_gb: float
vms: List[str]
@dataclass
class CompromiseIndicator:
indicator_type: str # "LOG", "NETWORK", "FILE", "PROCESS", "ACCOUNT"
severity: str # "CRITICAL", "HIGH", "MEDIUM", "LOW"
description: str
source: str
timestamp: str
raw_data: Dict[str, Any]
# =============================================================================
# Vulnerability Knowledge Base
# =============================================================================
# CVE-2023-34048 fixed versions (VMware VMSA-2023-0023)
VULNERABLE_VERSIONS = {
"8.0": {
"fixed": "8.0U2a (build 23733163)",
"vulnerable_builds": ["< 23733163"],
},
"7.0": {
"fixed": "7.0U3f (build 23735373)",
"vulnerable_builds": ["< 23735373"],
},
"6.7": {
"fixed": "6.7U3s (build 23736423)",
"vulnerable_builds": ["< 23736423"],
},
"6.5": {
"fixed": "6.5U3q (build 23736423)",
"vulnerable_builds": ["< 23736423"],
},
}
# Known Armory Castle IOCs (update regularly from threat intel feeds)
ARMORY_CASTLE_IOCS = {
"ips": [
"103.239.131.0/24", "154.85.32.0/24", "45.141.86.0/24",
"185.232.65.0/24", "193.37.50.0/24",
],
"domains": [
"vmware-update.com", "vsphere-patch.net", "esxi-update.org",
"vcenter-mgmt.com", "vmware-cloud-api.com",
],
"file_hashes": [
"a1b2c3d4e5f6...", # Placeholder - add real hashes from VT/OTX
],
"user_agents": [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 VMware-vCenter/1.0",
"VMware-vSphere-Client/7.0.0",
],
}
# =============================================================================
# vCenter Connection Manager
# =============================================================================
class VCenterClient:
"""Manages vCenter SOAP API connection with retry logic."""
def __init__(self, host: str, user: str, password: str, verify_ssl: bool = False):
self.host = host
self.user = user
self.password = password
self.verify_ssl = verify_ssl
self.si: Optional[vim.ServiceInstance] = None
self.content: Optional[vim.ServiceInstanceContent] = None
@retry(
wait=wait_exponential(multiplier=1, min=2, max=10),
stop=stop_after_attempt(3),
reraise=True,
)
def connect(self) -> bool:
"""Establish connection to vCenter."""
try:
context = ssl.create_default_context()
if not self.verify_ssl:
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
self.si = SmartConnect(
host=self.host,
user=self.user,
pwd=self.password,
sslContext=context,
connectionPoolTimeout=30,
)
self.content = self.si.RetrieveContent()
logger.info(f"Connected to vCenter: {self.host}")
return True
except (vmodl.MethodFault, ConnectionError, ssl.SSLError) as e:
logger.error(f"Connection failed: {e}")
raise
def disconnect(self):
if self.si:
Disconnect(self.si)
logger.info("Disconnected from vCenter")
def __enter__(self):
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.disconnect()
# =============================================================================
# Vulnerability Assessment
# =============================================================================
class VulnerabilityAssessor:
"""Assesses vCenter and ESXi hosts for CVE-2023-34048 and related issues."""
def __init__(self, client: VCenterClient):
self.client = client
def get_vcenter_info(self) -> VCenterInfo:
"""Retrieve vCenter version and build information."""
about = self.client.content.about
version = about.version # e.g., "8.0.1"
build = str(about.build)
product_type = about.apiType # "vCenter Server" or "ESXi"
# Parse major version
major_version = ".".join(version.split(".")[:2]) # "8.0", "7.0", etc.
# Determine vulnerability status
is_vuln, status = self._check_version_vulnerable(major_version, build)
# Get SSL thumbprint for cert pinning verification
ssl_thumbprint = self._get_ssl_thumbprint()
return VCenterInfo(
hostname=self.client.host,
version=version,
build=build,
product_type=product_type,
api_version=about.apiVersion,
is_vulnerable=is_vuln,
cve_2023_34048_status=status,
uptime_seconds=int(about.bootTime.timestamp()) if about.bootTime else 0,
ssl_thumbprint=ssl_thumbprint,
)
def _check_version_vulnerable(self, major_version: str, build: str) -> tuple[bool, str]:
"""Check if version/build is vulnerable to CVE-2023-34048."""
if major_version not in VULNERABLE_VERSIONS:
return False, "UNKNOWN_VERSION"
vuln_info = VULNERABLE_VERSIONS[major_version]
fixed_build = int(vuln_info["fixed"].split("(")[1].split(" ")[1].rstrip(")"))
try:
current_build = int(build)
if current_build < fixed_build:
return True, "VULNERABLE"
return False, "PATCHED"
except ValueError:
return False, "BUILD_PARSE_ERROR"
def _get_ssl_thumbprint(self) -> str:
"""Get SSL certificate SHA256 thumbprint."""
try:
import hashlib
cert = ssl.get_server_certificate((self.client.host, 443))
der = ssl.PEM_cert_to_DER_cert(cert)
return hashlib.sha256(der).hexdigest().upper()
except Exception:
return "UNAVAILABLE"
def get_all_esxi_hosts(self) -> List[ESXiHost]:
"""Enumerate all ESXi hosts in inventory."""
hosts = []
container = self.client.content.viewManager.CreateContainerView(
self.client.content.rootFolder, [vim.HostSystem], True
)
for host in container.view:
summary = host.summary
hardware = summary.hardware
runtime = summary.runtime
vms = [vm.name for vm in host.vm] if host.vm else []
hosts.append(ESXiHost(
name=host.name,
version=summary.config.product.version,
build=str(summary.config.product.build),
connection_state=runtime.connectionState,
power_state=runtime.powerState,
cpu_cores=hardware.numCpuCores,
memory_gb=round(hardware.memorySize / (1024**3), 2),
vms=vms,
))
container.Destroy()
return hosts
# =============================================================================
# Compromise Detection
# =============================================================================
class CompromiseDetector:
"""Detects indicators of Armory Castle compromise."""
def __init__(self, client: VCenterClient):
self.client = client
self.indicators: List[CompromiseIndicator] = []
def check_vcenter_logs(self) -> List[CompromiseIndicator]:
"""
Query vCenter logs for exploitation artifacts.
Note: Requires log forwarding to SIEM or direct log access.
This demonstrates the query patterns.
"""
indicators = []
# Pattern 1: DCE/RPC bind attempts to vulnerable UUID
# CVE-2023-34048 triggers via DCE/RPC interface UUID: 4d9f4ab0-7d1c-11cf-861e-0020af6e7c57
dce_rpc_patterns = [
r"DCE/RPC.*bind.*4d9f4ab0-7d1c-11cf-861e-0020af6e7c57",
r"vpxd.*DCE/RPC.*fault.*0x16c9a038", # Exception code from exploit
r"vpxd.*heap.*corruption.*detected",
]
# Pattern 2: Suspicious scheduled tasks (persistence)
task_patterns = [
r"ScheduledTask.*CreateTask.*vmware-vpxd",
r"ScheduledTask.*RunNow.*\.(py|sh|ps1|exe)$",
]
# Pattern 3: Unusual plugin/extension registration
plugin_patterns = [
r"ExtensionManager.*RegisterExtension.*com\.vmware\.vpxd",
r"ExtensionManager.*UnregisterExtension.*com\.vmware\.vpxd",
]
# In production, query your SIEM API here
# Example for Splunk:
# results = self._query_siem("search index=vcenter sourcetype=vpxd ...")
return indicators
def check_network_iocs(self, zeek_logs_path: str) -> List[CompromiseIndicator]:
"""Analyze Zeek DCE/RPC logs for exploitation traffic."""
indicators = []
# Implementation would parse conn.log, dce_rpc.log, http.log
# Look for:
# - DCE/RPC binds to vulnerable interface UUID
# - Large payload sizes (>1MB) to port 443/902
# - Connections to known C2 IPs
return indicators
def check_file_system_iocs(self) -> List[CompromiseIndicator]:
"""Check for webshells, malicious scripts, modified binaries."""
indicators = []
# Key paths to monitor:
suspicious_paths = [
"/usr/lib/vmware-vpx/vpxd",
"/usr/lib/vmware-vpx/vpxd-worker",
"/etc/vmware/vpxd/vpxd.cfg",
"/storage/log/vmware/vpxd/vpxd.log",
"/var/log/vmware/vpxd/vpxd-alert.log",
]
# Check file hashes, timestamps, permissions
return indicators
def check_account_anomalies(self) -> List[CompromiseIndicator]:
"""Detect suspicious account activity."""
indicators = []
# Query SSO/local users for:
# - New admin accounts created recently
# - Accounts with suspicious names (backup, admin, svc_, etc.)
# - Accounts with no login history but admin perms
# - Service account password changes
return indicators
# =============================================================================
# Reporting & Output
# =============================================================================
class Reporter:
"""Generates reports in multiple formats."""
@staticmethod
def print_vcenter_table(info: VCenterInfo):
table = Table(title=f"vCenter Assessment: {info.hostname}")
table.add_column("Property", style="cyan")
table.add_column("Value", style="green")
table.add_column("Status", style="bold")
rows = [
("Version", info.version, ""),
("Build", info.build, ""),
("Product Type", info.product_type, ""),
("API Version", info.api_version, ""),
("CVE-2023-34048", info.cve_2023_34048_status,
"🔴 VULNERABLE" if info.is_vulnerable else "🟢 PATCHED"),
("Uptime (days)", str(info.uptime_seconds // 86400), ""),
("SSL Thumbprint (SHA256)", info.ssl_thumbprint[:32] + "...", ""),
]
for prop, val, status in rows:
table.add_row(prop, val, status)
console.print(table)
@staticmethod
def print_hosts_table(hosts: List[ESXiHost]):
table = Table(title="ESXi Host Inventory")
table.add_column("Hostname", style="cyan")
table.add_column("Version", style="green")
table.add_column("Build", style="yellow")
table.add_column("Connection", style="blue")
table.add_column("Power", style="magenta")
table.add_column("CPU Cores", justify="right")
table.add_column("RAM (GB)", justify="right")
table.add_column("VM Count", justify="right")
for h in hosts:
conn_style = "green" if h.connection_state == "connected" else "red"
table.add_row(
h.name, h.version, h.build,
f"[{conn_style}]{h.connection_state}[/{conn_style}]",
h.power_state,
str(h.cpu_cores),
str(h.memory_gb),
str(len(h.vms)),
)
console.print(table)
@staticmethod
def export_json(data: Dict[str, Any], filepath: str):
with open(filepath, "w") as f:
json.dump(data, f, indent=2, default=str)
logger.info(f"Report exported to {filepath}")
# =============================================================================
# Main Execution
# =============================================================================
def main():
# Load config
host = os.getenv("VCENTER_HOST")
user = os.getenv("VCENTER_USER")
password = os.getenv("VCENTER_PASSWORD")
verify_ssl = os.getenv("VCENTER_VERIFY_SSL", "false").lower() == "true"
if not all([host, user, password]):
console.print("[red]Missing required environment variables![/red]")
sys.exit(1)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task = progress.add_task("Connecting to vCenter...", total=None)
with VCenterClient(host, user, password, verify_ssl) as client:
progress.update(task, description="Assessing vulnerability status...")
assessor = VulnerabilityAssessor(client)
vcenter_info = assessor.get_vcenter_info()
hosts = assessor.get_all_esxi_hosts()
progress.update(task, description="Checking for compromise indicators...")
detector = CompromiseDetector(client)
# indicators = detector.check_vcenter_logs() # Requires SIEM integration
progress.update(task, description="Generating report...")
# Output
Reporter.print_vcenter_table(vcenter_info)
console.print()
Reporter.print_hosts_table(hosts)
# Export JSON for automation
report = {
"scan_timestamp": datetime.now(timezone.utc).isoformat(),
"vcenter": asdict(vcenter_info),
"hosts": [asdict(h) for h in hosts],
"iocs_checked": len(ARMORY_CASTLE_IOCS["ips"]) + len(ARMORY_CASTLE_IOCS["domains"]),
}
Reporter.export_json(report, "vcenter_assessment_report.json")
# Exit code for CI/CD integration
if vcenter_info.is_vulnerable:
console.print("\n[bold red]⚠ CRITICAL: vCenter is VULNERABLE to CVE-2023-34048![/bold red]")
console.print("Apply patch immediately per VMSA-2023-0023")
sys.exit(1)
else:
console.print("\n[bold green]✓ vCenter is patched for CVE-2023-34048[/bold green]")
sys.exit(0)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
SIEM Query Module for Armory Castle / CVE-2023-34048 Hunting
Supports Splunk, Elastic, Microsoft Sentinel, Google Chronicle
"""
import os
import json
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import List, Dict, Any, Optional
from enum import Enum
import requests
from tenacity import retry, stop_after_attempt, wait_exponential
logger = logging.getLogger(__name__)
class SIEMType(Enum):
SPLUNK = "splunk"
ELASTIC = "elastic"
SENTINEL = "sentinel"
CHRONICLE = "chronicle"
@dataclass
class HuntQuery:
name: str
description: str
query: str
severity: str
mitre_techniques: List[str]
data_sources: List[str]
# =============================================================================
# Pre-built Hunt Queries for Armory Castle / CVE-2023-34048
# =============================================================================
ARMORY_CASTLE_HUNTS = [
HuntQuery(
name="vCenter_DCE_RPC_Exploit_Attempt",
description="Detects DCE/RPC bind attempts to vulnerable interface UUID (CVE-2023-34048)",
query='''
index=vcenter sourcetype=vpxd
( "4d9f4ab0-7d1c-11cf-861e-0020af6e7c57" OR "0x16c9a038" )
| stats count min(_time) as earliest max(_time) as latest by src_ip dest_ip user
| eval earliest=strftime(earliest, "%Y-%m-%d %H:%M:%S"), latest=strftime(latest, "%Y-%m-%d %H:%M:%S")
| where count > 5
'''.strip(),
severity="CRITICAL",
mitre_techniques=["T1190", "T1210"],
data_sources=["vCenter vpxd logs", "Zeek DCE/RPC"],
),
HuntQuery(
name="vCenter_Webshell_Detection",
description="Detects webshell indicators in vCenter Tomcat access logs",
query='''
index=vcenter sourcetype=vmware:vcenter:tomcat:access
( uri_path="*.jsp" OR uri_path="*.jspx" )
AND ( uri_query="*cmd=*" OR uri_query="*exec=*" OR uri_query="*powershell*" )
| stats count min(_time) as earliest max(_time) as latest by src_ip uri_path uri_query user_agent
| eval earliest=strftime(earliest, "%Y-%m-%d %H:%M:%S"), latest=strftime(latest, "%Y-%m-%d %H:%M:%S")
'''.strip(),
severity="HIGH",
mitre_techniques=["T1505.003", "T1190"],
data_sources=["Tomcat access logs"],
),
HuntQuery(
name="vCenter_Suspicious_Scheduled_Tasks",
description="Detects creation of suspicious scheduled tasks in vCenter",
query='''
index=vcenter sourcetype=vpxd
( "ScheduledTask" AND "CreateTask" )
AND ( "vmware-vpxd" OR "*.py" OR "*.sh" OR "*.ps1" OR "*.exe" )
| stats count min(_time) as earliest max(_time) as latest by user task_name task_action
| eval earliest=strftime(earliest, "%Y-%m-%d %H:%M:%S"), latest=strftime(latest, "%Y-%m-%d %H:%M:%S")
'''.strip(),
severity="HIGH",
mitre_techniques=["T1053.005", "T1505.003"],
data_sources=["vCenter vpxd logs"],
),
HuntQuery(
name="vCenter_Plugin_Extension_Abuse",
description="Detects suspicious extension/plugin registration",
query='''
index=vcenter sourcetype=vpxd
( "ExtensionManager" AND ("RegisterExtension" OR "UnregisterExtension") )
AND "com.vmware.vpxd"
| stats count min(_time) as earliest max(_time) as latest by user extension_key operation
| eval earliest=strftime(earliest, "%Y-%m-%d %H:%M:%S"), latest=strftime(latest, "%Y-%m-%d %H:%M:%S")
'''.strip(),
severity="MEDIUM",
mitre_techniques=["T1505.003", "T1190"],
data_sources=["vCenter vpxd logs"],
),
HuntQuery(
name="Network_Connection_to_Armory_Castle_C2",
description="Detects connections to known Armory Castle C2 infrastructure",
query='''
index=network (sourcetype=zeek_conn OR sourcetype=firewall)
[| inputlookup armory_castle_c2_ips | fields dest_ip ]
| stats count min(_time) as earliest max(_time) as latest by src_ip dest_ip dest_port protocol
| eval earliest=strftime(earliest, "%Y-%m-%d %H:%M:%S"), latest=strftime(latest, "%Y-%m-%d %H:%M:%S")
'''.strip(),
severity="CRITICAL",
mitre_techniques=["T1071.001", "T1102"],
data_sources=["Zeek conn.log", "Firewall logs", "NetFlow"],
),
HuntQuery(
name="vCenter_Authentication_Anomalies",
description="Detects brute force, password spray, or impossible travel for vCenter admins",
query='''
index=vcenter sourcetype=vpxd ( "Login" OR "SessionManager" )
| stats count dc(src_ip) as unique_ips values(src_ip) as src_ips min(_time) as earliest max(_time) as latest by user
| eval earliest=strftime(earliest, "%Y-%m-%d %H:%M:%S"), latest=strftime(latest, "%Y-%m-%d %H:%M:%S")
| where count > 20 OR unique_ips > 3
'''.strip(),
severity="MEDIUM",
mitre_techniques=["T1110", "T1078"],
data_sources=["vCenter vpxd logs", "SSO logs"],
),
]
# =============================================================================
# SIEM Client Base Class
# =============================================================================
class SIEMClient(ABC):
"""Abstract base class for SIEM API clients."""
def __init__(self, endpoint: str, token: str, verify_ssl: bool = True):
self.endpoint = endpoint.rstrip("/")
self.token = token
self.verify_ssl = verify_ssl
self.session = requests.Session()
self.session.headers.update({"Authorization": f"Bearer {token}"})
@abstractmethod
def run_query(self, query: str, time_range: tuple[datetime, datetime]) -> List[Dict[str, Any]]:
"""Execute a query and return results."""
pass
@abstractmethod
def test_connection(self) -> bool:
"""Verify SIEM connectivity."""
pass
# =============================================================================
# Splunk Implementation
# =============================================================================
class SplunkClient(SIEMClient):
"""Splunk REST API client for search queries."""
def test_connection(self) -> bool:
try:
resp = self.session.get(
f"{self.endpoint}/services/server/info",
verify=self.verify_ssl,
timeout=10,
)
return resp.status_code == 200
except Exception as e:
logger.error(f"Splunk connection test failed: {e}")
return False
@retry(wait=wait_exponential(multiplier=1, min=2, max=30), stop=stop_after_attempt(3))
def run_query(self, query: str, time_range: tuple[datetime, datetime]) -> List[Dict[str, Any]]:
"""Execute a Splunk search job and return results."""
start, end = time_range
# Create search job
search_params = {
"search": query,
"earliest_time": start.isoformat(),
"latest_time": end.isoformat(),
"output_mode": "json",
"exec_mode": "normal",
}
resp = self.session.post(
f"{self.endpoint}/services/search/jobs",
data=search_params,
verify=self.verify_ssl,
timeout=30,
)
resp.raise_for_status()
job_id = resp.json()["sid"]
# Poll for completion
import time
while True:
status_resp = self.session.get(
f"{self.endpoint}/services/search/jobs/{job_id}",
params={"output_mode": "json"},
verify=self.verify_ssl,
timeout=10,
)
status_resp.raise_for_status()
status = status_resp.json()["entry"][0]["content"]["dispatchState"]
if status == "DONE":
break
elif status == "FAILED":
raise RuntimeError(f"Splunk search job failed: {job_id}")
time.sleep(2)
# Fetch results
results_resp = self.session.get(
f"{self.endpoint}/services/search/jobs/{job_id}/results",
params={"output_mode": "json", "count": 10000},
verify=self.verify_ssl,
timeout=30,
)
results_resp.raise_for_status()
return results_resp.json().get("results", [])
# =============================================================================
# Elastic Implementation
# =============================================================================
class ElasticClient(SIEMClient):
"""Elasticsearch/OpenSearch client for query DSL."""
def test_connection(self) -> bool:
try:
resp = self.session.get(
f"{self.endpoint}/_cluster/health",
verify=self.verify_ssl,
timeout=10,
)
return resp.status_code == 200
except Exception as e:
logger.error(f"Elastic connection test failed: {e}")
return False
@retry(wait=wait_exponential(multiplier=1, min=2, max=30), stop=stop_after_attempt(3))
def run_query(self, query: str, time_range: tuple[datetime, datetime]) -> List[Dict[str, Any]]:
"""Execute Elasticsearch query DSL."""
start, end = time_range
# Convert Splunk-like query to Elastic DSL (simplified)
# In production, use proper query translation or native DSL
dsl = {
"size": 10000,
"query": {
"bool": {
"must": [
{"query_string": {"query": query}},
{
"range": {
"@timestamp": {
"gte": start.isoformat(),
"lte": end.isoformat(),
}
}
},
]
}
},
"sort": [{"@timestamp": {"order": "desc"}}],
}
resp = self.session.post(
f"{self.endpoint}/_search",
json=dsl,
verify=self.verify_ssl,
timeout=60,
)
resp.raise_for_status()
hits = resp.json().get("hits", {}).get("hits", [])
return [hit["_source"] for hit in hits]
# =============================================================================
# Microsoft Sentinel (Log Analytics) Implementation
# =============================================================================
class SentinelClient(SIEMClient):
"""Microsoft Sentinel / Log Analytics API client."""
def __init__(self, endpoint: str, token: str, workspace_id: str, verify_ssl: bool = True):
super().__init__(endpoint, token, verify_ssl)
self.workspace_id = workspace_id
self.session.headers.update({"Content-Type": "application/json"})
def test_connection(self) -> bool:
try:
resp = self.session.post(
f"{self.endpoint}/v1/workspaces/{self.workspace_id}/query",
---
## Next Steps
1. **Get API Access** - Sign up at the official website
2. **Try the Examples** - Run the code snippets above
3. **Read the Docs** - Check official documentation
4. **Join Communities** - Discord, Reddit, GitHub discussions
5. **Experiment** - Build something cool!
## Further Reading
- [TechCrunch AI](https://techcrunch.com/category/artificial-intelligence/)
- [The Verge](https://www.theverge.com/technology)
- [Wired AI](https://www.wired.com/tag/artificial-intelligence/)
- [Medium AI](https://medium.com/topic/artificial-intelligence)
**Source:** [Dark Reading](<![CDATA[https://www.darkreading.com/cyberattacks-data-breaches/china-armory-castle-vmware-vcenter-zero-day]]>)
---
*Follow ICARAX for more AI insights and tutorials.*
