# analyzing-malicious-url-with-urlscan

URLScan.io is a free service for scanning and analyzing suspicious URLs. It captures screenshots, DOM content, HTTP transactions, JavaScript behavior, and network connections of web pages in an isolat

- **Kind:** skill
- **Source:** https://github.com/mukul975/Anthropic-Cybersecurity-Skills
- **Page:** https://forefy.com/skills/c25fb523-34cb-4f37-b5e7-4b62b500e1a1
- **API (JSON + files):** https://forefy.com/api/asr/c25fb523-34cb-4f37-b5e7-4b62b500e1a1

---

## LICENSE

```

```

## SKILL.md

---
name: analyzing-malicious-url-with-urlscan
description: URLScan.io is a free service for scanning and analyzing suspicious URLs.
  It captures screenshots, DOM content, HTTP transactions, JavaScript behavior, and
  network connections of web pages in an isolat
domain: cybersecurity
subdomain: phishing-defense
tags:
- phishing
- email-security
- social-engineering
- dmarc
- awareness
- url-analysis
- threat-intelligence
version: '1.0'
author: mahipal
license: Apache-2.0
atlas_techniques:
- AML.T0052
nist_csf:
- PR.AT-01
- DE.CM-09
- RS.CO-02
- DE.AE-02
mitre_attack:
- T1566.002
- T1204.001
- T1598.003
---
# Analyzing Malicious URL with URLScan

## Overview
URLScan.io is a free service for scanning and analyzing suspicious URLs. It captures screenshots, DOM content, HTTP transactions, JavaScript behavior, and network connections of web pages in an isolated environment. This skill covers using URLScan's web interface and API to investigate phishing URLs, credential harvesting pages, and malicious redirects without exposing the analyst's system to risk.


## When to Use

- When investigating security incidents that require analyzing malicious url with urlscan
- When building detection rules or threat hunting queries for this domain
- When SOC analysts need structured procedures for this analysis type
- When validating security monitoring coverage for related attack techniques

## Prerequisites
- URLScan.io account (free tier available, API key for automation)
- Python 3.8+ with requests library
- Understanding of HTTP protocols and web technologies
- Familiarity with phishing URL patterns

## Key Concepts

### URLScan Capabilities
1. **Safe browsing**: Renders URLs in isolated Chromium instance
2. **Screenshot capture**: Visual snapshot of the rendered page
3. **DOM analysis**: Full HTML content after JavaScript execution
4. **Network log**: All HTTP requests made by the page (HAR format)
5. **Certificate analysis**: SSL/TLS certificate details
6. **Technology detection**: Identifies web frameworks and libraries
7. **IP/ASN mapping**: Infrastructure intelligence
8. **Verdict**: Community and automated classification

### Phishing URL Red Flags
- Newly registered domains (< 30 days)
- Free hosting services (Wix, GitHub Pages, Firebase)
- URL shorteners hiding final destination
- Excessive subdomain depth (login.microsoft.com.evil.com)
- Brand name in subdomain or path, not domain
- Non-standard ports
- Data URIs or base64-encoded content
- JavaScript-heavy pages with minimal HTML

## Workflow

### Step 1: Submit URL to URLScan
```
Web: Navigate to https://urlscan.io and submit the suspicious URL
API: POST https://urlscan.io/api/v1/scan/
     Header: API-Key: your-api-key
     Body: {"url": "https://suspicious-url.com", "visibility": "private"}
```

### Step 2: Analyze Results
- Review screenshot for brand impersonation
- Check redirects and final destination URL
- Examine DOM for credential input forms
- Review network requests for data exfiltration endpoints
- Check SSL certificate validity and issuer

### Step 3: Extract IOCs
- Domains and IPs contacted
- URLs in redirect chain
- SHA-256 hashes of page resources
- JavaScript file hashes

### Step 4: Cross-Reference with Threat Intelligence
Use the `scripts/process.py` to automate URL scanning, extract IOCs, and cross-reference with VirusTotal, PhishTank, and Google Safe Browsing.

## Tools & Resources
- **URLScan.io**: https://urlscan.io/
- **URLScan API**: https://urlscan.io/docs/api/
- **VirusTotal URL Scanner**: https://www.virustotal.com/
- **PhishTank**: https://phishtank.org/
- **Google Safe Browsing**: https://transparencyreport.google.com/safe-browsing/search
- **Any.Run**: https://any.run/ (interactive sandbox)
- **Hybrid Analysis**: https://www.hybrid-analysis.com/

