From 00a45ad9bb42fdedfb8d764b9ee5a19b2d671851 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 10 Mar 2022 18:24:31 +0100 Subject: [PATCH] Add RandomAccessCollection conformance to `SubjectAlternativeNames` and make it public (#345) * make `_SubjectAlternativeNames` and related types public and add `RandomAccessCollection` conformance to `_SubjectAlternativeNames` * move type conversion out of collection * add `_SubjectAlternativeName`, `. NameType` and `. Contents` * remove new error case * add email as a supported name type * fix review comments and move _SubjectAlternativeNames and related types to a separate file * remove unused error code * fix review comments * add missing Glibc import for `in_addr` and related functionality * add bounds check and use load instead of memoryRebound --- Sources/NIOSSL/IdentityVerification.swift | 17 +- Sources/NIOSSL/SSLCertificate.swift | 147 ++------------ Sources/NIOSSL/SubjectAlternativeName.swift | 203 ++++++++++++++++++++ Tests/NIOSSLTests/SSLCertificateTest.swift | 39 ++-- 4 files changed, 247 insertions(+), 159 deletions(-) create mode 100644 Sources/NIOSSL/SubjectAlternativeName.swift diff --git a/Sources/NIOSSL/IdentityVerification.swift b/Sources/NIOSSL/IdentityVerification.swift index 2c0b9c73..220f9468 100644 --- a/Sources/NIOSSL/IdentityVerification.swift +++ b/Sources/NIOSSL/IdentityVerification.swift @@ -135,19 +135,24 @@ private func validIdentityForService(serverHostname: Array?, // them, and then refuse to check the commonName field. If there are no SAN fields to // validate against, we'll check commonName. var checkedMatch = false - if let alternativeNames = leafCertificate.subjectAlternativeNames() { + if let alternativeNames = leafCertificate._subjectAlternativeNames() { for name in alternativeNames { checkedMatch = true - switch name { - case .dnsName(let dnsName): + switch name.nameType { + case .dnsName: + let dnsName = Array(name.contents) if matchHostname(ourHostname: serverHostnameSlice, firstPeriodIndex: firstPeriodIndex, dnsName: dnsName) { return true } - case .ipAddress(let ip): - if matchIpAddress(socketAddress: socketAddress, certificateIP: ip) { + case .ipAddress: + if let ip = _SubjectAlternativeName.IPAddress(name), + matchIpAddress(socketAddress: socketAddress, certificateIP: ip) + { return true } + default: + continue } } } @@ -187,7 +192,7 @@ private func matchHostname(ourHostname: ArraySlice?, firstPeriodIndex: Ar } -private func matchIpAddress(socketAddress: SocketAddress, certificateIP: NIOSSLCertificate.IPAddress) -> Bool { +private func matchIpAddress(socketAddress: SocketAddress, certificateIP: _SubjectAlternativeName.IPAddress) -> Bool { // These match if the two underlying IP address structures match. switch (socketAddress, certificateIP) { case (.v4(let address), .ipv4(var addr2)): diff --git a/Sources/NIOSSL/SSLCertificate.swift b/Sources/NIOSSL/SSLCertificate.swift index 4fb68bb2..8d1fe4a0 100644 --- a/Sources/NIOSSL/SSLCertificate.swift +++ b/Sources/NIOSSL/SSLCertificate.swift @@ -52,16 +52,6 @@ public class NIOSSLCertificate { private var ref: OpaquePointer { return self._ref } - - internal enum AlternativeName { - case dnsName([UInt8]) - case ipAddress(IPAddress) - } - - internal enum IPAddress { - case ipv4(in_addr) - case ipv6(in6_addr) - } public var serialNumber: [UInt8] { let serialNumber = CNIOBoringSSL_X509_get_serialNumber(self.ref)! @@ -174,12 +164,12 @@ public class NIOSSLCertificate { return NIOSSLCertificate(withOwnedReference: pointer) } - /// Get a sequence of the alternative names in the certificate. - internal func subjectAlternativeNames() -> SubjectAltNameSequence? { + /// Get a collection of the alternative names in the certificate. + public func _subjectAlternativeNames() -> _SubjectAlternativeNames? { guard let sanExtension = CNIOBoringSSL_X509_get_ext_d2i(self.ref, NID_subject_alt_name, nil, nil) else { return nil } - return SubjectAltNameSequence(nameStack: OpaquePointer(sanExtension)) + return _SubjectAlternativeNames(nameStack: OpaquePointer(sanExtension)) } /// Extracts the SHA1 hash of the subject name before it has been truncated. @@ -407,80 +397,6 @@ extension NIOSSLCertificate: Hashable { } } -/// A helper sequence object that enables us to represent subject alternative names -/// as an iterable Swift sequence. -internal class SubjectAltNameSequence: Sequence, IteratorProtocol { - typealias Element = NIOSSLCertificate.AlternativeName - - private let nameStack: OpaquePointer - private var nextIdx: Int - private let stackSize: Int - - init(nameStack: OpaquePointer) { - self.nameStack = nameStack - self.stackSize = CNIOBoringSSLShims_sk_GENERAL_NAME_num(nameStack) - self.nextIdx = 0 - } - - private func addressFromBytes(bytes: UnsafeBufferPointer) -> NIOSSLCertificate.IPAddress? { - switch bytes.count { - case 4: - let addr = bytes.baseAddress?.withMemoryRebound(to: in_addr.self, capacity: 1) { - return $0.pointee - } - guard let innerAddr = addr else { - return nil - } - return .ipv4(innerAddr) - case 16: - let addr = bytes.baseAddress?.withMemoryRebound(to: in6_addr.self, capacity: 1) { - return $0.pointee - } - guard let innerAddr = addr else { - return nil - } - return .ipv6(innerAddr) - default: - return nil - } - } - - func next() -> NIOSSLCertificate.AlternativeName? { - guard self.nextIdx < self.stackSize else { - return nil - } - - guard let name = CNIOBoringSSLShims_sk_GENERAL_NAME_value(self.nameStack, self.nextIdx) else { - fatalError("Unexpected null pointer when unwrapping SAN value") - } - - self.nextIdx += 1 - - switch name.pointee.type { - case GEN_DNS: - let namePtr = UnsafeBufferPointer(start: CNIOBoringSSL_ASN1_STRING_get0_data(name.pointee.d.ia5), - count: Int(CNIOBoringSSL_ASN1_STRING_length(name.pointee.d.ia5))) - let nameString = [UInt8](namePtr) - return .dnsName(nameString) - case GEN_IPADD: - let addrPtr = UnsafeBufferPointer(start: CNIOBoringSSL_ASN1_STRING_get0_data(name.pointee.d.ia5), - count: Int(CNIOBoringSSL_ASN1_STRING_length(name.pointee.d.ia5))) - guard let addr = addressFromBytes(bytes: addrPtr) else { - // This should throw, but we can't throw from next(). Skip this instead. - return self.next() - } - return .ipAddress(addr) - default: - // We don't recognise this name type. Skip it. - return next() - } - } - - deinit { - CNIOBoringSSL_GENERAL_NAMES_free(self.nameStack) - } -} - extension NIOSSLCertificate: CustomStringConvertible { public var description: String { @@ -490,13 +406,18 @@ extension NIOSSLCertificate: CustomStringConvertible { let commonName = String(decoding: commonNameBytes, as: UTF8.self) desc += ";common_name=" + commonName } - if let alternativeName = self.subjectAlternativeNames() { - let altNames = alternativeName.map { name in - switch name { - case .dnsName(let bytes): - return String(decoding: bytes, as: UTF8.self) - case .ipAddress(let address): - return String(describing: address) + if let alternativeName = self._subjectAlternativeNames() { + let altNames = alternativeName.compactMap { name in + switch name.nameType { + case .dnsName: + return String(decoding: name.contents, as: UTF8.self) + case .ipAddress: + guard let ipAddress = _SubjectAlternativeName.IPAddress(name) else { + return nil + } + return ipAddress.description + default: + return nil } }.joined(separator: ",") desc += ";alternative_names=\(altNames)" @@ -506,44 +427,6 @@ extension NIOSSLCertificate: CustomStringConvertible { } -extension NIOSSLCertificate.IPAddress: CustomStringConvertible { - - private static let ipv4AddressLength = 16 - private static let ipv6AddressLength = 46 - - /// A string representation of the IP address. - /// E.g. IPv4: `192.168.0.1` - /// E.g. IPv6: `2001:db8::1` - public var description: String { - switch self { - case .ipv4(let addr): - return self.ipv4ToString(addr) - case .ipv6(let addr): - return self.ipv6ToString(addr) - } - } - - private func ipv4ToString(_ address: in_addr) -> String { - var address = address - var dest: [CChar] = Array(repeating: 0, count: NIOSSLCertificate.IPAddress.ipv4AddressLength) - dest.withUnsafeMutableBufferPointer { pointer in - let result = inet_ntop(AF_INET, &address, pointer.baseAddress!, socklen_t(pointer.count)) - precondition(result != nil, "The IP address was invalid. This should never happen as we're within the IP address struct.") - } - return String(cString: &dest) - } - - private func ipv6ToString(_ address: in6_addr) -> String { - var address = address - var dest: [CChar] = Array(repeating: 0, count: NIOSSLCertificate.IPAddress.ipv6AddressLength) - dest.withUnsafeMutableBufferPointer { pointer in - let result = inet_ntop(AF_INET6, &address, pointer.baseAddress!, socklen_t(pointer.count)) - precondition(result != nil, "The IP address was invalid. This should never happen as we're within the IP address struct.") - } - return String(cString: &dest) - } -} - extension UnsafePointer where Pointee == ASN1_TIME { var timeSinceEpoch: time_t { let epochTime = CNIOBoringSSL_ASN1_TIME_new()! diff --git a/Sources/NIOSSL/SubjectAlternativeName.swift b/Sources/NIOSSL/SubjectAlternativeName.swift new file mode 100644 index 00000000..41a26a36 --- /dev/null +++ b/Sources/NIOSSL/SubjectAlternativeName.swift @@ -0,0 +1,203 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +@_implementationOnly import CNIOBoringSSL +@_implementationOnly import CNIOBoringSSLShims + +#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +import Darwin.C +#elseif os(Linux) || os(FreeBSD) || os(Android) +import Glibc +#else +#error("unsupported os") +#endif + +/// Collection of all Subject Alternative Names from a `NIOSSLCertificate` +public struct _SubjectAlternativeNames { + + @usableFromInline + internal final class Storage { + + fileprivate let nameStack: OpaquePointer + @usableFromInline internal let stackSize: Int + + internal init(nameStack: OpaquePointer) { + self.nameStack = nameStack + self.stackSize = CNIOBoringSSLShims_sk_GENERAL_NAME_num(nameStack) + } + + public subscript(position: Int) -> Element { + guard let name = CNIOBoringSSLShims_sk_GENERAL_NAME_value(self.nameStack, position) else { + fatalError("Unexpected null pointer when unwrapping SAN value") + } + + let contents = UnsafeBufferPointer( + start: CNIOBoringSSL_ASN1_STRING_get0_data(name.pointee.d.ia5), + count: Int(CNIOBoringSSL_ASN1_STRING_length(name.pointee.d.ia5)) + ) + return .init(nameType: .init(name.pointee.type), contents: .init(collection: self, buffer: contents)) + } + + deinit { + CNIOBoringSSL_GENERAL_NAMES_free(self.nameStack) + } + } + + + @usableFromInline internal var storage: Storage + + internal init(nameStack: OpaquePointer) { + self.storage = .init(nameStack: nameStack) + } +} + +extension _SubjectAlternativeNames: RandomAccessCollection { + + @inlinable public subscript(position: Int) -> _SubjectAlternativeName { + precondition(self.indices.contains(position), "index \(position) out of bounds") + return self.storage[position] + } + + @inlinable public var startIndex: Int { 0 } + @inlinable public var endIndex: Int { self.storage.stackSize } +} + +public struct _SubjectAlternativeName { + + public struct NameType: Hashable { + public var rawValue: Int + + public init(_ rawCode: Int) { + self.rawValue = rawCode + } + + fileprivate init(_ rawCode: Int32) { + self.init(Int(rawCode)) + } + + public static let email = Self(GEN_EMAIL) + public static let dnsName = Self(GEN_DNS) + public static let ipAddress = Self(GEN_IPADD) + } + + public struct Contents { + // only part of this type to keep a strong reference to the underlying storage of `buffer` + private let collection: _SubjectAlternativeNames.Storage + // lifetime automatically managed by `collection` + @usableFromInline internal let buffer: UnsafeBufferPointer + + internal init(collection: _SubjectAlternativeNames.Storage, buffer: UnsafeBufferPointer) { + self.collection = collection + self.buffer = buffer + } + + @inlinable public func withUnsafeBufferPointer( + _ body: (UnsafeBufferPointer) throws -> Result + ) rethrows -> Result { + try body(self.buffer) + } + } + + // should be replaced by `swift-nio`s `IPAddress` once https://github.com/apple/swift-nio/issues/1650 is resolved + internal enum IPAddress { + case ipv4(in_addr) + case ipv6(in6_addr) + } + + public var nameType: NameType + public var contents: Contents +} + +extension _SubjectAlternativeName.Contents: RandomAccessCollection { + + @inlinable public var startIndex: Int { self.buffer.startIndex } + @inlinable public var endIndex: Int { self.buffer.endIndex } + + @inlinable public subscript(position: Int) -> UInt8 { + precondition(self.indices.contains(position), "index \(position) out of bounds") + return self.buffer[position] + } +} + +extension _SubjectAlternativeName.IPAddress { + + internal init?(_ subjectAlternativeName: _SubjectAlternativeName) { + guard subjectAlternativeName.nameType == .ipAddress else { + return nil + } + switch subjectAlternativeName.contents.count { + case 4: + let addr = subjectAlternativeName.contents.withUnsafeBufferPointer { + $0.baseAddress.map { + UnsafeRawPointer($0).load(as: in_addr.self) + } + } + guard let innerAddr = addr else { + return nil + } + self = .ipv4(innerAddr) + case 16: + let addr = subjectAlternativeName.contents.withUnsafeBufferPointer { + $0.baseAddress.map { + UnsafeRawPointer($0).load(as: in6_addr.self) + } + } + guard let innerAddr = addr else { + return nil + } + self = .ipv6(innerAddr) + default: + return nil + } + } +} + +extension _SubjectAlternativeName.IPAddress: CustomStringConvertible { + + private static let ipv4AddressLength = 16 + private static let ipv6AddressLength = 46 + + /// A string representation of the IP address. + /// E.g. IPv4: `192.168.0.1` + /// E.g. IPv6: `2001:db8::1` + public var description: String { + switch self { + case .ipv4(let addr): + return Self.ipv4ToString(addr) + case .ipv6(let addr): + return Self.ipv6ToString(addr) + } + } + + static private func ipv4ToString(_ address: in_addr) -> String { + + var address = address + var dest: [CChar] = Array(repeating: 0, count: Self.ipv4AddressLength) + dest.withUnsafeMutableBufferPointer { pointer in + let result = inet_ntop(AF_INET, &address, pointer.baseAddress!, socklen_t(pointer.count)) + precondition(result != nil, "The IP address was invalid. This should never happen as we're within the IP address struct.") + } + return String(cString: &dest) + } + + static private func ipv6ToString(_ address: in6_addr) -> String { + var address = address + var dest: [CChar] = Array(repeating: 0, count: Self.ipv6AddressLength) + dest.withUnsafeMutableBufferPointer { pointer in + let result = inet_ntop(AF_INET6, &address, pointer.baseAddress!, socklen_t(pointer.count)) + precondition(result != nil, "The IP address was invalid. This should never happen as we're within the IP address struct.") + } + return String(cString: &dest) + } +} diff --git a/Tests/NIOSSLTests/SSLCertificateTest.swift b/Tests/NIOSSLTests/SSLCertificateTest.swift index bc5119a3..e3e1bbe8 100644 --- a/Tests/NIOSSLTests/SSLCertificateTest.swift +++ b/Tests/NIOSSLTests/SSLCertificateTest.swift @@ -317,33 +317,30 @@ class SSLCertificateTest: XCTestCase { precondition(inet_pton(AF_INET, "192.168.0.1", &v4addr) == 1) precondition(inet_pton(AF_INET6, "2001:db8::1", &v6addr) == 1) - let expectedSanFields: [NIOSSLCertificate.AlternativeName] = [ - .dnsName(Array("localhost".utf8)), - .dnsName(Array("example.com".utf8)), - .ipAddress(.ipv4(v4addr)), - .ipAddress(.ipv6(v6addr)), - ] let cert = try NIOSSLCertificate(bytes: .init(multiSanCert.utf8), format: .pem) - let sans = [NIOSSLCertificate.AlternativeName](cert.subjectAlternativeNames()!) - - XCTAssertEqual(sans.count, expectedSanFields.count) - for index in 0...size), 0) - case (.ipAddress(.ipv6(var actualAddr)), .ipAddress(.ipv6(var expectedAddr))): - XCTAssertEqual(memcmp(&actualAddr, &expectedAddr, MemoryLayout.size), 0) - default: - XCTFail("Invalid entry in sans.") - } + guard let sans = cert._subjectAlternativeNames() else { + return XCTFail("could not get subject alternative names") + } + XCTAssertEqual(sans.count, 5) + XCTAssertEqual(sans[0].nameType, .dnsName) + XCTAssertEqual(String(decoding: sans[0].contents, as: UTF8.self), "localhost") + XCTAssertEqual(sans[1].nameType, .dnsName) + XCTAssertEqual(String(decoding: sans[1].contents, as: UTF8.self), "example.com") + XCTAssertEqual(sans[2].nameType, .email) + XCTAssertEqual(String(decoding: sans[2].contents, as: UTF8.self), "user@example.com") + XCTAssertEqual(sans[3].nameType, .ipAddress) + withUnsafeBytes(of: &v4addr) { v4addr in + XCTAssertEqual(Array(sans[3].contents), Array(v4addr)) + } + XCTAssertEqual(sans[4].nameType, .ipAddress) + withUnsafeBytes(of: &v6addr) { v6addr in + XCTAssertEqual(Array(sans[4].contents), Array(v6addr)) } } func testNonexistentSan() throws { let cert = try NIOSSLCertificate(bytes: .init(samplePemCert.utf8), format: .pem) - XCTAssertNil(cert.subjectAlternativeNames()) + XCTAssertNil(cert._subjectAlternativeNames()) } func testCommonName() throws {