mirror of
https://github.com/apple/swift-certificates
synced 2026-11-22 04:20:39 +00:00
Initial commit
This commit is contained in:
commit
42be2505cc
60 files changed
+8082
No files matched your search
+11
@@ -0,0 +1,11 @@
|
||||
.DS_Store
|
||||
/.build
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
DerivedData/
|
||||
.swiftpm/config/registries.json
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.netrc
|
||||
Package.resolved
|
||||
.swiftpm
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// swift-tools-version: 5.7
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "swift-certificate",
|
||||
platforms: [
|
||||
.macOS(.v10_15),
|
||||
.iOS(.v13),
|
||||
.watchOS(.v6),
|
||||
.tvOS(.v13),
|
||||
],
|
||||
products: [
|
||||
.library(
|
||||
name: "X509",
|
||||
targets: ["X509"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-crypto.git", from: "2.1.0"),
|
||||
.package(url: "https://github.com/apple/swift-asn1.git", .upToNextMinor(from: "0.2.0")),
|
||||
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(
|
||||
name: "X509",
|
||||
dependencies: [
|
||||
.product(name: "SwiftASN1", package: "swift-asn1"),
|
||||
.product(name: "Crypto", package: "swift-crypto"),
|
||||
.product(name: "_CryptoExtras", package: "swift-crypto"),
|
||||
]),
|
||||
.testTarget(
|
||||
name: "X509Tests",
|
||||
dependencies: [
|
||||
"X509",
|
||||
.product(name: "Crypto", package: "swift-crypto"),
|
||||
]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,284 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
import SwiftASN1
|
||||
|
||||
/// A representation of an X.509 certificate object.
|
||||
///
|
||||
/// X.509 certificates are a commonly-used identity format to cryptographically
|
||||
/// attest to the identity of an actor in a system. They form part of the X.509
|
||||
/// standard created by the ITU-T for defining a public key infrastructure (PKI).
|
||||
/// X.509-style PKIs are commonly used in cases where it is necessary to delegate
|
||||
/// the authority to attest to an actor's identity to a small number of trusted
|
||||
/// parties (called Certificate Authorities).
|
||||
///
|
||||
/// The most common usage of X.509 certificates today is as part of the WebPKI,
|
||||
/// where they are used to secure TLS connections to websites. X.509 certificates
|
||||
/// are also used in a wide range of other TLS-based communications, as well as
|
||||
/// in code signing infrastructure.
|
||||
///
|
||||
/// This type is intended to be useful for users both to create new ``Certificate``
|
||||
/// objects, and to handle existing ones that they have received. In particular,
|
||||
/// users need to be able to create ``Certificate`` objects directly (in the case
|
||||
/// of self-signed certificates) and from Certificate Signing Requests, as well
|
||||
/// as from their serialized DER representation.
|
||||
///
|
||||
/// ### Structure
|
||||
///
|
||||
/// ``Certificate`` is a representation of an X.509v3 certificate, as defined in
|
||||
/// [RFC 5280](https://datatracker.ietf.org/doc/html/rfc5280.html). It provides
|
||||
/// support for the full range of features in RFC 5280.
|
||||
///
|
||||
/// The type has two main goals. The first is that it aims to be able to store and
|
||||
/// represent a parsed X.509 certificate issued by an arbitrary system in full
|
||||
/// fidelity. As the X.509 standards have evolved over time, a number of certificates
|
||||
/// exist in circulation that do not meet the current best practice standards. It is
|
||||
/// important for this type to be able to represent these older certificates.
|
||||
///
|
||||
/// The second goal is to make it possible for users to easily construct _new_
|
||||
/// ``Certificate`` objects from whole cloth. To achieve this there are a number of
|
||||
/// higher-level APIs that can be used to construct the constituent parts of the
|
||||
/// certificate. These are discussed at length in their relevant API documentation
|
||||
/// (e.g. ``Certificate/Extensions-swift.struct`` & ``DistinguishedName``).
|
||||
///
|
||||
/// Both of these goals encourage this type to be immutable. A ``Certificate`` represents
|
||||
/// a specific assertion of identity. Its ``Certificate/signature-swift.property`` is signed
|
||||
/// across the rest of the data. Allowing users to change this data makes it easy to accidentally modify
|
||||
/// a ``Certificate`` in one part of your code and not realise that the signature has inevitably
|
||||
/// been invalidated.
|
||||
public struct Certificate {
|
||||
/// The X.509 version of this certificate.
|
||||
///
|
||||
/// This should be set to ``Certificate/Version-swift.struct/v3`` in
|
||||
/// almost all cases.
|
||||
@inlinable
|
||||
public var version: Version {
|
||||
self.tbsCertificate.version
|
||||
}
|
||||
|
||||
/// The serial number of this certificate.
|
||||
///
|
||||
/// This should be a unique, large, random number.
|
||||
@inlinable
|
||||
public var serialNumber: SerialNumber {
|
||||
self.tbsCertificate.serialNumber
|
||||
}
|
||||
|
||||
/// The public key associated with this certificate.
|
||||
///
|
||||
/// When validating that a certificate belongs to a service, that service should be able to
|
||||
/// produce cryptographic proof that it holds the private key associated with this public key.
|
||||
@inlinable
|
||||
public var publicKey: PublicKey {
|
||||
self.tbsCertificate.publicKey
|
||||
}
|
||||
|
||||
/// The date before which this certificate is not valid.
|
||||
@inlinable
|
||||
public var notValidBefore: Date {
|
||||
// TODO: Do we need to do this conversion every time? Hard to be sure.
|
||||
// Need to work out how costly it is.
|
||||
Date(self.tbsCertificate.validity.notBefore)!
|
||||
}
|
||||
|
||||
/// The date after which this certificate is not valid.
|
||||
@inlinable
|
||||
public var notValidAfter: Date {
|
||||
Date(self.tbsCertificate.validity.notAfter)!
|
||||
}
|
||||
|
||||
/// The ``DistinguishedName`` of the issuer of this certificate.
|
||||
@inlinable
|
||||
public var issuer: DistinguishedName {
|
||||
self.tbsCertificate.issuer
|
||||
}
|
||||
|
||||
/// The ``DistinguishedName`` of the subject of this certificate.
|
||||
@inlinable
|
||||
public var subject: DistinguishedName {
|
||||
self.tbsCertificate.subject
|
||||
}
|
||||
|
||||
/// The extensions on this certificate.
|
||||
@inlinable
|
||||
public var extensions: Extensions {
|
||||
self.tbsCertificate.extensions
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal let tbsCertificate: TBSCertificate
|
||||
|
||||
/// The bytes of the `TBSCertificate` structure.
|
||||
///
|
||||
/// The ``signature-swift.property`` is calculated over these bytes.
|
||||
public let tbsCertificateBytes: ArraySlice<UInt8>
|
||||
|
||||
/// The signature attached to this certificate.
|
||||
///
|
||||
/// This signature is computed over ``tbsCertificateBytes``.
|
||||
public let signature: Signature
|
||||
|
||||
/// The signature algorithm used to produce ``signature-swift.property``.
|
||||
public let signatureAlgorithm: SignatureAlgorithm
|
||||
|
||||
/// Construct a certificate from constituent parts.
|
||||
///
|
||||
/// This API is generally not recommended for use, as it makes it very easy to construct a ``Certificate``
|
||||
/// whose ``signature-swift.property`` is not valid. However, for testing and validation purposes it is useful to be
|
||||
/// able to do this.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: The X.509 specification version for this certificate.
|
||||
/// - serialNumber: The serial number of this certificate.
|
||||
/// - publicKey: The public key associated with this certificate.
|
||||
/// - notValidBefore: The date before which this certificate is not valid.
|
||||
/// - notValidAfter: The date after which this certificate is not valid.
|
||||
/// - issuer: The ``DistinguishedName`` of the issuer of this certificate.
|
||||
/// - subject: The ``DistinguishedName`` of the subject of this certificate.
|
||||
/// - signatureAlgorithm: The signature algorithm used to produce `signature`
|
||||
/// - extensions: The extensions on this certificate.
|
||||
/// - signature: The signature attached to this certificate.
|
||||
@inlinable
|
||||
public init(
|
||||
version: Version,
|
||||
serialNumber: SerialNumber,
|
||||
publicKey: PublicKey,
|
||||
notValidBefore: Date,
|
||||
notValidAfter: Date,
|
||||
issuer: DistinguishedName,
|
||||
subject: DistinguishedName,
|
||||
signatureAlgorithm: SignatureAlgorithm,
|
||||
extensions: Extensions,
|
||||
signature: Signature
|
||||
) throws {
|
||||
self.tbsCertificate = TBSCertificate(
|
||||
version: version,
|
||||
serialNumber: serialNumber,
|
||||
signature: signatureAlgorithm,
|
||||
issuer: issuer,
|
||||
validity: try Validity(notBefore: .makeTime(from: notValidBefore), notAfter: .makeTime(from: notValidAfter)),
|
||||
subject: subject,
|
||||
publicKey: publicKey,
|
||||
extensions: extensions
|
||||
)
|
||||
// TODO: enforce that signature algorithm and signature have the same algorithm.
|
||||
self.signatureAlgorithm = signatureAlgorithm
|
||||
self.signature = signature
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(self.tbsCertificate)
|
||||
self.tbsCertificateBytes = serializer.serializedBytes[...]
|
||||
}
|
||||
|
||||
/// Construct a certificate from constituent parts, signed by an issuer key.
|
||||
///
|
||||
/// This API can be used to construct a ``Certificate`` directly, without an intermediary
|
||||
/// Certificate Signing Request. The ``signature-swift.property`` for this certificate will be produced
|
||||
/// automatically, using `issuerPrivateKey`.
|
||||
///
|
||||
/// This API can be used to construct a self-signed key by passing the private key for `publicKey` as the
|
||||
/// `issuerPrivateKey` argument.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: The X.509 specification version for this certificate.
|
||||
/// - serialNumber: The serial number of this certificate.
|
||||
/// - publicKey: The public key associated with this certificate.
|
||||
/// - notValidBefore: The date before which this certificate is not valid.
|
||||
/// - notValidAfter: The date after which this certificate is not valid.
|
||||
/// - issuer: The ``DistinguishedName`` of the issuer of this certificate.
|
||||
/// - subject: The ``DistinguishedName`` of the subject of this certificate.
|
||||
/// - signatureAlgorithm: The signature algorithm that will be used to produce `signature`. Must be compatible with the private key type.
|
||||
/// - extensions: The extensions on this certificate.
|
||||
/// - issuerPrivateKey: The private key to use to sign this certificate.
|
||||
@inlinable
|
||||
public init(
|
||||
version: Version,
|
||||
serialNumber: SerialNumber,
|
||||
publicKey: PublicKey,
|
||||
notValidBefore: Date,
|
||||
notValidAfter: Date,
|
||||
issuer: DistinguishedName,
|
||||
subject: DistinguishedName,
|
||||
signatureAlgorithm: SignatureAlgorithm,
|
||||
extensions: Extensions,
|
||||
issuerPrivateKey: PrivateKey
|
||||
) throws {
|
||||
self.tbsCertificate = TBSCertificate(
|
||||
version: version,
|
||||
serialNumber: serialNumber,
|
||||
signature: signatureAlgorithm,
|
||||
issuer: issuer,
|
||||
validity: try Validity(notBefore: .makeTime(from: notValidBefore), notAfter: .makeTime(from: notValidAfter)),
|
||||
subject: subject,
|
||||
publicKey: publicKey,
|
||||
extensions: extensions
|
||||
)
|
||||
// TODO: validate that signature algorithm is comoatible with the signature.
|
||||
self.signatureAlgorithm = signatureAlgorithm
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(self.tbsCertificate)
|
||||
let tbsCertificateBytes = serializer.serializedBytes[...]
|
||||
self.signature = try issuerPrivateKey.sign(tbsCertificateBytes: tbsCertificateBytes)
|
||||
self.tbsCertificateBytes = tbsCertificateBytes
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(tbsCertificate: TBSCertificate, signatureAlgorithm: AlgorithmIdentifier, signature: ASN1.ASN1BitString, tbsCertificateBytes: ArraySlice<UInt8>) throws {
|
||||
self.tbsCertificate = tbsCertificate
|
||||
self.signatureAlgorithm = SignatureAlgorithm(algorithmIdentifier: signatureAlgorithm)
|
||||
self.signature = try Signature(signatureAlgorithm: self.signatureAlgorithm, signatureBytes: signature)
|
||||
self.tbsCertificateBytes = tbsCertificateBytes
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate: Hashable { }
|
||||
|
||||
extension Certificate: Sendable { }
|
||||
|
||||
extension Certificate: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
public static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
guard let tbsCertificateNode = nodes.next() else {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
let tbsCertificate = try TBSCertificate(asn1Encoded: tbsCertificateNode)
|
||||
let signatureAlgorithm = try AlgorithmIdentifier(asn1Encoded: &nodes)
|
||||
let signature = try ASN1.ASN1BitString(asn1Encoded: &nodes)
|
||||
return try Certificate(tbsCertificate: tbsCertificate, signatureAlgorithm: signatureAlgorithm, signature: signature, tbsCertificateBytes: tbsCertificateNode.encodedBytes)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.tbsCertificate)
|
||||
try coder.serialize(AlgorithmIdentifier(self.signatureAlgorithm))
|
||||
try coder.serialize(ASN1.ASN1BitString(self.signature))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@preconcurrency import Crypto
|
||||
@preconcurrency import _CryptoExtras
|
||||
|
||||
extension Certificate {
|
||||
/// A private key that can be used with a certificate.
|
||||
///
|
||||
/// This type provides an opaque wrapper around the various private key types
|
||||
/// provided by `swift-crypto`. Users are expected to construct this key from
|
||||
/// one of those types.
|
||||
///
|
||||
/// As private keys are never sent over the wire, this type does not offer
|
||||
/// support for being unwrapped back into the underlying key types.
|
||||
public struct PrivateKey {
|
||||
@usableFromInline
|
||||
var backing: BackingPrivateKey
|
||||
|
||||
@inlinable
|
||||
internal init(backing: BackingPrivateKey) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
/// Construct a private key wrapping a P256 private key.
|
||||
/// - Parameter p256: The P256 private key to wrap.
|
||||
@inlinable
|
||||
public init(_ p256: P256.Signing.PrivateKey) {
|
||||
self.backing = .p256(p256)
|
||||
}
|
||||
|
||||
/// Construct a private key wrapping a P384 private key.
|
||||
/// - Parameter p384: The P384 private key to wrap.
|
||||
@inlinable
|
||||
public init(_ p384: P384.Signing.PrivateKey) {
|
||||
self.backing = .p384(p384)
|
||||
}
|
||||
|
||||
/// Construct a private key wrapping a P521 private key.
|
||||
/// - Parameter p521: The P521 private key to wrap.
|
||||
@inlinable
|
||||
public init(_ p521: P521.Signing.PrivateKey) {
|
||||
self.backing = .p521(p521)
|
||||
}
|
||||
|
||||
/// Construct a private key wrapping a RSA private key.
|
||||
/// - Parameter rsa: The RSA private key to wrap.
|
||||
@inlinable
|
||||
public init(_ rsa: _RSA.Signing.PrivateKey) {
|
||||
self.backing = .rsa(rsa)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func sign(tbsCertificateBytes: ArraySlice<UInt8>) throws -> Signature {
|
||||
switch self.backing {
|
||||
case .p256(let p256):
|
||||
let sig = try p256.signature(for: tbsCertificateBytes)
|
||||
return Signature(backing: .p256(sig))
|
||||
case .p384(let p384):
|
||||
let sig = try p384.signature(for: tbsCertificateBytes)
|
||||
return Signature(backing: .p384(sig))
|
||||
case .p521(let p521):
|
||||
let sig = try p521.signature(for: tbsCertificateBytes)
|
||||
return Signature(backing: .p521(sig))
|
||||
case .rsa:
|
||||
fatalError("TODO: not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtain the ``Certificate/PublicKey-swift.struct`` corresponding to
|
||||
/// this private key.
|
||||
@inlinable
|
||||
public var publicKey: PublicKey {
|
||||
switch self.backing {
|
||||
case .p256(let p256):
|
||||
return PublicKey(p256.publicKey)
|
||||
case .p384(let p384):
|
||||
return PublicKey(p384.publicKey)
|
||||
case .p521(let p521):
|
||||
return PublicKey(p521.publicKey)
|
||||
case .rsa(let rsa):
|
||||
return PublicKey(rsa.publicKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.PrivateKey: Hashable { }
|
||||
|
||||
extension Certificate.PrivateKey: Sendable { }
|
||||
|
||||
extension Certificate.PrivateKey: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.PrivateKey {
|
||||
@usableFromInline
|
||||
enum BackingPrivateKey: Hashable, Sendable {
|
||||
case p256(Crypto.P256.Signing.PrivateKey)
|
||||
case p384(Crypto.P384.Signing.PrivateKey)
|
||||
case p521(Crypto.P521.Signing.PrivateKey)
|
||||
case rsa(_CryptoExtras._RSA.Signing.PrivateKey)
|
||||
|
||||
@inlinable
|
||||
static func ==(lhs: BackingPrivateKey, rhs: BackingPrivateKey) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.p256(let l), .p256(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.p384(let l), .p384(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.p521(let l), .p521(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.rsa(let l), .rsa(let r)):
|
||||
return l.derRepresentation == r.derRepresentation
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func hash(into hasher: inout Hasher) {
|
||||
switch self {
|
||||
case .p256(let digest):
|
||||
hasher.combine(0)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .p384(let digest):
|
||||
hasher.combine(1)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .p521(let digest):
|
||||
hasher.combine(2)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .rsa(let digest):
|
||||
hasher.combine(3)
|
||||
hasher.combine(digest.derRepresentation)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
@preconcurrency import Crypto
|
||||
@preconcurrency import _CryptoExtras
|
||||
|
||||
extension Certificate {
|
||||
/// A public key that can be used with a certificate.
|
||||
///
|
||||
/// This type provides an opaque wrapper around the various public key types
|
||||
/// provided by `swift-crypto`. Users are expected to construct this key from
|
||||
/// one of those types, or to decode it from the network.
|
||||
public struct PublicKey {
|
||||
@usableFromInline
|
||||
var backing: BackingPublicKey
|
||||
|
||||
@inlinable
|
||||
internal init(spki: SubjectPublicKeyInfo) throws {
|
||||
switch spki.algorithmIdentifier {
|
||||
case .p256PublicKey:
|
||||
let key = try P256.Signing.PublicKey(x963Representation: spki.key.bytes)
|
||||
self.backing = .p256(key)
|
||||
case .p384PublicKey:
|
||||
let key = try P384.Signing.PublicKey(x963Representation: spki.key.bytes)
|
||||
self.backing = .p384(key)
|
||||
case .p521PublicKey:
|
||||
let key = try P521.Signing.PublicKey(x963Representation: spki.key.bytes)
|
||||
self.backing = .p521(key)
|
||||
case .rsaPublicKey:
|
||||
// TODO: Confirm that the derRepresentation here only tolerates the representation
|
||||
// we want to allow.
|
||||
let key = try _RSA.Signing.PublicKey(derRepresentation: spki.key.bytes)
|
||||
self.backing = .rsa(key)
|
||||
default:
|
||||
// TODO(cory): RSA keys
|
||||
throw CertificateError.unsupportedPublicKeyAlgorithm(reason: "\(spki.algorithmIdentifier)")
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(backing: BackingPublicKey) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
/// Construct a public key wrapping a P256 public key.
|
||||
/// - Parameter p256: The P256 public key to wrap.
|
||||
@inlinable
|
||||
public init(_ p256: P256.Signing.PublicKey) {
|
||||
self.backing = .p256(p256)
|
||||
}
|
||||
|
||||
/// Construct a public key wrapping a P384 public key.
|
||||
/// - Parameter p384: The P384 public key to wrap.
|
||||
@inlinable
|
||||
public init(_ p384: P384.Signing.PublicKey) {
|
||||
self.backing = .p384(p384)
|
||||
}
|
||||
|
||||
/// Construct a public key wrapping a P521 public key.
|
||||
/// - Parameter p521: The P521 public key to wrap.
|
||||
@inlinable
|
||||
public init(_ p521: P521.Signing.PublicKey) {
|
||||
self.backing = .p521(p521)
|
||||
}
|
||||
|
||||
/// Construct a public key wrapping a RSA public key.
|
||||
/// - Parameter rsa: The RSA public key to wrap.
|
||||
@inlinable
|
||||
public init(_ rsa: _RSA.Signing.PublicKey) {
|
||||
self.backing = .rsa(rsa)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.PublicKey {
|
||||
/// Confirms that `signature` is a valid signature for `certificate`, created by the
|
||||
/// private key associated with this public key.
|
||||
///
|
||||
/// This function abstracts over the need to unwrap both the signature and public key to
|
||||
/// confirm they're of matching type before we validate the signature.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signature: The signature to validate against `certificate`.
|
||||
/// - certificate: The `certificate` to validate against `signature`.
|
||||
/// - Returns: Whether the signature was produced by signing `certificate` with the private key corresponding to this public key.
|
||||
@inlinable
|
||||
public func isValidSignature(_ signature: Certificate.Signature, for certificate: Certificate) -> Bool {
|
||||
// TODO(cory): I'm not sure this API is sensible, but for now I'm sticking with it.
|
||||
switch (signature.backing, self.backing) {
|
||||
case (.p256(let p256Sig), .p256(let p256Key)):
|
||||
return p256Key.isValidSignature(p256Sig, for: certificate.tbsCertificateBytes)
|
||||
case (.p384(let p384Sig), .p384(let p384Key)):
|
||||
return p384Key.isValidSignature(p384Sig, for: certificate.tbsCertificateBytes)
|
||||
case (.p521(let p521Sig), .p521(let p521Key)):
|
||||
return p521Key.isValidSignature(p521Sig, for: certificate.tbsCertificateBytes)
|
||||
case (.rsa(let rsaSig), .rsa(let rsaKey)):
|
||||
switch certificate.signatureAlgorithm {
|
||||
case .sha1WithRSAEncryption:
|
||||
let digest = Insecure.SHA1.hash(data: certificate.tbsCertificateBytes)
|
||||
return rsaKey.isValidSignature(rsaSig, for: digest, padding: .insecurePKCS1v1_5)
|
||||
case .sha256WithRSAEncryption:
|
||||
let digest = SHA256.hash(data: certificate.tbsCertificateBytes)
|
||||
return rsaKey.isValidSignature(rsaSig, for: digest, padding: .insecurePKCS1v1_5)
|
||||
case .sha384WithRSAEncryption:
|
||||
let digest = SHA384.hash(data: certificate.tbsCertificateBytes)
|
||||
return rsaKey.isValidSignature(rsaSig, for: digest, padding: .insecurePKCS1v1_5)
|
||||
case .sha512WithRSAEncryption:
|
||||
let digest = SHA512.hash(data: certificate.tbsCertificateBytes)
|
||||
return rsaKey.isValidSignature(rsaSig, for: digest, padding: .insecurePKCS1v1_5)
|
||||
default:
|
||||
// Huh, we have an RSA signature but we don't know how to validate it.
|
||||
// TODO: Extend for PSS?
|
||||
return false
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.PublicKey: Hashable { }
|
||||
|
||||
extension Certificate.PublicKey: Sendable { }
|
||||
|
||||
extension Certificate.PublicKey: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.PublicKey {
|
||||
@usableFromInline
|
||||
enum BackingPublicKey: Hashable, Sendable {
|
||||
case p256(Crypto.P256.Signing.PublicKey)
|
||||
case p384(Crypto.P384.Signing.PublicKey)
|
||||
case p521(Crypto.P521.Signing.PublicKey)
|
||||
case rsa(_CryptoExtras._RSA.Signing.PublicKey)
|
||||
|
||||
@inlinable
|
||||
static func ==(lhs: BackingPublicKey, rhs: BackingPublicKey) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.p256(let l), .p256(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.p384(let l), .p384(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.p521(let l), .p521(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.rsa(let l), .rsa(let r)):
|
||||
return l.derRepresentation == r.derRepresentation
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func hash(into hasher: inout Hasher) {
|
||||
switch self {
|
||||
case .p256(let digest):
|
||||
hasher.combine(0)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .p384(let digest):
|
||||
hasher.combine(1)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .p521(let digest):
|
||||
hasher.combine(2)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .rsa(let digest):
|
||||
hasher.combine(3)
|
||||
hasher.combine(digest.derRepresentation)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SubjectPublicKeyInfo {
|
||||
@inlinable
|
||||
init(_ publicKey: Certificate.PublicKey) {
|
||||
let algorithmIdentifier: AlgorithmIdentifier
|
||||
let key: ASN1.ASN1BitString
|
||||
|
||||
switch publicKey.backing {
|
||||
case .p256(let p256):
|
||||
algorithmIdentifier = .p256PublicKey
|
||||
key = .init(bytes: ArraySlice(p256.x963Representation))
|
||||
case .p384(let p384):
|
||||
algorithmIdentifier = .p384PublicKey
|
||||
key = .init(bytes: ArraySlice(p384.x963Representation))
|
||||
case .p521(let p521):
|
||||
algorithmIdentifier = .p521PublicKey
|
||||
key = .init(bytes: ArraySlice(p521.x963Representation))
|
||||
case .rsa(let rsa):
|
||||
algorithmIdentifier = .rsaPublicKey
|
||||
key = .init(bytes: ArraySlice(rsa.derRepresentation))
|
||||
}
|
||||
|
||||
self.algorithmIdentifier = algorithmIdentifier
|
||||
self.key = key
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Certificate {
|
||||
/// A number that uniquely identifies a certificate issued by a specific
|
||||
/// certificate authority.
|
||||
///
|
||||
/// Serial numbers are often extremely large (up to 20 bytes), so they cannot typically
|
||||
/// be represented using a fixed-width integer type. This type therefore represents the
|
||||
/// raw big-endian bytes of the serial number, suitable for loading into a more specific
|
||||
/// type.
|
||||
public struct SerialNumber {
|
||||
/// The raw big-endian bytes of the serial number.
|
||||
public var bytes: ArraySlice<UInt8>
|
||||
|
||||
/// Construct a serial number from its raw big-endian bytes.
|
||||
/// - Parameter bytes: The raw big-endian bytes of the serial number.
|
||||
@inlinable
|
||||
public init(bytes: ArraySlice<UInt8>) {
|
||||
self.bytes = bytes
|
||||
}
|
||||
|
||||
/// Construct a serial number from its raw big-endian bytes.
|
||||
/// - Parameter bytes: The raw big-endian bytes of the serial number.
|
||||
@inlinable
|
||||
public init(bytes: [UInt8]) {
|
||||
self.bytes = bytes[...]
|
||||
}
|
||||
|
||||
/// Construct a serial number from its raw big-endian bytes.
|
||||
/// - Parameter bytes: The raw big-endian bytes of the serial number.
|
||||
@inlinable
|
||||
public init<Bytes: Collection>(bytes: Bytes) where Bytes.Element == UInt8 {
|
||||
self.bytes = ArraySlice(bytes)
|
||||
}
|
||||
|
||||
/// Construct a serial number from a fixed width integer.
|
||||
///
|
||||
/// In general this API should only be used for testing, as fixed width integers
|
||||
/// are not sufficiently large for use in certificates. Using this API for production
|
||||
/// use-cases may expose users to hash collision attacks on generated certificates.
|
||||
///
|
||||
/// - Parameter bytes: The raw big-endian bytes of the serial number.
|
||||
@inlinable
|
||||
public init<Number: FixedWidthInteger>(_ number: Number) {
|
||||
fatalError("TODO: Need ASN1 to implement")
|
||||
}
|
||||
|
||||
/// Construct a random 20-byte serial number.
|
||||
///
|
||||
/// Serial numbers should be generated randomly, and may contain up to 20 bytes. This
|
||||
/// initializer generates an appropriate serial number.
|
||||
@inlinable
|
||||
public init() {
|
||||
var rng = SystemRandomNumberGenerator()
|
||||
var bytes = [UInt8]()
|
||||
|
||||
while bytes.count < 20 {
|
||||
bytes.appendLittleEndianBytes(rng.next())
|
||||
}
|
||||
|
||||
self.bytes = bytes[..<20]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.SerialNumber: Hashable { }
|
||||
|
||||
extension Certificate.SerialNumber: Sendable { }
|
||||
|
||||
extension Certificate.SerialNumber: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension Array where Element == UInt8 {
|
||||
@inlinable
|
||||
mutating func appendLittleEndianBytes(_ number: UInt64) {
|
||||
let number = number.littleEndian
|
||||
|
||||
for byte in 0..<(MemoryLayout<UInt64>.size) {
|
||||
let shifted = number >> (byte * 8)
|
||||
self.append(UInt8(truncatingIfNeeded: shifted))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Certificate {
|
||||
/// The X.509 certificate version.
|
||||
///
|
||||
/// Almost all certificates in use today use X.509v3, and this should be the default for almost
|
||||
/// all use today. In very rare cases X.509v1 certificates can be found, but they should be avoided in
|
||||
/// almost all cases.
|
||||
public struct Version {
|
||||
@usableFromInline
|
||||
var rawValue: Int
|
||||
|
||||
@inlinable
|
||||
init(rawValue: Int) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// Corresponds to an X.509 v1 certificate.
|
||||
public static let v1 = Self(rawValue: 0)
|
||||
|
||||
/// Corresponds to an X.509 v3 certificate
|
||||
public static let v3 = Self(rawValue: 2)
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Version: Hashable { }
|
||||
|
||||
extension Certificate.Version: Sendable { }
|
||||
|
||||
extension Certificate.Version: Comparable {
|
||||
@inlinable
|
||||
public static func < (lhs: Certificate.Version, rhs: Certificate.Version) -> Bool {
|
||||
lhs.rawValue < rhs.rawValue
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Version: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// A distinguished name is a name that uniquely identifies a specific entity.
|
||||
///
|
||||
/// Distinguished names are a remnant of the X.500 directory system. In that system,
|
||||
/// distinguished names were the primary key, enabling the identification of a specific entity
|
||||
/// within the directory.
|
||||
///
|
||||
/// These use-cases are largely obsolete, but distinguished names continue to be used to identify
|
||||
/// both the subject of and issuer of a given X.509 certificate. In this context, the distinguished
|
||||
/// name is a largely opaque identifier that just happens to have a human-readable string representation.
|
||||
///
|
||||
/// The struture of a distinguished name reflects its X.500 roots. A distinguished name is conceptually
|
||||
/// an ordered sequence of ``RelativeDistinguishedName``s. This sequence is conceptually ordered by hierarchy, from least
|
||||
/// to most specific. Each ``RelativeDistinguishedName`` contains a collection of ``RelativeDistinguishedName/Attribute``s
|
||||
/// that are intended to be equivalent representations of the same idea. In common usage, each ``RelativeDistinguishedName``
|
||||
/// contains a single ``RelativeDistinguishedName/Attribute``.
|
||||
///
|
||||
/// As an example, the ``DistinguishedName`` that represents the Apple-operated intermediate certificate authority
|
||||
/// "Apple Public EV Server RSA CA 2 - G1" is:
|
||||
///
|
||||
/// ```swift
|
||||
/// try DistinguishedName([
|
||||
/// RelativeDistinguishedName([
|
||||
/// RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, printableString: "US"),
|
||||
/// ]),
|
||||
/// RelativeDistinguishedName([
|
||||
/// RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, printableString: "Apple Inc."),
|
||||
/// ]),
|
||||
/// RelativeDistinguishedName([
|
||||
/// RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, printableString: "Apple Public EV Server ECC CA 1 - G1"),
|
||||
/// ]),
|
||||
/// ])
|
||||
/// ```
|
||||
///
|
||||
/// The ``DistinguishedName`` type models this in its full complexity.
|
||||
///
|
||||
/// ``DistinguishedName`` is a collection of ``RelativeDistinguishedName``, making it easy to perform generic computations
|
||||
/// across the ``RelativeDistinguishedName``s that make up a full ``DistinguishedName``.
|
||||
///
|
||||
/// To make working with ``DistinguishedName`` easier, users have a number of convenience APIs for creating the most common
|
||||
/// kinds of ``DistinguishedName``. In addition to the example above (using ``init(_:)-3no37``), users can also create distinguished
|
||||
/// names that follow the "one ``RelativeDistinguishedName/Attribute`` per ``RelativeDistinguishedName``" pattern by passing
|
||||
/// a sequence of ``RelativeDistinguishedName/Attribute`` directly, which will be wrapped into ``RelativeDistinguishedName``
|
||||
/// objects. For example, the above ``DistinguishedName`` can also be represented by:
|
||||
///
|
||||
/// ```swift
|
||||
/// try DistinguishedName([
|
||||
/// RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, printableString: "US"),
|
||||
/// RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, printableString: "Apple Inc."),
|
||||
/// RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, printableString: "Apple Public EV Server ECC CA 1 - G1"),
|
||||
/// ])
|
||||
/// ```
|
||||
///
|
||||
/// This produces an identical ``DistinguishedName`` to the prior example.
|
||||
///
|
||||
/// Additionally, users can take advantage of ``DistinguishedNameBuilder`` to use a result builder DSL to construct ``DistinguishedName`` objects.
|
||||
/// The above distinguished name can further be represented as:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = try DistinguishedName {
|
||||
/// CountryName(printableString: "US")
|
||||
/// OrganizationName(printableString: "Apple Inc.")
|
||||
/// CommonName("Apple Public EV Server ECC CA 1 - G1")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This convenient shorthand is particularly valuable in testing, as well as in code that needs to generate certificates or CSRs.
|
||||
public struct DistinguishedName {
|
||||
@usableFromInline
|
||||
var rdns: [RelativeDistinguishedName]
|
||||
|
||||
/// Construct a ``DistinguishedName`` from a sequence of ``RelativeDistinguishedName``.
|
||||
///
|
||||
/// - Parameter rdns: The elements of this ``DistinguishedName``.
|
||||
@inlinable
|
||||
public init<RDNSequence: Sequence>(_ rdns: RDNSequence) where RDNSequence.Element == RelativeDistinguishedName {
|
||||
self.rdns = Array(rdns)
|
||||
}
|
||||
|
||||
/// Construct a ``DistinguishedName`` from a sequence of ``RelativeDistinguishedName/Attribute``.
|
||||
///
|
||||
/// This helper initializer will wrap each ``RelativeDistinguishedName/Attribute`` in a ``RelativeDistinguishedName``
|
||||
/// transparently.
|
||||
///
|
||||
/// - Parameter attributes: The sequence of ``RelativeDistinguishedName/Attribute``s that make up the ``DistinguishedName``.
|
||||
@inlinable
|
||||
public init<AttributeSequence: Sequence>(_ attributes: AttributeSequence) throws where AttributeSequence.Element == RelativeDistinguishedName.Attribute {
|
||||
// TODO: This is a bit expensive, should we special-case the "one AVA per RDN" pattern?
|
||||
self.rdns = try attributes.map { try RelativeDistinguishedName([$0]) }
|
||||
}
|
||||
|
||||
/// Construct a new empty ``DistinguishedName``.
|
||||
@inlinable
|
||||
public init() {
|
||||
self.rdns = []
|
||||
}
|
||||
|
||||
/// Construct a ``DistinguishedName`` using a DSL.
|
||||
///
|
||||
/// This API uses a result builder DSL to make it easier to construct complex
|
||||
/// ``DistinguishedName``s. As an example, a ``DistinguishedName`` can be constructed
|
||||
/// like this:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = try DistinguishedName {
|
||||
/// CountryName(printableString: "US")
|
||||
/// OrganizationName(printableString: "Apple Inc.")
|
||||
/// CommonName("Apple Public EV Server ECC CA 1 - G1")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter builder: The ``DistinguishedNameBuilder`` block.
|
||||
@inlinable
|
||||
public init(@DistinguishedNameBuilder builder: () throws -> DistinguishedName) throws {
|
||||
self = try builder()
|
||||
}
|
||||
}
|
||||
|
||||
extension DistinguishedName: Hashable { }
|
||||
|
||||
extension DistinguishedName: Sendable { }
|
||||
|
||||
extension DistinguishedName: RandomAccessCollection, MutableCollection, RangeReplaceableCollection {
|
||||
@inlinable
|
||||
public var startIndex: Int {
|
||||
self.rdns.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Int {
|
||||
self.rdns.endIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Int) -> RelativeDistinguishedName {
|
||||
get {
|
||||
self.rdns[position]
|
||||
}
|
||||
set {
|
||||
self.rdns[position] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func replaceSubrange<NewElements>(_ subrange: Range<Int>, with newElements: NewElements) where NewElements: Collection, RelativeDistinguishedName == NewElements.Element {
|
||||
self.rdns.replaceSubrange(subrange, with: newElements)
|
||||
}
|
||||
}
|
||||
|
||||
extension DistinguishedName: CustomStringConvertible {
|
||||
public var description: String {
|
||||
// TODO(cory): Relevant citation is probably https://www.rfc-editor.org/rfc/rfc4514
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension DistinguishedName: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
public static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self.rdns = try ASN1.sequence(of: RelativeDistinguishedName.self, identifier: identifier, rootNode: rootNode)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { rootCoder in
|
||||
for element in self.rdns {
|
||||
try element.serialize(into: &rootCoder)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Set the Common Name (CN) of a ``DistinguishedName``.
|
||||
///
|
||||
/// This type is used in ``DistinguishedNameBuilder`` contexts.
|
||||
public struct CommonName: RelativeDistinguishedNameConvertible {
|
||||
/// The value of the common name
|
||||
public var name: String
|
||||
|
||||
/// Construct a new common name
|
||||
///
|
||||
/// - Parameter name: The value of the common name
|
||||
@inlinable
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeRDN() throws -> RelativeDistinguishedName {
|
||||
return try RelativeDistinguishedName([
|
||||
try .init(type: .RDNAttributeType.commonName, utf8String: name)
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Set the Country Name (C) of a ``DistinguishedName``.
|
||||
///
|
||||
/// This type is used in ``DistinguishedNameBuilder`` contexts.
|
||||
public struct CountryName: RelativeDistinguishedNameConvertible {
|
||||
/// The value of the country name field.
|
||||
public var name: String
|
||||
|
||||
/// Construct a new country name
|
||||
///
|
||||
/// - Parameter name: The value of the country name
|
||||
@inlinable
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeRDN() throws -> RelativeDistinguishedName {
|
||||
return try RelativeDistinguishedName([
|
||||
try .init(type: .RDNAttributeType.countryName, utf8String: name)
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Provides a result-builder style DSL for constructing ``DistinguishedName`` values.
|
||||
///
|
||||
/// This DSL allows us to construct distinguished names straightforwardly, using their high-level representation instead of
|
||||
/// the awkward representation provided by sequences of ``RelativeDistinguishedName`` and
|
||||
/// ``RelativeDistinguishedName/Attribute``. For example, a simple ``DistinguishedName`` can be
|
||||
/// provided like this:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = try DistinguishedName {
|
||||
/// CountryName(printableString: "US")
|
||||
/// OrganizationName(printableString: "Apple Inc.")
|
||||
/// CommonName("Apple Public EV Server ECC CA 1 - G1")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Users can extend this syntax for their own extensions by conforming their semantic type to ``RelativeDistinguishedNameConvertible``.
|
||||
/// This is the only requirement for adding new extensions to this builder syntax.
|
||||
@resultBuilder
|
||||
public struct DistinguishedNameBuilder {
|
||||
@inlinable
|
||||
public static func buildExpression<Extension: RelativeDistinguishedNameConvertible>(_ expression: Extension) -> DistinguishedName {
|
||||
// TODO: Remove the try!
|
||||
try! DistinguishedName([expression.makeRDN()])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildBlock(_ components: DistinguishedName...) -> DistinguishedName {
|
||||
DistinguishedName(components.flatMap { $0 })
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildOptional(_ component: DistinguishedName?) -> DistinguishedName {
|
||||
component ?? DistinguishedName()
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildEither(first component: DistinguishedName) -> DistinguishedName {
|
||||
component
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildEither(second component: DistinguishedName) -> DistinguishedName {
|
||||
component
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildArray(_ components: [DistinguishedName]) -> DistinguishedName {
|
||||
DistinguishedName(components.flatMap { $0 })
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildLimitedAvailability(_ component: DistinguishedName) -> DistinguishedName {
|
||||
component
|
||||
}
|
||||
}
|
||||
|
||||
public protocol RelativeDistinguishedNameConvertible {
|
||||
func makeRDN() throws -> RelativeDistinguishedName
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Set the Locality Name (L) of a ``DistinguishedName``.
|
||||
///
|
||||
/// This type is used in ``DistinguishedNameBuilder`` contexts.
|
||||
public struct LocalityName: RelativeDistinguishedNameConvertible {
|
||||
/// The value of the locality name field.
|
||||
public var name: String
|
||||
|
||||
/// Construct a new locality name
|
||||
///
|
||||
/// - Parameter name: The value of the locality name
|
||||
@inlinable
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeRDN() throws -> RelativeDistinguishedName {
|
||||
return try RelativeDistinguishedName([
|
||||
try .init(type: .RDNAttributeType.localityName, utf8String: name)
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Set the Organization Name (O) of a ``DistinguishedName``.
|
||||
///
|
||||
/// This type is used in ``DistinguishedNameBuilder`` contexts.
|
||||
public struct OrganizationName: RelativeDistinguishedNameConvertible {
|
||||
/// The value of the organization name field.
|
||||
public var name: String
|
||||
|
||||
/// Construct a new organization name
|
||||
///
|
||||
/// - Parameter name: The value of the organization name
|
||||
@inlinable
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeRDN() throws -> RelativeDistinguishedName {
|
||||
return try RelativeDistinguishedName([
|
||||
try .init(type: .RDNAttributeType.organizationName, utf8String: name)
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Set the Organizational Unit Name (OU) of a ``DistinguishedName``.
|
||||
///
|
||||
/// This type is used in ``DistinguishedNameBuilder`` contexts.
|
||||
public struct OrganizationalUnitName: RelativeDistinguishedNameConvertible {
|
||||
/// The value of the organizational unit name field.
|
||||
public var name: String
|
||||
|
||||
/// Construct a new organizational unit name
|
||||
///
|
||||
/// - Parameter name: The value of the organizational unit name
|
||||
@inlinable
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeRDN() throws -> RelativeDistinguishedName {
|
||||
return try RelativeDistinguishedName([
|
||||
try .init(type: .RDNAttributeType.organizationalUnitName, utf8String: name)
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Set the State or Province Name (ST) of a ``DistinguishedName``.
|
||||
///
|
||||
/// This type is used in ``DistinguishedNameBuilder`` contexts.
|
||||
public struct StateOrProvinceName: RelativeDistinguishedNameConvertible {
|
||||
/// The value of the state or province name field.
|
||||
public var name: String
|
||||
|
||||
/// Construct a new state or province name
|
||||
///
|
||||
/// - Parameter name: The value of the state or province name
|
||||
@inlinable
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeRDN() throws -> RelativeDistinguishedName {
|
||||
return try RelativeDistinguishedName([
|
||||
try .init(type: .RDNAttributeType.stateOrProvinceName, utf8String: name)
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Set the Street Address (STREET) of a ``DistinguishedName``.
|
||||
///
|
||||
/// This type is used in ``DistinguishedNameBuilder`` contexts.
|
||||
public struct StreetAddress: RelativeDistinguishedNameConvertible {
|
||||
/// The value of the street address field.
|
||||
public var name: String
|
||||
|
||||
/// Construct a street address
|
||||
///
|
||||
/// - Parameter name: The value of the street address field
|
||||
@inlinable
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeRDN() throws -> RelativeDistinguishedName {
|
||||
return try RelativeDistinguishedName([
|
||||
try .init(type: .RDNAttributeType.streetAddress, utf8String: name)
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
# Creating Certificates
|
||||
|
||||
Users often have a need to create certificates. Whether for testing or some other interaction with an
|
||||
existing system, creating a certificate programmatically is a powerful tool for users.
|
||||
|
||||
``X509`` provides a number of conveniences for making this easy. There are two common ways to create
|
||||
a certificate: directly, or from a CSR.
|
||||
|
||||
## Creating Certificates Directly
|
||||
|
||||
There are many kinds of certificates that users may want to create, but the most common is to want
|
||||
to create a self-signed certificate. These are valuable in testing scenarios, as they can serve
|
||||
both as a trusted root and as an end-entity certificate.
|
||||
|
||||
Fortunately, creating a self-signed certificate is very similar to creating an intermediate or leaf
|
||||
certificate. This document will call out the steps that might need to be different.
|
||||
|
||||
### Gathering our requirements
|
||||
|
||||
To create a certificate directly we're going to call the
|
||||
``Certificate/init(version:serialNumber:publicKey:notValidBefore:notValidAfter:issuer:subject:signatureAlgorithm:extensions:issuerPrivateKey:)``
|
||||
initializer. This requires that we put together the following information:
|
||||
|
||||
- Version
|
||||
- Serial number
|
||||
- Validity period
|
||||
- Subject name
|
||||
- Issuer name
|
||||
- Extensions
|
||||
- Signature algorithm
|
||||
- Public Key
|
||||
- Issuer private key
|
||||
|
||||
### Version
|
||||
|
||||
Working out the version to use is easy. When creating our own certificates, we should always create a
|
||||
``Certificate/Version-swift.struct/v3`` certificate. There is no reason to use any version older than this.
|
||||
|
||||
### Serial Number
|
||||
|
||||
The certificate serial number forms part of the identifier of the certificate, along with the issuer name. For a given
|
||||
CA, each certificate it issues must have a unique serial number. Additionally, the
|
||||
[CAB Forum Baseline Requirements](https://cabforum.org/baseline-requirements-documents/) require that for certificates that
|
||||
need to conform to this profile the serial number must contain at least 64-bits of output from a CSPRNG.
|
||||
|
||||
``Certificate/SerialNumber-swift.struct`` has a helper initializer that will create a 20-byte serial number
|
||||
consisting entirely of randomness: ``Certificate/SerialNumber-swift.struct/init()``. That's a good default choice for
|
||||
this kind of use-case.
|
||||
|
||||
### Validity Period
|
||||
|
||||
The validity period of a certificate is made up of two dates: "not valid before" and "not valid after". The "not valid before" date
|
||||
refers to the point in time before which a certificate must not be trusted, and is typically set to the date and time at which
|
||||
the certificate was signed by the issuer. The "not valid after" date refers to the point in time after which the certificate has
|
||||
expired and should not be trusted.
|
||||
|
||||
Together these two dates define a validity period. We'll set "not valid before" to the current time (`Date()`), and we'll set the
|
||||
certificate to be valid for a year, making the "not valid after" date `now.addingTimeInterval(60 * 60 * 24 * 365)`.
|
||||
|
||||
### Subject Name
|
||||
|
||||
The subject name identifies the the entity to whom the certificate is being issued. This is a hierarchical name type called a
|
||||
``DistinguishedName``. The full complexity of distinguished names is tackled in the ``DistinguishedName`` API documentation,
|
||||
but for our use-case it's sufficient to know that we don't need to set anything other than the common name. Additionally, in
|
||||
all modern use-cases the common name is nothing more than an identifier, so we can set it to whatever we like.
|
||||
|
||||
```swift
|
||||
let subjectName = DistinguishedName {
|
||||
CommonName("My awesome subject")
|
||||
}
|
||||
```
|
||||
|
||||
### Issuer Name
|
||||
|
||||
Just as the subject name identifies the entity to whom the subject is being issued, the issuer name identifies the entity that
|
||||
issued the certificate. In particular, the issuer name should be exactly equivalent to the subject name in the issuing entity's
|
||||
certificate.
|
||||
|
||||
If we were creating a non-self-signed certificate, we'd set `issuerName` equal to ``Certificate/issuer`` from the parent
|
||||
certificate. For self-signed certificates, the issuer and the subject are identical, so we can set `issuerName = subjectName`.
|
||||
|
||||
### Extensions
|
||||
|
||||
The bulk of the semantic information in a certificate is contained in its extensions. For our case, we care about only a small
|
||||
few.
|
||||
|
||||
We need ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum`` to be present, and set to
|
||||
`isCertificateAuthority`. We also need ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` with the appropriate bits
|
||||
set. Finally, we want to set ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct`` to include the domain
|
||||
name we're going to be self-signing for, which in this case we'll set to `localhost`.
|
||||
|
||||
We can use the helpful builder syntax for this:
|
||||
|
||||
```swift
|
||||
let extensions = try Certificate.Extensions {
|
||||
Critical(
|
||||
Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil)
|
||||
)
|
||||
Critical(
|
||||
Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true)
|
||||
)
|
||||
Certificate.Extensions.SubjectAlternativeNames([.dNSName("localhost")])
|
||||
}
|
||||
```
|
||||
|
||||
### Cryptographic Material
|
||||
|
||||
In our case, the public key, signature algorithm, and issuer private key are intimately bound together. For self-signed certs, the
|
||||
public key is the public key that belongs to the issuer private key. Relatedly, the signature algorithm is constrained to only those
|
||||
that are supported by our private key, as that'll be the one doing the signing.
|
||||
|
||||
If we weren't creating a self-signed certificate, the issuer private key would be the private key for the issuing certificate,
|
||||
and the signature algorithm would be constrained to what that key is capable of. The public key could be anything, but it needs to
|
||||
match the private key that the subject entity has attested to possessing.
|
||||
|
||||
We can use the keys from `swift-crypto` for this operation. We'll select `P256.Signing.PrivateKey` as our private key, which
|
||||
we can wrap up in ``Certificate/PrivateKey/init(_:)-2we15`` to get `issuerPrivateKey`. We can then derive `publicKey` via
|
||||
``Certificate/PrivateKey/publicKey``. Finally, we'll pick the only signature algorithm compatible with that key, which is
|
||||
``Certificate/SignatureAlgorithm-swift.struct/ecdsaWithSHA256``.
|
||||
|
||||
### Serializing
|
||||
|
||||
Once the certificate is created, we'll want to write it out to a file so we can use it! We can easily output this in DER format,
|
||||
which is commonly indicated using a `.crt` file extension.
|
||||
|
||||
We get the DER representation by using code from `SwiftASN1`. ``Certificate`` conforms to `ASN1Serializable`, so we can serialize
|
||||
it like this:
|
||||
|
||||
```swift
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(certificate)
|
||||
```
|
||||
|
||||
### Putting it all together
|
||||
|
||||
That leaves us with the following code for generating a self-signed certificate.
|
||||
|
||||
```swift
|
||||
import Crypto
|
||||
import SwiftASN1
|
||||
import X509
|
||||
|
||||
let swiftCryptoKey = P256.Signing.PrivateKey()
|
||||
let key = Certificate.PrivateKey(swiftCryptoKey)
|
||||
|
||||
let subjectName = try DistinguishedName {
|
||||
CommonName("My awesome subject")
|
||||
}
|
||||
let issuerName = subjectName
|
||||
|
||||
let now = Date()
|
||||
|
||||
let extensions = try Certificate.Extensions {
|
||||
Critical(
|
||||
Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil)
|
||||
)
|
||||
Critical(
|
||||
Certificate.Extensions.KeyUsage(keyCertSign: true)
|
||||
)
|
||||
Certificate.Extensions.SubjectAlternativeNames([.dNSName("localhost")])
|
||||
}
|
||||
|
||||
let certificate = try Certificate(
|
||||
version: .v3,
|
||||
serialNumber: Certificate.SerialNumber(),
|
||||
publicKey: key.publicKey,
|
||||
notValidBefore: now,
|
||||
notValidAfter: now.addingTimeInterval(60 * 60 * 24 * 365),
|
||||
issuer: name,
|
||||
subject: name,
|
||||
signatureAlgorithm: .ecdsaWithSHA256,
|
||||
extensions: extensions,
|
||||
issuerPrivateKey: key)
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(certificate)
|
||||
|
||||
let derEncodedCertificate = serializer.serializedBytes
|
||||
let derEncodedPrivateKey = swiftCryptoKey.derRepresentation
|
||||
```
|
||||
@@ -0,0 +1,170 @@
|
||||
# Examining Certificates
|
||||
|
||||
Decoding and introspecting certificates.
|
||||
|
||||
A common use-case is to have received an X.509 certificate from some source, and to want
|
||||
to inspect it and make decisions based on its content. X.509 certificates are complex
|
||||
objects with highly dynamic and nested content, so this article attempts to outline
|
||||
how to work with ``Certificate`` in order to get the most out of the content of an
|
||||
X.509 certificate.
|
||||
|
||||
## Parsing
|
||||
|
||||
Certificates are commonly provided in two formats: PEM and DER. The two formats are closely
|
||||
related. PEM stands for "Private Enhanced Mail", and a PEM certificate commonly looks like
|
||||
this:
|
||||
|
||||
```
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIB0jCCAXegAwIBAgIUKggFG6vN44MJ3HhCMcypJZTjzyUwCgYIKoZIzj0EAwIw
|
||||
SjELMAkGA1UEBgwCVVMxGjAYBgNVBAoMEVN3aWZ0IENlcnRpZmljYXRlMR8wHQYD
|
||||
VQQDDBZHb29kIGpvYiBkZWNvZGluZyB0aGlzMB4XDTIyMTAyODEwMTQyMloXDTIz
|
||||
MTAyODEwMTQyMlowSjELMAkGA1UEBgwCVVMxGjAYBgNVBAoMEVN3aWZ0IENlcnRp
|
||||
ZmljYXRlMR8wHQYDVQQDDBZHb29kIGpvYiBkZWNvZGluZyB0aGlzMFkwEwYHKoZI
|
||||
zj0CAQYIKoZIzj0DAQcDQgAEa0NRgN2LXAvr66LEna3rmJTTn2O1WC6tFJCCw6LD
|
||||
8TRA9Rz6zYzbpD4+rEoxRTyF6AQuIint1+LmbdmcGhTsUqM7MDkwDwYDVR0TAQH/
|
||||
BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAgQwFgYDVR0RBA8wDYILZXhhbXBsZS5jb20w
|
||||
CgYIKoZIzj0EAwIDSQAwRgIhAORCXnM39TRyN5RRmsFgEZgojUf1MqyG/azkAMx1
|
||||
FGgfAiEA1PMpcTTeK8Hi17N0oaNNIWERLqDketPZG5E3OdEDw9E=
|
||||
-----END CERTIFICATE-----
|
||||
```
|
||||
|
||||
This format is the DER representation of a certificate, base64-encoded, line wrapped at 64
|
||||
bytes, and bracketed by the `BEGIN X`/`END X` delimiter. As PEMs can easily be translated
|
||||
to DER bytes and vice-versa, the rest of this document will focus on the DER format.
|
||||
|
||||
To parse a certificate from DER, we can construct it with a helper initializer from `SwiftASN1`:
|
||||
|
||||
```swift
|
||||
let derBytes: [UInt8] = // get these from somewhere
|
||||
let certificate = try Certificate(asn1Encoded: derBytes)
|
||||
```
|
||||
|
||||
Assuming the certificate is well-formed, this constructor will build us a ``Certificate`` object
|
||||
that we can work with.
|
||||
|
||||
## Introspecting Certificates
|
||||
|
||||
Certificates have a wide range of fields. Many of them are not that interesting (for example,
|
||||
``Certificate/version-swift.property``). However, a number of them make useful attestations about the
|
||||
subject of the certificate.
|
||||
|
||||
### Names
|
||||
|
||||
Certificates have at least two names attached to them: ``Certificate/issuer`` and ``Certificate/subject``.
|
||||
``Certificate/issuer`` provides the name of the entity that issued the certificate, while
|
||||
``Certificate/subject`` provides the name of the entity to which the certificate was issued. Both of
|
||||
these names are represented using ``DistinguishedName``.
|
||||
|
||||
``DistinguishedName`` is a fairly complex type that is described in more detail in its API documentation.
|
||||
In short, it's a hierarchical collection of ``RelativeDistinguishedName``s, each of which is made up
|
||||
of a set of equivalent ``RelativeDistinguishedName/Attribute``s. These ``RelativeDistinguishedName``s
|
||||
are arranged in order from least specific to most specific, typically ending with a relative
|
||||
distinguished name containing a ``CommonName`` ``RelativeDistinguishedName/Attribute``.
|
||||
|
||||
A string representation of a ``DistinguishedName`` can be obtained by using `String(describing:)`. This
|
||||
uses the common [RFC4514 format](https://www.rfc-editor.org/rfc/rfc4514) for textual ``DistinguishedName``s.
|
||||
|
||||
Generally speaking the specific content of the names in these fields are unimportant to end users, though they do
|
||||
play a vital role in validating certificates.
|
||||
|
||||
### Keys
|
||||
|
||||
Certificates are bound to a specific private key, which can be used to authenticate that a specific entity is
|
||||
the one to whom the certificate was issued. This binding is achieved by embedding the public key corresponding
|
||||
to the underlying private key into the certificate object itself. This is modelled in the ``Certificate/publicKey-swift.property``
|
||||
field.
|
||||
|
||||
In ``X509`` the ``Certificate/PublicKey-swift.struct`` type is opaque, but they can be compared for equality.
|
||||
|
||||
### Extensions
|
||||
|
||||
The majority of the semantic information in certificate objects is stored in their X509v3 extensions.
|
||||
These are a typed key-value dictionary that contain additional information about both the subject of the
|
||||
certificate and about much of its content.
|
||||
|
||||
``X509`` stores the extension information in an ``Certificate/Extensions-swift.struct`` collection. This
|
||||
is a full-fidelity representation of all extensions found in the certificate. This stores the extensions
|
||||
as ``Certificate/Extension`` objects, an opaque raw-bytes representation of the extension.
|
||||
|
||||
Implementations are generally not required to understand all extensions in a certificate, as many are
|
||||
strictly informational. However, some extensions must be understood in order for the certificate to safely
|
||||
fulfil their function. As a result, users of a certificate should always search for extensions that have
|
||||
the ``Certificate/Extension/critical`` bit set to `true` and, if they do not understand those extensions,
|
||||
should refuse to trust the certificate.
|
||||
|
||||
As the raw representation of extensions is difficult to use, ``X509`` provides a number of higher-level
|
||||
typed representations of common extensions. These can decode themselves from the ``Certificate/Extension/value``
|
||||
bytes in an extension, as well as wrap themselves back into the opaque ``Certificate/Extension`` type.
|
||||
|
||||
Out of the box, ``X509`` ships support for the following extension types:
|
||||
|
||||
- ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum``
|
||||
- ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct``
|
||||
|
||||
To decode an extension usually requires examining its ``Certificate/Extension/oid`` field. For example, to search
|
||||
for the ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct``, the typical code would be:
|
||||
|
||||
```swift
|
||||
let opaqueSANExtension = certificate.extensions.first(where: { $0.oid == .X509ExtensionID.subjectAlternativeName })
|
||||
if let opaqueSanExtension {
|
||||
let unwrappedSanExtension = try Certificate.Extensions.SubjectAlternativeName(opaqueSanExtension)
|
||||
}
|
||||
```
|
||||
|
||||
This is verbose and repetitive code, so users are encouraged to use the helper function ``Certificate/Extensions-swift.struct/subscript(oid:)``
|
||||
to search for a specific extension. The above code could be replaced by:
|
||||
|
||||
```swift
|
||||
if let opaqueSanExtension = certificate.extensions[oid: .X509ExtensionID.subjectAlternativeName] {
|
||||
let unwrappedSanExtension = try Certificate.Extensions.SubjectAlternativeName(opaqueSanExtension)
|
||||
}
|
||||
```
|
||||
|
||||
This pattern is itself still somewhat repetitive, so ``Certificate/Extensions-swift.struct`` offers a number of helper properties
|
||||
that can be used to get a specific typed extension:
|
||||
|
||||
- ``Certificate/Extensions-swift.struct/authorityInformationAccess-swift.property``
|
||||
- ``Certificate/Extensions-swift.struct/authorityKeyIdentifier-swift.property``
|
||||
- ``Certificate/Extensions-swift.struct/basicConstraints-swift.property``
|
||||
- ``Certificate/Extensions-swift.struct/extendedKeyUsage-swift.property``
|
||||
- ``Certificate/Extensions-swift.struct/keyUsage-swift.property``
|
||||
- ``Certificate/Extensions-swift.struct/nameConstraints-swift.property``
|
||||
- ``Certificate/Extensions-swift.struct/subjectAlternativeNames-swift.property``
|
||||
- ``Certificate/Extensions-swift.struct/subjectKeyIdentifier-swift.property``
|
||||
|
||||
This lets us reduce the above code to a single line:
|
||||
|
||||
```swift
|
||||
let unwrappedSanExtension = try certificate.extensions.subjectAlternativeName
|
||||
```
|
||||
|
||||
This shorthand is most useful when searching for a specific extension. When attempting to work with an entire certificate,
|
||||
users are encouraged to iterate the ``Certificate/Extensions-swift.struct`` and unwrap each extension in turn. This ensures
|
||||
that unknown or invalid ``Certificate/Extension/critical`` extensions are not incorrectly tolerated.
|
||||
|
||||
### Signatures
|
||||
|
||||
All X.509 certificates are signed by their issuer. The issuer calculates the signature over a specific sub-portion
|
||||
of the certificate called the `TBSCertificate`. The signature is then appended to the `TBSCertificate` along with an
|
||||
identifier of what the signature algorithm was.
|
||||
|
||||
These fields are all exposed on the ``Certificate`` type. The signature itself is represented by ``Certificate/signature-swift.property``,
|
||||
an opaque object (``Certificate/Signature-swift.struct``) that encapsulates a specific signature field. The signature algorithm is also
|
||||
represented by ``Certificate/signatureAlgorithm-swift.property`` which stores a simple identifier for the algorithm in question.
|
||||
|
||||
The bytes to be signed are also present in the ``Certificate/tbsCertificateBytes`` field. For parsed certificates, these bytes are
|
||||
the raw certificate bytes as parsed from the wire, which guarantees that there is no encode/decode misrepresentation in these bytes.
|
||||
|
||||
Together these objects make it possible to validate that a signature was correctly signed, using
|
||||
``Certificate/PublicKey-swift.struct/isValidSignature(_:for:)``.
|
||||
|
||||
> Warning: While this is a necessary condition for determining the issuer of a certificate, it is not a sufficient one.
|
||||
> Users are strongly discouraged from hand-rolling their own verification logic, and should instead prefer using an
|
||||
> existing verifier. Wherever possible, prefer to use the platform verifier.
|
||||
@@ -0,0 +1,81 @@
|
||||
# ``X509``
|
||||
|
||||
A library for working with X.509 certificates.
|
||||
|
||||
## Overview
|
||||
|
||||
X.509 certificates are a commonly-used identity format to cryptographically
|
||||
attest to the identity of an actor in a system. They form part of the X.509
|
||||
standard created by the ITU-T for defining a public key infrastructure (PKI).
|
||||
X.509-style PKIs are commonly used in cases where it is necessary to delegate
|
||||
the authority to attest to an actor's identity to a small number of trusted
|
||||
parties (called Certificate Authorities).
|
||||
|
||||
The most common usage of X.509 certificates today is as part of the WebPKI,
|
||||
where they are used to secure TLS connections to websites. X.509 certificates
|
||||
are also used in a wide range of other TLS-based communications, as well as
|
||||
in code signing infrastructure.
|
||||
|
||||
This module makes it possible to serialize, deserialize, create, and interact
|
||||
with X.509 certificates. This is an essential building-block for a wide range
|
||||
of PKI applications. It enables building verifiers, interacting with
|
||||
certificate authorities, authenticating peers, and more.
|
||||
|
||||
## Topics
|
||||
|
||||
### Articles
|
||||
|
||||
- <doc:Examining-Certificates>
|
||||
- <doc:Creating-Certificates>
|
||||
|
||||
### Certificates
|
||||
|
||||
- ``Certificate``
|
||||
- ``Certificate/SerialNumber-swift.struct``
|
||||
- ``Certificate/Version-swift.struct``
|
||||
- ``Certificate/PublicKey-swift.struct``
|
||||
- ``Certificate/PrivateKey``
|
||||
- ``Certificate/Signature-swift.struct``
|
||||
- ``Certificate/SignatureAlgorithm-swift.struct``
|
||||
|
||||
### X.509 Extensions
|
||||
|
||||
- ``Certificate/Extensions-swift.struct``
|
||||
- ``Certificate/Extension``
|
||||
- ``ExtensionsBuilder``
|
||||
- ``CertificateExtensionConvertible``
|
||||
|
||||
### Supported Extension Types
|
||||
|
||||
- ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum``
|
||||
- ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct``
|
||||
- ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct``
|
||||
- ``Critical``
|
||||
|
||||
### Names
|
||||
|
||||
- ``DistinguishedName``
|
||||
- ``RelativeDistinguishedName``
|
||||
- ``RelativeDistinguishedName/Attribute``
|
||||
- ``GeneralName``
|
||||
|
||||
### Distinguished Name Builder
|
||||
|
||||
- ``DistinguishedNameBuilder``
|
||||
- ``RelativeDistinguishedNameConvertible``
|
||||
- ``CommonName``
|
||||
- ``CountryName``
|
||||
- ``LocalityName``
|
||||
- ``OrganizationalUnitName``
|
||||
- ``OrganizationName``
|
||||
- ``StateOrProvinceName``
|
||||
- ``StreetAddress``
|
||||
|
||||
### Errors
|
||||
|
||||
- ``CertificateError``
|
||||
@@ -0,0 +1,191 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Represents an error that may be thrown from the ``Certificate`` module.
|
||||
///
|
||||
/// This object contains both an error ``code`` and a textual reason for the error,
|
||||
/// as well as source code context for the error. When attempting to process a specific
|
||||
/// error, users are encouraged to check the ``code``. The additional diagnostic information
|
||||
/// is available by using `String(describing:)` to format ``CertificateError``.
|
||||
///
|
||||
/// This type is `Equatable` and `Hashable`, but only the ``code`` field is considered in the
|
||||
/// implementation of that behaviour. This makes it relatively easy to test code that throws
|
||||
/// a specific error by creating the error type directly in your own code.
|
||||
public struct CertificateError: Error, Hashable, CustomStringConvertible {
|
||||
private var backing: Backing
|
||||
|
||||
/// Represents the kind of error that was encountered.
|
||||
public var code: ErrorCode {
|
||||
get {
|
||||
self.backing.code
|
||||
}
|
||||
set {
|
||||
self.makeUnique()
|
||||
self.backing.code = newValue
|
||||
}
|
||||
}
|
||||
|
||||
private var reason: String {
|
||||
self.backing.reason
|
||||
}
|
||||
|
||||
private var file: String {
|
||||
self.backing.file
|
||||
}
|
||||
|
||||
private var line: UInt {
|
||||
self.backing.line
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
"CertificateError.\(self.code): \(self.reason) \(self.file):\(self.line)"
|
||||
}
|
||||
|
||||
private mutating func makeUnique() {
|
||||
if !isKnownUniquelyReferenced(&self.backing) {
|
||||
self.backing = self.backing.copy()
|
||||
}
|
||||
}
|
||||
|
||||
/// The signature algorithm used in a ``Certificate`` is not supported by this library.
|
||||
/// - Parameter reason: A detailed reason explaining what signature algorithm was not supported.
|
||||
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/unsupportedSignatureAlgorithm``.
|
||||
@inline(never)
|
||||
public static func unsupportedSignatureAlgorithm(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
) -> CertificateError {
|
||||
return CertificateError(
|
||||
backing: .init(
|
||||
code: .unsupportedSignatureAlgorithm, reason: reason, file: file, line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// The private key algorithm used in a ``Certificate`` is not supported by this library.
|
||||
/// - Parameter reason: A detailed reason explaining what private key algorithm was not supported.
|
||||
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/unsupportedPublicKeyAlgorithm``.
|
||||
@inline(never)
|
||||
public static func unsupportedPublicKeyAlgorithm(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
) -> CertificateError {
|
||||
return CertificateError(
|
||||
backing: .init(
|
||||
code: .unsupportedPublicKeyAlgorithm, reason: reason, file: file, line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// The signature was not valid for the provided ``Certificate``.
|
||||
/// - Parameter reason: A detailed reason detailing the signature and certificate that did not match.
|
||||
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/invalidSignatureForCertificate``.
|
||||
@inline(never)
|
||||
public static func invalidSignatureForCertificate(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
) -> CertificateError {
|
||||
return CertificateError(
|
||||
backing: .init(
|
||||
code: .invalidSignatureForCertificate, reason: reason, file: file, line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// An extension has the wrong OID.
|
||||
/// - Parameter reason: A detailed reason detailing the extension and OID that didn't match.
|
||||
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/incorrectOIDForExtension``.
|
||||
@inline(never)
|
||||
public static func incorrectOIDForExtension(
|
||||
reason: String, file: String = #fileID, line: UInt = #line
|
||||
) -> CertificateError {
|
||||
return CertificateError(
|
||||
backing: .init(
|
||||
code: .incorrectOIDForExtension, reason: reason, file: file, line: line
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension CertificateError {
|
||||
/// Represents the kind of an error.
|
||||
///
|
||||
/// The same kind of error may be thrown from more than one place, for more than one reason. This type represents
|
||||
/// only a fairly high level kind of error: use the string representation of ``CertificateError`` to get more details
|
||||
/// about the specific cause.
|
||||
public struct ErrorCode: Hashable, Sendable, CustomStringConvertible {
|
||||
fileprivate enum BackingCode {
|
||||
case unsupportedSignatureAlgorithm
|
||||
case unsupportedPublicKeyAlgorithm
|
||||
case invalidSignatureForCertificate
|
||||
case incorrectOIDForExtension
|
||||
}
|
||||
|
||||
fileprivate var backingCode: BackingCode
|
||||
|
||||
fileprivate init(_ backingCode: BackingCode) {
|
||||
self.backingCode = backingCode
|
||||
}
|
||||
|
||||
/// The signature algorithm used in a ``Certificate`` is not supported by this library.
|
||||
public static let unsupportedSignatureAlgorithm = ErrorCode(.unsupportedSignatureAlgorithm)
|
||||
|
||||
/// The public key algorithm used in a ``Certificate`` is not supported by this library.
|
||||
public static let unsupportedPublicKeyAlgorithm = ErrorCode(.unsupportedPublicKeyAlgorithm)
|
||||
|
||||
/// The signature was not valid for the provided ``Certificate``.
|
||||
public static let invalidSignatureForCertificate = ErrorCode(.invalidSignatureForCertificate)
|
||||
|
||||
/// An extension has the wrong OID.
|
||||
public static let incorrectOIDForExtension = ErrorCode(.incorrectOIDForExtension)
|
||||
|
||||
public var description: String {
|
||||
return String(describing: self.backingCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension CertificateError {
|
||||
final class Backing: Hashable {
|
||||
var code: CertificateError.ErrorCode
|
||||
|
||||
let reason: String
|
||||
|
||||
let file: String
|
||||
|
||||
let line: UInt
|
||||
|
||||
fileprivate init(
|
||||
code: CertificateError.ErrorCode,
|
||||
reason: String,
|
||||
file: String,
|
||||
line: UInt
|
||||
) {
|
||||
self.code = code
|
||||
self.reason = reason
|
||||
self.file = file
|
||||
self.line = line
|
||||
}
|
||||
|
||||
// Only the error code matters for equality.
|
||||
static func ==(lhs: Backing, rhs: Backing) -> Bool {
|
||||
return lhs.code == rhs.code
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(self.code)
|
||||
}
|
||||
|
||||
fileprivate func copy() -> Backing {
|
||||
return Backing(code: self.code, reason: self.reason, file: self.file, line: self.line)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate.Extensions {
|
||||
/// Provides details on how to access information about the certificate issuer.
|
||||
///
|
||||
/// This extension behaves as a collection of ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct/AccessDescription`` objects.
|
||||
///
|
||||
/// In practice this most commonly contains OCSP servers and links to the issuing CA certificate.
|
||||
public struct AuthorityInformationAccess {
|
||||
@usableFromInline
|
||||
var descriptions: [AccessDescription]
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct/`` object
|
||||
/// containing specific access descriptions.
|
||||
///
|
||||
/// - Parameter descriptions: The descriptions to include in the AIA extension.
|
||||
@inlinable
|
||||
public init<Descriptions: Sequence>(_ descriptions: Descriptions) where Descriptions.Element == AccessDescription {
|
||||
self.descriptions = Array(descriptions)
|
||||
}
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct`` object
|
||||
/// by unwrapping a ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to unwrap
|
||||
/// - Throws: if the ``Certificate/Extension/oid`` is not equal to
|
||||
/// `ASN1ObjectIdentifier.X509ExtensionID.authorityInformationAccess`.
|
||||
@inlinable
|
||||
public init(_ ext: Certificate.Extension) throws {
|
||||
guard ext.oid == .X509ExtensionID.authorityInformationAccess else {
|
||||
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1.ASN1ObjectIdentifier.X509ExtensionID.authorityInformationAccess), got \(ext.oid)")
|
||||
}
|
||||
|
||||
let aiaSyntax = try AuthorityInfoAccessSyntax(asn1Encoded: ext.value)
|
||||
self.descriptions = aiaSyntax.descriptions.map { AccessDescription($0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"TODO"
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(cory): Probably also RangeReplaceableCollection, even though it's kinda crap.
|
||||
extension Certificate.Extensions.AuthorityInformationAccess: RandomAccessCollection {
|
||||
@inlinable
|
||||
public var startIndex: Int {
|
||||
self.descriptions.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Int {
|
||||
self.descriptions.endIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Int) -> AccessDescription {
|
||||
// TODO(cory): Maintain uniqueness
|
||||
get {
|
||||
self.descriptions[position]
|
||||
}
|
||||
set {
|
||||
self.descriptions[position] = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess {
|
||||
/// Describes the location and format of additional information provided
|
||||
/// by the issuer of a given certificate.
|
||||
public struct AccessDescription {
|
||||
/// The format and meaning of the information at ``location``.
|
||||
public var method: AccessMethod
|
||||
|
||||
/// The location where the information may be found.
|
||||
public var location: GeneralName
|
||||
|
||||
/// Construct a new ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct/AccessDescription`` from constituent parts.
|
||||
@inlinable
|
||||
public init(method: AccessMethod, location: GeneralName) {
|
||||
self.method = method
|
||||
self.location = location
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(_ asn1Form: AIAAccessDescription) {
|
||||
self.method = .init(asn1Form.accessMethod)
|
||||
self.location = asn1Form.accessLocation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription {
|
||||
/// The format and meaning of the information included in a single
|
||||
/// ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct/AccessDescription``
|
||||
/// object.
|
||||
public struct AccessMethod {
|
||||
@usableFromInline
|
||||
var backing: Backing
|
||||
|
||||
@usableFromInline
|
||||
enum Backing {
|
||||
case ocspServer
|
||||
case issuingCA
|
||||
case unknownType(ASN1.ASN1ObjectIdentifier)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(_ backing: Backing) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(_ oid: ASN1.ASN1ObjectIdentifier) {
|
||||
switch oid {
|
||||
case .AccessMethodIdentifiers.ocspServer:
|
||||
self.backing = .ocspServer
|
||||
case .AccessMethodIdentifiers.issuingCA:
|
||||
self.backing = .issuingCA
|
||||
default:
|
||||
self.backing = .unknownType(oid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents an OCSP server that can be queried for certificate revocation information.
|
||||
public static let ocspServer = Self(.ocspServer)
|
||||
|
||||
/// A location from which a copy of the issuing CA certificate may be obtained.
|
||||
public static let issuingCA = Self(.issuingCA)
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension {
|
||||
/// Construct an opaque ``Certificate/Extension`` from this AIA extension.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - aia: The extension to wrap
|
||||
/// - critical: Whether this extension should have the critical bit set.
|
||||
@inlinable
|
||||
public init(_ aia: Certificate.Extensions.AuthorityInformationAccess, critical: Bool) throws {
|
||||
let asn1Representation = AuthorityInfoAccessSyntax(aia)
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(asn1Representation)
|
||||
self.init(oid: .X509ExtensionID.authorityInformationAccess, critical: critical, value: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityInformationAccess: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
return try .init(self, critical: false)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: ASN.1 Helpers
|
||||
|
||||
// AuthorityInfoAccessSyntax ::=
|
||||
// SEQUENCE SIZE (1..MAX) OF AccessDescription
|
||||
//
|
||||
// AccessDescription ::= SEQUENCE {
|
||||
// accessMethod OBJECT IDENTIFIER,
|
||||
// accessLocation GeneralName }
|
||||
@usableFromInline
|
||||
struct AuthorityInfoAccessSyntax: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var descriptions: [AIAAccessDescription]
|
||||
|
||||
@inlinable
|
||||
init(_ aia: Certificate.Extensions.AuthorityInformationAccess) {
|
||||
self.descriptions = aia.descriptions.map { .init($0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self.descriptions = try ASN1.sequence(of: AIAAccessDescription.self, identifier: identifier, rootNode: rootNode)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
for description in descriptions {
|
||||
try coder.serialize(description)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct AIAAccessDescription: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var accessMethod: ASN1.ASN1ObjectIdentifier
|
||||
|
||||
@usableFromInline
|
||||
var accessLocation: GeneralName
|
||||
|
||||
@inlinable
|
||||
init(accessMethod: ASN1.ASN1ObjectIdentifier, accessLocation: GeneralName) {
|
||||
self.accessMethod = accessMethod
|
||||
self.accessLocation = accessLocation
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(_ description: Certificate.Extensions.AuthorityInformationAccess.AccessDescription) {
|
||||
self.accessMethod = ASN1.ASN1ObjectIdentifier(accessMethod: description.method)
|
||||
self.accessLocation = description.location
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let accessMethod = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
|
||||
let accessLocation = try GeneralName(asn1Encoded: &nodes)
|
||||
return AIAAccessDescription(accessMethod: accessMethod, accessLocation: accessLocation)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.accessMethod)
|
||||
try coder.serialize(self.accessLocation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1ObjectIdentifier {
|
||||
@usableFromInline
|
||||
enum AccessMethodIdentifiers {
|
||||
@usableFromInline
|
||||
static let ocspServer: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 48, 1]
|
||||
|
||||
@usableFromInline
|
||||
static let issuingCA: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 48, 2]
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(accessMethod: Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod) {
|
||||
switch accessMethod.backing {
|
||||
case .ocspServer:
|
||||
self = .AccessMethodIdentifiers.ocspServer
|
||||
case .issuingCA:
|
||||
self = .AccessMethodIdentifiers.issuingCA
|
||||
case .unknownType(let oid):
|
||||
self = oid
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate.Extensions {
|
||||
/// Provides information about the public key corresponding to the private key that was
|
||||
/// used to sign a specific certificate.
|
||||
public struct AuthorityKeyIdentifier {
|
||||
/// An opaque sequence of bytes uniquely derived from the public key of the issuing
|
||||
/// CA.
|
||||
///
|
||||
/// This is commonly a hash of the subject public key info from the issuing certificate.
|
||||
public var keyIdentifier: ArraySlice<UInt8>?
|
||||
|
||||
/// The name of the issuer of the issuing cert.
|
||||
public var authorityCertIssuer: [GeneralName]?
|
||||
|
||||
/// The serial number of the issuing cert.
|
||||
public var authorityCertSerialNumber: Certificate.SerialNumber?
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct`` extension value.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyIdentifier: An opaque sequence of bytes uniquely derived from the public key of the issuing CA.
|
||||
/// - authorityCertIssuer: The name of the issuer of the issuing cert.
|
||||
/// - authorityCertSerialNumber: The serial number of the issuing cert.
|
||||
@inlinable
|
||||
public init(keyIdentifier: ArraySlice<UInt8>? = nil, authorityCertIssuer: [GeneralName]? = nil, authorityCertSerialNumber: Certificate.SerialNumber? = nil) {
|
||||
self.keyIdentifier = keyIdentifier
|
||||
self.authorityCertIssuer = authorityCertIssuer
|
||||
self.authorityCertSerialNumber = authorityCertSerialNumber
|
||||
}
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct`` object
|
||||
/// by unwrapping a ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to unwrap
|
||||
/// - Throws: if the ``Certificate/Extension/oid`` is not equal to
|
||||
/// `ASN1ObjectIdentifier.X509ExtensionID.authorityKeyIdentifier`.
|
||||
@inlinable
|
||||
public init(_ ext: Certificate.Extension) throws {
|
||||
guard ext.oid == .X509ExtensionID.authorityKeyIdentifier else {
|
||||
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1.ASN1ObjectIdentifier.X509ExtensionID.authorityKeyIdentifier), got \(ext.oid)")
|
||||
}
|
||||
|
||||
let asn1KeyIdentifier = try AuthorityKeyIdentifierValue(asn1Encoded: ext.value)
|
||||
self.keyIdentifier = asn1KeyIdentifier.keyIdentifier.map { $0.bytes }
|
||||
self.authorityCertIssuer = asn1KeyIdentifier.authorityCertIssuer
|
||||
self.authorityCertSerialNumber = asn1KeyIdentifier.authorityCertSerialNumber.map { Certificate.SerialNumber(bytes: $0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityKeyIdentifier: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityKeyIdentifier: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.AuthorityKeyIdentifier: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension {
|
||||
/// Construct an opaque ``Certificate/Extension`` from this AKI extension.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - aki: The extension to wrap
|
||||
/// - critical: Whether this extension should have the critical bit set.
|
||||
@inlinable
|
||||
public init(_ aki: Certificate.Extensions.AuthorityKeyIdentifier, critical: Bool) throws {
|
||||
let asn1Representation = AuthorityKeyIdentifierValue(aki)
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(asn1Representation)
|
||||
self.init(oid: .X509ExtensionID.authorityKeyIdentifier, critical: critical, value: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.AuthorityKeyIdentifier: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
return try .init(self, critical: false)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: ASN1 helpers
|
||||
@usableFromInline
|
||||
struct AuthorityKeyIdentifierValue: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var keyIdentifier: ASN1.ASN1OctetString?
|
||||
|
||||
@usableFromInline
|
||||
var authorityCertIssuer: [GeneralName]?
|
||||
|
||||
@usableFromInline
|
||||
var authorityCertSerialNumber: ArraySlice<UInt8>?
|
||||
|
||||
@inlinable
|
||||
init(keyIdentifier: ASN1.ASN1OctetString?, authorityCertIssuer: [GeneralName]?, authorityCertSerialNumber: ArraySlice<UInt8>?) {
|
||||
self.keyIdentifier = keyIdentifier
|
||||
self.authorityCertIssuer = authorityCertIssuer
|
||||
self.authorityCertSerialNumber = authorityCertSerialNumber
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(_ aki: Certificate.Extensions.AuthorityKeyIdentifier) {
|
||||
self.keyIdentifier = aki.keyIdentifier.map { ASN1.ASN1OctetString(contentBytes: $0) }
|
||||
self.authorityCertIssuer = aki.authorityCertIssuer
|
||||
self.authorityCertSerialNumber = aki.authorityCertSerialNumber.map { $0.bytes }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let keyIdentifier: ASN1.ASN1OctetString? = try ASN1.optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 0, tagClass: .contextSpecific, constructed: false))
|
||||
let authorityCertIssuer: GeneralNames? = try ASN1.optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 1, tagClass: .contextSpecific, constructed: true))
|
||||
let authorityCertSerialNumber: ArraySlice<UInt8>? = try ASN1.optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 2, tagClass: .contextSpecific, constructed: false))
|
||||
|
||||
return AuthorityKeyIdentifierValue(
|
||||
keyIdentifier: keyIdentifier, authorityCertIssuer: authorityCertIssuer?.names, authorityCertSerialNumber: authorityCertSerialNumber
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serializeOptionalImplicitlyTagged(self.keyIdentifier, withIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific, constructed: false))
|
||||
try coder.serializeOptionalImplicitlyTagged(
|
||||
self.authorityCertIssuer.map { GeneralNames($0) }, withIdentifier: .init(tagWithNumber: 1, tagClass: .contextSpecific, constructed: true)
|
||||
)
|
||||
try coder.serializeOptionalImplicitlyTagged(self.authorityCertSerialNumber, withIdentifier: .init(tagWithNumber: 2, tagClass: .contextSpecific, constructed: false))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate.Extensions {
|
||||
/// Identifies whether the subject of the certificate is a CA and the
|
||||
/// maximum verification depth of valid certificate paths that include this
|
||||
/// certificate.
|
||||
public enum BasicConstraints {
|
||||
/// This entity is a certificate authority.
|
||||
///
|
||||
/// If `maxPathLength` is non-nil, this length is the maximum number of intermediate
|
||||
/// certificates that may follow this one in a valid certification path. Note that this
|
||||
/// excludes the leaf, so a valid (and common) `maxPathLength` is `0`.
|
||||
case isCertificateAuthority(maxPathLength: Int?)
|
||||
|
||||
/// This entity is not a certificate authority, and may not be a valid issuer of any
|
||||
/// certificate.
|
||||
case notCertificateAuthority
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum`` object
|
||||
/// by unwrapping a ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to unwrap
|
||||
/// - Throws: if the ``Certificate/Extension/oid`` is not equal to
|
||||
/// `ASN1ObjectIdentifier.X509ExtensionID.basicConstraints`.
|
||||
@inlinable
|
||||
public init(_ ext: Certificate.Extension) throws {
|
||||
guard ext.oid == .X509ExtensionID.basicConstraints else {
|
||||
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1.ASN1ObjectIdentifier.X509ExtensionID.basicConstraints), got \(ext.oid)")
|
||||
}
|
||||
|
||||
let basicConstraintsValue = try BasicConstraintsValue(asn1Encoded: ext.value)
|
||||
if basicConstraintsValue.isCA {
|
||||
self = .isCertificateAuthority(maxPathLength: basicConstraintsValue.pathLenConstraint)
|
||||
} else {
|
||||
self = .notCertificateAuthority
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.BasicConstraints: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.BasicConstraints: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.BasicConstraints: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension {
|
||||
/// Construct an opaque ``Certificate/Extension`` from this Basic Constraints extension.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - basicConstraints: The extension to wrap
|
||||
/// - critical: Whether this extension should have the critical bit set.
|
||||
@inlinable
|
||||
public init(_ basicConstraints: Certificate.Extensions.BasicConstraints, critical: Bool) throws {
|
||||
let asn1Representation = BasicConstraintsValue(basicConstraints)
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(asn1Representation)
|
||||
self.init(oid: .X509ExtensionID.basicConstraints, critical: critical, value: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.BasicConstraints: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
return try .init(self, critical: false)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: ASN1 helpers
|
||||
@usableFromInline
|
||||
struct BasicConstraintsValue: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var isCA: Bool
|
||||
|
||||
@usableFromInline
|
||||
var pathLenConstraint: Int?
|
||||
|
||||
@inlinable
|
||||
init(isCA: Bool, pathLenConstraint: Int?) throws {
|
||||
self.isCA = isCA
|
||||
self.pathLenConstraint = pathLenConstraint
|
||||
|
||||
// CA's must not assert the path len constraint field unless isCA is true.
|
||||
guard pathLenConstraint == nil || isCA else {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(_ ext: Certificate.Extensions.BasicConstraints) {
|
||||
switch ext {
|
||||
case .isCertificateAuthority(maxPathLength: let maxPathLen):
|
||||
self.isCA = true
|
||||
self.pathLenConstraint = maxPathLen
|
||||
case .notCertificateAuthority:
|
||||
self.isCA = false
|
||||
self.pathLenConstraint = nil
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let isCA: Bool = try ASN1.decodeDefault(&nodes, defaultValue: false)
|
||||
let pathLenConstraint: Int? = try ASN1.optionalImplicitlyTagged(&nodes)
|
||||
return try BasicConstraintsValue(isCA: isCA, pathLenConstraint: pathLenConstraint)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
if self.isCA != false {
|
||||
try coder.serialize(self.isCA)
|
||||
}
|
||||
try coder.serializeOptionalImplicitlyTagged(self.pathLenConstraint)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate.Extensions {
|
||||
/// Indicates one or more purposes for which the certified public key
|
||||
/// may be used, in addition to or instead of the the purposes indicated
|
||||
/// in the ``KeyUsage-swift.struct`` extension.
|
||||
public struct ExtendedKeyUsage {
|
||||
@usableFromInline
|
||||
var usages: [Usage]
|
||||
|
||||
/// Construct an ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` extension containing the
|
||||
/// given usages.
|
||||
///
|
||||
/// - Parameter usages: The purposes for which the certificate may be used.
|
||||
@inlinable
|
||||
public init<Usages: Sequence>(_ usages: Usages) where Usages.Element == Usage {
|
||||
self.usages = Array(usages)
|
||||
}
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` object
|
||||
/// by unwrapping a ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to unwrap
|
||||
/// - Throws: if the ``Certificate/Extension/oid`` is not equal to
|
||||
/// `ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage`.
|
||||
@inlinable
|
||||
public init(_ ext: Certificate.Extension) throws {
|
||||
guard ext.oid == .X509ExtensionID.extendedKeyUsage else {
|
||||
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1.ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage), got \(ext.oid)")
|
||||
}
|
||||
|
||||
let asn1EKU = try ASN1ExtendedKeyUsage(asn1Encoded: ext.value)
|
||||
self.usages = asn1EKU.usages.map { Usage(oid: $0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(cory): Probably also RangeReplaceableCollection, even though it's kinda crap.
|
||||
extension Certificate.Extensions.ExtendedKeyUsage: RandomAccessCollection {
|
||||
public var startIndex: Int {
|
||||
self.usages.startIndex
|
||||
}
|
||||
|
||||
public var endIndex: Int {
|
||||
self.usages.endIndex
|
||||
}
|
||||
|
||||
public subscript(position: Int) -> Usage {
|
||||
// TODO(cory): Maintain uniqueness
|
||||
get {
|
||||
self.usages[position]
|
||||
}
|
||||
set {
|
||||
self.usages[position] = newValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage {
|
||||
/// An acceptable usage for a certificate as attested in an
|
||||
/// ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct``
|
||||
/// extension.
|
||||
public struct Usage {
|
||||
@usableFromInline
|
||||
enum Backing {
|
||||
case serverAuth
|
||||
case clientAuth
|
||||
case codeSigning
|
||||
case emailProtection
|
||||
case timeStamping
|
||||
case ocspSigning
|
||||
case any
|
||||
case certificateTransparency
|
||||
case unknown(ASN1.ASN1ObjectIdentifier)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var backing: Backing
|
||||
|
||||
@inlinable
|
||||
init(_ backing: Backing) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
/// Constructs a ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct/Usage`` from an opaque oid.
|
||||
///
|
||||
/// - Parameter oid: The OID of the usage.
|
||||
@inlinable
|
||||
public init(oid: ASN1.ASN1ObjectIdentifier) {
|
||||
switch oid {
|
||||
case .ExtendedKeyUsage.serverAuth:
|
||||
self = .serverAuth
|
||||
case .ExtendedKeyUsage.clientAuth:
|
||||
self = .clientAuth
|
||||
case .ExtendedKeyUsage.codeSigning:
|
||||
self = .codeSigning
|
||||
case .ExtendedKeyUsage.emailProtection:
|
||||
self = .emailProtection
|
||||
case .ExtendedKeyUsage.timeStamping:
|
||||
self = .timeStamping
|
||||
case .ExtendedKeyUsage.ocspSigning:
|
||||
self = .ocspSigning
|
||||
case .ExtendedKeyUsage.any:
|
||||
self = .any
|
||||
case .ExtendedKeyUsage.certificateTransparency:
|
||||
self = .certificateTransparency
|
||||
default:
|
||||
self.backing = .unknown(oid)
|
||||
}
|
||||
}
|
||||
|
||||
/// The public key may be used for TLS web servers.
|
||||
public static let serverAuth = Self(.serverAuth)
|
||||
|
||||
/// The public key may be used for TLS web client authentication.
|
||||
public static let clientAuth = Self(.clientAuth)
|
||||
|
||||
/// The public key may be used for signing of downloadable executable code.
|
||||
public static let codeSigning = Self(.codeSigning)
|
||||
|
||||
/// The public key may be used for email protection.
|
||||
public static let emailProtection = Self(.emailProtection)
|
||||
|
||||
/// The public key may be used for binding the hash of an object to a time.
|
||||
public static let timeStamping = Self(.timeStamping)
|
||||
|
||||
/// The public key may be used for signing OCSP responses.
|
||||
public static let ocspSigning = Self(.ocspSigning)
|
||||
|
||||
/// The public key may be used for any purpose.
|
||||
public static let any = Self(.any)
|
||||
|
||||
/// The public key may be used for signing certificate transparency precertificates.
|
||||
public static let certificateTransparency = Self(.certificateTransparency)
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage.Usage: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage.Usage: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage.Usage: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage.Usage.Backing: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage.Usage.Backing: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage.Usage.Backing: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension {
|
||||
/// Construct an opaque ``Certificate/Extension`` from this Extended Key Usage extension.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eku: The extension to wrap
|
||||
/// - critical: Whether this extension should have the critical bit set.
|
||||
@inlinable
|
||||
public init(_ eku: Certificate.Extensions.ExtendedKeyUsage, critical: Bool) throws {
|
||||
let asn1Representation = ASN1ExtendedKeyUsage(eku)
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(asn1Representation)
|
||||
self.init(oid: .X509ExtensionID.extendedKeyUsage, critical: critical, value: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.ExtendedKeyUsage: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
return try .init(self, critical: false)
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1ObjectIdentifier {
|
||||
/// Construct the OID corresponding to a specific extended key usage.
|
||||
///
|
||||
/// - Parameter usage: the EKU to use to construct the OID.
|
||||
@inlinable
|
||||
public init(_ usage: Certificate.Extensions.ExtendedKeyUsage.Usage) {
|
||||
switch usage.backing {
|
||||
case .serverAuth:
|
||||
self = .ExtendedKeyUsage.serverAuth
|
||||
case .clientAuth:
|
||||
self = .ExtendedKeyUsage.clientAuth
|
||||
case .codeSigning:
|
||||
self = .ExtendedKeyUsage.codeSigning
|
||||
case .emailProtection:
|
||||
self = .ExtendedKeyUsage.emailProtection
|
||||
case .timeStamping:
|
||||
self = .ExtendedKeyUsage.timeStamping
|
||||
case .ocspSigning:
|
||||
self = .ExtendedKeyUsage.ocspSigning
|
||||
case .any:
|
||||
self = .ExtendedKeyUsage.any
|
||||
case .certificateTransparency:
|
||||
self = .ExtendedKeyUsage.certificateTransparency
|
||||
case .unknown(let oid):
|
||||
self = oid
|
||||
}
|
||||
}
|
||||
|
||||
/// An acceptable usage for a certificate as attested in an
|
||||
/// ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct``
|
||||
/// extension.
|
||||
public enum ExtendedKeyUsage {
|
||||
/// The public key may be used for any purpose.
|
||||
public static let any: ASN1.ASN1ObjectIdentifier = [2, 5, 29, 37, 0]
|
||||
|
||||
/// The public key may be used for TLS web servers.
|
||||
public static let serverAuth: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 3, 1]
|
||||
|
||||
/// The public key may be used for TLS web client authentication.
|
||||
public static let clientAuth: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 3, 2]
|
||||
|
||||
/// The public key may be used for signing of downloadable executable code.
|
||||
public static let codeSigning: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 3, 3]
|
||||
|
||||
/// The public key may be used for email protection.
|
||||
public static let emailProtection: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 3, 4]
|
||||
|
||||
/// The public key may be used for binding the hash of an object to a time.
|
||||
public static let timeStamping: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 3, 8]
|
||||
|
||||
/// The public key may be used for signing OCSP responses.
|
||||
public static let ocspSigning: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 3, 9]
|
||||
|
||||
/// The public key may be used for signing certificate transparency precertificates.
|
||||
public static let certificateTransparency: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 4, 1, 11129, 2, 4, 4]
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct ASN1ExtendedKeyUsage: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var usages: [ASN1.ASN1ObjectIdentifier]
|
||||
|
||||
@inlinable
|
||||
init(_ usages: [ASN1.ASN1ObjectIdentifier]) {
|
||||
self.usages = usages
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(_ eku: Certificate.Extensions.ExtendedKeyUsage) {
|
||||
self.usages = eku.usages.map { ASN1.ASN1ObjectIdentifier($0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self.usages = try ASN1.sequence(identifier: identifier, rootNode: rootNode)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.serializeSequenceOf(self.usages, identifier: identifier)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension ASN1.ASN1ObjectIdentifier {
|
||||
/// OIDs that identify known X509 extensions.
|
||||
public enum X509ExtensionID {
|
||||
/// Identifies the authority key identifier extension, corresponding to
|
||||
/// ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct``.
|
||||
public static let authorityKeyIdentifier: ASN1.ASN1ObjectIdentifier = [2, 5, 29, 35]
|
||||
|
||||
/// Identifies the subject key identifier extension, corresponding to
|
||||
/// ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct``.
|
||||
public static let subjectKeyIdentifier: ASN1.ASN1ObjectIdentifier = [2, 5, 29, 14]
|
||||
|
||||
/// Identifies the key usgae extension, corresponding to
|
||||
/// ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct``.
|
||||
public static let keyUsage: ASN1.ASN1ObjectIdentifier = [2, 5, 29, 15]
|
||||
|
||||
/// Identifies the subject alternative name extension, corresponding to
|
||||
/// ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct``.
|
||||
public static let subjectAlternativeName: ASN1.ASN1ObjectIdentifier = [2, 5, 29, 17]
|
||||
|
||||
/// Identifies the basic constraints extension, corresponding to
|
||||
/// ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum``.
|
||||
public static let basicConstraints: ASN1.ASN1ObjectIdentifier = [2, 5, 29, 19]
|
||||
|
||||
/// Identifies the name constraints extension, corresponding to
|
||||
/// ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct``.
|
||||
public static let nameConstraints: ASN1.ASN1ObjectIdentifier = [2, 5, 29, 30]
|
||||
|
||||
/// Identifies the extended key usage extension, corresponding to
|
||||
/// ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct``.
|
||||
public static let extendedKeyUsage: ASN1.ASN1ObjectIdentifier = [2, 5, 29, 37]
|
||||
|
||||
/// Identifies the authority information access extension, corresponding to
|
||||
/// ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct``.
|
||||
public static let authorityInformationAccess: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 1, 1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate.Extensions {
|
||||
/// Defines the purpose of the key contained in the certificate.
|
||||
///
|
||||
/// This usage restriction may be employed when a key that could conceptually be used
|
||||
/// for more than one operation (such as an RSA key) is to be restricted.
|
||||
public struct KeyUsage {
|
||||
// KeyUsage is only actually 9-bits wide, so we store it in a UInt16 in bits 0 through 8.
|
||||
// To avoid the need to do bit swaps, we treat this as though the bits were encoded in ASN.1:
|
||||
// bit zero is the highest bit, bit 16 is the lowest.
|
||||
@usableFromInline
|
||||
internal var rawValue: UInt16
|
||||
|
||||
/// Construct a ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` extension with no usages set.
|
||||
@inlinable
|
||||
public init() {
|
||||
self.rawValue = 0
|
||||
}
|
||||
|
||||
/// Construct a ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` extension with some usages set.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - digitalSignature: This is true when the subject public key is used for verifying digital signatures,
|
||||
/// other than signatures used in certificates (covered by `keyCertSign`) or in
|
||||
/// CRLs (covered by `cRLSign`).
|
||||
/// - nonRepudiation: This is true when the subject public key is used to verify digital signatures used
|
||||
/// to provide a non-repudiation service that protects against the signing entity denying
|
||||
/// some action. This does not cover signatures used in certificates (covered by `keyCertSign`)
|
||||
/// or in CRLs (`cRLSign`).
|
||||
/// - keyEncipherment: This is true when the subject public key is used to encrypt private or secret keys, e.g.
|
||||
/// for key transport.
|
||||
/// - dataEncipherment: This is true when the subject public key is used to encrypt raw data directly, without the use
|
||||
/// of an intervening symmetric cipher.
|
||||
/// - keyAgreement: This is true when the subject public key is used for key agreement.
|
||||
/// - keyCertSign: This is true when the subject public key is used for verifying signatures on
|
||||
/// certificates.
|
||||
/// - cRLSign: This is true when the subject public key is used for verifying signatures on
|
||||
/// certificate revocation lists.
|
||||
/// - encipherOnly: This only has meaning when the `keyAgreement` field is also `true`. When `true` in that
|
||||
/// case, the subject public key may only be used for encrypting data while performing key
|
||||
/// agreement.
|
||||
/// - decipherOnly: This only has meaning when the `keyAgreement` field is also `true`. When `true` in that
|
||||
/// case, the subject public key may only be used for decrypting data while performing key
|
||||
/// agreement.
|
||||
@inlinable
|
||||
public init(
|
||||
digitalSignature: Bool = false,
|
||||
nonRepudiation: Bool = false,
|
||||
keyEncipherment: Bool = false,
|
||||
dataEncipherment: Bool = false,
|
||||
keyAgreement: Bool = false,
|
||||
keyCertSign: Bool = false,
|
||||
cRLSign: Bool = false,
|
||||
encipherOnly: Bool = false,
|
||||
decipherOnly: Bool = false
|
||||
) {
|
||||
self = Self()
|
||||
self.digitalSignature = digitalSignature
|
||||
self.nonRepudiation = nonRepudiation
|
||||
self.keyEncipherment = keyEncipherment
|
||||
self.dataEncipherment = dataEncipherment
|
||||
self.keyAgreement = keyAgreement
|
||||
self.keyCertSign = keyCertSign
|
||||
self.cRLSign = cRLSign
|
||||
self.encipherOnly = encipherOnly
|
||||
self.decipherOnly = decipherOnly
|
||||
}
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` object
|
||||
/// by unwrapping a ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to unwrap
|
||||
/// - Throws: if the ``Certificate/Extension/oid`` is not equal to
|
||||
/// `ASN1ObjectIdentifier.X509ExtensionID.keyUsage`.
|
||||
@inlinable
|
||||
public init(_ ext: Certificate.Extension) throws {
|
||||
guard ext.oid == .X509ExtensionID.keyUsage else {
|
||||
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1.ASN1ObjectIdentifier.X509ExtensionID.keyUsage), got \(ext.oid)")
|
||||
}
|
||||
|
||||
let keyUsageValue = try ASN1.ASN1BitString(asn1Encoded: ext.value)
|
||||
try Self.validateBitString(keyUsageValue)
|
||||
self.rawValue = UInt16(keyUsageValue)
|
||||
}
|
||||
|
||||
/// This is true when the subject public key is used for verifying digital signatures,
|
||||
/// other than signatures used in certificates (covered by ``keyCertSign``) or in
|
||||
/// CRLs (covered by ``cRLSign``).
|
||||
@inlinable
|
||||
public var digitalSignature: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x8000) == 0x8000
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x8000
|
||||
} else {
|
||||
self.rawValue &= (~0x8000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is true when the subject public key is used to verify digital signatures used
|
||||
/// to provide a non-repudiation service that protects against the signing entity denying
|
||||
/// some action. This does not cover signatures used in certificates (covered by ``keyCertSign``)
|
||||
/// or in CRLs (``cRLSign``).
|
||||
@inlinable
|
||||
public var nonRepudiation: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x4000) == 0x4000
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x4000
|
||||
} else {
|
||||
self.rawValue &= (~0x4000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is true when the subject public key is used to encrypt private or secret keys, e.g.
|
||||
/// for key transport.
|
||||
@inlinable
|
||||
public var keyEncipherment: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x2000) == 0x2000
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x2000
|
||||
} else {
|
||||
self.rawValue &= (~0x2000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is true when the subject public key is used to encrypt raw data directly, without the use
|
||||
/// of an intervening symmetric cipher.
|
||||
@inlinable
|
||||
public var dataEncipherment: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x1000) == 0x1000
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x1000
|
||||
} else {
|
||||
self.rawValue &= (~0x1000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is true when the subject public key is used for key agreement.
|
||||
@inlinable
|
||||
public var keyAgreement: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x0800) == 0x0800
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x08000
|
||||
} else {
|
||||
self.rawValue &= (~0x0800)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is true when the subject public key is used for verifying signatures on
|
||||
/// certificates.
|
||||
@inlinable
|
||||
public var keyCertSign: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x0400) == 0x0400
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x0400
|
||||
} else {
|
||||
self.rawValue &= (~0x0400)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This is true when the subject public key is used for verifying signatures on
|
||||
/// certificate revocation lists.
|
||||
@inlinable
|
||||
public var cRLSign: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x0200) == 0x0200
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x0200
|
||||
} else {
|
||||
self.rawValue &= (~0x0200)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This only has meaning when the ``keyAgreement`` field is also `true`. When `true` in that
|
||||
/// case, the subject public key may only be used for encrypting data while performing key
|
||||
/// agreement.
|
||||
@inlinable
|
||||
public var encipherOnly: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x0100) == 0x0100
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x0100
|
||||
} else {
|
||||
self.rawValue &= (~0x0100)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This only has meaning when the ``keyAgreement`` field is also `true`. When `true` in that
|
||||
/// case, the subject public key may only be used for decrypting data while performing key
|
||||
/// agreement.
|
||||
@inlinable
|
||||
public var decipherOnly: Bool {
|
||||
get {
|
||||
return (self.rawValue & 0x0080) == 0x0080
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
self.rawValue |= 0x0080
|
||||
} else {
|
||||
self.rawValue &= (~0x0080)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func validateBitString(_ bitstring: ASN1.ASN1BitString) throws {
|
||||
switch bitstring.bytes.count {
|
||||
case 0:
|
||||
// This is fine, no bits are set.
|
||||
precondition(bitstring.paddingBits == 0)
|
||||
case 1:
|
||||
// This is fine, no more than 8 bits.
|
||||
// We want to confirm that the bit _before_ the first padding bit isn't 0.
|
||||
// We cannot have 8 padding bits.
|
||||
precondition(bitstring.paddingBits < 8)
|
||||
let bitMask = UInt8(0x01) << bitstring.paddingBits
|
||||
if (bitstring.bytes[bitstring.bytes.startIndex] & bitMask) == 0 {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
case 2 where bitstring.paddingBits == 7:
|
||||
// This is fine, there are 9 valid bits: 8 from the prior byte and 1 here.
|
||||
if (bitstring.bytes[bitstring.bytes.startIndex &+ 1] & 0x80) == 0 {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
default:
|
||||
// Too many bits!
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.KeyUsage: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.KeyUsage: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.KeyUsage: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension {
|
||||
/// Construct an opaque ``Certificate/Extension`` from this Key Usage extension.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - keyUsage: The extension to wrap
|
||||
/// - critical: Whether this extension should have the critical bit set.
|
||||
@inlinable
|
||||
public init(_ keyUsage: Certificate.Extensions.KeyUsage, critical: Bool) throws {
|
||||
let asn1Representation = ASN1.ASN1BitString(keyUsage)
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(asn1Representation)
|
||||
self.init(oid: .X509ExtensionID.keyUsage, critical: critical, value: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.KeyUsage: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
return try .init(self, critical: false)
|
||||
}
|
||||
}
|
||||
|
||||
extension UInt16 {
|
||||
@inlinable
|
||||
init(_ bitString: ASN1.ASN1BitString) {
|
||||
switch bitString.bytes.count {
|
||||
case 0:
|
||||
self = 0
|
||||
case 1:
|
||||
self = UInt16(bitString.bytes[bitString.bytes.startIndex]) << 8
|
||||
case 2:
|
||||
self = UInt16(bitString.bytes[bitString.bytes.startIndex]) << 8
|
||||
self |= UInt16(bitString.bytes[bitString.bytes.startIndex + 1])
|
||||
default:
|
||||
preconditionFailure()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1BitString {
|
||||
@inlinable
|
||||
init(_ ext: Certificate.Extensions.KeyUsage) {
|
||||
if ext.decipherOnly {
|
||||
// We need two bytes here.
|
||||
let bytes = [UInt8(truncatingIfNeeded: ext.rawValue >> 8), UInt8(truncatingIfNeeded: ext.rawValue)]
|
||||
self = .init(bytes: bytes[...], paddingBits: 7)
|
||||
} else {
|
||||
// We only need one byte here.
|
||||
let byte = UInt8(truncatingIfNeeded: ext.rawValue >> 8)
|
||||
self = .init(bytes: [byte], paddingBits: byte.trailingZeroBitCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate.Extensions {
|
||||
/// Constraints the namespace within which all subject names issued by a given CA must reside.
|
||||
///
|
||||
/// These constraints apply both to the ``Certificate/subject`` and also to any
|
||||
/// ``SubjectAlternativeNames-swift.struct`` that may be present. Restrictions are applied to
|
||||
/// specific name _forms_, and when the form is not present then the restriction does not apply.
|
||||
///
|
||||
/// Restrictions are defined in terms of both permitted and forbidden subtrees. The forbidden trees
|
||||
/// are consulted first, and if a name is matched in a forbidden tree then it does not matter whether
|
||||
/// the same name is also matched in a permitted tree.
|
||||
public struct NameConstraints {
|
||||
/// The DNS name trees that are permitted in certificates issued by this CA.
|
||||
///
|
||||
/// These restrictions are expressed in forms like `host.example.com`. Any DNS name that can be
|
||||
/// constructed by adding zero or more labels to the left-hand side of the name satifies the constraint.
|
||||
public var permittedDNSDomains: [String] {
|
||||
// TODO(cory): We probably want a different collection type here that can lazily construct its contents, and
|
||||
// that will let us support people assigning into this collection.
|
||||
get {
|
||||
self.permittedSubtrees.compactMap {
|
||||
if case .dNSName(let name) = $0 {
|
||||
return name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
/// The DNS name trees that are forbidden in certificates issued by this CA.
|
||||
///
|
||||
/// These restrictions are expressed in forms like `host.example.com`. Any DNS name that can be
|
||||
/// constructed by adding zero or more labels to the left-hand side of the name satifies the constraint.
|
||||
public var excludedDNSDomains: [String] {
|
||||
get {
|
||||
self.excludedSubtrees.compactMap {
|
||||
if case .dNSName(let name) = $0 {
|
||||
return name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
/// The IP ranges that are permitted in certificates issued by this CA.
|
||||
///
|
||||
/// These restrictions are expressed as a subnet, represented in an ASN.1 octet string.
|
||||
/// Due to the absence of a currency subnet and IP address type in Swift, these are preserved
|
||||
/// as octet strings.
|
||||
///
|
||||
/// As an example, the subnet 192.0.2.0/24 is encoded as the bytes `0xC0, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x00`.
|
||||
/// This represents a subnet root and its mask.
|
||||
///
|
||||
/// Any IP address attested that falls within one of these subnets matches the constraint.
|
||||
public var permittedIPRanges: [ASN1.ASN1OctetString] {
|
||||
get {
|
||||
self.permittedSubtrees.compactMap {
|
||||
if case .iPAddress(let address) = $0 {
|
||||
return address
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
/// The IP ranges that are forbidden in certificates issued by this CA.
|
||||
///
|
||||
/// These restrictions are expressed as a subnet, represented in an ASN.1 octet string.
|
||||
/// Due to the absence of a currency subnet and IP address type in Swift, these are preserved
|
||||
/// as octet strings.
|
||||
///
|
||||
/// As an example, the subnet 192.0.2.0/24 is encoded as the bytes `0xC0, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x00`.
|
||||
/// This represents a subnet root and its mask.
|
||||
///
|
||||
/// Any IP address attested that falls within one of these subnets matches the constraint.
|
||||
public var excludedIPRanges: [ASN1.ASN1OctetString] {
|
||||
get {
|
||||
self.excludedSubtrees.compactMap {
|
||||
if case .iPAddress(let address) = $0 {
|
||||
return address
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
/// The email addresses that are permitted in certificates issued by this CA.
|
||||
///
|
||||
/// This form may contain a specific mailbox (e.g. `user@example.com`), all
|
||||
/// addresses on a given host (e.g. `example.com`), or all mailboxes within a
|
||||
/// given domain (e.g. `.example.com`).
|
||||
public var permittedEmailAddresses: [String] {
|
||||
get {
|
||||
self.permittedSubtrees.compactMap {
|
||||
if case .rfc822Name(let name) = $0 {
|
||||
return name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
/// The email addresses that are permitted in certificates issued by this CA.
|
||||
///
|
||||
/// This form may contain a specific mailbox (e.g. `user@example.com`), all
|
||||
/// addresses on a given host (e.g. `example.com`), or all mailboxes within a
|
||||
/// given domain (e.g. `.example.com`).
|
||||
public var excludedEmailAddresses: [String] {
|
||||
get {
|
||||
self.excludedSubtrees.compactMap {
|
||||
if case .rfc822Name(let name) = $0 {
|
||||
return name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
/// The URI domains permitted in certificates issued by this CA.
|
||||
///
|
||||
/// This contraint applies only to the host part of the URI. The constraint
|
||||
/// must be specified as a fully-qualified domain name and may specify either
|
||||
/// a host or a domain. When it specifies a domain the string will begin with a
|
||||
/// period, and matches any name that can be expanded with one or more labels to
|
||||
/// the left. Note that expanding with zero labels does not match: that is,
|
||||
/// `.example.com` matches `host.example.com`, but not `example.com`.
|
||||
public var permittedURIDomains: [String] {
|
||||
get {
|
||||
self.permittedSubtrees.compactMap {
|
||||
if case .uniformResourceIdentifier(let name) = $0 {
|
||||
return name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
/// The URI domains forbidden in certificates issued by this CA.
|
||||
///
|
||||
/// This contraint applies only to the host part of the URI. The constraint
|
||||
/// must be specified as a fully-qualified domain name and may specify either
|
||||
/// a host or a domain. When it specifies a domain the string will begin with a
|
||||
/// period, and matches any name that can be expanded with one or more labels to
|
||||
/// the left. Note that expanding with zero labels does not match: that is,
|
||||
/// `.example.com` matches `host.example.com`, but not `example.com`.
|
||||
public var forbiddenURIDomains: [String] {
|
||||
get {
|
||||
self.excludedSubtrees.compactMap {
|
||||
if case .uniformResourceIdentifier(let name) = $0 {
|
||||
return name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
set {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
/// The complete set of permitted subtrees in ``GeneralName`` form.
|
||||
///
|
||||
/// This contains the same data as the broken out forms (``permittedIPRanges``, ``permittedDNSDomains``,
|
||||
/// ``permittedURIDomains``, ``permittedEmailAddresses``), but may also include other cases
|
||||
/// that those helpers do not represent.
|
||||
public var permittedSubtrees: [GeneralName]
|
||||
|
||||
/// The complete set of forbidden subtrees in ``GeneralName`` form.
|
||||
///
|
||||
/// This contains the same data as the broken out forms (``excludedIPRanges``, ``excludedDNSDomains``,
|
||||
/// ``forbiddenURIDomains``, ``excludedEmailAddresses``), but may also include other cases
|
||||
/// that those helpers do not represent.
|
||||
public var excludedSubtrees: [GeneralName]
|
||||
|
||||
/// Construct an extension constraining the names a CA may issue.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - permittedDNSDomains: The DNS name trees that are permitted in certificates issued by this CA.
|
||||
/// - excludedDNSDomains: The DNS name trees that are forbidden in certificates issued by this CA.
|
||||
/// - permittedIPRanges: The IP address ranges that are permitted in certificates issued by this CA.
|
||||
/// - excludedIPRanges: The IP address ranges that are forbidden in certificates issued by this CA.
|
||||
/// - permittedEmailAddresses: The email address trees that are permitted in certificates issued by this CA.
|
||||
/// - excludedEmailAddress: The email address trees that are forbidden in certificates issued by this CA.
|
||||
/// - permittedURIDomains: The URI domains that are permitted in certificates issued by this CA.
|
||||
/// - excludedURIDomains: The URI domains that are forbidden in certificates issued by this CA.
|
||||
@inlinable
|
||||
public init(
|
||||
permittedDNSDomains: [String] = [],
|
||||
excludedDNSDomains: [String] = [],
|
||||
permittedIPRanges: [ASN1.ASN1OctetString] = [],
|
||||
excludedIPRanges: [ASN1.ASN1OctetString] = [],
|
||||
permittedEmailAddresses: [String] = [],
|
||||
excludedEmailAddresses: [String] = [],
|
||||
permittedURIDomains: [String] = [],
|
||||
forbiddenURIDomains: [String] = []
|
||||
) {
|
||||
self.permittedSubtrees = []
|
||||
self.excludedSubtrees = []
|
||||
|
||||
self.permittedDNSDomains = permittedDNSDomains
|
||||
self.excludedDNSDomains = excludedDNSDomains
|
||||
self.permittedIPRanges = permittedIPRanges
|
||||
self.excludedIPRanges = excludedIPRanges
|
||||
self.permittedEmailAddresses = permittedEmailAddresses
|
||||
self.excludedEmailAddresses = excludedEmailAddresses
|
||||
self.permittedURIDomains = permittedURIDomains
|
||||
self.forbiddenURIDomains = forbiddenURIDomains
|
||||
}
|
||||
|
||||
/// Construct an extension constraining the names a CA may issue.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - permittedSubtrees: The complete set of permitted subtrees in ``GeneralName`` form.
|
||||
/// - excludedSubtrees: The complete set of excluded subtrees in ``GeneralName`` form.
|
||||
@inlinable
|
||||
public init(
|
||||
permittedSubtrees: [GeneralName] = [],
|
||||
excludedSubtrees: [GeneralName] = []
|
||||
) {
|
||||
self.permittedSubtrees = permittedSubtrees
|
||||
self.excludedSubtrees = excludedSubtrees
|
||||
}
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct`` object
|
||||
/// by unwrapping a ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to unwrap
|
||||
/// - Throws: if the ``Certificate/Extension/oid`` is not equal to
|
||||
/// `ASN1ObjectIdentifier.X509ExtensionID.nameConstraints`.
|
||||
@inlinable
|
||||
public init(_ ext: Certificate.Extension) throws {
|
||||
guard ext.oid == .X509ExtensionID.nameConstraints else {
|
||||
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1.ASN1ObjectIdentifier.X509ExtensionID.nameConstraints), got \(ext.oid)")
|
||||
}
|
||||
|
||||
let nameConstraintsValue = try NameConstraintsValue(asn1Encoded: ext.value)
|
||||
guard nameConstraintsValue.permittedSubtrees != nil || nameConstraintsValue.excludedSubtrees != nil else {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
|
||||
self.permittedSubtrees = nameConstraintsValue.permittedSubtrees ?? []
|
||||
self.excludedSubtrees = nameConstraintsValue.excludedSubtrees ?? []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.NameConstraints: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.NameConstraints: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.NameConstraints: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension {
|
||||
/// Construct an opaque ``Certificate/Extension`` from this Name Constraints extension.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - nameConstraints: The extension to wrap
|
||||
/// - critical: Whether this extension should have the critical bit set.
|
||||
@inlinable
|
||||
public init(_ nameConstraints: Certificate.Extensions.NameConstraints, critical: Bool) throws {
|
||||
let asn1Representation = NameConstraintsValue(nameConstraints)
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(asn1Representation)
|
||||
self.init(oid: .X509ExtensionID.nameConstraints, critical: critical, value: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.NameConstraints: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
return try .init(self, critical: false)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: ASN1 Helpers
|
||||
@usableFromInline
|
||||
struct NameConstraintsValue: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var permittedSubtrees: [GeneralName]?
|
||||
|
||||
@usableFromInline
|
||||
var excludedSubtrees: [GeneralName]?
|
||||
|
||||
@inlinable
|
||||
init(permittedSubtrees: [GeneralName]?, excludedSubtrees: [GeneralName]?) {
|
||||
self.permittedSubtrees = permittedSubtrees
|
||||
self.excludedSubtrees = excludedSubtrees
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(_ ext: Certificate.Extensions.NameConstraints) {
|
||||
if !ext.permittedSubtrees.isEmpty {
|
||||
self.permittedSubtrees = ext.permittedSubtrees
|
||||
}
|
||||
if !ext.excludedSubtrees.isEmpty {
|
||||
self.excludedSubtrees = ext.excludedSubtrees
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let permittedSubtrees: GeneralSubtrees? = try ASN1.optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 0, tagClass: .contextSpecific, constructed: true))
|
||||
let excludedSubtrees: GeneralSubtrees? = try ASN1.optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 1, tagClass: .contextSpecific, constructed: true))
|
||||
|
||||
return NameConstraintsValue(permittedSubtrees: permittedSubtrees.map { $0.base }, excludedSubtrees: excludedSubtrees.map { $0.base })
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serializeOptionalImplicitlyTagged(
|
||||
self.permittedSubtrees.map { GeneralSubtrees($0) },
|
||||
withIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific, constructed: true)
|
||||
)
|
||||
|
||||
try coder.serializeOptionalImplicitlyTagged(
|
||||
self.excludedSubtrees.map { GeneralSubtrees($0) },
|
||||
withIdentifier: .init(tagWithNumber: 1, tagClass: .contextSpecific, constructed: true)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct GeneralSubtrees: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var base: [GeneralName]
|
||||
|
||||
@inlinable
|
||||
init(_ base: [GeneralName]) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self.base = try ASN1.sequence(identifier: identifier, rootNode: rootNode)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.serializeSequenceOf(self.base, identifier: identifier)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct GeneralSubtree: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var base: GeneralName
|
||||
|
||||
@inlinable
|
||||
init(_ base: GeneralName) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self.base = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
try GeneralName(asn1Encoded: &nodes)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.base)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate.Extensions {
|
||||
/// Allows identities to be bound to the subject of a certificate.
|
||||
///
|
||||
/// The identities attested in this extension belong to the subject of the certificate.
|
||||
/// Users of the certificate may validate that these names correspond to a name they are
|
||||
/// expecting, depending on the context.
|
||||
public struct SubjectAlternativeNames {
|
||||
@usableFromInline
|
||||
var names: [GeneralName]
|
||||
|
||||
/// Construct a Subject Alternative Name extension from a sequence of
|
||||
/// ``GeneralName``s.
|
||||
///
|
||||
/// - Parameter names: The names to bind to the subject of the certificate.
|
||||
@inlinable
|
||||
public init<Names: Sequence>(_ names: Names) where Names.Element == GeneralName {
|
||||
self.names = Array(names)
|
||||
}
|
||||
|
||||
/// Construct a Subject Alternative Name extension that attests to no names.
|
||||
@inlinable
|
||||
public init() {
|
||||
self.names = []
|
||||
}
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct`` object
|
||||
/// by unwrapping a ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to unwrap
|
||||
/// - Throws: if the ``Certificate/Extension/oid`` is not equal to
|
||||
/// `ASN1ObjectIdentifier.X509ExtensionID.subjectAlternativeName`.
|
||||
@inlinable
|
||||
public init(_ ext: Certificate.Extension) throws {
|
||||
guard ext.oid == .X509ExtensionID.subjectAlternativeName else {
|
||||
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1.ASN1ObjectIdentifier.X509ExtensionID.subjectAlternativeName), got \(ext.oid)")
|
||||
}
|
||||
|
||||
let asn1SAN = try GeneralNames(asn1Encoded: ext.value)
|
||||
self.names = asn1SAN.names
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.SubjectAlternativeNames: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.SubjectAlternativeNames: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.SubjectAlternativeNames: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.SubjectAlternativeNames: RandomAccessCollection, MutableCollection, RangeReplaceableCollection {
|
||||
@inlinable
|
||||
public var startIndex: Int {
|
||||
self.names.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Int {
|
||||
self.names.endIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Int) -> GeneralName {
|
||||
get {
|
||||
self.names[position]
|
||||
}
|
||||
set {
|
||||
self.names[position] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func replaceSubrange<NewElements>(_ subrange: Range<Int>, with newElements: NewElements) where NewElements: Collection, GeneralName == NewElements.Element {
|
||||
self.names.replaceSubrange(subrange, with: newElements)
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension {
|
||||
/// Construct an opaque ``Certificate/Extension`` from this Subject Alternative Name extension.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - san: The extension to wrap
|
||||
/// - critical: Whether this extension should have the critical bit set.
|
||||
@inlinable
|
||||
public init(_ san: Certificate.Extensions.SubjectAlternativeNames, critical: Bool) throws {
|
||||
let asn1Representation = GeneralNames(san.names)
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(asn1Representation)
|
||||
self.init(oid: .X509ExtensionID.subjectAlternativeName, critical: critical, value: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.SubjectAlternativeNames: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
return try .init(self, critical: false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate.Extensions {
|
||||
/// Provides a means of identifying a certificate that contains a particular public key.
|
||||
///
|
||||
/// This extension contains a value derived from the public key of the certificate in which it appears.
|
||||
/// That value can be used to build the ``AuthorityKeyIdentifier-swift.struct/keyIdentifier`` field in
|
||||
/// any certificate issued by this certificate. This makes it possible to identify a certificate
|
||||
/// possessing the key that issued another certificate.
|
||||
public struct SubjectKeyIdentifier {
|
||||
public var keyIdentifier: ArraySlice<UInt8>
|
||||
|
||||
/// Construct a Subject Key Identifier extension with a specific key identifier.
|
||||
///
|
||||
/// - Parameter keyIdentifier: The identifier to associate with this certificate.
|
||||
@inlinable
|
||||
public init(keyIdentifier: ArraySlice<UInt8>) {
|
||||
self.keyIdentifier = keyIdentifier
|
||||
}
|
||||
|
||||
/// Create a new ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct`` object
|
||||
/// by unwrapping a ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to unwrap
|
||||
/// - Throws: if the ``Certificate/Extension/oid`` is not equal to
|
||||
/// `ASN1ObjectIdentifier.X509ExtensionID.subjectKeyIdentifier`.
|
||||
@inlinable
|
||||
public init(_ ext: Certificate.Extension) throws {
|
||||
guard ext.oid == .X509ExtensionID.subjectKeyIdentifier else {
|
||||
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1.ASN1ObjectIdentifier.X509ExtensionID.subjectKeyIdentifier), got \(ext.oid)")
|
||||
}
|
||||
|
||||
let asn1KeyIdentifier = try ASN1.ASN1OctetString(asn1Encoded: ext.value)
|
||||
self.keyIdentifier = asn1KeyIdentifier.bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.SubjectKeyIdentifier: Hashable { }
|
||||
|
||||
extension Certificate.Extensions.SubjectKeyIdentifier: Sendable { }
|
||||
|
||||
extension Certificate.Extensions.SubjectKeyIdentifier: CustomStringConvertible {
|
||||
public var description: String {
|
||||
fatalError("TODO")
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension {
|
||||
/// Construct an opaque ``Certificate/Extension`` from this Subject Key Identifier extension.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - ski: The extension to wrap
|
||||
/// - critical: Whether this extension should have the critical bit set.
|
||||
@inlinable
|
||||
public init(_ ski: Certificate.Extensions.SubjectKeyIdentifier, critical: Bool) throws {
|
||||
let asn1Representation = ASN1.ASN1OctetString(contentBytes: ski.keyIdentifier)
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(asn1Representation)
|
||||
self.init(oid: .X509ExtensionID.subjectKeyIdentifier, critical: critical, value: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions.SubjectKeyIdentifier: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
return try .init(self, critical: false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate {
|
||||
/// A general-purpose representation of a specific X.509 extension.
|
||||
///
|
||||
/// X.509 extensions are a general representation, with three properties: an identifier, a critical flag, and the encoded value.
|
||||
/// The specific data contained in the encoded value is determined by the value of the identifier stored in ``oid``.
|
||||
///
|
||||
/// This value enables ``Certificate/Extensions-swift.struct`` to store the value of all extensions in a certificate, even ones
|
||||
/// it does not understand. A number of extensions have built-in support, and can be decoded directly from an ``Extension``
|
||||
/// value. These are:
|
||||
///
|
||||
/// - ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct``
|
||||
/// - ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct``
|
||||
/// - ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum``
|
||||
/// - ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct``
|
||||
/// - ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct``
|
||||
/// - ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct``
|
||||
/// - ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct``
|
||||
/// - ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct``
|
||||
///
|
||||
/// Users can write their own types by using a similar approach to these types, when it is necessary to add support for
|
||||
/// different X.509 extension.
|
||||
public struct Extension {
|
||||
/// The identifier for this extension type.
|
||||
///
|
||||
/// Common values are stored in `ASN1.ASN1ObjectIdentifier.X509ExtensionID`.
|
||||
public var oid: ASN1.ASN1ObjectIdentifier
|
||||
|
||||
/// Whether this extension must be processed in order to trust the certificate.
|
||||
///
|
||||
/// If the code processing this ``Certificate`` does not understand this extension, the certificate
|
||||
/// must not be trusted.
|
||||
public var critical: Bool
|
||||
|
||||
/// The encoded bytes of the value of this extension.
|
||||
///
|
||||
/// This value should be decoded based on the value of ``oid``.
|
||||
public var value: ArraySlice<UInt8>
|
||||
|
||||
/// Construct a new extension from its constituent parts.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - oid: The identifier for this extension type.
|
||||
/// - critical: Whether this extension must be processed in order to trust the certificate.
|
||||
/// - value: The encoded bytes of the value of this extension.
|
||||
@inlinable
|
||||
public init(oid: ASN1.ASN1ObjectIdentifier, critical: Bool, value: ArraySlice<UInt8>) {
|
||||
self.oid = oid
|
||||
self.critical = critical
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension: Hashable { }
|
||||
|
||||
extension Certificate.Extension: Sendable { }
|
||||
|
||||
extension Certificate.Extension: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
public static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let extensionID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
|
||||
let critical = try ASN1.decodeDefault(&nodes, defaultValue: false)
|
||||
let value = try ASN1.ASN1OctetString(asn1Encoded: &nodes)
|
||||
|
||||
return Certificate.Extension(oid: extensionID, critical: critical, value: value.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.oid)
|
||||
|
||||
if self.critical {
|
||||
try coder.serialize(self.critical)
|
||||
}
|
||||
|
||||
try coder.serialize(ASN1.ASN1OctetString(contentBytes: self.value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extension: CertificateExtensionConvertible {
|
||||
public func makeCertificateExtension() -> Certificate.Extension {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension Certificate {
|
||||
/// A representation of a collection of X.509 extensions.
|
||||
///
|
||||
/// The majority of semantic information in an X.509 certificate is contained within its
|
||||
/// collection of extensions. These extensions can add additional constraints or capabilities
|
||||
/// to a certificate, or provide additional information about either the subject or the issuer
|
||||
/// of the certificate.
|
||||
///
|
||||
/// Each extension may appear only once in a given certificate. It may be marked as either critical
|
||||
/// or not. Critical extensions require that the user of a certificate understands the meaning of that
|
||||
/// extension (and can enforce it) in order to trust the certificate: if the user does not understand
|
||||
/// or cannot enforce that extension, it must reject the certificate outright.
|
||||
///
|
||||
/// ### Sequence and Collection Helpers
|
||||
///
|
||||
/// ``Certificate/Extensions-swift.struct`` is conceptually a collection of ``Certificate/Extension`` objects. The order
|
||||
/// is semantic and is preserved either in or from the serialized representation.
|
||||
///
|
||||
/// However, ``Certificate/Extensions-swift.struct`` is also conceptually a dictionary keyed by ``Certificate/Extension/oid``.
|
||||
/// For that reason, in addition to the index-based subscript ``Certificate/Extensions-swift.struct/subscript(_:)-5rodj``, this type also offers
|
||||
/// ``subscript(oid:)`` to enable finding the extension with a specific OID. This API also lets users replace
|
||||
/// the value of a specific extension.
|
||||
///
|
||||
/// ### Specific extension helpers
|
||||
///
|
||||
/// To make it easier to decode specific extensions, this type provides a number of helpers for known extension types:
|
||||
///
|
||||
/// - ``authorityInformationAccess-swift.property``
|
||||
/// - ``subjectKeyIdentifier-swift.property``
|
||||
/// - ``authorityKeyIdentifier-swift.property``
|
||||
/// - ``extendedKeyUsage-swift.property``
|
||||
/// - ``basicConstraints-swift.property``
|
||||
/// - ``keyUsage-swift.property``
|
||||
/// - ``nameConstraints-swift.property``
|
||||
/// - ``subjectAlternativeNames-swift.property``
|
||||
///
|
||||
/// Users who add their own extension types (see ``Certificate/Extension`` for more) are encouraged to add their
|
||||
/// own helper getters for those types.
|
||||
///
|
||||
/// ### Builder
|
||||
///
|
||||
/// Constructing ``Certificate/Extensions-swift.struct`` can be somewhat awkward due to the opaque nature of ``Certificate/Extension``.
|
||||
/// To make this easier, ``Certificate/Extensions-swift.struct`` supports being constructed using a result builder DSL powered by ``ExtensionsBuilder``
|
||||
/// and ``CertificateExtensionConvertible``, using ``init(builder:)``. As an example, we can create a simple set of
|
||||
/// extensions like this:
|
||||
///
|
||||
/// ```swift
|
||||
/// let extensions = Certificate.Extensions {
|
||||
/// Critical(
|
||||
/// Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true)
|
||||
/// )
|
||||
///
|
||||
/// Certificate.Extensions.ExtendedKeyUsage([.serverAuth, .clientAuth])
|
||||
///
|
||||
/// Critical(
|
||||
/// Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 0)
|
||||
/// )
|
||||
///
|
||||
/// Certificate.Extensions.AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This interface also makes it easy to mark specific extensions as critical.
|
||||
public struct Extensions {
|
||||
@usableFromInline
|
||||
var _extensions: [Extension]
|
||||
|
||||
/// Produce a new Extensions container from an array of ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter extensions: The base extensions.
|
||||
@inlinable
|
||||
public init(extensions: [Extension]) {
|
||||
// TODO(cory): Police uniqueness
|
||||
self._extensions = extensions
|
||||
}
|
||||
|
||||
/// Produce a new Extensions container from a collection of ``Certificate/Extension``.
|
||||
///
|
||||
/// - Parameter extensions: The base extensions.
|
||||
@inlinable
|
||||
public init<Elements>(_ extensions: Elements) where Elements: Sequence, Elements.Element == Extension {
|
||||
self._extensions = Array(extensions)
|
||||
}
|
||||
|
||||
/// Construct a collection of extensions using the ``ExtensionsBuilder`` syntax.
|
||||
///
|
||||
/// Constructing ``Certificate/Extensions-swift.struct`` can be somewhat awkward due to the opaque nature of ``Certificate/Extension``.
|
||||
/// To make this easier, ``Certificate/Extensions-swift.struct`` supports being constructed using a result builder DSL powered by ``ExtensionsBuilder``
|
||||
/// and ``CertificateExtensionConvertible``, using ``init(builder:)``. As an example, we can create a simple set of
|
||||
/// extensions like this:
|
||||
///
|
||||
/// ```swift
|
||||
/// let extensions = Certificate.Extensions {
|
||||
/// Critical(
|
||||
/// Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true)
|
||||
/// )
|
||||
///
|
||||
/// Certificate.Extensions.ExtendedKeyUsage([.serverAuth, .clientAuth])
|
||||
///
|
||||
/// Critical(
|
||||
/// Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 0)
|
||||
/// )
|
||||
///
|
||||
/// Certificate.Extensions.AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter builder: The ``ExtensionsBuilder`` DSL.
|
||||
@inlinable
|
||||
public init(@ExtensionsBuilder builder: () throws -> Certificate.Extensions) throws {
|
||||
self = try builder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions: Hashable { }
|
||||
|
||||
extension Certificate.Extensions: Sendable { }
|
||||
|
||||
// TODO: Tweak API surface here, this is more like a dictionary than an Array, and we
|
||||
// need to forbid duplicate extensions. Consider backing this with OrderedDictionary.
|
||||
extension Certificate.Extensions: RandomAccessCollection {
|
||||
@inlinable
|
||||
public init() {
|
||||
self._extensions = []
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var startIndex: Int {
|
||||
self._extensions.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Int {
|
||||
self._extensions.endIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Int) -> Certificate.Extension {
|
||||
// TODO(cory): enforce uniqueness
|
||||
get {
|
||||
self._extensions[position]
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a new ``Certificate/Extension`` into this set of ``Certificate/Extensions-swift.struct``.
|
||||
///
|
||||
/// - Parameter ext: The ``Certificate/Extension`` to insert.
|
||||
@inlinable
|
||||
public mutating func append(_ ext: Certificate.Extension) {
|
||||
// TODO(cory): enforce uniqueness
|
||||
self._extensions.append(ext)
|
||||
}
|
||||
|
||||
/// Append a sequence of new ``Certificate/Extension``s into this set of ``Certificate/Extensions-swift.struct``.
|
||||
///
|
||||
/// - Parameter extensions: The sequence of new ``Certificate/Extension``s to insert.
|
||||
@inlinable
|
||||
public mutating func append<Extensions: Sequence>(contentsOf extensions: Extensions) where Extensions.Element == Certificate.Extension {
|
||||
// TODO(cory): enforce uniqueness
|
||||
self._extensions.append(contentsOf: extensions)
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Extensions: CustomStringConvertible {
|
||||
@inlinable
|
||||
public var description: String {
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Helpers for specific extensions
|
||||
extension Certificate.Extensions {
|
||||
/// Look up a specific extension by its OID.
|
||||
///
|
||||
/// - Parameter oid: The OID to search for.
|
||||
@inlinable
|
||||
public subscript(oid oid: ASN1.ASN1ObjectIdentifier) -> Certificate.Extension? {
|
||||
get {
|
||||
return self.first(where: { $0.oid == oid })
|
||||
}
|
||||
set {
|
||||
if let newValue = newValue {
|
||||
precondition(oid == newValue.oid)
|
||||
if let currentExtensionIndex = self.firstIndex(where: { $0.oid == oid }) {
|
||||
self._extensions[currentExtensionIndex] = newValue
|
||||
} else {
|
||||
self._extensions.append(newValue)
|
||||
}
|
||||
} else if let currentExtensionIndex = self.firstIndex(where: { $0.oid == oid }) {
|
||||
self._extensions.remove(at: currentExtensionIndex)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct``
|
||||
/// extension, if it is present.
|
||||
///
|
||||
/// Throws if it is not possible to decode the AIA extension.
|
||||
@inlinable
|
||||
public var authorityInformationAccess: Certificate.Extensions.AuthorityInformationAccess? {
|
||||
get throws {
|
||||
try self[oid: .X509ExtensionID.authorityInformationAccess].map { try .init($0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct``
|
||||
/// extension, if it is present.
|
||||
///
|
||||
/// Throws if it is not possible to decode the SKI extension.
|
||||
@inlinable
|
||||
public var subjectKeyIdentifier: Certificate.Extensions.SubjectKeyIdentifier? {
|
||||
get throws {
|
||||
try self[oid: .X509ExtensionID.subjectKeyIdentifier].map { try .init($0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct``
|
||||
/// extension, if it is present.
|
||||
///
|
||||
/// Throws if it is not possible to decode the AKI extension.
|
||||
@inlinable
|
||||
public var authorityKeyIdentifier: Certificate.Extensions.AuthorityKeyIdentifier? {
|
||||
get throws {
|
||||
try self[oid: .X509ExtensionID.authorityKeyIdentifier].map { try .init($0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct``
|
||||
/// extension, if it is present.
|
||||
///
|
||||
/// Throws if it is not possible to decode the EKU extension.
|
||||
@inlinable
|
||||
public var extendedKeyUsage: Certificate.Extensions.ExtendedKeyUsage? {
|
||||
get throws {
|
||||
try self[oid: .X509ExtensionID.extendedKeyUsage].map { try .init($0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum``
|
||||
/// extension, if it is present.
|
||||
///
|
||||
/// Throws if it is not possible to decode the basic constraints extension.
|
||||
@inlinable
|
||||
public var basicConstraints: Certificate.Extensions.BasicConstraints? {
|
||||
get throws {
|
||||
try self[oid: .X509ExtensionID.basicConstraints].map { try .init($0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct``
|
||||
/// extension, if it is present.
|
||||
///
|
||||
/// Throws if it is not possible to decode the key usage extension.
|
||||
@inlinable
|
||||
public var keyUsage: Certificate.Extensions.KeyUsage? {
|
||||
get throws {
|
||||
try self[oid: .X509ExtensionID.keyUsage].map { try .init($0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct``
|
||||
/// extension, if it is present.
|
||||
///
|
||||
/// Throws if it is not possible to decode the name constraints extension.
|
||||
@inlinable
|
||||
public var nameConstraints: Certificate.Extensions.NameConstraints? {
|
||||
get throws {
|
||||
try self[oid: .X509ExtensionID.nameConstraints].map { try .init($0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct``
|
||||
/// extension, if it is present.
|
||||
///
|
||||
/// Throws if it is not possible to decode the SAN extension.
|
||||
@inlinable
|
||||
public var subjectAlternativeNames: Certificate.Extensions.SubjectAlternativeNames? {
|
||||
get throws {
|
||||
try self[oid: .X509ExtensionID.subjectAlternativeName].map { try .init($0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Provides a result-builder style DSL for constructing ``Certificate/Extensions-swift.struct`` values.
|
||||
///
|
||||
/// This DSL allows us to construct extensions straightforwardly, using their high-level representation instead of
|
||||
/// the erased representation provided by ``Certificate/Extension``. For example, a simple set of
|
||||
/// extensions can be produced like this:
|
||||
///
|
||||
/// ```swift
|
||||
/// let extensions = Certificate.Extensions {
|
||||
/// Critical(
|
||||
/// Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true)
|
||||
/// )
|
||||
///
|
||||
/// Certificate.Extensions.ExtendedKeyUsage([.serverAuth, .clientAuth])
|
||||
///
|
||||
/// Critical(
|
||||
/// Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 0)
|
||||
/// )
|
||||
///
|
||||
/// Certificate.Extensions.AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Users can extend this syntax for their own extensions by conforming their semantic type to ``CertificateExtensionConvertible``.
|
||||
/// This is the only requirement for adding new extensions to this builder syntax.
|
||||
///
|
||||
/// Users are also able to mark specific extensions as critical by using the ``Critical`` helper type.
|
||||
@resultBuilder
|
||||
public struct ExtensionsBuilder {
|
||||
@inlinable
|
||||
public static func buildExpression<Extension: CertificateExtensionConvertible>(_ expression: Extension) -> Certificate.Extensions {
|
||||
// TODO: we really need a way to avoid having this be try!.
|
||||
try! Certificate.Extensions([expression.makeCertificateExtension()])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildBlock(_ components: Certificate.Extensions...) -> Certificate.Extensions {
|
||||
Certificate.Extensions(components.lazy.flatMap { $0 })
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildOptional(_ component: Certificate.Extensions?) -> Certificate.Extensions {
|
||||
component ?? Certificate.Extensions([])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildEither(first component: Certificate.Extensions) -> Certificate.Extensions {
|
||||
component
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildEither(second component: Certificate.Extensions) -> Certificate.Extensions {
|
||||
component
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildArray(_ components: [Certificate.Extensions]) -> Certificate.Extensions {
|
||||
Certificate.Extensions(components.lazy.flatMap { $0 })
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func buildLimitedAvailability(_ component: Certificate.Extensions) -> Certificate.Extensions {
|
||||
component
|
||||
}
|
||||
}
|
||||
|
||||
/// Conforming types are capable of being erased into ``Certificate/Extension`` values.
|
||||
///
|
||||
/// Note that for most extension types, the returned ``Certificate/Extension`` should have its
|
||||
/// ``Certificate/Extension/critical`` value set to `false`. This allows the ``Critical`` helper
|
||||
/// type to fulfil its function as expected.
|
||||
public protocol CertificateExtensionConvertible {
|
||||
/// Convert the value into a ``Certificate/Extension``.
|
||||
func makeCertificateExtension() throws -> Certificate.Extension
|
||||
}
|
||||
|
||||
/// Marks a given ``CertificateExtensionConvertible`` value as critical.
|
||||
///
|
||||
/// This type is used only within the ``ExtensionsBuilder`` DSL to mark extensions as critical.
|
||||
@frozen
|
||||
public struct Critical<BaseExtension: CertificateExtensionConvertible>: CertificateExtensionConvertible {
|
||||
/// The ``CertificateExtensionConvertible`` backing this value.
|
||||
public var base: BaseExtension
|
||||
|
||||
/// Wrap a ``CertificateExtensionConvertible`` value and mark it critical.
|
||||
@inlinable
|
||||
public init(_ base: BaseExtension) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func makeCertificateExtension() throws -> Certificate.Extension {
|
||||
var ext = try self.base.makeCertificateExtension()
|
||||
ext.critical = true
|
||||
return ext
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
public enum GeneralName: Hashable, Sendable, ASN1Parseable, ASN1Serializable {
|
||||
case otherName(OtherName)
|
||||
case rfc822Name(String)
|
||||
case dNSName(String)
|
||||
case x400Address(ASN1.ASN1Any)
|
||||
case directoryName(DistinguishedName)
|
||||
case ediPartyName(ASN1.ASN1Any)
|
||||
case uniformResourceIdentifier(String)
|
||||
case iPAddress(ASN1.ASN1OctetString)
|
||||
case registeredID(ASN1.ASN1ObjectIdentifier)
|
||||
|
||||
@usableFromInline
|
||||
static let otherNameTag = ASN1.ASN1Identifier(tagWithNumber: 0, tagClass: .contextSpecific, constructed: true)
|
||||
@usableFromInline
|
||||
static let rfc822NameTag = ASN1.ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific, constructed: false)
|
||||
@usableFromInline
|
||||
static let dNSNameTag = ASN1.ASN1Identifier(tagWithNumber: 2, tagClass: .contextSpecific, constructed: false)
|
||||
@usableFromInline
|
||||
static let x400AddressTag = ASN1.ASN1Identifier(tagWithNumber: 3, tagClass: .contextSpecific, constructed: true)
|
||||
@usableFromInline
|
||||
static let directoryNameTag = ASN1.ASN1Identifier(tagWithNumber: 4, tagClass: .contextSpecific, constructed: true)
|
||||
@usableFromInline
|
||||
static let ediPartyNameTag = ASN1.ASN1Identifier(tagWithNumber: 5, tagClass: .contextSpecific, constructed: true)
|
||||
@usableFromInline
|
||||
static let uriTag = ASN1.ASN1Identifier(tagWithNumber: 6, tagClass: .contextSpecific, constructed: false)
|
||||
@usableFromInline
|
||||
static let iPAddressTag = ASN1.ASN1Identifier(tagWithNumber: 7, tagClass: .contextSpecific, constructed: false)
|
||||
@usableFromInline
|
||||
static let registeredIDTag = ASN1.ASN1Identifier(tagWithNumber: 8, tagClass: .contextSpecific, constructed: false)
|
||||
|
||||
@inlinable
|
||||
public init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
|
||||
switch rootNode.identifier {
|
||||
case Self.otherNameTag:
|
||||
self = try .otherName(OtherName(asn1Encoded: rootNode, withIdentifier: Self.otherNameTag))
|
||||
case Self.rfc822NameTag:
|
||||
let result = try ASN1.ASN1IA5String(asn1Encoded: rootNode, withIdentifier: Self.rfc822NameTag)
|
||||
self = .rfc822Name(String(result))
|
||||
case Self.dNSNameTag:
|
||||
let result = try ASN1.ASN1IA5String(asn1Encoded: rootNode, withIdentifier: Self.dNSNameTag)
|
||||
self = .dNSName(String(result))
|
||||
case Self.x400AddressTag:
|
||||
self = .x400Address(ASN1.ASN1Any(asn1Encoded: rootNode))
|
||||
case Self.directoryNameTag:
|
||||
self = try .directoryName(DistinguishedName(asn1Encoded: rootNode, withIdentifier: Self.directoryNameTag))
|
||||
case Self.ediPartyNameTag:
|
||||
self = .ediPartyName(ASN1.ASN1Any(asn1Encoded: rootNode))
|
||||
case Self.uriTag:
|
||||
let result = try ASN1.ASN1IA5String(asn1Encoded: rootNode, withIdentifier: Self.uriTag)
|
||||
self = .uniformResourceIdentifier(String(result))
|
||||
case Self.iPAddressTag:
|
||||
self = try .iPAddress(ASN1.ASN1OctetString(asn1Encoded: rootNode, withIdentifier: Self.iPAddressTag))
|
||||
case Self.registeredIDTag:
|
||||
self = try .registeredID(ASN1.ASN1ObjectIdentifier(asn1Encoded: rootNode, withIdentifier: Self.registeredIDTag))
|
||||
default:
|
||||
throw ASN1Error.invalidFieldIdentifier
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func serialize(into coder: inout ASN1.Serializer) throws {
|
||||
switch self {
|
||||
case .otherName(let otherName):
|
||||
try otherName.serialize(into: &coder, withIdentifier: Self.otherNameTag)
|
||||
case .rfc822Name(let name):
|
||||
let ia5String = try ASN1.ASN1IA5String(name)
|
||||
try ia5String.serialize(into: &coder, withIdentifier: Self.rfc822NameTag)
|
||||
case .dNSName(let name):
|
||||
let ia5String = try ASN1.ASN1IA5String(name)
|
||||
try ia5String.serialize(into: &coder, withIdentifier: Self.dNSNameTag)
|
||||
case .x400Address(let orAddress):
|
||||
try orAddress.serialize(into: &coder)
|
||||
case .directoryName(let name):
|
||||
try name.serialize(into: &coder, withIdentifier: Self.directoryNameTag)
|
||||
case .ediPartyName(let name):
|
||||
try name.serialize(into: &coder)
|
||||
case .uniformResourceIdentifier(let name):
|
||||
let ia5String = try ASN1.ASN1IA5String(name)
|
||||
try ia5String.serialize(into: &coder, withIdentifier: Self.uriTag)
|
||||
case .iPAddress(let ipAddress):
|
||||
try ipAddress.serialize(into: &coder, withIdentifier: Self.iPAddressTag)
|
||||
case .registeredID(let id):
|
||||
try id.serialize(into: &coder, withIdentifier: Self.registeredIDTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//GeneralName ::= CHOICE {
|
||||
// otherName [0] OtherName,
|
||||
// rfc822Name [1] IA5String,
|
||||
// dNSName [2] IA5String,
|
||||
// x400Address [3] ORAddress,
|
||||
// directoryName [4] Name,
|
||||
// ediPartyName [5] EDIPartyName,
|
||||
// uniformResourceIdentifier [6] IA5String,
|
||||
// iPAddress [7] OCTET STRING,
|
||||
// registeredID [8] OBJECT IDENTIFIER }
|
||||
//
|
||||
//OtherName ::= SEQUENCE {
|
||||
// type-id OBJECT IDENTIFIER,
|
||||
// value [0] EXPLICIT ANY DEFINED BY type-id }
|
||||
//
|
||||
//EDIPartyName ::= SEQUENCE {
|
||||
// nameAssigner [0] DirectoryString OPTIONAL,
|
||||
// partyName [1] DirectoryString }
|
||||
|
||||
extension GeneralName {
|
||||
public struct OtherName: Hashable, Sendable, ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
public static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
public var typeID: ASN1.ASN1ObjectIdentifier
|
||||
|
||||
public var value: ASN1.ASN1Any?
|
||||
|
||||
@inlinable
|
||||
public init(typeID: ASN1.ASN1ObjectIdentifier, value: ASN1.ASN1Any?) {
|
||||
self.typeID = typeID
|
||||
self.value = value
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let typeID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
|
||||
let value = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) {
|
||||
ASN1.ASN1Any(asn1Encoded: $0)
|
||||
}
|
||||
|
||||
return OtherName(typeID: typeID, value: value)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.typeID)
|
||||
if let value = self.value {
|
||||
try coder.serialize(value, explicitlyTaggedWithIdentifier: .init(explicitTagWithNumber: 0, tagClass: .contextSpecific))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct GeneralNames: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var names: [GeneralName]
|
||||
|
||||
@inlinable
|
||||
init(_ names: [GeneralName]) {
|
||||
self.names = names
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self.names = try ASN1.sequence(of: GeneralName.self, identifier: identifier, rootNode: rootNode)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
for name in names {
|
||||
try coder.serialize(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// Let's talk about OCSP.
|
||||
///
|
||||
/// We can provide the needed type definitions from RFC 6960 to construct BasicOCSPResponse:
|
||||
///
|
||||
/// ```
|
||||
/// BasicOCSPResponse ::= SEQUENCE {
|
||||
/// tbsResponseData ResponseData,
|
||||
/// signatureAlgorithm AlgorithmIdentifier,
|
||||
/// signature BIT STRING,
|
||||
/// certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
|
||||
///
|
||||
/// ResponseData ::= SEQUENCE {
|
||||
/// version [0] EXPLICIT Version DEFAULT v1,
|
||||
/// responderID ResponderID,
|
||||
/// producedAt GeneralizedTime,
|
||||
/// responses SEQUENCE OF SingleResponse,
|
||||
/// responseExtensions [1] EXPLICIT Extensions OPTIONAL }
|
||||
///
|
||||
/// ResponderID ::= CHOICE {
|
||||
/// byName [1] Name,
|
||||
/// byKey [2] KeyHash }
|
||||
///
|
||||
/// KeyHash ::= OCTET STRING
|
||||
///
|
||||
/// SingleResponse ::= SEQUENCE {
|
||||
/// certID CertID,
|
||||
/// certStatus CertStatus,
|
||||
/// thisUpdate GeneralizedTime,
|
||||
/// nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
|
||||
/// singleExtensions [1] EXPLICIT Extensions OPTIONAL }
|
||||
///
|
||||
/// CertStatus ::= CHOICE {
|
||||
/// good [0] IMPLICIT NULL,
|
||||
/// revoked [1] IMPLICIT RevokedInfo,
|
||||
/// unknown [2] IMPLICIT UnknownInfo }
|
||||
///
|
||||
/// RevokedInfo ::= SEQUENCE {
|
||||
/// revocationTime GeneralizedTime,
|
||||
/// revocationReason [0] EXPLICIT CRLReason OPTIONAL }
|
||||
///
|
||||
/// UnknownInfo ::= NULL
|
||||
///
|
||||
/// Version ::= INTEGER { v1(0) }
|
||||
///
|
||||
/// CertID ::= SEQUENCE {
|
||||
/// hashAlgorithm AlgorithmIdentifier,
|
||||
/// issuerNameHash OCTET STRING,
|
||||
/// issuerKeyHash OCTET STRING,
|
||||
/// serialNumber CertificateSerialNumber }
|
||||
/// ```
|
||||
|
||||
/// A Basic OCSP Response is laid out as follows:
|
||||
///
|
||||
/// ```
|
||||
/// BasicOCSPResponse ::= SEQUENCE {
|
||||
/// tbsResponseData ResponseData,
|
||||
/// signatureAlgorithm AlgorithmIdentifier,
|
||||
/// signature BIT STRING,
|
||||
/// certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
|
||||
/// ```
|
||||
///
|
||||
/// This type is generic because our different backends want to use different bignum representations.
|
||||
struct BasicOCSPResponse: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
var responseData: OCSPResponseData
|
||||
|
||||
var signatureAlgorithm: AlgorithmIdentifier
|
||||
|
||||
var signature: ASN1.ASN1BitString
|
||||
|
||||
// Yup, you read this right: for the moment, we don't decode certs. We need a strategy for this.
|
||||
//var certs: []
|
||||
|
||||
init(responseData: OCSPResponseData, signatureAlgorithm: AlgorithmIdentifier, signature: ASN1.ASN1BitString) {
|
||||
self.responseData = responseData
|
||||
self.signatureAlgorithm = signatureAlgorithm
|
||||
self.signature = signature
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let responseData = try OCSPResponseData(asn1Encoded: &nodes)
|
||||
let signatureAlgorithm = try AlgorithmIdentifier(asn1Encoded: &nodes)
|
||||
let signature = try ASN1.ASN1BitString(asn1Encoded: &nodes)
|
||||
|
||||
// We need to consume the certificate nodes, but we don't _yet_ parse it.
|
||||
_ = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in }
|
||||
|
||||
return .init(responseData: responseData, signatureAlgorithm: signatureAlgorithm, signature: signature)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.responseData)
|
||||
try coder.serialize(self.signatureAlgorithm)
|
||||
try coder.serialize(self.signature)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ResponderID: ASN1Parseable, ASN1Serializable, Hashable {
|
||||
case byName(DistinguishedName)
|
||||
case byKey(ASN1.ASN1OctetString)
|
||||
|
||||
private static let nameIdentifier = ASN1.ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific, constructed: true)
|
||||
private static let keyIdentifier = ASN1.ASN1Identifier(tagWithNumber: 2, tagClass: .contextSpecific, constructed: true)
|
||||
|
||||
init(asn1Encoded: ASN1.ASN1Node) throws {
|
||||
switch asn1Encoded.identifier {
|
||||
case ResponderID.nameIdentifier:
|
||||
guard case .constructed(let nodes) = asn1Encoded.content else {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
var iterator = nodes.makeIterator()
|
||||
guard let rootNode = iterator.next(), iterator.next() == nil else {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
|
||||
self = try .byName(.init(asn1Encoded: rootNode))
|
||||
case ResponderID.keyIdentifier:
|
||||
guard case .constructed(let nodes) = asn1Encoded.content else {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
var iterator = nodes.makeIterator()
|
||||
guard let rootNode = iterator.next(), iterator.next() == nil else {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
|
||||
self = try .byKey(.init(asn1Encoded: rootNode))
|
||||
default:
|
||||
throw ASN1Error.unexpectedFieldType
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer) throws {
|
||||
switch self {
|
||||
case .byName(let name):
|
||||
try coder.appendConstructedNode(identifier: ResponderID.nameIdentifier) { coder in
|
||||
try name.serialize(into: &coder)
|
||||
}
|
||||
case .byKey(let key):
|
||||
try coder.appendConstructedNode(identifier: ResponderID.keyIdentifier) { coder in
|
||||
try key.serialize(into: &coder)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
/// A DirectoryString is defined as:
|
||||
///
|
||||
/// ```
|
||||
/// DirectoryString ::= CHOICE {
|
||||
/// teletexString TeletexString (SIZE (1..MAX)),
|
||||
/// printableString PrintableString (SIZE (1..MAX)),
|
||||
/// universalString UniversalString (SIZE (1..MAX)),
|
||||
/// utf8String UTF8String (SIZE (1..MAX)),
|
||||
/// bmpString BMPString (SIZE (1..MAX)) }
|
||||
/// ```
|
||||
///
|
||||
/// Note that these upper bounds are measured in _characters_, not bytes.
|
||||
///
|
||||
@usableFromInline
|
||||
enum DirectoryString: ASN1Parseable, ASN1Serializable, Hashable {
|
||||
case teletexString(ASN1.ASN1TeletexString)
|
||||
case printableString(ASN1.ASN1PrintableString)
|
||||
case universalString(ASN1.ASN1UniversalString)
|
||||
case utf8String(ASN1.ASN1UTF8String)
|
||||
case bmpString(ASN1.ASN1BMPString)
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
|
||||
switch rootNode.identifier {
|
||||
case .primitiveTeletexString:
|
||||
self = .teletexString(try ASN1.ASN1TeletexString(asn1Encoded: rootNode))
|
||||
case .primitivePrintableString:
|
||||
self = .printableString(try ASN1.ASN1PrintableString(asn1Encoded: rootNode))
|
||||
case .primitiveUniversalString:
|
||||
self = .universalString(try ASN1.ASN1UniversalString(asn1Encoded: rootNode))
|
||||
case .primitiveUTF8String:
|
||||
self = .utf8String(try ASN1.ASN1UTF8String(asn1Encoded: rootNode))
|
||||
case .primitiveBMPString:
|
||||
self = .bmpString(try ASN1.ASN1BMPString(asn1Encoded: rootNode))
|
||||
default:
|
||||
throw ASN1Error.unexpectedFieldType
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer) throws {
|
||||
switch self {
|
||||
case .teletexString(let string):
|
||||
try string.serialize(into: &coder)
|
||||
case .printableString(let string):
|
||||
try string.serialize(into: &coder)
|
||||
case .universalString(let string):
|
||||
try string.serialize(into: &coder)
|
||||
case .utf8String(let string):
|
||||
try string.serialize(into: &coder)
|
||||
case .bmpString(let string):
|
||||
try string.serialize(into: &coder)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// A CertID is defined as:
|
||||
///
|
||||
/// ```
|
||||
/// CertID ::= SEQUENCE {
|
||||
/// hashAlgorithm AlgorithmIdentifier,
|
||||
/// issuerNameHash OCTET STRING, -- Hash of issuer's DN
|
||||
/// issuerKeyHash OCTET STRING, -- Hash of issuer's public key
|
||||
/// serialNumber CertificateSerialNumber }
|
||||
///
|
||||
/// CertificateSerialNumber ::= INTEGER
|
||||
/// ```
|
||||
///
|
||||
struct OCSPCertID: ASN1ImplicitlyTaggable, Hashable {
|
||||
var hashAlgorithm: AlgorithmIdentifier
|
||||
|
||||
var issuerNameHash: ASN1.ASN1OctetString
|
||||
|
||||
var issuerKeyHash: ASN1.ASN1OctetString
|
||||
|
||||
var serialNumber: ArraySlice<UInt8>
|
||||
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
init(hashAlgorithm: AlgorithmIdentifier,
|
||||
issuerNameHash: ASN1.ASN1OctetString,
|
||||
issuerKeyHash: ASN1.ASN1OctetString,
|
||||
serialNumber: ArraySlice<UInt8>) {
|
||||
self.hashAlgorithm = hashAlgorithm
|
||||
self.issuerNameHash = issuerNameHash
|
||||
self.issuerKeyHash = issuerKeyHash
|
||||
self.serialNumber = serialNumber
|
||||
}
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(node, identifier: identifier) { nodes in
|
||||
let hashAlgorithm = try AlgorithmIdentifier(asn1Encoded: &nodes)
|
||||
let issuerNameHash = try ASN1.ASN1OctetString(asn1Encoded: &nodes)
|
||||
let issuerKeyHash = try ASN1.ASN1OctetString(asn1Encoded: &nodes)
|
||||
let serialNumber = try ArraySlice<UInt8>(asn1Encoded: &nodes)
|
||||
|
||||
return .init(hashAlgorithm: hashAlgorithm,
|
||||
issuerNameHash: issuerNameHash,
|
||||
issuerKeyHash: issuerKeyHash,
|
||||
serialNumber: serialNumber)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try self.hashAlgorithm.serialize(into: &coder)
|
||||
try self.issuerNameHash.serialize(into: &coder)
|
||||
try self.issuerKeyHash.serialize(into: &coder)
|
||||
try self.serialNumber.serialize(into: &coder)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// A CertID is defined as:
|
||||
///
|
||||
/// ```
|
||||
/// CertStatus ::= CHOICE {
|
||||
/// good [0] IMPLICIT NULL,
|
||||
/// revoked [1] IMPLICIT RevokedInfo,
|
||||
/// unknown [2] IMPLICIT UnknownInfo }
|
||||
///
|
||||
/// RevokedInfo ::= SEQUENCE {
|
||||
/// revocationTime GeneralizedTime,
|
||||
/// revocationReason [0] EXPLICIT CRLReason OPTIONAL }
|
||||
///
|
||||
/// UnknownInfo ::= NULL
|
||||
///
|
||||
/// CRLReason ::= ENUMERATED {
|
||||
/// unspecified (0),
|
||||
/// keyCompromise (1),
|
||||
/// cACompromise (2),
|
||||
/// affiliationChanged (3),
|
||||
/// superseded (4),
|
||||
/// cessationOfOperation (5),
|
||||
/// certificateHold (6),
|
||||
/// -- value 7 is not used
|
||||
/// removeFromCRL (8),
|
||||
/// privilegeWithdrawn (9),
|
||||
/// aACompromise (10) }
|
||||
/// ```
|
||||
///
|
||||
enum OCSPCertStatus: ASN1Parseable, ASN1Serializable, Hashable {
|
||||
case good
|
||||
case revoked(OCSPRevokedInfo)
|
||||
case unknown
|
||||
|
||||
private static let goodIdentifier = ASN1.ASN1Identifier(tagWithNumber: 0, tagClass: .contextSpecific, constructed: false)
|
||||
private static let revokedIdentifier = ASN1.ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific, constructed: true)
|
||||
private static let unknownIdentifier = ASN1.ASN1Identifier(tagWithNumber: 2, tagClass: .contextSpecific, constructed: false)
|
||||
|
||||
init(asn1Encoded node: ASN1.ASN1Node) throws {
|
||||
switch node.identifier {
|
||||
case OCSPCertStatus.goodIdentifier:
|
||||
_ = try ASN1.ASN1Null(asn1Encoded: node, withIdentifier: OCSPCertStatus.goodIdentifier)
|
||||
self = .good
|
||||
|
||||
case OCSPCertStatus.revokedIdentifier:
|
||||
self = try .revoked(.init(asn1Encoded: node, withIdentifier: OCSPCertStatus.revokedIdentifier))
|
||||
|
||||
case OCSPCertStatus.unknownIdentifier:
|
||||
_ = try ASN1.ASN1Null(asn1Encoded: node, withIdentifier: OCSPCertStatus.unknownIdentifier)
|
||||
self = .unknown
|
||||
|
||||
default:
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer) throws {
|
||||
switch self {
|
||||
case .good:
|
||||
ASN1.ASN1Null().serialize(into: &coder, withIdentifier: OCSPCertStatus.goodIdentifier)
|
||||
|
||||
case .revoked(let revokedInfo):
|
||||
try revokedInfo.serialize(into: &coder, withIdentifier: OCSPCertStatus.revokedIdentifier)
|
||||
|
||||
case .unknown:
|
||||
ASN1.ASN1Null().serialize(into: &coder, withIdentifier: OCSPCertStatus.unknownIdentifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct OCSPRevokedInfo: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
var revocationTime: ASN1.GeneralizedTime
|
||||
|
||||
var revocationReason: CRLReason?
|
||||
|
||||
init(revocationTime: ASN1.GeneralizedTime, revocationReason: CRLReason?) {
|
||||
self.revocationTime = revocationTime
|
||||
self.revocationReason = revocationReason
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let revocationTime = try ASN1.GeneralizedTime(asn1Encoded: &nodes)
|
||||
let revocationReason = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
|
||||
try CRLReason(asn1Encoded: node)
|
||||
}
|
||||
|
||||
return .init(revocationTime: revocationTime, revocationReason: revocationReason)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.revocationTime)
|
||||
|
||||
if let revocationReason = self.revocationReason {
|
||||
try coder.serialize(revocationReason, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CRLReason: ASN1ImplicitlyTaggable, Hashable, RawRepresentable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.enumerated
|
||||
}
|
||||
|
||||
var rawValue: Int
|
||||
|
||||
init(rawValue: Int) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self.rawValue = try .init(asn1Encoded: rootNode, withIdentifier: identifier)
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try self.rawValue.serialize(into: &coder, withIdentifier: identifier)
|
||||
}
|
||||
|
||||
static let unspecified = CRLReason(rawValue: 0)
|
||||
static let keyCompromise = CRLReason(rawValue: 1)
|
||||
static let caCompromise = CRLReason(rawValue: 2)
|
||||
static let affiliationChanged = CRLReason(rawValue: 3)
|
||||
static let superseded = CRLReason(rawValue: 4)
|
||||
static let cessationOfOperation = CRLReason(rawValue: 5)
|
||||
static let certificateHold = CRLReason(rawValue: 6)
|
||||
static let removeFromCRL = CRLReason(rawValue: 8)
|
||||
static let privilegeWithdrawn = CRLReason(rawValue: 9)
|
||||
static let aaCompromise = CRLReason(rawValue: 10)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// An OCSPResponse is defined as:
|
||||
///
|
||||
/// ```
|
||||
/// OCSPResponse ::= SEQUENCE {
|
||||
/// responseStatus OCSPResponseStatus,
|
||||
/// responseBytes [0] EXPLICIT ResponseBytes OPTIONAL }
|
||||
///
|
||||
/// ```
|
||||
///
|
||||
struct OCSPResponse: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
var responseStatus: OCSPResponseStatus
|
||||
|
||||
var responseBytes: OCSPResponseBytes?
|
||||
|
||||
init(responseStatus: OCSPResponseStatus, responseBytes: OCSPResponseBytes?) {
|
||||
self.responseStatus = responseStatus
|
||||
self.responseBytes = responseBytes
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let responseStatus = try OCSPResponseStatus(asn1Encoded: &nodes)
|
||||
let responseBytes = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
|
||||
try OCSPResponseBytes(asn1Encoded: node)
|
||||
}
|
||||
|
||||
return .init(responseStatus: responseStatus, responseBytes: responseBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.responseStatus)
|
||||
if let responseBytes = self.responseBytes {
|
||||
try coder.serialize(responseBytes, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// An OCSPResponseBytes is defined as:
|
||||
///
|
||||
/// ```
|
||||
/// ResponseBytes ::= SEQUENCE {
|
||||
/// responseType OBJECT IDENTIFIER,
|
||||
/// response OCTET STRING }
|
||||
///
|
||||
/// For a basic OCSP responder, responseType will be id-pkix-ocsp-basic.
|
||||
///
|
||||
/// id-pkix-ocsp OBJECT IDENTIFIER ::= { id-ad-ocsp }
|
||||
/// id-pkix-ocsp-basic OBJECT IDENTIFIER ::= { id-pkix-ocsp 1 }
|
||||
/// ```
|
||||
///
|
||||
struct OCSPResponseBytes: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
var responseType: ASN1.ASN1ObjectIdentifier
|
||||
|
||||
var response: ASN1.ASN1OctetString
|
||||
|
||||
init(responseType: ASN1.ASN1ObjectIdentifier, response: ASN1.ASN1OctetString) {
|
||||
self.responseType = responseType
|
||||
self.response = response
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let responseType = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
|
||||
let response = try ASN1.ASN1OctetString(asn1Encoded: &nodes)
|
||||
return .init(responseType: responseType, response: response)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.responseType)
|
||||
try coder.serialize(self.response)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BasicOCSPResponse {
|
||||
init(decoding original: OCSPResponseBytes) throws {
|
||||
guard original.responseType == .OCSP.basicResponse else {
|
||||
throw ASN1Error.invalidObjectIdentifier
|
||||
}
|
||||
|
||||
self = try .init(asn1Encoded: original.response.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
extension OCSPResponseBytes {
|
||||
init(encoding original: BasicOCSPResponse) throws {
|
||||
self.responseType = .OCSP.basicResponse
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(original)
|
||||
self.response = ASN1.ASN1OctetString(contentBytes: serializer.serializedBytes[...])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// An OCSPResponseData is defined as:
|
||||
///
|
||||
/// ```
|
||||
/// ResponseData ::= SEQUENCE {
|
||||
/// version [0] EXPLICIT Version DEFAULT v1,
|
||||
/// responderID ResponderID,
|
||||
/// producedAt GeneralizedTime,
|
||||
/// responses SEQUENCE OF SingleResponse,
|
||||
/// responseExtensions [1] EXPLICIT Extensions OPTIONAL }
|
||||
///
|
||||
/// Version ::= INTEGER { v1(0) }
|
||||
/// ```
|
||||
///
|
||||
struct OCSPResponseData: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
var version: Int
|
||||
|
||||
var responderID: ResponderID
|
||||
|
||||
var producedAt: ASN1.GeneralizedTime
|
||||
|
||||
var responses: [OCSPSingleResponse]
|
||||
|
||||
var responseExtensions: [Certificate.Extension]?
|
||||
|
||||
init(version: Int = 0,
|
||||
responderID: ResponderID,
|
||||
producedAt: ASN1.GeneralizedTime,
|
||||
responses: [OCSPSingleResponse],
|
||||
responseExtensions: [Certificate.Extension]?) {
|
||||
self.version = version
|
||||
self.responderID = responderID
|
||||
self.producedAt = producedAt
|
||||
self.responses = responses
|
||||
self.responseExtensions = responseExtensions
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let version = try ASN1.decodeDefaultExplicitlyTagged(&nodes,
|
||||
tagNumber: 0,
|
||||
tagClass: .contextSpecific,
|
||||
defaultValue: 0) { try Int(asn1Encoded: $0) }
|
||||
let responderID = try ResponderID(asn1Encoded: &nodes)
|
||||
let producedAt = try ASN1.GeneralizedTime(asn1Encoded: &nodes)
|
||||
let responses = try ASN1.sequence(of: OCSPSingleResponse.self, identifier: .sequence, nodes: &nodes)
|
||||
let responseExtensions = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
|
||||
try ASN1.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node)
|
||||
}
|
||||
|
||||
return .init(version: version, responderID: responderID, producedAt: producedAt, responses: responses, responseExtensions: responseExtensions)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
if self.version != 0 {
|
||||
try coder.serialize(self.version, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
|
||||
}
|
||||
|
||||
try coder.serialize(self.responderID)
|
||||
try coder.serialize(self.producedAt)
|
||||
try coder.serializeSequenceOf(self.responses)
|
||||
|
||||
if let responseExtensions = self.responseExtensions {
|
||||
try coder.serialize(explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific) { coder in
|
||||
try coder.serializeSequenceOf(responseExtensions)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// A OCSPResponseStatus is defined as:
|
||||
///
|
||||
/// ```
|
||||
/// OCSPResponseStatus ::= ENUMERATED {
|
||||
/// successful (0), -- Response has valid confirmations
|
||||
/// malformedRequest (1), -- Illegal confirmation request
|
||||
/// internalError (2), -- Internal error in issuer
|
||||
/// tryLater (3), -- Try again later
|
||||
/// -- (4) is not used
|
||||
/// sigRequired (5), -- Must sign the request
|
||||
/// unauthorized (6) -- Request unauthorized
|
||||
/// }
|
||||
|
||||
/// ```
|
||||
///
|
||||
enum OCSPResponseStatus: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.enumerated
|
||||
}
|
||||
|
||||
case successful
|
||||
case malformedRequest
|
||||
case internalError
|
||||
case tryLater
|
||||
case sigRequired
|
||||
case unauthorized
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
let rawValue = try Int(asn1Encoded: rootNode, withIdentifier: identifier)
|
||||
|
||||
switch rawValue {
|
||||
case 0:
|
||||
self = .successful
|
||||
case 1:
|
||||
self = .malformedRequest
|
||||
case 2:
|
||||
self = .internalError
|
||||
case 3:
|
||||
self = .tryLater
|
||||
case 5:
|
||||
self = .sigRequired
|
||||
case 6:
|
||||
self = .unauthorized
|
||||
default:
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
let integerValue: Int
|
||||
|
||||
switch self {
|
||||
case .successful:
|
||||
integerValue = 0
|
||||
case .malformedRequest:
|
||||
integerValue = 1
|
||||
case .internalError:
|
||||
integerValue = 2
|
||||
case .tryLater:
|
||||
integerValue = 3
|
||||
case .sigRequired:
|
||||
integerValue = 5
|
||||
case .unauthorized:
|
||||
integerValue = 6
|
||||
}
|
||||
|
||||
try integerValue.serialize(into: &coder, withIdentifier: identifier)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// An OCSPSingleResponse is defined as:
|
||||
///
|
||||
/// ```
|
||||
/// SingleResponse ::= SEQUENCE {
|
||||
/// certID CertID,
|
||||
/// certStatus CertStatus,
|
||||
/// thisUpdate GeneralizedTime,
|
||||
/// nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
|
||||
/// singleExtensions [1] EXPLICIT Extensions OPTIONAL }
|
||||
/// ```
|
||||
///
|
||||
struct OCSPSingleResponse: ASN1ImplicitlyTaggable, Hashable {
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
var certID: OCSPCertID
|
||||
|
||||
var certStatus: OCSPCertStatus
|
||||
|
||||
var thisUpdate: ASN1.GeneralizedTime
|
||||
|
||||
var nextUpdate: ASN1.GeneralizedTime?
|
||||
|
||||
var extensions: [Certificate.Extension]?
|
||||
|
||||
init(certID: OCSPCertID,
|
||||
certStatus: OCSPCertStatus,
|
||||
thisUpdate: ASN1.GeneralizedTime,
|
||||
nextUpdate: ASN1.GeneralizedTime?,
|
||||
extensions: [Certificate.Extension]?) {
|
||||
self.certID = certID
|
||||
self.certStatus = certStatus
|
||||
self.thisUpdate = thisUpdate
|
||||
self.nextUpdate = nextUpdate
|
||||
self.extensions = extensions
|
||||
}
|
||||
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let certID = try OCSPCertID(asn1Encoded: &nodes)
|
||||
let certStatus = try OCSPCertStatus(asn1Encoded: &nodes)
|
||||
let thisUpdate = try ASN1.GeneralizedTime(asn1Encoded: &nodes)
|
||||
let nextUpdate = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
|
||||
try ASN1.GeneralizedTime(asn1Encoded: node)
|
||||
}
|
||||
let extensions = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
|
||||
try ASN1.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node)
|
||||
}
|
||||
|
||||
return .init(certID: certID,
|
||||
certStatus: certStatus,
|
||||
thisUpdate: thisUpdate,
|
||||
nextUpdate: nextUpdate,
|
||||
extensions: extensions)
|
||||
}
|
||||
}
|
||||
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.certID)
|
||||
try coder.serialize(self.certStatus)
|
||||
try coder.serialize(self.thisUpdate)
|
||||
if let nextUpdate = self.nextUpdate {
|
||||
try coder.serialize(nextUpdate, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
|
||||
}
|
||||
if let extensions = self.extensions {
|
||||
try coder.serialize(explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific) { coder in
|
||||
try coder.appendConstructedNode(identifier: .sequence) { coder in
|
||||
for ext in extensions {
|
||||
try coder.serialize(ext)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
extension RelativeDistinguishedName {
|
||||
/// A single attribute of a ``RelativeDistinguishedName``.
|
||||
///
|
||||
/// A ``RelativeDistinguishedName`` is made up of one or more attributes that represent the same
|
||||
/// node in the hierarchical ``DistinguishedName`` representation. In almost all cases there is
|
||||
/// only one ``Attribute`` in a given ``RelativeDistinguishedName``.
|
||||
///
|
||||
/// These attributes are a key-value type, with the type of the node being identified by
|
||||
/// ``type`` and the value being stored in ``value``. In the vast majority of cases the ``value``
|
||||
/// of the node will be an `ASN1PrintableString` or `ASN1UTF8String`, but the value can only
|
||||
/// be derived by inspection.
|
||||
public struct Attribute {
|
||||
/// The type of this attribute.
|
||||
///
|
||||
/// Common types can be found in `ASN1ObjectIdentifier.RDNAttributeType`.
|
||||
public var type: ASN1.ASN1ObjectIdentifier
|
||||
|
||||
// TODO(cory): This feels gross, we should have a better representation that reduces the runtime type checking and recomputation.
|
||||
// These are all strings in other places, but we can't necessarily guarantee that. Probably want a computed property.
|
||||
/// The value of this attribute.
|
||||
public var value: ASN1.ASN1Any
|
||||
|
||||
/// Create a new attribute from a given type and value.
|
||||
///
|
||||
/// - Parameter type: The type of the attribute.
|
||||
/// - Parameter value: The value of the attribute, wrapped in an `ASN1Any`.
|
||||
@inlinable
|
||||
public init(type: ASN1.ASN1ObjectIdentifier, value: ASN1.ASN1Any) {
|
||||
self.type = type
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension RelativeDistinguishedName.Attribute: Hashable { }
|
||||
|
||||
extension RelativeDistinguishedName.Attribute: Sendable { }
|
||||
|
||||
extension RelativeDistinguishedName.Attribute: CustomStringConvertible {
|
||||
@inlinable
|
||||
public var description: String {
|
||||
// TODO(cory): Relevant citation is probably https://www.rfc-editor.org/rfc/rfc4514
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension RelativeDistinguishedName.Attribute: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
public static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let type = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
|
||||
let value = try ASN1.ASN1Any(asn1Encoded: &nodes)
|
||||
|
||||
return .init(type: type, value: value)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.type)
|
||||
try coder.serialize(self.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension RelativeDistinguishedName.Attribute {
|
||||
/// A helper constructor to construct a ``RelativeDistinguishedName/Attribute`` whose
|
||||
/// value is an `ASN1UTF8String`.
|
||||
///
|
||||
/// - Parameter type: The type of the attribute.
|
||||
/// - Parameter utf8String: The value of the attribute.
|
||||
@inlinable
|
||||
public init(type: ASN1.ASN1ObjectIdentifier, utf8String: String) throws {
|
||||
self.type = type
|
||||
self.value = try ASN1.ASN1Any(erasing: ASN1.ASN1UTF8String(utf8String))
|
||||
}
|
||||
|
||||
/// A helper constructor to construct a ``RelativeDistinguishedName/Attribute`` whose
|
||||
/// value is an `ASN1PrintableString`.
|
||||
///
|
||||
/// - Parameter type: The type of the attribute.
|
||||
/// - Parameter printableString: The value of the attribute.
|
||||
@inlinable
|
||||
public init(type: ASN1.ASN1ObjectIdentifier, printableString: String) throws {
|
||||
self.type = type
|
||||
self.value = try ASN1.ASN1Any(erasing: ASN1.ASN1PrintableString(printableString))
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1ObjectIdentifier {
|
||||
/// Common object identifiers used within ``RelativeDistinguishedName/Attribute``s.
|
||||
public enum RDNAttributeType {
|
||||
/// The 'countryName' attribute type contains a two-letter
|
||||
/// ISO 3166 country code.
|
||||
public static let countryName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 6]
|
||||
|
||||
/// The 'commonName' attribute type contains names of an
|
||||
/// object.
|
||||
public static let commonName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 3]
|
||||
|
||||
/// The 'localityName' attribute type contains names of a
|
||||
/// locality or place, such as a city, county, or other geographic
|
||||
/// region.
|
||||
public static let localityName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 7]
|
||||
|
||||
/// The 'stateOrProvinceName' attribute type contains the
|
||||
/// full names of states or provinces.
|
||||
public static let stateOrProvinceName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 8]
|
||||
|
||||
/// The 'organizationName' attribute type contains the
|
||||
/// names of an organization.
|
||||
public static let organizationName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 10]
|
||||
|
||||
/// The 'organizationalUnitName' attribute type contains
|
||||
/// the names of an organizational unit.
|
||||
public static let organizationalUnitName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 11]
|
||||
|
||||
/// The 'streetAddress' attribute type contains site
|
||||
/// information from a postal address (i.e., the street name, place,
|
||||
/// avenue, and the house number).
|
||||
public static let streetAddress: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 9]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
/// A ``RelativeDistinguishedName`` is a collection of elements at a single level of a hierarchical
|
||||
/// ``DistinguishedName``.
|
||||
///
|
||||
/// Distinguished names are a remnant of the X.500 directory system. In that system,
|
||||
/// distinguished names were the primary key, enabling the identification of a specific entity
|
||||
/// within the directory.
|
||||
///
|
||||
/// ``RelativeDistinguishedName``s are the elements of a ``DistinguishedName``. Each ``RelativeDistinguishedName``
|
||||
/// contains one or more ``RelativeDistinguishedName/Attribute`` which are considered equivalent: that is, they
|
||||
/// are each a representation of the same piece of information.
|
||||
///
|
||||
/// ``RelativeDistinguishedName``s are organised into a hierarchy in a ``DistinguishedName``, in order from least
|
||||
/// to most specific. In almost all current use-cases a ``RelativeDistinguishedName`` will contain only a single
|
||||
/// ``Attribute``.
|
||||
///
|
||||
/// Note that ``RelativeDistinguishedName`` does not have a stable ordering of its elements. Inserting an element
|
||||
/// at index `i` does not guarantee it will remain at that location. As a result, ``RelativeDistinguishedName`` is
|
||||
/// not a `MutableCollection`.
|
||||
public struct RelativeDistinguishedName {
|
||||
// TODO: Should we special-case this to the circumstance where we have only one attribute?
|
||||
@usableFromInline
|
||||
var attributes: [Attribute] {
|
||||
didSet {
|
||||
Self._sortElements(&self.attributes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct a ``RelativeDistinguishedName`` from a sequence of ``Attribute``.
|
||||
///
|
||||
/// - Parameter attributes: The sequence of ``Attribute``s that make up the ``DistinguishedName``.
|
||||
@inlinable
|
||||
public init<AttributeSequence: Sequence>(_ attributes: AttributeSequence) throws where AttributeSequence.Element == RelativeDistinguishedName.Attribute {
|
||||
// TODO(cory:) We need to validate this, an attribute cannot be repeated.
|
||||
self.attributes = Array(attributes)
|
||||
Self._sortElements(&self.attributes)
|
||||
}
|
||||
|
||||
/// Create an empty ``RelativeDistinguishedName``.
|
||||
@inlinable
|
||||
public init() {
|
||||
self.attributes = []
|
||||
}
|
||||
}
|
||||
|
||||
extension RelativeDistinguishedName: Hashable { }
|
||||
|
||||
extension RelativeDistinguishedName: Sendable { }
|
||||
|
||||
extension RelativeDistinguishedName: RandomAccessCollection {
|
||||
@inlinable
|
||||
public var startIndex: Int {
|
||||
self.attributes.startIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public var endIndex: Int {
|
||||
self.attributes.endIndex
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public subscript(position: Int) -> RelativeDistinguishedName.Attribute {
|
||||
get {
|
||||
self.attributes[position]
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a new ``Attribute`` into this ``RelativeDistinguishedName``.
|
||||
///
|
||||
/// - Parameter attribute: The ``Attribute`` to insert.
|
||||
@inlinable
|
||||
public mutating func insert(_ attribute: RelativeDistinguishedName.Attribute) {
|
||||
self.attributes.append(attribute)
|
||||
}
|
||||
|
||||
/// Insert a `Collection` of ``Attribute``s into this ``RelativeDistinguishedName``.
|
||||
///
|
||||
/// Note that the order of `attributes` will not be preserved.
|
||||
///
|
||||
/// - Parameter attributes: The ``Attribute``s to be inserted.
|
||||
@inlinable
|
||||
public mutating func insert<Attributes: Collection>(contentsOf attributes: Attributes) where Attributes.Element == RelativeDistinguishedName.Attribute {
|
||||
self.attributes.append(contentsOf: attributes)
|
||||
}
|
||||
}
|
||||
|
||||
extension RelativeDistinguishedName: CustomStringConvertible {
|
||||
@inlinable
|
||||
public var description: String {
|
||||
// TODO(cory): Relevant citation is probably https://www.rfc-editor.org/rfc/rfc4514
|
||||
return "TODO"
|
||||
}
|
||||
}
|
||||
|
||||
extension RelativeDistinguishedName: ASN1ImplicitlyTaggable {
|
||||
@inlinable
|
||||
public static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.set
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.set(rootNode, identifier: identifier) { nodes in
|
||||
// TODO: We need to validate that these are lexicographically sorted. Perhaps ASN1.set should do it?
|
||||
var elements = Array<RelativeDistinguishedName.Attribute>()
|
||||
|
||||
while let node = nodes.next() {
|
||||
try elements.append(.init(asn1Encoded: node))
|
||||
}
|
||||
|
||||
return try RelativeDistinguishedName(elements)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { rootCoder in
|
||||
for element in self.attributes {
|
||||
try element.serialize(into: &rootCoder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func _sortElements(_ elements: inout [RelativeDistinguishedName.Attribute]) {
|
||||
// We keep the elements sorted at all times. This is dumb, but we assume that these objects get
|
||||
// mutated infrequently.
|
||||
// This is weird. We need to individually serialize each element, then lexicographically compare
|
||||
// them and then write them out. We could do this in place but for now let's not worry about it.
|
||||
try! elements.sort { lhs, rhs in
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(lhs)
|
||||
let lhsBytes = serializer.serializedBytes
|
||||
|
||||
serializer = ASN1.Serializer()
|
||||
try serializer.serialize(rhs)
|
||||
let rhsBytes = serializer.serializedBytes
|
||||
|
||||
// Compare up to the common length lexicographically.
|
||||
for (leftByte, rightByte) in zip(lhsBytes, rhsBytes) {
|
||||
if leftByte < rightByte {
|
||||
// true means left comes before right
|
||||
return true
|
||||
} else if rightByte < leftByte {
|
||||
// Right comes after left
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// We got to the end of the shorter element, so all current elements are equal.
|
||||
// If lhs is shorter, it comes earlier, _unless_ all of rhs's trailing elements are zero.
|
||||
let trailing = rhsBytes.dropFirst(lhsBytes.count)
|
||||
if trailing.count == 0 || trailing.allSatisfy({ $0 == 0}) {
|
||||
// Must return false when the two elements are equal.
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
@preconcurrency import Crypto
|
||||
@preconcurrency import _CryptoExtras
|
||||
|
||||
extension Certificate {
|
||||
/// An abstract representation of the cryptographic signature on a certificate.
|
||||
///
|
||||
/// Certificates may have a wide range of signature types. This type provides a runtime
|
||||
/// abstraction across these types. It ensures that we understand the algorithm used to
|
||||
/// sign the certificate, and enables us to provide verification logic, without forcing
|
||||
/// users to wrestle with the wide variety of runtime types that may represent a
|
||||
/// signature.
|
||||
///
|
||||
/// This type is almost entirely opaque. It can be validated by way of
|
||||
/// ``Certificate/PublicKey-swift.struct/isValidSignature(_:for:)``, and it
|
||||
/// can be generated by ``Certificate/PrivateKey``s automatically when
|
||||
/// used by ``Certificate/init(version:serialNumber:publicKey:notValidBefore:notValidAfter:issuer:subject:signatureAlgorithm:extensions:issuerPrivateKey:)``.
|
||||
/// Otherwise, this type has essentially no behaviours.
|
||||
public struct Signature {
|
||||
@usableFromInline
|
||||
var backing: BackingSignature
|
||||
|
||||
@inlinable
|
||||
internal init(backing: BackingSignature) {
|
||||
self.backing = backing
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(signatureAlgorithm: SignatureAlgorithm, signatureBytes: ASN1.ASN1BitString) throws {
|
||||
switch signatureAlgorithm {
|
||||
case .ecdsaWithSHA256:
|
||||
let signature = try P256.Signing.ECDSASignature(derRepresentation: signatureBytes.bytes)
|
||||
self.backing = .p256(signature)
|
||||
case .ecdsaWithSHA384:
|
||||
let signature = try P384.Signing.ECDSASignature(derRepresentation: signatureBytes.bytes)
|
||||
self.backing = .p384(signature)
|
||||
case .ecdsaWithSHA512:
|
||||
let signature = try P521.Signing.ECDSASignature(derRepresentation: signatureBytes.bytes)
|
||||
self.backing = .p521(signature)
|
||||
case .sha1WithRSAEncryption:
|
||||
// TODO: We need to validate the signature is actually reasonable here.
|
||||
let signature = _RSA.Signing.RSASignature(rawRepresentation: signatureBytes.bytes)
|
||||
self.backing = .rsa(signature)
|
||||
case .sha256WithRSAEncryption:
|
||||
// TODO: We need to validate the signature is actually reasonable here.
|
||||
let signature = _RSA.Signing.RSASignature(rawRepresentation: signatureBytes.bytes)
|
||||
self.backing = .rsa(signature)
|
||||
case .sha384WithRSAEncryption:
|
||||
// TODO: We need to validate the signature is actually reasonable here.
|
||||
let signature = _RSA.Signing.RSASignature(rawRepresentation: signatureBytes.bytes)
|
||||
self.backing = .rsa(signature)
|
||||
case .sha512WithRSAEncryption:
|
||||
// TODO: We need to validate the signature is actually reasonable here.
|
||||
let signature = _RSA.Signing.RSASignature(rawRepresentation: signatureBytes.bytes)
|
||||
self.backing = .rsa(signature)
|
||||
default:
|
||||
throw CertificateError.unsupportedSignatureAlgorithm(reason: "\(signatureAlgorithm)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Signature: Hashable { }
|
||||
|
||||
extension Certificate.Signature: Sendable { }
|
||||
|
||||
extension Certificate.Signature: CustomStringConvertible {
|
||||
public var description: String {
|
||||
return String(describing: self.backing)
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.Signature {
|
||||
@usableFromInline
|
||||
enum BackingSignature: Hashable, Sendable {
|
||||
case p256(Crypto.P256.Signing.ECDSASignature)
|
||||
case p384(Crypto.P384.Signing.ECDSASignature)
|
||||
case p521(Crypto.P521.Signing.ECDSASignature)
|
||||
case rsa(_CryptoExtras._RSA.Signing.RSASignature)
|
||||
|
||||
@inlinable
|
||||
static func ==(lhs: BackingSignature, rhs: BackingSignature) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.p256(let l), .p256(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.p384(let l), .p384(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.p521(let l), .p521(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
case (.rsa(let l), .rsa(let r)):
|
||||
return l.rawRepresentation == r.rawRepresentation
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func hash(into hasher: inout Hasher) {
|
||||
switch self {
|
||||
case .p256(let digest):
|
||||
hasher.combine(0)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .p384(let digest):
|
||||
hasher.combine(1)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .p521(let digest):
|
||||
hasher.combine(2)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
case .rsa(let digest):
|
||||
hasher.combine(3)
|
||||
hasher.combine(digest.rawRepresentation)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ASN1.ASN1BitString {
|
||||
@inlinable
|
||||
init(_ signature: Certificate.Signature) {
|
||||
switch signature.backing {
|
||||
case .p256(let sig):
|
||||
self = ASN1.ASN1BitString(bytes: ArraySlice(sig.derRepresentation))
|
||||
case .p384(let sig):
|
||||
self = ASN1.ASN1BitString(bytes: ArraySlice(sig.derRepresentation))
|
||||
case .p521(let sig):
|
||||
self = ASN1.ASN1BitString(bytes: ArraySlice(sig.derRepresentation))
|
||||
case .rsa(let sig):
|
||||
self = ASN1.ASN1BitString(bytes: ArraySlice(sig.rawRepresentation))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Certificate {
|
||||
/// A representation of a kind of signature algorithm.
|
||||
///
|
||||
/// X.509 certificates support a wide range of signature algorithms. This type
|
||||
/// identifies the algorithm, independently of the signature itself.
|
||||
///
|
||||
/// This type represents an unbounded enumeration. There are potentially infinite
|
||||
/// signature algorithms. Users are able to create representations of the signature
|
||||
/// algorithms this library supports by using static fields on this type.
|
||||
public struct SignatureAlgorithm {
|
||||
@usableFromInline
|
||||
var _algorithmIdentifier: AlgorithmIdentifier
|
||||
|
||||
@inlinable
|
||||
init(algorithmIdentifier: AlgorithmIdentifier) {
|
||||
switch algorithmIdentifier {
|
||||
// Per RFC 4055 § 5, we need to accept the RSA parameters field being
|
||||
// absent, but we must _produce_ the one with an explicit NULL. So we
|
||||
// normalise the signature algorithm here.
|
||||
case .sha1WithRSAEncryptionUsingNil:
|
||||
self._algorithmIdentifier = .sha1WithRSAEncryption
|
||||
case .sha256WithRSAEncryptionUsingNil:
|
||||
self._algorithmIdentifier = .sha256WithRSAEncryption
|
||||
case .sha384WithRSAEncryptionUsingNil:
|
||||
self._algorithmIdentifier = .sha384WithRSAEncryption
|
||||
case .sha512WithRSAEncryptionUsingNil:
|
||||
self._algorithmIdentifier = .sha512WithRSAEncryption
|
||||
case let identifier:
|
||||
self._algorithmIdentifier = identifier
|
||||
}
|
||||
}
|
||||
|
||||
/// This value represents an ECDSA signature using SHA256 and P256.
|
||||
public static let ecdsaWithSHA256 = Self(algorithmIdentifier: .ecdsaWithSHA256)
|
||||
|
||||
/// This value represents an ECDSA signature using SHA384 and P384.
|
||||
public static let ecdsaWithSHA384 = Self(algorithmIdentifier: .ecdsaWithSHA384)
|
||||
|
||||
/// This value represents an ECDSA signature using SHA512 and P521.
|
||||
public static let ecdsaWithSHA512 = Self(algorithmIdentifier: .ecdsaWithSHA512)
|
||||
|
||||
/// This value represents an RSA signature with PKCS1v1.5 padding and SHA1 as the hash function.
|
||||
public static let sha1WithRSAEncryption = Self(algorithmIdentifier: .sha1WithRSAEncryption)
|
||||
|
||||
/// This value represents an RSA signature with PKCS1v1.5 padding and SHA256 as the hash function.
|
||||
public static let sha256WithRSAEncryption = Self(algorithmIdentifier: .sha256WithRSAEncryption)
|
||||
|
||||
/// This value represents an RSA signature with PKCS1v1.5 padding and SHA384 as the hash function.
|
||||
public static let sha384WithRSAEncryption = Self(algorithmIdentifier: .sha384WithRSAEncryption)
|
||||
|
||||
/// This value represents an RSA signature with PKCS1v1.5 padding and SHA521 as the hash function.
|
||||
public static let sha512WithRSAEncryption = Self(algorithmIdentifier: .sha512WithRSAEncryption)
|
||||
}
|
||||
}
|
||||
|
||||
extension Certificate.SignatureAlgorithm: Hashable { }
|
||||
|
||||
extension Certificate.SignatureAlgorithm: Sendable { }
|
||||
|
||||
extension Certificate.SignatureAlgorithm: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .ecdsaWithSHA256:
|
||||
return "SignatureAlgorithm.ecdsaWithSHA256"
|
||||
case .ecdsaWithSHA384:
|
||||
return "SignatureAlgorithm.ecdsaWithSHA384"
|
||||
case .ecdsaWithSHA512:
|
||||
return "SignatureAlgorithm.ecdsaWithSHA512"
|
||||
case .sha1WithRSAEncryption:
|
||||
return "SignatureAlgorithm.sha1WithRSAEncryption"
|
||||
case .sha256WithRSAEncryption:
|
||||
return "SignatureAlgorithm.sha256WithRSAEncryption"
|
||||
case .sha384WithRSAEncryption:
|
||||
return "SignatureAlgorithm.sha384WithRSAEncryption"
|
||||
case .sha512WithRSAEncryption:
|
||||
return "SignatureAlgorithm.sha512WithRSAEncryption"
|
||||
default:
|
||||
return "SignatureAlgorithm(\(self._algorithmIdentifier))"
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
extension AlgorithmIdentifier {
|
||||
@inlinable
|
||||
init(_ signatureAlgorithm: Certificate.SignatureAlgorithm) {
|
||||
self = signatureAlgorithm._algorithmIdentifier
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
@usableFromInline
|
||||
struct AlgorithmIdentifier: ASN1ImplicitlyTaggable, Hashable, Sendable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var algorithm: ASN1.ASN1ObjectIdentifier
|
||||
|
||||
@usableFromInline
|
||||
var parameters: ASN1.ASN1Any?
|
||||
|
||||
@inlinable
|
||||
init(algorithm: ASN1.ASN1ObjectIdentifier, parameters: ASN1.ASN1Any?) {
|
||||
self.algorithm = algorithm
|
||||
self.parameters = parameters
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
// The AlgorithmIdentifier block looks like this.
|
||||
//
|
||||
// AlgorithmIdentifier ::= SEQUENCE {
|
||||
// algorithm OBJECT IDENTIFIER,
|
||||
// parameters ANY DEFINED BY algorithm OPTIONAL
|
||||
// }
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let algorithmOID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes)
|
||||
|
||||
let parameters = nodes.next().map { ASN1.ASN1Any(asn1Encoded: $0) }
|
||||
|
||||
return .init(algorithm: algorithmOID, parameters: parameters)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.algorithm)
|
||||
if let parameters = self.parameters {
|
||||
try coder.serialize(parameters)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Algorithm Identifier Statics
|
||||
extension AlgorithmIdentifier {
|
||||
@usableFromInline
|
||||
static let p256PublicKey = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp256r1))
|
||||
|
||||
@usableFromInline
|
||||
static let p384PublicKey = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp384r1))
|
||||
|
||||
@usableFromInline
|
||||
static let p521PublicKey = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
|
||||
parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp521r1))
|
||||
|
||||
@usableFromInline
|
||||
static let ecdsaWithSHA256 = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.ecdsaWithSHA256,
|
||||
parameters: nil)
|
||||
|
||||
@usableFromInline
|
||||
static let ecdsaWithSHA384 = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.ecdsaWithSHA384,
|
||||
parameters: nil)
|
||||
|
||||
@usableFromInline
|
||||
static let ecdsaWithSHA512 = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.ecdsaWithSHA512,
|
||||
parameters: nil)
|
||||
|
||||
// MARK: For the RSA signature types, explicit ASN.1 NULL is equivalent to a missing parameters field.
|
||||
// We include both here, and the usage sites need to handle the equivalent.
|
||||
@usableFromInline
|
||||
static let sha1WithRSAEncryption = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.sha1WithRSAEncryption, parameters: try! ASN1.ASN1Any(erasing: ASN1.ASN1Null())
|
||||
)
|
||||
|
||||
@usableFromInline
|
||||
static let sha1WithRSAEncryptionUsingNil = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.sha1WithRSAEncryption, parameters: nil
|
||||
)
|
||||
|
||||
@usableFromInline
|
||||
static let sha256WithRSAEncryption = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.sha256WithRSAEncryption, parameters: try! ASN1.ASN1Any(erasing: ASN1.ASN1Null())
|
||||
)
|
||||
|
||||
@usableFromInline
|
||||
static let sha256WithRSAEncryptionUsingNil = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.sha256WithRSAEncryption, parameters: nil
|
||||
)
|
||||
|
||||
@usableFromInline
|
||||
static let sha384WithRSAEncryption = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.sha384WithRSAEncryption, parameters: try! ASN1.ASN1Any(erasing: ASN1.ASN1Null())
|
||||
)
|
||||
|
||||
@usableFromInline
|
||||
static let sha384WithRSAEncryptionUsingNil = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.sha384WithRSAEncryption, parameters: nil
|
||||
)
|
||||
|
||||
@usableFromInline
|
||||
static let sha512WithRSAEncryption = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.sha512WithRSAEncryption, parameters: try! ASN1.ASN1Any(erasing: ASN1.ASN1Null())
|
||||
)
|
||||
|
||||
@usableFromInline
|
||||
static let sha512WithRSAEncryptionUsingNil = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.sha512WithRSAEncryption, parameters: nil
|
||||
)
|
||||
|
||||
@usableFromInline
|
||||
static let rsaPublicKey = AlgorithmIdentifier(
|
||||
algorithm: .AlgorithmIdentifier.rsaEncryption, parameters: try! ASN1.ASN1Any(erasing: ASN1.ASN1Null())
|
||||
)
|
||||
}
|
||||
|
||||
extension AlgorithmIdentifier: CustomStringConvertible {
|
||||
@usableFromInline
|
||||
var description: String {
|
||||
switch self {
|
||||
case .p256PublicKey:
|
||||
return "p256PublicKey"
|
||||
case .p384PublicKey:
|
||||
return "p384PublicKey"
|
||||
case .p521PublicKey:
|
||||
return "p521PublicKey"
|
||||
case .ecdsaWithSHA256:
|
||||
return "ecdsaWithSHA256"
|
||||
case .ecdsaWithSHA384:
|
||||
return "ecdsaWithSHA384"
|
||||
case .ecdsaWithSHA512:
|
||||
return "ecdsaWithSHA512"
|
||||
case .sha256WithRSAEncryption, .sha256WithRSAEncryptionUsingNil:
|
||||
return "sha256WithRSAEncryption"
|
||||
case .sha384WithRSAEncryption, .sha384WithRSAEncryptionUsingNil:
|
||||
return "sha384WithRSAEncryption"
|
||||
case .p521PublicKey, .sha512WithRSAEncryptionUsingNil:
|
||||
return "sha512WithRSAEncryption"
|
||||
default:
|
||||
return "AlgorithmIdentifier(\(self.algorithm) - \(String(describing: self.parameters)))"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(cory): We need representations for RSA-PSS. See RFC 4055 for descriptions of the ASN.1.
|
||||
// Relevant note: the PKCS1v1.5 versions need to treat having no parameters and a NULL parameters as identical. This is probably general,
|
||||
// so we may need a custom equatable implementation there.
|
||||
|
||||
extension ASN1.ASN1ObjectIdentifier.AlgorithmIdentifier {
|
||||
static let ecdsaWithSHA256: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10045, 4, 3, 2]
|
||||
|
||||
static let ecdsaWithSHA384: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10045, 4, 3, 3]
|
||||
|
||||
static let ecdsaWithSHA512: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10045, 4, 3, 4]
|
||||
|
||||
static let sha1WithRSAEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 113549, 1, 1, 5]
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
@usableFromInline
|
||||
struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable, Hashable, Sendable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var algorithmIdentifier: AlgorithmIdentifier
|
||||
|
||||
@usableFromInline
|
||||
var key: ASN1.ASN1BitString
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
// The SPKI block looks like this:
|
||||
//
|
||||
// SubjectPublicKeyInfo ::= SEQUENCE {
|
||||
// algorithm AlgorithmIdentifier,
|
||||
// subjectPublicKey BIT STRING
|
||||
// }
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let algorithmIdentifier = try AlgorithmIdentifier(asn1Encoded: &nodes)
|
||||
let key = try ASN1.ASN1BitString(asn1Encoded: &nodes)
|
||||
|
||||
return SubjectPublicKeyInfo(algorithmIdentifier: algorithmIdentifier, key: key)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(algorithmIdentifier: AlgorithmIdentifier, key: ASN1.ASN1BitString) {
|
||||
self.algorithmIdentifier = algorithmIdentifier
|
||||
self.key = key
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(algorithmIdentifier: AlgorithmIdentifier, key: [UInt8]) {
|
||||
self.algorithmIdentifier = algorithmIdentifier
|
||||
self.key = ASN1.ASN1BitString(bytes: key[...])
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.algorithmIdentifier)
|
||||
try coder.serialize(self.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
// TBSCertificate ::= SEQUENCE {
|
||||
// version [0] Version DEFAULT v1,
|
||||
// serialNumber CertificateSerialNumber,
|
||||
// signature AlgorithmIdentifier,
|
||||
// issuer Name,
|
||||
// validity Validity,
|
||||
// subject Name,
|
||||
// subjectPublicKeyInfo SubjectPublicKeyInfo,
|
||||
// issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
|
||||
// -- If present, version MUST be v2 or v3
|
||||
// subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
|
||||
// -- If present, version MUST be v2 or v3
|
||||
// extensions [3] Extensions OPTIONAL
|
||||
// -- If present, version MUST be v3 -- }
|
||||
//
|
||||
// Version ::= INTEGER { v1(0), v2(1), v3(2) }
|
||||
//
|
||||
// CertificateSerialNumber ::= INTEGER
|
||||
//
|
||||
// UniqueIdentifier ::= BIT STRING
|
||||
//
|
||||
// Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
|
||||
@usableFromInline
|
||||
typealias UniqueIdentifier = ASN1.ASN1BitString
|
||||
|
||||
@usableFromInline
|
||||
struct TBSCertificate: ASN1ImplicitlyTaggable, Hashable, Sendable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var version: Certificate.Version
|
||||
|
||||
@usableFromInline
|
||||
var serialNumber: Certificate.SerialNumber
|
||||
|
||||
@usableFromInline
|
||||
var signature: Certificate.SignatureAlgorithm
|
||||
|
||||
@usableFromInline
|
||||
var issuer: DistinguishedName
|
||||
|
||||
@usableFromInline
|
||||
var validity: Validity
|
||||
|
||||
@usableFromInline
|
||||
var subject: DistinguishedName
|
||||
|
||||
@usableFromInline
|
||||
var publicKey: Certificate.PublicKey
|
||||
|
||||
@usableFromInline
|
||||
var issuerUniqueID: UniqueIdentifier?
|
||||
|
||||
@usableFromInline
|
||||
var subjectUniqueID: UniqueIdentifier?
|
||||
|
||||
@usableFromInline
|
||||
var extensions: Certificate.Extensions
|
||||
|
||||
@inlinable
|
||||
internal init(
|
||||
version: Certificate.Version,
|
||||
serialNumber: Certificate.SerialNumber,
|
||||
signature: Certificate.SignatureAlgorithm,
|
||||
issuer: DistinguishedName,
|
||||
validity: Validity,
|
||||
subject: DistinguishedName,
|
||||
publicKey: Certificate.PublicKey,
|
||||
issuerUniqueID: UniqueIdentifier? = nil,
|
||||
subjectUniqueID: UniqueIdentifier? = nil,
|
||||
extensions: Certificate.Extensions
|
||||
) {
|
||||
self.version = version
|
||||
self.serialNumber = serialNumber
|
||||
self.signature = signature
|
||||
self.issuer = issuer
|
||||
self.validity = validity
|
||||
self.subject = subject
|
||||
self.publicKey = publicKey
|
||||
self.issuerUniqueID = issuerUniqueID
|
||||
self.subjectUniqueID = subjectUniqueID
|
||||
self.extensions = extensions
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let version = try ASN1.decodeDefaultExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific, defaultValue: Int(0))
|
||||
guard (0...2).contains(version) else {
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
|
||||
let serialNumber = try ArraySlice<UInt8>(asn1Encoded: &nodes)
|
||||
let signature = try AlgorithmIdentifier(asn1Encoded: &nodes)
|
||||
let issuer = try DistinguishedName(asn1Encoded: &nodes)
|
||||
let validity = try Validity(asn1Encoded: &nodes)
|
||||
let subject = try DistinguishedName(asn1Encoded: &nodes)
|
||||
let subjectPublicKeyInfo = try SubjectPublicKeyInfo(asn1Encoded: &nodes)
|
||||
let issuerUniqueID = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) {
|
||||
try UniqueIdentifier(asn1Encoded: $0)
|
||||
}
|
||||
let subjectUniqueID = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 2, tagClass: .contextSpecific) {
|
||||
try UniqueIdentifier(asn1Encoded: $0)
|
||||
}
|
||||
let extensions = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 3, tagClass: .contextSpecific) {
|
||||
try ASN1.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: $0)
|
||||
}
|
||||
|
||||
return TBSCertificate(
|
||||
version: Certificate.Version(rawValue: version),
|
||||
serialNumber: Certificate.SerialNumber(bytes: serialNumber),
|
||||
signature: Certificate.SignatureAlgorithm(algorithmIdentifier: signature),
|
||||
issuer: issuer,
|
||||
validity: validity,
|
||||
subject: subject,
|
||||
publicKey: try Certificate.PublicKey(spki: subjectPublicKeyInfo),
|
||||
issuerUniqueID: issuerUniqueID,
|
||||
subjectUniqueID: subjectUniqueID,
|
||||
extensions: Certificate.Extensions(extensions ?? [])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
if self.version != .v1 {
|
||||
try coder.serialize(self.version.rawValue, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
|
||||
}
|
||||
try coder.serialize(self.serialNumber.bytes)
|
||||
try coder.serialize(AlgorithmIdentifier(self.signature))
|
||||
try coder.serialize(self.issuer)
|
||||
try coder.serialize(self.validity)
|
||||
try coder.serialize(self.subject)
|
||||
try coder.serialize(SubjectPublicKeyInfo(self.publicKey))
|
||||
if let issuerUniqueID = self.issuerUniqueID {
|
||||
try coder.serialize(issuerUniqueID, explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific)
|
||||
}
|
||||
if let subjectUniqueID = self.subjectUniqueID {
|
||||
try coder.serialize(subjectUniqueID, explicitlyTaggedWithTagNumber: 2, tagClass: .contextSpecific)
|
||||
}
|
||||
if self.extensions.count > 0 {
|
||||
try coder.serialize(explicitlyTaggedWithTagNumber: 3, tagClass: .contextSpecific) { coder in
|
||||
try coder.serializeSequenceOf(extensions)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
import SwiftASN1
|
||||
|
||||
// Time ::= CHOICE {
|
||||
// utcTime UTCTime,
|
||||
// generalTime GeneralizedTime }
|
||||
@usableFromInline
|
||||
enum Time: ASN1Parseable, ASN1Serializable, Hashable, Sendable {
|
||||
case utcTime(ASN1.UTCTime)
|
||||
case generalTime(ASN1.GeneralizedTime)
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node) throws {
|
||||
switch rootNode.identifier {
|
||||
case ASN1.GeneralizedTime.defaultIdentifier:
|
||||
self = .generalTime(try ASN1.GeneralizedTime(asn1Encoded: rootNode))
|
||||
case ASN1.UTCTime.defaultIdentifier:
|
||||
self = .utcTime(try ASN1.UTCTime(asn1Encoded: rootNode))
|
||||
default:
|
||||
throw ASN1Error.invalidASN1Object
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer) throws {
|
||||
switch self {
|
||||
case .utcTime(let utcTime):
|
||||
try coder.serialize(utcTime)
|
||||
case .generalTime(let generalizedTime):
|
||||
try coder.serialize(generalizedTime)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
static func makeTime(from date: Date) throws -> Time {
|
||||
let components = gregorianCalendar.dateComponents(in: utcTimeZone, from: date)
|
||||
|
||||
// The rule is if the year is outside the range 1950-2049 inclusive, we should encode
|
||||
// it as a generalized time. Otherwise, use a UTCTime.
|
||||
// These force-unwraps are safe: all the components are returned by the above call.
|
||||
if (1950..<2050).contains(components.year!) {
|
||||
let utcTime = try ASN1.UTCTime(
|
||||
year: components.year!,
|
||||
month: components.month!,
|
||||
day: components.day!,
|
||||
hours: components.hour!,
|
||||
minutes: components.minute!,
|
||||
seconds: components.second!
|
||||
)
|
||||
|
||||
return .utcTime(utcTime)
|
||||
} else {
|
||||
let generalizedTime = try ASN1.GeneralizedTime(
|
||||
year: components.year!,
|
||||
month: components.month!,
|
||||
day: components.day!,
|
||||
hours: components.hour!,
|
||||
minutes: components.minute!,
|
||||
seconds: components.second!,
|
||||
fractionalSeconds: 0.0
|
||||
)
|
||||
|
||||
return .generalTime(generalizedTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Date {
|
||||
@inlinable
|
||||
init?(_ time: Time) {
|
||||
let maybeDate: Date?
|
||||
|
||||
switch time {
|
||||
case .utcTime(let utcTime):
|
||||
maybeDate = Date(utcTime)
|
||||
case .generalTime(let generalizedTime):
|
||||
maybeDate = Date(generalizedTime)
|
||||
}
|
||||
|
||||
guard let date = maybeDate else {
|
||||
return nil
|
||||
}
|
||||
|
||||
self = date
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init?(_ utcTime: ASN1.UTCTime) {
|
||||
let components = DateComponents(
|
||||
calendar: gregorianCalendar,
|
||||
timeZone: utcTimeZone,
|
||||
year: utcTime.year,
|
||||
month: utcTime.month,
|
||||
day: utcTime.day,
|
||||
hour: utcTime.hours,
|
||||
minute: utcTime.minutes,
|
||||
second: utcTime.seconds
|
||||
)
|
||||
guard let date = components.date else {
|
||||
return nil
|
||||
}
|
||||
self = date
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init?(_ generalizedTime: ASN1.GeneralizedTime) {
|
||||
let components = DateComponents(
|
||||
calendar: gregorianCalendar,
|
||||
timeZone: utcTimeZone,
|
||||
year: generalizedTime.year,
|
||||
month: generalizedTime.month,
|
||||
day: generalizedTime.day,
|
||||
hour: generalizedTime.hours,
|
||||
minute: generalizedTime.minutes,
|
||||
second: generalizedTime.seconds
|
||||
)
|
||||
guard let date = components.date else {
|
||||
return nil
|
||||
}
|
||||
self = date
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
let gregorianCalendar = Calendar(identifier: .gregorian)
|
||||
|
||||
@usableFromInline
|
||||
let utcTimeZone = TimeZone(identifier: "UTC")!
|
||||
@@ -0,0 +1,55 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SwiftASN1
|
||||
|
||||
// Validity ::= SEQUENCE {
|
||||
// notBefore Time,
|
||||
// notAfter Time }
|
||||
@usableFromInline
|
||||
struct Validity: ASN1ImplicitlyTaggable, Hashable, Sendable {
|
||||
@inlinable
|
||||
static var defaultIdentifier: ASN1.ASN1Identifier {
|
||||
.sequence
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
var notBefore: Time
|
||||
|
||||
@usableFromInline
|
||||
var notAfter: Time
|
||||
|
||||
@inlinable
|
||||
internal init(notBefore: Time, notAfter: Time) {
|
||||
self.notBefore = notBefore
|
||||
self.notAfter = notAfter
|
||||
}
|
||||
|
||||
@inlinable
|
||||
init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in
|
||||
let notBefore = try Time(asn1Encoded: &nodes)
|
||||
let notAfter = try Time(asn1Encoded: &nodes)
|
||||
return Validity(notBefore: notBefore, notAfter: notAfter)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws {
|
||||
try coder.appendConstructedNode(identifier: identifier) { coder in
|
||||
try coder.serialize(self.notBefore)
|
||||
try coder.serialize(self.notAfter)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
import XCTest
|
||||
import SwiftASN1
|
||||
import X509
|
||||
import Crypto
|
||||
|
||||
final class CertificateDERTests: XCTestCase {
|
||||
static let base64EncodedSampleCert = """
|
||||
MIIDsjCCAzigAwIBAgIQDKuq0c7E6XzCZliB0CE49zAKBggqhkjOPQQDAzBhMQsw
|
||||
CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu
|
||||
ZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe
|
||||
Fw0yMDA0MjkxMjM0NTJaFw0zMDA0MTAyMzU5NTlaMFExCzAJBgNVBAYTAlVTMRMw
|
||||
EQYDVQQKEwpBcHBsZSBJbmMuMS0wKwYDVQQDEyRBcHBsZSBQdWJsaWMgRVYgU2Vy
|
||||
dmVyIEVDQyBDQSAxIC0gRzEwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQp+OFa
|
||||
uYdEBJj/FpCG+eDhQmVfhv0DGPzGz40TW8BeWxipYTOa4FLieAYoU+3t2tg9FZKt
|
||||
A4BDTO43YprLZm6zo4IB4DCCAdwwHQYDVR0OBBYEFOCFSH0TptMQGZ9cy2t4JJL4
|
||||
rhuuMB8GA1UdIwQYMBaAFLPbSKT5ocXYrjZBzBFjaWIpvEvGMA4GA1UdDwEB/wQE
|
||||
AwIBhjAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwEgYDVR0TAQH/BAgw
|
||||
BgEB/wIBADA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3Nw
|
||||
LmRpZ2ljZXJ0LmNvbTBCBgNVHR8EOzA5MDegNaAzhjFodHRwOi8vY3JsMy5kaWdp
|
||||
Y2VydC5jb20vRGlnaUNlcnRHbG9iYWxSb290RzMuY3JsMIHcBgNVHSAEgdQwgdEw
|
||||
gcUGCWCGSAGG/WwCATCBtzAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNl
|
||||
cnQuY29tL0NQUzCBigYIKwYBBQUHAgIwfgx8QW55IHVzZSBvZiB0aGlzIENlcnRp
|
||||
ZmljYXRlIGNvbnN0aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFJlbHlpbmcgUGFy
|
||||
dHkgQWdyZWVtZW50IGxvY2F0ZWQgYXQgaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29t
|
||||
L3JwYS11YTAHBgVngQwBATAKBggqhkjOPQQDAwNoADBlAjEAyHLAT/4iBuxi4/NH
|
||||
hZde4PZO8CnG2/A3oGO0Nsjpoe2SV94Hr+JpYHrBzT8hyeKSAjBnRXyRac9sM8KN
|
||||
Fdg3+7LWIiW9sUjtJC6kGmRyGm6vV4oAhEDd9jdk4q+7b5zlid4=
|
||||
"""
|
||||
|
||||
static let base64EncodedRSARootCert = """
|
||||
MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB
|
||||
hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
|
||||
A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV
|
||||
BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5
|
||||
MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT
|
||||
EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR
|
||||
Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh
|
||||
dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR
|
||||
6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X
|
||||
pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC
|
||||
9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV
|
||||
/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf
|
||||
Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z
|
||||
+pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w
|
||||
qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah
|
||||
SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC
|
||||
u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf
|
||||
Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq
|
||||
crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E
|
||||
FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB
|
||||
/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl
|
||||
wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM
|
||||
4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV
|
||||
2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna
|
||||
FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ
|
||||
CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK
|
||||
boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke
|
||||
jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL
|
||||
S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb
|
||||
QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl
|
||||
0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB
|
||||
NVOFBkpdn627G190
|
||||
"""
|
||||
|
||||
/// A Safari codesign chain
|
||||
static let codesignCerts = [
|
||||
"""
|
||||
MIIEtDCCA5ygAwIBAgIIZO/q/sI56KUwDQYJKoZIhvcNAQEFBQAwfzELMAkGA1UE
|
||||
BhMCVVMxEzARBgNVBAoMCkFwcGxlIEluYy4xJjAkBgNVBAsMHUFwcGxlIENlcnRp
|
||||
ZmljYXRpb24gQXV0aG9yaXR5MTMwMQYDVQQDDCpBcHBsZSBDb2RlIFNpZ25pbmcg
|
||||
Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMjAxMDI5MTgzMjM4WhcNMjYxMDI0
|
||||
MTczOTQxWjBWMQswCQYDVQQGEwJVUzETMBEGA1UECgwKQXBwbGUgSW5jLjEXMBUG
|
||||
A1UECwwOQXBwbGUgU29mdHdhcmUxGTAXBgNVBAMMEFNvZnR3YXJlIFNpZ25pbmcw
|
||||
ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC/MLh0mE+uBguklG4xVG0J
|
||||
0TyjsDkQqdDmqmAiXdPkhKJAQZBkxmA9kWHaUqhFJ54sZMvkHqgkClI6s9PsFkF4
|
||||
wZ7RBuZ4JWMI89/KQeYd/jXpUVwTFYvp0Z1xe9HJqkuemdqPwCm4L5BvpLtlj4Bq
|
||||
1z1obeR4wqUSL/gy6X7JXVyMPhYgG9denRuGLQj3vBmkTQ5BpErbaxqARVAEqUyN
|
||||
FQfqaie9u4iePD+yUjmX47fI61RSmIovI1Zl5ekq2VG0I/oE3ffroN/VmvJeCPFf
|
||||
h/CxR2x1sbGM0RPjesHsYkF0poM08fladGQ5P1luzyzAYIMpPOfeT18N85M5XzCN
|
||||
AgMBAAGjggFbMIIBVzAMBgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFI5ppsR3Qk4E
|
||||
pVZCnFEfhtrSII8JMIGWBgNVHSAEgY4wgYswgYgGCSqGSIb3Y2QFATB7MHkGCCsG
|
||||
AQUFBwICMG0Ma1RoaXMgY2VydGlmaWNhdGUgaXMgdG8gYmUgdXNlZCBleGNsdXNp
|
||||
dmVseSBmb3IgZnVuY3Rpb25zIGludGVybmFsIHRvIEFwcGxlIFByb2R1Y3RzIGFu
|
||||
ZC9vciBBcHBsZSBwcm9jZXNzZXMuMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMDMDUG
|
||||
A1UdHwQuMCwwKqAooCaGJGh0dHA6Ly9jcmwuYXBwbGUuY29tL2NvZGVzaWduaW5n
|
||||
LmNybDAdBgNVHQ4EFgQUxu0+Svsu6D8T1aAVs13Z57P3aDUwDgYDVR0PAQH/BAQD
|
||||
AgeAMA8GCSqGSIb3Y2QGFgQCBQAwDQYJKoZIhvcNAQEFBQADggEBAImdqA6ANj/n
|
||||
AWa6c4Ijc5udq8taXsIwT5AlYJpJMQQJUja4xm5KZlc/Vazm9eTSdfdbz2WD+yj5
|
||||
lWkQSsmpwpz+iyAgipl+m2JBmp+mh7pI9nGwlYwkAgg/PrkW8D74/mf+9tidOr6Q
|
||||
wQLQSb+bzRoRGQAFOoAVTX0s4419xIygW2SwzhBvXDW5XhZPy/IdTtej2tN9ovsY
|
||||
gOBfN9okEUUes4byotjYEeFMNJSWlchRoQhYM2BvvL3PjFYzdUgS5OZrTZjrVDE1
|
||||
8DlIa8DPVeqoeE7C699Yb8dRF9XYVUG8aVXco7QB9N80o0zagpmAQtoHMos3u8rh
|
||||
59zvNaFyVtE=
|
||||
""",
|
||||
|
||||
"""
|
||||
MIIEDjCCAvagAwIBAgIBITANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQGEwJVUzET
|
||||
MBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlv
|
||||
biBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwHhcNMTExMDI0MTcz
|
||||
OTQxWhcNMjYxMDI0MTczOTQxWjB/MQswCQYDVQQGEwJVUzETMBEGA1UECgwKQXBw
|
||||
bGUgSW5jLjEmMCQGA1UECwwdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkx
|
||||
MzAxBgNVBAMMKkFwcGxlIENvZGUgU2lnbmluZyBDZXJ0aWZpY2F0aW9uIEF1dGhv
|
||||
cml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKKoEXH/DvkLa/gl
|
||||
DZiBXWtZvVobibPn5e7OOZgjNTlInyGrJ9nunCDwZDgIawynz9xQth0GxFvxXRqb
|
||||
VGWGcy9i5Ti9ARBkcm18aUdhnBAFJuPrhcIsJNxqwj+I/MysKUyhSXkRmnV25R64
|
||||
0NIJtExTePvfGHahj6SpMsqRp7b6l705qs0bUBGIq2rt62bKIEusOy3vqufWyYgt
|
||||
acKkKmEv24cC86EhuUyfDvj52S3KcgR/Ha5u+j+Is8yjQO4XhxhRlrzP5C2twulZ
|
||||
Tl0cZTMnA6pno5Mkh8eHeQK5XZizDu7NaQg+jEiSJLJt1zC+z9jkyKeXgdAeI9w4
|
||||
mV9h/oUCAwEAAaOBsTCBrjAOBgNVHQ8BAf8EBAMCAYYwEwYDVR0lBAwwCgYIKwYB
|
||||
BQUHAwMwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUjmmmxHdCTgSlVkKcUR+G
|
||||
2tIgjwkwHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/CF4wNgYDVR0fBC8w
|
||||
LTAroCmgJ4YlaHR0cDovL3d3dy5hcHBsZS5jb20vYXBwbGVjYS9yb290LmNybDAN
|
||||
BgkqhkiG9w0BAQUFAAOCAQEAcHOt9lIVarcVGN6pKtGddpsesmmWx8LD4SvQ7wdd
|
||||
cPjaPFpIR9s5bIDKc95iG7c6yqNaHuOH2iVKk5vvcxCTc13j9J1+3g+B9qmZwVhu
|
||||
nPSJAL7PT/8C0w789fP0choysconDt6o05mPauaZ+2HJT/IXsRhn8DDAxgruyESB
|
||||
pIm78XlBw+6uyGtnfMxsSYZMAtPTam4YnPhcOMgwh5ow2mcouOKaedqfpTsfUWI7
|
||||
IvF+U3waC8PwTdxJRPKIiM46W7md6bK3W1KnxtVYiXK32MyzqBgdUJc/Hdpqrji/
|
||||
e3kxvmO594WFF+ltisTiGJQv129SpZmx3USbB3CSiCZ32w==
|
||||
""",
|
||||
|
||||
"""
|
||||
MIIEuzCCA6OgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQGEwJVUzET
|
||||
MBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlv
|
||||
biBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwHhcNMDYwNDI1MjE0
|
||||
MDM2WhcNMzUwMjA5MjE0MDM2WjBiMQswCQYDVQQGEwJVUzETMBEGA1UEChMKQXBw
|
||||
bGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkx
|
||||
FjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
|
||||
ggEKAoIBAQDkkakJH5HbHkdQ6wXtXnmELes2oldMVeyLGYne+Uts9QerIjAC6Bg+
|
||||
+FAJ039BqJj50cpmnCRrEdCju+QbKsMflZ56DKRHi1vUFjczy8QPTc4UadHJGXL1
|
||||
XQ7Vf1+b8iUDulWPTV0N8WQ1IxVLFVkds5T39pyez1C6wVhQZ48ItCD3y6wsIG9w
|
||||
tj8BMIy3Q88PnT3zK0koGsj+zrW5DtleHNbLPbU6rfQPDgCSC7EhFi501TwN22IW
|
||||
q6NxkkdTVcGvL0Gz+PvjcM3mo0xFfh9Ma1CWQYnEdGILEINBhzOKgbEwWOxaBDKM
|
||||
aLOPHd5lc/9nXmW8Sdh2nzMUZaF3lMktAgMBAAGjggF6MIIBdjAOBgNVHQ8BAf8E
|
||||
BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUK9BpR5R2Cf70a40uQKb3
|
||||
R01/CF4wHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/CF4wggERBgNVHSAE
|
||||
ggEIMIIBBDCCAQAGCSqGSIb3Y2QFATCB8jAqBggrBgEFBQcCARYeaHR0cHM6Ly93
|
||||
d3cuYXBwbGUuY29tL2FwcGxlY2EvMIHDBggrBgEFBQcCAjCBthqBs1JlbGlhbmNl
|
||||
IG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0
|
||||
YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBj
|
||||
b25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZp
|
||||
Y2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMA0GCSqGSIb3DQEBBQUAA4IBAQBc
|
||||
NplMLXi37Yyb3PN3m/J20ncwT8EfhYOFG5k9RzfyqZtAjizUsZAS2L70c5vu0mQP
|
||||
y3lPNNiiPvl4/2vIB+x9OYOLUyDTOMSxv5pPCmv/K/xZpwUJfBdAVhEedNO3iyM7
|
||||
R6PVbyTi69G3cN8PReEnyvFteO3ntRcXqNx+IjXKJdXZD9Zr1KIkIxH3oayPc4Fg
|
||||
xhtbCS+SsvhESPBgOJ4V9T0mZyCKM2r3DYLP3uujL/lTaltkwGMzd/c6ByxW69oP
|
||||
IQ7aunMZT7XZNn/Bh1XZp5m5MkL72NVxnn6hUrcbvZNCJBIqxw8dtk2cXmPIS4AX
|
||||
UKqK1drk/NAJBzewdXUh
|
||||
""",
|
||||
]
|
||||
|
||||
func testSimpleDecode() throws {
|
||||
let binary = Array(Data(base64Encoded: Self.base64EncodedSampleCert, options: .ignoreUnknownCharacters)!)
|
||||
let cert = try Certificate(asn1Encoded: binary)
|
||||
|
||||
let expectedPublicKey = try P256.Signing.PublicKey(
|
||||
x963Representation: [
|
||||
0x04, 0x29, 0xf8, 0xe1, 0x5a, 0xb9, 0x87, 0x44, 0x04, 0x98, 0xff, 0x16, 0x90, 0x86, 0xf9,
|
||||
0xe0, 0xe1, 0x42, 0x65, 0x5f, 0x86, 0xfd, 0x03, 0x18, 0xfc, 0xc6, 0xcf, 0x8d, 0x13, 0x5b,
|
||||
0xc0, 0x5e, 0x5b, 0x18, 0xa9, 0x61, 0x33, 0x9a, 0xe0, 0x52, 0xe2, 0x78, 0x06, 0x28, 0x53,
|
||||
0xed, 0xed, 0xda, 0xd8, 0x3d, 0x15, 0x92, 0xad, 0x03, 0x80, 0x43, 0x4c, 0xee, 0x37, 0x62,
|
||||
0x9a, 0xcb, 0x66, 0x6e, 0xb3,
|
||||
]
|
||||
)
|
||||
|
||||
XCTAssertEqual(cert.version, .v3)
|
||||
XCTAssertEqual(cert.serialNumber.bytes, [0x0c, 0xab, 0xaa, 0xd1, 0xce, 0xc4, 0xe9, 0x7c, 0xc2, 0x66, 0x58, 0x81, 0xd0, 0x21, 0x38, 0xf7])
|
||||
XCTAssertEqual(cert.publicKey, Certificate.PublicKey(expectedPublicKey))
|
||||
|
||||
let expectedNotBefore = Date(timeIntervalSince1970: 1588163692.0)
|
||||
let expectedNotAfter = Date(timeIntervalSince1970: 1902095999.0)
|
||||
|
||||
XCTAssertEqual(expectedNotBefore, cert.notValidBefore)
|
||||
XCTAssertEqual(expectedNotAfter, cert.notValidAfter)
|
||||
|
||||
let expectedIssuer = try DistinguishedName([
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, printableString: "US"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, printableString: "DigiCert Inc"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, printableString: "www.digicert.com"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, printableString: "DigiCert Global Root G3"),
|
||||
])
|
||||
|
||||
let expectedSubject = try DistinguishedName([
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, printableString: "US"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, printableString: "Apple Inc."),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, printableString: "Apple Public EV Server ECC CA 1 - G1"),
|
||||
])
|
||||
|
||||
XCTAssertEqual(cert.issuer, expectedIssuer)
|
||||
XCTAssertEqual(cert.subject, expectedSubject)
|
||||
|
||||
XCTAssertEqual(cert.extensions.count, 8)
|
||||
XCTAssertEqual(try cert.extensions.authorityInformationAccess, .init([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]))
|
||||
XCTAssertEqual(
|
||||
try cert.extensions.subjectKeyIdentifier,
|
||||
.init(keyIdentifier: [0xE0, 0x85, 0x48, 0x7D, 0x13, 0xA6, 0xD3, 0x10, 0x19, 0x9F, 0x5C, 0xCB, 0x6B, 0x78, 0x24, 0x92, 0xF8, 0xAE, 0x1B, 0xAE])
|
||||
)
|
||||
XCTAssertEqual(
|
||||
try cert.extensions.authorityKeyIdentifier,
|
||||
.init(keyIdentifier: [0xB3, 0xDB, 0x48, 0xA4, 0xF9, 0xA1, 0xC5, 0xD8, 0xAE, 0x36, 0x41, 0xCC, 0x11, 0x63, 0x69, 0x62, 0x29, 0xBC, 0x4B, 0xC6])
|
||||
)
|
||||
XCTAssertEqual(
|
||||
try cert.extensions.extendedKeyUsage,
|
||||
.init([.serverAuth, .clientAuth])
|
||||
)
|
||||
XCTAssertEqual(
|
||||
try cert.extensions.basicConstraints,
|
||||
.isCertificateAuthority(maxPathLength: 0)
|
||||
)
|
||||
XCTAssertEqual(
|
||||
try cert.extensions.keyUsage,
|
||||
.init(digitalSignature: true, keyCertSign: true, cRLSign: true)
|
||||
)
|
||||
|
||||
XCTAssertEqual(cert.signatureAlgorithm, .ecdsaWithSHA384)
|
||||
}
|
||||
|
||||
func testMatchingExtensionsViaExtensionBuilder() throws {
|
||||
let binary = Array(Data(base64Encoded: Self.base64EncodedSampleCert, options: .ignoreUnknownCharacters)!)
|
||||
let cert = try Certificate(asn1Encoded: binary)
|
||||
|
||||
let expectedExtensions = try Certificate.Extensions {
|
||||
Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: [0xE0, 0x85, 0x48, 0x7D, 0x13, 0xA6, 0xD3, 0x10, 0x19, 0x9F, 0x5C, 0xCB, 0x6B, 0x78, 0x24, 0x92, 0xF8, 0xAE, 0x1B, 0xAE])
|
||||
|
||||
Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: [0xB3, 0xDB, 0x48, 0xA4, 0xF9, 0xA1, 0xC5, 0xD8, 0xAE, 0x36, 0x41, 0xCC, 0x11, 0x63, 0x69, 0x62, 0x29, 0xBC, 0x4B, 0xC6])
|
||||
|
||||
Critical(
|
||||
Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true)
|
||||
)
|
||||
|
||||
Certificate.Extensions.ExtendedKeyUsage([.serverAuth, .clientAuth])
|
||||
|
||||
Critical(
|
||||
Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 0)
|
||||
)
|
||||
|
||||
Certificate.Extensions.AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))])
|
||||
|
||||
// CRL Distribution Points
|
||||
Certificate.Extension(
|
||||
oid: [2, 5, 29, 31],
|
||||
critical: false,
|
||||
value: [
|
||||
0x30, 0x39, 0x30, 0x37, 0xA0, 0x35, 0xA0, 0x33, 0x86, 0x31, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F,
|
||||
0x2F, 0x63, 0x72, 0x6C, 0x33, 0x2E, 0x64, 0x69, 0x67, 0x69, 0x63, 0x65, 0x72, 0x74, 0x2E, 0x63,
|
||||
0x6F, 0x6D, 0x2F, 0x44, 0x69, 0x67, 0x69, 0x43, 0x65, 0x72, 0x74, 0x47, 0x6C, 0x6F, 0x62, 0x61,
|
||||
0x6C, 0x52, 0x6F, 0x6F, 0x74, 0x47, 0x33, 0x2E, 0x63, 0x72, 0x6C
|
||||
]
|
||||
)
|
||||
|
||||
// Certificate policies
|
||||
Certificate.Extension(
|
||||
oid: [2, 5, 29, 32],
|
||||
critical: false,
|
||||
value: [
|
||||
0x30, 0x81, 0xD1, 0x30, 0x81, 0xC5, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xFD, 0x6C, 0x02,
|
||||
0x01, 0x30, 0x81, 0xB7, 0x30, 0x28, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x02, 0x01,
|
||||
0x16, 0x1C, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3A, 0x2F, 0x2F, 0x77, 0x77, 0x77, 0x2E, 0x64, 0x69,
|
||||
0x67, 0x69, 0x63, 0x65, 0x72, 0x74, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x43, 0x50, 0x53, 0x30, 0x81,
|
||||
0x8A, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x02, 0x02, 0x30, 0x7E, 0x0C, 0x7C, 0x41,
|
||||
0x6E, 0x79, 0x20, 0x75, 0x73, 0x65, 0x20, 0x6F, 0x66, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x43,
|
||||
0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74,
|
||||
0x69, 0x74, 0x75, 0x74, 0x65, 0x73, 0x20, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x61, 0x6E, 0x63,
|
||||
0x65, 0x20, 0x6F, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x52, 0x65, 0x6C, 0x79, 0x69, 0x6E, 0x67,
|
||||
0x20, 0x50, 0x61, 0x72, 0x74, 0x79, 0x20, 0x41, 0x67, 0x72, 0x65, 0x65, 0x6D, 0x65, 0x6E, 0x74,
|
||||
0x20, 0x6C, 0x6F, 0x63, 0x61, 0x74, 0x65, 0x64, 0x20, 0x61, 0x74, 0x20, 0x68, 0x74, 0x74, 0x70,
|
||||
0x73, 0x3A, 0x2F, 0x2F, 0x77, 0x77, 0x77, 0x2E, 0x64, 0x69, 0x67, 0x69, 0x63, 0x65, 0x72, 0x74,
|
||||
0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x72, 0x70, 0x61, 0x2D, 0x75, 0x61, 0x30, 0x07, 0x06, 0x05, 0x67,
|
||||
0x81, 0x0C, 0x01, 0x01
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
XCTAssertEqual(cert.extensions, expectedExtensions)
|
||||
}
|
||||
|
||||
func testRSARootCert() throws {
|
||||
let binary = Array(Data(base64Encoded: Self.base64EncodedRSARootCert, options: .ignoreUnknownCharacters)!)
|
||||
let cert = try Certificate(asn1Encoded: binary)
|
||||
XCTAssertTrue(cert.publicKey.isValidSignature(cert.signature, for: cert))
|
||||
}
|
||||
|
||||
func testCodesignChain() throws {
|
||||
let binaryCerts = Self.codesignCerts.map { Array(Data(base64Encoded: $0, options: .ignoreUnknownCharacters)!) }
|
||||
let certs = try binaryCerts.map { try Certificate(asn1Encoded: $0) }
|
||||
|
||||
// Confirm basic signature validation.
|
||||
XCTAssertTrue(certs[1].publicKey.isValidSignature(certs[0].signature, for: certs[0]))
|
||||
XCTAssertTrue(certs[2].publicKey.isValidSignature(certs[1].signature, for: certs[1]))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import X509
|
||||
|
||||
final class CertificateTests: XCTestCase {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import SwiftASN1
|
||||
@testable import X509
|
||||
|
||||
final class DistinguishedNameTests: XCTestCase {
|
||||
private func assertRoundTrips<ASN1Object: ASN1Parseable & ASN1Serializable & Equatable>(_ value: ASN1Object) throws {
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(value)
|
||||
let parsed = try ASN1Object(asn1Encoded: serializer.serializedBytes)
|
||||
XCTAssertEqual(parsed, value)
|
||||
}
|
||||
|
||||
func testSimpleRelativeDistinguishedNameSortsItsElements() throws {
|
||||
let expected = [
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.commonName, printableString: "efgh"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
|
||||
]
|
||||
let nameA = try RelativeDistinguishedName(expected)
|
||||
let nameB = try RelativeDistinguishedName(expected.reversed())
|
||||
XCTAssertEqual(Array(nameA), expected)
|
||||
XCTAssertEqual(Array(nameB), expected)
|
||||
}
|
||||
|
||||
func testSimpleRelativeDistinguishedNameSortsItsElementsWhenAssignedAfterTheFact() throws {
|
||||
let expected = [
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.commonName, printableString: "efgh"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
|
||||
]
|
||||
var nameA = RelativeDistinguishedName()
|
||||
var nameB = RelativeDistinguishedName()
|
||||
nameA.insert(contentsOf: expected)
|
||||
nameB.insert(contentsOf: expected.reversed())
|
||||
XCTAssertEqual(Array(nameA), expected)
|
||||
XCTAssertEqual(Array(nameB), expected)
|
||||
}
|
||||
|
||||
func testSimpleRelativeDistinguishedNameSortsItsElementsIncludingByLength() throws {
|
||||
let expected = [
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcde"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
|
||||
]
|
||||
let nameA = try RelativeDistinguishedName(expected)
|
||||
let nameB = try RelativeDistinguishedName(expected.reversed())
|
||||
XCTAssertEqual(Array(nameA), expected)
|
||||
XCTAssertEqual(Array(nameB), expected)
|
||||
}
|
||||
|
||||
|
||||
func testSimpleRelativeDistinguishedNameRoundTrips() throws {
|
||||
let name = try RelativeDistinguishedName([
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.commonName, printableString: "efgh"),
|
||||
])
|
||||
try self.assertRoundTrips(name)
|
||||
}
|
||||
|
||||
func testSimpleRelativeDistinguishedNameSerializesAsExpected() throws {
|
||||
let name = try RelativeDistinguishedName([
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.commonName, printableString: "efgh"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
|
||||
])
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(name)
|
||||
|
||||
let expectedBytes: [UInt8] = [
|
||||
49, 26, 48, 11, 6, 3, 85, 4, 3, 19, 4, 0x65, 0x66, 0x67, 0x68, 48, 11, 6, 3, 85, 4, 41, 12, 4, 0x61, 0x62, 0x63, 0x64
|
||||
]
|
||||
|
||||
XCTAssertEqual(serializer.serializedBytes, expectedBytes)
|
||||
}
|
||||
|
||||
func testSimpleDistinguishedNameRoundTrips() throws {
|
||||
let firstName = try RelativeDistinguishedName([
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.commonName, printableString: "efgh"),
|
||||
])
|
||||
let secondName = try RelativeDistinguishedName([
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "ijkl"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.commonName, printableString: "mnop"),
|
||||
])
|
||||
let name = DistinguishedName([firstName, secondName])
|
||||
try self.assertRoundTrips(name)
|
||||
}
|
||||
|
||||
func testSimpleDistinguishedNameSerializesAsExpected() throws {
|
||||
let firstName = try RelativeDistinguishedName([
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.commonName, printableString: "efgh"),
|
||||
])
|
||||
let secondName = try RelativeDistinguishedName([
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "ijkl"),
|
||||
try RelativeDistinguishedName.Attribute(type: .NameAttributes.commonName, printableString: "mnop"),
|
||||
])
|
||||
let name = DistinguishedName([firstName, secondName])
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(name)
|
||||
|
||||
let expectedBytes: [UInt8] = [
|
||||
48, 56, 49, 26, 48, 11, 6, 3, 85, 4, 3, 19, 4, 0x65, 0x66, 0x67, 0x68, 48, 11, 6, 3, 85,
|
||||
4, 41, 12, 4, 0x61, 0x62, 0x63, 0x64, 49, 26, 48, 11, 6, 3, 85, 4, 3, 19, 4, 0x6d, 0x6e, 0x6f,
|
||||
0x70, 48, 11, 6, 3, 85, 4, 41, 12, 4, 0x69, 0x6a, 0x6b, 0x6c
|
||||
]
|
||||
|
||||
XCTAssertEqual(serializer.serializedBytes, expectedBytes)
|
||||
}
|
||||
|
||||
func testDistinguishedNameBuilder() throws {
|
||||
let name = try DistinguishedName {
|
||||
CountryName("US")
|
||||
OrganizationName("DigiCert Inc")
|
||||
OrganizationalUnitName("www.digicert.com")
|
||||
CommonName("DigiCert Global Root G3")
|
||||
}
|
||||
XCTAssertEqual(
|
||||
name,
|
||||
try DistinguishedName([
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, utf8String: "DigiCert Inc"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, utf8String: "www.digicert.com"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, utf8String: "DigiCert Global Root G3"),
|
||||
])
|
||||
)
|
||||
}
|
||||
|
||||
func testDistinguishedNameBuilderFlow() throws {
|
||||
let x = 1
|
||||
let name = try DistinguishedName {
|
||||
CountryName("US")
|
||||
OrganizationName("DigiCert Inc")
|
||||
|
||||
if x == 1 {
|
||||
OrganizationalUnitName("www.digicert.com")
|
||||
}
|
||||
|
||||
if x == 2 {
|
||||
StreetAddress("123 Fake Street")
|
||||
} else {
|
||||
StreetAddress("123 Real Street")
|
||||
}
|
||||
|
||||
if x == 3 {
|
||||
StateOrProvinceName("DigiLand")
|
||||
}
|
||||
|
||||
for name in ["foo", "bar", "baz"].filter { $0 == "baz" } {
|
||||
CommonName(name)
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertEqual(
|
||||
name,
|
||||
try DistinguishedName([
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, utf8String: "DigiCert Inc"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, utf8String: "www.digicert.com"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.streetAddress, utf8String: "123 Real Street"),
|
||||
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, utf8String: "baz"),
|
||||
])
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import X509
|
||||
|
||||
final class ExtensionBuilderTests: XCTestCase {
|
||||
func testSimpleBuilder() throws {
|
||||
let x = 1
|
||||
let extensions = try Certificate.Extensions {
|
||||
Certificate.Extension(oid: .X509ExtensionID.authorityInformationAccess, critical: true, value: [1, 2, 3])
|
||||
|
||||
Certificate.Extension(oid: .X509ExtensionID.authorityKeyIdentifier, critical: true, value: [4, 5, 6])
|
||||
|
||||
if x == 1 {
|
||||
Certificate.Extension(oid: .X509ExtensionID.basicConstraints, critical: true, value: [7, 8, 9])
|
||||
}
|
||||
|
||||
if x == 2 {
|
||||
Certificate.Extension(oid: .X509ExtensionID.extendedKeyUsage, critical: true, value: [10, 11, 12])
|
||||
} else {
|
||||
Certificate.Extension(oid: .X509ExtensionID.nameConstraints, critical: false, value: [13, 14, 15])
|
||||
}
|
||||
|
||||
if x == 3 {
|
||||
Certificate.Extension(oid: .X509ExtensionID.nameConstraints, critical: false, value: [16, 17, 18])
|
||||
}
|
||||
|
||||
for i in 19..<22 {
|
||||
Certificate.Extension(oid: [UInt(i)], critical: false, value: [22])
|
||||
}
|
||||
}
|
||||
|
||||
let expectedExtensions = Certificate.Extensions([
|
||||
Certificate.Extension(oid: .X509ExtensionID.authorityInformationAccess, critical: true, value: [1, 2, 3]),
|
||||
Certificate.Extension(oid: .X509ExtensionID.authorityKeyIdentifier, critical: true, value: [4, 5, 6]),
|
||||
Certificate.Extension(oid: .X509ExtensionID.basicConstraints, critical: true, value: [7, 8, 9]),
|
||||
Certificate.Extension(oid: .X509ExtensionID.nameConstraints, critical: false, value: [13, 14, 15]),
|
||||
Certificate.Extension(oid: [19], critical: false, value: [22]),
|
||||
Certificate.Extension(oid: [20], critical: false, value: [22]),
|
||||
Certificate.Extension(oid: [21], critical: false, value: [22]),
|
||||
])
|
||||
|
||||
XCTAssertEqual(extensions, expectedExtensions)
|
||||
}
|
||||
|
||||
func testMakingThingsCritical() throws {
|
||||
let extensions = try Certificate.Extensions {
|
||||
Critical(
|
||||
Certificate.Extension(oid: .X509ExtensionID.authorityInformationAccess, critical: false, value: [1, 2, 3])
|
||||
)
|
||||
}
|
||||
|
||||
let expectedExtensions = Certificate.Extensions([
|
||||
Certificate.Extension(oid: .X509ExtensionID.authorityInformationAccess, critical: true, value: [1, 2, 3]),
|
||||
])
|
||||
|
||||
XCTAssertEqual(extensions, expectedExtensions)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCrypto open source project
|
||||
//
|
||||
// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
import XCTest
|
||||
|
||||
@testable import SwiftASN1
|
||||
|
||||
final class OCSPTests: XCTestCase {
|
||||
// TODO: Make these work.
|
||||
#if false
|
||||
private func assertRoundTrips<ASN1Object: ASN1Parseable & ASN1Serializable & Equatable>(_ value: ASN1Object) throws {
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(value)
|
||||
let parsed = try ASN1Object(asn1Encoded: serializer.serializedBytes)
|
||||
XCTAssertEqual(parsed, value)
|
||||
}
|
||||
|
||||
func testResponderIDByNameRoundTrips() throws {
|
||||
let id = ASN1.ResponderID.byName(
|
||||
ASN1.DistinguishedName(elements: [
|
||||
RelativeDistinguishedName(elements: [
|
||||
RFC5280AttributeTypeAndValue(type: .NameAttributes.name,
|
||||
value: .utf8String(.init(contentBytes: [1, 2, 3, 4]))),
|
||||
])
|
||||
])
|
||||
)
|
||||
|
||||
try self.assertRoundTrips(id)
|
||||
}
|
||||
|
||||
func testResponderIDByKeyIDRoundTrips() throws {
|
||||
let id = ASN1.ResponderID.byKey(
|
||||
ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4])
|
||||
)
|
||||
|
||||
try self.assertRoundTrips(id)
|
||||
}
|
||||
|
||||
func testResponderIDByNameSerialization() throws {
|
||||
let id = ASN1.ResponderID.byName(
|
||||
ASN1.DistinguishedName(elements: [
|
||||
RelativeDistinguishedName(elements: [
|
||||
RFC5280AttributeTypeAndValue(type: .NameAttributes.name,
|
||||
value: .utf8String(.init(contentBytes: [1, 2, 3, 4]))),
|
||||
])
|
||||
])
|
||||
)
|
||||
|
||||
let expected: [UInt8] = [161, 17, 48, 15, 49, 13, 48, 11, 6, 3, 85, 4, 41, 12, 4, 1, 2, 3, 4]
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(id)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
|
||||
func testResponderIDByKeySerialization() throws {
|
||||
let id = ASN1.ResponderID.byKey(
|
||||
ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4])
|
||||
)
|
||||
|
||||
let expected: [UInt8] = [162, 6, 4, 4, 1, 2, 3, 4]
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(id)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
|
||||
func testCertIDRoundTrips() throws {
|
||||
let certID = ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
)
|
||||
|
||||
try self.assertRoundTrips(certID)
|
||||
}
|
||||
|
||||
func testOCSPCertIDSerialization() throws {
|
||||
let certID = ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
)
|
||||
|
||||
let expected: [UInt8] = [
|
||||
48, 39, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 134,
|
||||
72, 206, 61, 3, 1, 7, 4, 4, 1, 2, 3, 4, 4, 4, 5, 6, 7, 8, 2, 4,
|
||||
9, 10, 11, 12
|
||||
]
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(certID)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
|
||||
func testCRLReasonRoundTrips() throws {
|
||||
let fixtures: [ASN1.CRLReason] = [
|
||||
.unspecified,
|
||||
.keyCompromise,
|
||||
.caCompromise,
|
||||
.affiliationChanged,
|
||||
.superseded,
|
||||
.cessationOfOperation,
|
||||
.certificateHold,
|
||||
.removeFromCRL,
|
||||
.privilegeWithdrawn,
|
||||
.aaCompromise,
|
||||
]
|
||||
|
||||
for fixture in fixtures {
|
||||
try self.assertRoundTrips(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
func testCRLReasionSerialization() throws {
|
||||
let fixtures: [(ASN1.CRLReason, Int)] = [
|
||||
(.unspecified, 0),
|
||||
(.keyCompromise, 1),
|
||||
(.caCompromise, 2),
|
||||
(.affiliationChanged, 3),
|
||||
(.superseded, 4),
|
||||
(.cessationOfOperation, 5),
|
||||
(.certificateHold, 6),
|
||||
(.removeFromCRL, 8),
|
||||
(.privilegeWithdrawn, 9),
|
||||
(.aaCompromise, 10),
|
||||
]
|
||||
|
||||
for (fixture, expectedPayload) in fixtures {
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(fixture)
|
||||
|
||||
var expected = Array<UInt8>()
|
||||
expected.writeIdentifier(ASN1.ASN1Identifier.enumerated)
|
||||
expected.append(1)
|
||||
expected.append(UInt8(expectedPayload))
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testOCSPRevokedInfoRoundTrips() throws {
|
||||
var revokedInfo = ASN1.OCSPRevokedInfo(
|
||||
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
|
||||
revocationReason: nil
|
||||
)
|
||||
try self.assertRoundTrips(revokedInfo)
|
||||
|
||||
revokedInfo.revocationReason = .caCompromise
|
||||
try self.assertRoundTrips(revokedInfo)
|
||||
}
|
||||
|
||||
func testOCSPRevokedInfoSerializesWithoutReason() throws {
|
||||
let revokedInfo = ASN1.OCSPRevokedInfo(
|
||||
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
|
||||
revocationReason: nil
|
||||
)
|
||||
let expected: [UInt8] = [48, 20, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90]
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(revokedInfo)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
|
||||
func testOCSPRevokedInfoSerializesWithReason() throws {
|
||||
let revokedInfo = ASN1.OCSPRevokedInfo(
|
||||
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
|
||||
revocationReason: .cessationOfOperation
|
||||
)
|
||||
let expected: [UInt8] = [48, 25, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90, 160, 3, 10, 1, 5]
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(revokedInfo)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
|
||||
func testOCSPCertStatusRoundTrips() throws {
|
||||
let fixtures: [ASN1.OCSPCertStatus] = [
|
||||
.good,
|
||||
.revoked(
|
||||
ASN1.OCSPRevokedInfo(
|
||||
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
|
||||
revocationReason: .cessationOfOperation)
|
||||
),
|
||||
.unknown,
|
||||
]
|
||||
|
||||
for fixture in fixtures {
|
||||
try self.assertRoundTrips(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
func testOCSPCertStatusGoodSerializes() throws {
|
||||
let value = ASN1.OCSPCertStatus.good
|
||||
let expected: [UInt8] = [128, 0]
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(value)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
|
||||
func testOCSPCertStatusRevokedSerializes() throws {
|
||||
let value = ASN1.OCSPCertStatus.revoked(
|
||||
ASN1.OCSPRevokedInfo(
|
||||
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
|
||||
revocationReason: .cessationOfOperation)
|
||||
)
|
||||
let expected: [UInt8] = [161, 25, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90, 160, 3, 10, 1, 5]
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(value)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
|
||||
func testOCSPCertStatusUnknownSerializes() throws {
|
||||
let value = ASN1.OCSPCertStatus.unknown
|
||||
let expected: [UInt8] = [130, 0]
|
||||
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(value)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
|
||||
func testRFC5280ExtensionRoundTrip() throws {
|
||||
let fixtures: [ASN1.RFC5280Extension] = [
|
||||
.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8])),
|
||||
.init(extensionID: [2, 10, 11, 12], critical: false, extensionValue: .init(contentBytes: [13, 14, 15, 16])),
|
||||
]
|
||||
|
||||
for fixture in fixtures {
|
||||
try self.assertRoundTrips(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
func testRFC5280ExtensionEncodesCorrectly() throws {
|
||||
let fixtures: [(ASN1.RFC5280Extension, [UInt8])] = [
|
||||
(
|
||||
.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8])),
|
||||
[48, 14, 6, 3, 42, 3, 4, 1, 1, 255, 4, 4, 5, 6, 7, 8]
|
||||
),
|
||||
(
|
||||
.init(extensionID: [2, 10, 11, 12], critical: false, extensionValue: .init(contentBytes: [13, 14, 15, 16])),
|
||||
[48, 11, 6, 3, 90, 11, 12, 4, 4, 13, 14, 15, 16]
|
||||
),
|
||||
]
|
||||
|
||||
for (value, expected) in fixtures {
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(value)
|
||||
XCTAssertEqual(serializer.serializedBytes, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func testRFC5280ExtensionRejectsParsingFalse() throws {
|
||||
let bytes: [UInt8] = [48, 14, 6, 3, 42, 3, 4, 1, 1, 0, 4, 4, 5, 6, 7, 8]
|
||||
XCTAssertThrowsError(try ASN1.RFC5280Extension(asn1Encoded: bytes))
|
||||
}
|
||||
|
||||
func testOCSPSingleResponseRoundTrips() throws {
|
||||
let fixtures: [ASN1.OCSPSingleResponse] = [
|
||||
.init(
|
||||
certID: ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
),
|
||||
certStatus: .good,
|
||||
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
nextUpdate: nil,
|
||||
extensions: nil
|
||||
),
|
||||
.init(
|
||||
certID: ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
),
|
||||
certStatus: .good,
|
||||
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
|
||||
extensions: nil
|
||||
),
|
||||
.init(
|
||||
certID: ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
),
|
||||
certStatus: .good,
|
||||
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
nextUpdate: nil,
|
||||
extensions: [.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8]))]
|
||||
),
|
||||
.init(
|
||||
certID: ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
),
|
||||
certStatus: .good,
|
||||
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
|
||||
extensions: [.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8]))]
|
||||
),
|
||||
]
|
||||
|
||||
for fixture in fixtures {
|
||||
try self.assertRoundTrips(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
func testOCSPResponseDataRoundTrips() throws {
|
||||
let responderID = ASN1.ResponderID.byName(
|
||||
ASN1.DistinguishedName(elements: [
|
||||
RelativeDistinguishedName(elements: [
|
||||
RFC5280AttributeTypeAndValue(type: .NameAttributes.name,
|
||||
value: .utf8String(.init(contentBytes: [1, 2, 3, 4]))),
|
||||
])
|
||||
])
|
||||
)
|
||||
|
||||
let response = ASN1.OCSPSingleResponse(
|
||||
certID: ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
),
|
||||
certStatus: .good,
|
||||
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
|
||||
extensions: [.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8]))]
|
||||
)
|
||||
|
||||
let extensions: [ASN1.RFC5280Extension] = [
|
||||
.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8])),
|
||||
.init(extensionID: [2, 10, 11, 12], critical: false, extensionValue: .init(contentBytes: [13, 14, 15, 16])),
|
||||
]
|
||||
|
||||
let fixtures: [ASN1.OCSPResponseData] = [
|
||||
.init(
|
||||
responderID: responderID,
|
||||
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
responses: [response, response, response],
|
||||
responseExtensions: nil
|
||||
),
|
||||
.init(
|
||||
version: 3,
|
||||
responderID: responderID,
|
||||
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
responses: [response, response, response],
|
||||
responseExtensions: nil
|
||||
),
|
||||
.init(
|
||||
responderID: responderID,
|
||||
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
responses: [response, response, response],
|
||||
responseExtensions: extensions
|
||||
),
|
||||
.init(
|
||||
version: 3,
|
||||
responderID: responderID,
|
||||
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
responses: [response, response, response],
|
||||
responseExtensions: extensions
|
||||
),
|
||||
]
|
||||
|
||||
for fixture in fixtures {
|
||||
try self.assertRoundTrips(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
func testBasicOCSPResponseRoundTrips() throws {
|
||||
let responderID = ASN1.ResponderID.byName(
|
||||
ASN1.DistinguishedName(elements: [
|
||||
RelativeDistinguishedName(elements: [
|
||||
RFC5280AttributeTypeAndValue(type: .NameAttributes.name,
|
||||
value: .utf8String(.init(contentBytes: [1, 2, 3, 4]))),
|
||||
])
|
||||
])
|
||||
)
|
||||
|
||||
let response = ASN1.OCSPSingleResponse(
|
||||
certID: ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
),
|
||||
certStatus: .good,
|
||||
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
|
||||
extensions: [.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8]))]
|
||||
)
|
||||
|
||||
let extensions: [ASN1.RFC5280Extension] = [
|
||||
.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8])),
|
||||
.init(extensionID: [2, 10, 11, 12], critical: false, extensionValue: .init(contentBytes: [13, 14, 15, 16])),
|
||||
]
|
||||
|
||||
let responseData = ASN1.OCSPResponseData(
|
||||
responderID: responderID,
|
||||
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
responses: [response, response, response],
|
||||
responseExtensions: extensions
|
||||
)
|
||||
|
||||
// This is massive, so we don't have more than one fixture. Takes a lot of space to even write it down!
|
||||
let basicResponse = ASN1.BasicOCSPResponse(
|
||||
responseData: responseData,
|
||||
signatureAlgorithm: .p256PublicKey,
|
||||
signature: ASN1.ASN1BitString(bytes: [1, 2, 3, 4]))
|
||||
try self.assertRoundTrips(basicResponse)
|
||||
}
|
||||
|
||||
func testOCSPResponseBytesRoundTrips() throws {
|
||||
let bytes = ASN1.OCSPResponseBytes(responseType: .OCSP.basicResponse, response: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]))
|
||||
try self.assertRoundTrips(bytes)
|
||||
}
|
||||
|
||||
func testOCSPResponseBytesFromBasicResponse() throws {
|
||||
let responderID = ASN1.ResponderID.byName(
|
||||
ASN1.DistinguishedName(elements: [
|
||||
RelativeDistinguishedName(elements: [
|
||||
RFC5280AttributeTypeAndValue(type: .NameAttributes.name,
|
||||
value: .utf8String(.init(contentBytes: [1, 2, 3, 4]))),
|
||||
])
|
||||
])
|
||||
)
|
||||
|
||||
let response = ASN1.OCSPSingleResponse(
|
||||
certID: ASN1.OCSPCertID(
|
||||
hashAlgorithm: .p256PublicKey,
|
||||
issuerNameHash: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]),
|
||||
issuerKeyHash: ASN1.ASN1OctetString(contentBytes: [5, 6, 7, 8]),
|
||||
serialNumber: [9, 10, 11, 12]
|
||||
),
|
||||
certStatus: .good,
|
||||
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
|
||||
extensions: [.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8]))]
|
||||
)
|
||||
|
||||
let extensions: [ASN1.RFC5280Extension] = [
|
||||
.init(extensionID: [1, 2, 3, 4], critical: true, extensionValue: .init(contentBytes: [5, 6, 7, 8])),
|
||||
.init(extensionID: [2, 10, 11, 12], critical: false, extensionValue: .init(contentBytes: [13, 14, 15, 16])),
|
||||
]
|
||||
|
||||
let responseData = ASN1.OCSPResponseData(
|
||||
responderID: responderID,
|
||||
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
|
||||
responses: [response, response, response],
|
||||
responseExtensions: extensions
|
||||
)
|
||||
|
||||
// This is massive, so we don't have more than one fixture. Takes a lot of space to even write it down!
|
||||
let basicResponse = ASN1.BasicOCSPResponse(
|
||||
responseData: responseData,
|
||||
signatureAlgorithm: .p256PublicKey,
|
||||
signature: ASN1.ASN1BitString(bytes: [1, 2, 3, 4]))
|
||||
|
||||
let bytes = try ASN1.OCSPResponseBytes(encoding: basicResponse)
|
||||
XCTAssertEqual(bytes.responseType, .OCSP.basicResponse)
|
||||
XCTAssertEqual(try ASN1.BasicOCSPResponse(asn1Encoded: bytes.response.bytes), basicResponse)
|
||||
XCTAssertEqual(try ASN1.BasicOCSPResponse(decoding: bytes), basicResponse)
|
||||
try assertRoundTrips(bytes)
|
||||
}
|
||||
|
||||
func testCannotDecodeBasicOCSPResponseWithWrongOID() throws {
|
||||
let bytes = ASN1.OCSPResponseBytes(responseType: .AlgorithmIdentifier.idEcPublicKey, response: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]))
|
||||
XCTAssertThrowsError(try ASN1.BasicOCSPResponse(decoding: bytes))
|
||||
}
|
||||
|
||||
func testOCSPResponseStatusRoundTrips() throws {
|
||||
let fixtures: [ASN1.OCSPResponseStatus] = [
|
||||
.successful,
|
||||
.malformedRequest,
|
||||
.internalError,
|
||||
.tryLater,
|
||||
.sigRequired,
|
||||
.unauthorized,
|
||||
]
|
||||
|
||||
for fixture in fixtures {
|
||||
try self.assertRoundTrips(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
func testOCSPResponseStatusRefusesToDeserializeOutOfBandValues() throws {
|
||||
var serializer = ASN1.Serializer()
|
||||
try serializer.serialize(Int(4))
|
||||
|
||||
XCTAssertThrowsError(try ASN1.OCSPResponseStatus(asn1Encoded: serializer.serializedBytes))
|
||||
}
|
||||
|
||||
func testOCSPResponse() throws {
|
||||
let fixtures: [ASN1.OCSPResponse] = [
|
||||
.init(responseStatus: .successful, responseBytes: nil),
|
||||
.init(responseStatus: .malformedRequest, responseBytes: nil),
|
||||
.init(responseStatus: .successful, responseBytes: ASN1.OCSPResponseBytes(responseType: .AlgorithmIdentifier.idEcPublicKey, response: ASN1.ASN1OctetString(contentBytes: [1, 2, 3, 4]))),
|
||||
]
|
||||
|
||||
for fixture in fixtures {
|
||||
try self.assertRoundTrips(fixture)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import SwiftASN1
|
||||
@testable import X509
|
||||
|
||||
final class SignatureTests: XCTestCase {
|
||||
func testP384Signature() throws {
|
||||
// This is the P384 signature over LetsEncrypt Intermediate E1.
|
||||
let signatureBytes: [UInt8] = [
|
||||
0x30, 0x64, 0x02, 0x30, 0x7B, 0x74,
|
||||
0xD5, 0x52, 0x13, 0x8D, 0x61, 0xFE, 0x0D, 0xBA, 0x3F,
|
||||
0x03, 0x00, 0x9D, 0xF3, 0xD7, 0x98, 0x84, 0xD9, 0x57,
|
||||
0x2E, 0xBD, 0xE9, 0x0F, 0x9C, 0x5C, 0x48, 0x04, 0x21,
|
||||
0xF2, 0xCB, 0xB3, 0x60, 0x72, 0x8E, 0x97, 0xD6, 0x12,
|
||||
0x4F, 0xCA, 0x44, 0xF6, 0x42, 0xC9, 0xD3, 0x7B, 0x86,
|
||||
0xA9, 0x02, 0x30, 0x5A, 0xB1, 0xB1, 0xB4, 0xED, 0xEA,
|
||||
0x60, 0x99, 0x20, 0xB1, 0x38, 0x03, 0xCA, 0x3D, 0xA0,
|
||||
0x26, 0xB8, 0xEE, 0x6E, 0x2D, 0x4A, 0xF6, 0xC6, 0x66,
|
||||
0x1F, 0x33, 0x9A, 0xDB, 0x92, 0x4A, 0xD5, 0xF5, 0x29,
|
||||
0x13, 0xC6, 0x70, 0x62, 0x28, 0xBA, 0x23, 0x8C, 0xCF,
|
||||
0x3D, 0x2F, 0xCB, 0x82, 0xE9, 0x7F
|
||||
]
|
||||
let signature = try Certificate.Signature(
|
||||
signatureAlgorithm: .ecdsaWithSHA384,
|
||||
signatureBytes: ASN1.ASN1BitString(bytes: signatureBytes[...])
|
||||
)
|
||||
guard case .p384 = signature.backing else {
|
||||
XCTFail("Invalid signature decode")
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: test that the signature is valid over the TBSCertificate.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftCertificate open source project
|
||||
//
|
||||
// Copyright (c) 2022 Apple Inc. and the SwiftCertificate project authors
|
||||
// Licensed under Apache License v2.0
|
||||
//
|
||||
// See LICENSE.txt for license information
|
||||
// See CONTRIBUTORS.md for the list of SwiftCertificate project authors
|
||||
//
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import XCTest
|
||||
import SwiftASN1
|
||||
@testable import X509
|
||||
|
||||
final class TimeTests: XCTestCase {
|
||||
func testConvertUTCTimeToDate() throws {
|
||||
// 2022-07-01 12:15:55 corresponds to 1656677755 seconds from 1970.
|
||||
let utctime = try ASN1.UTCTime(year: 2022, month: 07, day: 01, hours: 12, minutes: 15, seconds: 55)
|
||||
let expected = Date(timeIntervalSince1970: 1656677755)
|
||||
XCTAssertEqual(expected, Date(utctime))
|
||||
}
|
||||
|
||||
func testConvertGeneralizedTimeToDate() throws {
|
||||
// 2022-07-01 12:15:55 corresponds to 1656677755 seconds from 1970.
|
||||
let generalizedTime = try ASN1.GeneralizedTime(year: 2022, month: 07, day: 01, hours: 12, minutes: 15, seconds: 55, fractionalSeconds: 0.0)
|
||||
let expected = Date(timeIntervalSince1970: 1656677755)
|
||||
XCTAssertEqual(expected, Date(generalizedTime))
|
||||
}
|
||||
|
||||
func testConvertUTCTimeAsTimeToDate() throws {
|
||||
// 2022-07-01 12:15:55 corresponds to 1656677755 seconds from 1970.
|
||||
let utctime = try ASN1.UTCTime(year: 2022, month: 07, day: 01, hours: 12, minutes: 15, seconds: 55)
|
||||
let time = Time.utcTime(utctime)
|
||||
let expected = Date(timeIntervalSince1970: 1656677755)
|
||||
XCTAssertEqual(expected, Date(time))
|
||||
}
|
||||
|
||||
func testConvertGeneralizedTimeAsTimeToDate() throws {
|
||||
// 2022-07-01 12:15:55 corresponds to 1656677755 seconds from 1970.
|
||||
let generalizedTime = try ASN1.GeneralizedTime(year: 2022, month: 07, day: 01, hours: 12, minutes: 15, seconds: 55, fractionalSeconds: 0.0)
|
||||
let time = Time.generalTime(generalizedTime)
|
||||
let expected = Date(timeIntervalSince1970: 1656677755)
|
||||
XCTAssertEqual(expected, Date(time))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user