threat intelligence

Implementing Threat Intelligence Lifecycle Management

Implement a structured threat intelligence lifecycle encompassing planning, collection, processing, analysis, dissemination, and feedback stages to produce actionable intelligence for organizational decision-making.

analysiscollectioncti-programdisseminationintelligence-cyclelifecyclestrategic-intelligencethreat-intelligence
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

The threat intelligence lifecycle is a structured, iterative process for transforming raw data into actionable intelligence. Based on the intelligence cycle used by military and government agencies, it comprises six phases: Direction (requirements gathering), Collection (data acquisition), Processing (normalization and deduplication), Analysis (contextualization and assessment), Dissemination (distribution to stakeholders), and Feedback (evaluation and refinement). This skill covers building each phase with tooling, metrics, and integration points for a mature CTI program.

When to Use

  • When deploying or configuring implementing threat intelligence lifecycle management capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Python 3.9+ with pymisp, stix2, requests, pandas libraries
  • MISP or OpenCTI as threat intelligence platform
  • Ticketing system (Jira, ServiceNow) for requirements management
  • SIEM integration (Splunk, Elastic) for indicator operationalization
  • Understanding of intelligence analysis techniques (ACH, Diamond Model)

Key Concepts

Intelligence Requirements (IR)

Priority Intelligence Requirements (PIRs) define what the organization needs to know. Examples: Which threat actors target our sector? What vulnerabilities are being actively exploited? Are our brand or credentials being traded on dark web? PIRs drive collection planning and ensure intelligence production is relevant.

Collection Management Framework

A collection management framework maps intelligence requirements to collection sources, tracks collection gaps, and ensures coverage across the threat landscape. Sources include OSINT, commercial feeds, ISAC sharing, internal telemetry, and human intelligence from industry contacts.

Intelligence Levels

Strategic intelligence informs executive decision-making (threat landscape, risk trends, geopolitical context). Operational intelligence supports security operations (campaign tracking, actor TTPs, attack timing). Tactical intelligence enables immediate defense (IOCs, detection rules, blocklists).

Workflow

Step 1: Define Intelligence Requirements

import json
from datetime import datetime
from enum import Enum
 
class Priority(Enum):
    CRITICAL = 1
    HIGH = 2
    MEDIUM = 3
    LOW = 4
 
class IntelligenceRequirement:
    def __init__(self, requirement_id, question, priority, stakeholder,
                 intelligence_level, collection_sources=None):
        self.id = requirement_id
        self.question = question
        self.priority = priority
        self.stakeholder = stakeholder
        self.level = intelligence_level
        self.sources = collection_sources or []
        self.created = datetime.now().isoformat()
        self.status = "active"
        self.last_answered = None
 
    def to_dict(self):
        return {
            "id": self.id,
            "question": self.question,
            "priority": self.priority.name,
            "stakeholder": self.stakeholder,
            "intelligence_level": self.level,
            "collection_sources": self.sources,
            "created": self.created,
            "status": self.status,
            "last_answered": self.last_answered,
        }
 
class RequirementsManager:
    def __init__(self):
        self.requirements = []
 
    def add_requirement(self, requirement):
        self.requirements.append(requirement)
        print(f"[+] Added IR-{requirement.id}: {requirement.question[:60]}...")
 
    def get_active_requirements(self, priority=None, level=None):
        filtered = [r for r in self.requirements if r.status == "active"]
        if priority:
            filtered = [r for r in filtered if r.priority == priority]
        if level:
            filtered = [r for r in filtered if r.level == level]
        return filtered
 
    def export_requirements(self, output_file="intelligence_requirements.json"):
        data = [r.to_dict() for r in self.requirements]
        with open(output_file, "w") as f:
            json.dump(data, f, indent=2)
        print(f"[+] Exported {len(data)} requirements to {output_file}")
 
# Define organizational PIRs
mgr = RequirementsManager()
mgr.add_requirement(IntelligenceRequirement(
    "PIR-001", "Which threat actors are actively targeting our sector?",
    Priority.CRITICAL, "CISO", "strategic",
    ["MITRE ATT&CK", "ISAC feeds", "Vendor reports"],
))
mgr.add_requirement(IntelligenceRequirement(
    "PIR-002", "What vulnerabilities are being actively exploited in the wild?",
    Priority.CRITICAL, "Vulnerability Management", "operational",
    ["CISA KEV", "Exploit-DB", "VulnCheck", "Shodan"],
))
mgr.add_requirement(IntelligenceRequirement(
    "PIR-003", "Are any organization credentials or data exposed on dark web?",
    Priority.HIGH, "SOC Manager", "tactical",
    ["Dark web monitoring", "Paste site monitoring", "Breach databases"],
))
mgr.add_requirement(IntelligenceRequirement(
    "PIR-004", "What are the emerging attack techniques against cloud infrastructure?",
    Priority.HIGH, "Cloud Security", "operational",
    ["ATT&CK Cloud matrix", "Vendor advisories", "ISAC bulletins"],
))
mgr.export_requirements()

