diff --git a/bridge_test.go b/bridge_test.go index ae9c2c5..e0de81c 100644 --- a/bridge_test.go +++ b/bridge_test.go @@ -983,3 +983,26 @@ func TestNewHTTPServer_BoundsEveryPhase(t *testing.T) { t.Errorf("short bound: header=%v read=%v, want 1s for both", short.ReadHeaderTimeout, short.ReadTimeout) } } + +func TestBuildSyslogStripsControlChars(t *testing.T) { + ts := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + got := buildSyslog(13, ts, "h", "app", "a\x1b[2Jb\x00c\td\x7fe") + want := "<13>1 2026-01-02T03:04:05.000Z h app - - - a [2Jb c d e" + if got != want { + t.Errorf("buildSyslog =\n %q\nwant\n %q", got, want) + } +} + +// A request that is waiting for the forwarder must return once its context +// ends, rather than queue behind a busy connection forever. +func TestForwarderSendHonoursContextWhileBusy(t *testing.T) { + f := newForwarder("tcp", "127.0.0.1:1", false, time.Second) + f.gate <- struct{}{} + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + err := f.send(ctx, []byte("x")) + if !errors.Is(err, context.Canceled) { + t.Fatalf("send error = %v, want one wrapping context.Canceled", err) + } +} diff --git a/main.go b/main.go index 08e0681..392bb0e 100644 --- a/main.go +++ b/main.go @@ -11,6 +11,7 @@ package main import ( "context" + "crypto/sha256" "crypto/subtle" "crypto/tls" "errors" @@ -212,7 +213,7 @@ func (s *server) handle(w http.ResponseWriter, r *http.Request) { return } if s.authHeader != "" && - subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte(s.authHeader)) != 1 { + !authMatches(r.Header.Get("Authorization"), s.authHeader) { http.Error(w, "unauthorized", http.StatusUnauthorized) return } @@ -238,12 +239,23 @@ func (s *server) handle(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } +// authMatches compares the presented Authorization header with the configured +// value by SHA-256 digest, so the comparison time does not reveal the expected +// token's length. +func authMatches(got, want string) bool { + g := sha256.Sum256([]byte(got)) + w := sha256.Sum256([]byte(want)) + return subtle.ConstantTimeCompare(g[:], w[:]) == 1 +} + // buildSyslog renders one RFC 5424 message: // // 1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG // // PROCID, MSGID and STRUCTURED-DATA are nil ("-"); MSG carries the JSON body -// collapsed to a single line so it stays one syslog record. +// collapsed to a single line so it stays one syslog record. Every control +// character (C0, DEL and C1) in the body is replaced by a space, so a body +// cannot inject terminal escapes or extra records. func buildSyslog(pri int, ts time.Time, host, app, msg string) string { if host == "" { host = "-" @@ -251,7 +263,12 @@ func buildSyslog(pri int, ts time.Time, host, app, msg string) string { if app == "" { app = "-" } - msg = strings.NewReplacer("\n", " ", "\r", " ").Replace(msg) + msg = strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f || (r >= 0x80 && r <= 0x9f) { + return ' ' + } + return r + }, msg) return fmt.Sprintf("<%d>1 %s %s %s - - - %s", pri, ts.UTC().Format("2006-01-02T15:04:05.000Z07:00"), host, app, msg) } @@ -280,12 +297,16 @@ type forwarder struct { // certificate instead of the system root pool. tlsConfig *tls.Config + // gate is a one-slot semaphore taken before mu so a waiting request gives up + // when its context ends instead of queuing forever behind a hung collector. + gate chan struct{} + mu sync.Mutex conn net.Conn } func newForwarder(network, addr string, useTLS bool, dialTimeout time.Duration) *forwarder { - return &forwarder{network: network, addr: addr, useTLS: useTLS, dialTimeout: dialTimeout} + return &forwarder{network: network, addr: addr, useTLS: useTLS, dialTimeout: dialTimeout, gate: make(chan struct{}, 1)} } func (f *forwarder) dial(ctx context.Context) error { @@ -312,6 +333,12 @@ func (f *forwarder) dial(ctx context.Context) error { } func (f *forwarder) send(ctx context.Context, frame []byte) error { + select { + case f.gate <- struct{}{}: + case <-ctx.Done(): + return fmt.Errorf("wait for syslog connection: %w", ctx.Err()) + } + defer func() { <-f.gate }() f.mu.Lock() defer f.mu.Unlock() if f.conn != nil && !f.alive() { diff --git a/specs.md b/specs.md index 486a603..db3c132 100644 --- a/specs.md +++ b/specs.md @@ -49,8 +49,8 @@ Single flat package (`main`): `main.go` (relay + config + server logic), `bridge - Forwards the received JSON body verbatim (schema-agnostic; does not parse, validate, or understand audit events) - Prefers TCP over UDP for audit/compliance trails (UDP has no delivery confirmation; TCP surfaces a dead collector as a 502) - Connection reuse: lazily dials once, then reuses; before each TCP write a short read probe (5 ms) checks whether the collector has closed the connection, and the bridge redials if it has; on write error, closes and reconnects once before surfacing the error. The probe is best-effort, not a delivery guarantee: a collector close whose FIN/RST lands after the probe goes unnoticed, and one record may then be written into the dead connection (reported as `204`: written to connection, best effort); the next write detects the close and reconnects, returning `204` on successful retry or `502` if the retry fails. Syslog framing has no acknowledgement, so this cannot be closed without a different transport -- Write deadline per frame (5s default) prevents a collector that accepts but does not drain from blocking indefinitely and wedging the handler behind the connection mutex -- RFC 5424 compliance: formats message as `1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG`; collapses embedded newlines/CRs to spaces so each syslog record is one line; PROCID, MSGID, STRUCTURED-DATA are "-" +- Write deadline per frame (5s default) prevents a collector that accepts but does not drain from blocking indefinitely and wedging the handler behind the connection mutex; a request waiting for that mutex gives up when its request context ends (the wait is cancelled with the request) +- RFC 5424 compliance: formats message as `1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID STRUCTURED-DATA MSG`; replaces every control character (C0, DEL and C1) in the body with a space, so each syslog record is one line and a body cannot inject terminal escapes or extra records; PROCID, MSGID, STRUCTURED-DATA are "-" - `APP_NAME` and `SYSLOG_HOSTNAME` are validated at startup the same way `FACILITY`/`SEVERITY` are: each must be 1*max PRINTUSASCII (RFC 5424 %d33-126, no spaces or control bytes), APP-NAME capped at 48 bytes and HOSTNAME at 255 bytes, or `newServer` rejects the config before the process starts serving. An empty value is accepted and rendered as the RFC 5424 nil value `-`; when `SYSLOG_HOSTNAME` is empty the OS hostname is used instead, and an OS hostname that fails the same check (or can't be read) falls back to `-` ## Dependencies