Correctly apply the end-of-contents octets to the right level (#134)

Motivation

In #125 we attempted to apply a hardening fix that would avoid allowing
truncation of BER content by applying an end-of-contents octets at the
wrong parse depth to a higher-level object. This fix was incomplete.

Modifications

Re-write the code to handle the end-of-contents octets as part of the
loop instead of attempting to detect it after the fact. Add
defense-in-depth for unexpected nodes.

Results

More robust against issues with end-of-contents octets.
This commit is contained in:
Cory Benfield authored and GitHub committed 2026-10-08 13:02:26 +01:00
1 parent 1964dcaab3
commit 917b472dbe
2 files changed
+111 -19

No files matched your search

+18 -19
View File
@@ -113,16 +113,6 @@ extension ASN1.ParserNode: CustomStringConvertible {
}
}
extension ASN1.ParserNode {
@inlinable
var isEndMarker: Bool {
self.identifier.tagClass == .universal
&& self.identifier.tagNumber == 0
&& self.isConstructed == false
&& self.encodedBytes.elementsEqual([0x00, 0x00])
}
}
// MARK: - Parsing
extension ASN1 {
@@ -192,6 +182,12 @@ extension ASN1 {
throw ASN1Error.truncatedASN1Field()
}
// [UNIVERSAL 0] is reserved for end-of-contents octets, which are consumed by the
// indefinite-length case below and never parsed as a node.
guard !(identifier.tagClass == .universal && identifier.tagNumber == 0) else {
throw ASN1Error.invalidASN1Object(reason: "Unexpected end-of-contents octets or [UNIVERSAL 0] tag")
}
switch wideLength {
case let .definite(wideLength):
guard let length = Int(exactly: wideLength) else {
@@ -255,17 +251,15 @@ extension ASN1 {
)
)
let lastIndex = nodes.endIndex - 1
repeat {
// X.690 §8.1.3.6.1: contents run until end-of-contents octets at this level.
while !data._startsWithEndOfContentsOctets {
guard data.count > 0 else {
throw ASN1Error.truncatedASN1Field()
}
try _parseNode(from: &data, encoding: rules, depth: depth + 1, into: &nodes)
} while data.count > 0 && nodes.last!.isEndMarker == false
// X.690 §8.1.3.6.1 requires end-of-contents octets. If input is exhausted first,
// the last child would otherwise be popped and treated as the marker.
guard nodes.last?.isEndMarker == true else {
throw ASN1Error.truncatedASN1Field()
}
let endMarker = nodes.popLast()!
let encodedBytes = originalData[..<endMarker.encodedBytes.endIndex]
nodes[lastIndex].encodedBytes = encodedBytes
data = data.dropFirst(2)
nodes[lastIndex].encodedBytes = originalData[..<data.startIndex]
}
}
}
@@ -446,6 +440,11 @@ extension ArraySlice where Element == UInt8 {
case definite(_: UInt)
}
@inlinable
var _startsWithEndOfContentsOctets: Bool {
self.count >= 2 && self[self.startIndex] == 0x00 && self[self.startIndex + 1] == 0x00
}
@inlinable
mutating func _readASN1Length(_ minimalEncoding: Bool) throws -> ASN1Length? {
guard let firstByte = self.popFirst() else {
+93
View File
@@ -1467,6 +1467,99 @@ class ASN1Tests: XCTestCase {
// The same encoding with the required EOC marker parses successfully.
let complete: [UInt8] = [0x30, 0x80, 0x04, 0x01, 0x41, 0x00, 0x00]
XCTAssertNoThrow(try BER.parse(complete))
// Input ending partway through the EOC marker is also truncated.
let partialEndMarker: [UInt8] = [0x30, 0x80, 0x04, 0x01, 0x41, 0x00]
XCTAssertThrowsError(try BER.parse(partialEndMarker)) { error in
XCTAssertEqual((error as? ASN1Error)?.code, .truncatedASN1Field)
}
}
func testRejectsEndOfContentsOctetsInsideDefiniteLengthContents() throws {
let invalid: [[UInt8]] = [
// 00 00 nested in a definite-length SEQUENCE, no EOC for the outer indefinite SEQUENCE.
[0x30, 0x80, 0x04, 0x01, 0x41, 0x30, 0x02, 0x00, 0x00],
// As above, with the outer EOC present.
[0x30, 0x80, 0x04, 0x01, 0x41, 0x30, 0x02, 0x00, 0x00, 0x00, 0x00],
// Nested 00 00 must not end the indefinite SEQUENCE early.
[0x30, 0x0b, 0x30, 0x80, 0x30, 0x02, 0x00, 0x00, 0x02, 0x01, 0x05, 0x00, 0x00],
// Two nested 00 00 must not end two levels of indefinite SEQUENCE.
[0x30, 0x80, 0x30, 0x80, 0x30, 0x04, 0x00, 0x00, 0x00, 0x00],
// Constructed OCTET STRING variant.
[0x24, 0x80, 0x04, 0x01, 0x41, 0x24, 0x02, 0x00, 0x00],
// 00 00 directly inside definite-length contents.
[0x30, 0x02, 0x00, 0x00],
]
for bytes in invalid {
XCTAssertThrowsError(try BER.parse(bytes), "\(bytes)") { error in
XCTAssertEqual((error as? ASN1Error)?.code, .invalidASN1Object, "\(bytes)")
}
}
XCTAssertThrowsError(try DER.parse([0x30, 0x02, 0x00, 0x00]))
}
func testRejectsUniversalTagZero() throws {
let invalid: [[UInt8]] = [
// Top-level 00 00.
[0x00, 0x00],
// [UNIVERSAL 0] with contents.
[0x30, 0x03, 0x00, 0x01, 0xff],
// Constructed [UNIVERSAL 0].
[0x30, 0x02, 0x20, 0x00],
]
for bytes in invalid {
XCTAssertThrowsError(try BER.parse(bytes), "\(bytes)") { error in
XCTAssertEqual((error as? ASN1Error)?.code, .invalidASN1Object, "\(bytes)")
}
XCTAssertThrowsError(try DER.parse(bytes), "\(bytes)") { error in
XCTAssertEqual((error as? ASN1Error)?.code, .invalidASN1Object, "\(bytes)")
}
}
// A non-minimally encoded zero length is not an EOC marker.
let nonMinimalEndMarker: [UInt8] = [0x30, 0x80, 0x04, 0x01, 0x41, 0x00, 0x81, 0x00, 0x00, 0x00]
XCTAssertThrowsError(try BER.parse(nonMinimalEndMarker)) { error in
XCTAssertEqual((error as? ASN1Error)?.code, .invalidASN1Object)
}
}
func testParseNestedBERIndefiniteLengthEncodings() throws {
// SEQUENCE (indefinite) { SEQUENCE (indefinite) { INTEGER 5 }, SEQUENCE (indefinite) {}, INTEGER 6 }
let encoded: [UInt8] = [
0x30, 0x80,
0x30, 0x80, 0x02, 0x01, 0x05, 0x00, 0x00,
0x30, 0x80, 0x00, 0x00,
0x02, 0x01, 0x06,
0x00, 0x00,
]
let parsed = try BER.parse(encoded)
XCTAssertEqual(parsed.encodedBytes, encoded[...])
guard case .constructed(let children) = parsed.content else {
XCTFail("Unexpected node")
return
}
let childNodes = Array(children)
guard childNodes.count == 3 else {
XCTFail("Invalid number of children")
return
}
XCTAssertEqual(childNodes[0].encodedBytes, [0x30, 0x80, 0x02, 0x01, 0x05, 0x00, 0x00])
guard case .constructed(let innerChildren) = childNodes[0].content else {
XCTFail("Unexpected node")
return
}
XCTAssertEqual(try innerChildren.map { try Int(berEncoded: $0) }, [5])
XCTAssertEqual(childNodes[1].encodedBytes, [0x30, 0x80, 0x00, 0x00])
guard case .constructed(let emptyChildren) = childNodes[1].content else {
XCTFail("Unexpected node")
return
}
XCTAssertEqual(Array(emptyChildren).count, 0)
XCTAssertEqual(try Int(berEncoded: childNodes[2]), 6)
}
func testConstructedBoolean() throws {