Skip to content

Commit c874aad

Browse files
authored
fix: deny attach and refuse protocol upgrades in all three (#76) (#79)
* spec: deny attach in the router model (#76) * test: pin the attach deny and the upgrade refusal (#76) * fix: deny attach and refuse protocol upgrades in all three (#76)
1 parent 2bdc552 commit c874aad

17 files changed

Lines changed: 611 additions & 41 deletions

‎AGENTS.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,17 @@ deploy/ — Docker Compose + integration tests
3939
- Zero external deps where possible (Go: yaml.v3, Rust: tokio/hyper/serde/clap, TS: yaml)
4040

4141
## Test Coverage
42-
- Go: 108 unit tests (main/listener: 24, policy: 10, middleware: 25, proxy: 45, audit: 4)
43-
- Rust: 140 unit tests (main/listener: 23, policy: 15, middleware: 41, proxy: 46, handler: 9, audit: 4, transport: 2)
44-
- TypeScript: 157 unit tests, 1 skipped (flags: 44, listen: 13 incl. 1 skipped concurrency test (#46), middleware: 32, proxy: 33, policy: 10, handler: 11, shutdown: 5, transport: 5, audit: 4)
45-
- Integration, per implementation: 50 tests via deploy/test.sh and 15 socket tests via deploy/test-sock.sh (docker-compose)
46-
- Quint: `make test-spec` runs the `spec/listener.qnt` `run` tests (instances `listener_locked`, `listener_unlocked`) and the `spec/router.qnt` `run` tests (instances `router`, `router_pre48`, `router_pre53`, `router_pre55`, and `router_readonly`, whose `readonly*` tests run with `--match`)
42+
- Go: 110 unit tests (main/listener: 24, policy: 10, middleware: 25, proxy: 47, audit: 4)
43+
- Rust: 142 unit tests (main/listener: 23, policy: 15, middleware: 41, proxy: 47, handler: 10, audit: 4, transport: 2)
44+
- TypeScript: 160 unit tests, 1 skipped (flags: 44, listen: 13 incl. 1 skipped concurrency test (#46), middleware: 32, proxy: 34, policy: 10, handler: 13, shutdown: 5, transport: 5, audit: 4)
45+
- Integration, per implementation: 53 tests via deploy/test.sh and 15 socket tests via deploy/test-sock.sh (docker-compose)
46+
- Quint: `make test-spec` runs the `spec/listener.qnt` `run` tests (instances `listener_locked`, `listener_unlocked`) and the `spec/router.qnt` `run` tests (instances `router`, `router_pre48`, `router_pre53`, `router_pre55`, `router_readonly`, whose `readonly*` tests run with `--match`, and `router_pre76`)
4747

4848
## Test Conventions
4949
- Go: stdlib `testing` package, `go test ./...`
5050
- Rust: `#[cfg(test)]` inline modules, `cargo test`
5151
- TypeScript: `node:test` framework, `npm run build && node --test dist/*.test.js`
52-
- Integration: `make test-integration` (50 test cases) and `make test-integration-sock` (15 socket cases) via Docker Compose
52+
- Integration: `make test-integration` (53 test cases) and `make test-integration-sock` (15 socket cases) via Docker Compose
5353

5454
## Contribution Workflow
5555

‎Makefile‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ test-spec:
103103
$(QUINT) test $(ROUTER_SPEC) --main=router_pre53
104104
$(QUINT) test $(ROUTER_SPEC) --main=router_pre55
105105
$(QUINT) test $(ROUTER_SPEC) --main=router_readonly --match='^readonly.*Test$$'
106+
$(QUINT) test $(ROUTER_SPEC) --main=router_pre76
106107

107108
verify-ts:
108109
$(QUINT) run $(SPEC) --max-steps=50 --invariants allInvariants --backend typescript

‎README.md‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Key features:
1212
- **Policy-driven**: Per-service YAML policies, selected by image name, control images, volumes, flags, and env vars. The listening socket is the trust boundary: every caller of a socket can use every policy behind it (see [Trust model](#trust-model))
1313
- **Middleware pipeline**: 4 validation gates + 1 config mutator chain
1414
- **Default-deny router**: Only explicitly allowed endpoints pass through
15-
- **Formally verified**: [Quint](https://quint-lang.org/) specification: 9 request-handling invariants, 6 listener invariants, and router properties for `--readonly`, percent-encoded paths, empty segments, exec and the container lifecycle
15+
- **Formally verified**: [Quint](https://quint-lang.org/) specification: 9 request-handling invariants, 6 listener invariants, and router properties for `--readonly`, percent-encoded paths, empty segments, exec, attach and the container lifecycle
1616
- **Audit logging**: JSON-structured logs for all requests and decisions
1717
- **Three implementations**: [Go](go/), [Rust](rs/), [TypeScript](ts/) — equal peer languages
1818
- **Minimal dependencies**: Zero external deps for Go, crate-based for Rust, npm for TypeScript
@@ -100,9 +100,9 @@ All three implementations expose the same API surface, share the same [Quint spe
100100

101101
| Language | Directory | Tests | Stack |
102102
|----------|-----------|-------|-------|
103-
| Go | [go/](go/) | 108 unit + 50 integration + 15 socket | stdlib net/http + yaml.v3 |
104-
| Rust | [rs/](rs/) | 140 unit + 50 integration + 15 socket | tokio, hyper, serde, clap |
105-
| TypeScript | [ts/](ts/) | 157 unit (1 skipped) + 50 integration + 15 socket | Node 22 ESM, built-in http |
103+
| Go | [go/](go/) | 110 unit + 53 integration + 15 socket | stdlib net/http + yaml.v3 |
104+
| Rust | [rs/](rs/) | 142 unit + 53 integration + 15 socket | tokio, hyper, serde, clap |
105+
| TypeScript | [ts/](ts/) | 160 unit (1 skipped) + 53 integration + 15 socket | Node 22 ESM, built-in http |
106106

107107
### Build All
108108

@@ -198,20 +198,22 @@ docker pull attacker/malware:latest # denied: image not in allowlist
198198
| EnvFileGate | Gate | Strips `Env` field from create body; env must come from locked `env_file` |
199199
| CmdGate | Gate | Validates each CLI flag in `Cmd` array against allowlist + denylist |
200200

201-
The chain runs only on container create. `--readonly` is not a gate: the router denies every request that is not `GET` or `HEAD`, on every path, before any other check ([#75](https://github.com/ChainSafe/docker-socket-policy/issues/75)). A websocket attach (`GET /containers/{name}/attach/ws` with `Upgrade`) is a `GET` and is not denied yet; the Go proxy lets it write to a container's stdin ([#76](https://github.com/ChainSafe/docker-socket-policy/issues/76)).
201+
The chain runs only on container create. `--readonly` is not a gate: the router denies every request that is not `GET` or `HEAD`, on every path, before any other check ([#75](https://github.com/ChainSafe/docker-socket-policy/issues/75)). Attach is denied by the router for every method, so a websocket attach (`GET /containers/{name}/attach/ws`) cannot reach a container's stdin, with or without `--readonly` ([#76](https://github.com/ChainSafe/docker-socket-policy/issues/76)).
202202

203203
## Endpoint Access
204204

205205
| HTTP Method | Path | Action |
206206
|-------------|------|--------|
207-
| Not GET/HEAD | Any (with `--readonly`) | **DENIED** (checked first) |
207+
| Any | Request with an `Upgrade` header, or `Connection: upgrade` | **DENIED** (checked before routing) |
208+
| Not GET/HEAD | Any (with `--readonly`) | **DENIED** (checked first in the router) |
208209
| Any | Path containing `%` | **DENIED** (see below) |
209210
| Any | Path containing `//` | **DENIED** |
210211
| POST | `/containers/create` | Validated by middleware chain |
211212
| POST | `/containers/{name}/start\|stop\|restart\|kill\|wait\|pause\|unpause` | Allowed on known containers |
212213
| DELETE | `/containers/{name}` | Allowed on known containers |
213214
| Any | `/containers/…/exec` (an `exec` segment anywhere under `/containers`) | **DENIED** |
214215
| Any | `/exec/*` | **DENIED** |
216+
| Any | `/containers/{name}/attach…` (an `attach` segment anywhere under `/containers`) | **DENIED** |
215217
| POST | `/containers/{name}/rename\|update` | **DENIED** |
216218
| POST | `/images/create` | Validated by registry gate |
217219
| POST | `/auth` | **DENIED** |
@@ -224,6 +226,8 @@ Any request whose path contains a percent-encoded byte (`%`) is denied with 403
224226

225227
Exec is matched on whole path segments, so containers named like `exec-runner` work normally, and exec inspect (`GET /exec/{id}/json`) is denied too. A path with an empty segment (`//`, as in `//exec/{id}/json`) is denied for every method, so an empty segment cannot hide the exec namespace; a single trailing slash is fine, and `//` in the query string is not inspected. Absolute-form request targets (`GET http://host/…`) never reach exec: Go and Rust route them on the parsed path, so exec is denied and other paths are routed as usual, while the TypeScript proxy sees the raw target and denies every absolute-form request (its `//` after the scheme is an empty segment). The Docker CLI never sends absolute form.
226228

229+
Attach is matched the same way: an `attach` segment under `/containers` is denied for every method, so `attach-runner` is an ordinary name, while a container literally named `attach` cannot be reached by name. Protocol upgrades are refused outright: any request with an `Upgrade` header, or a `Connection` header that lists `upgrade`, gets 403 `protocol upgrade not allowed` before it is routed, whatever its path ([#76](https://github.com/ChainSafe/docker-socket-policy/issues/76)). Forwarding one would hand the caller a raw stream to the daemon. Every Docker endpoint that upgrades (attach, exec start, the build session) is denied anyway; the refusal keeps any path the router allows from becoming one.
230+
227231
## Configuration
228232

229233
### CLI Flags
@@ -441,7 +445,7 @@ not at the socket.
441445

442446
## Formal Verification
443447

444-
This project includes a [Quint](https://quint-lang.org/) formal specification that models the security invariants as a state machine. Random-simulation verification runs 10,000 sampled traces of up to 100 steps each, checking all 9 invariants on every state transition. A second module, `spec/listener.qnt`, models listening-socket startup (group selection, existing-path checks, the single-instance lock) with 6 more invariants. A third module, `spec/router.qnt`, models the router's denies for writes under `--readonly` ([#75](https://github.com/ChainSafe/docker-socket-policy/issues/75)), percent-encoded paths ([#53](https://github.com/ChainSafe/docker-socket-policy/issues/53)), empty interior segments ([#55](https://github.com/ChainSafe/docker-socket-policy/issues/55)) and exec ([#49](https://github.com/ChainSafe/docker-socket-policy/issues/49)), the `POST /containers/create` route, container-name extraction and the container-lifecycle branch, not the full routing table ([#24](https://github.com/ChainSafe/docker-socket-policy/issues/24), [#48](https://github.com/ChainSafe/docker-socket-policy/issues/48)). Its 8 properties are checked exhaustively over the methods `GET`, `HEAD`, `POST`, `DELETE` and every path of 1 to 3 segments over the model's word set; exec is denied by the router, not by a middleware gate.
448+
This project includes a [Quint](https://quint-lang.org/) formal specification that models the security invariants as a state machine. Random-simulation verification runs 10,000 sampled traces of up to 100 steps each, checking all 9 invariants on every state transition. A second module, `spec/listener.qnt`, models listening-socket startup (group selection, existing-path checks, the single-instance lock) with 6 more invariants. A third module, `spec/router.qnt`, models the router's denies for writes under `--readonly` ([#75](https://github.com/ChainSafe/docker-socket-policy/issues/75)), percent-encoded paths ([#53](https://github.com/ChainSafe/docker-socket-policy/issues/53)), empty interior segments ([#55](https://github.com/ChainSafe/docker-socket-policy/issues/55)), exec ([#49](https://github.com/ChainSafe/docker-socket-policy/issues/49)) and attach ([#76](https://github.com/ChainSafe/docker-socket-policy/issues/76)), the `POST /containers/create` route, container-name extraction and the container-lifecycle branch, not the full routing table ([#24](https://github.com/ChainSafe/docker-socket-policy/issues/24), [#48](https://github.com/ChainSafe/docker-socket-policy/issues/48)). Its 9 properties are checked exhaustively over the methods `GET`, `HEAD`, `POST`, `DELETE` and every path of 1 to 3 segments over the model's word set; exec is denied by the router, not by a middleware gate.
445449

446450
The CI pipeline runs verification on every push and PR. A violation blocks the build.
447451

‎deploy/test.sh‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
# Sends HTTP requests directly to the proxy's Docker API and checks status codes,
44
# and the deny message on every expected proxy 403.
55
# The proxy's RegistryGate, MountSourceGate, EnvFileGate, CmdGate, and
6-
# ContainerConfigMutator are all exercised; exec is denied by the router, and so
7-
# is every write on a second proxy run with --readonly (#75).
6+
# ContainerConfigMutator are all exercised; exec and attach are denied by the
7+
# router, protocol upgrades by the handler (#76), and every write on a second
8+
# proxy run with --readonly (#75).
89

910
set -e
1011

@@ -448,6 +449,30 @@ S="${S:-000}"
448449
check_denied "GET http://docker/exec/*/json -> 403 (absolute-form target)" "$S" "$BODY" \
449450
'exec is not allowed' 'empty path segment not allowed'
450451

452+
# #76: attach is denied by the router for every method, and any protocol
453+
# upgrade is refused by the handler before routing. Before #76 a websocket
454+
# attach went through the GET passthrough and Go relayed the daemon's 101,
455+
# handing the caller the container's stdin. The target is this test
456+
# container (its hostname is its short ID), so on a proxy without the fix the
457+
# daemon answers 101, not 404. curl does not speak websocket over http://, so
458+
# it reports the status and waits for the body until --max-time.
459+
upgrade_get() {
460+
: >"$BODY"
461+
out=$(curl -s -o "$BODY" -w '%{http_code}' $TIMEOUT --unix-socket "$PROXY_SOCK" \
462+
-H 'Upgrade: websocket' -H 'Connection: Upgrade' -H 'Sec-WebSocket-Version: 13' \
463+
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' "$1" 2>/dev/null || true)
464+
echo "${out:-000}"
465+
}
466+
467+
S=$(upgrade_get "$PROXY/containers/$(hostname)/attach/ws?stdin=1&stream=1")
468+
check_denied "GET /containers/*/attach/ws with Upgrade: websocket -> 403 (upgrade refused)" "$S" "$BODY" 'protocol upgrade not allowed'
469+
470+
S=$(get_status "$PROXY/containers/no-such-container/attach/ws")
471+
check_denied "GET /containers/*/attach/ws -> 403 (attach denied)" "$S" "$BODY" 'attach is not allowed'
472+
473+
S=$(upgrade_get "$PROXY/_ping")
474+
check_denied "GET /_ping with Upgrade: websocket -> 403 (upgrade refused)" "$S" "$BODY" 'protocol upgrade not allowed'
475+
451476
# ─── Read-only mode (#75) ────────────────────────────────
452477

453478
# The same config behind --readonly. Every request whose method is not GET or

‎go/internal/proxy/handler.go‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"io"
77
"log/slog"
88
"net/http"
9+
"strings"
910

1011
"github.com/ChainSafe/docker-socket-policy/go/internal/audit"
1112
"github.com/ChainSafe/docker-socket-policy/go/internal/middleware"
@@ -32,6 +33,16 @@ func NewHandler(router *Router, chain *middleware.Chain, auditLog *audit.Logger,
3233
}
3334

3435
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
36+
// Refuse protocol upgrades before anything else: the reverse proxy would
37+
// relay a 101 and hand the caller a raw stream to the daemon (#76).
38+
if isUpgradeRequest(r.Header) {
39+
const msg = "protocol upgrade not allowed"
40+
slog.Warn("denied", "method", r.Method, "path", r.URL.EscapedPath(), "reason", msg)
41+
h.auditLog.Deny(r.Method, r.RequestURI, msg, map[string]interface{}{"method": r.Method, "path": r.URL.EscapedPath()})
42+
http.Error(w, msg, http.StatusForbidden)
43+
return
44+
}
45+
3546
body, err := io.ReadAll(r.Body)
3647
if err != nil {
3748
slog.Warn("failed to read request body", "error", err)
@@ -96,3 +107,19 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
96107

97108
h.transport.ServeHTTP(w, r)
98109
}
110+
111+
// isUpgradeRequest reports an Upgrade header, or a Connection header that
112+
// lists the upgrade token.
113+
func isUpgradeRequest(h http.Header) bool {
114+
if _, ok := h["Upgrade"]; ok {
115+
return true
116+
}
117+
for _, v := range h.Values("Connection") {
118+
for _, tok := range strings.Split(v, ",") {
119+
if strings.EqualFold(strings.TrimSpace(tok), "upgrade") {
120+
return true
121+
}
122+
}
123+
}
124+
return false
125+
}

‎go/internal/proxy/handler_test.go‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,3 +377,79 @@ container_config:
377377
t.Fatalf("ContentLength %d does not match body size %d", rec.lastRequest.ContentLength, len(forwardedBody))
378378
}
379379
}
380+
381+
// #76: any protocol upgrade is refused before the body is read and before
382+
// routing, so the transport never sees it. Before #76 a websocket attach went
383+
// through the GET passthrough and Go relayed the daemon's 101.
384+
func TestHandlerRefusesProtocolUpgrade(t *testing.T) {
385+
dir := t.TempDir()
386+
os.WriteFile(filepath.Join(dir, "default.yaml"), []byte("service_name: default\nallowed_image_prefixes:\n - scratch\n"), 0644)
387+
policyManager, err := policy.NewManager(dir)
388+
if err != nil {
389+
t.Fatalf("NewManager failed: %v", err)
390+
}
391+
logPath := filepath.Join(t.TempDir(), "audit.log")
392+
auditLog, err := audit.NewLogger(logPath)
393+
if err != nil {
394+
t.Fatalf("NewLogger failed: %v", err)
395+
}
396+
defer auditLog.Close()
397+
const refused = "protocol upgrade not allowed"
398+
399+
tests := []struct {
400+
name string
401+
target string
402+
headers map[string]string
403+
}{
404+
{"websocket", "/containers/json", map[string]string{"Upgrade": "websocket", "Connection": "Upgrade"}},
405+
{"connection token only", "/_ping", map[string]string{"Connection": "keep-alive, Upgrade"}},
406+
{"upgrade header only", "/_ping", map[string]string{"Upgrade": "h2c"}},
407+
}
408+
var mismatches []string
409+
for _, tt := range tests {
410+
rec := &recorderTransport{}
411+
h := NewHandler(NewRouter(policyManager), middleware.NewChain(), auditLog, rec)
412+
req := httptest.NewRequest("GET", tt.target, nil)
413+
for k, v := range tt.headers {
414+
req.Header.Set(k, v)
415+
}
416+
w := httptest.NewRecorder()
417+
h.ServeHTTP(w, req)
418+
if got := strings.TrimSpace(w.Body.String()); w.Code != http.StatusForbidden || got != refused {
419+
mismatches = append(mismatches, tt.name+": "+http.StatusText(w.Code)+" "+got)
420+
}
421+
if rec.lastRequest != nil {
422+
mismatches = append(mismatches, tt.name+": forwarded")
423+
}
424+
}
425+
426+
rec := &recorderTransport{}
427+
h := NewHandler(NewRouter(policyManager), middleware.NewChain(), auditLog, rec)
428+
w := httptest.NewRecorder()
429+
h.ServeHTTP(w, httptest.NewRequest("GET", "/containers/json", nil))
430+
if w.Code != http.StatusOK || rec.lastRequest == nil {
431+
mismatches = append(mismatches, "plain GET /containers/json: not forwarded")
432+
}
433+
434+
data, err := os.ReadFile(logPath)
435+
if err != nil {
436+
t.Fatalf("reading audit log: %v", err)
437+
}
438+
lines := strings.Split(strings.TrimSpace(string(data)), "\n")
439+
var entry struct {
440+
Method string `json:"method"`
441+
URI string `json:"uri"`
442+
Decision string `json:"decision"`
443+
Reason string `json:"reason"`
444+
}
445+
if err := json.Unmarshal([]byte(lines[0]), &entry); err != nil {
446+
t.Fatalf("audit line 0: %v", err)
447+
}
448+
if entry.Method != "GET" || entry.URI != "/containers/json" || entry.Decision != "DENY" || entry.Reason != refused {
449+
mismatches = append(mismatches, "audit entry: "+lines[0])
450+
}
451+
452+
if len(mismatches) > 0 {
453+
t.Fatalf("protocol upgrade mismatches:\n%s", strings.Join(mismatches, "\n"))
454+
}
455+
}

‎go/internal/proxy/router.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ func (r *Router) Route(method, path string, body map[string]interface{}) *RouteR
7171
return &RouteResult{Action: ActionDeny, DenyMsg: "exec is not allowed"}
7272
}
7373

74+
if isAttachPath(path) {
75+
return &RouteResult{Action: ActionDeny, DenyMsg: "attach is not allowed"}
76+
}
77+
7478
if strings.HasPrefix(path, "/build") {
7579
return &RouteResult{Action: ActionDeny, DenyMsg: "build is not allowed"}
7680
}
@@ -216,6 +220,13 @@ func isExecPath(path string) bool {
216220
return segs[0] == "exec" || (segs[0] == "containers" && slices.Contains(segs[1:], "exec"))
217221
}
218222

223+
// isAttachPath matches attach on whole segments after /containers, so a name
224+
// like attach-runner is not attach (#76).
225+
func isAttachPath(path string) bool {
226+
segs := strings.Split(strings.TrimPrefix(path, "/"), "/")
227+
return segs[0] == "containers" && slices.Contains(segs[1:], "attach")
228+
}
229+
219230
// reservedContainerSegments are Docker endpoints that sit where a container
220231
// name would: /containers/json lists, /containers/create creates. Treating one
221232
// as a container name routes the request down the lifecycle path, where an

0 commit comments

Comments
 (0)