docker-host-audit 0.2.0__tar.gz → 0.4.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.
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/PKG-INFO +41 -2
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/README.md +38 -1
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/pyproject.toml +5 -1
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/pyproject.toml.orig +5 -1
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/__init__.py +1 -1
- docker_host_audit-0.4.0/src/ca/checks/__init__.py +19 -0
- docker_host_audit-0.4.0/src/ca/checks/devices.py +89 -0
- docker_host_audit-0.4.0/src/ca/checks/runtime.py +105 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/cli.py +49 -4
- docker_host_audit-0.4.0/src/ca/compose.py +257 -0
- docker_host_audit-0.4.0/src/ca/config.py +64 -0
- docker_host_audit-0.2.0/src/ca/checks/__init__.py +0 -12
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/__main__.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/checks/exposure.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/checks/hardening.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/checks/images.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/checks/privilege.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/collect.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/docker_cli.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/models.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/py.typed +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/redact.py +0 -0
- {docker_host_audit-0.2.0 → docker_host_audit-0.4.0}/src/ca/report.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: docker-host-audit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Read-only security audit for Docker hosts: flags root containers, exposed ports, secrets in env, privileged mode and mounted docker sockets.
|
|
5
5
|
Author: Petr Hromádka
|
|
6
6
|
Author-email: Petr Hromádka <109349500+petrhromadka@users.noreply.github.com>
|
|
@@ -17,7 +17,9 @@ Classifier: Programming Language :: Python :: 3.14
|
|
|
17
17
|
Classifier: Topic :: Security
|
|
18
18
|
Classifier: Topic :: System :: Systems Administration
|
|
19
19
|
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Dist: pyyaml>=6 ; extra == 'compose'
|
|
20
21
|
Requires-Python: >=3.12
|
|
22
|
+
Provides-Extra: compose
|
|
21
23
|
Description-Content-Type: text/markdown
|
|
22
24
|
|
|
23
25
|
<div align="center">
|
|
@@ -67,7 +69,8 @@ reads live containers via `docker ps` / `docker inspect`.
|
|
|
67
69
|
## 🔍 What it checks
|
|
68
70
|
|
|
69
71
|
Severity key: 🔴 critical · 🟠 high · 🟡 medium · 🔵 low. Each finding carries a title, a plain-language
|
|
70
|
-
explanation, short **redacted** evidence, and a one-line remediation.
|
|
72
|
+
explanation, short **redacted** evidence, and a one-line remediation. See
|
|
73
|
+
[docs/checks.md](docs/checks.md) for every check with rationale and remediation.
|
|
71
74
|
|
|
72
75
|
### Privilege & escape
|
|
73
76
|
|
|
@@ -85,6 +88,7 @@ explanation, short **redacted** evidence, and a one-line remediation.
|
|
|
85
88
|
| :-: | --- | --- | --- |
|
|
86
89
|
| 🟠 | `host-pid` | Shares the host PID namespace (`--pid=host`) | It can see and signal every process on the host. |
|
|
87
90
|
| 🟠 | `host-network` | Shares the host network namespace (`--network=host`) | Network isolation and port mapping are bypassed. |
|
|
91
|
+
| 🟡 | `shared-network-container` | Shares another container's network namespace (`--network=container:<id>`) | One compromised container can observe or interfere with the other's traffic and ports. |
|
|
88
92
|
| 🟡 | `port-all-interfaces` | Port published on `0.0.0.0` / `::` | Reachable from every network the host is on, not just where you intend. |
|
|
89
93
|
| 🟡 | `host-ipc` | Shares the host IPC namespace (`--ipc=host`) | Shared memory and semaphores cross the container boundary. |
|
|
90
94
|
| 🔵 | `host-uts` | Shares the host UTS namespace (`--uts=host`) | It can change the host's hostname. |
|
|
@@ -100,6 +104,25 @@ explanation, short **redacted** evidence, and a one-line remediation.
|
|
|
100
104
|
| 🔵 | `unpinned-image` | Image uses `:latest`, no tag, or no digest | Pulls aren't reproducible; upstream can silently change what runs. |
|
|
101
105
|
| 🔵 | `unlimited-memory` | No memory limit set | A single container can exhaust host RAM and take the host down. |
|
|
102
106
|
|
|
107
|
+
### Runtime hardening
|
|
108
|
+
|
|
109
|
+
| | Check id | What | Why it matters |
|
|
110
|
+
| :-: | --- | --- | --- |
|
|
111
|
+
| 🟠 | `seccomp-unconfined` | `seccomp=unconfined` disables the default syscall filter | Widens the kernel attack surface available from inside the container. |
|
|
112
|
+
| 🟡 | `apparmor-unconfined` | `apparmor=unconfined` disables the AppArmor profile | Drops mandatory access control confinement. |
|
|
113
|
+
| 🔵 | `caps-not-dropped` | Capabilities are not dropped to `ALL` | The container keeps Docker's default cap set instead of least privilege. |
|
|
114
|
+
| 🔵 | `no-healthcheck` | No container healthcheck is configured | Orchestration can't tell when the container is unhealthy. |
|
|
115
|
+
|
|
116
|
+
### Host resources
|
|
117
|
+
|
|
118
|
+
| | Check id | What | Why it matters |
|
|
119
|
+
| :-: | --- | --- | --- |
|
|
120
|
+
| 🟡 | `host-devices` | Host devices passed into the container (`HostConfig.Devices`) | Direct access to host hardware can be used to read or alter host state. |
|
|
121
|
+
| 🟡 | `dangerous-sysctls` | Custom `kernel.*` / `net.*` sysctls set | Tuning kernel or network sysctls from inside can weaken host and network protections. |
|
|
122
|
+
| 🔵 | `oom-kill-disable` | The OOM killer is disabled | The container can hold memory under pressure and hang the host instead of being killed. |
|
|
123
|
+
|
|
124
|
+
See [docs/checks.md](docs/checks.md) for every check with full rationale and remediation.
|
|
125
|
+
|
|
103
126
|
---
|
|
104
127
|
|
|
105
128
|
## 📦 Install
|
|
@@ -141,11 +164,18 @@ container-audit --format markdown > report.md # for an issue / PR /
|
|
|
141
164
|
|
|
142
165
|
docker inspect $(docker ps -aq) $(docker inspect -f '{{.Image}}' $(docker ps -aq) | sort -u) > sample.json # save containers + their images
|
|
143
166
|
container-audit --input sample.json --fail-on high # audit the dump; non-zero exit for CI
|
|
167
|
+
|
|
168
|
+
container-audit --compose docker-compose.yml --fail-on high # audit a compose file, no daemon needed
|
|
144
169
|
```
|
|
145
170
|
|
|
171
|
+
Auditing a compose file needs the optional `[compose]` extra:
|
|
172
|
+
`pip install docker-host-audit[compose]` (or `uvx --from docker-host-audit[compose] container-audit`).
|
|
173
|
+
See [docs/compose.md](docs/compose.md).
|
|
174
|
+
|
|
146
175
|
| Flag | Meaning |
|
|
147
176
|
| --- | --- |
|
|
148
177
|
| `--input FILE` | Read `docker inspect` JSON from `FILE` instead of calling Docker. |
|
|
178
|
+
| `--compose PATH` | Statically audit a `docker-compose.yml` without a running daemon (needs the `[compose]` extra). Mutually exclusive with `--input`. |
|
|
149
179
|
| `--format FORMAT` | Output format: `text` (default), `json`, `markdown` or `sarif`. |
|
|
150
180
|
| `--ignore CHECK_ID` | Suppress findings with this check id (e.g. `docker-socket-mount`). Repeatable. |
|
|
151
181
|
| `--include-stopped` | Also inspect containers that are not running. |
|
|
@@ -297,6 +327,15 @@ register it in the `CHECKS` list of the relevant module under `src/ca/checks/`.
|
|
|
297
327
|
|
|
298
328
|
---
|
|
299
329
|
|
|
330
|
+
## 📚 Documentation
|
|
331
|
+
|
|
332
|
+
- [docs/checks.md](docs/checks.md) — reference for every check, with severity, trigger, rationale and remediation.
|
|
333
|
+
- [docs/compose.md](docs/compose.md) — auditing a `docker-compose.yml` with `--compose`, without a daemon.
|
|
334
|
+
- [docs/configuration.md](docs/configuration.md) — the optional config file and its settings.
|
|
335
|
+
- [docs/github-action.md](docs/github-action.md) — the reusable GitHub Action for CI.
|
|
336
|
+
|
|
337
|
+
---
|
|
338
|
+
|
|
300
339
|
## 📄 License
|
|
301
340
|
|
|
302
341
|
[MIT](LICENSE) © 2026 Petr Hromádka
|
|
@@ -45,7 +45,8 @@ reads live containers via `docker ps` / `docker inspect`.
|
|
|
45
45
|
## 🔍 What it checks
|
|
46
46
|
|
|
47
47
|
Severity key: 🔴 critical · 🟠 high · 🟡 medium · 🔵 low. Each finding carries a title, a plain-language
|
|
48
|
-
explanation, short **redacted** evidence, and a one-line remediation.
|
|
48
|
+
explanation, short **redacted** evidence, and a one-line remediation. See
|
|
49
|
+
[docs/checks.md](docs/checks.md) for every check with rationale and remediation.
|
|
49
50
|
|
|
50
51
|
### Privilege & escape
|
|
51
52
|
|
|
@@ -63,6 +64,7 @@ explanation, short **redacted** evidence, and a one-line remediation.
|
|
|
63
64
|
| :-: | --- | --- | --- |
|
|
64
65
|
| 🟠 | `host-pid` | Shares the host PID namespace (`--pid=host`) | It can see and signal every process on the host. |
|
|
65
66
|
| 🟠 | `host-network` | Shares the host network namespace (`--network=host`) | Network isolation and port mapping are bypassed. |
|
|
67
|
+
| 🟡 | `shared-network-container` | Shares another container's network namespace (`--network=container:<id>`) | One compromised container can observe or interfere with the other's traffic and ports. |
|
|
66
68
|
| 🟡 | `port-all-interfaces` | Port published on `0.0.0.0` / `::` | Reachable from every network the host is on, not just where you intend. |
|
|
67
69
|
| 🟡 | `host-ipc` | Shares the host IPC namespace (`--ipc=host`) | Shared memory and semaphores cross the container boundary. |
|
|
68
70
|
| 🔵 | `host-uts` | Shares the host UTS namespace (`--uts=host`) | It can change the host's hostname. |
|
|
@@ -78,6 +80,25 @@ explanation, short **redacted** evidence, and a one-line remediation.
|
|
|
78
80
|
| 🔵 | `unpinned-image` | Image uses `:latest`, no tag, or no digest | Pulls aren't reproducible; upstream can silently change what runs. |
|
|
79
81
|
| 🔵 | `unlimited-memory` | No memory limit set | A single container can exhaust host RAM and take the host down. |
|
|
80
82
|
|
|
83
|
+
### Runtime hardening
|
|
84
|
+
|
|
85
|
+
| | Check id | What | Why it matters |
|
|
86
|
+
| :-: | --- | --- | --- |
|
|
87
|
+
| 🟠 | `seccomp-unconfined` | `seccomp=unconfined` disables the default syscall filter | Widens the kernel attack surface available from inside the container. |
|
|
88
|
+
| 🟡 | `apparmor-unconfined` | `apparmor=unconfined` disables the AppArmor profile | Drops mandatory access control confinement. |
|
|
89
|
+
| 🔵 | `caps-not-dropped` | Capabilities are not dropped to `ALL` | The container keeps Docker's default cap set instead of least privilege. |
|
|
90
|
+
| 🔵 | `no-healthcheck` | No container healthcheck is configured | Orchestration can't tell when the container is unhealthy. |
|
|
91
|
+
|
|
92
|
+
### Host resources
|
|
93
|
+
|
|
94
|
+
| | Check id | What | Why it matters |
|
|
95
|
+
| :-: | --- | --- | --- |
|
|
96
|
+
| 🟡 | `host-devices` | Host devices passed into the container (`HostConfig.Devices`) | Direct access to host hardware can be used to read or alter host state. |
|
|
97
|
+
| 🟡 | `dangerous-sysctls` | Custom `kernel.*` / `net.*` sysctls set | Tuning kernel or network sysctls from inside can weaken host and network protections. |
|
|
98
|
+
| 🔵 | `oom-kill-disable` | The OOM killer is disabled | The container can hold memory under pressure and hang the host instead of being killed. |
|
|
99
|
+
|
|
100
|
+
See [docs/checks.md](docs/checks.md) for every check with full rationale and remediation.
|
|
101
|
+
|
|
81
102
|
---
|
|
82
103
|
|
|
83
104
|
## 📦 Install
|
|
@@ -119,11 +140,18 @@ container-audit --format markdown > report.md # for an issue / PR /
|
|
|
119
140
|
|
|
120
141
|
docker inspect $(docker ps -aq) $(docker inspect -f '{{.Image}}' $(docker ps -aq) | sort -u) > sample.json # save containers + their images
|
|
121
142
|
container-audit --input sample.json --fail-on high # audit the dump; non-zero exit for CI
|
|
143
|
+
|
|
144
|
+
container-audit --compose docker-compose.yml --fail-on high # audit a compose file, no daemon needed
|
|
122
145
|
```
|
|
123
146
|
|
|
147
|
+
Auditing a compose file needs the optional `[compose]` extra:
|
|
148
|
+
`pip install docker-host-audit[compose]` (or `uvx --from docker-host-audit[compose] container-audit`).
|
|
149
|
+
See [docs/compose.md](docs/compose.md).
|
|
150
|
+
|
|
124
151
|
| Flag | Meaning |
|
|
125
152
|
| --- | --- |
|
|
126
153
|
| `--input FILE` | Read `docker inspect` JSON from `FILE` instead of calling Docker. |
|
|
154
|
+
| `--compose PATH` | Statically audit a `docker-compose.yml` without a running daemon (needs the `[compose]` extra). Mutually exclusive with `--input`. |
|
|
127
155
|
| `--format FORMAT` | Output format: `text` (default), `json`, `markdown` or `sarif`. |
|
|
128
156
|
| `--ignore CHECK_ID` | Suppress findings with this check id (e.g. `docker-socket-mount`). Repeatable. |
|
|
129
157
|
| `--include-stopped` | Also inspect containers that are not running. |
|
|
@@ -275,6 +303,15 @@ register it in the `CHECKS` list of the relevant module under `src/ca/checks/`.
|
|
|
275
303
|
|
|
276
304
|
---
|
|
277
305
|
|
|
306
|
+
## 📚 Documentation
|
|
307
|
+
|
|
308
|
+
- [docs/checks.md](docs/checks.md) — reference for every check, with severity, trigger, rationale and remediation.
|
|
309
|
+
- [docs/compose.md](docs/compose.md) — auditing a `docker-compose.yml` with `--compose`, without a daemon.
|
|
310
|
+
- [docs/configuration.md](docs/configuration.md) — the optional config file and its settings.
|
|
311
|
+
- [docs/github-action.md](docs/github-action.md) — the reusable GitHub Action for CI.
|
|
312
|
+
|
|
313
|
+
---
|
|
314
|
+
|
|
278
315
|
## 📄 License
|
|
279
316
|
|
|
280
317
|
[MIT](LICENSE) © 2026 Petr Hromádka
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "docker-host-audit"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.0"
|
|
4
4
|
description = "Read-only security audit for Docker hosts: flags root containers, exposed ports, secrets in env, privileged mode and mounted docker sockets."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -25,6 +25,9 @@ dependencies = []
|
|
|
25
25
|
name = "Petr Hromádka"
|
|
26
26
|
email = "109349500+petrhromadka@users.noreply.github.com"
|
|
27
27
|
|
|
28
|
+
[project.optional-dependencies]
|
|
29
|
+
compose = ["pyyaml>=6"]
|
|
30
|
+
|
|
28
31
|
[project.scripts]
|
|
29
32
|
container-audit = "ca.cli:main"
|
|
30
33
|
docker-host-audit = "ca.cli:main"
|
|
@@ -72,6 +75,7 @@ addopts = "-q"
|
|
|
72
75
|
[dependency-groups]
|
|
73
76
|
dev = [
|
|
74
77
|
"pytest>=9.2.0",
|
|
78
|
+
"pyyaml>=6",
|
|
75
79
|
"ruff>=0.17.4",
|
|
76
80
|
"ty>=0.0.98",
|
|
77
81
|
]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "docker-host-audit"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.0"
|
|
4
4
|
description = "Read-only security audit for Docker hosts: flags root containers, exposed ports, secrets in env, privileged mode and mounted docker sockets."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -22,6 +22,9 @@ classifiers = [
|
|
|
22
22
|
]
|
|
23
23
|
dependencies = []
|
|
24
24
|
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
compose = ["pyyaml>=6"]
|
|
27
|
+
|
|
25
28
|
[project.scripts]
|
|
26
29
|
container-audit = "ca.cli:main"
|
|
27
30
|
docker-host-audit = "ca.cli:main"
|
|
@@ -51,6 +54,7 @@ addopts = "-q"
|
|
|
51
54
|
[dependency-groups]
|
|
52
55
|
dev = [
|
|
53
56
|
"pytest>=9.2.0",
|
|
57
|
+
"pyyaml>=6",
|
|
54
58
|
"ruff>=0.17.4",
|
|
55
59
|
"ty>=0.0.98",
|
|
56
60
|
]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Check registry. Each submodule exposes `CHECKS: list[CheckFn]`; we aggregate them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ca.models import CheckFn
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def get_checks() -> list[CheckFn]:
|
|
9
|
+
"""Every registered check, across all submodules."""
|
|
10
|
+
from ca.checks import devices, exposure, hardening, images, privilege, runtime
|
|
11
|
+
|
|
12
|
+
return [
|
|
13
|
+
*privilege.CHECKS,
|
|
14
|
+
*exposure.CHECKS,
|
|
15
|
+
*hardening.CHECKS,
|
|
16
|
+
*images.CHECKS,
|
|
17
|
+
*runtime.CHECKS,
|
|
18
|
+
*devices.CHECKS,
|
|
19
|
+
]
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Device and kernel-exposure checks: host devices, shared netns, sysctls, OOM kill."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from ca.models import CheckFn, Container, Finding, Severity
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _host_config(c: Container) -> dict[str, Any]:
|
|
12
|
+
host_config = c.raw.get("HostConfig")
|
|
13
|
+
return host_config if isinstance(host_config, dict) else {}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def host_devices(containers: list[Container]) -> Iterable[Finding]:
|
|
17
|
+
for c in containers:
|
|
18
|
+
devices = _host_config(c).get("Devices")
|
|
19
|
+
if isinstance(devices, list) and devices:
|
|
20
|
+
first = devices[0] if isinstance(devices[0], dict) else {}
|
|
21
|
+
path = first.get("PathOnHost", "")
|
|
22
|
+
yield Finding(
|
|
23
|
+
check_id="host-devices",
|
|
24
|
+
title="Host devices are exposed to the container",
|
|
25
|
+
severity=Severity.MEDIUM,
|
|
26
|
+
container=c.name,
|
|
27
|
+
detail="Host devices are passed through to the container, giving it direct "
|
|
28
|
+
"access to host hardware.",
|
|
29
|
+
evidence=f"HostConfig.Devices has {len(devices)} entr"
|
|
30
|
+
f"{'y' if len(devices) == 1 else 'ies'}, first PathOnHost={path}",
|
|
31
|
+
remediation="Remove device passthrough unless the container truly needs it.",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def shared_network_container(containers: list[Container]) -> Iterable[Finding]:
|
|
36
|
+
for c in containers:
|
|
37
|
+
if c.network_mode.startswith("container:"):
|
|
38
|
+
yield Finding(
|
|
39
|
+
check_id="shared-network-container",
|
|
40
|
+
title="Container shares another container's network namespace",
|
|
41
|
+
severity=Severity.MEDIUM,
|
|
42
|
+
container=c.name,
|
|
43
|
+
detail="The container shares another container's network namespace, so they can "
|
|
44
|
+
"reach each other's loopback services and traffic.",
|
|
45
|
+
evidence=f"HostConfig.NetworkMode={c.network_mode}",
|
|
46
|
+
remediation="Use a dedicated bridge or user-defined network instead.",
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def dangerous_sysctls(containers: list[Container]) -> Iterable[Finding]:
|
|
51
|
+
for c in containers:
|
|
52
|
+
sysctls = _host_config(c).get("Sysctls")
|
|
53
|
+
if not isinstance(sysctls, dict) or not sysctls:
|
|
54
|
+
continue
|
|
55
|
+
matching = [key for key in sysctls if str(key).lower().startswith(("kernel.", "net."))]
|
|
56
|
+
if matching:
|
|
57
|
+
yield Finding(
|
|
58
|
+
check_id="dangerous-sysctls",
|
|
59
|
+
title="Container sets kernel or network sysctls",
|
|
60
|
+
severity=Severity.MEDIUM,
|
|
61
|
+
container=c.name,
|
|
62
|
+
detail="The container overrides kernel or network sysctls, which can weaken "
|
|
63
|
+
"host isolation.",
|
|
64
|
+
evidence=f"HostConfig.Sysctls sets {', '.join(sorted(matching))}",
|
|
65
|
+
remediation="Drop custom sysctls unless they are strictly required.",
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def oom_kill_disable(containers: list[Container]) -> Iterable[Finding]:
|
|
70
|
+
for c in containers:
|
|
71
|
+
if _host_config(c).get("OomKillDisable") is True:
|
|
72
|
+
yield Finding(
|
|
73
|
+
check_id="oom-kill-disable",
|
|
74
|
+
title="OOM killer is disabled for the container",
|
|
75
|
+
severity=Severity.LOW,
|
|
76
|
+
container=c.name,
|
|
77
|
+
detail="The OOM killer is disabled for this container, so it can hang the host "
|
|
78
|
+
"under memory pressure instead of being killed.",
|
|
79
|
+
evidence="HostConfig.OomKillDisable=true",
|
|
80
|
+
remediation="Do not set oom_kill_disable.",
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
CHECKS: list[CheckFn] = [
|
|
85
|
+
host_devices,
|
|
86
|
+
shared_network_container,
|
|
87
|
+
dangerous_sysctls,
|
|
88
|
+
oom_kill_disable,
|
|
89
|
+
]
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Runtime hardening checks: seccomp/apparmor profiles, capability dropping, healthchecks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from ca.models import CheckFn, Container, Finding, Severity
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _security_opt(c: Container) -> list[Any]:
|
|
12
|
+
host_config = c.raw.get("HostConfig")
|
|
13
|
+
if not isinstance(host_config, dict):
|
|
14
|
+
return []
|
|
15
|
+
opts = host_config.get("SecurityOpt")
|
|
16
|
+
return list(opts) if isinstance(opts, list) else []
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _has_unconfined(c: Container, key: str) -> bool:
|
|
20
|
+
target = f"{key}:unconfined"
|
|
21
|
+
return any(str(opt).strip().lower().replace("=", ":") == target for opt in _security_opt(c))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _normalize_cap(cap: str) -> str:
|
|
25
|
+
return cap.strip().upper().removeprefix("CAP_")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _healthcheck_test(c: Container) -> list[Any] | None:
|
|
29
|
+
config = c.raw.get("Config")
|
|
30
|
+
if not isinstance(config, dict):
|
|
31
|
+
return None
|
|
32
|
+
healthcheck = config.get("Healthcheck")
|
|
33
|
+
if not isinstance(healthcheck, dict):
|
|
34
|
+
return None
|
|
35
|
+
test = healthcheck.get("Test")
|
|
36
|
+
return list(test) if isinstance(test, list) else []
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def seccomp_unconfined(containers: list[Container]) -> Iterable[Finding]:
|
|
40
|
+
for c in containers:
|
|
41
|
+
if _has_unconfined(c, "seccomp"):
|
|
42
|
+
yield Finding(
|
|
43
|
+
check_id="seccomp-unconfined",
|
|
44
|
+
title="Seccomp profile disabled (unconfined)",
|
|
45
|
+
severity=Severity.HIGH,
|
|
46
|
+
container=c.name,
|
|
47
|
+
detail="The default seccomp syscall filter is disabled, widening the kernel "
|
|
48
|
+
"attack surface.",
|
|
49
|
+
evidence="HostConfig.SecurityOpt contains seccomp=unconfined",
|
|
50
|
+
remediation="Remove `seccomp=unconfined`; use the default profile.",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def apparmor_unconfined(containers: list[Container]) -> Iterable[Finding]:
|
|
55
|
+
for c in containers:
|
|
56
|
+
if _has_unconfined(c, "apparmor"):
|
|
57
|
+
yield Finding(
|
|
58
|
+
check_id="apparmor-unconfined",
|
|
59
|
+
title="AppArmor profile disabled (unconfined)",
|
|
60
|
+
severity=Severity.MEDIUM,
|
|
61
|
+
container=c.name,
|
|
62
|
+
detail="The container runs without an AppArmor profile, removing a layer of "
|
|
63
|
+
"mandatory access control.",
|
|
64
|
+
evidence="HostConfig.SecurityOpt contains apparmor=unconfined",
|
|
65
|
+
remediation="Use the default `docker-default` AppArmor profile.",
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def caps_not_dropped(containers: list[Container]) -> Iterable[Finding]:
|
|
70
|
+
for c in containers:
|
|
71
|
+
if "ALL" not in {_normalize_cap(cap) for cap in c.cap_drop}:
|
|
72
|
+
yield Finding(
|
|
73
|
+
check_id="caps-not-dropped",
|
|
74
|
+
title="Default capabilities are not dropped",
|
|
75
|
+
severity=Severity.LOW,
|
|
76
|
+
container=c.name,
|
|
77
|
+
detail="The container keeps Docker's default capability set instead of dropping "
|
|
78
|
+
"all and adding only what's needed.",
|
|
79
|
+
evidence="cap_drop does not contain ALL",
|
|
80
|
+
remediation="`cap_drop: [ALL]` then add back only required caps.",
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def no_healthcheck(containers: list[Container]) -> Iterable[Finding]:
|
|
85
|
+
for c in containers:
|
|
86
|
+
test = _healthcheck_test(c)
|
|
87
|
+
if not test or test == ["NONE"]:
|
|
88
|
+
yield Finding(
|
|
89
|
+
check_id="no-healthcheck",
|
|
90
|
+
title="Container has no healthcheck",
|
|
91
|
+
severity=Severity.LOW,
|
|
92
|
+
container=c.name,
|
|
93
|
+
detail="No container healthcheck, so orchestration can't detect an unhealthy "
|
|
94
|
+
"container.",
|
|
95
|
+
evidence="Config.Healthcheck is missing or disabled",
|
|
96
|
+
remediation="Add a HEALTHCHECK to the image or compose.",
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
CHECKS: list[CheckFn] = [
|
|
101
|
+
seccomp_unconfined,
|
|
102
|
+
apparmor_unconfined,
|
|
103
|
+
caps_not_dropped,
|
|
104
|
+
no_healthcheck,
|
|
105
|
+
]
|
|
@@ -8,12 +8,16 @@ import socket
|
|
|
8
8
|
import sys
|
|
9
9
|
from datetime import UTC, datetime
|
|
10
10
|
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
11
12
|
|
|
12
13
|
from ca import __version__
|
|
13
14
|
from ca.checks import get_checks
|
|
15
|
+
from ca.config import load_config
|
|
14
16
|
from ca.models import Container, Finding, Report, Severity
|
|
15
17
|
from ca.report import render
|
|
16
18
|
|
|
19
|
+
_DEFAULTS = {"format": "text", "fail_on": "none", "min_severity": "info"}
|
|
20
|
+
|
|
17
21
|
_FAIL_LEVELS = {
|
|
18
22
|
"low": Severity.LOW,
|
|
19
23
|
"medium": Severity.MEDIUM,
|
|
@@ -29,7 +33,18 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
29
33
|
)
|
|
30
34
|
p.add_argument("--version", action="version", version=f"container-audit {__version__}")
|
|
31
35
|
p.add_argument("--input", metavar="PATH", help="JSON array of `docker inspect` objects")
|
|
32
|
-
p.add_argument(
|
|
36
|
+
p.add_argument(
|
|
37
|
+
"--compose",
|
|
38
|
+
metavar="PATH",
|
|
39
|
+
help="audit a docker-compose.yml instead of a live host or --input",
|
|
40
|
+
)
|
|
41
|
+
p.add_argument(
|
|
42
|
+
"--config",
|
|
43
|
+
metavar="PATH",
|
|
44
|
+
help="path to a TOML config file; otherwise container-audit.toml / "
|
|
45
|
+
".container-audit.toml in the current directory is used",
|
|
46
|
+
)
|
|
47
|
+
p.add_argument("--format", choices=["text", "json", "markdown", "sarif"], default=None)
|
|
33
48
|
p.add_argument("--include-stopped", action="store_true", help="also audit stopped containers")
|
|
34
49
|
p.add_argument(
|
|
35
50
|
"--ignore",
|
|
@@ -40,13 +55,13 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
40
55
|
p.add_argument(
|
|
41
56
|
"--fail-on",
|
|
42
57
|
choices=["none", *_FAIL_LEVELS],
|
|
43
|
-
default=
|
|
58
|
+
default=None,
|
|
44
59
|
help="exit 1 if any finding is at or above this severity",
|
|
45
60
|
)
|
|
46
61
|
p.add_argument(
|
|
47
62
|
"--min-severity",
|
|
48
63
|
choices=list(_MIN_LEVELS),
|
|
49
|
-
default=
|
|
64
|
+
default=None,
|
|
50
65
|
help="hide findings below this severity from the report (--fail-on sees the same list)",
|
|
51
66
|
)
|
|
52
67
|
p.add_argument(
|
|
@@ -58,6 +73,16 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
58
73
|
|
|
59
74
|
|
|
60
75
|
def _load_unchecked(args: argparse.Namespace) -> list[Container] | None:
|
|
76
|
+
if args.compose:
|
|
77
|
+
from ca.compose import parse_compose
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
return parse_compose(args.compose)
|
|
81
|
+
except Exception as exc:
|
|
82
|
+
if type(exc).__module__.split(".", 1)[0] == "yaml":
|
|
83
|
+
raise ValueError(f"invalid compose file: {exc}") from exc
|
|
84
|
+
raise
|
|
85
|
+
|
|
61
86
|
if args.input:
|
|
62
87
|
from ca.collect import parse_inspect
|
|
63
88
|
|
|
@@ -91,8 +116,29 @@ def _load(args: argparse.Namespace) -> list[Container] | None:
|
|
|
91
116
|
return None
|
|
92
117
|
|
|
93
118
|
|
|
119
|
+
def _apply_config(args: argparse.Namespace, config: dict[str, Any]) -> set[str]:
|
|
120
|
+
"""Merge config into args (CLI flag > config > default) and return the ignore set."""
|
|
121
|
+
for key, default in _DEFAULTS.items():
|
|
122
|
+
if getattr(args, key) is None:
|
|
123
|
+
setattr(args, key, config.get(key, default))
|
|
124
|
+
for key in ("include_host", "include_stopped"):
|
|
125
|
+
if config.get(key):
|
|
126
|
+
setattr(args, key, True)
|
|
127
|
+
return set(args.ignore or []) | set(config.get("ignore", []))
|
|
128
|
+
|
|
129
|
+
|
|
94
130
|
def main(argv: list[str] | None = None) -> int:
|
|
95
131
|
args = _parser().parse_args(argv)
|
|
132
|
+
if args.input and args.compose:
|
|
133
|
+
print("error: use either --input or --compose, not both", file=sys.stderr)
|
|
134
|
+
return 2
|
|
135
|
+
try:
|
|
136
|
+
config = load_config(args.config, Path.cwd())
|
|
137
|
+
except ValueError as exc:
|
|
138
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
139
|
+
return 2
|
|
140
|
+
ignored = _apply_config(args, config)
|
|
141
|
+
|
|
96
142
|
containers = _load(args)
|
|
97
143
|
if containers is None:
|
|
98
144
|
return 2
|
|
@@ -102,7 +148,6 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
102
148
|
findings.extend(check(containers))
|
|
103
149
|
floor = _MIN_LEVELS[args.min_severity]
|
|
104
150
|
findings = [f for f in findings if f.severity >= floor]
|
|
105
|
-
ignored = set(args.ignore or [])
|
|
106
151
|
findings = [f for f in findings if f.check_id not in ignored]
|
|
107
152
|
|
|
108
153
|
report = Report(
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Audit a docker-compose.yml without a running daemon.
|
|
2
|
+
|
|
3
|
+
Each compose service is translated into a `docker inspect`-shaped dict and then fed to
|
|
4
|
+
`ca.collect.parse_inspect`, so every existing (and future) check works unchanged. The
|
|
5
|
+
mapping is best-effort: compose is a build-time description, not a daemon's view, so some
|
|
6
|
+
runtime-only fields are approximated and bad input is coerced or skipped rather than fatal.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ca.collect import parse_inspect
|
|
15
|
+
from ca.models import Container
|
|
16
|
+
|
|
17
|
+
_MEMORY_SUFFIXES = {"b": 1, "k": 1024, "m": 1024**2, "g": 1024**3}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _as_dict(x: Any) -> dict:
|
|
21
|
+
return x if isinstance(x, dict) else {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _as_list(x: Any) -> list:
|
|
25
|
+
if isinstance(x, list):
|
|
26
|
+
return x
|
|
27
|
+
return [x] if isinstance(x, str) else []
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _as_str(x: Any) -> str:
|
|
31
|
+
return x if isinstance(x, str) else ""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _str_list(x: Any) -> list[str] | None:
|
|
35
|
+
"""A list of strings, or None if the value is absent/unusable (so callers can omit it)."""
|
|
36
|
+
if not isinstance(x, list):
|
|
37
|
+
return None
|
|
38
|
+
return [i for i in x if isinstance(i, str)]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _env(value: Any) -> list[str]:
|
|
42
|
+
"""Normalize `environment` (list of "K=V" or mapping {K: V}) to ["K=V", ...]."""
|
|
43
|
+
if isinstance(value, dict):
|
|
44
|
+
out = []
|
|
45
|
+
for k, v in value.items():
|
|
46
|
+
key = str(k)
|
|
47
|
+
out.append(key if v is None else f"{key}={v}")
|
|
48
|
+
return out
|
|
49
|
+
if isinstance(value, list):
|
|
50
|
+
return [i for i in value if isinstance(i, str)]
|
|
51
|
+
return []
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _parse_memory(value: Any) -> int:
|
|
55
|
+
"""Convert a compose memory limit (int bytes or "512m"/"1g"/"536870912") to bytes."""
|
|
56
|
+
if isinstance(value, bool):
|
|
57
|
+
return 0
|
|
58
|
+
if isinstance(value, int):
|
|
59
|
+
return value if value > 0 else 0
|
|
60
|
+
if not isinstance(value, str):
|
|
61
|
+
return 0
|
|
62
|
+
text = value.strip().lower()
|
|
63
|
+
if not text:
|
|
64
|
+
return 0
|
|
65
|
+
suffix = text[-1]
|
|
66
|
+
if suffix in _MEMORY_SUFFIXES:
|
|
67
|
+
number, unit = text[:-1], _MEMORY_SUFFIXES[suffix]
|
|
68
|
+
else:
|
|
69
|
+
number, unit = text, 1
|
|
70
|
+
try:
|
|
71
|
+
return int(float(number) * unit)
|
|
72
|
+
except ValueError:
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _service_memory(service: dict[str, Any]) -> int:
|
|
77
|
+
if "mem_limit" in service:
|
|
78
|
+
mem = _parse_memory(service.get("mem_limit"))
|
|
79
|
+
if mem:
|
|
80
|
+
return mem
|
|
81
|
+
limits = _as_dict(_as_dict(_as_dict(service.get("deploy")).get("resources")).get("limits"))
|
|
82
|
+
return _parse_memory(limits.get("memory"))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _healthcheck(service: dict[str, Any]) -> dict[str, Any] | None:
|
|
86
|
+
"""Config.Healthcheck for a service, or None to omit (so no-healthcheck fires)."""
|
|
87
|
+
hc = service.get("healthcheck")
|
|
88
|
+
if not isinstance(hc, dict):
|
|
89
|
+
return None
|
|
90
|
+
if hc.get("disable") is True:
|
|
91
|
+
return {"Test": ["NONE"]}
|
|
92
|
+
test = hc.get("test")
|
|
93
|
+
if isinstance(test, list):
|
|
94
|
+
return {"Test": [str(i) for i in test]}
|
|
95
|
+
if isinstance(test, str):
|
|
96
|
+
return {"Test": ["CMD-SHELL", test]}
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _port_entry(host_ip: str, published: str, target: str, proto: str) -> tuple[str, Any]:
|
|
101
|
+
key = f"{target}/{proto}"
|
|
102
|
+
if not published:
|
|
103
|
+
return key, None
|
|
104
|
+
return key, [{"HostIp": host_ip, "HostPort": published}]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _parse_port(spec: Any) -> tuple[str, Any] | None:
|
|
108
|
+
"""One compose port (short string or long mapping) -> a NetworkSettings.Ports item."""
|
|
109
|
+
if isinstance(spec, int):
|
|
110
|
+
spec = str(spec)
|
|
111
|
+
if isinstance(spec, str):
|
|
112
|
+
text, _, proto = spec.partition("/")
|
|
113
|
+
proto = proto or "tcp"
|
|
114
|
+
parts = text.split(":")
|
|
115
|
+
if len(parts) == 1:
|
|
116
|
+
return _port_entry("", "", parts[0], proto)
|
|
117
|
+
if len(parts) == 2:
|
|
118
|
+
return _port_entry("", parts[0], parts[1], proto)
|
|
119
|
+
return _port_entry(parts[0], parts[1], parts[2], proto)
|
|
120
|
+
if isinstance(spec, dict):
|
|
121
|
+
target = spec.get("target")
|
|
122
|
+
if target is None:
|
|
123
|
+
return None
|
|
124
|
+
proto = _as_str(spec.get("protocol")) or "tcp"
|
|
125
|
+
published = spec.get("published")
|
|
126
|
+
return _port_entry(
|
|
127
|
+
_as_str(spec.get("host_ip")),
|
|
128
|
+
"" if published is None else str(published),
|
|
129
|
+
str(target),
|
|
130
|
+
proto,
|
|
131
|
+
)
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _parse_ports(value: Any) -> dict[str, Any]:
|
|
136
|
+
ports: dict[str, Any] = {}
|
|
137
|
+
for spec in _as_list(value):
|
|
138
|
+
entry = _parse_port(spec)
|
|
139
|
+
if entry is not None:
|
|
140
|
+
ports[entry[0]] = entry[1]
|
|
141
|
+
return ports
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _looks_like_path(source: str) -> bool:
|
|
145
|
+
return source.startswith(("/", ".", "~"))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _parse_mount(spec: Any) -> dict[str, Any] | None:
|
|
149
|
+
"""One compose volume (short "src:dst[:mode]" or long mapping) -> a Mounts item."""
|
|
150
|
+
if isinstance(spec, str):
|
|
151
|
+
parts = spec.split(":")
|
|
152
|
+
if len(parts) == 1:
|
|
153
|
+
source, destination, mode = "", parts[0], "rw"
|
|
154
|
+
elif len(parts) == 2:
|
|
155
|
+
source, destination, mode = parts[0], parts[1], "rw"
|
|
156
|
+
else:
|
|
157
|
+
source, destination, mode = parts[0], parts[1], parts[2]
|
|
158
|
+
mount_type = "bind" if _looks_like_path(source) else "volume"
|
|
159
|
+
return {
|
|
160
|
+
"Type": mount_type,
|
|
161
|
+
"Source": source,
|
|
162
|
+
"Destination": destination,
|
|
163
|
+
"RW": "ro" not in mode.split(","),
|
|
164
|
+
"Mode": mode,
|
|
165
|
+
}
|
|
166
|
+
if isinstance(spec, dict):
|
|
167
|
+
source = _as_str(spec.get("source"))
|
|
168
|
+
mount_type = _as_str(spec.get("type")) or ("bind" if _looks_like_path(source) else "volume")
|
|
169
|
+
read_only = spec.get("read_only") is True
|
|
170
|
+
return {
|
|
171
|
+
"Type": mount_type,
|
|
172
|
+
"Source": source,
|
|
173
|
+
"Destination": _as_str(spec.get("target")),
|
|
174
|
+
"RW": not read_only,
|
|
175
|
+
"Mode": "ro" if read_only else "rw",
|
|
176
|
+
}
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _parse_mounts(value: Any) -> list[dict[str, Any]]:
|
|
181
|
+
mounts = []
|
|
182
|
+
for spec in _as_list(value):
|
|
183
|
+
mount = _parse_mount(spec)
|
|
184
|
+
if mount is not None:
|
|
185
|
+
mounts.append(mount)
|
|
186
|
+
return mounts
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _parse_devices(value: Any) -> list[dict[str, str]]:
|
|
190
|
+
devices = []
|
|
191
|
+
for spec in _as_list(value):
|
|
192
|
+
if not isinstance(spec, str):
|
|
193
|
+
continue
|
|
194
|
+
parts = spec.split(":")
|
|
195
|
+
host = parts[0]
|
|
196
|
+
container = parts[1] if len(parts) > 1 else host
|
|
197
|
+
devices.append({"PathOnHost": host, "PathInContainer": container})
|
|
198
|
+
return devices
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _to_inspect(name: str, service: dict[str, Any]) -> dict[str, Any]:
|
|
202
|
+
config: dict[str, Any] = {
|
|
203
|
+
"Image": _as_str(service.get("image")),
|
|
204
|
+
"User": _as_str(service.get("user")),
|
|
205
|
+
"Env": _env(service.get("environment")),
|
|
206
|
+
}
|
|
207
|
+
healthcheck = _healthcheck(service)
|
|
208
|
+
if healthcheck is not None:
|
|
209
|
+
config["Healthcheck"] = healthcheck
|
|
210
|
+
|
|
211
|
+
host_config: dict[str, Any] = {
|
|
212
|
+
"Privileged": bool(service.get("privileged")),
|
|
213
|
+
"ReadonlyRootfs": bool(service.get("read_only")),
|
|
214
|
+
"SecurityOpt": _str_list(service.get("security_opt")) or [],
|
|
215
|
+
"PidMode": _as_str(service.get("pid")),
|
|
216
|
+
"NetworkMode": _as_str(service.get("network_mode")),
|
|
217
|
+
"IpcMode": _as_str(service.get("ipc")),
|
|
218
|
+
"UTSMode": _as_str(service.get("uts")),
|
|
219
|
+
}
|
|
220
|
+
cap_add = _str_list(service.get("cap_add"))
|
|
221
|
+
if cap_add is not None:
|
|
222
|
+
host_config["CapAdd"] = cap_add
|
|
223
|
+
cap_drop = _str_list(service.get("cap_drop"))
|
|
224
|
+
if cap_drop is not None:
|
|
225
|
+
host_config["CapDrop"] = cap_drop
|
|
226
|
+
memory = _service_memory(service)
|
|
227
|
+
if memory:
|
|
228
|
+
host_config["Memory"] = memory
|
|
229
|
+
devices = _parse_devices(service.get("devices"))
|
|
230
|
+
if devices:
|
|
231
|
+
host_config["Devices"] = devices
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
"Name": "/" + name,
|
|
235
|
+
"Config": config,
|
|
236
|
+
"HostConfig": host_config,
|
|
237
|
+
"NetworkSettings": {"Ports": _parse_ports(service.get("ports"))},
|
|
238
|
+
"Mounts": _parse_mounts(service.get("volumes")),
|
|
239
|
+
"State": {"Status": "n/a"},
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def parse_compose(path: str | Path) -> list[Container]:
|
|
244
|
+
"""Parse a docker-compose.yml into Container models via the existing inspect pipeline."""
|
|
245
|
+
try:
|
|
246
|
+
import yaml # optional extra, installed via the [compose] group in pyproject
|
|
247
|
+
except ImportError as exc:
|
|
248
|
+
raise RuntimeError(
|
|
249
|
+
"compose support needs PyYAML: install docker-host-audit[compose]"
|
|
250
|
+
) from exc
|
|
251
|
+
|
|
252
|
+
data = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
|
|
253
|
+
services = _as_dict(_as_dict(data).get("services"))
|
|
254
|
+
objects = [
|
|
255
|
+
_to_inspect(str(name), svc) for name, svc in services.items() if isinstance(svc, dict)
|
|
256
|
+
]
|
|
257
|
+
return parse_inspect(objects)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Load optional TOML configuration. Stdlib-only, read-only.
|
|
2
|
+
|
|
3
|
+
The config file sets defaults for a few CLI options. CLI flags always win
|
|
4
|
+
over the file; the file wins over the built-in defaults. See `cli.py` for
|
|
5
|
+
how the merge is applied.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import tomllib
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
# key -> expected python type. `ignore` is a list of strings, handled separately.
|
|
15
|
+
_STR_KEYS = ("min_severity", "fail_on", "format")
|
|
16
|
+
_BOOL_KEYS = ("include_host", "include_stopped")
|
|
17
|
+
_RECOGNISED = ("ignore", *_STR_KEYS, *_BOOL_KEYS)
|
|
18
|
+
|
|
19
|
+
_DISCOVERY = ("container-audit.toml", ".container-audit.toml")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _validate(data: dict[str, Any]) -> dict[str, Any]:
|
|
23
|
+
result: dict[str, Any] = {}
|
|
24
|
+
for key, value in data.items():
|
|
25
|
+
if key not in _RECOGNISED:
|
|
26
|
+
raise ValueError(f"unknown config key: {key!r}")
|
|
27
|
+
if key == "ignore":
|
|
28
|
+
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
|
29
|
+
raise ValueError("config key 'ignore' must be a list of strings")
|
|
30
|
+
elif key in _STR_KEYS:
|
|
31
|
+
if not isinstance(value, str):
|
|
32
|
+
raise ValueError(f"config key {key!r} must be a string")
|
|
33
|
+
elif not isinstance(value, bool): # _BOOL_KEYS
|
|
34
|
+
raise ValueError(f"config key {key!r} must be a boolean")
|
|
35
|
+
result[key] = value
|
|
36
|
+
return result
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load_config(path: str | None, cwd: Path) -> dict[str, Any]:
|
|
40
|
+
"""Return recognised config keys from `path`, or auto-discovered file, or {}.
|
|
41
|
+
|
|
42
|
+
Raises ValueError on a missing explicit path, malformed TOML, an unknown
|
|
43
|
+
key, or a wrong value type.
|
|
44
|
+
"""
|
|
45
|
+
if path is not None:
|
|
46
|
+
config_path: Path | None = Path(path)
|
|
47
|
+
else:
|
|
48
|
+
config_path = next((cwd / name for name in _DISCOVERY if (cwd / name).is_file()), None)
|
|
49
|
+
if config_path is None:
|
|
50
|
+
return {}
|
|
51
|
+
|
|
52
|
+
try:
|
|
53
|
+
raw = config_path.read_bytes()
|
|
54
|
+
except FileNotFoundError:
|
|
55
|
+
raise ValueError(f"config file not found: {config_path}") from None
|
|
56
|
+
except OSError as exc:
|
|
57
|
+
raise ValueError(f"cannot read config file ({type(exc).__name__})") from None
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
data = tomllib.loads(raw.decode("utf-8"))
|
|
61
|
+
except (tomllib.TOMLDecodeError, UnicodeDecodeError) as exc:
|
|
62
|
+
raise ValueError(f"invalid config file: {exc}") from None
|
|
63
|
+
|
|
64
|
+
return _validate(data)
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
"""Check registry. Each submodule exposes `CHECKS: list[CheckFn]`; we aggregate them."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
from ca.models import CheckFn
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
def get_checks() -> list[CheckFn]:
|
|
9
|
-
"""Every registered check, across all submodules."""
|
|
10
|
-
from ca.checks import exposure, hardening, images, privilege
|
|
11
|
-
|
|
12
|
-
return [*privilege.CHECKS, *exposure.CHECKS, *hardening.CHECKS, *images.CHECKS]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|