Motivation
We have a check that requires that the bit strings for Ed25519
signatures don't have any padding bits. That check is good, but the same
check should have been applied to all the signatures, and it wasn't.
There is no particular security risk with this: while it allows moderate
signature malleability (as we accept multiple signatures that have
different bits as equally valid), there is no way we can conceive of to
launch an attack based on this malleability: the signature itself needs
to remain valid. The only note is that the representation differs.
Modifications
Centralise the check and apply it to all the code paths. Make sure the
OCSP code doesn't lose track of whether there was any padding.
Add tests for the OCSP verifier and the signature code directly.
Result
No more signature malleability.
### Motivation
`NameConstraintsPolicy` read an all-zero CIDR mask as matching nothing.
An all-zero mask constrains no bits, so it matches every address: the
CA/Browser Forum Baseline Requirements express "this subordinate CA must
not issue for IP addresses" as `excludedSubtrees` of `0.0.0.0/0` and
`::/0`, and against this code those exclusions constrained nothing, so a
leaf with an IP SAN under such a CA verified.
### Modifications
The leading-zero shortcut in `isValidCIDRMask` is removed and the
general leading-ones-then-zeros check decides. The two
`IPAddressNameTests` rows that pinned the old reading now expect a
match. `testAllZeroMaskIsValidCIDRMask` asserts the IPv4 and IPv6
all-zero masks directly, and two `RFC5280PolicyTests1` tests run
`RFC5280Policy` with `0.0.0.0/0` and `::/0` as permitted and as excluded
subtrees. All of them fail on main.
### Result
A `/0` iPAddress constraint covers the whole address space, as RFC 5280
4.2.1.10 defines it. `swift test` passes under the CI flags (`-Xswiftc
-warnings-as-errors --explicit-target-dependency-import-check error
-Xswiftc -require-explicit-sendable`) on Swift 6.1.2; `swift-format lint
--strict` is clean on the changed files.
---------
Co-authored-by: Raphael Hiesgen <r_hiesgen@apple.com>
### Motivation
`CMSSignerInfo` could not round-trip `unsignedAttrs`: it serializes them
as `[1] IMPLICIT SET` but the DER and BER parsers asked for the inner
set with implicit tag `[0]`, so parsing any SignerInfo with unsigned
attributes threw `unexpectedFieldType: [1]`.
### Changes
Fixes issue #306 by:
- Correcting the `unsignedAttrs` inner set identifier from `[0]` to
`[1]` in the DER and BER initializers of `CMSSignerInfo`.
- Adding a round-trip unit test for a `CMSSignerInfo` carrying
`unsignedAttrs`.
### Result
`unsignedAttrs` now round-trip correctly; no behavior change to the
(already correct) serialized output.
## Motivation:
In some cases a developer may want to sign a certificate using a method
other than a private key. For example: if a private key is protected by
hardware which signs asynchronously.
## Modifications:
- Create `CustomPrivateKey` protocol
- Create `async` initializers for `Certificate` and
`CertificateSigningRequest`.
- `CustomPrivateKey` can now back a`Certificate.PrivateKey`
- Make `Certificate.Signature` initializer public
## Result:
Developers can now sign a certificate with greater flexibility.
## Alternatives Considered:
### Implementations
#### Pass the `CustomPrivateKey` into `Certificate` and
`CertificateSigningRequest` initializers directly.
There is concern this could add too much duplication of api.
### Various names for the protocol:
- `Certificate.PrivateKeyProtocol` and
`Certificate.AsyncPrivateKeyProtocol`
- `Certificate.Signer`/`Certificate.AsyncSigner`
- `Certificate.SignatureProvider`/`Certificate.AsyncSignatureProvider`
---------
Co-authored-by: Cory Benfield <cbenfield@apple.com>
When `signingTime` was provided to `CMS.sign`, the
`additionalIntermediateCertificates`
parameter was not being forwarded to `signWithSigningTime`, causing
signature verification
to fail for certificates that require an intermediate CA chain.
Fixes#287
### Motivation
Signatures can be performed on any kind of data, e.g., to prove
ownership of the private key for a given certificate. This data usually
comes as a blob of bytes.
### Modification
Add a signature verification function that operates on bytes represented
by the `DataProtocol`. The bytes are converted to the signature type
matching the key and share an implementation with the verification
function for `Certificate.Signature`.
### Result
Easy validation of signatures represented as bytes.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Swift 5.10 is no longer supported. We should raise the minimum Swift
tools version to 6.0, fix consequent build warnings/errors, and remove
5.10 CI jobs.
Modifications:
- Raised the Swift tools version to 6.0 in both the main
`swift-certificates` package and the Benchmark package.
- Removed the now redundant `StrictConcurrency=complete` flag in
`swift-certificates`' `Package.swift`.
- Removed 5.10 CI job arguments.
- Removed 5.10 benchmark thresholds.
- Added an explicit type annotation to the `package-benchmark` setup
closure to address a build error.
- Updated `VerifierBenchmark` to use newer, non-deprecated
`RFC5280Policy` initializers (as a result of #276).
- Updated a test case in `Tests/X509Tests/PEMTests.swift` to no longer
use a deprecated `String` initializer.
Result:
Code reflects our support window.
### Motivation:
When loading a private key from disk as a `Certificate.PrivateKey` there
is no straight forward way to query the supported signature algorithms.
For signature algorithm negotiation, the raw values defined in RFC are
useful as well.
### Modifications:
Add a new property to query the supported signature algorithms for a
given key. Add a new property that translates a signature algorithm to
the respective value defined in RFC 8446.
### Results:
Working with certificate private keys and signature algorithms gets
easier.
Motivation:
swift-crypto just added `derRepresentation` to
`Curve25519.Signing.PrivateKey`, however swift-certificates already
provides the same API internally but returning an array of bytes (as
opposed to Data). This causes ambiguity in the swift-certificates tests.
Modifications:
- Specify the type to disambiguate. We do this rather than using the new
API as swift-crypto has stricter availability requirements which we
don't need to impose on our tests.
Result:
No ambiguity
### Motivation:
New initializers for `ExpiryPolicy`, `RFC5280Policy`, and
`OCSPVerifierPolicy` were introduced in #266. These initializers were
added to prevent users from specifying `Date.now` as the time to
validate certificate expiry against. For context, the problem was that
`Date.now` would be evaluated at initialization, but validation could
occur at a later stage, at which point the validation time would become
stale.
These initializers had a `fixedValidationTime: Date? = nil` argument,
where a non-`nil` value denoted a *fixed* time to validate against, and
a `nil` value denoted that the current time, evaluated at the point of
validation, would be used for validation (the common case). Although the
dangers of specifying `fixedValidationTime = .now` were documented, in
practice, it is very easy for users to miss this and continue using the
API in an incorrect way.
Given that most users will validate certificate expiry against the
current time, we want to default to this and remove the validation time
argument from the public initializers entirely. Users who want to
specify a fixed predetermined time **must explicitly opt-in** by using
`@_spi(FixedExpiryValidationTime)` to access the initializers that have
a *non-optional* `fixedExpiryValidationTime` argument.
### Modifications:
- Deprecated the initializers of `RFC5280Policy` and
`OCSPVerifierPolicy` and introduced two new initializers for each: one
without a validation time argument (common case), and one with a
*non-optional* validation time argument guarded behind an SPI
- Updated the initializers of `ExpiryPolicy` (an internal type)
- Additional changes:
- Updated test cases to use new initializers
- Updated examples in documentation to use new initializers
### Result:
`RFC5280Policy` and `OCSPVerifierPolicy` can be used more safely
### Motivation:
The certificate chain returned by validation has properties that are
currently not expressed in the API. Introducing a type that does so
allows other APIs to build on these properties.
### Modifications:
* Add a new `ValidatedCertificateChain` type and use it as a result type
for certificate validation. Since a validated chain always has at least
a leaf and a root, the type gives direct access to them.
* Deprecate the previous validate function and introduce a replacement.
Update use of the now-deprecated API and duplicate tests to include both
APIs.
### Result:
Certificate validation returns a type that conceptually holds meaning.
## Motivation:
The initializers of `RFC5280Policy` and `OCSPPolicy` require a
validation time as an argument. If this argument is set to `Date.now`,
the timestamp would be captured at the point of initialization. As such,
if the validation method is invoked on the policy instance long after
initialization, the timestamp can become stale at that point. This means
that the validation function could incorrectly determine a certificate
(`RFC5280Policy`) or an OCSP response (`OCSPPolicy`) to be valid, when
it has actually expired by the time the validation is performed.
This is not an issue in common use-cases where the policy is initialized
(with `validationTime` set to `.now`) inside a `PolicyBuilder` closure,
because the closure is evaluated at the point of validation. However,
some use-cases may initialize the policy independently; the issue can
potentially arise here.
## Modifications:
This patch deprecates the current initializers of `RFC5280Policy` and
`OCSPPolicy` to guide users toward using a safer initializer which
requires a `fixedValidationTime: Date?` argument:
- Passing `nil` (default) will lead to the current time being obtained
*at the point of validation*. This will prevent the bug described above.
- Passing a specific `Date` instance preserves the ability to validate
against a fixed point in time, i.e. a time in the past or future, but
*not* the current time.
## Result:
Users now have the option to use a safer initializer to construct
`RFC5280Policy` and `OCSPPolicy`.
This PR introduces two key changes to improve flexibility when working
with signatures in swift-certificates. Previously, it was only possible
to verify signatures using `Certificate.PrivateKey`, but not to generate
them.
- The internal `sign(bytes:signatureAlgorithm:)` method on
`Certificate.PrivateKey` is now public, allowing users to generate
signatures directly.
- `Certificate.Signature` gains a new `rawRepresentation` property that
exposes the raw byte representation of a signature.
This change adds support for implementing a `CustomCertificateStore` in
a backwards compatible way with minimal impact to performance. A custom
certificate store can be implemented, and then the new
`CertificateStore(custom:)` constructor can be used so that the custom
certificate store can be used interchangeably with a "normal"
certificate store.
Additionally, a test case verifies that this new protocol will work for
our use case. More specifically, the use case we have is for
normalization of distinguished names so that an exact match of
distinguished names is no longer required. For example, if
`printableString` should be used interchangeably with a `utf8String`.
This pull request has two commits:
- One that adds support for a `CustomCertificateStore`
- One that modifies the implementation to support `async` lookup of
certificiates.
The second change is not required for our use-case, however I would
expect that there may be a future use-case that requires looking up
certificates in a database, and supporting an `async` protocol would be
valuable. Also, the `verify()` method is already async, so supporting an
`async` lookup does not disrupt any existing public APIs.
Base on `macOS 11 and iOS 14 (iPadOS 14)`, I think the correct is
`macCatalyst 14` . Maybe it is a copy issue above available condition in
this file `@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4,
macCatalyst 16.4, visionOS 1.0, *)` .
Motivation:
Swift 5.9 is no longer supported, we should bump the tools version and
remove it from our CI.
Modifications:
* Bump the Swift tools version to Swift 5.10
* Remove Swift 5.9 jobs where appropriate in main.yml, pull_request.yml
Result:
Code reflects our support window.
Add capability of converting RDN value of ASN1IA5String to String, if I
am correct all RFC expect that RDN value can be ASN1IA5String..
- additionally fix tests after this change
- added DN components emailAddress(E) and domainComponent(DC)
Most of the time, the signature algorithm that should be used is
dictated by the type of the private key.
* Ed25519 keys support only one signature algorithm.
* RFC 5753 section 8 recommends that "[the P-256 curve] be used with
SHA-256; the P-384 curve be used with SHA-384; and the P-521 curve be
used with SHA-512".
* RSA keys support 4 signature algorithms. But most people use RSA with
SHA-256 and nobody should use RSA with SHA-1 anymore.
More over, Certificate.PrivateKey is opaque to the user, who may not
know what type of private key they're using and what the appropriate
signature algorithm is.
For those reasons, we add convenience wrappers around methods with a
signature algorithm to provide a reasonable default value.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Per [RFC 5652 §
11.2](https://datatracker.ietf.org/doc/html/rfc5652#section-11.2):
"For signed-data, the message digest is computed using the signer's
message digest algorithm."
Currently, when computing the signed attributes' message digest,
`CMS.sign` assumes the digest algorithm is SHA256, which is incorrect.
The behavior of `CMS.isValid` is already correct and doesn't need
updating. I've made `Digest` conform to `Sequence` to facilitate the
conversion/comparison of the message digest.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Some certificate authorities issue certificates with invalid RDN
attribute values. Certificates must use UTF8String instead of
PrintableString to represent strings that contains `*` or `@`, but
mistakes happen.
When a RDN attribute value is a PrintableString or UTF8String with an
invalid content, rather than rejecting the certificate, fall back to
storing the value as an Any.
## Rationale
Certificate authorities using the wrong string type is a common mistake.
For example, DigiCert issued intermediate certificates with invalid
ampersands to Wells Fargo & Company (golang/go#22970).
This PR adds *partial* support for certificates that contain invalid
PrintableString or UTF8String (less likely) values. When failing to
parse a PrintableString or UTF8String, the raw bytes are stored as an
Any (same as IA5String, BMPString, ...).
Though those certificates are now parsed without any error, they aren't
fully supported yet. Trying to convert the value to a String returns
`nil`, so the CN doesn't match. I don't know whether we should add
support for converting invalid PrintableString values (and
IA5String/BMPString/...) to String in the future. In the meantime,
developers who want to read the CN have access the raw Any value.
Motivation:
To catch potential data races at build time.
Modifications:
- Bump Swift tools version from 5.8 to 5.9 in Package.swift.
- Enable strict concurrency in Package.swift.
- Adjust the documentation section on the supported Swift versions.
- Implement minor fixes for the surfaced strict concurrency warnings.
- Add `-require-explicit-sendable` to the 6.0, nightly 6.0 and nightly
main CI checks.
Result:
Strict concurrency adoption.
Motivation:
The test fails when the local machine is not set to 24-hour time.
Modifications:
- Adjust the test to use dynamic time values based on Foundation's
`Date` instead of hard-coded time strings.
Result:
A non-flaky test.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Enable MemberImportVisibility check on all targets. Use a standard
string header and footer to bracket the new block for ease of updating
in the future with scripts.
* Add support for attached signatures (#201)
* Relay detachment through with signing time
* Factor attachment into generateSignedData
* Adjust test coverage
* Test verifying an attached signature
* Test verifying an attached signature and timestamp
* Test failing detached signature as attached
* Test failing detached timed signature as attached
* Test accepting attached signature as detached
* Test accepting attached timed signature as detached
Motivation
While Ed25519 is not available in the WebPKI, there
are a number of contexts where it's an appropriate
signature algorithm for X.509. In those contexts,
we should allow the signature algorithm.
Modifications
Add support for Ed25519 keys and signatures.
Add unit tests
Result
Ed25519 support in the X509 certs
Motivation:
I would like to create Certificates using a SecKey so that I can create certificates signed by hardware-backed keys. Currently, Swift Certificates requires the private key be provided in an exported representation, but this isn't possible when a SecKey is marked as non-exportable.
Modifications:
Adds a new SecKeyWrapper backing to Certificate.PrivateKey to support initalisation with SecKey. This wrapper struct handles key validation and signing operations by calling the appropriate SecKey interfaces. Adds additional tests to support new backing type.
Result:
Certifcate.PrivateKey can be initialised with a SecKey, allowing existing hardware-backed SecKey instances to be used as the issuer private key for new Certificate instances.
Co-authored-by: Rory Smith <rory.s@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Crypto does not yet support concurrency.
Modifications:
Change Crypto imports where necessary to import
with preconcurrency flag.
Result:
Fewer warnings in swift 6.
Motivation:
This is consistent with what underlying assert does.
Swift 6 warns about this mismatch
Modifications:
Use filePath for test assert location
Result:
Consistency in test assert location reportin
DistinguishedName was incorrectly marked DERImplicitlyTaggable,
but it isn't. DistinguishedName is our name for Name, which is
an untagged choice type. Untagged choice types can never be
implicitly tagged.
* Add bridge between Certificate and Security.SecCertificate
* Add documentation for explaining the bridge between `Certificate` and `Security.SecCertificate`. Add `make` prefix to `SecCertificate` factory method.
* Adds support for including signing time in signedAttrs for CMS signing.
Motivation:
Many CMS signing validations require the inclusion of signing time in signedAttrs (for example Apple Wallet's Pass CMS signing validation)
Modifications:
* Adds optional includeSigningTime flag to CMS.sign method (defaults to false)
* When includeSigningTime flag is true: includes signing-time (UTCTime ASN1Type), content-type, and message-digest signedAttrs and signs those instead of content bytes (as specified in RFC 5652 section 5.4)
* Adds contentType ASN1ObjectIdentifier
* Adds CMSSigningError (noTimeZone, invalidSigningDateComponent) for when includeSigningTime is true and unable to get UTC time zone or date components
* Adds tests for valid and invalid CMS signature when including signedAttrs
Result:
Providing the includeSigningTime = true flag to CMS.sign will cause signing-time, content-type, and message-digest signedAttrs to be included in the CMS signature and the signature bytes will represent signing those signedAttrs. Using CMS.sign without the flag (defaulting to false) should leave the previous CMS.sign behavior unchanged.
* Improvements to inclusion of signing time in signedAttrs of CMS signing.
Motivation:
Callers may want to provide their own signingTime (Date). Code improvements for inclusion of singing time in signedAttrs.
Modifications:
* Changes CMS.sign method to take Date? instead of Bool for signingTime so callers can provide their own signingTime Date
* Adds internal method CMS.signWithSigningTime to separate logic for CMS signing with signingTime in signedAttrs
* Uses Date.utcDate transformation to get DateComponents instead of manually constructing them within CMS.signWithSigningTime
* Removes CMSSigningError from CMSOperations as its no longer needed after removal of manual DateComponents construction
* Switches message digest SHA256 from using unsafe bytes to converting Sequence<UInt8> to ArraySlice directly
Result:
CMS.sign callers can now provide signingTime (Date). CMS.sign with signingTime signedAttrs code is improved.
* Adds explicit self to internal signing method calls within CMSOperations.
Motivation:
Conform to standards regaring usage of explicit self for internal methods calls.
Modifications:
* Adds explicit self to signWithSigningTime and serializeSignedData internal methods calls with CMSOperations
Result:
Internal CMSOperations method calls are now compliant to standards.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
* Allow OneOfPolicies and AllOfPolicies to take throwing policy builders, to match Verifier
* add tests
* avoid api break
* soundness
* fix
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Created a new OneOfPolicyBuilder
This is similar to the existing PolicyBuilder
The difference is that the new OneOfPolicyBuilder requires only one of the child policies to be valid, not necessarily all of them
A new struct, OneOfPolicies implements VerifierPolicy and can be constructed using OneOfPolicyBuilder
This can be used within a larger policy e.g.
let x = Verifier(rootCertificates: .init([])) {
RFC5280Policy(validationTime: .init()) // this must be met
OneOfPolicies {
SomethingPolicy() // one of these 2 must be met
SomethingElsePolicy() // one of these 2 must be met
}
}
The verifyingCriticalExtensions of OneOfPolicies is intersection of the verifyingCriticalExtensions of each of the child policies, because the overall policy will only be guaranteed to verify an extension if every child policy does so, because we don't know which child policies will actually be evaluated (we stop evaluating when any one passes)
OneOfPolicies will only fail if all of the child policies fail. In this case, the failure reason will be a concatenation of all the child failure reasons, with the word 'and' in between them
This PR also introduces AllOfPolicies
This is to allow users to specify a set of policies which must always be set, as a single item within a OneOfPolicies
Motivation
To make Swift Certificates useful for the Web PKI it's vital
that we can validate that a particular certificate is authoritative
for a specific domain. This requires a new verifier policy.
Modifications
Added ServerIdentityPolicy
Added tests
Result
We can validate the identity of remote servers.