Step 2: Build Collection Pipeline

import requests
from datetime import datetime, timedelta
 
class CollectionPipeline:
    def __init__(self, config):
        self.config = config
        self.collected_data = []
 
    def collect_cisa_kev(self):
        """Collect CISA Known Exploited Vulnerabilities catalog."""
        url = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
        resp = requests.get(url, timeout=30)
        if resp.status_code == 200:
            data = resp.json()
            vulns = data.get("vulnerabilities", [])
            self.collected_data.append({
                "source": "CISA KEV",
                "type": "vulnerability",
                "count": len(vulns),
                "collected_at": datetime.now().isoformat(),
                "data": vulns,
            })
            print(f"[+] CISA KEV: {len(vulns)} known exploited vulnerabilities")
            return vulns
        return []
 
    def collect_otx_pulses(self, api_key, days=7):
        """Collect recent OTX pulses."""
        headers = {"X-OTX-API-KEY": api_key}
        since = (datetime.now() - timedelta(days=days)).isoformat()
        url = f"https://otx.alienvault.com/api/v1/pulses/subscribed?modified_since={since}"
        resp = requests.get(url, headers=headers, timeout=30)
        if resp.status_code == 200:
            pulses = resp.json().get("results", [])
            self.collected_data.append({
                "source": "AlienVault OTX",
                "type": "threat_intelligence",
                "count": len(pulses),
                "collected_at": datetime.now().isoformat(),
            })
            print(f"[+] OTX: {len(pulses)} pulses in last {days} days")
            return pulses
        return []
 
    def collect_abuse_ch(self):
        """Collect recent malware samples from MalwareBazaar."""
        url = "https://mb-api.abuse.ch/api/v1/"
        resp = requests.post(url, data={"query": "get_recent", "selector": "time"}, timeout=30)
        if resp.status_code == 200:
            data = resp.json().get("data", [])
            self.collected_data.append({
                "source": "MalwareBazaar",
                "type": "malware_samples",
                "count": len(data),
                "collected_at": datetime.now().isoformat(),
            })
            print(f"[+] MalwareBazaar: {len(data)} recent samples")
            return data
        return []
 
    def get_collection_summary(self):
        summary = {
            "total_sources": len(self.collected_data),
            "total_items": sum(d.get("count", 0) for d in self.collected_data),
            "sources": [
                {"name": d["source"], "type": d["type"], "count": d["count"]}
                for d in self.collected_data
            ],
        }
        return summary
 
pipeline = CollectionPipeline({})
pipeline.collect_cisa_kev()
pipeline.collect_abuse_ch()
print(json.dumps(pipeline.get_collection_summary(), indent=2))

Step 3: Process and Normalize Data

class IntelligenceProcessor:
    def __init__(self):
        self.processed_items = []
        self.dedup_hashes = set()
 
    def process_collection(self, raw_data, source_name):
        """Normalize and deduplicate collected intelligence."""
        processed = []
        duplicates = 0
 
        for item in raw_data:
            normalized = self._normalize(item, source_name)
            if normalized:
                item_hash = self._compute_hash(normalized)
                if item_hash not in self.dedup_hashes:
                    self.dedup_hashes.add(item_hash)
                    normalized["processed_at"] = datetime.now().isoformat()
                    processed.append(normalized)
                else:
                    duplicates += 1
 
        self.processed_items.extend(processed)
        print(f"[+] Processed {len(processed)} items from {source_name} "
              f"({duplicates} duplicates removed)")
        return processed
 
    def _normalize(self, item, source):
        """Normalize item to standard format."""
        return {
            "source": source,
            "type": item.get("type", "unknown"),
            "value": item.get("value", item.get("indicator", "")),
            "confidence": item.get("confidence", 50),
            "tlp": item.get("tlp", "green"),
            "tags": item.get("tags", []),
            "first_seen": item.get("first_seen", item.get("date_added", "")),
            "raw": item,
        }
 
    def _compute_hash(self, item):
        import hashlib
        key = f"{item['type']}:{item['value']}:{item['source']}"
        return hashlib.sha256(key.encode()).hexdigest()
 
