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
+43 -8
View File
@@ -114,19 +114,32 @@ def _delete_rule(chain: str, rule_args: List[str]) -> None:
# ---------------------------------------------------------------------------
def _peer_comment(peer_ip: str) -> str:
return f'pic-peer-{peer_ip.replace(".", "-")}'
# SECURITY: append a non-numeric, non-dash suffix so peer comments cannot
# be substrings of one another. Without this, the comment for 10.0.0.1
# ('pic-peer-10-0-0-1') is a prefix of 10.0.0.10..19 and a naive
# substring match would delete unrelated peers' rules.
return f'pic-peer-{peer_ip.replace(".", "-")}/32'
def clear_peer_rules(peer_ip: str) -> None:
"""Remove all FORWARD rules tagged with this peer's IP via iptables-save/restore."""
comment = _peer_comment(peer_ip)
# SECURITY: match the comment as a complete --comment token, not a
# substring. iptables-save renders comments as `--comment "<value>"` (or
# occasionally without quotes), so we anchor on the surrounding quotes /
# whitespace. Even with the unique /32 suffix in _peer_comment, we keep
# exact-token matching so a future change to the comment format cannot
# silently re-introduce the substring-deletion bug.
comment_re = re.compile(
rf'--comment\s+["\']?{re.escape(comment)}["\']?(\s|$)'
)
try:
# Dump rules, strip matching lines, restore — atomic and order-stable
save = _wg_exec(['iptables-save'])
if save.returncode != 0:
return
lines = save.stdout.splitlines()
filtered = [l for l in lines if comment not in l]
filtered = [l for l in lines if not comment_re.search(l)]
if len(filtered) == len(lines):
return # nothing to remove
restore_input = '\n'.join(filtered) + '\n'
@@ -243,11 +256,15 @@ def _build_acl_block(blocked_peers_by_service: Dict[str, List[str]],
def generate_corefile(peers: List[Dict[str, Any]], corefile_path: str = COREFILE_PATH,
domain: str = 'cell') -> bool:
domain: str = 'cell',
cell_links: Optional[List[Dict[str, Any]]] = None) -> bool:
"""
Rewrite the CoreDNS Corefile with per-peer ACL rules and reload plugin.
The file is written to corefile_path (API-side path mapped into CoreDNS container).
domain: the configured cell domain (e.g. 'cell', 'dev') — must match zone file names.
cell_links: optional list of cell-to-cell DNS forwarding entries, each a dict with
'domain' and 'dns_ip' keys (same shape as CellLinkManager.list_connections()).
When non-empty, a forwarding stanza is appended for each entry.
"""
try:
# Collect which peers block which services
@@ -275,8 +292,25 @@ def generate_corefile(peers: List[Dict[str, Any]], corefile_path: str = COREFILE
health
}}
{primary_zone_block}
"""
{primary_zone_block}"""
# Append cell-to-cell DNS forwarding stanzas if provided
if cell_links:
for link in cell_links:
link_domain = link.get('domain', '')
link_dns_ip = link.get('dns_ip', '')
if not link_domain or not link_dns_ip:
continue
corefile += (
f'\n{link_domain} {{\n'
f' forward . {link_dns_ip}\n'
f' cache\n'
f' log\n'
f'}}\n'
)
else:
corefile += '\n'
# local.{domain} block intentionally omitted: /data/local.zone does not exist
# and CoreDNS logs errors on every reload for a missing zone file.
os.makedirs(os.path.dirname(corefile_path), exist_ok=True)
@@ -309,9 +343,10 @@ def reload_coredns() -> bool:
def apply_all_dns_rules(peers: List[Dict[str, Any]], corefile_path: str = COREFILE_PATH,
domain: str = 'cell') -> bool:
"""Regenerate Corefile and reload CoreDNS."""
ok = generate_corefile(peers, corefile_path, domain)
domain: str = 'cell',
cell_links: Optional[List[Dict[str, Any]]] = None) -> bool:
"""Regenerate Corefile (including any cell-to-cell forwarding stanzas) and reload CoreDNS."""
ok = generate_corefile(peers, corefile_path, domain, cell_links)
if ok:
reload_coredns()
return ok