From c6e2e5cbe0d2653b39988f10f8af784e0a38d46a Mon Sep 17 00:00:00 2001 From: Madalin Ignisca Date: Fri, 14 Aug 2026 09:50:04 +0200 Subject: [PATCH] fix(header): accept non-standard end-of-header values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `HeaderReader` required the outer header's end-of-header field (type 0) to contain exactly `\r\n\r\n`, and threw `corrupted` otherwise. Implementations disagree about this field. KeePass 2.x, KeePassXC and KeePassium all write `\r\n\r\n`, but KDBX 4.0 files carrying an empty value turn up in the wild, and they are valid in every other respect. Reproduced against such a file (KDBX 4.0, ChaCha20, Argon2id), which fails on develop with: Invalid end-of-header value. Length: 0; bytes: The check also buys no security. The header bytes are already covered by the header SHA-256 digest and by the HMAC, so tampering is detected regardless of this field's contents — it is a legacy sanity marker, not integrity data. Enforcing it only rejects otherwise-conforming files. Non-standard values are now accepted and logged at debug level. Nothing else about header validation changes; a truncated header still throws. Adds EndOfHeaderCompatTests covering the conventional marker, an empty marker, an arbitrary value, and that real corruption is still rejected. Full suite: 477 tests, 74 suites, all passing. Co-Authored-By: Claude Opus 5 (1M context) --- Sources/KDBXKit/Header/HeaderReader.swift | 14 ++- .../KDBXKitTests/EndOfHeaderCompatTests.swift | 111 ++++++++++++++++++ 2 files changed, 124 insertions(+), 1 deletion(-) create mode 100644 Tests/KDBXKitTests/EndOfHeaderCompatTests.swift diff --git a/Sources/KDBXKit/Header/HeaderReader.swift b/Sources/KDBXKit/Header/HeaderReader.swift index 77e6826..b80f8a5 100644 --- a/Sources/KDBXKit/Header/HeaderReader.swift +++ b/Sources/KDBXKit/Header/HeaderReader.swift @@ -95,8 +95,20 @@ struct HeaderReader: Sendable { switch fieldType { case .endOfHeader: + // The end-of-header value is a legacy sanity marker, not + // integrity data. KeePass 2.x, KeePassXC and KeePassium write + // "\r\n\r\n"; other implementations emit an empty value. + // Both occur in real KDBX 4 files. + // + // Rejecting anything but "\r\n\r\n" buys no security: the + // header bytes are already covered by the header SHA-256 digest + // and by the HMAC, so tampering is caught regardless of what + // this marker contains. Enforcing it only locks out vaults + // written by conforming implementations. if valueData != HeaderFieldType.endOfHeaderValue { - throw Error.corrupted(reason: "Invalid end-of-header value. Length: \(valueData.count); bytes: \(valueData.hexString)") + KDBXLog.header.debug( + "Non-standard end-of-header value (\(valueData.count) bytes); accepting" + ) } done = true diff --git a/Tests/KDBXKitTests/EndOfHeaderCompatTests.swift b/Tests/KDBXKitTests/EndOfHeaderCompatTests.swift new file mode 100644 index 0000000..d3dc4fb --- /dev/null +++ b/Tests/KDBXKitTests/EndOfHeaderCompatTests.swift @@ -0,0 +1,111 @@ +// +// Copyright (c) 2025, Denis Dzyubenko +// +// SPDX-License-Identifier: BSD-2-Clause +// + +import Foundation +import Testing + +@testable import KDBXKit + +/// The outer header's end-of-header field (type 0) carries a value that +/// implementations disagree about. +/// +/// KeePass 2.x, KeePassXC and KeePassium all write `\r\n\r\n`. Some other +/// implementation writes an empty value — KDBX 4.0 files carrying one turn up +/// in the wild. A reader that insists on `\r\n\r\n` cannot open them, even +/// though they are valid in every other respect. +/// +/// Rejecting a non-standard marker also buys nothing: the header bytes are +/// covered by the header SHA-256 digest and the HMAC, so tampering is detected +/// regardless of what this field contains. +struct EndOfHeaderCompatTests { + /// A representative KDBX 4.1 header, serialized to bytes. + private func headerBytes() throws -> Data { + let header = Header( + formatVersion: .v4_1, + encryptionAlgorithm: .AES256CBC, + compressionAlgorithm: .gzip, + masterSalt: Data(repeating: 0x11, count: 32), + encryptionNonce: Data(repeating: 0x22, count: 16), + kdfParameters: .argon2id( + .init( + version: .v1_3, + salt: Data(repeating: 0x33, count: 32), + iterations: 2, + memory: 1 << 20, + parallelism: 2 + ), + additional: [:] + ), + publicCustomData: [:] + ) + + let stream = OutputStream(toMemory: ()) + stream.open() + try HeaderWriter(to: stream).write(header) + return stream.property(forKey: .dataWrittenToMemoryStreamKey) as! Data + } + + /// Replace the trailing end-of-header TLV with one carrying `value`. + /// + /// The writer emits end-of-header last, as `type(1) + length(4) + 4 bytes`, + /// so dropping the final 9 bytes removes exactly that field. + private func replacingEndOfHeader(_ data: Data, with value: Data) -> Data { + var rewritten = data.dropLast(9) + rewritten.append(0x00) + rewritten.append(contentsOf: UInt32(value.count).toDataLittleEndian()) + rewritten.append(contentsOf: value) + return Data(rewritten) + } + + @Test("the conventional \\r\\n\\r\\n marker still parses") + func conventionalMarker() throws { + var reader = HeaderReader(data: try headerBytes()) + let (parsed, _) = try reader.parse() + #expect(parsed.formatVersion == .v4_1) + } + + @Test("an empty end-of-header value parses") + func emptyMarker() throws { + // The exact shape found in real KDBX 4.0 files. Before this change it + // threw `corrupted(reason: "Invalid end-of-header value...")`, which + // made those vaults unreadable. + let patched = replacingEndOfHeader(try headerBytes(), with: Data()) + + var reader = HeaderReader(data: patched) + let (parsed, length) = try reader.parse() + + #expect(parsed.formatVersion == .v4_1) + #expect(parsed.encryptionAlgorithm == .AES256CBC) + #expect(parsed.masterSalt == Data(repeating: 0x11, count: 32)) + #expect(length == patched.count) + } + + @Test("an arbitrary end-of-header value parses") + func arbitraryMarker() throws { + // Nothing in the format assigns this field meaning, so a reader should + // not care what a writer chose to put there. + let patched = replacingEndOfHeader( + try headerBytes(), + with: Data("KeePassX".utf8) + ) + + var reader = HeaderReader(data: patched) + let (parsed, _) = try reader.parse() + #expect(parsed.formatVersion == .v4_1) + } + + @Test("the rest of the header is still validated") + func stillValidatesRealCorruption() throws { + // Loosening the marker check must not loosen anything else: a header + // that ends before its fields are complete is still corrupt. + let truncated = Data(try headerBytes().prefix(20)) + + var reader = HeaderReader(data: truncated) + #expect(throws: HeaderReader.Error.self) { + _ = try reader.parse() + } + } +}