## Validation
- Successfully scan a suspicious URL via API
- Extract screenshot and identify brand impersonation
- Document complete redirect chain
- Generate IOC list from scan results
- Cross-reference findings with at least 2 threat intelligence sources

## assets

```

```

## assets/template.md

# URL Analysis Report Template

## Analysis Information
- **Analyst**: [Name]
- **Date**: [YYYY-MM-DD]
- **Case ID**: [CASE-XXXX]
- **Source**: [User report / Email gateway / SIEM alert]

## URL Details
| Field | Value |
|---|---|
| Original URL | |
| Defanged URL | hxxps://... |
| Final URL (after redirects) | |
| URLScan UUID | |
| Scan visibility | private/public |

## Page Analysis
| Field | Value |
|---|---|
| Page Title | |
| HTTP Status | |
| Server | |
| Domain | |
| IP Address | |
| ASN | |
| Country | |
| Login Form Detected | Yes/No |

## TLS Certificate
| Field | Value |
|---|---|
| Issuer | |
| Subject | |
| Valid From | |
| Valid To | |
| Certificate Age | |

## Redirect Chain
| # | URL | Status |
|---|---|---|
| 1 (original) | | |
| 2 | | |
| 3 (final) | | |

## Threat Intelligence Cross-Reference
| Source | Result | Score |
|---|---|---|
| URLScan Verdict | | |
| VirusTotal | /XX engines | |
| PhishTank | | |
| Google Safe Browsing | | |
| AbuseIPDB | | |

## IOCs Extracted
### Domains
| Domain | Role | Reputation |
|---|---|---|
| | | |

### IP Addresses
| IP | ASN | Country | Reputation |
|---|---|---|---|
| | | | |

### File Hashes
| Hash (SHA-256) | Type | Size |
|---|---|---|
| | | |

## Classification
- [ ] Phishing - Credential Harvesting
- [ ] Phishing - Malware Delivery
- [ ] Scam / Fraud
- [ ] Benign
- [ ] Inconclusive

## Recommended Actions
- [ ] Block domain at proxy/firewall
- [ ] Block IP at firewall
- [ ] Add to email gateway blocklist
- [ ] Submit to PhishTank / APWG
- [ ] Notify affected users
- [ ] Request domain takedown

## Notes
[Additional analysis observations]

## references

```

```

## references/api-reference.md

# API Reference: urlscan.io URL Analysis

## Base URL
```
https://urlscan.io/api/v1
```

## Authentication
```
API-Key: YOUR_API_KEY
```

## Submit Scan
```
POST /scan/
```
```json
{"url": "https://example.com", "visibility": "private"}
```
| Field | Values | Description |
|-------|--------|-------------|
| `url` | URL string | URL to scan |
| `visibility` | public/unlisted/private | Scan visibility |

Response: `{"uuid": "...", "result": "https://urlscan.io/result/UUID/", "api": "..."}`

## Get Result
```
GET /result/{uuid}/
```
Returns 404 while scanning, 200 when complete.

## Search
```
GET /search/?q=domain:example.com&size=100
```
Query fields: `domain:`, `ip:`, `server:`, `country:`, `filename:`, `hash:`

## Result Structure
| Field | Description |
|-------|-------------|
| `page.url` | Final URL after redirects |
| `page.domain` | Domain name |
| `page.ip` | Resolved IP |
| `page.country` | Server country |
| `page.status` | HTTP status code |
| `page.title` | Page title |
| `page.server` | Server header |
| `page.tlsIssuer` | TLS certificate issuer |
| `verdicts.overall.malicious` | Boolean malicious verdict |
| `verdicts.overall.score` | Risk score (0-100) |
| `lists.ips` | List of contacted IPs |
| `lists.certificates` | TLS certificates observed |
| `stats.resourceStats` | Resource type statistics |

## Screenshot
```
GET /screenshots/{uuid}.png
```

## DOM Snapshot
```
GET /dom/{uuid}/
```

## Rate Limits
- Free: 100 scans/day, 1000 searches/day
- Paid: Higher limits per plan

## references/standards.md

