diff --git a/Sources/NIOSSL/SSLContext.swift b/Sources/NIOSSL/SSLContext.swift index 4e41e22a..c147fba9 100644 --- a/Sources/NIOSSL/SSLContext.swift +++ b/Sources/NIOSSL/SSLContext.swift @@ -782,26 +782,38 @@ extension NIOSSLContext { /// Takes a path and determines if the file at this path is of c_rehash format . internal static func _isRehashFormat(path: String) throws -> Bool { // Check if the element’s name matches the c_rehash symlink name format. - // The links created are of the form HHHHHHHH.D, where each H is a hexadecimal character and D is a single decimal digit. + // `openssl rehash` writes its links with `snprintf(..., "%08x.%s%d", ...)` (apps/rehash.c): + // eight hex characters, a period, a type infix that is empty for certificates and "r" for + // CRLs, and a decimal collision id that starts at 0 and counts up for every further + // certificate sharing the same subject name hash. The id is a plain %d, not one character, + // so ".10" and beyond are ordinary names and must be recognised here. let utf8PathView = path.utf8 let utf8PathSplitView = utf8PathView.split(separator: UInt8(ascii: "/")) - // Make sure the path is at least 10 units long - guard let lastPathComponent = utf8PathSplitView.last, - lastPathComponent.count == 10 - else { return false } - // Split into filename parts HHHHHHHH.D -> [[HHHHHHHH], [D]] - let filenameParts = lastPathComponent.split(separator: UInt8(ascii: ".")) + guard let lastPathComponent = utf8PathSplitView.last else { return false } - // Double check that the extension did not fail to cast to an integer. - // Make sure that the filename is an 8 character hex based file name. + // Split into filename parts HHHHHHHH.D -> [[HHHHHHHH], [D]]. + // + // The split must keep empty subsequences. With the default (omitting) behaviour a name + // such as "7f44456a..0", ".7f44456a.0" or "7f44456a.0." collapses to the same two parts + // as "7f44456a.0" and would be accepted, even though it has a period in a position + // `openssl rehash` never puts one. Keeping the empty pieces makes every stray period show + // up in the part count or as an empty part, so the checks below can reject it. + let filenameParts = lastPathComponent.split( + separator: UInt8(ascii: "."), + omittingEmptySubsequences: false + ) + + // Exactly one period, an 8 character hex filename before it and at least one decimal digit + // after it. No separate length check on the whole name is needed: those three conditions + // already pin it to 8 + 1 + digits. guard filenameParts.count == 2, let filename = filenameParts.first, let fileExtension = filenameParts.last, - fileExtension.count == 1, filename.count == 8, filename.allSatisfy({ $0.isHexDigit }), - fileExtension.first == UInt8(ascii: "0") + !fileExtension.isEmpty, + fileExtension.allSatisfy({ $0.isDecimalDigit }) else { return false } // Check if the element is a symlink. If it is not, return false. @@ -815,7 +827,8 @@ extension NIOSSLContext { #endif // Return true at this point because the file format is considered to be in rehash format and a symlink. - // Rehash format being "%08lx.%d" or HHHHHHHH.D + // Rehash format being "%08x.%s%d" with an empty infix, or HHHHHHHH.D where D is one or + // more decimal digits. return true } } @@ -964,7 +977,8 @@ internal class DirectoryContents: Sequence, IteratorProtocol { } } -// Used as part of the `_isRehashFormat` format to determine if the filename is a hexadecimal filename. +// Used as part of the `_isRehashFormat` format to determine whether the filename is a hexadecimal +// filename and whether its extension is a decimal digit. extension UTF8.CodeUnit { private static let asciiZero = UInt8(ascii: "0") private static let asciiNine = UInt8(ascii: "9") @@ -983,4 +997,13 @@ extension UTF8.CodeUnit { return false } } + + var isDecimalDigit: Bool { + switch self { + case (.asciiZero)...(.asciiNine): + return true + default: + return false + } + } } diff --git a/Tests/NIOSSLTests/TLSConfigurationTest.swift b/Tests/NIOSSLTests/TLSConfigurationTest.swift index 3516375e..e569f440 100644 --- a/Tests/NIOSSLTests/TLSConfigurationTest.swift +++ b/Tests/NIOSSLTests/TLSConfigurationTest.swift @@ -995,9 +995,12 @@ class TLSConfigurationTest: XCTestCase { // Filename is not in rehash format. let acceptablePathBadFilename = try NIOSSLContext._isRehashFormat(path: "/etc/ssl/certs/myFile.pem") XCTAssertFalse(acceptablePathBadFilename) - // Filename is in bad rehash format. + // Filename is in bad rehash format: the extension is not a decimal digit. let acceptablePathBadRehashFormat = try NIOSSLContext._isRehashFormat(path: "/etc/ssl/certs/7f44456a.z") XCTAssertFalse(acceptablePathBadRehashFormat) + // Nor is a non-digit that happens to be a hex character. + let acceptablePathHexExtension = try NIOSSLContext._isRehashFormat(path: "/etc/ssl/certs/7f44456a.a") + XCTAssertFalse(acceptablePathHexExtension) // Test with an actual file, but no symlink. let dummyFile = try dumpToFile(data: Data(), fileExtension: ".txt", customPath: testName) @@ -1041,6 +1044,100 @@ class TLSConfigurationTest: XCTestCase { XCTAssertTrue(successSymlink) } + func testRehashFormatAcceptsCollisionSuffixes() throws { + // `openssl rehash` names its links "%08x.%s%d", the infix being empty for certificates: + // when several certificates share a subject name hash, the id is incremented rather than + // staying at 0. Every one of those links is in c_rehash format and must be recognised, + // otherwise the CAs behind the higher ids are silently left out of the client CA list. + // + // The id is a plain %d, so it grows past one digit. `apps/rehash.c` caps a hash bucket at + // 256 entries (MAX_COLLISIONS), which makes 255 the largest id that tool can write. The + // older perl `tools/c_rehash.in`, still shipped on the 3.0 and 3.5 branches, has no such + // cap: its suffix loop just increments until it finds a free name. So the predicate + // deliberately accepts any number of digits rather than enforcing a ceiling of its own. + let testName = String("\(#function)".dropLast(2)) + + let rootCAPath = try dumpToFile( + data: .init(customChain.rootPEM.utf8), + fileExtension: ".pem", + customPath: testName + ) + let rootCAFilename = URL(string: "file://" + rootCAPath)!.lastPathComponent + + var symlinks: [String] = [] + defer { + for symlink in symlinks { + XCTAssertNoThrow(try FileManager.default.removeItem(at: URL(string: "file://" + symlink)!)) + } + XCTAssertNoThrow(try FileManager.default.removeItem(at: URL(string: "file://" + rootCAPath)!)) + let removePath = "\(FileManager.default.temporaryDirectory.path)/\(testName)/" + XCTAssertNoThrow(try FileManager.default.removeItem(at: URL(string: "file://" + removePath)!)) + } + + let acceptedSuffixes: [(id: Int, why: String)] = [ + (0, "the first link for a hash"), + (1, "the first collision"), + (9, "the last single-digit id"), + (10, "the first two-digit id; a single-character check would drop it"), + (123, "an arbitrary id in the middle of the range"), + (255, "the largest id apps/rehash.c can write (MAX_COLLISIONS - 1)"), + ] + for (numericExtension, why) in acceptedSuffixes { + let symlinkName = getRehashFilename( + path: rootCAPath, + testName: testName, + numericExtension: numericExtension + ) + XCTAssertNoThrow( + try FileManager.default.createSymbolicLink( + atPath: symlinkName, + withDestinationPath: rootCAFilename + ) + ) + symlinks.append(symlinkName) + + XCTAssertTrue( + try NIOSSLContext._isRehashFormat(path: symlinkName), + "\(symlinkName) is a valid c_rehash link (\(why)) and should be recognised" + ) + } + + // Names that have the right characters but a shape `openssl rehash` never produces. They + // are real symlinks to a real certificate, so the name check is the only thing that can + // reject them. + // + // The first three depend on the split keeping empty subsequences: ".7f44456a.0", + // "7f44456a..0" and "7f44456a.0." each collapse to the same two parts as "7f44456a.0" + // when empty pieces are discarded, and would be accepted. The other three are rejected + // for reasons that do not involve the split at all: "7f44456a." by the !isEmpty check, + // "7f44456a.0.1" by yielding three parts under either behaviour, and "7f44456a.r0" by + // isDecimalDigit. + let rejectedNames: [(name: String, why: String)] = [ + (".7f44456a.0", "leading period gives an empty first part"), + ("7f44456a..0", "doubled period gives an empty middle part"), + ("7f44456a.0.", "trailing period gives an empty last part"), + ("7f44456a.", "empty extension: openssl rehash always writes at least one digit"), + ("7f44456a.0.1", "two periods: three parts, not two"), + ("7f44456a.r0", "CRL link: the caller loads every accepted name as a PEM certificate"), + ] + let tempDirPath = FileManager.default.temporaryDirectory.path + "/" + testName + "/" + for (name, why) in rejectedNames { + let symlinkName = tempDirPath + name + XCTAssertNoThrow( + try FileManager.default.createSymbolicLink( + atPath: symlinkName, + withDestinationPath: rootCAFilename + ) + ) + symlinks.append(symlinkName) + + XCTAssertFalse( + try NIOSSLContext._isRehashFormat(path: symlinkName), + "\(symlinkName) is not a name openssl rehash produces (\(why)) and must be rejected" + ) + } + } + func testNonexistentFileObject() throws { var clientConfig = TLSConfiguration.makeClientConfiguration() clientConfig.trustRoots = .file("/thispathbetternotexist/bogus.foo")