Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Fix an issue causing a crash when the Content-Lenght was negative
* Add an unit tests for the new exception
* Fix an Swiftlint warning regarding the colon
* Fix a spelling error
  • Loading branch information
Vkt0r committed Sep 16, 2020
commit 8ceaeb1925fdf7a9cffb9b6a9b85813f6b9b8041
8 changes: 7 additions & 1 deletion XCode/Sources/HttpParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@

import Foundation

enum HttpParserError: Error {
enum HttpParserError: Error, Equatable {
case invalidStatusLine(String)
case negativeContentLength
}

public class HttpParser {
Expand All @@ -29,6 +30,11 @@ public class HttpParser {
request.queryParams = urlComponents?.queryItems?.map { ($0.name, $0.value ?? "") } ?? []
request.headers = try readHeaders(socket)
if let contentLength = request.headers["content-length"], let contentLengthValue = Int(contentLength) {
// Prevent a buffer overflow and runtime error trying to create an `UnsafeMutableBufferPointer` with
// a negative length
guard contentLengthValue >= 0 else {
throw HttpParserError.negativeContentLength
}
request.body = try readBody(socket, size: contentLengthValue)
}
return request
Expand Down
2 changes: 1 addition & 1 deletion XCode/Sources/WebSockets.swift
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ public class WebSocketSession: Hashable, Equatable {
frm.rsv3 = fst & 0x10
guard frm.rsv1 == 0 && frm.rsv2 == 0 && frm.rsv3 == 0
else {
throw WsError.protocolError("Reserved frame bit has not been negocitated.")
throw WsError.protocolError("Reserved frame bit has not been negociated.")
}
let opc = fst & 0x0F
guard let opcode = OpCode(rawValue: opc) else {
Expand Down
8 changes: 8 additions & 0 deletions XCode/Tests/SwifterTestsHttpParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ class SwifterTestsHttpParser: XCTestCase {
XCTAssert(false, "Parser should not throw any errors if there is a valid 'Content-Length' header.")
}

do {
_ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\r\nContent-Length: -1\r\n\r\n"))
} catch let error {
let error = error as? HttpParserError
XCTAssertNotNil(error)
XCTAssertEqual(error!, HttpParserError.negativeContentLength)
}

do {
_ = try parser.readHttpRequest(TestSocket("GET / HTTP/1.0\nContent-Length: 5\n\n12345"))
} catch {
Expand Down