# Standards & References: Analyzing Malicious URLs with URLScan

## MITRE ATT&CK References
- **T1566.002**: Phishing: Spearphishing Link
- **T1204.001**: User Execution: Malicious Link
- **T1608.005**: Stage Capabilities: Link Target
- **T1071.001**: Application Layer Protocol: Web Protocols
- **T1102**: Web Service (for C2 via web)

## URLScan.io API Reference
| Endpoint | Method | Description |
|---|---|---|
| `/api/v1/scan/` | POST | Submit URL for scanning |
| `/api/v1/result/{uuid}/` | GET | Get scan results |
| `/api/v1/search/?q=` | GET | Search scan database |
| `/api/v1/result/{uuid}/screenshot/` | GET | Get page screenshot |
| `/api/v1/result/{uuid}/dom/` | GET | Get rendered DOM |

### Search Query Syntax
- `domain:example.com` - Search by domain
- `ip:1.2.3.4` - Search by IP
- `server:nginx` - Search by web server
- `filename:login.php` - Search by filename
- `hash:abc123` - Search by resource hash
- `page.domain:example.com AND date:>now-7d` - Combined queries

## Industry Standards
- **NIST SP 800-83**: Guide to Malware Incident Prevention and Handling
- **NIST SP 800-86**: Guide to Integrating Forensic Techniques into Incident Response
- **RFC 3986**: Uniform Resource Identifier (URI) syntax