processor = IntelligenceProcessor()

Step 4: Analyze and Produce Intelligence

class IntelligenceAnalyzer:
    def __init__(self, requirements, processed_data):
        self.requirements = requirements
        self.data = processed_data
 
    def answer_requirement(self, requirement_id):
        """Produce intelligence answering a specific requirement."""
        req = next((r for r in self.requirements if r.id == requirement_id), None)
        if not req:
            return None
 
        # Filter relevant data based on requirement type
        relevant = self.data  # In practice, filter by requirement topic
        analysis = {
            "requirement_id": requirement_id,
            "question": req.question,
            "intelligence_level": req.level,
            "data_points_analyzed": len(relevant),
            "produced_at": datetime.now().isoformat(),
            "key_findings": [],
            "confidence": "medium",
            "recommendations": [],
        }
        return analysis
 
    def produce_daily_brief(self):
        """Produce daily threat intelligence brief."""
        brief = {
            "date": datetime.now().strftime("%Y-%m-%d"),
            "total_items_processed": len(self.data),
            "highlights": [],
            "active_requirements_status": [
                {"id": r.id, "question": r.question[:80], "status": r.status}
                for r in self.requirements if r.status == "active"
            ],
        }
        return brief

Step 5: Disseminate and Track Feedback

class IntelligenceDisseminator:
    def __init__(self):
        self.distribution_log = []
 
    def distribute_report(self, report, channels, classification="TLP:GREEN"):
        """Distribute intelligence report to appropriate channels."""
        for channel in channels:
            entry = {
                "report_id": report.get("requirement_id", "daily"),
                "channel": channel,
                "classification": classification,
                "distributed_at": datetime.now().isoformat(),
                "status": "sent",
            }
            self.distribution_log.append(entry)
            print(f"  [+] Distributed to {channel}")
 
    def collect_feedback(self, report_id, stakeholder, rating, comments=""):
        """Collect stakeholder feedback on intelligence product."""
        feedback = {
            "report_id": report_id,
            "stakeholder": stakeholder,
            "rating": rating,  # 1-5
            "comments": comments,
            "received_at": datetime.now().isoformat(),
        }
        print(f"[+] Feedback received from {stakeholder}: {rating}/5")
        return feedback
 
    def calculate_metrics(self):
        """Calculate CTI program performance metrics."""
        metrics = {
            "total_products_distributed": len(self.distribution_log),
            "distribution_by_channel": {},
        }
        for entry in self.distribution_log:
            channel = entry["channel"]
            if channel not in metrics["distribution_by_channel"]:
                metrics["distribution_by_channel"][channel] = 0
            metrics["distribution_by_channel"][channel] += 1
        return metrics
 
disseminator = IntelligenceDisseminator()

Validation Criteria

  • Intelligence requirements defined with priorities and stakeholders
  • Collection pipeline gathering from multiple sources
  • Processing deduplicates and normalizes data correctly
  • Analysis produces intelligence answering specific requirements
  • Dissemination reaches appropriate stakeholders through right channels
  • Feedback mechanism captures and incorporates stakeholder input

References

Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 1

api-reference.md4.9 KB

API Reference: Threat Intelligence Lifecycle Management

Libraries Used

Library Purpose
pymisp MISP threat intelligence platform API client
stix2 Create, parse, and manipulate STIX 2.1 objects
requests HTTP client for external TI feed APIs
json Parse and serialize intelligence data

Installation

pip install pymisp stix2 requests

Authentication

MISP Connection

from pymisp import PyMISP
import os
 
MISP_URL = os.environ["MISP_URL"]
MISP_KEY = os.environ["MISP_API_KEY"]
MISP_VERIFYCERT = os.environ.get("MISP_VERIFY", "True") == "True"
 
misp = PyMISP(MISP_URL, MISP_KEY, ssl=MISP_VERIFYCERT)

MISP API Operations

Search for Events

def search_events(tags=None, date_from=None, published=True):
    results = misp.search(
        controller="events",
        tags=tags,
        date_from=date_from,
        published=published,
        limit=100,
    )
    return results

Create a Threat Intelligence Event

from pymisp import MISPEvent, MISPAttribute
 
