hop3-rootd 0.5.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hop3_rootd-0.5.0/.gitignore +38 -0
- hop3_rootd-0.5.0/Makefile +39 -0
- hop3_rootd-0.5.0/PKG-INFO +63 -0
- hop3_rootd-0.5.0/README.md +42 -0
- hop3_rootd-0.5.0/pyproject.toml +44 -0
- hop3_rootd-0.5.0/src/hop3_rootd/__init__.py +17 -0
- hop3_rootd-0.5.0/src/hop3_rootd/__main__.py +220 -0
- hop3_rootd-0.5.0/src/hop3_rootd/audit.py +219 -0
- hop3_rootd-0.5.0/src/hop3_rootd/exec.py +196 -0
- hop3_rootd-0.5.0/src/hop3_rootd/nft/__init__.py +9 -0
- hop3_rootd-0.5.0/src/hop3_rootd/nft/rule.py +224 -0
- hop3_rootd-0.5.0/src/hop3_rootd/nft/table.py +138 -0
- hop3_rootd-0.5.0/src/hop3_rootd/ops/__init__.py +33 -0
- hop3_rootd-0.5.0/src/hop3_rootd/ops/_base.py +167 -0
- hop3_rootd-0.5.0/src/hop3_rootd/ops/daemon.py +57 -0
- hop3_rootd-0.5.0/src/hop3_rootd/ops/firewall.py +183 -0
- hop3_rootd-0.5.0/src/hop3_rootd/ops/nginx.py +144 -0
- hop3_rootd-0.5.0/src/hop3_rootd/protocol.py +252 -0
- hop3_rootd-0.5.0/src/hop3_rootd/reconcile.py +169 -0
- hop3_rootd-0.5.0/src/hop3_rootd/server.py +509 -0
- hop3_rootd-0.5.0/src/hop3_rootd/state.py +218 -0
- hop3_rootd-0.5.0/src/hop3_rootd/validation.py +264 -0
- hop3_rootd-0.5.0/tests/__init__.py +0 -0
- hop3_rootd-0.5.0/tests/a_unit/__init__.py +0 -0
- hop3_rootd-0.5.0/tests/a_unit/test_audit.py +293 -0
- hop3_rootd-0.5.0/tests/a_unit/test_exec.py +243 -0
- hop3_rootd-0.5.0/tests/a_unit/test_main.py +83 -0
- hop3_rootd-0.5.0/tests/a_unit/test_nft_rule.py +274 -0
- hop3_rootd-0.5.0/tests/a_unit/test_nft_table.py +170 -0
- hop3_rootd-0.5.0/tests/a_unit/test_ops_daemon.py +80 -0
- hop3_rootd-0.5.0/tests/a_unit/test_ops_firewall.py +315 -0
- hop3_rootd-0.5.0/tests/a_unit/test_ops_nginx.py +183 -0
- hop3_rootd-0.5.0/tests/a_unit/test_protocol.py +245 -0
- hop3_rootd-0.5.0/tests/a_unit/test_reconcile.py +224 -0
- hop3_rootd-0.5.0/tests/a_unit/test_server_dispatch.py +313 -0
- hop3_rootd-0.5.0/tests/a_unit/test_state.py +226 -0
- hop3_rootd-0.5.0/tests/a_unit/test_validation.py +440 -0
- hop3_rootd-0.5.0/tests/b_integration/__init__.py +0 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Python-generated files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[oc]
|
|
4
|
+
dist/
|
|
5
|
+
wheels/
|
|
6
|
+
*.egg-info
|
|
7
|
+
.coverage
|
|
8
|
+
|
|
9
|
+
# Misc cruft
|
|
10
|
+
.DS_Store
|
|
11
|
+
.idea
|
|
12
|
+
.git-old
|
|
13
|
+
|
|
14
|
+
# Virtual environments
|
|
15
|
+
.venv
|
|
16
|
+
.python-version
|
|
17
|
+
|
|
18
|
+
# Local / secrets / tmp
|
|
19
|
+
.envrc
|
|
20
|
+
/sandbox/
|
|
21
|
+
/OLD/
|
|
22
|
+
/data/
|
|
23
|
+
/demos/logs/
|
|
24
|
+
/demos/sandbox/
|
|
25
|
+
/demos/.demo-results.db
|
|
26
|
+
/logs
|
|
27
|
+
/apps/logs/
|
|
28
|
+
/test-logs/
|
|
29
|
+
test-logs/
|
|
30
|
+
/apps/internal-apps
|
|
31
|
+
/apps/sandbox/
|
|
32
|
+
|
|
33
|
+
# Demo-private hop3 CLI config (hermetic XDG_CONFIG_HOME)
|
|
34
|
+
demos/.cli-home/
|
|
35
|
+
|
|
36
|
+
# hop3-testlab cloud config — holds secrets (token / ssh key); keep the .example
|
|
37
|
+
/config.toml
|
|
38
|
+
/packages/hop3-testlab/config.toml
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
PKG:=hop3_rootd
|
|
2
|
+
|
|
3
|
+
## Default: run lint and test
|
|
4
|
+
all: lint test
|
|
5
|
+
|
|
6
|
+
#
|
|
7
|
+
# testing & checking
|
|
8
|
+
#
|
|
9
|
+
|
|
10
|
+
## Run unit tests (no privileges needed)
|
|
11
|
+
test:
|
|
12
|
+
@echo "--> Running Python unit tests"
|
|
13
|
+
pytest -x -p no:randomly tests/a_unit
|
|
14
|
+
@echo ""
|
|
15
|
+
|
|
16
|
+
## Run integration tests (requires root + nftables)
|
|
17
|
+
test-integration:
|
|
18
|
+
@echo "--> Running integration tests (requires root)"
|
|
19
|
+
pytest -x tests/b_integration
|
|
20
|
+
@echo ""
|
|
21
|
+
|
|
22
|
+
test-with-coverage:
|
|
23
|
+
@echo "--> Running tests with coverage"
|
|
24
|
+
pytest --cov $(PKG) tests/a_unit
|
|
25
|
+
@echo ""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
## Lint / check typing
|
|
29
|
+
lint:
|
|
30
|
+
ruff check
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
## Format
|
|
34
|
+
format:
|
|
35
|
+
ruff format
|
|
36
|
+
ruff check --fix
|
|
37
|
+
ruff format
|
|
38
|
+
|
|
39
|
+
.PHONY: all test test-integration test-with-coverage lint format
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hop3-rootd
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Privileged operations agent for Hop3 (kernel-boundary executor)
|
|
5
|
+
Author-email: Abilian SAS <contact@abilian.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Environment :: No Input/Output (Daemon)
|
|
9
|
+
Classifier: Intended Audience :: System Administrators
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: System :: Networking :: Firewalls
|
|
18
|
+
Classifier: Topic :: System :: Systems Administration
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# hop3-rootd
|
|
23
|
+
|
|
24
|
+
Privileged-operations agent for Hop3. Runs as root; exposes a narrow control-plane API to `hop3-server` (running unprivileged as the `hop3` user) over a Unix domain socket.
|
|
25
|
+
|
|
26
|
+
See `notes/adrs/041-privileged-operations-agent.md` for the design rationale and `notes/adrs/040-network-firewall-and-port-exposure.md` for the firewall integration that motivated v1's op set.
|
|
27
|
+
|
|
28
|
+
## What this is
|
|
29
|
+
|
|
30
|
+
`hop3-rootd` is the kernel-boundary executor for Hop3's runtime privileged actions. The unprivileged `hop3-server` reaches it via a Unix socket; rootd validates each request structurally, applies the privileged action (nftables mutation, nginx reload, etc.), and returns a typed result.
|
|
31
|
+
|
|
32
|
+
In v1 the operations are:
|
|
33
|
+
|
|
34
|
+
- `firewall.add_rule`, `firewall.remove_rule`, `firewall.list_rules` — manage rules in a dedicated `inet hop3` nftables table.
|
|
35
|
+
- `nginx.reload`, `nginx.validate_config` — wrap the privileged nginx commands previously granted to `hop3-server` via `/etc/sudoers.d/hop3` (now retired).
|
|
36
|
+
- `daemon.health`, `daemon.handshake` — introspection.
|
|
37
|
+
|
|
38
|
+
## What this is not
|
|
39
|
+
|
|
40
|
+
- A policy enforcement layer. SO_PEERCRED admits the `hop3` user; structural validation rejects malformed requests. There is no per-op authorization, no policy file. Operator-level "did you mean this?" prompts live in `hop3 deploy`, not in rootd.
|
|
41
|
+
- A general-purpose privileged-shell daemon. Rootd never accepts shell strings; every operation is a typed intent with a fixed argument schema.
|
|
42
|
+
|
|
43
|
+
## Deployment
|
|
44
|
+
|
|
45
|
+
`hop3-rootd` ships as a stdlib-only Python package and is installed by `hop3-installer` alongside `hop3-server`. It runs as a hardened systemd unit (full ProtectX suite, `CapabilityBoundingSet=CAP_NET_ADMIN`, syscall filter, resource limits). The socket is at `/run/hop3-rootd/socket`, mode `0660`, group `hop3`.
|
|
46
|
+
|
|
47
|
+
## Development
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
# Run unit tests (no privileges needed)
|
|
51
|
+
pytest tests/a_unit/ -v
|
|
52
|
+
|
|
53
|
+
# Run integration tests (requires root + nftables)
|
|
54
|
+
sudo pytest tests/b_integration/ -v
|
|
55
|
+
|
|
56
|
+
# Lint
|
|
57
|
+
ruff check src tests
|
|
58
|
+
ruff format src tests
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## License
|
|
62
|
+
|
|
63
|
+
Apache-2.0 — Copyright (c) 2026, Abilian SAS
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# hop3-rootd
|
|
2
|
+
|
|
3
|
+
Privileged-operations agent for Hop3. Runs as root; exposes a narrow control-plane API to `hop3-server` (running unprivileged as the `hop3` user) over a Unix domain socket.
|
|
4
|
+
|
|
5
|
+
See `notes/adrs/041-privileged-operations-agent.md` for the design rationale and `notes/adrs/040-network-firewall-and-port-exposure.md` for the firewall integration that motivated v1's op set.
|
|
6
|
+
|
|
7
|
+
## What this is
|
|
8
|
+
|
|
9
|
+
`hop3-rootd` is the kernel-boundary executor for Hop3's runtime privileged actions. The unprivileged `hop3-server` reaches it via a Unix socket; rootd validates each request structurally, applies the privileged action (nftables mutation, nginx reload, etc.), and returns a typed result.
|
|
10
|
+
|
|
11
|
+
In v1 the operations are:
|
|
12
|
+
|
|
13
|
+
- `firewall.add_rule`, `firewall.remove_rule`, `firewall.list_rules` — manage rules in a dedicated `inet hop3` nftables table.
|
|
14
|
+
- `nginx.reload`, `nginx.validate_config` — wrap the privileged nginx commands previously granted to `hop3-server` via `/etc/sudoers.d/hop3` (now retired).
|
|
15
|
+
- `daemon.health`, `daemon.handshake` — introspection.
|
|
16
|
+
|
|
17
|
+
## What this is not
|
|
18
|
+
|
|
19
|
+
- A policy enforcement layer. SO_PEERCRED admits the `hop3` user; structural validation rejects malformed requests. There is no per-op authorization, no policy file. Operator-level "did you mean this?" prompts live in `hop3 deploy`, not in rootd.
|
|
20
|
+
- A general-purpose privileged-shell daemon. Rootd never accepts shell strings; every operation is a typed intent with a fixed argument schema.
|
|
21
|
+
|
|
22
|
+
## Deployment
|
|
23
|
+
|
|
24
|
+
`hop3-rootd` ships as a stdlib-only Python package and is installed by `hop3-installer` alongside `hop3-server`. It runs as a hardened systemd unit (full ProtectX suite, `CapabilityBoundingSet=CAP_NET_ADMIN`, syscall filter, resource limits). The socket is at `/run/hop3-rootd/socket`, mode `0660`, group `hop3`.
|
|
25
|
+
|
|
26
|
+
## Development
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# Run unit tests (no privileges needed)
|
|
30
|
+
pytest tests/a_unit/ -v
|
|
31
|
+
|
|
32
|
+
# Run integration tests (requires root + nftables)
|
|
33
|
+
sudo pytest tests/b_integration/ -v
|
|
34
|
+
|
|
35
|
+
# Lint
|
|
36
|
+
ruff check src tests
|
|
37
|
+
ruff format src tests
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## License
|
|
41
|
+
|
|
42
|
+
Apache-2.0 — Copyright (c) 2026, Abilian SAS
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Copyright (c) 2026, Abilian SAS
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
[project]
|
|
5
|
+
name = "hop3-rootd"
|
|
6
|
+
version = "0.5.0"
|
|
7
|
+
description = "Privileged operations agent for Hop3 (kernel-boundary executor)"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
license = "Apache-2.0"
|
|
10
|
+
authors = [{ name = "Abilian SAS", email = "contact@abilian.com" }]
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
"Environment :: No Input/Output (Daemon)",
|
|
15
|
+
"Intended Audience :: System Administrators",
|
|
16
|
+
"License :: OSI Approved :: Apache Software License",
|
|
17
|
+
"Operating System :: POSIX :: Linux",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Topic :: System :: Networking :: Firewalls",
|
|
24
|
+
"Topic :: System :: Systems Administration",
|
|
25
|
+
]
|
|
26
|
+
# No runtime dependencies. The daemon is the kernel-privilege boundary;
|
|
27
|
+
# every transitive dep is part of the trust budget. Stdlib only.
|
|
28
|
+
dependencies = []
|
|
29
|
+
|
|
30
|
+
[dependency-groups]
|
|
31
|
+
dev = [
|
|
32
|
+
"pytest>=7.0",
|
|
33
|
+
"ruff>=0.1.0",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.scripts]
|
|
37
|
+
hop3-rootd = "hop3_rootd.__main__:main"
|
|
38
|
+
|
|
39
|
+
[build-system]
|
|
40
|
+
requires = ["hatchling"]
|
|
41
|
+
build-backend = "hatchling.build"
|
|
42
|
+
|
|
43
|
+
[tool.hatch.build.targets.wheel]
|
|
44
|
+
packages = ["src/hop3_rootd"]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Copyright (c) 2026, Abilian SAS
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""hop3-rootd — privileged-operations agent for Hop3.
|
|
5
|
+
|
|
6
|
+
Runs as root. Exposes a narrow set of typed-intent operations
|
|
7
|
+
(firewall.*, nginx.*, daemon.*) to hop3-server over a Unix socket.
|
|
8
|
+
|
|
9
|
+
See notes/adrs/041-privileged-operations-agent.md for the design.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
__version__ = "0.4.0"
|
|
15
|
+
|
|
16
|
+
# Wire-protocol version. Bump on incompatible protocol changes.
|
|
17
|
+
PROTOCOL_VERSION = 1
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# Copyright (c) 2026, Abilian SAS
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
"""Entry point for hop3-rootd.
|
|
6
|
+
|
|
7
|
+
Run via `python -m hop3_rootd` or the `hop3-rootd` console script.
|
|
8
|
+
|
|
9
|
+
Startup sequence:
|
|
10
|
+
1. Configure stderr logging (captured by journald under systemd).
|
|
11
|
+
2. Load state.json — refuse to start if missing or corrupt.
|
|
12
|
+
3. Run reconciliation against the kernel (skipped non-fatally when the nft
|
|
13
|
+
firewall backend isn't installed — the proxy/process duties don't need
|
|
14
|
+
it, and crashing here would take them down too).
|
|
15
|
+
4. Open the audit log (creates /var/log/hop3-rootd/ if needed).
|
|
16
|
+
5. Bind/inherit the Unix socket.
|
|
17
|
+
6. Notify systemd READY=1.
|
|
18
|
+
7. Run the accept-and-dispatch loop until SIGTERM/SIGINT.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import os
|
|
25
|
+
import signal
|
|
26
|
+
import socket
|
|
27
|
+
import sys
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Final
|
|
31
|
+
|
|
32
|
+
from hop3_rootd.audit import (
|
|
33
|
+
DEFAULT_AUDIT_LOG_PATH,
|
|
34
|
+
AuditLog,
|
|
35
|
+
configure_operational_logging,
|
|
36
|
+
logger,
|
|
37
|
+
)
|
|
38
|
+
from hop3_rootd.nft.rule import NftBinaryNotFoundError
|
|
39
|
+
from hop3_rootd.reconcile import reconcile
|
|
40
|
+
from hop3_rootd.server import DEFAULT_SOCKET_PATH, Server
|
|
41
|
+
from hop3_rootd.state import (
|
|
42
|
+
DEFAULT_STATE_PATH,
|
|
43
|
+
State,
|
|
44
|
+
StateError,
|
|
45
|
+
init_empty,
|
|
46
|
+
load,
|
|
47
|
+
save,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
EXIT_OK: Final[int] = 0
|
|
51
|
+
EXIT_STATE_ERROR: Final[int] = 2
|
|
52
|
+
EXIT_RECONCILE_ERROR: Final[int] = 3
|
|
53
|
+
EXIT_BIND_ERROR: Final[int] = 4
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
57
|
+
parser = argparse.ArgumentParser(
|
|
58
|
+
prog="hop3-rootd",
|
|
59
|
+
description="Hop3 privileged operations agent (kernel-boundary executor).",
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--socket-path",
|
|
63
|
+
type=Path,
|
|
64
|
+
default=DEFAULT_SOCKET_PATH,
|
|
65
|
+
help=f"Unix socket path (default: {DEFAULT_SOCKET_PATH})",
|
|
66
|
+
)
|
|
67
|
+
parser.add_argument(
|
|
68
|
+
"--state-path",
|
|
69
|
+
type=Path,
|
|
70
|
+
default=DEFAULT_STATE_PATH,
|
|
71
|
+
help=f"state.json path (default: {DEFAULT_STATE_PATH})",
|
|
72
|
+
)
|
|
73
|
+
parser.add_argument(
|
|
74
|
+
"--audit-log",
|
|
75
|
+
type=Path,
|
|
76
|
+
default=DEFAULT_AUDIT_LOG_PATH,
|
|
77
|
+
help=f"audit log path (default: {DEFAULT_AUDIT_LOG_PATH})",
|
|
78
|
+
)
|
|
79
|
+
parser.add_argument(
|
|
80
|
+
"--log-level",
|
|
81
|
+
default="INFO",
|
|
82
|
+
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
|
|
83
|
+
help="operational log level (default: INFO)",
|
|
84
|
+
)
|
|
85
|
+
parser.add_argument(
|
|
86
|
+
"--init-state",
|
|
87
|
+
action="store_true",
|
|
88
|
+
help="Create an empty state.json if missing, then exit. "
|
|
89
|
+
"Used by the installer at fresh-install.",
|
|
90
|
+
)
|
|
91
|
+
return parser.parse_args(argv)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _sd_notify(msg: str) -> None:
|
|
95
|
+
"""Send a notify message to systemd. Silent no-op if not running under it."""
|
|
96
|
+
addr = os.environ.get("NOTIFY_SOCKET")
|
|
97
|
+
if not addr:
|
|
98
|
+
return
|
|
99
|
+
# Abstract sockets start with @ on Linux.
|
|
100
|
+
if addr.startswith("@"):
|
|
101
|
+
addr = "\0" + addr[1:]
|
|
102
|
+
try:
|
|
103
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as s:
|
|
104
|
+
s.sendto(msg.encode("utf-8"), addr)
|
|
105
|
+
except OSError as e:
|
|
106
|
+
logger.warning("sd_notify failed: %s", e)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _startup_reconcile(state: State, state_path: Path) -> bool:
|
|
110
|
+
"""Reconcile kernel state at startup. Return True to continue, False to abort.
|
|
111
|
+
|
|
112
|
+
A *missing* nft backend is tolerated — the firewall subsystem degrades
|
|
113
|
+
(firewall ops fail at call time, see server.dispatch) but the daemon stays
|
|
114
|
+
up to serve its nginx/proxy duties, which don't need nft. Any other
|
|
115
|
+
reconciliation failure is fatal per ADR 041 §6: a firewall that's expected
|
|
116
|
+
to work but can't reach the kernel must refuse to start rather than run
|
|
117
|
+
with an unverified security posture.
|
|
118
|
+
"""
|
|
119
|
+
try:
|
|
120
|
+
report = reconcile(state)
|
|
121
|
+
except NftBinaryNotFoundError as e:
|
|
122
|
+
# nft isn't installed/allow-listed here — a supported configuration
|
|
123
|
+
# (containers, restricted VPSes that use Hop3 only for proxy/process
|
|
124
|
+
# duties). Crashing wouldn't enforce any rules anyway; it would just
|
|
125
|
+
# also kill the proxy, the failure mode this guards against.
|
|
126
|
+
log = logger.error if state.rules else logger.warning
|
|
127
|
+
log(
|
|
128
|
+
"firewall backend unavailable (%s); skipping firewall "
|
|
129
|
+
"reconciliation. %d rule(s) in state will NOT be enforced until "
|
|
130
|
+
"nft is installed. Proxy/process operations are unaffected.",
|
|
131
|
+
e,
|
|
132
|
+
len(state.rules),
|
|
133
|
+
)
|
|
134
|
+
return True
|
|
135
|
+
except Exception as e:
|
|
136
|
+
logger.error("reconciliation failed: %s", e)
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
save(state, state_path)
|
|
140
|
+
logger.info(
|
|
141
|
+
"reconciliation: verified=%d reapplied=%d orphans_removed=%d state_dropped=%d",
|
|
142
|
+
report.verified,
|
|
143
|
+
report.reapplied,
|
|
144
|
+
report.orphans_removed,
|
|
145
|
+
report.state_dropped,
|
|
146
|
+
)
|
|
147
|
+
return True
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def main(argv: list[str] | None = None) -> int:
|
|
151
|
+
args = _parse_args(argv)
|
|
152
|
+
configure_operational_logging(args.log_level)
|
|
153
|
+
|
|
154
|
+
if args.init_state:
|
|
155
|
+
if args.state_path.exists():
|
|
156
|
+
logger.info(
|
|
157
|
+
"state.json already present at %s; nothing to do", args.state_path
|
|
158
|
+
)
|
|
159
|
+
return EXIT_OK
|
|
160
|
+
init_empty(args.state_path)
|
|
161
|
+
logger.info("created empty state.json at %s", args.state_path)
|
|
162
|
+
return EXIT_OK
|
|
163
|
+
|
|
164
|
+
try:
|
|
165
|
+
state = load(args.state_path)
|
|
166
|
+
except StateError as e:
|
|
167
|
+
logger.error("cannot load state: %s", e)
|
|
168
|
+
logger.error("refusing to start. Operator must intervene.")
|
|
169
|
+
return EXIT_STATE_ERROR
|
|
170
|
+
|
|
171
|
+
logger.info(
|
|
172
|
+
"loaded state.json with %d rule(s) at %s",
|
|
173
|
+
len(state.rules),
|
|
174
|
+
args.state_path,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
if not _startup_reconcile(state, args.state_path):
|
|
178
|
+
return EXIT_RECONCILE_ERROR
|
|
179
|
+
|
|
180
|
+
audit = AuditLog(args.audit_log)
|
|
181
|
+
|
|
182
|
+
server = Server(state, args.state_path, audit)
|
|
183
|
+
server.stats.mark_reconcile(datetime.now(timezone.utc).isoformat())
|
|
184
|
+
if not server.inherit_systemd_socket():
|
|
185
|
+
try:
|
|
186
|
+
server.bind(args.socket_path)
|
|
187
|
+
except OSError as e:
|
|
188
|
+
logger.error("could not bind to %s: %s", args.socket_path, e)
|
|
189
|
+
return EXIT_BIND_ERROR
|
|
190
|
+
|
|
191
|
+
def _on_term(_signum, _frame):
|
|
192
|
+
logger.info("received TERM/INT — shutting down")
|
|
193
|
+
server.stop()
|
|
194
|
+
|
|
195
|
+
def _on_usr1(_signum, _frame):
|
|
196
|
+
logger.info("received USR1 — reopening audit log")
|
|
197
|
+
audit.reopen()
|
|
198
|
+
|
|
199
|
+
def _on_usr2(_signum, _frame):
|
|
200
|
+
logger.info("received USR2 — resetting error counter")
|
|
201
|
+
server.stats.reset_errors()
|
|
202
|
+
|
|
203
|
+
signal.signal(signal.SIGTERM, _on_term)
|
|
204
|
+
signal.signal(signal.SIGINT, _on_term)
|
|
205
|
+
signal.signal(signal.SIGUSR1, _on_usr1)
|
|
206
|
+
signal.signal(signal.SIGUSR2, _on_usr2)
|
|
207
|
+
|
|
208
|
+
_sd_notify("READY=1")
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
server.run()
|
|
212
|
+
finally:
|
|
213
|
+
audit.close()
|
|
214
|
+
|
|
215
|
+
_sd_notify("STOPPING=1")
|
|
216
|
+
return EXIT_OK
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
if __name__ == "__main__":
|
|
220
|
+
sys.exit(main())
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# Copyright (c) 2026, Abilian SAS
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
"""Audit logging for hop3-rootd.
|
|
6
|
+
|
|
7
|
+
Two log streams:
|
|
8
|
+
|
|
9
|
+
1. Operational logs to stderr, captured by journald automatically when
|
|
10
|
+
the daemon runs under systemd. Standard Python `logging`.
|
|
11
|
+
|
|
12
|
+
2. Append-only audit log at /var/log/hop3-rootd/audit.log. One JSON
|
|
13
|
+
line per request, mode 0640 group hop3 so hop3-server can read
|
|
14
|
+
it directly (powers `hop3 firewall history`).
|
|
15
|
+
|
|
16
|
+
See ADR 041 §13.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import logging
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any, Final, Literal, Self
|
|
28
|
+
|
|
29
|
+
Outcome = Literal["applied", "error"]
|
|
30
|
+
|
|
31
|
+
# --- Default audit-log path -----------------------------------------------
|
|
32
|
+
|
|
33
|
+
DEFAULT_AUDIT_LOG_PATH: Final[Path] = Path("/var/log/hop3-rootd/audit.log")
|
|
34
|
+
DEFAULT_AUDIT_LOG_MODE: Final[int] = 0o640
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# Field names (case-insensitive) whose values get redacted in audit args.
|
|
38
|
+
# Conservative: false-positives are fine; false-negatives leak.
|
|
39
|
+
#
|
|
40
|
+
# The original pattern used a ``$`` end-anchor, which silently missed
|
|
41
|
+
# anything where the secret-marker word wasn't the last component of
|
|
42
|
+
# the field name — most importantly ``aws_access_key_id`` (where
|
|
43
|
+
# ``key`` is in the middle) and any future ``…_token_…`` style name.
|
|
44
|
+
# Switch to ``re.search`` semantics (no anchor) so substrings match,
|
|
45
|
+
# and add the common ``aws_``, ``private_``, ``access_``, ``client_id``
|
|
46
|
+
# prefixes that show up in real configs.
|
|
47
|
+
_SECRET_FIELD_RE: Final[re.Pattern[str]] = re.compile(
|
|
48
|
+
r"("
|
|
49
|
+
r"password"
|
|
50
|
+
r"|passwd"
|
|
51
|
+
r"|passphrase"
|
|
52
|
+
r"|token"
|
|
53
|
+
r"|secret"
|
|
54
|
+
r"|credential"
|
|
55
|
+
r"|api[-_]?key"
|
|
56
|
+
r"|access[-_]?key"
|
|
57
|
+
r"|private[-_]?key"
|
|
58
|
+
r"|signing[-_]?key"
|
|
59
|
+
r"|encryption[-_]?key"
|
|
60
|
+
r"|key" # catch-all (must come last; prefixes above are more specific)
|
|
61
|
+
r"|aws_" # aws_access_key_id, aws_secret_access_key
|
|
62
|
+
r")",
|
|
63
|
+
re.IGNORECASE,
|
|
64
|
+
)
|
|
65
|
+
_REDACTED: Final[str] = "<redacted>"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# --- Setup helpers --------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
logger = logging.getLogger("hop3_rootd")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def configure_operational_logging(level: str = "INFO") -> None:
|
|
75
|
+
"""Configure the stderr logger for operational logs.
|
|
76
|
+
|
|
77
|
+
Under systemd Type=notify, stderr is captured by journald. Format
|
|
78
|
+
matches Hop3's existing structured-log idiom.
|
|
79
|
+
"""
|
|
80
|
+
handler = logging.StreamHandler()
|
|
81
|
+
handler.setFormatter(
|
|
82
|
+
logging.Formatter(
|
|
83
|
+
"%(asctime)s %(levelname)s [%(name)s] %(message)s",
|
|
84
|
+
datefmt="%Y-%m-%dT%H:%M:%S%z",
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
logger.addHandler(handler)
|
|
88
|
+
logger.setLevel(level)
|
|
89
|
+
logger.propagate = False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# --- Argument sanitisation ------------------------------------------------
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def sanitise_args(args: Any) -> Any:
|
|
96
|
+
"""Walk an arbitrary structure and redact values whose keys look secret.
|
|
97
|
+
|
|
98
|
+
Recurses into dicts, lists, and tuples (today's rootd ops are flat
|
|
99
|
+
dicts, but the redaction must hold for any nesting future ops
|
|
100
|
+
introduce). Returns structurally-equal value; never mutates input.
|
|
101
|
+
"""
|
|
102
|
+
if isinstance(args, dict):
|
|
103
|
+
out: dict[Any, Any] = {}
|
|
104
|
+
for k, v in args.items():
|
|
105
|
+
if isinstance(k, str) and _SECRET_FIELD_RE.search(k):
|
|
106
|
+
out[k] = _REDACTED
|
|
107
|
+
else:
|
|
108
|
+
out[k] = sanitise_args(v)
|
|
109
|
+
return out
|
|
110
|
+
if isinstance(args, list):
|
|
111
|
+
return [sanitise_args(item) for item in args]
|
|
112
|
+
if isinstance(args, tuple):
|
|
113
|
+
return tuple(sanitise_args(item) for item in args)
|
|
114
|
+
return args
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# --- Audit log writer -----------------------------------------------------
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass(frozen=True)
|
|
121
|
+
class AuditEntry:
|
|
122
|
+
"""One audit-log record. Serialised as JSON, one per line."""
|
|
123
|
+
|
|
124
|
+
ts: str # ISO-8601 with timezone
|
|
125
|
+
request_id: str
|
|
126
|
+
caller_uid: int
|
|
127
|
+
op: str
|
|
128
|
+
args: dict[str, Any]
|
|
129
|
+
outcome: Outcome
|
|
130
|
+
duration_ms: int
|
|
131
|
+
result: dict[str, Any] | None = None
|
|
132
|
+
error: dict[str, Any] | None = None
|
|
133
|
+
|
|
134
|
+
def to_json_line(self) -> str:
|
|
135
|
+
"""Serialise to a single-line JSON string (no trailing newline)."""
|
|
136
|
+
d: dict[str, Any] = {
|
|
137
|
+
"ts": self.ts,
|
|
138
|
+
"request_id": self.request_id,
|
|
139
|
+
"caller_uid": self.caller_uid,
|
|
140
|
+
"op": self.op,
|
|
141
|
+
"args": self.args,
|
|
142
|
+
"outcome": self.outcome,
|
|
143
|
+
"duration_ms": self.duration_ms,
|
|
144
|
+
}
|
|
145
|
+
if self.result is not None:
|
|
146
|
+
d["result"] = self.result
|
|
147
|
+
if self.error is not None:
|
|
148
|
+
d["error"] = self.error
|
|
149
|
+
return json.dumps(d, separators=(",", ":"))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class AuditLog:
|
|
153
|
+
"""Append-only audit-log writer.
|
|
154
|
+
|
|
155
|
+
The file is opened on construction (or first write) and re-opened on
|
|
156
|
+
SIGUSR1 (logrotate-style) via `reopen()`. Writes are line-buffered:
|
|
157
|
+
each call to `write()` flushes through to the kernel buffer.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
def __init__(self, path: Path = DEFAULT_AUDIT_LOG_PATH):
|
|
161
|
+
self.path = path
|
|
162
|
+
self._fd: Any = None # file object; type avoids stub gymnastics
|
|
163
|
+
|
|
164
|
+
def _ensure_open(self) -> None:
|
|
165
|
+
if self._fd is not None and not self._fd.closed:
|
|
166
|
+
return
|
|
167
|
+
# Create directory if missing (StateDirectory= should have made it).
|
|
168
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
169
|
+
# Open append-only; create with restrictive default mode.
|
|
170
|
+
self._fd = self.path.open("a", encoding="utf-8")
|
|
171
|
+
# Set file mode if we just created it. ifs the file pre-existed,
|
|
172
|
+
# we don't change its perms.
|
|
173
|
+
try:
|
|
174
|
+
self.path.chmod(DEFAULT_AUDIT_LOG_MODE)
|
|
175
|
+
except OSError:
|
|
176
|
+
# Best-effort; don't fail audit because chmod failed.
|
|
177
|
+
logger.warning(
|
|
178
|
+
"could not chmod audit log %s to %o",
|
|
179
|
+
self.path,
|
|
180
|
+
DEFAULT_AUDIT_LOG_MODE,
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def write(self, entry: AuditEntry) -> None:
|
|
184
|
+
"""Append one entry as a JSON line, flushing through to disk.
|
|
185
|
+
|
|
186
|
+
We fsync after each entry so an audit record survives an OS crash
|
|
187
|
+
in the page-cache window. The perf cost (one fsync per privileged
|
|
188
|
+
op) is acceptable: rootd ops are infrequent and durability of the
|
|
189
|
+
audit trail is more valuable than throughput here. ADR 041 §13.
|
|
190
|
+
"""
|
|
191
|
+
self._ensure_open()
|
|
192
|
+
self._fd.write(entry.to_json_line() + "\n")
|
|
193
|
+
self._fd.flush()
|
|
194
|
+
try:
|
|
195
|
+
os.fsync(self._fd.fileno())
|
|
196
|
+
except OSError as exc:
|
|
197
|
+
# fsync can fail on some filesystems (procfs, certain tmpfs
|
|
198
|
+
# layouts) — best-effort only. The flush above already gets
|
|
199
|
+
# us through to the kernel buffer.
|
|
200
|
+
logger.warning("audit log fsync failed: %s", exc)
|
|
201
|
+
|
|
202
|
+
def reopen(self) -> None:
|
|
203
|
+
"""Close + reopen the file. Hooked to SIGUSR1 (logrotate-friendly)."""
|
|
204
|
+
if self._fd is not None and not self._fd.closed:
|
|
205
|
+
self._fd.close()
|
|
206
|
+
self._fd = None
|
|
207
|
+
# Don't pre-open; next write() will open lazily.
|
|
208
|
+
|
|
209
|
+
def close(self) -> None:
|
|
210
|
+
if self._fd is not None and not self._fd.closed:
|
|
211
|
+
self._fd.close()
|
|
212
|
+
self._fd = None
|
|
213
|
+
|
|
214
|
+
def __enter__(self) -> Self:
|
|
215
|
+
self._ensure_open()
|
|
216
|
+
return self
|
|
217
|
+
|
|
218
|
+
def __exit__(self, *_exc: object) -> None:
|
|
219
|
+
self.close()
|