6 Commits
Author SHA1 Message Date
Eirik Botten Nicolaysen bea911a3de Reject the empty HTTP/2 field name (#563)
`isValidFieldName` validates a field name with `allSatisfy` over the
tchar set. `allSatisfy` returns `true` for an empty collection, so the
empty field name passes.

The file already states the rule it is implementing. The doc comment at
line 312 quotes:

```
token          = 1*tchar
```

The derivation that follows is correct — I expanded `0x21, 0x23...0x27,
0x2a, 0x2b, 0x2d, 0x2e, 0x30...0x39, 0x5e...0x7a, 0x7c, 0x7e` byte by
byte against tchar minus `A-Z` and every one of the four rewriting steps
in lines 315-341 holds, including the `%x5E-60 / %x61-7A` → `%x5E-7A`
collapse. It is the `1*` quantifier that is missing: the code implements
`*tchar`.

### Scope

All three block types accept an empty name today, since they share
`HeaderFieldName.init`:

```
request:  empty name -> accepted
response: empty name -> accepted
trailers: empty name -> accepted
```

An empty name serialises as `: value`, and RFC 9113 § 8.2.1 lists field
names as something a recipient is required to validate and treat as
malformed when the generic syntax is violated. This is a conformance gap
in a validator that already does the rest of that section — the
uppercase check, the CR/LF/NUL value check and the connection-specific
header check are all there.

(`":"` alone is already rejected, though as `unknownPseudoHeader` rather
than a name error, since `dropFirst()` leaves an empty base name that
matches no known pseudo-header. That path is unchanged here.)

### The change

An explicit early return, mirroring the shape swift-http-types uses for
the same production in `tokenValidity`:

```swift
if buffer.isEmpty {
    return .invalid
}
```

### Tests

Added to `HTTP2FramePayloadToHTTP1CodecCRLFTests.swift`, which already
exercises `validateRequestBlock`, `validateResponseBlock` and
`validateTrailersBlock` directly for the § 8.2.1 value rules. Five
cases: the empty name in each of the three block types, plus `"a b"` and
an ordinary `x-custom-header` to keep the surrounding behaviour pinned.

### Verification

**I could not run `swift test` here**: this machine has Command Line
Tools without XCTest, so the test targets fail at `import XCTest` with
`no such module`. Pre-existing and unrelated — it reproduces on an
unmodified checkout (18 occurrences). **CI should be the authority;
treat my local run as unverified.**

`swift build` succeeds. I linked a throwaway executable against
`NIOHTTP2` to exercise the change directly:

```
PASS request:  empty name       -> rejected
PASS response: empty name       -> rejected
PASS trailers: empty name       -> rejected
PASS request:  "a b"            -> rejected
PASS request:  "Host" (uppercase) -> rejected
PASS request:  valid name       -> accepted
PASS request:  pseudo-headers only -> accepted
```

Before the change the first three were accepted.

### Conflicts

No open PR touches `HPACKHeaders+Validation.swift`. #531 and #562 touch
NIOHPACK, and #531 (`+ Fix a bug`) is about `isASCII` in
`HPACKHeader.swift` — no overlap with `isValidFieldName`.
2026-09-01 05:16:30 +00:00
abhinav9-coderandGeorge Barnett 45bdf67024 NIOHTTP2: reject SP and control characters in pseudo-header values (#555)
Stacks on #554 — the diff will show that commit too until it merges.

## Motivation

`isValidPseudoHeaderValue` rejects CR, LF and NUL, which is narrower
than the HTTP/1.1 request line actually needs.

`:path` ends up as the request-target in:

```
METHOD SP request-target SP HTTP-version CRLF
```

so `:path = "/a HTTP/1.1"` serializes to `GET /a HTTP/1.1 HTTP/1.1`.
Whether a recipient reads the first or the last SP-delimited token as
the version decides what the request-target actually is, which is the
usual parser-differential setup. RFC 9112 § 3.2 wants SP in a
request-target percent-encoded, and bare HTAB and the other CTLs aren't
valid there either.

None of the HTTP/2 pseudo-headers have a grammar that allows SP or a
CTL: `:method` and `:protocol` are tokens, `:scheme` is a URI scheme,
`:authority` is host[:port], `:path` is a request-target, `:status` is
3DIGIT. So rejecting them doesn't reject anything well-formed.

Same severity caveat as #554: NIOHTTP1's
`uriOnlyContainsAllowedCharacters` already rejects SP in a
request-target by default, so this is hardening rather than something
exploitable on a stock pipeline.

## Modifications

`isValidPseudoHeaderValue` goes from `{0x00, 0x0A, 0x0D}` to `<= 0x20 ||
== 0x7F`, so the whole CTL range plus SP and DEL.

Bytes >= 0x80 stay allowed on purpose. They aren't delimiters in a
request line or header block, and rejecting them would break anyone
sending unencoded UTF-8 in `:path`.

### One behaviour change worth flagging

`validateRequestBlock` runs on send as well as receive, so a client
passing a URI with a raw space in it will now throw where it didn't
before. I'd argue that's the right outcome, since NIOHTTP1's validator
already rejects that URI by default and this makes the two layers agree,
but it is a behaviour change and it's the bit most likely to need
discussion. That's why I split it out of #554 instead of bundling them.

## Result

Pseudo-header values containing SP or any control character are
rejected.

## Testing

Added to `HTTP2FramePayloadToHTTP1CodecCRLFTests.swift`:

- `:path` with SP (`/a HTTP/1.1`), HTAB, VT, FF, DEL, SOH
- SP in `:authority`, `:method`, `:scheme`
- covered at the predicate, request-validation and server-codec levels

The existing positive cases in that file still pass untouched — `/`,
`/foo/bar`, `/foo?q=1&r=2`, `/foo#fragment`, `*`, `/foo%20bar`, `200` —
which is the check that this doesn't reject anything legitimate.

Built and ran on Linux, Swift 6.1 aarch64. `swift test -Xswiftc
-warnings-as-errors` is clean with no new warnings, the new tests pass,
and `swift format lint --strict Sources/ Tests/` is clean.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2026-07-22 11:34:07 +00:00
abhinav9-coder 48bfd9067d Treat CR, LF and NUL in regular header field values as malformed (#554)
## Motivation

RFC 9113 § 8.2.1 requires that a field value must not contain NUL, LF or
CR at any position, and that a message carrying one is treated as
malformed. That applies to every field value, not just pseudo-headers.

`legalHeaderField(value:)` only enforces it for pseudo-headers. The
regular-header branch checks the forbidden-name list and then returns
without looking at the value:

```swift
switch self.baseName {
case "connection", "transfer-encoding", "proxy-connection", "keep-alive", "upgrade":
    throw NIOHTTP2Errors.forbiddenHeaderField(name: String(self.baseName), value: value)
default:
    return
}
```

Nothing else on the inbound path picks it up either. HPACK values are
length-prefixed octet strings, and I couldn't find any charset
validation of values anywhere in NIOHPACK.

Where it bites is `HTTP2ToHTTP1Codec`. Serializing `name: value CRLF`
with an embedded CR or LF terminates the field early and injects header
lines into the HTTP/1.1 message downstream. Same sink as the `:path`
validation added for GHSA-4px2-pw77-vc85, just reached through a regular
field instead.

To be clear about severity: I don't think this is exploitable on a
default pipeline and I don't have a PoC. NIOHTTP1's
`NIOHTTPRequestHeadersValidator` rejects 0x00...0x1F and 0x7F on write,
and the pipeline helpers insert it by default
(`enableOutboundHeaderValidation` defaults to true). So this is
hardening.

I still think it's worth doing here. It's a MUST that NIOHTTP2 is in the
right place to enforce; `HTTPEncoder` itself doesn't validate, so a
hand-built pipeline has no check at all; and anyone reading
`HTTPRequestHead.headers` and passing values on elsewhere is inheriting
a check they'd probably assume the HTTP/2 layer had already done.

## Modifications

`isValidFieldValue(_:)` rejects 0x00, 0x0A and 0x0D, and
`legalHeaderField(value:)` now calls it for regular headers, throwing a
new `NIOHTTP2Errors.invalidHTTP2HeaderFieldValue`. The state machine
already turns a throw here into the right stream/connection error, so
nothing else needed changing.

SP, HTAB and obs-text stay legal (RFC 9110 § 5.5). It sits behind the
existing `headerBlockValidation` flag. The new error type mirrors
`ForbiddenHeaderField`'s storage pattern and is additive public API.

Two things I left out on purpose, both easy to add if you'd rather have
them:

- § 8.2.1 also forbids a value starting or ending with SP/HTAB. Not
smuggling-relevant, and rejecting it seemed likely to break peers
sending harmless padding.
- No check in the codec itself.
`HTTPRequestHead(http2HeaderBlock:isEndStream:)` validates
pseudo-headers inline via `peekPseudoHeader`, but
`appendRegularHeaders(from:)` just copies. I didn't add one there
because it's per-request and you have allocation thresholds. It does
leave the two asymmetric if `headerBlockValidation` is `.disabled`.

## Result

Regular field values containing NUL, CR or LF are treated as malformed.
Well-formed values are unaffected.

## Testing

Added to `HTTP2FramePayloadToHTTP1CodecCRLFTests.swift`, the regression
file from GHSA-4px2-pw77-vc85, which currently has no coverage for
regular field values.

- `isValidFieldValue` against CRLF, lone CR, lone LF, NUL, a full
smuggling payload, a TE desync payload
- values that must still pass: `with spaces inside`, `with\ttab`,
`text/html; charset=utf-8`, bearer tokens, non-ASCII
- request, response and trailers validation

Built and ran on Linux, Swift 6.1 aarch64. `swift test -Xswiftc
-warnings-as-errors` is clean with no new warnings, the new tests pass,
and `swift format lint --strict Sources/ Tests/` is clean.
2026-07-22 10:58:49 +01:00
AkshayandGeorge Barnett 41a8b95a98 NIOHTTP2: forbid keep-alive and upgrade connection-specific headers (#552)
RFC 9113 § 8.2.2 enumerates five connection-specific header fields that
a conformant HTTP/2 endpoint must treat as malformed: Connection,
Proxy-Connection, Keep-Alive, Transfer-Encoding, and Upgrade.
HeaderFieldName .legalHeaderField(value:) only rejected three of them,
so keep-alive and upgrade passed validation and were translated verbatim
into HTTP/1.1 messages by the H2->H1 codecs. This is a conformance gap
and a defence-in-depth issue, since downstream HTTP/1.1 parsers may act
on those fields independently.

Modifications:

- Add keep-alive and upgrade to the forbidden connection-specific header
switch in legalHeaderField(value:).
- Update the surrounding comment to cite RFC 9113 § 8.2.2 and its
explicit enumeration in place of the obsoleted RFC 7540 § 8.1.2.2
reference.
- Add request- and response-block validation tests covering all five
connection-specific fields.

Result:

All five connection-specific header fields named by RFC 9113 § 8.2.2 are
rejected during header-block validation.

Resolves #549

Co-authored-by: George Barnett <gbarnett@apple.com>
2026-07-02 10:58:11 +00:00
George Barnett 634d078571 Apply formatter (#553)
Motivation:

61d1b44 was merged in from a private security fork and didn't have the
formatter run on it.

Modifications:

- Run the formatter

Result:

Format check passes
2026-07-01 10:30:24 +00:00
Fabian Fett 61d1b44f6e Merge commit from fork 2026-05-20 10:08:41 +01:00