def create_ti_event(info, threat_level=2, analysis=1):
    event = MISPEvent()
    event.info = info
    event.threat_level_id = threat_level  # 1=High, 2=Medium, 3=Low, 4=Undefined
    event.analysis = analysis  # 0=Initial, 1=Ongoing, 2=Completed
    event.distribution = 1  # 1=This community
    created = misp.add_event(event)
    return created

Add Indicators to an Event

def add_indicators(event_id, indicators):
    for ioc in indicators:
        attr = MISPAttribute()
        attr.type = ioc["type"]  # "ip-dst", "domain", "sha256", "url"
        attr.value = ioc["value"]
        attr.category = ioc.get("category", "Network activity")
        attr.to_ids = ioc.get("to_ids", True)
        attr.comment = ioc.get("comment", "")
        misp.add_attribute(event_id, attr)

Search for Specific IOCs

def search_ioc(ioc_type, value):
    results = misp.search(
        controller="attributes",
        type_attribute=ioc_type,
        value=value,
    )
    return results

Tag Management

# Add TLP marking
misp.tag(event_id, "tlp:amber")
 
# Add threat actor tag
misp.tag(event_id, "mitre-attack-pattern:T1566.001")
 
# Add custom taxonomy
misp.tag(event_id, "adversary:APT29")

STIX 2.1 Intelligence Objects

Create STIX Indicator

import stix2
 
indicator = stix2.Indicator(
    name="Cobalt Strike C2 Domain",
    pattern="[domain-name:value = 'c2.evil.example.com']",
    pattern_type="stix",
    valid_from="2025-01-15T00:00:00Z",
    labels=["malicious-activity"],
    confidence=85,
    external_references=[
        stix2.ExternalReference(
            source_name="Internal IR",
            description="Observed during incident IR-2025-001",
        )
    ],
)

Create STIX Threat Actor

threat_actor = stix2.ThreatActor(
    name="APT29",
    aliases=["Cozy Bear", "The Dukes"],
    threat_actor_types=["nation-state"],
    roles=["agent"],
    sophistication="expert",
    resource_level="government",
    primary_motivation="espionage",
)

Create Relationships and Bundle

relationship = stix2.Relationship(
    relationship_type="indicates",
    source_ref=indicator.id,
    target_ref=threat_actor.id,
    confidence=80,
)
 
bundle = stix2.Bundle(objects=[indicator, threat_actor, relationship])

Convert MISP Event to STIX

def misp_to_stix(event):
    stix_objects = []
    for attr in event.get("Attribute", []):
        if attr["type"] == "ip-dst":
            stix_objects.append(stix2.Indicator(
                name=f"Malicious IP: {attr['value']}",
                pattern=f"[ipv4-addr:value = '{attr['value']}']",
                pattern_type="stix",
                valid_from=attr["timestamp"],
            ))
        elif attr["type"] == "domain":
            stix_objects.append(stix2.Indicator(
                name=f"Malicious Domain: {attr['value']}",
                pattern=f"[domain-name:value = '{attr['value']}']",
                pattern_type="stix",
                valid_from=attr["timestamp"],
            ))
    return stix2.Bundle(objects=stix_objects)

Intelligence Lifecycle Phases

Phase MISP Action STIX Object
Collection misp.add_event() Bundle
Processing misp.add_attribute() Indicator, ObservedData
Analysis misp.tag(), correlations Relationship, ThreatActor
Dissemination misp.publish(), TAXII push Collection (TAXII)
Feedback misp.add_sighting() Sighting

Output Format

{
  "lifecycle_phase": "analysis",
  "events_processed": 42,
  "indicators_created": 156,
  "stix_objects": {
    "indicators": 120,
    "threat_actors": 5,
    "malware": 8,
    "relationships": 95,
    "attack_patterns": 23
  },
  "tlp_distribution": {
    "tlp:white": 30,
    "tlp:green": 45,
    "tlp:amber": 65,
    "tlp:red": 16
  }
}

Scripts 1

agent.py8.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Threat intelligence lifecycle management agent.

