Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2.x.x: guard for index overflow #404

Merged
merged 4 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions Sources/HummingbirdCore/Utils/HBParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -596,8 +596,7 @@ extension Parser {
func _percentDecode(_ original: ArraySlice<UInt8>, _ bytes: UnsafeMutableBufferPointer<UInt8>) throws -> Int {
var newIndex = 0
var index = original.startIndex

while index < original.endIndex {
while index < (original.endIndex - 2) {
// if we have found a percent sign
if original[index] == 0x25 {
let high = Self.asciiHexValues[Int(original[index + 1])]
Expand All @@ -614,9 +613,13 @@ extension Parser {
index += 1
}
}
while index < original.endIndex {
bytes[newIndex] = original[index]
newIndex += 1
index += 1
}
return newIndex
}

guard self.index != self.range.endIndex else { return "" }
do {
if #available(macOS 11, macCatalyst 14.0, iOS 14.0, tvOS 14.0, *) {
Expand Down
22 changes: 22 additions & 0 deletions Tests/HummingbirdRouterTests/RouterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,28 @@ final class RouterTests: XCTestCase {
}
}

/// Test the hummingbird core parser against possible overflows of the percent encoder. this issue was introduced in pr #404 in the context of query parameters but I've thrown in some other random overflow scenarios in here too for good measure. if it doesn't crash, its a win.
func testQueryParameterOverflow() async throws {
let router = RouterBuilder(context: BasicRouterRequestContext.self) {
Get("overflow") { req, _ in
let currentQP = req.uri.queryParameters["query"]
return String("\(currentQP ?? "")")
}
}
let app = Application(router: router)
try await app.test(.router) { client in
try await client.execute(uri: "/overflow?query=value%", method: .get) { response in
XCTAssertEqual(String(buffer: response.body), "value%")
}
try await client.execute(uri: "/overflow?query%=value%", method: .get) { response in
XCTAssertEqual(String(buffer: response.body), "")
}
try await client.execute(uri: "/overflow?%&", method: .get) { response in
XCTAssertEqual(String(buffer: response.body), "")
}
}
}

func testParameters() async throws {
let router = RouterBuilder(context: BasicRouterRequestContext.self) {
Delete("/user/:id") { _, context -> String? in
Expand Down