Skip to content
Open
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: 8 additions & 1 deletion Sources/CBORDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,16 @@ public class CBORDecoder {
throw CBORError.tooLongSequence
}

/// Application-safe limit here
let MAX_REASONABLE_LENGTH = 200_000
guard n <= MAX_REASONABLE_LENGTH else {
throw CBORError.tooLongSequence
}

return Int(n)
}


private func readN(_ n: Int) throws -> [CBOR] {
return try (0..<n).map { _ in
guard let r = try decodeItem() else { throw CBORError.unfinishedSequence }
Expand Down Expand Up @@ -197,7 +204,7 @@ public class CBORDecoder {
return CBOR.double(try readBinaryNumber(Float64.self))

case 0xff: return CBOR.break
default: return nil
default: throw CBORError.unfinishedSequence
}
}
}
Expand Down
32 changes: 32 additions & 0 deletions Tests/CBORDecoderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,40 @@ class CBORDecoderTests: XCTestCase {
_ = try? CBOR.decode(randomData, options: CBOROptions(maximumDepth: 512))
}
}

func testDecodeFailsForAbsurdlyBigArrayOrMapLength() {

let hugeArrayHeader: [UInt8] = [
0x9b,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
]

XCTAssertThrowsError(try CBORDecoder(input: hugeArrayHeader).decodeItem()) { error in
XCTAssertEqual(error as? CBORError, CBORError.tooLongSequence)
}

let hugeMapHeader: [UInt8] = [
0xbb,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
]

XCTAssertThrowsError(try CBORDecoder(input: hugeMapHeader).decodeItem()) { error in
XCTAssertEqual(error as? CBORError, CBORError.tooLongSequence)
}
}

func testDecodeFailsForEmptyInput() {
let emptyInput: [UInt8] = []
XCTAssertThrowsError(try CBORDecoder(input: emptyInput).decodeItem()) { error in
XCTAssertEqual(error as? CBORError, CBORError.unfinishedSequence)
}
}


}



#if os(Android)

extension XCTestCase {
Expand Down