Manages the threat intelligence lifecycle: collection from feeds,
processing/normalization of IOCs, analysis/enrichment via VirusTotal
and AbuseIPDB, dissemination to SIEM/firewalls, and tracking of
IOC aging and confidence scoring.
"""
import argparse
import csv
import hashlib
import json
import os
import re
import sys
from datetime import datetime, timezone, timedelta

try:
    import requests
except ImportError:
    requests = None


IOC_PATTERNS = {
    "ipv4": re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b'),
    "domain": re.compile(r'\b(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}\b', re.I),
    "md5": re.compile(r'\b[a-fA-F0-9]{32}\b'),
    "sha1": re.compile(r'\b[a-fA-F0-9]{40}\b'),
    "sha256": re.compile(r'\b[a-fA-F0-9]{64}\b'),
    "url": re.compile(r'https?://[^\s<>"{}|\\^`\[\]]+'),
    "email": re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'),
}


def extract_iocs(text):
    """Extract IOCs from unstructured text."""
    iocs = {}
    for ioc_type, pattern in IOC_PATTERNS.items():
        matches = set(pattern.findall(text))
        # Filter out private IPs for ipv4
        if ioc_type == "ipv4":
            matches = {ip for ip in matches
                      if not ip.startswith(("10.", "192.168.", "127.", "0."))
                      and not ip.startswith("172.") or not (16 <= int(ip.split(".")[1]) <= 31)}
        if matches:
            iocs[ioc_type] = sorted(matches)
    return iocs


def load_ioc_feed(source):
    """Load IOCs from a file (JSON, CSV, or plain text)."""
    ext = os.path.splitext(source)[1].lower()
    iocs = []

    if ext == ".json":
        with open(source, "r") as f:
            data = json.load(f)
        if isinstance(data, list):
            iocs = data
        elif isinstance(data, dict):
            iocs = data.get("indicators", data.get("iocs", data.get("data", [])))
    elif ext == ".csv":
        with open(source, "r", newline="") as f:
            reader = csv.DictReader(f)
            iocs = list(reader)
    else:
        with open(source, "r") as f:
            text = f.read()
        extracted = extract_iocs(text)
        for ioc_type, values in extracted.items():
            for v in values:
                iocs.append({"type": ioc_type, "value": v, "source": source})

    return iocs


def normalize_ioc(ioc):
    """Normalize IOC into standard format."""
    if isinstance(ioc, str):
        for ioc_type, pattern in IOC_PATTERNS.items():
            if pattern.fullmatch(ioc):
                return {"type": ioc_type, "value": ioc.lower().strip()}
        return {"type": "unknown", "value": ioc.strip()}

    return {
        "type": (ioc.get("type") or ioc.get("indicator_type") or "unknown").lower(),
        "value": (ioc.get("value") or ioc.get("indicator") or "").lower().strip(),
        "source": ioc.get("source", ""),
        "confidence": ioc.get("confidence", 50),
        "first_seen": ioc.get("first_seen", ""),
        "last_seen": ioc.get("last_seen", ""),
        "tags": ioc.get("tags", []),
        "description": ioc.get("description", ""),
    }


def enrich_ioc_virustotal(ioc_value, ioc_type, api_key):
    """Enrich IOC via VirusTotal API v3."""
    if not requests or not api_key:
        return {}

    headers = {"x-apikey": api_key}
    base = "https://www.virustotal.com/api/v3"

    if ioc_type in ("md5", "sha1", "sha256"):
        url = f"{base}/files/{ioc_value}"
    elif ioc_type == "domain":
        url = f"{base}/domains/{ioc_value}"
    elif ioc_type == "ipv4":
        url = f"{base}/ip_addresses/{ioc_value}"
    elif ioc_type == "url":
        url_id = hashlib.sha256(ioc_value.encode()).hexdigest()
        url = f"{base}/urls/{url_id}"
    else:
        return {}

    try:
        resp = requests.get(url, headers=headers, timeout=15)
        if resp.status_code == 200:
            data = resp.json().get("data", {}).get("attributes", {})
            stats = data.get("last_analysis_stats", {})
            return {
                "malicious": stats.get("malicious", 0),
                "suspicious": stats.get("suspicious", 0),
                "harmless": stats.get("harmless", 0),
                "undetected": stats.get("undetected", 0),
                "reputation": data.get("reputation", 0),
                "source": "virustotal",
            }
    except requests.RequestException:
        pass
    return {}


def calculate_confidence(ioc, enrichment=None):
    """Calculate confidence score for an IOC (0-100)."""
    score = ioc.get("confidence", 50)

    # Boost for VT detections
    if enrichment:
        malicious = enrichment.get("malicious", 0)
        if malicious > 10:
            score = min(score + 30, 100)
        elif malicious > 5:
            score = min(score + 20, 100)
        elif malicious > 0:
            score = min(score + 10, 100)
        elif enrichment.get("harmless", 0) > 20:
            score = max(score - 20, 0)

    # Decay based on age
    first_seen = ioc.get("first_seen", "")
    if first_seen:
        try:
            if "T" in first_seen:
                seen_dt = datetime.fromisoformat(first_seen.replace("Z", "+00:00"))
            else:
                seen_dt = datetime.strptime(first_seen[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc)
            age_days = (datetime.now(timezone.utc) - seen_dt).days
            if age_days > 180:
                score = max(score - 20, 0)
            elif age_days > 90:
                score = max(score - 10, 0)
        except (ValueError, TypeError):
            pass

    return min(max(score, 0), 100)


def format_summary(iocs, enriched_count):
    """Print lifecycle report."""
    print(f"\n{'='*60}")
    print(f"  Threat Intelligence Lifecycle Report")
    print(f"{'='*60}")
    print(f"  Total IOCs    : {len(iocs)}")
    print(f"  Enriched      : {enriched_count}")

    by_type = {}
    for ioc in iocs:
        t = ioc.get("type", "unknown")
        by_type[t] = by_type.get(t, 0) + 1
    print(f"\n  By Type:")
    for t, count in sorted(by_type.items(), key=lambda x: -x[1]):
        print(f"    {t:12s}: {count}")

    high_conf = [i for i in iocs if i.get("confidence", 0) >= 80]
    med_conf = [i for i in iocs if 50 <= i.get("confidence", 0) < 80]
    low_conf = [i for i in iocs if i.get("confidence", 0) < 50]
    print(f"\n  By Confidence:")
    print(f"    High (>=80) : {len(high_conf)}")
    print(f"    Medium      : {len(med_conf)}")
    print(f"    Low (<50)   : {len(low_conf)}")

    if high_conf:
        print(f"\n  High-Confidence IOCs:")
        for i in high_conf[:15]:
            print(f"    [{i['type']:8s}] {i['value'][:50]:50s} (confidence: {i.get('confidence', 0)})")


def main():
    parser = argparse.ArgumentParser(description="Threat intelligence lifecycle management agent")
    parser.add_argument("--source", required=True, help="IOC source file (JSON/CSV/text)")
    parser.add_argument("--vt-key", help="VirusTotal API key (or VT_API_KEY env)")
    parser.add_argument("--enrich", action="store_true", help="Enrich IOCs via VirusTotal")
    parser.add_argument("--min-confidence", type=int, default=0, help="Min confidence to include")
    parser.add_argument("--output", "-o", help="Output JSON report")
    parser.add_argument("--verbose", "-v", action="store_true")
    args = parser.parse_args()

    vt_key = args.vt_key or os.environ.get("VT_API_KEY", "")

    raw_iocs = load_ioc_feed(args.source)
    print(f"[*] Loaded {len(raw_iocs)} raw IOCs from {args.source}")

    iocs = [normalize_ioc(ioc) for ioc in raw_iocs]
    iocs = [i for i in iocs if i.get("value")]

    # Deduplicate
    seen = set()
    unique_iocs = []
    for ioc in iocs:
        key = f"{ioc['type']}:{ioc['value']}"
        if key not in seen:
            seen.add(key)
            unique_iocs.append(ioc)
    iocs = unique_iocs
    print(f"[*] {len(iocs)} unique IOCs after dedup")

    enriched_count = 0
    if args.enrich and vt_key:
        print(f"[*] Enriching IOCs via VirusTotal...")
        for ioc in iocs[:100]:  # Rate limit
            enrichment = enrich_ioc_virustotal(ioc["value"], ioc["type"], vt_key)
            if enrichment:
                ioc["enrichment"] = enrichment
                enriched_count += 1
            ioc["confidence"] = calculate_confidence(ioc, enrichment)
    else:
        for ioc in iocs:
            ioc["confidence"] = calculate_confidence(ioc)

    iocs = [i for i in iocs if i.get("confidence", 0) >= args.min_confidence]
    iocs.sort(key=lambda x: -x.get("confidence", 0))

    format_summary(iocs, enriched_count)

    report = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "tool": "TI Lifecycle Manager",
        "source": args.source,
        "total_iocs": len(iocs),
        "enriched": enriched_count,
        "iocs": iocs,
    }

    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
        print(f"\n[+] Report saved to {args.output}")
    elif args.verbose:
        print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()
Keep exploring