Initial release: ghost_protocol privacy toolkit

This commit is contained in:
ghost
2026-03-04 09:13:16 -05:00
commit 973cede31f
99 changed files with 12158 additions and 0 deletions
+97
View File
@@ -0,0 +1,97 @@
# phantom — Privacy Server Deployer
Deploy self-hosted privacy infrastructure with a single command. Supports cloud providers, existing servers, and local deployment.
## Server Types
| Service | Status | Description |
|---|---|---|
| Matrix + Element | Ready | Encrypted messaging homeserver with web client |
| WireGuard VPN | Ready | Private VPN server with client config generation |
| Pi-hole DNS | Ready | Ad-blocking DNS server (Docker-based) |
| All-in-One | Ready | Multiple services on one server with nginx reverse proxy |
| Nextcloud | Stub | Self-hosted file sync and collaboration |
| Vaultwarden | Stub | Self-hosted Bitwarden password manager |
| Jellyfin | Stub | Self-hosted media server |
| Mail-in-a-Box | Stub | Self-hosted email |
## Deployment Targets
- **Linode** — Automated provisioning via API
- **AWS EC2** — Automated provisioning via API
- **FlokiNET** — Register pre-provisioned server
- **Existing server** — Any server with SSH access
- **Local** — Deploy directly on the current machine
## Quick Start
```bash
# Requirements
pip install ansible pyyaml # or: apt install ansible python3-yaml
# For AWS deployments:
pip install boto3
ansible-galaxy collection install amazon.aws
# Launch
python3 phantom.py
```
Select a service, choose a deployment target, provide configuration, and phantom handles the rest:
1. Provisions infrastructure (if cloud)
2. Applies base hardening (UFW, fail2ban, SSH lockdown, kernel hardening)
3. Deploys the selected service
4. Saves deployment info to `logs/`
## All-in-One Deployment
The all-in-one option deploys multiple services on a single server with:
- Nginx reverse proxy with TLS termination
- Let's Encrypt certificates via Certbot
- Per-service vhost routing
**Warning**: Running multiple services on one server means a compromise of one service risks all services. Use for lab/testing or personal use where convenience outweighs isolation. For production, deploy one service per server.
## Local Deployment
Select "Local (this machine)" as the deployment target to install services directly on your current system. This is useful for:
- Home lab servers
- Raspberry Pi deployments
- LAN-only services
- Testing before cloud deployment
No SSH key generation or remote provisioning is needed for local deployments.
## Provider Setup
### Linode
1. Create an API token at https://cloud.linode.com/profile/tokens
2. Select "Linode" when prompted and paste your token
### AWS
1. Create an IAM user with EC2 permissions
2. Generate access keys
3. Select "AWS" when prompted and provide credentials
### FlokiNET
1. Provision a server through FlokiNET's control panel
2. Select "FlokiNET" and provide the server IP
## Project Structure
```
phantom/
├── phantom.py # Main CLI
├── modules/ # Per-service configuration
├── playbooks/ # Ansible playbooks
│ ├── common/ # Shared hardening
│ ├── matrix/ # Synapse + Element
│ ├── vpn/ # WireGuard
│ ├── dns/ # Pi-hole
│ └── all_in_one/ # Multi-service composer
├── providers/ # Cloud provisioning
└── logs/ # Deployment artifacts
```
## License
MIT
+8
View File
@@ -0,0 +1,8 @@
[defaults]
host_key_checking = False
retry_files_enabled = False
stdout_callback = yaml
timeout = 30
[ssh_connection]
pipelining = True
+1
View File
@@ -0,0 +1 @@
# phantom modules
+126
View File
@@ -0,0 +1,126 @@
"""All-in-one single-server deployment module.
Composes multiple services onto a single server with nginx reverse proxy
and TLS via Certbot. Includes clear warnings about single-server risks.
"""
CYAN = "\033[38;5;51m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
YELLOW = "\033[38;5;214m"
RED = "\033[38;5;196m"
RESET = "\033[0m"
SERVICES = [
("matrix", "Matrix + Element", "Encrypted messaging"),
("vpn", "WireGuard VPN", "Private VPN server"),
("dns", "Pi-hole DNS", "Ad-blocking DNS"),
("cloud", "Nextcloud", "File sync (stub)"),
("vault", "Vaultwarden", "Password manager (stub)"),
("media", "Jellyfin", "Media server (stub)"),
]
def gather_config(config):
"""Gather all-in-one deployment configuration."""
# Risk warning
print(f"\n{RED} ╔═══════════════════════════════════════════════════════╗{RESET}")
print(f" {RED}{RESET} {YELLOW}WARNING: Single-Server Deployment{RESET} {RED}{RESET}")
print(f" {RED}{RESET} {RED}{RESET}")
print(f" {RED}{RESET} Running multiple services on one server means: {RED}{RESET}")
print(f" {RED}{RESET} - A compromise of one service risks ALL services {RED}{RESET}")
print(f" {RED}{RESET} - Resource contention between services {RED}{RESET}")
print(f" {RED}{RESET} - Single point of failure for all infrastructure {RED}{RESET}")
print(f" {RED}{RESET} - More complex backup and recovery {RED}{RESET}")
print(f" {RED}{RESET} {RED}{RESET}")
print(f" {RED}{RESET} For production use, prefer one service per server. {RED}{RESET}")
print(f" {RED}{RESET} This mode is intended for lab/testing or personal {RED}{RESET}")
print(f" {RED}{RESET} use where convenience outweighs isolation. {RED}{RESET}")
print(f" {RED}╚═══════════════════════════════════════════════════════╝{RESET}")
confirm = input(f"\n {YELLOW}Acknowledge risks and continue? [y/N]:{RESET} ").strip().lower()
if confirm != "y":
return None
# Service selection
print(f"\n{CYAN} ┌─ Select Services ────────────────────────────────────┐{RESET}")
for i, (svc_id, label, desc) in enumerate(SERVICES, 1):
print(f" {CYAN}{RESET} {WHITE}{i}{RESET}) {label:<20} {GREY}{desc}{RESET}")
print(f" {CYAN}└────────────────────────────────────────────────────────┘{RESET}")
selections = input(
f"\n {CYAN}Services to deploy (comma-separated, e.g. 1,2,3):{RESET} "
).strip()
selected_services = []
for s in selections.split(","):
s = s.strip()
try:
idx = int(s) - 1
if 0 <= idx < len(SERVICES):
selected_services.append(SERVICES[idx][0])
except ValueError:
pass
if not selected_services:
print(f" {RED}No services selected.{RESET}")
return None
# Warn about stub services
STUB_SERVICES = {"cloud", "vault", "media", "email"}
stubs_selected = [s for s in selected_services if s in STUB_SERVICES]
if stubs_selected:
stub_labels = {s[0]: s[1] for s in SERVICES}
print(f"\n {YELLOW}Warning: The following services are stubs (playbook not yet implemented):{RESET}")
for s in stubs_selected:
print(f" {YELLOW}- {stub_labels.get(s, s)}{RESET}")
proceed = input(f" {YELLOW}Continue anyway? [y/N]:{RESET} ").strip().lower()
if proceed != "y":
return None
config["services"] = selected_services
config["all_in_one"] = True
# Base domain for nginx vhosts
config["domain"] = input(
f"\n {CYAN}Base domain (e.g. example.com):{RESET} "
).strip()
if not config["domain"]:
print(f" {RED}Domain is required for reverse proxy.{RESET}")
return None
config["certbot_email"] = input(
f" {CYAN}Email for Let's Encrypt [{GREY}optional{RESET}]: "
).strip()
# Gather per-service configs
# Save base domain — each service stores config under its own prefixed keys
base_domain = config["domain"]
for svc in selected_services:
try:
mod = __import__(f"modules.{svc}", fromlist=[svc])
if hasattr(mod, "gather_config"):
# Set per-service subdomain default
svc_subdomains = {
"matrix": f"matrix.{base_domain}",
"cloud": f"cloud.{base_domain}",
"vault": f"vault.{base_domain}",
"media": f"media.{base_domain}",
"email": f"mail.{base_domain}",
"dns": f"dns.{base_domain}",
"vpn": base_domain,
}
if svc in svc_subdomains:
config["domain"] = svc_subdomains[svc]
config = mod.gather_config(config)
if config is None:
return None
except ImportError:
pass # Stub module, skip
# Restore base domain
config["domain"] = base_domain
config["nginx_reverse_proxy"] = True
config["certbot_enabled"] = bool(config.get("certbot_email"))
return config
+27
View File
@@ -0,0 +1,27 @@
"""Nextcloud deployment module (stub — playbook TODO)."""
CYAN = "\033[38;5;51m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
RESET = "\033[0m"
def gather_config(config):
"""Gather Nextcloud configuration."""
print(f"\n{CYAN} ┌─ Nextcloud Configuration ─────────────────────────┐{RESET}")
print(f" {CYAN}{RESET} {GREY}Note: Playbook coming soon{RESET}")
config["domain"] = config.get("domain") or input(
f" {CYAN}{RESET} Domain (e.g. cloud.example.com): "
).strip()
config["cloud_admin_user"] = input(
f" {CYAN}{RESET} Admin username [{WHITE}admin{RESET}]: "
).strip() or "admin"
config["cloud_storage_gb"] = input(
f" {CYAN}{RESET} Storage quota per user (GB) [{WHITE}10{RESET}]: "
).strip() or "10"
print(f" {CYAN}└─────────────────────────────────────────────────────┘{RESET}")
return config
+49
View File
@@ -0,0 +1,49 @@
"""Pi-hole / AdGuard DNS server deployment module."""
CYAN = "\033[38;5;51m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
YELLOW = "\033[38;5;214m"
RESET = "\033[0m"
def gather_config(config):
"""Gather DNS server configuration."""
print(f"\n{CYAN} ┌─ DNS Server Configuration ────────────────────────┐{RESET}")
print(f" {CYAN}{RESET} Upstream DNS provider:")
print(f" {CYAN}{RESET} {WHITE}1{RESET}) Quad9 (9.9.9.9) — security-focused")
print(f" {CYAN}{RESET} {WHITE}2{RESET}) Cloudflare (1.1.1.1) — privacy-focused")
print(f" {CYAN}{RESET} {WHITE}3{RESET}) Custom")
dns_choice = input(f" {CYAN}{RESET} Choice [{WHITE}1{RESET}]: ").strip() or "1"
if dns_choice == "1":
config["dns_upstream"] = "9.9.9.9;149.112.112.112"
config["dns_upstream_name"] = "Quad9"
elif dns_choice == "2":
config["dns_upstream"] = "1.1.1.1;1.0.0.1"
config["dns_upstream_name"] = "Cloudflare"
else:
config["dns_upstream"] = input(
f" {CYAN}{RESET} Custom DNS (semicolon-separated): "
).strip()
config["dns_upstream_name"] = "Custom"
config["dns_domain"] = input(
f" {CYAN}{RESET} Admin interface domain (optional): "
).strip()
print(f" {CYAN}{RESET}")
print(f" {CYAN}{RESET} Blocklist presets:")
print(f" {CYAN}{RESET} {WHITE}1{RESET}) Standard (ads + trackers)")
print(f" {CYAN}{RESET} {WHITE}2{RESET}) Aggressive (+ social media trackers)")
print(f" {CYAN}{RESET} {WHITE}3{RESET}) Minimal (ads only)")
bl_choice = input(f" {CYAN}{RESET} Choice [{WHITE}1{RESET}]: ").strip() or "1"
config["dns_blocklist"] = {"1": "standard", "2": "aggressive", "3": "minimal"}.get(
bl_choice, "standard"
)
print(f" {CYAN}└─────────────────────────────────────────────────────┘{RESET}")
return config
+23
View File
@@ -0,0 +1,23 @@
"""Mail-in-a-Box deployment module (stub — playbook TODO)."""
CYAN = "\033[38;5;51m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
RESET = "\033[0m"
def gather_config(config):
"""Gather Mail-in-a-Box configuration."""
print(f"\n{CYAN} ┌─ Mail-in-a-Box Configuration ─────────────────────┐{RESET}")
print(f" {CYAN}{RESET} {GREY}Note: Playbook coming soon{RESET}")
config["domain"] = config.get("domain") or input(
f" {CYAN}{RESET} Mail domain (e.g. mail.example.com): "
).strip()
config["email_first_user"] = input(
f" {CYAN}{RESET} First email user (e.g. admin@example.com): "
).strip()
print(f" {CYAN}└─────────────────────────────────────────────────────┘{RESET}")
return config
+47
View File
@@ -0,0 +1,47 @@
"""Matrix + Element homeserver deployment module."""
import getpass
import secrets
CYAN = "\033[38;5;51m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
RESET = "\033[0m"
def gather_config(config):
"""Gather Matrix/Synapse + Element configuration."""
print(f"\n{CYAN} ┌─ Matrix Homeserver Configuration ─────────────────┐{RESET}")
config["domain"] = config.get("domain") or input(
f" {CYAN}{RESET} Domain (e.g. matrix.example.com): "
).strip()
if not config["domain"]:
print(f" {CYAN}{RESET} Domain is required.")
return None
config["matrix_admin_user"] = input(
f" {CYAN}{RESET} Admin username [{WHITE}admin{RESET}]: "
).strip() or "admin"
config["matrix_admin_password"] = getpass.getpass(
f" {CYAN}{RESET} Admin password (blank=generate): "
) or secrets.token_urlsafe(20)
config["matrix_registration"] = input(
f" {CYAN}{RESET} Open registration? [{WHITE}no{RESET}]: "
).strip().lower()
config["matrix_registration"] = config["matrix_registration"] in ("yes", "y", "true")
config["matrix_element_web"] = input(
f" {CYAN}{RESET} Deploy Element Web? [{WHITE}yes{RESET}]: "
).strip().lower()
config["matrix_element_web"] = config["matrix_element_web"] not in ("no", "n", "false")
config["matrix_server_name"] = config["domain"].replace("matrix.", "", 1) \
if config["domain"].startswith("matrix.") else config["domain"]
config["matrix_signing_key"] = secrets.token_hex(32)
print(f" {CYAN}└─────────────────────────────────────────────────────┘{RESET}")
return config
+23
View File
@@ -0,0 +1,23 @@
"""Jellyfin media server deployment module (stub — playbook TODO)."""
CYAN = "\033[38;5;51m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
RESET = "\033[0m"
def gather_config(config):
"""Gather Jellyfin configuration."""
print(f"\n{CYAN} ┌─ Jellyfin Configuration ──────────────────────────┐{RESET}")
print(f" {CYAN}{RESET} {GREY}Note: Playbook coming soon{RESET}")
config["domain"] = config.get("domain") or input(
f" {CYAN}{RESET} Domain (e.g. media.example.com): "
).strip()
config["media_library_path"] = input(
f" {CYAN}{RESET} Media library path [{WHITE}/srv/media{RESET}]: "
).strip() or "/srv/media"
print(f" {CYAN}└─────────────────────────────────────────────────────┘{RESET}")
return config
+29
View File
@@ -0,0 +1,29 @@
"""Vaultwarden (Bitwarden) deployment module (stub — playbook TODO)."""
import secrets
CYAN = "\033[38;5;51m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
RESET = "\033[0m"
def gather_config(config):
"""Gather Vaultwarden configuration."""
print(f"\n{CYAN} ┌─ Vaultwarden Configuration ───────────────────────┐{RESET}")
print(f" {CYAN}{RESET} {GREY}Note: Playbook coming soon{RESET}")
config["domain"] = config.get("domain") or input(
f" {CYAN}{RESET} Domain (e.g. vault.example.com): "
).strip()
config["vault_admin_token"] = input(
f" {CYAN}{RESET} Admin token (blank=generate): "
).strip() or secrets.token_urlsafe(32)
config["vault_signups_allowed"] = input(
f" {CYAN}{RESET} Allow signups? [{WHITE}no{RESET}]: "
).strip().lower() in ("yes", "y", "true")
print(f" {CYAN}└─────────────────────────────────────────────────────┘{RESET}")
return config
+39
View File
@@ -0,0 +1,39 @@
"""WireGuard VPN server deployment module."""
CYAN = "\033[38;5;51m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
RESET = "\033[0m"
def gather_config(config):
"""Gather WireGuard VPN configuration."""
print(f"\n{CYAN} ┌─ WireGuard VPN Configuration ──────────────────────┐{RESET}")
config["vpn_port"] = input(
f" {CYAN}{RESET} Listen port [{WHITE}51820{RESET}]: "
).strip() or "51820"
config["vpn_client_count"] = input(
f" {CYAN}{RESET} Number of client configs [{WHITE}3{RESET}]: "
).strip() or "3"
try:
config["vpn_client_count"] = int(config["vpn_client_count"])
except ValueError:
config["vpn_client_count"] = 3
config["vpn_dns"] = input(
f" {CYAN}{RESET} Client DNS server [{WHITE}1.1.1.1{RESET}]: "
).strip() or "1.1.1.1"
config["vpn_allowed_ips"] = input(
f" {CYAN}{RESET} Allowed IPs [{WHITE}0.0.0.0/0, ::/0{RESET}]: "
).strip() or "0.0.0.0/0, ::/0"
config["vpn_subnet"] = input(
f" {CYAN}{RESET} VPN subnet [{WHITE}10.66.66.0/24{RESET}]: "
).strip() or "10.66.66.0/24"
print(f" {CYAN}└─────────────────────────────────────────────────────┘{RESET}")
return config
+463
View File
@@ -0,0 +1,463 @@
#!/usr/bin/env python3
"""phantom — Privacy Server Deployer
Deploy self-hosted privacy infrastructure with a single command.
Supports Matrix, WireGuard VPN, Pi-hole DNS, Nextcloud, and more.
Providers: Linode, AWS, FlokiNET, or local/existing server.
"""
import json
import os
import random
import subprocess
import sys
import time
from pathlib import Path
# Allow modules to import from phantom
sys.path.insert(0, os.path.dirname(__file__))
BASE_DIR = Path(__file__).resolve().parent
PLAYBOOKS_DIR = BASE_DIR / "playbooks"
PROVIDERS_DIR = BASE_DIR / "providers"
LOGS_DIR = BASE_DIR / "logs"
LOGS_DIR.mkdir(exist_ok=True)
# ─── Color Helpers ──────────────────────────────────────────────────────────
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
CYAN = "\033[38;5;51m"
GREEN = "\033[38;5;49m"
RED = "\033[38;5;196m"
YELLOW = "\033[38;5;214m"
MAGENTA = "\033[38;5;201m"
WHITE = "\033[38;5;255m"
GREY = "\033[38;5;244m"
def ok(msg):
print(f"{GREEN}[+]{RESET} {msg}")
def err(msg):
print(f"{RED}[-]{RESET} {msg}")
def warn(msg):
print(f"{YELLOW}[*]{RESET} {msg}")
def info(msg):
print(f"{CYAN}[~]{RESET} {msg}")
def dim(msg):
print(f"{GREY} {msg}{RESET}")
# ─── Banner ─────────────────────────────────────────────────────────────────
BANNER = f"""
{MAGENTA} ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗ ██████╗ ███╗ ███╗
██╔══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝██╔═══██╗████╗ ████║
██████╔╝███████║███████║██╔██╗ ██║ ██║ ██║ ██║██╔████╔██║
██╔═══╝ ██╔══██║██╔══██║██║╚██╗██║ ██║ ██║ ██║██║╚██╔╝██║
██║ ██║ ██║██║ ██║██║ ╚████║ ██║ ╚██████╔╝██║ ╚═╝ ██║
╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝{RESET}
{GREY} Privacy Server Deployer — Your infrastructure, your rules{RESET}
"""
def banner():
print(BANNER)
# ─── Deployment ID Generation ───────────────────────────────────────────────
ADJECTIVES = [
"silent", "hidden", "shadow", "quiet", "swift", "dark", "fading", "lost",
"frozen", "drifting", "hollow", "veiled", "pale", "deep", "still", "wild",
"broken", "burning", "crimson", "golden", "silver", "iron", "copper",
"cobalt", "jade", "amber", "arctic", "lunar", "solar", "astral", "coral",
"misty", "foggy", "dusty", "rusty", "mossy", "stormy", "cloudy", "windy",
"gentle", "fierce", "steady", "rapid", "lazy", "bold", "brave", "calm",
"clever", "cryptic", "cunning", "eager", "faint", "grave", "keen", "noble",
"prime", "rare", "stark", "terse", "vivid", "wary", "zealous", "agile",
"blunt", "coarse", "dense", "eerie", "fleet", "gaunt", "harsh", "lucid",
"muted", "numb", "opaque", "plain", "rigid", "sleek", "taut", "urban",
"vacant", "woven", "binary", "cipher", "delta", "echo", "foxtrot", "gamma",
"hex", "index", "kilo", "lambda", "micro", "nano", "omega", "proxy",
"quantum", "rogue", "sigma", "theta", "ultra", "vector", "xray", "zero",
]
NOUNS = [
"phantom", "spectre", "wraith", "shade", "ghost", "echo", "void", "rift",
"nexus", "pulse", "signal", "cipher", "prism", "beacon", "aegis", "bastion",
"citadel", "forge", "haven", "vault", "harbor", "summit", "ridge", "canyon",
"glacier", "tundra", "steppe", "mesa", "delta", "fjord", "grove", "marsh",
"oasis", "reef", "shoal", "brook", "creek", "falls", "rapids", "spring",
"falcon", "raven", "hawk", "condor", "osprey", "heron", "crane", "wren",
"finch", "swift", "sparrow", "robin", "wolf", "fox", "lynx", "panther",
"tiger", "cobra", "viper", "mantis", "hornet", "spider", "scorpion",
"anchor", "arrow", "blade", "bolt", "chain", "crown", "flint", "glyph",
"helm", "ingot", "jewel", "knot", "lance", "mast", "oar", "pike",
"quill", "rune", "shard", "thorn", "urn", "wand", "atlas", "core",
"dusk", "ember", "frost", "gale", "haze", "iris", "jade", "karma",
"lumen", "myth", "nova", "orbit", "pixel", "quest", "relay", "sage",
"trace", "unity", "vertex", "zenith",
]
def generate_id():
"""Generate a deployment ID with 10k+ unique combinations."""
adj = random.choice(ADJECTIVES)
noun = random.choice(NOUNS)
num = random.randint(10, 99)
return f"{adj}-{noun}-{num}"
# ─── SSH Key Generation ─────────────────────────────────────────────────────
def generate_ssh_key(deploy_id):
"""Generate an RSA 4096 SSH keypair for deployment."""
key_dir = LOGS_DIR / deploy_id
key_dir.mkdir(parents=True, exist_ok=True)
key_path = key_dir / f"deploy_{deploy_id}"
if key_path.exists():
info(f"SSH key already exists: {key_path}")
return str(key_path)
info(f"Generating SSH key: {key_path}")
subprocess.run(
["ssh-keygen", "-t", "rsa", "-b", "4096", "-f", str(key_path),
"-N", "", "-C", f"deploy-{deploy_id}"],
check=True, capture_output=True,
)
os.chmod(key_path, 0o600)
ok(f"SSH key generated: {key_path}")
return str(key_path)
# ─── Ansible Playbook Execution ─────────────────────────────────────────────
def run_playbook(playbook_path, config, extra_vars=None):
"""Execute an Ansible playbook with the given config.
Args:
playbook_path: Path object or string to the playbook file.
config: Deployment config dict.
extra_vars: Optional dict of extra Ansible variables.
Returns:
True if playbook succeeded, False otherwise.
"""
playbook_path = Path(playbook_path)
if not playbook_path.exists():
err(f"Playbook not found: {playbook_path}")
return False
cmd = ["ansible-playbook", str(playbook_path)]
# Build vars file
vars_file = LOGS_DIR / config["deploy_id"] / "vars.yaml"
vars_file.parent.mkdir(parents=True, exist_ok=True)
try:
import yaml # noqa: optional dependency
with open(vars_file, "w") as f:
yaml.dump(config, f, default_flow_style=False)
except ImportError:
with open(vars_file, "w") as f:
for k, v in config.items():
f.write(f"{k}: {json.dumps(v)}\n")
cmd.extend(["-e", f"@{vars_file}"])
if extra_vars:
for k, v in extra_vars.items():
cmd.extend(["-e", f"{k}={v}"])
# Set inventory
target = config.get("target_host", "localhost")
if target == "localhost":
cmd.extend(["-i", "localhost,", "--connection", "local"])
else:
inv_file = LOGS_DIR / config["deploy_id"] / "inventory"
with open(inv_file, "w") as f:
ssh_key = config.get("ssh_key", "")
ssh_user = config.get("ssh_user", "root")
line = f"{target} ansible_user={ssh_user}"
if ssh_key:
line += f" ansible_ssh_private_key_file={ssh_key}"
f.write(f"[servers]\n{line}\n")
cmd.extend(["-i", str(inv_file)])
# Elevate privileges for non-root users
if ssh_user != "root":
cmd.append("--become")
info(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd)
return result.returncode == 0
# ─── Deployment Info Logging ────────────────────────────────────────────────
def save_deploy_info(config):
"""Save deployment metadata to logs."""
deploy_dir = LOGS_DIR / config["deploy_id"]
deploy_dir.mkdir(parents=True, exist_ok=True)
info_file = deploy_dir / "deploy_info.json"
config["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
with open(info_file, "w") as f:
json.dump(config, f, indent=2, default=str)
ok(f"Deployment info saved: {info_file}")
# ─── SSH Connect ────────────────────────────────────────────────────────────
def ssh_connect(config):
"""Offer to SSH into the deployed server."""
target = config.get("target_host", "")
if not target or target == "localhost":
return
ssh_key = config.get("ssh_key", "")
ssh_user = config.get("ssh_user", "root")
cmd = ["ssh"]
if ssh_key:
cmd.extend(["-i", ssh_key])
cmd.append(f"{ssh_user}@{target}")
print()
resp = input(f"{CYAN}[?]{RESET} SSH into {target}? [y/N] ").strip().lower()
if resp == "y":
os.execvp("ssh", cmd)
# ─── Provider Selection ─────────────────────────────────────────────────────
def select_provider():
"""Select deployment target: cloud provider or local/existing server."""
print(f"\n{CYAN} Select deployment target:{RESET}")
print(f" {WHITE}1{RESET}) Linode")
print(f" {WHITE}2{RESET}) AWS (EC2)")
print(f" {WHITE}3{RESET}) FlokiNET (pre-provisioned)")
print(f" {WHITE}4{RESET}) Existing server (SSH)")
print(f" {WHITE}5{RESET}) Local (this machine)")
print()
choice = input(f" {MAGENTA}>{RESET} ").strip()
providers = {"1": "linode", "2": "aws", "3": "flokinet", "4": "existing", "5": "local"}
return providers.get(choice)
def gather_credentials(provider, config):
"""Gather provider-specific credentials."""
if provider == "linode":
config["provider"] = "linode"
config["api_token"] = input(f" {CYAN}Linode API token:{RESET} ").strip()
config["region"] = input(f" {CYAN}Region (e.g. us-east):{RESET} ").strip() or "us-east"
config["plan"] = input(f" {CYAN}Plan (e.g. g6-nanode-1):{RESET} ").strip() or "g6-nanode-1"
elif provider == "aws":
config["provider"] = "aws"
config["aws_access_key"] = input(f" {CYAN}AWS Access Key ID:{RESET} ").strip()
config["aws_secret_key"] = input(f" {CYAN}AWS Secret Access Key:{RESET} ").strip()
config["region"] = input(f" {CYAN}Region (e.g. us-east-1):{RESET} ").strip() or "us-east-1"
config["instance_type"] = input(f" {CYAN}Instance type (e.g. t3.micro):{RESET} ").strip() or "t3.micro"
elif provider == "flokinet":
config["provider"] = "flokinet"
config["target_host"] = input(f" {CYAN}Server IP:{RESET} ").strip()
config["ssh_user"] = input(f" {CYAN}SSH user [root]:{RESET} ").strip() or "root"
elif provider == "existing":
config["provider"] = "existing"
config["target_host"] = input(f" {CYAN}Server IP/hostname:{RESET} ").strip()
config["ssh_user"] = input(f" {CYAN}SSH user [root]:{RESET} ").strip() or "root"
existing_key = input(f" {CYAN}SSH key path (blank to generate):{RESET} ").strip()
if existing_key:
config["ssh_key"] = existing_key
elif provider == "local":
config["provider"] = "local"
config["target_host"] = "localhost"
config["ssh_user"] = os.getenv("USER", "root")
warn("Local deployment will install services directly on this machine.")
confirm = input(f" {YELLOW}Continue? [y/N]:{RESET} ").strip().lower()
if confirm != "y":
return False
return True
# ─── Deployment Orchestration ───────────────────────────────────────────────
def deploy(server_type, config):
"""Full deployment pipeline: summarize -> confirm -> provision -> configure."""
config["server_type"] = server_type
config.setdefault("deploy_id", generate_id())
deploy_id = config["deploy_id"]
# Summary
print(f"\n{CYAN}{'' * 60}{RESET}")
print(f"{MAGENTA} Deployment Summary{RESET}")
print(f"{CYAN}{'' * 60}{RESET}")
print(f" {WHITE}ID:{RESET} {deploy_id}")
print(f" {WHITE}Type:{RESET} {server_type}")
print(f" {WHITE}Provider:{RESET} {config.get('provider', 'unknown')}")
print(f" {WHITE}Target:{RESET} {config.get('target_host', 'TBD (will provision)')}")
if config.get("domain"):
print(f" {WHITE}Domain:{RESET} {config['domain']}")
for k, v in config.items():
if k not in ("deploy_id", "server_type", "provider", "target_host",
"domain", "api_token", "aws_access_key", "aws_secret_key",
"ssh_key", "ssh_user", "timestamp"):
print(f" {WHITE}{k}:{RESET} {v}")
print(f"{CYAN}{'' * 60}{RESET}")
confirm = input(f"\n {MAGENTA}Deploy? [y/N]:{RESET} ").strip().lower()
if confirm != "y":
warn("Deployment cancelled.")
return
# Generate SSH key if needed
if config.get("provider") not in ("local",) and not config.get("ssh_key"):
config["ssh_key"] = generate_ssh_key(deploy_id)
# Provision if cloud provider
if config.get("provider") in ("linode", "aws"):
provider_playbook = PROVIDERS_DIR / f"{config['provider']}.yml"
# Tell the provider playbook where to write the provisioned IP
host_file = LOGS_DIR / deploy_id / "provisioned_host"
config["_host_output_file"] = str(host_file)
info(f"Provisioning {config['provider']} instance...")
if not run_playbook(provider_playbook, config):
err("Provisioning failed.")
return
# Read back the provisioned host IP
if host_file.exists():
config["target_host"] = host_file.read_text().strip()
ok(f"Provisioned server: {config['target_host']}")
else:
err("Provisioning completed but no host IP was returned.")
return
# Base hardening
info("Applying base hardening...")
if not run_playbook(PLAYBOOKS_DIR / "common/base_hardening.yml", config):
err("Base hardening failed — aborting deployment.")
return
# Service-specific playbook
playbook_map = {
"matrix": PLAYBOOKS_DIR / "matrix/main.yml",
"vpn": PLAYBOOKS_DIR / "vpn/main.yml",
"dns": PLAYBOOKS_DIR / "dns/main.yml",
"cloud": PLAYBOOKS_DIR / "cloud/main.yml",
"vault": PLAYBOOKS_DIR / "vault/main.yml",
"media": PLAYBOOKS_DIR / "media/main.yml",
"email": PLAYBOOKS_DIR / "email/main.yml",
"all_in_one": PLAYBOOKS_DIR / "all_in_one/main.yml",
}
playbook = playbook_map.get(server_type)
if playbook:
info(f"Configuring {server_type}...")
if run_playbook(playbook, config):
ok(f"Deployment complete: {deploy_id}")
else:
err(f"Service configuration failed for {server_type}")
return
# Save info and offer SSH
save_deploy_info(config)
ssh_connect(config)
# ─── Main Menu ──────────────────────────────────────────────────────────────
MENU_ITEMS = [
("1", "Matrix + Element", "matrix", "Encrypted messaging homeserver"),
("2", "WireGuard VPN", "vpn", "Private VPN server"),
("3", "Pi-hole DNS", "dns", "Ad-blocking DNS server"),
("4", "Nextcloud", "cloud", "Self-hosted file sync (coming soon)"),
("5", "Vaultwarden", "vault", "Password manager (coming soon)"),
("6", "Jellyfin", "media", "Media server (coming soon)"),
("7", "Mail-in-a-Box", "email", "Email server (coming soon)"),
("8", "All-in-One", "all_in_one", "Multiple services on one server"),
("0", "Exit", None, None),
]
def main_menu():
banner()
while True:
print(f"\n{CYAN} ┌─ Deploy a Privacy Server ──────────────────────────┐{RESET}")
for num, label, _, desc in MENU_ITEMS:
if desc:
print(f" {CYAN}{RESET} {WHITE}{num}{RESET}) {label:<20} {GREY}{desc}{RESET}")
else:
print(f" {CYAN}{RESET} {WHITE}{num}{RESET}) {label}")
print(f" {CYAN}└─────────────────────────────────────────────────────┘{RESET}")
choice = input(f"\n {MAGENTA}>{RESET} ").strip()
if choice == "0":
print(f"\n{GREY} Goodbye.{RESET}\n")
break
# Find matching menu item
selected = None
for num, label, stype, _ in MENU_ITEMS:
if choice == num and stype:
selected = stype
break
if not selected:
warn("Invalid selection.")
continue
# Import the module
try:
mod = __import__(f"modules.{selected}", fromlist=[selected])
except ImportError as e:
err(f"Module not found: {selected} ({e})")
continue
# Select provider
provider = select_provider()
if not provider:
warn("Invalid provider selection.")
continue
config = {"deploy_id": generate_id()}
if not gather_credentials(provider, config):
continue
# Gather service-specific config
if hasattr(mod, "gather_config"):
config = mod.gather_config(config)
if config is None:
continue
# Deploy
deploy(selected, config)
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] in ("--help", "-h"):
print("Usage: python3 phantom.py")
print(" Interactive privacy server deployer.")
print(" Supports Matrix, WireGuard, Pi-hole, and more.")
print(" Run without arguments to launch the interactive menu.")
sys.exit(0)
try:
main_menu()
except KeyboardInterrupt:
print(f"\n{GREY} Interrupted.{RESET}\n")
+92
View File
@@ -0,0 +1,92 @@
---
# All-in-One deployment — multiple services on a single server
# Installs nginx as reverse proxy with TLS termination via Certbot,
# then deploys selected services behind vhost routing.
#
# NOTE: This playbook includes task files directly rather than
# importing full playbooks, to allow conditional composition.
- name: All-in-One Privacy Server
hosts: all
become: true
vars:
base_domain: "{{ domain }}"
selected_services: "{{ services | default([]) }}"
certbot_email: "{{ certbot_email | default('') }}"
target_host: "{{ target_host | default('localhost') }}"
tasks:
# ─── Base: Nginx + Certbot ────────────────────────────────────────
- name: Install nginx and certbot
apt:
name:
- nginx
- certbot
- python3-certbot-nginx
state: present
- name: Remove default nginx site
file:
path: /etc/nginx/sites-enabled/default
state: absent
notify: reload nginx
- name: Allow HTTP/HTTPS through UFW
ufw:
rule: allow
port: "{{ item }}"
proto: tcp
loop:
- "80"
- "443"
# ─── Deploy Individual Services (task files, not full playbooks) ──
- name: Deploy Matrix — Synapse
include_tasks: "{{ playbook_dir }}/../matrix/tasks/synapse.yml"
when: "'matrix' in selected_services"
- name: Deploy Matrix — Element Web
include_tasks: "{{ playbook_dir }}/../matrix/tasks/element.yml"
when: "'matrix' in selected_services and (matrix_element_web | default(true) | bool)"
- name: Deploy Matrix — Nginx vhost
include_tasks: "{{ playbook_dir }}/../matrix/tasks/nginx.yml"
when: "'matrix' in selected_services"
- name: Deploy WireGuard — Install
include_tasks: "{{ playbook_dir }}/../vpn/tasks/install.yml"
when: "'vpn' in selected_services"
- name: Deploy WireGuard — Configure
include_tasks: "{{ playbook_dir }}/../vpn/tasks/configure.yml"
when: "'vpn' in selected_services"
- name: Deploy Pi-hole — Install
include_tasks: "{{ playbook_dir }}/../dns/tasks/install.yml"
when: "'dns' in selected_services"
- name: Deploy Pi-hole — Configure
include_tasks: "{{ playbook_dir }}/../dns/tasks/configure.yml"
when: "'dns' in selected_services"
# Stub services — print notice
- name: Notice for stub services
debug:
msg: "Service '{{ item }}' playbook not yet implemented — skipping"
loop: "{{ selected_services | select('in', ['cloud', 'vault', 'media', 'email']) | list }}"
handlers:
- name: reload nginx
service:
name: nginx
state: reloaded
- name: restart synapse
service:
name: matrix-synapse
state: restarted
- name: restart sshd
service:
name: sshd
state: restarted
+11
View File
@@ -0,0 +1,11 @@
---
# Cloud deployment — Coming soon
# This is a stub playbook. Full implementation planned.
- name: Deploy Cloud Server
hosts: all
become: true
tasks:
- name: Placeholder
debug:
msg: "Cloud playbook not yet implemented. Check phantom/README.md for status."
+144
View File
@@ -0,0 +1,144 @@
---
# Base server hardening — applied to all deployments
# Covers: updates, firewall, fail2ban, SSH hardening
- name: Base Server Hardening
hosts: all
become: true
vars:
ssh_port: "{{ ssh_port | default(22) }}"
ssh_allow_password: false
tasks:
# ─── System Updates ─────────────────────────────────────────────────
- name: Update apt cache
apt:
update_cache: true
cache_valid_time: 3600
when: ansible_os_family == "Debian"
- name: Upgrade all packages
apt:
upgrade: safe
when: ansible_os_family == "Debian"
- name: Install essential packages
apt:
name:
- ufw
- fail2ban
- unattended-upgrades
- apt-listchanges
- curl
- wget
- gnupg
- ca-certificates
- software-properties-common
state: present
when: ansible_os_family == "Debian"
# ─── UFW Firewall ───────────────────────────────────────────────────
- name: Set UFW default deny incoming
ufw:
direction: incoming
policy: deny
- name: Set UFW default allow outgoing
ufw:
direction: outgoing
policy: allow
- name: Allow SSH through UFW
ufw:
rule: allow
port: "{{ ssh_port }}"
proto: tcp
- name: Enable UFW
ufw:
state: enabled
# ─── Fail2ban ───────────────────────────────────────────────────────
- name: Configure fail2ban SSH jail
copy:
dest: /etc/fail2ban/jail.local
content: |
[sshd]
enabled = true
port = {{ ssh_port }}
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 3600
findtime = 600
mode: "0644"
notify: restart fail2ban
- name: Enable fail2ban
service:
name: fail2ban
state: started
enabled: true
# ─── SSH Hardening ──────────────────────────────────────────────────
- name: Disable SSH password authentication
lineinfile:
path: /etc/ssh/sshd_config
regexp: "^#?PasswordAuthentication"
line: "PasswordAuthentication no"
when: not ssh_allow_password
notify: restart sshd
- name: Disable SSH root login with password
lineinfile:
path: /etc/ssh/sshd_config
regexp: "^#?PermitRootLogin"
line: "PermitRootLogin prohibit-password"
notify: restart sshd
- name: Disable SSH X11 forwarding
lineinfile:
path: /etc/ssh/sshd_config
regexp: "^#?X11Forwarding"
line: "X11Forwarding no"
notify: restart sshd
# ─── Automatic Security Updates ─────────────────────────────────────
- name: Enable unattended upgrades for security
copy:
dest: /etc/apt/apt.conf.d/20auto-upgrades
content: |
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
mode: "0644"
when: ansible_os_family == "Debian"
# ─── Kernel Hardening ───────────────────────────────────────────────
- name: Apply sysctl hardening
sysctl:
name: "{{ item.key }}"
value: "{{ item.value }}"
sysctl_set: true
reload: true
loop:
- { key: "net.ipv4.conf.all.rp_filter", value: "1" }
- { key: "net.ipv4.conf.default.rp_filter", value: "1" }
- { key: "net.ipv4.icmp_echo_ignore_broadcasts", value: "1" }
- { key: "net.ipv4.conf.all.accept_redirects", value: "0" }
- { key: "net.ipv4.conf.default.accept_redirects", value: "0" }
- { key: "net.ipv6.conf.all.accept_redirects", value: "0" }
- { key: "net.ipv6.conf.default.accept_redirects", value: "0" }
- { key: "net.ipv4.conf.all.send_redirects", value: "0" }
- { key: "net.ipv4.conf.default.send_redirects", value: "0" }
handlers:
- name: restart fail2ban
service:
name: fail2ban
state: restarted
- name: restart sshd
service:
name: sshd
state: restarted
+18
View File
@@ -0,0 +1,18 @@
---
# Pi-hole DNS server deployment (Docker-based)
- name: Deploy Pi-hole DNS Server
hosts: all
become: true
vars:
pihole_upstream: "{{ dns_upstream | default('9.9.9.9;149.112.112.112') }}"
pihole_domain: "{{ dns_domain | default('') }}"
pihole_blocklist: "{{ dns_blocklist | default('standard') }}"
target_host: "{{ target_host | default('localhost') }}"
tasks:
- name: Include Pi-hole installation
include_tasks: tasks/install.yml
- name: Include Pi-hole configuration
include_tasks: tasks/configure.yml
+66
View File
@@ -0,0 +1,66 @@
---
# Pi-hole Docker configuration and launch
- name: Create Pi-hole directories
file:
path: "{{ item }}"
state: directory
mode: "0755"
loop:
- /opt/pihole
- /opt/pihole/etc-pihole
- /opt/pihole/etc-dnsmasq.d
- name: Generate Pi-hole admin password
shell: "openssl rand -base64 16"
register: pihole_password
args:
creates: /opt/pihole/.password
- name: Save admin password
copy:
content: "{{ pihole_password.stdout }}"
dest: /opt/pihole/.password
mode: "0600"
when: pihole_password.changed
- name: Deploy Pi-hole Docker Compose
copy:
dest: /opt/pihole/docker-compose.yml
content: |
services:
pihole:
container_name: pihole
image: pihole/pihole:latest
ports:
- "53:53/tcp"
- "53:53/udp"
- "80:80/tcp"
environment:
TZ: UTC
WEBPASSWORD_FILE: /run/secrets/webpassword
PIHOLE_DNS_: "{{ pihole_upstream }}"
DNSSEC: "true"
QUERY_LOGGING: "false"
volumes:
- /opt/pihole/etc-pihole:/etc/pihole
- /opt/pihole/etc-dnsmasq.d:/etc/dnsmasq.d
secrets:
- webpassword
restart: unless-stopped
dns:
- 127.0.0.1
- 9.9.9.9
secrets:
webpassword:
file: /opt/pihole/.password
mode: "0644"
- name: Start Pi-hole
shell: cd /opt/pihole && docker compose up -d
args:
creates: /opt/pihole/etc-pihole/pihole-FTL.db
- name: Display admin password
debug:
msg: "Pi-hole admin password: {{ pihole_password.stdout | default('(see /opt/pihole/.password)') }}"
+62
View File
@@ -0,0 +1,62 @@
---
# Pi-hole installation via Docker
- name: Install Docker prerequisites
apt:
name:
- apt-transport-https
- ca-certificates
- curl
- gnupg
- lsb-release
state: present
- name: Add Docker GPG key
apt_key:
url: https://download.docker.com/linux/{{ ansible_distribution | lower }}/gpg
state: present
- name: Add Docker repository
apt_repository:
repo: "deb https://download.docker.com/linux/{{ ansible_distribution | lower }} {{ ansible_distribution_release }} stable"
state: present
- name: Install Docker
apt:
name:
- docker-ce
- docker-ce-cli
- containerd.io
- docker-compose-plugin
state: present
- name: Enable Docker service
service:
name: docker
state: started
enabled: true
- name: Stop systemd-resolved (conflicts with Pi-hole on port 53)
service:
name: systemd-resolved
state: stopped
enabled: false
failed_when: false
- name: Set DNS fallback
copy:
dest: /etc/resolv.conf
content: |
nameserver 9.9.9.9
nameserver 1.1.1.1
mode: "0644"
- name: Allow DNS through UFW
ufw:
rule: allow
port: "{{ item.port }}"
proto: "{{ item.proto }}"
loop:
- { port: "53", proto: "tcp" }
- { port: "53", proto: "udp" }
- { port: "80", proto: "tcp" }
+11
View File
@@ -0,0 +1,11 @@
---
# Email deployment — Coming soon
# This is a stub playbook. Full implementation planned.
- name: Deploy Email Server
hosts: all
become: true
tasks:
- name: Placeholder
debug:
msg: "Email playbook not yet implemented. Check phantom/README.md for status."
+38
View File
@@ -0,0 +1,38 @@
---
# Matrix (Synapse) + Element Web deployment
# Installs Synapse homeserver with optional Element Web frontend
- name: Deploy Matrix Homeserver
hosts: all
become: true
vars:
matrix_domain: "{{ domain }}"
matrix_server_name: "{{ matrix_server_name | default(domain) }}"
matrix_admin: "{{ matrix_admin_user | default('admin') }}"
matrix_admin_pass: "{{ matrix_admin_password }}"
matrix_registration_enabled: "{{ matrix_registration | default(false) }}"
element_enabled: "{{ matrix_element_web | default(true) }}"
matrix_signing_key: "{{ matrix_signing_key }}"
target_host: "{{ target_host | default('localhost') }}"
tasks:
- name: Include Synapse installation tasks
include_tasks: tasks/synapse.yml
- name: Include Element Web tasks
include_tasks: tasks/element.yml
when: element_enabled | bool
- name: Include nginx reverse proxy tasks
include_tasks: tasks/nginx.yml
handlers:
- name: restart synapse
service:
name: matrix-synapse
state: restarted
- name: reload nginx
service:
name: nginx
state: reloaded
@@ -0,0 +1,44 @@
---
# Element Web frontend installation
- name: Install nginx (if not already)
apt:
name: nginx
state: present
- name: Create Element Web directory
file:
path: /var/www/element
state: directory
owner: www-data
group: www-data
mode: "0755"
- name: Download latest Element Web release
shell: |
LATEST=$(curl -s https://api.github.com/repos/element-hq/element-web/releases/latest | grep -oP '"tag_name": "\K[^"]+')
curl -sL "https://github.com/element-hq/element-web/releases/download/${LATEST}/element-${LATEST}.tar.gz" | tar xz -C /var/www/element --strip-components=1
args:
creates: /var/www/element/index.html
- name: Deploy Element Web config
copy:
dest: /var/www/element/config.json
content: |
{
"default_server_config": {
"m.homeserver": {
"base_url": "https://{{ matrix_domain }}",
"server_name": "{{ matrix_server_name }}"
}
},
"brand": "Element",
"integrations_ui_url": "",
"integrations_rest_url": "",
"disable_guests": true,
"disable_3pid_login": false,
"default_theme": "dark"
}
owner: www-data
group: www-data
mode: "0644"
+115
View File
@@ -0,0 +1,115 @@
---
# Nginx reverse proxy for Matrix + Element
# Two-phase: HTTP-only first for certbot, then full SSL config
- name: Create certbot webroot
file:
path: /var/www/certbot
state: directory
owner: www-data
group: www-data
mode: "0755"
- name: Deploy HTTP-only nginx config (for certbot)
copy:
dest: /etc/nginx/sites-available/matrix
content: |
server {
listen 80;
server_name {{ matrix_domain }};
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 200 'phantom setup in progress';
add_header Content-Type text/plain;
}
}
mode: "0644"
notify: reload nginx
- name: Enable Matrix nginx site
file:
src: /etc/nginx/sites-available/matrix
dest: /etc/nginx/sites-enabled/matrix
state: link
notify: reload nginx
- name: Flush handlers to apply HTTP config
meta: flush_handlers
- name: Obtain TLS certificate
command: >
certbot certonly --webroot -w /var/www/certbot
-d {{ matrix_domain }}
--non-interactive
--agree-tos
{% if certbot_email is defined and certbot_email %}
--email {{ certbot_email }}
{% else %}
--register-unsafely-without-email
{% endif %}
args:
creates: "/etc/letsencrypt/live/{{ matrix_domain }}/fullchain.pem"
- name: Deploy full SSL nginx config
copy:
dest: /etc/nginx/sites-available/matrix
content: |
server {
listen 80;
server_name {{ matrix_domain }};
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
listen 8448 ssl http2;
server_name {{ matrix_domain }};
ssl_certificate /etc/letsencrypt/live/{{ matrix_domain }}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/{{ matrix_domain }}/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
client_max_body_size 50m;
# Synapse
location ~* ^(\/_matrix|\/_synapse\/client) {
proxy_pass http://127.0.0.1:8008;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
}
# .well-known delegation
location /.well-known/matrix/server {
return 200 '{"m.server": "{{ matrix_domain }}:443"}';
add_header Content-Type application/json;
}
location /.well-known/matrix/client {
return 200 '{"m.homeserver": {"base_url": "https://{{ matrix_domain }}"}}';
add_header Content-Type application/json;
add_header Access-Control-Allow-Origin *;
}
# Element Web (if enabled)
location / {
root /var/www/element;
try_files $uri $uri/ /index.html;
}
}
mode: "0644"
notify: reload nginx
@@ -0,0 +1,99 @@
---
# Synapse homeserver installation and configuration
- name: Install dependencies
apt:
name:
- python3
- python3-pip
- python3-venv
- libpq-dev
- postgresql
- postgresql-contrib
- nginx
- certbot
- python3-certbot-nginx
state: present
- name: Add Matrix Synapse apt repository key
apt_key:
url: https://packages.matrix.org/debian/matrix-org-archive-keyring.gpg
state: present
- name: Add Matrix Synapse apt repository
apt_repository:
repo: "deb https://packages.matrix.org/debian/ {{ ansible_distribution_release }} main"
state: present
filename: matrix-org
- name: Install Synapse
apt:
name: matrix-synapse-py3
state: present
environment:
DEBIAN_FRONTEND: noninteractive
- name: Create PostgreSQL database
become_user: postgres
postgresql_db:
name: synapse
encoding: UTF-8
lc_collate: C
lc_ctype: C
template: template0
- name: Create PostgreSQL user
become_user: postgres
postgresql_user:
name: synapse
password: "{{ matrix_signing_key[:32] }}"
db: synapse
priv: ALL
- name: Deploy Synapse homeserver config
template:
src: ../templates/homeserver.yaml.j2
dest: /etc/matrix-synapse/homeserver.yaml
owner: matrix-synapse
group: matrix-synapse
mode: "0640"
notify: restart synapse
- name: Allow Matrix federation port through UFW
ufw:
rule: allow
port: "8448"
proto: tcp
- name: Allow HTTP/HTTPS through UFW
ufw:
rule: allow
port: "{{ item }}"
proto: tcp
loop:
- "80"
- "443"
- name: Enable and start Synapse
service:
name: matrix-synapse
state: started
enabled: true
- name: Wait for Synapse to be ready
wait_for:
port: 8008
host: 127.0.0.1
timeout: 30
- name: Create admin user
command: >
register_new_matrix_user
-u {{ matrix_admin }}
-p {{ matrix_admin_pass }}
-a
-c /etc/matrix-synapse/homeserver.yaml
http://localhost:8008
register: admin_create
failed_when: false
changed_when: admin_create.rc == 0
@@ -0,0 +1,53 @@
## Synapse Homeserver Configuration
## Generated by phantom
server_name: "{{ matrix_server_name }}"
pid_file: /run/matrix-synapse.pid
listeners:
- port: 8008
tls: false
type: http
x_forwarded: true
resources:
- names: [client, federation]
compress: false
database:
name: psycopg2
args:
user: synapse
password: "{{ matrix_signing_key[:32] }}"
database: synapse
host: localhost
cp_min: 5
cp_max: 10
log_config: "/etc/matrix-synapse/log.yaml"
media_store_path: /var/lib/matrix-synapse/media
signing_key_path: "/etc/matrix-synapse/{{ matrix_server_name }}.signing.key"
enable_registration: {{ matrix_registration_enabled | lower }}
{% if not matrix_registration_enabled %}
enable_registration_without_verification: false
{% endif %}
suppress_key_server_warning: true
trusted_key_servers:
- server_name: "matrix.org"
max_upload_size: 50M
url_preview_enabled: true
url_preview_ip_range_blacklist:
- '127.0.0.0/8'
- '10.0.0.0/8'
- '172.16.0.0/12'
- '192.168.0.0/16'
- '100.64.0.0/10'
- '192.0.0.0/24'
- '169.254.0.0/16'
- '::1/128'
- 'fe80::/10'
- 'fc00::/7'
+11
View File
@@ -0,0 +1,11 @@
---
# Media deployment — Coming soon
# This is a stub playbook. Full implementation planned.
- name: Deploy Media Server
hosts: all
become: true
tasks:
- name: Placeholder
debug:
msg: "Media playbook not yet implemented. Check phantom/README.md for status."
+11
View File
@@ -0,0 +1,11 @@
---
# Vault deployment — Coming soon
# This is a stub playbook. Full implementation planned.
- name: Deploy Vault Server
hosts: all
become: true
tasks:
- name: Placeholder
debug:
msg: "Vault playbook not yet implemented. Check phantom/README.md for status."
+20
View File
@@ -0,0 +1,20 @@
---
# WireGuard VPN server deployment
- name: Deploy WireGuard VPN Server
hosts: all
become: true
vars:
wg_port: "{{ vpn_port | default(51820) }}"
wg_clients: "{{ vpn_client_count | default(3) }}"
wg_dns: "{{ vpn_dns | default('1.1.1.1') }}"
wg_subnet: "{{ vpn_subnet | default('10.66.66.0/24') }}"
wg_allowed_ips: "{{ vpn_allowed_ips | default('0.0.0.0/0, ::/0') }}"
target_host: "{{ target_host | default('localhost') }}"
tasks:
- name: Include WireGuard installation tasks
include_tasks: tasks/install.yml
- name: Include WireGuard configuration tasks
include_tasks: tasks/configure.yml
+88
View File
@@ -0,0 +1,88 @@
---
# WireGuard server and client configuration
- name: Detect primary network interface
shell: ip route get 1.1.1.1 | awk '{for(i=1;i<=NF;i++) if($i=="dev") print $(i+1)}'
register: primary_interface
changed_when: false
- name: Generate client keys
shell: |
mkdir -p /etc/wireguard/clients
for i in $(seq 1 {{ wg_clients }}); do
if [ ! -f /etc/wireguard/clients/client${i}_private.key ]; then
wg genkey | tee /etc/wireguard/clients/client${i}_private.key | wg pubkey > /etc/wireguard/clients/client${i}_public.key
wg genpsk > /etc/wireguard/clients/client${i}_psk.key
chmod 600 /etc/wireguard/clients/client${i}_*.key
fi
done
args:
creates: /etc/wireguard/clients/client1_private.key
- name: Build WireGuard server config
shell: |
SERVER_PRIVKEY=$(cat /etc/wireguard/server_private.key)
IFACE={{ primary_interface.stdout | trim }}
cat > /etc/wireguard/wg0.conf << EOF
[Interface]
Address = {{ wg_subnet | regex_replace('/\\d+$', '') | regex_replace('\\.[0-9]+$', '.1/24') }}
ListenPort = {{ wg_port }}
PrivateKey = ${SERVER_PRIVKEY}
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ${IFACE} -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o ${IFACE} -j MASQUERADE
EOF
for i in $(seq 1 {{ wg_clients }}); do
CLIENT_PUBKEY=$(cat /etc/wireguard/clients/client${i}_public.key)
CLIENT_PSK=$(cat /etc/wireguard/clients/client${i}_psk.key)
cat >> /etc/wireguard/wg0.conf << EOF
[Peer]
# Client ${i}
PublicKey = ${CLIENT_PUBKEY}
PresharedKey = ${CLIENT_PSK}
AllowedIPs = {{ wg_subnet | regex_replace('/\\d+$', '') | regex_replace('\\.[0-9]+$', '') }}.$(( i + 1 ))/32
EOF
done
chmod 600 /etc/wireguard/wg0.conf
args:
creates: /etc/wireguard/wg0.conf
- name: Generate client config files
shell: |
SERVER_PUBKEY=$(echo '{{ server_privkey_content.content | b64decode | trim }}' | wg pubkey)
SERVER_ENDPOINT="{{ target_host }}:{{ wg_port }}"
for i in $(seq 1 {{ wg_clients }}); do
CLIENT_PRIVKEY=$(cat /etc/wireguard/clients/client${i}_private.key)
CLIENT_PSK=$(cat /etc/wireguard/clients/client${i}_psk.key)
CLIENT_IP="{{ wg_subnet | regex_replace('/\\d+$', '') | regex_replace('\\.[0-9]+$', '') }}.$(( i + 1 ))"
cat > /etc/wireguard/clients/client${i}.conf << EOF
[Interface]
PrivateKey = ${CLIENT_PRIVKEY}
Address = ${CLIENT_IP}/32
DNS = {{ wg_dns }}
[Peer]
PublicKey = ${SERVER_PUBKEY}
PresharedKey = ${CLIENT_PSK}
Endpoint = ${SERVER_ENDPOINT}
AllowedIPs = {{ wg_allowed_ips }}
PersistentKeepalive = 25
EOF
# Generate QR code
qrencode -t ansiutf8 < /etc/wireguard/clients/client${i}.conf > /etc/wireguard/clients/client${i}_qr.txt 2>/dev/null || true
done
args:
creates: /etc/wireguard/clients/client1.conf
- name: Enable and start WireGuard
systemd:
name: wg-quick@wg0
state: started
enabled: true
+54
View File
@@ -0,0 +1,54 @@
---
# WireGuard installation and server key generation
- name: Install WireGuard
apt:
name:
- wireguard
- wireguard-tools
- qrencode
state: present
when: ansible_os_family == "Debian"
- name: Enable IP forwarding (IPv4)
sysctl:
name: net.ipv4.ip_forward
value: "1"
sysctl_set: true
reload: true
- name: Enable IP forwarding (IPv6)
sysctl:
name: net.ipv6.conf.all.forwarding
value: "1"
sysctl_set: true
reload: true
- name: Generate server private key
shell: wg genkey
register: wg_server_privkey
args:
creates: /etc/wireguard/server_private.key
- name: Save server private key
copy:
content: "{{ wg_server_privkey.stdout }}"
dest: /etc/wireguard/server_private.key
mode: "0600"
when: wg_server_privkey.changed
- name: Read server private key
slurp:
src: /etc/wireguard/server_private.key
register: server_privkey_content
- name: Generate server public key
shell: "echo '{{ server_privkey_content.content | b64decode | trim }}' | wg pubkey"
register: wg_server_pubkey
changed_when: false
- name: Allow WireGuard port through UFW
ufw:
rule: allow
port: "{{ wg_port }}"
proto: udp
+105
View File
@@ -0,0 +1,105 @@
---
# Provision an AWS EC2 instance for phantom deployment
# Requires: aws_access_key, aws_secret_key variables
- name: Provision AWS EC2 Instance
hosts: localhost
connection: local
gather_facts: false
vars:
aws_region: "{{ region | default('us-east-1') }}"
ec2_instance_type: "{{ instance_type | default('t3.micro') }}"
ec2_ami: "{{ ami | default('') }}"
ec2_key_name: "phantom-{{ deploy_id }}"
ssh_key_path: "{{ ssh_key }}.pub"
environment:
AWS_ACCESS_KEY_ID: "{{ aws_access_key }}"
AWS_SECRET_ACCESS_KEY: "{{ aws_secret_key }}"
AWS_DEFAULT_REGION: "{{ aws_region }}"
tasks:
- name: Read SSH public key
slurp:
src: "{{ ssh_key_path }}"
register: ssh_pubkey
- name: Import SSH key to AWS
amazon.aws.ec2_key:
name: "{{ ec2_key_name }}"
key_material: "{{ ssh_pubkey.content | b64decode | trim }}"
region: "{{ aws_region }}"
- name: Find latest Debian AMI (if not specified)
amazon.aws.ec2_ami_info:
region: "{{ aws_region }}"
owners: ["136693071363"]
filters:
name: "debian-12-amd64-*"
architecture: x86_64
virtualization-type: hvm
register: ami_results
when: ec2_ami == ""
- name: Set AMI fact
set_fact:
ec2_ami: "{{ (ami_results.images | sort(attribute='creation_date') | last).image_id }}"
when: ec2_ami == ""
- name: Create security group
amazon.aws.ec2_security_group:
name: "phantom-{{ deploy_id }}"
description: "phantom deployment {{ deploy_id }}"
region: "{{ aws_region }}"
rules:
- proto: tcp
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 80
to_port: 80
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 443
to_port: 443
cidr_ip: 0.0.0.0/0
register: sg_result
- name: Launch EC2 instance
amazon.aws.ec2_instance:
name: "phantom-{{ deploy_id }}"
key_name: "{{ ec2_key_name }}"
instance_type: "{{ ec2_instance_type }}"
image_id: "{{ ec2_ami }}"
region: "{{ aws_region }}"
security_group: "{{ sg_result.group_id }}"
wait: true
state: running
register: ec2_result
- name: Set target host fact
set_fact:
target_host: "{{ ec2_result.instances[0].public_ip_address }}"
- name: Display instance info
debug:
msg: |
EC2 instance provisioned:
ID: {{ ec2_result.instances[0].instance_id }}
IP: {{ target_host }}
Region: {{ aws_region }}
Type: {{ ec2_instance_type }}
- name: Write provisioned host IP for phantom
copy:
content: "{{ target_host }}"
dest: "{{ _host_output_file }}"
when: _host_output_file is defined
- name: Wait for SSH
wait_for:
host: "{{ target_host }}"
port: 22
delay: 15
timeout: 300
+30
View File
@@ -0,0 +1,30 @@
---
# Register a pre-provisioned FlokiNET server for phantom deployment
# FlokiNET servers are provisioned manually via their control panel.
# This playbook only validates SSH connectivity and prepares the server.
- name: Register FlokiNET Server
hosts: all
become: true
gather_facts: false
tasks:
- name: Ensure Python is available for Ansible
raw: test -e /usr/bin/python3 || (apt-get update && apt-get install -y python3)
changed_when: false
- name: Gather facts now that Python is available
setup:
- name: Verify SSH connectivity
ping:
- name: Display server info
debug:
msg: |
FlokiNET server registered:
Hostname: {{ ansible_hostname }}
OS: {{ ansible_distribution }} {{ ansible_distribution_version }}
IP: {{ ansible_default_ipv4.address | default(target_host) }}
RAM: {{ ansible_memtotal_mb }}MB
Cores: {{ ansible_processor_vcpus }}
+66
View File
@@ -0,0 +1,66 @@
---
# Provision a Linode instance for phantom deployment
# Requires: LINODE_API_TOKEN or api_token variable
- name: Provision Linode Instance
hosts: localhost
connection: local
gather_facts: false
vars:
linode_token: "{{ api_token }}"
linode_region: "{{ region | default('us-east') }}"
linode_plan: "{{ plan | default('g6-nanode-1') }}"
linode_image: "{{ image | default('linode/debian12') }}"
linode_label: "phantom-{{ deploy_id }}"
ssh_key_path: "{{ ssh_key }}.pub"
tasks:
- name: Read SSH public key
slurp:
src: "{{ ssh_key_path }}"
register: ssh_pubkey
- name: Create Linode instance
uri:
url: https://api.linode.com/v4/linode/instances
method: POST
headers:
Authorization: "Bearer {{ linode_token }}"
Content-Type: application/json
body_format: json
body:
type: "{{ linode_plan }}"
region: "{{ linode_region }}"
image: "{{ linode_image }}"
label: "{{ linode_label }}"
authorized_keys:
- "{{ ssh_pubkey.content | b64decode | trim }}"
booted: true
status_code: 200
register: linode_result
- name: Set target host fact
set_fact:
target_host: "{{ linode_result.json.ipv4[0] }}"
- name: Display instance info
debug:
msg: |
Linode provisioned:
ID: {{ linode_result.json.id }}
IP: {{ linode_result.json.ipv4[0] }}
Region: {{ linode_region }}
Plan: {{ linode_plan }}
- name: Write provisioned host IP for phantom
copy:
content: "{{ target_host }}"
dest: "{{ _host_output_file }}"
when: _host_output_file is defined
- name: Wait for SSH
wait_for:
host: "{{ target_host }}"
port: 22
delay: 10
timeout: 300