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
+56 -1
View File
@@ -459,12 +459,38 @@ class WireGuardManager(BaseServiceManager):
Unlike add_peer(), allows a subnet CIDR as AllowedIPs (whole remote VPN range).
The endpoint is expected to already include the port (e.g. '1.2.3.4:51820').
"""
import ipaddress
import ipaddress, re as _re
# Validate public_key strictly — empty/garbled keys later cause remove_peer("")
# to wipe ALL peer blocks via substring match.
if not isinstance(public_key, str) or not _re.match(r'^[A-Za-z0-9+/]{43}=$', public_key.strip()):
logger.error(f'add_cell_peer: invalid public_key')
return False
# Validate name — reject newlines/brackets that could inject config blocks
if not isinstance(name, str) or not _re.match(r'^[A-Za-z0-9_. -]{1,64}$', name):
logger.error(f'add_cell_peer: invalid name {name!r}')
return False
# Validate endpoint as host:port — reject newlines and out-of-range ports
if endpoint:
if not isinstance(endpoint, str) or not _re.match(r'^[A-Za-z0-9._-]+:\d{1,5}$', endpoint):
logger.error(f'add_cell_peer: invalid endpoint {endpoint!r}')
return False
try:
_port = int(endpoint.rsplit(':', 1)[1])
if not (1 <= _port <= 65535):
logger.error(f'add_cell_peer: endpoint port out of range: {endpoint!r}')
return False
except (ValueError, IndexError):
logger.error(f'add_cell_peer: invalid endpoint port: {endpoint!r}')
return False
try:
ipaddress.ip_network(vpn_subnet, strict=False)
except ValueError as e:
logger.error(f'add_cell_peer: invalid vpn_subnet {vpn_subnet!r}: {e}')
return False
# Reject any whitespace/newlines in vpn_subnet that ip_network() may have tolerated
if any(c.isspace() for c in vpn_subnet):
logger.error(f'add_cell_peer: vpn_subnet contains whitespace: {vpn_subnet!r}')
return False
try:
content = self._read_config()
peer_block = (
@@ -531,6 +557,16 @@ class WireGuardManager(BaseServiceManager):
def update_peer_ip(self, public_key: str, new_ip: str) -> bool:
"""Update AllowedIPs for the peer with the given public key."""
import ipaddress
# Reject whitespace/newlines that ip_network() may tolerate but would inject config
if not isinstance(new_ip, str) or any(c.isspace() for c in new_ip):
logger.error(f'update_peer_ip: invalid new_ip {new_ip!r}')
return False
try:
ipaddress.ip_network(new_ip, strict=False)
except ValueError as e:
logger.error(f'update_peer_ip: invalid new_ip {new_ip!r}: {e}')
return False
content = self._read_config()
if f'PublicKey = {public_key}' not in content:
return False
@@ -737,6 +773,25 @@ class WireGuardManager(BaseServiceManager):
status = self.get_status()
running = status.get('running', False)
return {'success': running, 'reachable': running, 'status': status.get('status')}
# Validate target_ip — reject argv injection (any string starting with '-' would
# be parsed by ping as a flag) and any non-IP input.
import ipaddress
if not isinstance(peer_ip, str) or peer_ip.startswith('-'):
return {
'peer_ip': peer_ip,
'ping_success': False,
'ping_output': '',
'ping_error': 'invalid peer_ip',
}
try:
ipaddress.ip_address(peer_ip)
except ValueError:
return {
'peer_ip': peer_ip,
'ping_success': False,
'ping_output': '',
'ping_error': 'invalid peer_ip',
}
try:
result = subprocess.run(
['ping', '-c', '1', '-W', '2', peer_ip],