npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
NIST CSF 2.0
MITRE ATLAS
When to Use
Use this skill when:
- Deploying CrowdStrike Falcon sensors to Windows, macOS, or Linux endpoints
- Configuring Falcon prevention and detection policies for different endpoint groups
- Integrating CrowdStrike telemetry with SIEM (Splunk, Elastic, Sentinel) for correlated detection
- Troubleshooting sensor connectivity, performance, or detection issues
Do not use this skill for deploying other EDR solutions (Carbon Black, SentinelOne) or for Falcon cloud workload protection (use cloud-specific deployment guides).
Prerequisites
- CrowdStrike Falcon console access with Falcon Administrator role
- Customer ID (CID) and Falcon sensor installer package
- Administrative/root access on target endpoints
- Network access: endpoints must reach CrowdStrike cloud (ts01-b.cloudsink.net on port 443)
- Deployment tool: SCCM, Intune, GPO, Ansible, or manual installation
Workflow
Step 1: Obtain Falcon Sensor Installer and CID
1. Log into Falcon Console: https://falcon.crowdstrike.com
2. Navigate: Host setup and management → Sensor downloads
3. Download the appropriate installer:
- Windows: WindowsSensor_<version>.exe
- macOS: FalconSensorMacOS_<version>.pkg
- Linux: falcon-sensor_<version>_amd64.deb / .rpm
4. Copy the Customer ID (CID) from the Sensor downloads page
- CID format: <32-char-hex>-<2-char-checksum>Step 2: Deploy Falcon Sensor - Windows
Silent installation via command line:
WindowsSensor_7.18.17106.exe /install /quiet /norestart CID=<YOUR_CID>SCCM deployment:
1. Create an Application in SCCM
2. Deployment type: Script Installer
3. Install command: WindowsSensor_7.18.17106.exe /install /quiet /norestart CID=<CID>
4. Detection method: Registry key exists
- HKLM\SYSTEM\CrowdStrike\{9b03c1d9-3138-44ed-9fae-d9f4c034b88d}\{16e0423f-7058-48c9-a204-725362b67639}\Default
5. Deploy to target collection
6. Deployment purpose: Required (for mandatory installation)Microsoft Intune deployment:
1. Navigate: Devices → Windows → Configuration profiles
2. Create Win32 app deployment
3. Upload .intunewin package (wrapped sensor installer)
4. Install command: WindowsSensor_7.18.17106.exe /install /quiet /norestart CID=<CID>
5. Detection rule: File exists C:\Windows\System32\drivers\CrowdStrike\csagent.sys
6. Assign to device groupGPO deployment:
# Create startup script that checks for existing installation
$sensorPath = "C:\Windows\System32\drivers\CrowdStrike\csagent.sys"
if (-not (Test-Path $sensorPath)) {
Start-Process -FilePath "\\fileserver\CrowdStrike\WindowsSensor.exe" `
-ArgumentList "/install /quiet /norestart CID=<CID>" -Wait
}Step 3: Deploy Falcon Sensor - Linux
# Debian/Ubuntu
sudo dpkg -i falcon-sensor_7.18.0-17106_amd64.deb
sudo /opt/CrowdStrike/falconctl -s -f --cid=<YOUR_CID>
sudo systemctl start falcon-sensor
sudo systemctl enable falcon-sensor
# RHEL/CentOS
sudo yum install falcon-sensor-7.18.0-17106.el8.x86_64.rpm
sudo /opt/CrowdStrike/falconctl -s -f --cid=<YOUR_CID>
sudo systemctl start falcon-sensor
sudo systemctl enable falcon-sensor
# Verify sensor is running and connected
sudo /opt/CrowdStrike/falconctl -g --rfm-state
# Expected output: rfm-state=false (sensor is communicating with cloud)Step 4: Deploy Falcon Sensor - macOS
# Install sensor package
sudo installer -pkg FalconSensorMacOS_7.18.pkg -target /
# Set CID
sudo /Applications/Falcon.app/Contents/Resources/falconctl license <YOUR_CID>
# Grant Full Disk Access and System Extension via MDM profile
# Required for macOS Ventura+ (manual approval or MDM PPPC profile)
# MDM payload: com.crowdstrike.falcon.Agent → SystemExtension + Full Disk Access
# Verify sensor status
sudo /Applications/Falcon.app/Contents/Resources/falconctl statsStep 5: Configure Prevention Policies
In Falcon Console, navigate to Configuration → Prevention Policies:
Recommended prevention policy settings:
Machine Learning:
- Cloud ML: Aggressive (extra protection, may increase false positives)
- Sensor ML: Moderate
- Adware & PUP: Moderate
Behavioral Protection:
- On Write: Enabled (detect malware on file creation)
- On Sensor ML: Enabled
- Interpreter-Only: Enabled (detect script-based attacks)
Exploit Mitigation:
- Exploit behavior protection: Enabled
- Memory scanning: Enabled (detects in-memory attacks)
- Code injection: Enabled
Ransomware:
- Ransomware protection: Enabled
- Shadow copy protection: Enabled
- MBR protection: EnabledCreate separate policies for:
- Workstations (aggressive settings)
- Servers (moderate settings to avoid false positives on server workloads)
- Critical infrastructure (maximum protection with exception lists)
Step 6: Configure Response Policies
Real-Time Response:
- Enable RTR for all sensor groups
- Configure RTR admin vs. RTR responder roles
- Enable script execution (for IR teams)
- Enable file extraction (for forensics)
Network Containment:
- Pre-authorize containment for specific host groups
- Configure containment exclusions (allow management traffic)
Automated Response:
- Enable automated remediation for high-confidence detections
- Configure kill process action for ransomware detections
- Enable quarantine for malware file detectionsStep 7: Validate Deployment
# Windows: Check Falcon sensor status
sc query csagent
# Expected: RUNNING
# Check sensor version
reg query "HKLM\SYSTEM\CrowdStrike\{9b03c1d9-3138-44ed-9fae-d9f4c034b88d}\{16e0423f-7058-48c9-a204-725362b67639}\Default" /v AgentVersion
# Verify cloud connectivity
# In Falcon Console: Host Management → Hosts → search for hostname
# Status should show "Online" with last seen timestamp < 5 minutesTest detection capability:
# CrowdStrike provides test detection samples
# Download CsTestDetect.exe from Falcon Console → Host setup
# Run on endpoint to generate a test detection
.\CsTestDetect.exe
# Verify detection appears in Falcon Console within 60 secondsStep 8: SIEM Integration
# Falcon SIEM Connector (Streaming API)
# Configure in Falcon Console: Support → API Clients and Keys
# Create API client with scope: Event Streams → Read
# Use falcon-siem-connector or Falcon Data Replicator (FDR)
# Splunk integration:
# Install CrowdStrike Falcon Event Streams Technical Add-on from Splunkbase
# Configure: Settings → Data inputs → CrowdStrike Falcon Event Streams
# Enter API Client ID and Secret
# Index: crowdstrike_events
# Elastic integration:
# Use Elastic Agent with CrowdStrike module
# Configure: Fleet → Agent policies → Add integration → CrowdStrikeKey Concepts
| Term | Definition |
|---|---|
| Falcon Sensor | Lightweight kernel-mode agent (25-30 MB) that collects endpoint telemetry and enforces prevention policies |
| CID (Customer ID) | Unique identifier that associates the sensor with your CrowdStrike Falcon tenant |
| RFM (Reduced Functionality Mode) | State where sensor operates with limited capability due to cloud connectivity loss |
| Sensor Grouping Tags | Labels applied during installation to auto-assign hosts to groups and policies |
| RTR (Real-Time Response) | Remote shell capability for incident responders to interact with endpoints through Falcon |
| IOA (Indicators of Attack) | Behavioral detections based on adversary techniques rather than static signatures |
Tools & Systems
- CrowdStrike Falcon Console: Cloud-hosted management platform for all Falcon modules
- Falcon SIEM Connector: Streams detection and audit events to SIEM platforms
- Falcon Data Replicator (FDR): Streams raw endpoint telemetry to S3/cloud storage for hunting
- CrowdStrike Falcon API (OAuth2): RESTful API for automation, integration, and custom workflows
- PSFalcon: PowerShell module for CrowdStrike Falcon API automation
Common Pitfalls
- Missing CID during installation: Sensor installs but never connects to Falcon cloud. Always pass CID during install, not after.
- Proxy not configured: In environments with web proxies, configure proxy during installation:
/install /quiet CID=<CID> APP_PROXYNAME=proxy.corp.com APP_PROXYPORT=8080. - macOS System Extension blocked: macOS requires explicit approval for kernel/system extensions. Use MDM to pre-approve CrowdStrike extensions before deployment.
- Conflicting security products: Running multiple EDR/AV products causes performance issues and false positives. Coordinate exclusions or remove legacy AV before Falcon deployment.
- Sensor version pinning: Falcon auto-updates sensors by default. Pin sensor versions in the console for change-controlled environments before testing new versions.
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 3
api-reference.md1.4 KB
CrowdStrike EDR Deployment — API Reference
Libraries
| Library | Install | Purpose |
|---|---|---|
| crowdstrike-falconpy | pip install crowdstrike-falconpy |
Official CrowdStrike Falcon SDK |
Key FalconPy Service Classes
| Class | Description |
|---|---|
Hosts(client_id, client_secret) |
Host/device management |
Detections(client_id, client_secret) |
Detection queries and management |
RealTimeResponse(client_id, client_secret) |
RTR session management |
SensorDownload(client_id, client_secret) |
Sensor installer download |
Prevention(client_id, client_secret) |
Prevention policy management |
Key Methods
| Method | Description |
|---|---|
hosts.query_devices_by_filter(filter=, limit=) |
Query host IDs |
hosts.get_device_details(ids=[]) |
Get host details |
hosts.perform_action(action_name="contain", ids=[]) |
Contain/lift containment |
detections.query_detects(filter=, sort=) |
Query detection IDs |
detections.get_detect_summaries(body={"ids": []}) |
Get detection details |
FQL Filter Examples
platform_name:'Windows' + status:'normal'
last_seen:>='2024-01-01T00:00:00Z'
hostname:'*server*'External References
standards.md2.5 KB
Standards & References - Deploying EDR Agent with CrowdStrike
Primary Standards
MITRE ATT&CK Enterprise Framework
- Publisher: MITRE Corporation
- URL: https://attack.mitre.org/
- Relevance: CrowdStrike Falcon maps detections to ATT&CK techniques; understanding ATT&CK is essential for tuning detection policies
- Key tactics for EDR: Initial Access, Execution, Persistence, Privilege Escalation, Defense Evasion, Lateral Movement
NIST SP 800-83 Rev 1 - Guide to Malware Incident Prevention and Handling
- Publisher: NIST
- Relevance: Defines endpoint protection architecture including EDR placement and malware prevention controls
CIS Control 10 - Malware Defenses
- Publisher: Center for Internet Security
- Relevance: CIS Controls v8 Control 10 mandates deploying anti-malware with centralized management and automated updates
CrowdStrike-Specific References
CrowdStrike Falcon Deployment Guide
- Scope: Official deployment procedures for Windows, macOS, Linux sensors
- Key sections: Silent install parameters, proxy configuration, sensor grouping tags
- Access: Falcon Console → Support → Documentation
CrowdStrike Falcon API Documentation
- URL: https://falcon.crowdstrike.com/documentation/
- Scope: OAuth2 authentication, host management, detection management, RTR APIs
- Key endpoints: /devices/queries/devices/v1, /detects/queries/detects/v1
Falcon SIEM Integration Guide
- Scope: Event streaming via SIEM Connector, FDR, and direct API
- Supported SIEMs: Splunk, Elastic, Microsoft Sentinel, IBM QRadar, ArcSight
Compliance Mappings
| Framework | Requirement | CrowdStrike Coverage |
|---|---|---|
| PCI DSS 4.0 | 5.2 - Anti-malware on systems | Falcon sensor on all in-scope endpoints |
| HIPAA | 164.308(a)(5)(ii)(B) - Protection from malware | Falcon prevention + detection |
| SOC 2 | CC6.8 - Malicious software prevention | Falcon sensor with prevention policies |
| NIST 800-171 | 3.14.2 - Malicious code protection | Falcon ML + behavioral detection |
| ISO 27001 | A.12.2.1 - Controls against malware | Falcon sensor with automated response |
Industry Benchmarks
- MITRE Engenuity ATT&CK Evaluations: CrowdStrike Falcon regularly achieves high detection scores in Enterprise evaluations
- Gartner Magic Quadrant for Endpoint Protection: CrowdStrike positioned as Leader
- Forrester Wave Endpoint Detection and Response: CrowdStrike rated Strong Performer/Leader
workflows.md4.4 KB
Workflows - Deploying EDR Agent with CrowdStrike
Workflow 1: Enterprise Sensor Rollout
[Plan Deployment]
│
├── Obtain Falcon Console access and CID
├── Download sensor installer for each OS
├── Create deployment groups (Workstations, Servers, VDI)
│
▼
[Configure Policies Before Deployment]
│
├── Create prevention policies per group
├── Configure sensor update policies (pinned vs. auto-update)
├── Set sensor grouping tags for auto-assignment
│
▼
[Pilot Deployment (5% of endpoints)]
│
├── Deploy via SCCM/Intune to pilot group
├── Monitor for 1 week: performance impact, false positives
├── Tune exclusions for LOB applications
│
▼
[Validation]
│
├── All pilot hosts show "Online" in Falcon Console
├── Test detection with CsTestDetect
├── No critical application breakage
│
▼
[Production Rollout (phased)]
│
├── Phase 1: Workstations (2 weeks)
├── Phase 2: Standard servers (2 weeks)
├── Phase 3: Critical servers (1 week, change window)
│
▼
[Post-Deployment]
│
├── Enable SIEM integration
├── Configure automated response policies
├── Establish exclusion review cadence (monthly)
└── Train SOC on Falcon Console workflowsWorkflow 2: Detection Triage in Falcon Console
[New Detection Alert]
│
▼
[Review Detection in Falcon Console]
│
├── Severity: Critical/High/Medium/Low/Informational
├── Tactic & Technique (ATT&CK mapping)
├── Process tree visualization
├── Network connections
│
▼
[Assess: True Positive or False Positive?]
│
├── True Positive ──► [Contain Host via Network Containment]
│ │
│ ▼
│ [Launch RTR session for investigation]
│ │
│ ▼
│ [Collect artifacts, kill malicious processes]
│ │
│ ▼
│ [Remediate and release from containment]
│
└── False Positive ──► [Create exclusion rule]
│
▼
[Document exclusion with justification]
│
▼
[Mark detection as false positive]Workflow 3: Sensor Troubleshooting
[Sensor Issue Reported]
│
▼
[Check Falcon Console Host Status]
│
├── Online ──► [Issue is not connectivity; check policy assignment]
│
└── Offline / RFM ──► [Check network connectivity]
│
├── Can reach ts01-b.cloudsink.net:443?
│ │
│ ├── Yes ──► [Check proxy settings]
│ │ ▼
│ │ [Reconfigure: falconctl -s --apd=false --aph=proxy --app=8080]
│ │
│ └── No ──► [Firewall blocking; add CrowdStrike domains to allowlist]
│
▼
[Check sensor service status]
│
├── Service running ──► [Review sensor logs in C:\Windows\System32\drivers\CrowdStrike\]
│
└── Service stopped ──► [Restart: sc start csagent (Windows) or systemctl start falcon-sensor (Linux)]Workflow 4: Sensor Version Upgrade
[New Sensor Version Available]
│
▼
[Review Release Notes in Falcon Console]
│
▼
[Test on pilot group (N-1 update policy)]
│
├── No issues after 1 week ──► [Move production to N update policy]
│
└── Issues found ──► [Hold on current version, file support ticket]
│
▼
[Pin current version in sensor update policy]Scripts 2
agent.py4.6 KB
#!/usr/bin/env python3
"""CrowdStrike EDR deployment and monitoring agent using FalconPy."""
import json
import sys
import argparse
from datetime import datetime
try:
from falconpy import Hosts, Detections
except ImportError:
print("Install: pip install crowdstrike-falconpy")
sys.exit(1)
def list_hosts(client_id, client_secret, filter_query=None):
"""List managed hosts with sensor details."""
hosts = Hosts(client_id=client_id, client_secret=client_secret)
params = {"limit": 100}
if filter_query:
params["filter"] = filter_query
id_resp = hosts.query_devices_by_filter(**params)
if id_resp["status_code"] != 200:
return []
device_ids = id_resp["body"]["resources"]
if not device_ids:
return []
detail_resp = hosts.get_device_details(ids=device_ids)
results = []
for device in detail_resp["body"].get("resources", []):
results.append({
"hostname": device.get("hostname", ""),
"device_id": device.get("device_id", ""),
"platform": device.get("platform_name", ""),
"os_version": device.get("os_version", ""),
"sensor_version": device.get("agent_version", ""),
"status": device.get("status", ""),
"last_seen": device.get("last_seen", ""),
})
return results
def get_detections(client_id, client_secret, severity=None):
"""Retrieve recent detections."""
detections = Detections(client_id=client_id, client_secret=client_secret)
params = {"limit": 50, "sort": "last_behavior|desc"}
if severity:
params["filter"] = f"max_severity_displayname:'{severity}'"
id_resp = detections.query_detects(**params)
if id_resp["status_code"] != 200:
return []
detect_ids = id_resp["body"]["resources"]
if not detect_ids:
return []
detail_resp = detections.get_detect_summaries(body={"ids": detect_ids})
results = []
for det in detail_resp["body"].get("resources", []):
results.append({
"detection_id": det.get("detection_id", ""),
"hostname": det.get("device", {}).get("hostname", ""),
"severity": det.get("max_severity_displayname", ""),
"tactic": det.get("behaviors", [{}])[0].get("tactic", "") if det.get("behaviors") else "",
"technique": det.get("behaviors", [{}])[0].get("technique", "") if det.get("behaviors") else "",
"status": det.get("status", ""),
"timestamp": det.get("last_behavior", ""),
})
return results
def check_sensor_versions(hosts_data):
"""Audit sensor version compliance across fleet."""
versions = {}
for host in hosts_data:
ver = host.get("sensor_version", "unknown")
versions[ver] = versions.get(ver, 0) + 1
return {"version_distribution": versions, "total_hosts": len(hosts_data)}
def run_audit(client_id, client_secret):
"""Execute CrowdStrike EDR audit."""
print(f"\n{'='*60}")
print(f" CROWDSTRIKE EDR DEPLOYMENT AUDIT")
print(f" Generated: {datetime.utcnow().isoformat()} UTC")
print(f"{'='*60}\n")
hosts_data = list_hosts(client_id, client_secret)
print(f"--- MANAGED HOSTS ({len(hosts_data)}) ---")
for h in hosts_data[:10]:
print(f" {h['hostname']}: {h['platform']} v{h['sensor_version']} ({h['status']})")
versions = check_sensor_versions(hosts_data)
print(f"\n--- SENSOR VERSIONS ---")
for ver, count in sorted(versions["version_distribution"].items()):
print(f" {ver}: {count} hosts")
detections = get_detections(client_id, client_secret)
print(f"\n--- RECENT DETECTIONS ({len(detections)}) ---")
for d in detections[:10]:
print(f" [{d['severity']}] {d['hostname']}: {d['tactic']} / {d['technique']}")
return {"hosts": len(hosts_data), "versions": versions, "detections": detections}
def main():
parser = argparse.ArgumentParser(description="CrowdStrike EDR Agent")
parser.add_argument("--client-id", required=True, help="CrowdStrike API client ID")
parser.add_argument("--client-secret", required=True, help="CrowdStrike API client secret")
parser.add_argument("--audit", action="store_true", help="Run full audit")
parser.add_argument("--output", help="Save report to JSON file")
args = parser.parse_args()
if args.audit:
report = run_audit(args.client_id, args.client_secret)
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"\n[+] Report saved to {args.output}")
else:
parser.print_help()
if __name__ == "__main__":
main()
process.py8.4 KB
#!/usr/bin/env python3
"""
CrowdStrike Falcon Deployment Verification Tool
Queries the CrowdStrike Falcon API to verify sensor deployment coverage,
identify unmanaged endpoints, and generate deployment status reports.
"""
import json
import sys
import os
import time
import csv
from datetime import datetime, timedelta
from urllib.request import Request, urlopen
from urllib.parse import urlencode
from urllib.error import HTTPError
FALCON_BASE_URL = os.environ.get("FALCON_BASE_URL", "https://api.crowdstrike.com")
FALCON_CLIENT_ID = os.environ.get("FALCON_CLIENT_ID", "")
FALCON_CLIENT_SECRET = os.environ.get("FALCON_CLIENT_SECRET", "")
def get_oauth_token() -> str:
"""Obtain OAuth2 bearer token from CrowdStrike API."""
url = f"{FALCON_BASE_URL}/oauth2/token"
data = urlencode({
"client_id": FALCON_CLIENT_ID,
"client_secret": FALCON_CLIENT_SECRET,
}).encode()
req = Request(url, data=data, method="POST")
req.add_header("Content-Type", "application/x-www-form-urlencoded")
with urlopen(req) as resp:
body = json.loads(resp.read())
return body["access_token"]
def api_get(token: str, endpoint: str, params: dict = None) -> dict:
"""Make authenticated GET request to Falcon API."""
url = f"{FALCON_BASE_URL}{endpoint}"
if params:
url += "?" + urlencode(params)
req = Request(url, method="GET")
req.add_header("Authorization", f"Bearer {token}")
req.add_header("Accept", "application/json")
with urlopen(req) as resp:
return json.loads(resp.read())
def get_all_host_ids(token: str) -> list:
"""Retrieve all host device IDs from Falcon."""
all_ids = []
offset = 0
limit = 5000
while True:
result = api_get(token, "/devices/queries/devices-scroll/v1", {
"limit": limit,
"offset": offset,
})
resources = result.get("resources", [])
if not resources:
break
all_ids.extend(resources)
offset += limit
if len(resources) < limit:
break
return all_ids
def get_host_details(token: str, host_ids: list) -> list:
"""Retrieve detailed host information for given IDs (batches of 100)."""
all_details = []
for i in range(0, len(host_ids), 100):
batch = host_ids[i:i + 100]
url = f"{FALCON_BASE_URL}/devices/entities/devices/v2"
data = json.dumps({"ids": batch}).encode()
req = Request(url, data=data, method="POST")
req.add_header("Authorization", f"Bearer {token}")
req.add_header("Content-Type", "application/json")
with urlopen(req) as resp:
body = json.loads(resp.read())
all_details.extend(body.get("resources", []))
return all_details
def analyze_deployment(hosts: list) -> dict:
"""Analyze deployment coverage and sensor health."""
now = datetime.utcnow()
stale_threshold = now - timedelta(days=7)
analysis = {
"total_hosts": len(hosts),
"os_breakdown": {},
"status_breakdown": {"online": 0, "offline": 0, "stale": 0},
"sensor_versions": {},
"rfm_hosts": [],
"stale_hosts": [],
"unprotected_hosts": [],
}
for host in hosts:
platform = host.get("platform_name", "Unknown")
analysis["os_breakdown"][platform] = analysis["os_breakdown"].get(platform, 0) + 1
version = host.get("agent_version", "Unknown")
analysis["sensor_versions"][version] = analysis["sensor_versions"].get(version, 0) + 1
status = host.get("status", "unknown")
last_seen = host.get("last_seen", "")
if last_seen:
try:
last_seen_dt = datetime.fromisoformat(last_seen.replace("Z", "+00:00")).replace(tzinfo=None)
if last_seen_dt < stale_threshold:
analysis["status_breakdown"]["stale"] += 1
analysis["stale_hosts"].append({
"hostname": host.get("hostname", ""),
"last_seen": last_seen,
"platform": platform,
})
elif status == "normal":
analysis["status_breakdown"]["online"] += 1
else:
analysis["status_breakdown"]["offline"] += 1
except (ValueError, TypeError):
analysis["status_breakdown"]["offline"] += 1
reduced_functionality = host.get("reduced_functionality_mode", "no")
if reduced_functionality == "yes":
analysis["rfm_hosts"].append({
"hostname": host.get("hostname", ""),
"reason": host.get("device_policies", {}).get("prevention", {}).get("policy_type", "unknown"),
})
prevention_policy = host.get("device_policies", {}).get("prevention", {})
if not prevention_policy.get("applied", False):
analysis["unprotected_hosts"].append({
"hostname": host.get("hostname", ""),
"platform": platform,
"reason": "Prevention policy not applied",
})
return analysis
def generate_deployment_report(analysis: dict, output_path: str) -> None:
"""Generate deployment status report."""
report = {
"report_generated": datetime.utcnow().isoformat() + "Z",
"deployment_summary": {
"total_managed_hosts": analysis["total_hosts"],
"online": analysis["status_breakdown"]["online"],
"offline": analysis["status_breakdown"]["offline"],
"stale_7_days": analysis["status_breakdown"]["stale"],
"in_rfm": len(analysis["rfm_hosts"]),
"unprotected": len(analysis["unprotected_hosts"]),
},
"os_distribution": analysis["os_breakdown"],
"sensor_version_distribution": analysis["sensor_versions"],
"hosts_requiring_attention": {
"stale_hosts": analysis["stale_hosts"][:50],
"rfm_hosts": analysis["rfm_hosts"][:50],
"unprotected_hosts": analysis["unprotected_hosts"][:50],
},
}
with open(output_path, "w", encoding="utf-8") as f:
json.dump(report, f, indent=2)
def export_stale_hosts_csv(stale_hosts: list, output_path: str) -> None:
"""Export stale hosts to CSV for remediation tracking."""
with open(output_path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["Hostname", "Platform", "Last Seen", "Action Required"])
for host in stale_hosts:
writer.writerow([
host["hostname"],
host.get("platform", ""),
host["last_seen"],
"Investigate connectivity / reinstall sensor",
])
if __name__ == "__main__":
if not FALCON_CLIENT_ID or not FALCON_CLIENT_SECRET:
print("Error: Set FALCON_CLIENT_ID and FALCON_CLIENT_SECRET environment variables")
print()
print("Required environment variables:")
print(" FALCON_CLIENT_ID - API client ID from Falcon Console")
print(" FALCON_CLIENT_SECRET - API client secret")
print(" FALCON_BASE_URL - (Optional) API base URL (default: https://api.crowdstrike.com)")
sys.exit(1)
print("Authenticating with CrowdStrike Falcon API...")
token = get_oauth_token()
print("Retrieving host inventory...")
host_ids = get_all_host_ids(token)
print(f"Found {len(host_ids)} managed hosts")
print("Fetching host details...")
hosts = get_host_details(token, host_ids)
print("Analyzing deployment coverage...")
analysis = analyze_deployment(hosts)
report_path = "falcon_deployment_report.json"
generate_deployment_report(analysis, report_path)
print(f"\nDeployment report: {report_path}")
if analysis["stale_hosts"]:
csv_path = "falcon_stale_hosts.csv"
export_stale_hosts_csv(analysis["stale_hosts"], csv_path)
print(f"Stale hosts CSV: {csv_path}")
print(f"\n--- Deployment Summary ---")
print(f"Total hosts: {analysis['total_hosts']}")
print(f"Online: {analysis['status_breakdown']['online']}")
print(f"Offline: {analysis['status_breakdown']['offline']}")
print(f"Stale (>7 days): {analysis['status_breakdown']['stale']}")
print(f"In RFM: {len(analysis['rfm_hosts'])}")
print(f"Unprotected: {len(analysis['unprotected_hosts'])}")
print(f"\nOS Distribution: {json.dumps(analysis['os_breakdown'], indent=2)}")
print(f"Sensor Versions: {json.dumps(analysis['sensor_versions'], indent=2)}")