mirror of
https://github.com/trailofbits/algo.git
synced 2025-09-02 10:03:01 +02:00
* Fix VPN routing by adding output interface to NAT rules The NAT rules were missing the output interface specification (-o eth0), which caused routing failures on multi-homed systems (servers with multiple network interfaces). Without specifying the output interface, packets might not be NAT'd correctly. Changes: - Added -o {{ ansible_default_ipv4['interface'] }} to all NAT rules - Updated both IPv4 and IPv6 templates - Updated tests to verify output interface is present - Added ansible_default_ipv4/ipv6 to test fixtures This fixes the issue where VPN clients could connect but not route traffic to the internet on servers with multiple network interfaces (like DigitalOcean droplets with private networking enabled). 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Fix VPN routing by adding output interface to NAT rules On multi-homed systems (servers with multiple network interfaces or multiple IPs on one interface), MASQUERADE rules need to specify which interface to use for NAT. Without the output interface specification, packets may not be routed correctly. This fix adds the output interface to all NAT rules: -A POSTROUTING -s [vpn_subnet] -o eth0 -j MASQUERADE Changes: - Modified roles/common/templates/rules.v4.j2 to include output interface - Modified roles/common/templates/rules.v6.j2 for IPv6 support - Added tests to verify output interface is present in NAT rules - Added ansible_default_ipv4/ipv6 variables to test fixtures For deployments on providers like DigitalOcean where MASQUERADE still fails due to multiple IPs on the same interface, users can enable the existing alternative_ingress_ip option in config.cfg to use explicit SNAT. Testing: - Verified on live servers - All unit tests pass (67/67) - Mutation testing confirms test coverage This fixes VPN connectivity on servers with multiple interfaces while remaining backward compatible with single-interface deployments. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Fix dnscrypt-proxy not listening on VPN service IPs Problem: dnscrypt-proxy on Ubuntu uses systemd socket activation by default, which overrides the configured listen_addresses in dnscrypt-proxy.toml. The socket only listens on 127.0.2.1:53, preventing VPN clients from resolving DNS queries through the configured service IPs. Solution: Disable and mask the dnscrypt-proxy.socket unit to allow dnscrypt-proxy to bind directly to the VPN service IPs specified in its configuration file. This fixes DNS resolution for VPN clients on Ubuntu 20.04+ systems. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Apply Python linting and formatting - Run ruff check --fix to fix linting issues - Run ruff format to ensure consistent formatting - All tests still pass after formatting changes 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Restrict DNS access to VPN clients only Security fix: The firewall rule for DNS was accepting traffic from any source (0.0.0.0/0) to the local DNS resolver. While the service IP is on the loopback interface (which normally isn't routable externally), this could be a security risk if misconfigured. Changed firewall rules to only accept DNS traffic from VPN subnets: - INPUT rule now includes -s {{ subnets }} to restrict source IPs - Applied to both IPv4 and IPv6 rules - Added test to verify DNS is properly restricted This ensures the DNS resolver is only accessible to connected VPN clients, not the entire internet. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Fix dnscrypt-proxy service startup with masked socket Problem: dnscrypt-proxy.service has a dependency on dnscrypt-proxy.socket through the TriggeredBy directive. When we mask the socket before starting the service, systemd fails with "Unit dnscrypt-proxy.socket is masked." Solution: 1. Override the service to remove socket dependency (TriggeredBy=) 2. Reload systemd daemon immediately after override changes 3. Start the service (which now doesn't require the socket) 4. Only then disable and mask the socket This ensures dnscrypt-proxy can bind directly to the configured IPs without socket activation, while preventing the socket from being re-enabled by package updates. Changes: - Added TriggeredBy= override to remove socket dependency - Added explicit daemon reload after service overrides - Moved socket masking to after service start in main.yml - Fixed YAML formatting issues Testing: Deployment now succeeds with dnscrypt-proxy binding to VPN IPs 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Fix dnscrypt-proxy by not masking the socket Problem: Masking dnscrypt-proxy.socket prevents the service from starting because the service has Requires=dnscrypt-proxy.socket dependency. Solution: Simply stop and disable the socket without masking it. This prevents socket activation while allowing the service to start and bind directly to the configured IPs. Changes: - Removed socket masking (just disable it) - Moved socket disabling before service start - Removed invalid systemd directives from override Testing: Confirmed dnscrypt-proxy now listens on VPN service IPs 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Use systemd socket activation properly for dnscrypt-proxy Instead of fighting systemd socket activation, configure it to listen on the correct VPN service IPs. This is more systemd-native and reliable. Changes: - Create socket override to listen on VPN IPs instead of localhost - Clear default listeners and add VPN service IPs - Use empty listen_addresses in dnscrypt-proxy.toml for socket activation - Keep socket enabled and let systemd manage the activation - Add handler for restarting socket when config changes Benefits: - Works WITH systemd instead of against it - Survives package updates better - No dependency conflicts - More reliable service management This approach is cleaner than disabling socket activation entirely and ensures dnscrypt-proxy is accessible to VPN clients on the correct IPs. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Document debugging lessons learned in CLAUDE.md Added comprehensive debugging guidance based on our troubleshooting session: - VPN connectivity troubleshooting order (DNS first!) - systemd socket activation best practices - Common deployment failures and solutions - Time wasters to avoid (lessons learned the hard way) - Multi-homed system considerations - Testing notes for DigitalOcean These additions will help future debugging sessions avoid the same rabbit holes and focus on the most likely issues first. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Fix DNS resolution for VPN clients by enabling route_localnet The issue was that dnscrypt-proxy listens on a special loopback IP (randomly generated in 172.16.0.0/12 range) which wasn't accessible from VPN clients. This fix: 1. Enables net.ipv4.conf.all.route_localnet sysctl to allow routing to loopback IPs from other interfaces 2. Ensures dnscrypt-proxy socket is properly restarted when its configuration changes 3. Adds proper handler flushing after socket configuration updates This allows VPN clients to reach the DNS resolver at the local_service_ip address configured on the loopback interface. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Improve security by using interface-specific route_localnet Instead of enabling route_localnet globally (net.ipv4.conf.all.route_localnet), this change enables it only on the specific interfaces that need it: - WireGuard interface (wg0) for WireGuard VPN clients - Main network interface (eth0/etc) for IPsec VPN clients This minimizes the security impact by restricting loopback routing to only the VPN interfaces, preventing other interfaces from being able to route to loopback addresses. The interface-specific approach provides the same functionality (allowing VPN clients to reach the DNS resolver on the local_service_ip) while reducing the potential attack surface. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Revert to global route_localnet to fix deployment failure The interface-specific route_localnet approach failed because: - WireGuard interface (wg0) doesn't exist until the service starts - We were trying to set the sysctl before the interface was created - This caused deployment failures with "No such file or directory" Reverting to the global setting (net.ipv4.conf.all.route_localnet=1) because: - It always works regardless of interface creation timing - VPN users are trusted (they have our credentials) - Firewall rules still restrict access to only port 53 - The security benefit of interface-specific settings is minimal - The added complexity isn't worth the marginal security improvement This ensures reliable deployments while maintaining the DNS resolution fix. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Fix dnscrypt-proxy socket restart and remove problematic BPF hardening Two important fixes: 1. Fix dnscrypt-proxy socket not restarting with new configuration - The socket wasn't properly restarting when its override config changed - This caused DNS to listen on wrong IP (127.0.2.1 instead of local_service_ip) - Now directly restart the socket when configuration changes - Add explicit daemon reload before restarting 2. Remove BPF JIT hardening that causes deployment errors - The net.core.bpf_jit_enable sysctl isn't available on all kernels - It was causing "Invalid argument" errors during deployment - This was optional security hardening with minimal benefit - Removing it eliminates deployment errors for most users These fixes ensure reliable DNS resolution for VPN clients and clean deployments without error messages. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> * Update CLAUDE.md with comprehensive debugging lessons learned Based on our extensive debugging session, this update adds critical documentation: ## DNS Architecture and Troubleshooting - Explained the local_service_ip design and why it requires route_localnet - Added detailed DNS debugging methodology with exact steps in order - Documented systemd socket activation complexities and common mistakes - Added specific commands to verify DNS is working correctly ## Architectural Decisions - Added new section explaining trade-offs in Algo's design choices - Documented why local_service_ip uses loopback instead of alternatives - Explained iptables-legacy vs iptables-nft backend choice ## Enhanced Debugging Guidance - Expanded troubleshooting with exact commands and expected outputs - Added warnings about configuration changes that need restarts - Documented socket activation override requirements in detail - Added common pitfalls like interface-specific sysctls ## Time Wasters Section - Added new lessons learned from this debugging session - Interface-specific route_localnet (fails before interface exists) - DNAT for loopback addresses (doesn't work) - BPF JIT hardening (causes errors on many kernels) This documentation will help future maintainers avoid the same debugging rabbit holes and understand why things are designed the way they are. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
260 lines
8.3 KiB
Python
260 lines
8.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Cloud-init template validation test.
|
|
|
|
This test validates that the cloud-init template for DigitalOcean deployments
|
|
renders correctly and produces valid YAML that cloud-init can parse.
|
|
|
|
This test helps prevent regressions like issue #14800 where YAML formatting
|
|
issues caused cloud-init to fail completely, resulting in SSH timeouts.
|
|
|
|
Usage:
|
|
python3 tests/test_cloud_init_template.py
|
|
|
|
Or from project root:
|
|
python3 -m pytest tests/test_cloud_init_template.py -v
|
|
"""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import yaml
|
|
|
|
# Add project root to path for imports if needed
|
|
PROJECT_ROOT = Path(__file__).parent.parent
|
|
sys.path.insert(0, str(PROJECT_ROOT))
|
|
|
|
|
|
def create_expected_cloud_init():
|
|
"""
|
|
Create the expected cloud-init content that should be generated
|
|
by our template after the YAML indentation fix.
|
|
"""
|
|
return """#cloud-config
|
|
# CRITICAL: The above line MUST be exactly "#cloud-config" (no space after #)
|
|
# This is required by cloud-init's YAML parser. Adding a space breaks parsing
|
|
# and causes all cloud-init directives to be skipped, resulting in SSH timeouts.
|
|
# See: https://github.com/trailofbits/algo/issues/14800
|
|
output: {all: '| tee -a /var/log/cloud-init-output.log'}
|
|
|
|
package_update: true
|
|
package_upgrade: true
|
|
|
|
packages:
|
|
- sudo
|
|
|
|
users:
|
|
- default
|
|
- name: algo
|
|
homedir: /home/algo
|
|
sudo: ALL=(ALL) NOPASSWD:ALL
|
|
groups: adm,netdev
|
|
shell: /bin/bash
|
|
lock_passwd: true
|
|
ssh_authorized_keys:
|
|
- "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDTest algo-test"
|
|
|
|
write_files:
|
|
- path: /etc/ssh/sshd_config
|
|
content: |
|
|
Port 4160
|
|
AllowGroups algo
|
|
PermitRootLogin no
|
|
PasswordAuthentication no
|
|
ChallengeResponseAuthentication no
|
|
UsePAM yes
|
|
X11Forwarding yes
|
|
PrintMotd no
|
|
AcceptEnv LANG LC_*
|
|
Subsystem sftp /usr/lib/openssh/sftp-server
|
|
|
|
runcmd:
|
|
- set -x
|
|
- ufw --force reset
|
|
- sudo apt-get remove -y --purge sshguard || true
|
|
- systemctl restart sshd.service
|
|
"""
|
|
|
|
|
|
class TestCloudInitTemplate:
|
|
"""Test class for cloud-init template validation."""
|
|
|
|
def test_yaml_validity(self):
|
|
"""Test that the expected cloud-init YAML is valid."""
|
|
print("🧪 Testing YAML validity...")
|
|
|
|
cloud_init_content = create_expected_cloud_init()
|
|
|
|
try:
|
|
parsed = yaml.safe_load(cloud_init_content)
|
|
print("✅ YAML parsing successful")
|
|
assert parsed is not None, "YAML should parse to a non-None value"
|
|
return parsed
|
|
except yaml.YAMLError as e:
|
|
print(f"❌ YAML parsing failed: {e}")
|
|
assert False, f"YAML parsing failed: {e}"
|
|
|
|
def test_required_sections(self):
|
|
"""Test that all required cloud-init sections are present."""
|
|
print("🧪 Testing required sections...")
|
|
|
|
parsed = self.test_yaml_validity()
|
|
|
|
required_sections = ["package_update", "package_upgrade", "packages", "users", "write_files", "runcmd"]
|
|
|
|
missing = [section for section in required_sections if section not in parsed]
|
|
assert not missing, f"Missing required sections: {missing}"
|
|
|
|
print("✅ All required sections present")
|
|
|
|
def test_ssh_configuration(self):
|
|
"""Test that SSH configuration is correct."""
|
|
print("🧪 Testing SSH configuration...")
|
|
|
|
parsed = self.test_yaml_validity()
|
|
|
|
write_files = parsed.get("write_files", [])
|
|
assert write_files, "write_files section should be present"
|
|
|
|
# Find sshd_config file
|
|
sshd_config = None
|
|
for file_entry in write_files:
|
|
if file_entry.get("path") == "/etc/ssh/sshd_config":
|
|
sshd_config = file_entry
|
|
break
|
|
|
|
assert sshd_config, "sshd_config file should be in write_files"
|
|
|
|
content = sshd_config.get("content", "")
|
|
assert content, "sshd_config should have content"
|
|
|
|
# Check required SSH configurations
|
|
required_configs = ["Port 4160", "AllowGroups algo", "PermitRootLogin no", "PasswordAuthentication no"]
|
|
|
|
missing = [config for config in required_configs if config not in content]
|
|
assert not missing, f"Missing SSH configurations: {missing}"
|
|
|
|
# Verify proper formatting - first line should be Port directive
|
|
lines = content.strip().split("\n")
|
|
assert lines[0].strip() == "Port 4160", f"First line should be 'Port 4160', got: {repr(lines[0])}"
|
|
|
|
print("✅ SSH configuration correct")
|
|
|
|
def test_user_creation(self):
|
|
"""Test that algo user will be created correctly."""
|
|
print("🧪 Testing user creation...")
|
|
|
|
parsed = self.test_yaml_validity()
|
|
|
|
users = parsed.get("users", [])
|
|
assert users, "users section should be present"
|
|
|
|
# Find algo user
|
|
algo_user = None
|
|
for user in users:
|
|
if isinstance(user, dict) and user.get("name") == "algo":
|
|
algo_user = user
|
|
break
|
|
|
|
assert algo_user, "algo user should be defined"
|
|
|
|
# Check required user properties
|
|
required_props = ["sudo", "groups", "shell", "ssh_authorized_keys"]
|
|
missing = [prop for prop in required_props if prop not in algo_user]
|
|
assert not missing, f"algo user missing properties: {missing}"
|
|
|
|
# Verify sudo configuration
|
|
sudo_config = algo_user.get("sudo", "")
|
|
assert "NOPASSWD:ALL" in sudo_config, f"sudo config should allow passwordless access: {sudo_config}"
|
|
|
|
print("✅ User creation correct")
|
|
|
|
def test_runcmd_section(self):
|
|
"""Test that runcmd section will restart SSH correctly."""
|
|
print("🧪 Testing runcmd section...")
|
|
|
|
parsed = self.test_yaml_validity()
|
|
|
|
runcmd = parsed.get("runcmd", [])
|
|
assert runcmd, "runcmd section should be present"
|
|
|
|
# Check for SSH restart command
|
|
ssh_restart_found = False
|
|
for cmd in runcmd:
|
|
if "systemctl restart sshd" in str(cmd):
|
|
ssh_restart_found = True
|
|
break
|
|
|
|
assert ssh_restart_found, f"SSH restart command not found in runcmd: {runcmd}"
|
|
|
|
print("✅ runcmd section correct")
|
|
|
|
def test_indentation_consistency(self):
|
|
"""Test that sshd_config content has consistent indentation."""
|
|
print("🧪 Testing indentation consistency...")
|
|
|
|
cloud_init_content = create_expected_cloud_init()
|
|
|
|
# Extract the sshd_config content lines
|
|
lines = cloud_init_content.split("\n")
|
|
in_sshd_content = False
|
|
sshd_lines = []
|
|
|
|
for line in lines:
|
|
if "content: |" in line:
|
|
in_sshd_content = True
|
|
continue
|
|
elif in_sshd_content:
|
|
if line.strip() == "" and len(sshd_lines) > 0:
|
|
break
|
|
if line.startswith("runcmd:"):
|
|
break
|
|
sshd_lines.append(line)
|
|
|
|
assert sshd_lines, "Should be able to extract sshd_config content"
|
|
|
|
# Check that all non-empty lines have consistent 6-space indentation
|
|
non_empty_lines = [line for line in sshd_lines if line.strip()]
|
|
assert non_empty_lines, "sshd_config should have content"
|
|
|
|
for line in non_empty_lines:
|
|
# Each line should start with exactly 6 spaces
|
|
assert line.startswith(" ") and not line.startswith(" "), (
|
|
f"Line should have exactly 6 spaces indentation: {repr(line)}"
|
|
)
|
|
|
|
print("✅ Indentation is consistent")
|
|
|
|
|
|
def run_tests():
|
|
"""Run all tests manually (for non-pytest usage)."""
|
|
print("🚀 Cloud-init template validation tests")
|
|
print("=" * 50)
|
|
|
|
test_instance = TestCloudInitTemplate()
|
|
|
|
try:
|
|
test_instance.test_yaml_validity()
|
|
test_instance.test_required_sections()
|
|
test_instance.test_ssh_configuration()
|
|
test_instance.test_user_creation()
|
|
test_instance.test_runcmd_section()
|
|
test_instance.test_indentation_consistency()
|
|
|
|
print("=" * 50)
|
|
print("🎉 ALL TESTS PASSED!")
|
|
print("✅ Cloud-init template is working correctly")
|
|
print("✅ DigitalOcean deployment should succeed")
|
|
return True
|
|
|
|
except AssertionError as e:
|
|
print(f"❌ Test failed: {e}")
|
|
return False
|
|
except Exception as e:
|
|
print(f"❌ Unexpected error: {e}")
|
|
return False
|
|
|
|
|
|
if __name__ == "__main__":
|
|
success = run_tests()
|
|
sys.exit(0 if success else 1)
|