## URL Classification Indicators
| Indicator | Risk Level | Description |
|---|---|---|
| Domain age < 7 days | Critical | Very recently registered |
| Domain age < 30 days | High | Recently registered |
| Free TLS cert (Let's Encrypt) with brand impersonation | High | Common phishing pattern |
| URL shortener | Medium | Obfuscates destination |
| Credential input form on non-brand domain | Critical | Credential harvesting |
| JavaScript obfuscation | High | Evasion technique |
| Multiple redirects | Medium | Chain obfuscation |
| Data URI scheme | High | Inline content, hard to trace |

## references/workflows.md

# Workflows: Analyzing Malicious URLs with URLScan

## Workflow 1: URL Triage Pipeline

```
Suspicious URL received (from user report / email gateway / SIEM)
  |
  v
[Step 1: Defang and document URL]
  +-- Replace http with hxxp, . with [.]
  +-- Record original context (email subject, sender, timestamp)
  |
  v
[Step 2: Submit to URLScan (private visibility)]
  +-- POST to /api/v1/scan/
  +-- Wait for scan completion (poll /api/v1/result/{uuid}/)
  |
  v
[Step 3: Analyze results]
  +-- Review screenshot for brand impersonation
  +-- Check redirect chain (original URL vs final URL)
  +-- Examine DOM for login forms / credential inputs
  +-- Review network requests for suspicious endpoints
  +-- Check SSL certificate details
  |
  v
[Step 4: Classify]
  +-- Phishing (credential harvesting)
  +-- Malware delivery
  +-- Scam / fraud
  +-- Benign (false positive)
  |
  v
[Step 5: Action]
  +-- If malicious: Extract IOCs, block domain/IP, update filters
  +-- If benign: Document and close
  +-- If uncertain: Escalate for deeper analysis
```

## Workflow 2: Bulk URL Analysis

```
URL list from email gateway / threat feed
  |
  v
[Batch submit to URLScan API]
  +-- Rate limit: 2 submissions/second (free tier)
  +-- Use private visibility for sensitive URLs
  |
  v
[Collect all results]
  +-- Poll each scan UUID for completion
  +-- Download screenshots and DOM content
  |
  v
[Automated triage]
  +-- Flag: credential input forms detected
  +-- Flag: brand impersonation in screenshot
  +-- Flag: known phishing infrastructure (IP/ASN)
  +-- Flag: newly registered domains
  |
  v
[Generate report]
  +-- Categorized URL list (malicious / suspicious / clean)
  +-- IOC extract for blocking
  +-- Statistics summary
```

## Workflow 3: IOC Extraction and Enrichment

```
URLScan result available
  |
  v
[Extract from scan]
  +-- All domains contacted
  +-- All IPs contacted
  +-- SSL certificate fingerprints
  +-- JavaScript file hashes
  +-- Page resource hashes
  +-- Final redirect URL
  |
  v
[Cross-reference]
  +-- VirusTotal: domain/IP/hash reputation
  +-- PhishTank: known phishing URL database
  +-- WHOIS: domain registration details
  +-- AbuseIPDB: IP abuse reports
  +-- Google Safe Browsing: malware/phishing flags
  |
  v
[Compile IOC package]
  +-- STIX/TAXII format for TIP
  +-- CSV for firewall/proxy rules
  +-- JSON for SIEM enrichment
```

## scripts

```

```

## scripts/agent.py

```python
#!/usr/bin/env python3
"""URLScan.io Malicious URL Analysis Agent - Submits and analyzes URLs via the urlscan.io API."""

import json
import time
import logging
import argparse
from datetime import datetime

import requests

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

URLSCAN_API = "https://urlscan.io/api/v1"


def submit_url(url, api_key, visibility="private"):
    """Submit a URL to urlscan.io for scanning."""
    headers = {"API-Key": api_key, "Content-Type": "application/json"}
    payload = {"url": url, "visibility": visibility}
    resp = requests.post(f"{URLSCAN_API}/scan/", headers=headers, json=payload, timeout=30)
    resp.raise_for_status()
    data = resp.json()
    logger.info("Submitted URL: %s -> scan UUID: %s", url, data.get("uuid"))
    return data


def get_scan_result(uuid, api_key, max_wait=120):
    """Poll for scan results until complete."""
    headers = {"API-Key": api_key}
    for _ in range(max_wait // 5):
        try:
            resp = requests.get(f"{URLSCAN_API}/result/{uuid}/", headers=headers, timeout=30)
            if resp.status_code == 200:
                return resp.json()
        except requests.RequestException:
            pass
        time.sleep(5)
    return None


def search_urlscan(query, api_key, size=100):
    """Search urlscan.io for existing scans."""
    headers = {"API-Key": api_key}
    params = {"q": query, "size": size}
    resp = requests.get(f"{URLSCAN_API}/search/", headers=headers, params=params, timeout=30)
    resp.raise_for_status()
    return resp.json().get("results", [])


def analyze_result(result):
    """Analyze urlscan.io scan result for malicious indicators."""
    findings = []
    verdicts = result.get("verdicts", {})
    overall = verdicts.get("overall", {})
    urlscan_verdict = verdicts.get("urlscan", {})
    community = verdicts.get("community", {})

    if overall.get("malicious"):
        findings.append({"type": "Malicious verdict", "severity": "critical", "source": "overall", "score": overall.get("score", 0)})
    if urlscan_verdict.get("malicious"):
        findings.append({"type": "URLScan malicious", "severity": "critical", "score": urlscan_verdict.get("score", 0)})
    if community.get("score", 0) < 0:
        findings.append({"type": "Negative community score", "severity": "high", "score": community.get("score")})

    page = result.get("page", {})
    lists = result.get("lists", {})
    stats = result.get("stats", {})

    if lists.get("ips", []):
        for ip in lists["ips"]:
            if ip.get("malicious"):
                findings.append({"type": "Malicious IP contacted", "severity": "high", "ip": ip.get("ip"), "asn": ip.get("asn")})

    for cert in lists.get("certificates", []):
        if cert.get("validTo"):
            try:
                exp = datetime.fromisoformat(cert["validTo"].replace("Z", "+00:00"))
                if exp < datetime.now(exp.tzinfo):
                    findings.append({"type": "Expired TLS certificate", "severity": "medium", "subject": cert.get("subjectName")})
            except (ValueError, TypeError):
                pass

    js_count = len([r for r in stats.get("resourceStats", []) if "javascript" in r.get("type", "").lower()])
    if js_count > 20:
        findings.append({"type": "High JavaScript resource count", "severity": "medium", "count": js_count})

    redirects = stats.get("uniqCountries", 0)
    if result.get("data", {}).get("requests"):
        redirect_chain = [r.get("request", {}).get("redirectHasExtraInfo") for r in result["data"]["requests"][:5]]

    return {
        "url": page.get("url", ""),
        "domain": page.get("domain", ""),
        "ip": page.get("ip", ""),
        "country": page.get("country", ""),
        "server": page.get("server", ""),
        "status_code": page.get("status", 0),
        "title": page.get("title", ""),
        "mime_type": page.get("mimeType", ""),
        "tls_issuer": page.get("tlsIssuer", ""),
        "overall_malicious": overall.get("malicious", False),
        "overall_score": overall.get("score", 0),
        "findings": findings,
    }


def bulk_analyze(urls, api_key):
    """Submit and analyze multiple URLs."""
    results = []
    for url in urls:
        try:
            submission = submit_url(url, api_key)
            uuid = submission.get("uuid")
            if uuid:
                result = get_scan_result(uuid, api_key)
                if result:
                    analysis = analyze_result(result)
                    results.append(analysis)
                else:
                    results.append({"url": url, "error": "Scan timeout"})
        except requests.RequestException as e:
            results.append({"url": url, "error": str(e)})
    return results


def generate_report(analyses):
    """Generate URL analysis report."""
    malicious = [a for a in analyses if a.get("overall_malicious")]
    report = {
        "timestamp": datetime.utcnow().isoformat(),
        "urls_analyzed": len(analyses),
        "malicious_count": len(malicious),
        "results": analyses,
    }
    print(f"URLSCAN REPORT: {len(analyses)} URLs analyzed, {len(malicious)} malicious")
    return report


def main():
    parser = argparse.ArgumentParser(description="URLScan.io Malicious URL Analysis Agent")
    parser.add_argument("--api-key", required=True, help="urlscan.io API key")
    parser.add_argument("--url", help="Single URL to scan")
    parser.add_argument("--url-file", help="File with URLs (one per line)")
    parser.add_argument("--search", help="Search query for existing scans")
    parser.add_argument("--output", default="urlscan_report.json")
    args = parser.parse_args()

    urls = []
    if args.url:
        urls.append(args.url)
    if args.url_file:
        with open(args.url_file) as f:
            urls.extend(line.strip() for line in f if line.strip())

    if args.search:
        results = search_urlscan(args.search, args.api_key)
        analyses = [analyze_result(r) for r in results if "page" in r]
    else:
        analyses = bulk_analyze(urls, args.api_key)

    report = generate_report(analyses)
    with open(args.output, "w") as f:
        json.dump(report, f, indent=2)
    logger.info("Report saved to %s", args.output)


if __name__ == "__main__":
    main()
```

## scripts/process.py

```python
#!/usr/bin/env python3
"""
URLScan.io URL Analysis Automation

Submits suspicious URLs to URLScan.io for analysis, retrieves results,
extracts IOCs, and cross-references with threat intelligence sources.

Usage:
    python process.py scan --url "https://suspicious-site.com"
    python process.py scan --url-file urls.txt
    python process.py result --uuid <scan-uuid>
    python process.py search --query "domain:evil.com"
    python process.py ioc --uuid <scan-uuid>
"""

import argparse
import json
import sys
import time
import os
import hashlib
from datetime import datetime, timezone
from pathlib import Path
from dataclasses import dataclass, field, asdict

try:
    import requests
    HAS_REQUESTS = True
except ImportError:
    HAS_REQUESTS = False

URLSCAN_API_KEY = os.environ.get("URLSCAN_API_KEY", "")
URLSCAN_BASE = "https://urlscan.io/api/v1"
VT_API_KEY = os.environ.get("VT_API_KEY", "")


@dataclass
class URLScanResult:
    """Parsed URLScan result."""
    uuid: str = ""
    url: str = ""
    effective_url: str = ""
    status_code: int = 0
    domain: str = ""
    ip: str = ""
    asn: str = ""
    asn_name: str = ""
    country: str = ""
    server: str = ""
    title: str = ""
    tls_issuer: str = ""
    tls_subject: str = ""
    tls_valid_from: str = ""
    tls_valid_to: str = ""
    screenshot_url: str = ""
    dom_url: str = ""
    technologies: list = field(default_factory=list)
    redirects: list = field(default_factory=list)
    domains_contacted: list = field(default_factory=list)
    ips_contacted: list = field(default_factory=list)
    urls_contacted: list = field(default_factory=list)
    has_login_form: bool = False
    resource_hashes: list = field(default_factory=list)
    verdicts: dict = field(default_factory=dict)
    is_malicious: bool = False
    risk_indicators: list = field(default_factory=list)


def submit_scan(url: str, visibility: str = "private",
                api_key: str = "") -> dict:
    """Submit a URL to URLScan for scanning."""
    if not api_key:
        api_key = URLSCAN_API_KEY
    if not api_key:
        print("Warning: No URLScan API key provided. Using public submission.", file=sys.stderr)

    headers = {"Content-Type": "application/json"}
    if api_key:
        headers["API-Key"] = api_key

    data = {"url": url, "visibility": visibility}

    try:
        resp = requests.post(f"{URLSCAN_BASE}/scan/", headers=headers,
                             json=data, timeout=30)
        if resp.status_code == 200:
            return resp.json()
        elif resp.status_code == 429:
            print("Rate limited. Waiting 10 seconds...", file=sys.stderr)
            time.sleep(10)
            resp = requests.post(f"{URLSCAN_BASE}/scan/", headers=headers,
                                 json=data, timeout=30)
            return resp.json() if resp.status_code == 200 else {"error": resp.text}
        else:
            return {"error": f"HTTP {resp.status_code}: {resp.text}"}
    except Exception as e:
        return {"error": str(e)}


def get_result(uuid: str, api_key: str = "", max_wait: int = 60) -> dict:
    """Get scan results, polling until ready."""
    if not api_key:
        api_key = URLSCAN_API_KEY

    headers = {}
    if api_key:
        headers["API-Key"] = api_key

    for attempt in range(max_wait // 5):
        try:
            resp = requests.get(f"{URLSCAN_BASE}/result/{uuid}/",
                                headers=headers, timeout=30)
            if resp.status_code == 200:
                return resp.json()
            elif resp.status_code == 404:
                time.sleep(5)
                continue
            else:
                return {"error": f"HTTP {resp.status_code}: {resp.text}"}
        except Exception as e:
            return {"error": str(e)}

    return {"error": "Timeout waiting for scan results"}


def search_scans(query: str, api_key: str = "", size: int = 10) -> list:
    """Search URLScan database."""
    if not api_key:
        api_key = URLSCAN_API_KEY

    headers = {}
    if api_key:
        headers["API-Key"] = api_key

    try:
        resp = requests.get(f"{URLSCAN_BASE}/search/?q={query}&size={size}",
                            headers=headers, timeout=30)
        if resp.status_code == 200:
            return resp.json().get("results", [])
    except Exception:
        pass
    return []


def parse_result(raw_result: dict) -> URLScanResult:
    """Parse raw URLScan API result into structured data."""
    result = URLScanResult()

    task = raw_result.get("task", {})
    result.uuid = task.get("uuid", "")
    result.url = task.get("url", "")

    page = raw_result.get("page", {})
    result.effective_url = page.get("url", "")
    result.status_code = page.get("status", 0)
    result.domain = page.get("domain", "")
    result.ip = page.get("ip", "")
    result.asn = page.get("asn", "")
    result.asn_name = page.get("asnname", "")
    result.country = page.get("country", "")
    result.server = page.get("server", "")
    result.title = page.get("title", "")

    # TLS info
    tls_list = raw_result.get("lists", {}).get("certificates", [])
    if tls_list:
        cert = tls_list[0]
        result.tls_issuer = cert.get("issuer", "")
        result.tls_subject = cert.get("subjectName", "")
        result.tls_valid_from = cert.get("validFrom", "")
        result.tls_valid_to = cert.get("validTo", "")

    # Screenshot and DOM URLs
    result.screenshot_url = f"https://urlscan.io/screenshots/{result.uuid}.png"
    result.dom_url = f"https://urlscan.io/dom/{result.uuid}/"

    # Technologies
    meta = raw_result.get("meta", {})
    for processor in meta.get("processors", {}).values():
        if isinstance(processor, dict) and "data" in processor:
            techs = processor["data"]
            if isinstance(techs, list):
                for tech in techs:
                    if isinstance(tech, dict) and "app" in tech:
                        result.technologies.append(tech["app"])

    # Redirects
    data = raw_result.get("data", {})
    for request in data.get("requests", [])[:5]:
        req_url = request.get("request", {}).get("request", {}).get("url", "")
        resp_url = request.get("response", {}).get("response", {}).get("url", "")
        if req_url != result.url:
            result.redirects.append(req_url)

    # Domains and IPs contacted
    lists = raw_result.get("lists", {})
    result.domains_contacted = lists.get("domains", [])
    result.ips_contacted = lists.get("ips", [])
    result.urls_contacted = lists.get("urls", [])[:50]

    # Resource hashes
    for request in data.get("requests", []):
        resp_data = request.get("response", {}).get("response", {})
        resp_hash = resp_data.get("hash", "")
        if resp_hash:
            result.resource_hashes.append({
                "url": resp_data.get("url", ""),
                "hash": resp_hash,
                "size": resp_data.get("size", 0),
                "mimeType": resp_data.get("mimeType", "")
            })

    # Check for login forms in DOM
    dom_content = raw_result.get("data", {}).get("dom", "")
    if isinstance(dom_content, str):
        if ('type="password"' in dom_content.lower() or
                'input type=password' in dom_content.lower() or
                '<form' in dom_content.lower()):
            result.has_login_form = True

    # Verdicts
    verdicts = raw_result.get("verdicts", {})
    result.verdicts = {
        "overall_score": verdicts.get("overall", {}).get("score", 0),
        "overall_malicious": verdicts.get("overall", {}).get("malicious", False),
        "urlscan_score": verdicts.get("urlscan", {}).get("score", 0),
        "engines": verdicts.get("engines", {}).get("malicious", []),
        "community_score": verdicts.get("community", {}).get("score", 0),
    }
    result.is_malicious = verdicts.get("overall", {}).get("malicious", False)

    # Risk indicators
    if result.has_login_form and result.domain != result.url.split("/")[2]:
        result.risk_indicators.append("Credential harvesting form on non-origin domain")
    if result.url != result.effective_url:
        result.risk_indicators.append(f"URL redirected: {result.url} -> {result.effective_url}")
    if result.is_malicious:
        result.risk_indicators.append("Flagged as malicious by URLScan verdicts")
    if len(result.redirects) > 3:
        result.risk_indicators.append(f"Excessive redirects ({len(result.redirects)})")

    return result


def extract_iocs(result: URLScanResult) -> dict:
    """Extract IOCs from scan result."""
    iocs = {
        "domains": list(set(result.domains_contacted)),
        "ips": list(set(result.ips_contacted)),
        "urls": [result.url, result.effective_url] + result.redirects,
        "hashes": [h["hash"] for h in result.resource_hashes if h.get("hash")],
        "tls_fingerprint": result.tls_subject,
        "scan_uuid": result.uuid,
        "scan_date": datetime.now(timezone.utc).isoformat(),
    }
    # Deduplicate URLs
    iocs["urls"] = list(set(u for u in iocs["urls"] if u))
    return iocs


def check_virustotal(url: str, api_key: str = "") -> dict:
    """Check URL against VirusTotal (requires API key)."""
    if not api_key:
        api_key = VT_API_KEY
    if not api_key:
        return {}

    url_id = hashlib.sha256(url.encode()).hexdigest()
    headers = {"x-apikey": api_key}

    try:
        resp = requests.get(f"https://www.virustotal.com/api/v3/urls/{url_id}",
                            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),
            }
    except Exception:
        pass
    return {}


def format_report(result: URLScanResult) -> str:
    """Format scan result as text report."""
    lines = []
    lines.append("=" * 60)
    lines.append("  URL ANALYSIS REPORT (URLScan.io)")
    lines.append("=" * 60)
    lines.append(f"  Scan UUID: {result.uuid}")
    lines.append(f"  Submitted URL: {result.url}")
    lines.append(f"  Effective URL: {result.effective_url}")
    lines.append(f"  Status Code: {result.status_code}")
    lines.append(f"  Malicious: {'YES' if result.is_malicious else 'NO'}")
    lines.append("")

    lines.append("[PAGE INFO]")
    lines.append(f"  Title: {result.title}")
    lines.append(f"  Domain: {result.domain}")
    lines.append(f"  IP: {result.ip}")
    lines.append(f"  ASN: {result.asn} ({result.asn_name})")
    lines.append(f"  Country: {result.country}")
    lines.append(f"  Server: {result.server}")
    lines.append(f"  Login Form: {'DETECTED' if result.has_login_form else 'Not found'}")
    lines.append(f"  Screenshot: {result.screenshot_url}")
    lines.append("")

    if result.tls_issuer:
        lines.append("[TLS CERTIFICATE]")
        lines.append(f"  Issuer: {result.tls_issuer}")
        lines.append(f"  Subject: {result.tls_subject}")
        lines.append("")

    if result.redirects:
        lines.append(f"[REDIRECTS] ({len(result.redirects)} found)")
        for r in result.redirects[:10]:
            lines.append(f"  -> {r}")
        lines.append("")

    if result.risk_indicators:
        lines.append(f"[RISK INDICATORS] ({len(result.risk_indicators)})")
        for ind in result.risk_indicators:
            lines.append(f"  - {ind}")
        lines.append("")

    lines.append(f"[INFRASTRUCTURE]")
    lines.append(f"  Domains contacted: {len(result.domains_contacted)}")
    lines.append(f"  IPs contacted: {len(result.ips_contacted)}")
    lines.append(f"  Resource hashes: {len(result.resource_hashes)}")

    lines.append("=" * 60)
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(description="URLScan.io URL Analysis Tool")
    subparsers = parser.add_subparsers(dest="command")

    scan_parser = subparsers.add_parser("scan", help="Scan a URL")
    scan_parser.add_argument("--url", help="Single URL to scan")
    scan_parser.add_argument("--url-file", help="File with URLs (one per line)")
    scan_parser.add_argument("--visibility", default="private",
                             choices=["public", "unlisted", "private"])
    scan_parser.add_argument("--wait", action="store_true", help="Wait for results")

    result_parser = subparsers.add_parser("result", help="Get scan result")
    result_parser.add_argument("--uuid", required=True)

    search_parser = subparsers.add_parser("search", help="Search URLScan database")
    search_parser.add_argument("--query", "-q", required=True)
    search_parser.add_argument("--size", type=int, default=10)

    ioc_parser = subparsers.add_parser("ioc", help="Extract IOCs from scan")
    ioc_parser.add_argument("--uuid", required=True)

    parser.add_argument("--api-key", default=URLSCAN_API_KEY)
    parser.add_argument("--json", action="store_true")
    parser.add_argument("--output", "-o")

    args = parser.parse_args()

    if not HAS_REQUESTS:
        print("Error: 'requests' library required", file=sys.stderr)
        sys.exit(1)

    api_key = args.api_key

    if args.command == "scan":
        urls = []
        if args.url:
            urls.append(args.url)
        elif args.url_file:
            with open(args.url_file) as f:
                urls = [line.strip() for line in f if line.strip()]

        for url in urls:
            print(f"Scanning: {url}")
            scan_result = submit_scan(url, args.visibility, api_key)

            if "error" in scan_result:
                print(f"  Error: {scan_result['error']}", file=sys.stderr)
                continue

            uuid = scan_result.get("uuid", "")
            print(f"  UUID: {uuid}")
            print(f"  Result URL: https://urlscan.io/result/{uuid}/")

            if args.wait and uuid:
                print("  Waiting for results...")
                time.sleep(10)
                raw = get_result(uuid, api_key)
                if "error" not in raw:
                    result = parse_result(raw)
                    if args.json:
                        print(json.dumps(asdict(result), indent=2, default=str))
                    else:
                        print(format_report(result))

            if len(urls) > 1:
                time.sleep(2)  # Rate limiting

    elif args.command == "result":
        raw = get_result(args.uuid, api_key)
        if "error" in raw:
            print(f"Error: {raw['error']}", file=sys.stderr)
            sys.exit(1)
        result = parse_result(raw)
        if args.json:
            print(json.dumps(asdict(result), indent=2, default=str))
        else:
            print(format_report(result))

    elif args.command == "search":
        results = search_scans(args.query, api_key, args.size)
        for r in results:
            task = r.get("task", {})
            page = r.get("page", {})
            print(f"  {task.get('time', '')} | {task.get('url', '')} | "
                  f"{page.get('domain', '')} | {page.get('ip', '')}")

    elif args.command == "ioc":
        raw = get_result(args.uuid, api_key)
        if "error" in raw:
            print(f"Error: {raw['error']}", file=sys.stderr)
            sys.exit(1)
        result = parse_result(raw)
        iocs = extract_iocs(result)
        print(json.dumps(iocs, indent=2))

    else:
        parser.print_help()


if __name__ == "__main__":
    main()
```

