fix: full security audit remediation — P0/P1/P2/P3 fixes + 1020 passing tests

P0 — Broken functionality:
- Fix 12+ endpoints with wrong manager method signatures (email/calendar/file/routing)
- Fix email_manager.delete_email_user() missing domain arg
- Fix cell-link DNS forwarding wiped on every peer change (generate_corefile now
  accepts cell_links param; add/remove_cell_dns_forward no longer clobber the file)
- Fix Flask SECRET_KEY regenerating on every restart (persisted to DATA_DIR)
- Fix _next_peer_ip exhaustion returning 500 instead of 409
- Fix ConfigManager Caddyfile path (/app/config-caddy/)
- Fix UI double-add and wrong-key peer bugs in Peers.jsx / WireGuard.jsx
- Remove hardcoded credentials from Dashboard.jsx

P1 — Security:
- CSRF token validation on all POST/PUT/DELETE/PATCH to /api/* (double-submit pattern)
- enforce_auth: 503 only when users file readable but empty; never bypass on IOError
- WireGuard add_cell_peer: validate pubkey, name, endpoint against strict regexes
- DNS add_cell_dns_forward: validate IP and domain; reject injection chars
- DNS zone write: realpath containment + record content validation
- iptables comment /32 suffix prevents substring match deleting wrong peer rules
- is_local_request() trusts only loopback + 172.16.0.0/12 (Docker bridge)
- POST /api/containers: volume allow-list prevents arbitrary host mounts
- file_manager: bcrypt ($2b→$2y) for WebDAV; realpath containment in delete_user
- email/calendar: stop persisting plaintext passwords in user records
- routing_manager: validate IPs, networks, and interface names
- peer_registry: write peers.json at mode 0o600
- vault_manager: Fernet key file at mode 0o600
- CORS: lock down to explicit origin list
- domain/cell_name validation: reject newline, brace, semicolon injection chars

P2 — Architecture:
- Peer add: rollback registry entry if firewall rules fail post-add
- restart_service(): base class now calls _restart_container(); email and calendar
  managers call cell-mail / cell-radicale respectively
- email/calendar managers sync user list (no passwords) to cell_config.json
- Pending-restart flag cleared only after helper subprocess exits with code 0
- docker-compose.yml: add config-caddy volume to API container

P3 — Tests (854 → 1020):
- Fill test_email_endpoints.py, test_calendar_endpoints.py,
  test_network_endpoints.py, test_routing_endpoints.py
- New: test_peer_management_update.py, test_peer_management_edge_cases.py,
  test_input_validation.py, test_enforce_auth_configured.py,
  test_cell_link_dns.py, test_logs_endpoints.py, test_cells_endpoints.py,
  test_is_local_request_per_endpoint.py, test_caddy_routing.py
- E2E conftest: skip WireGuard suite when wg-quick absent
- Update existing tests to match fixed signatures and comment formats

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-27 11:30:21 -04:00
parent 0c12e3fc97
commit a43f9fbf0d
47 changed files with 4578 additions and 579 deletions
+86 -39
View File
@@ -29,8 +29,28 @@ class NetworkManager(BaseServiceManager):
def update_dns_zone(self, zone_name: str, records: List[Dict]) -> bool:
"""Update DNS zone file with new records"""
# Validate zone_name — must be a safe DNS label, no path traversal
if not isinstance(zone_name, str) or not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9.-]{0,252}$', zone_name):
logger.error(f"update_dns_zone: invalid zone_name {zone_name!r}")
return False
try:
zone_file = os.path.join(self.dns_zones_dir, f'{zone_name}.zone')
# Containment check: resolved zone_file must be inside dns_zones_dir
real_dir = os.path.realpath(self.dns_zones_dir)
real_zone = os.path.realpath(zone_file)
if not (real_zone == real_dir or real_zone.startswith(real_dir + os.sep)):
logger.error(f"update_dns_zone: path traversal attempt for zone {zone_name!r}")
return False
# Validate every record's name and value to prevent zone-file injection
for rec in records:
rname = rec.get('name', '')
rvalue = rec.get('value', '')
if rname and not re.match(r'^[a-zA-Z0-9_.*-]{1,253}$', str(rname)):
logger.error(f"update_dns_zone: invalid record name {rname!r}")
return False
if rvalue and not re.match(r'^[a-zA-Z0-9._: -]{1,512}$', str(rvalue)):
logger.error(f"update_dns_zone: invalid record value {rvalue!r}")
return False
# Create zone file content
content = self._generate_zone_content(zone_name, records)
@@ -84,6 +104,16 @@ class NetworkManager(BaseServiceManager):
def add_dns_record(self, zone: str, name: str, record_type: str, value: str, ttl: int = 3600) -> bool:
"""Add a DNS record to a zone"""
# Validate zone, name, and value to prevent injection / path traversal
if not isinstance(zone, str) or not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9.-]{0,252}$', zone):
logger.error(f"add_dns_record: invalid zone {zone!r}")
return False
if not isinstance(name, str) or not re.match(r'^[a-zA-Z0-9_.*-]{1,253}$', name):
logger.error(f"add_dns_record: invalid name {name!r}")
return False
if not isinstance(value, str) or not re.match(r'^[a-zA-Z0-9._: -]{1,512}$', value):
logger.error(f"add_dns_record: invalid value {value!r}")
return False
try:
# Load existing records
records = self._load_dns_records(zone)
@@ -505,58 +535,75 @@ class NetworkManager(BaseServiceManager):
warnings.append(f"cell_name DNS update failed: {e}")
return {'restarted': restarted, 'warnings': warnings}
def _load_cell_links(self) -> List[Dict[str, Any]]:
"""Load cell_links.json from the data directory (written by CellLinkManager)."""
links_file = os.path.join(self.data_dir, 'cell_links.json')
if os.path.exists(links_file):
try:
with open(links_file) as f:
return json.load(f)
except Exception:
return []
return []
def add_cell_dns_forward(self, domain: str, dns_ip: str) -> Dict[str, Any]:
"""Append a CoreDNS forwarding block for a remote cell's domain."""
"""Register a CoreDNS forwarding entry for a remote cell's domain.
Validates inputs, then rebuilds the entire Corefile via
firewall_manager.apply_all_dns_rules() so that no existing stanza is
silently wiped. Does NOT write the Corefile directly.
"""
import ipaddress
import firewall_manager as fm
restarted = []
warnings = []
# Validate dns_ip — newlines/garbage would inject arbitrary CoreDNS directives
try:
corefile = os.path.join(self.config_dir, 'dns', 'Corefile')
if not os.path.exists(corefile):
warnings.append('Corefile not found')
return {'restarted': restarted, 'warnings': warnings}
with open(corefile) as f:
content = f.read()
marker = f'# cell:{domain}'
if marker in content:
return {'restarted': restarted, 'warnings': warnings} # already present
forward_block = (
f'\n{marker}\n'
f'{domain} {{\n'
f' forward . {dns_ip}\n'
f' log\n'
f'}}\n'
)
with open(corefile, 'a') as f:
f.write(forward_block)
self._reload_dns_service()
ipaddress.ip_address(dns_ip)
except (ValueError, TypeError):
warnings.append(f'add_cell_dns_forward: invalid dns_ip {dns_ip!r}')
return {'restarted': restarted, 'warnings': warnings}
# Validate domain — reject newlines, braces, spaces, and any non-DNS chars
if (not isinstance(domain, str)
or not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9.-]{0,252}$', domain)
or any(c in domain for c in ('\n', '\r', '{', '}', ' ', '\t'))):
warnings.append(f'add_cell_dns_forward: invalid domain {domain!r}')
return {'restarted': restarted, 'warnings': warnings}
try:
# Build the full forwarding list: existing links + new entry (deduped by domain)
existing_links = self._load_cell_links()
# The new entry may not yet be in cell_links.json (CellLinkManager saves after
# calling us), so we merge it in here.
merged = [l for l in existing_links if l.get('domain') != domain]
merged.append({'domain': domain, 'dns_ip': dns_ip})
corefile_path = os.path.join(self.config_dir, 'dns', 'Corefile')
# Peers list is empty here; the full peer list is used by the periodic
# apply_all_dns_rules() call from app.py. We only need to persist the
# forwarding stanza without disturbing whatever peer ACLs are in the file.
fm.apply_all_dns_rules([], corefile_path=corefile_path, cell_links=merged)
restarted.append('cell-dns (reloaded)')
except Exception as e:
warnings.append(f'add_cell_dns_forward failed: {e}')
return {'restarted': restarted, 'warnings': warnings}
def remove_cell_dns_forward(self, domain: str) -> Dict[str, Any]:
"""Remove a CoreDNS forwarding block for a remote cell's domain."""
import re
"""Unregister a CoreDNS forwarding entry for a remote cell's domain.
Rebuilds the entire Corefile via firewall_manager.apply_all_dns_rules()
with the named domain excluded. Does NOT write the Corefile directly.
"""
import firewall_manager as fm
restarted = []
warnings = []
try:
corefile = os.path.join(self.config_dir, 'dns', 'Corefile')
if not os.path.exists(corefile):
return {'restarted': restarted, 'warnings': warnings}
with open(corefile) as f:
content = f.read()
marker = f'# cell:{domain}'
if marker not in content:
return {'restarted': restarted, 'warnings': warnings}
new_content = re.sub(
rf'\n# cell:{re.escape(domain)}\n{re.escape(domain)}\s*\{{[^}}]*\}}\n',
'',
content,
flags=re.DOTALL,
)
with open(corefile, 'w') as f:
f.write(new_content)
self._reload_dns_service()
existing_links = self._load_cell_links()
# Exclude the domain being removed; CellLinkManager will also remove it
# from cell_links.json after this call returns.
remaining = [l for l in existing_links if l.get('domain') != domain]
corefile_path = os.path.join(self.config_dir, 'dns', 'Corefile')
fm.apply_all_dns_rules([], corefile_path=corefile_path, cell_links=remaining)
restarted.append('cell-dns (reloaded)')
except Exception as e:
warnings.append(f'remove_cell_dns_forward failed: {e}')