Skip to content

Commit 116b6d1

Browse files
authored
Merge pull request from GHSA-v3r5-pjpm-mwgq
Motivation Allowing arbitrary data in outbound header field values allows for the possibility that users of AHC will accidentally pass untrusted data into those values. That untrusted data can substantially alter the parsing and content of the HTTP requests, which is extremely dangerous. The result of this is vulnerability to CRLF injection. Modifications Add validation of outbound header field values. Result No longer vulnerable to CRLF injection (cherry picked from commit 3034835a213babfcda19031e80c0b7c9780475e9)
1 parent 7a4dfe0 commit 116b6d1

File tree

4 files changed

+167
-0
lines changed

4 files changed

+167
-0
lines changed

Sources/AsyncHTTPClient/HTTPClient.swift

+3
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,7 @@ public struct HTTPClientError: Error, Equatable, CustomStringConvertible {
924924
case uncleanShutdown
925925
case traceRequestWithBody
926926
case invalidHeaderFieldNames([String])
927+
case invalidHeaderFieldValues([String])
927928
case bodyLengthMismatch
928929
case writeAfterRequestSent
929930
@available(*, deprecated, message: "AsyncHTTPClient now silently corrects invalid headers.")
@@ -988,6 +989,8 @@ public struct HTTPClientError: Error, Equatable, CustomStringConvertible {
988989
public static let traceRequestWithBody = HTTPClientError(code: .traceRequestWithBody)
989990
/// Header field names contain invalid characters.
990991
public static func invalidHeaderFieldNames(_ names: [String]) -> HTTPClientError { return HTTPClientError(code: .invalidHeaderFieldNames(names)) }
992+
/// Header field values contain invalid characters.
993+
public static func invalidHeaderFieldValues(_ values: [String]) -> HTTPClientError { return HTTPClientError(code: .invalidHeaderFieldValues(values)) }
991994
/// Body length is not equal to `Content-Length`.
992995
public static let bodyLengthMismatch = HTTPClientError(code: .bodyLengthMismatch)
993996
/// Body part was written after request was fully sent.

Sources/AsyncHTTPClient/RequestValidation.swift

+51
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ extension HTTPHeaders {
2121
bodyLength: RequestBodyLength
2222
) throws -> RequestFramingMetadata {
2323
try self.validateFieldNames()
24+
try self.validateFieldValues()
2425

2526
if case .TRACE = method {
2627
switch bodyLength {
@@ -80,6 +81,56 @@ extension HTTPHeaders {
8081
}
8182
}
8283

84+
private func validateFieldValues() throws {
85+
let invalidValues = self.compactMap { _, value -> String? in
86+
let satisfy = value.utf8.allSatisfy { char -> Bool in
87+
/// Validates a byte of a given header field value against the definition in RFC 9110.
88+
///
89+
/// The spec in [RFC 9110](https://httpwg.org/specs/rfc9110.html#fields.values) defines the valid
90+
/// characters as the following:
91+
///
92+
/// ```
93+
/// field-value = *field-content
94+
/// field-content = field-vchar
95+
/// [ 1*( SP / HTAB / field-vchar ) field-vchar ]
96+
/// field-vchar = VCHAR / obs-text
97+
/// obs-text = %x80-FF
98+
/// ```
99+
///
100+
/// Additionally, it makes the following note:
101+
///
102+
/// "Field values containing CR, LF, or NUL characters are invalid and dangerous, due to the
103+
/// varying ways that implementations might parse and interpret those characters; a recipient
104+
/// of CR, LF, or NUL within a field value MUST either reject the message or replace each of
105+
/// those characters with SP before further processing or forwarding of that message. Field
106+
/// values containing other CTL characters are also invalid; however, recipients MAY retain
107+
/// such characters for the sake of robustness when they appear within a safe context (e.g.,
108+
/// an application-specific quoted string that will not be processed by any downstream HTTP
109+
/// parser)."
110+
///
111+
/// As we cannot guarantee the context is safe, this code will reject all ASCII control characters
112+
/// directly _except_ for HTAB, which is explicitly allowed.
113+
switch char {
114+
case UInt8(ascii: "\t"):
115+
// HTAB, explicitly allowed.
116+
return true
117+
case 0...0x1f, 0x7F:
118+
// ASCII control character, forbidden.
119+
return false
120+
default:
121+
// Printable or non-ASCII, allowed.
122+
return true
123+
}
124+
}
125+
126+
return satisfy ? nil : value
127+
}
128+
129+
guard invalidValues.count == 0 else {
130+
throw HTTPClientError.invalidHeaderFieldValues(invalidValues)
131+
}
132+
}
133+
83134
private mutating func setTransportFraming(
84135
method: HTTPMethod,
85136
bodyLength: RequestBodyLength

Tests/AsyncHTTPClientTests/HTTPClientTests+XCTest.swift

+4
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,10 @@ extension HTTPClientTests {
136136
("testRequestSpecificTLS", testRequestSpecificTLS),
137137
("testConnectionPoolSizeConfigValueIsRespected", testConnectionPoolSizeConfigValueIsRespected),
138138
("testRequestWithHeaderTransferEncodingIdentityDoesNotFail", testRequestWithHeaderTransferEncodingIdentityDoesNotFail),
139+
("testRejectsInvalidCharactersInHeaderFieldNames_http1", testRejectsInvalidCharactersInHeaderFieldNames_http1),
140+
("testRejectsInvalidCharactersInHeaderFieldNames_http2", testRejectsInvalidCharactersInHeaderFieldNames_http2),
141+
("testRejectsInvalidCharactersInHeaderFieldValues_http1", testRejectsInvalidCharactersInHeaderFieldValues_http1),
142+
("testRejectsInvalidCharactersInHeaderFieldValues_http2", testRejectsInvalidCharactersInHeaderFieldValues_http2),
139143
]
140144
}
141145
}

Tests/AsyncHTTPClientTests/HTTPClientTests.swift

+109
Original file line numberDiff line numberDiff line change
@@ -3114,4 +3114,113 @@ class HTTPClientTests: XCTestCase {
31143114

31153115
XCTAssertNoThrow(try client.execute(request: request).wait())
31163116
}
3117+
3118+
func testRejectsInvalidCharactersInHeaderFieldNames_http1() throws {
3119+
try self._rejectsInvalidCharactersInHeaderFieldNames(mode: .http1_1(ssl: true))
3120+
}
3121+
3122+
func testRejectsInvalidCharactersInHeaderFieldNames_http2() throws {
3123+
try self._rejectsInvalidCharactersInHeaderFieldNames(mode: .http2(compress: false))
3124+
}
3125+
3126+
private func _rejectsInvalidCharactersInHeaderFieldNames(mode: HTTPBin<HTTPBinHandler>.Mode) throws {
3127+
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
3128+
defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) }
3129+
let client = HTTPClient(eventLoopGroupProvider: .shared(group))
3130+
defer { XCTAssertNoThrow(try client.syncShutdown()) }
3131+
let bin = HTTPBin(mode)
3132+
defer { XCTAssertNoThrow(try bin.shutdown()) }
3133+
3134+
// The spec in [RFC 9110](https://httpwg.org/specs/rfc9110.html#fields.values) defines the valid
3135+
// characters as the following:
3136+
//
3137+
// ```
3138+
// field-name = token
3139+
//
3140+
// token = 1*tchar
3141+
//
3142+
// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
3143+
// / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
3144+
// / DIGIT / ALPHA
3145+
// ; any VCHAR, except delimiters
3146+
let weirdAllowedFieldName = "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
3147+
3148+
var request = try Request(url: "\(self.defaultHTTPBinURLPrefix)get")
3149+
request.headers.add(name: weirdAllowedFieldName, value: "present")
3150+
3151+
// This should work fine.
3152+
let response = try client.execute(request: request).wait()
3153+
XCTAssertEqual(response.status, .ok)
3154+
3155+
// Now, let's confirm all other bytes are rejected. We want to stay within the ASCII space as the HTTPHeaders type will forbid anything else.
3156+
for byte in UInt8(0)...UInt8(127) {
3157+
// Skip bytes that we already believe are allowed.
3158+
if weirdAllowedFieldName.utf8.contains(byte) {
3159+
continue
3160+
}
3161+
let forbiddenFieldName = weirdAllowedFieldName + String(decoding: [byte], as: UTF8.self)
3162+
3163+
var request = try Request(url: "\(self.defaultHTTPBinURLPrefix)get")
3164+
request.headers.add(name: forbiddenFieldName, value: "present")
3165+
3166+
XCTAssertThrowsError(try client.execute(request: request).wait()) { error in
3167+
XCTAssertEqual(error as? HTTPClientError, .invalidHeaderFieldNames([forbiddenFieldName]))
3168+
}
3169+
}
3170+
}
3171+
3172+
func testRejectsInvalidCharactersInHeaderFieldValues_http1() throws {
3173+
try self._rejectsInvalidCharactersInHeaderFieldValues(mode: .http1_1(ssl: true))
3174+
}
3175+
3176+
func testRejectsInvalidCharactersInHeaderFieldValues_http2() throws {
3177+
try self._rejectsInvalidCharactersInHeaderFieldValues(mode: .http2(compress: false))
3178+
}
3179+
3180+
private func _rejectsInvalidCharactersInHeaderFieldValues(mode: HTTPBin<HTTPBinHandler>.Mode) throws {
3181+
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
3182+
defer { XCTAssertNoThrow(try group.syncShutdownGracefully()) }
3183+
let client = HTTPClient(eventLoopGroupProvider: .shared(group))
3184+
defer { XCTAssertNoThrow(try client.syncShutdown()) }
3185+
let bin = HTTPBin(mode)
3186+
defer { XCTAssertNoThrow(try bin.shutdown()) }
3187+
3188+
// We reject all ASCII control characters except HTAB and tolerate everything else.
3189+
let weirdAllowedFieldValue = "!\" \t#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
3190+
3191+
var request = try Request(url: "\(self.defaultHTTPBinURLPrefix)get")
3192+
request.headers.add(name: "Weird-Value", value: weirdAllowedFieldValue)
3193+
3194+
// This should work fine.
3195+
let response = try client.execute(request: request).wait()
3196+
XCTAssertEqual(response.status, .ok)
3197+
3198+
// Now, let's confirm all other bytes in the ASCII range ar rejected
3199+
for byte in UInt8(0)...UInt8(127) {
3200+
// Skip bytes that we already believe are allowed.
3201+
if weirdAllowedFieldValue.utf8.contains(byte) {
3202+
continue
3203+
}
3204+
let forbiddenFieldValue = weirdAllowedFieldValue + String(decoding: [byte], as: UTF8.self)
3205+
3206+
var request = try Request(url: "\(self.defaultHTTPBinURLPrefix)get")
3207+
request.headers.add(name: "Weird-Value", value: forbiddenFieldValue)
3208+
3209+
XCTAssertThrowsError(try client.execute(request: request).wait()) { error in
3210+
XCTAssertEqual(error as? HTTPClientError, .invalidHeaderFieldValues([forbiddenFieldValue]))
3211+
}
3212+
}
3213+
3214+
// All the bytes outside the ASCII range are fine though.
3215+
for byte in UInt8(128)...UInt8(255) {
3216+
let evenWeirderAllowedValue = weirdAllowedFieldValue + String(decoding: [byte], as: UTF8.self)
3217+
3218+
var request = try Request(url: "\(self.defaultHTTPBinURLPrefix)get")
3219+
request.headers.add(name: "Weird-Value", value: evenWeirderAllowedValue)
3220+
3221+
// This should work fine.
3222+
let response = try client.execute(request: request).wait()
3223+
XCTAssertEqual(response.status, .ok)
3224+
}
3225+
}
31173226
}

0 commit comments

Comments
 (0)