164 Commits
Author SHA1 Message Date
Nicolas Bachschmidt 87d0a2752b Support certificates with invalid RDN attribute values (#214)
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.
2024-12-17 18:25:36 +00:00
Clinton Nkwocha 5fd8063331 Enable strict concurrency (#213)
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.
2024-12-13 18:24:01 +00:00
Jon C. Thomason d4d564670a Add support for attached signatures (#201) (#206)
* 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
2024-11-22 10:54:27 +00:00
Luke Howard 2be7251a3a Android build fixes (#207) 2024-11-08 11:31:34 +00:00
Cory Benfield 27c6b0fcfa Add support for Ed25519 certificates (#205)
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
2024-10-30 13:30:13 +00:00
Franz Busch c0b6a47ffe [CI] Adopt GitHub actions (#193) 2024-10-21 16:01:05 +01:00
Cory Benfield 1fbb6ef21f Avoid the macOS requirement. (#204) 2024-10-15 13:19:03 -07:00
d8799da503 Support SecKey Certificate private keys (#195)
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>
2024-10-02 16:40:39 +01:00
finagolfin a846fc7149 Add support for Android (#183) 2024-09-12 02:35:46 -07:00
Mark SchallandFranz Busch abe0f0b248 Fixing SHA512 in comment (#196)
Co-authored-by: Franz Busch <f.busch@apple.com>
2024-09-11 05:37:44 -07:00
Cory Benfield 387fb97cf6 Stop implicitly tagging DistinguishedName (#188)
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.
2024-08-15 20:11:51 +01:00
aryan-25 2f797305c1 Add bridge between Certificate and Security.SecCertificate (#182)
* 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.
2024-07-02 08:31:19 -07:00
Micah MooreandCory Benfield 44f2a33ec3 Adds support for including signing time in signedAttrs for CMS signing. (#176)
* 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>
2024-06-21 11:38:32 +01:00
Przemysław Lenart be1264c502 Add missing import statement. (#180) 2024-06-20 16:09:06 +01:00
hamzahrmalikandCory Benfield d93756ba92 Allow OneOfPolicies and AllOfPolicies to take throwing policy builders, to match Verifier (#173)
* 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>
2024-05-17 10:04:40 -07:00
Nicolas Bachschmidt 6f2dc4affc Use case-insensitive comparison when validating cert domain name (#175) 2024-05-15 13:58:23 -07:00
hamzahrmalik 83640c8097 Add OneOfPolicies and AllOfPolicies (#172)
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
2024-05-01 16:48:25 +01:00
Cory Benfield 4975de4e97 Add support for validating server hostnames and IP addresses (#171)
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.
2024-04-22 16:24:19 +01:00
David Nadoba 5194b38d36 Fix Sendable warnings from latest main compiler (#166)
* Fix `Sendable` warnings on main

* remove `@preconcurrency` from `import _CryptoExtras`

* move documentation to extensions
2024-03-21 18:14:07 +00:00
David Nadoba d71e4c4261 CountryName should be a PrintableString RDNA (#165) 2024-03-21 16:38:30 +01:00
David NadobaandCory Benfield bc566f8884 Simplify the internal representation of RDN.Attribute.Value (#156)
* Simplify the internal representation of RDNAttribute.Value

Motivation

The 1.1.0 release included a patch (#154) that supported converting
RDNAttribute values into strings. This patch missed that the `.any`
case may also have strings in it.

While investigating this limitation, I realised that the constructor
function was excessively complex. While it attempted to coerce based
on extra information in the ASN.1 specification, it always fell back
into the `.any` case. This meant that as a practical matter we always
took the same few paths, and so could safely simplify the code.

Modifications

Simplify DER decoding of RDNAttribute.Values.
Introspect the .any cases for UTF8 strings and Printable strings
when converting to String.

Result

Faster construction, more flexible representation.

* normalise `RDN.Value.Storage` representation

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-12-05 16:15:19 -08:00
David Nadoba 66143b83e0 Move ExpressibleByArrayLiteral conformance of _TinyArray to the declaring module (#157)
Motivation

Nightly compilers start complaining about retroactive conformances.

Modifications

- move conformance to declaring module
- optimise code to not allocate

Result

no warning, optimal generated code for:

```swift
func foo1(int: Int) -> _TinyArray<Int> {
    [int]
}
```

compiles down to:
```
output.foo1(int: Swift.Int) -> output._TinyArray<Swift.Int>:
        mov     rax, rdi
        xor     edx, edx
        ret
```

https://godbolt.org/z/a91fPe6or
2023-12-05 18:19:37 +00:00
Cory Benfield 4ff26ad6cc Support converting RDNAttribute values into Strings (#154)
Motivation

RDNAttribute Values are mostly strings, and it's useful to be able
to convert them. This patch adds that support.

Modifications

Add support for converting RDN attribute values into Strings.

Result

Easier to work with distinguished names.
2023-12-01 05:03:37 -08:00
David Zech 5afc92197a Add Expanded CMS Support (#151)
* Support BER Encoded CMS
* Support Attached CMS
* Support Signed Attributes CMS
2023-10-25 16:19:41 +01:00
David Nadoba 3c33085404 Support loading trust root CAs on Linux (#136)
* Support loading trust roots on Linux

* Fix linux

* run `swift-format`

* Apply review feedback

* Implement `_TinyArray2`

* fix tests

* Update benchmarks for _TinyArray2

* run swift-format

* use two properties instead of TinyArray2

* remove usage of `_TinyArray2` and rename `insert` to `append`

* remove TinyArray2 and rename TinyArray1 back to just TinyArray

* run swift-format

* fix tests

* Fix review comments
2023-10-18 14:01:10 +01:00
David Nadoba 50ec4771c2 Add the diagnosticCallback to CMS.isValidSignature (#135)
* Allow setting `diagnosticCallback ` for `CMS.isValidSignature`

* swift-format
2023-09-18 15:44:29 +01:00
Alexander Cyon 216a8a1166 Fix typos in Sources and Tests (#133)
* Fix typos in Sources and Tests

* Address PR review comments

* Second attempt to rectify tab instead of spaces.
2023-09-04 10:34:25 +01:00
David Nadoba ef10b819c7 Add Certificate.PrivateKey description (#132)
* Add `Certificate.PrivateKey` description

and update `Certificate.PublicKey` description to disambiguate from private keys.

* secure enclave is only a thing on darwin

* update tests
2023-08-25 08:32:40 +01:00
Stefana-Ioana DrancaandDavid Nadoba 44a0c84fce Make PublicKey DERImplicitlyTaggable (#129)
Motivation:

PublicKey doesn't conform to DERImplicitlyTaggable which was an oversight during development.

Modifications:

Add conformance to DERImplicitlyTaggable, PEMSerializable, and PEMParsable.

Result:

PublicKey is DERImplicitlyTaggable.

Co-authored-by: David Nadoba <d_nadoba@apple.com>
2023-08-24 15:09:43 +01:00
David NadobaandCory Benfield 0a44251615 Fix preference of root certificates (#127)
Motivation

We prefer issuers that have a subject key identifier that matches the authority key identifier of the certificate for which were are searching for an issuer. However, currently we have flipped this sort order.

Modifications

Flip preference order
update test
add test which would previously fail

Result

We actually prefer certificates in the order described above.
Note that this is just a performance improvement.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-08-24 06:32:50 -07:00
David Nadoba 26832755b5 Refactor ASN1UTF8StringView to ASN1TaggedStringView and use it for printable strings (#128)
* Refactor `ASN1UTF8StringView` to `ASN1TaggedStringView` and use it for `printable` strings

* run swift-format

* fix comments
2023-08-24 14:13:58 +01:00
David Nadoba 92ffb4827b Add PolicyFailureReason to support lazy failure reason string interpolation (#126)
* Add `PolicyFailureReason` to support lazy failure reason string interpolation

* fix allocation test compilation

* update allocation counters
2023-08-21 20:01:19 +01:00
David Nadoba b69a931b43 remove deprecated API (#123) 2023-08-21 06:32:51 -07:00
David Nadoba 1442890101 Allow RelativeDistinguishedNameConvertible to fail gracefully (#122) 2023-08-16 13:01:49 +01:00
David Nadoba 45ad9935c7 Adopt apple/swift-format (#121)
* Adopt `apple/swift-format`

* install swift-format

* set `UseSynthesizedInitializer` to `false` until bug is fixed https://github.com/apple/swift-format/issues/591

* fix license header

* Fix license header
2023-08-16 11:17:34 +01:00
David NadobaandCory Benfield 98e0f85457 Do not count self-issued certificates against maxPathLength (#119)
Only non-self-issued certificates count against the maxPathLength limit.

RFC Section 4.2.1.9.  Basic Constraints:

> [...]
> The pathLenConstraint field is meaningful only if the cA boolean is
> asserted and the key usage extension, if present, asserts the
> keyCertSign bit (Section 4.2.1.3).  In this case, it gives the
> maximum number of non-self-issued intermediate certificates that may
> follow this certificate in a valid certification path.  (Note: The
> last certificate in the certification path is not an intermediate
> certificate, and is not included in this limit.  Usually, the last
> certificate is an end entity certificate, but it can be a CA
> certificate.)  A pathLenConstraint of zero indicates that no non-
> self-issued intermediate CA certificates may follow in a valid
> certification path.  Where it appears, the pathLenConstraint field
> MUST be greater than or equal to zero.  Where pathLenConstraint does
> not appear, no limit is imposed.
> [...]
> https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-08-10 03:58:44 -07:00
David Nadoba 21a8721886 Reject v1 Certificates with extensions (#118)
v1 certificates do not support extensions and any v1 certificate we encounter with extensions can’t be used to verify a chain.
2023-08-10 11:43:21 +01:00
David Nadoba 619756c18f Add custom String representation to Certificate and related types (#116)
* `Custom[String|DebugString]Convertible` conformance

* save progress

* Apply new learned rules

debugDescription should be usable in structural display

* remove unused init

* remove unused properties

* Some fixups before review

* change description a bit around and respect RFC 2253

* add addition test

* fix license header and tests

* update allocation counters
2023-08-09 08:30:09 +01:00
David Nadoba 583414dad1 Make debugDescription work well as part of a structural display (#115)
### Motivation

`debugDescription` name and documentation is confusing and should be changed but it is today expected to be suitable to be used as part of a structured display e.g. to be printed as part of `struct` or `enum` with associated values. Therefore it should have no unpaired parentheses, no unescaped quotes and no top-level commas.

### Modifications
- let `debugDescription` simply contain the same contents as `description` but suitable for structural display as described above.
- add a new `multilineDescription` which contains the same contents as the `description` but breaded down on multiple lines for better readability.
2023-08-07 11:48:43 +01:00
David Nadoba 8debe3f20d Add optional diagnostic information to Verifier (#113)
* work in progress

* remove generic

* save progress

* Add description

* Apply review feedback

* run `./scripts/update_cmakelists.sh`

* Conform to `CustomDebugStringConvertible` instead of `CustomStringConvertible`

* implement `CustomStringConvertible` for `VerificationDiagnostic`

* Apply review feedback

* Add more diagnostics

* Update tests

* Remove prototype code

* add `IssuerIsAlreadyInTheChain` diagnostics
2023-07-27 09:46:07 +01:00
David Nadoba 5f82c70d24 Make hashing a RDN.Attribute.Value.utf8String not allocate (#112)
* Make hashing a `RDN.Attribute.Value.utf8String` not allocate

* Precompute as much as possible

and fix bounds checking

* Update allocation counter
2023-07-20 09:59:29 +01:00
David Nadoba 1db96874fa Remove unused import (#110) 2023-07-10 05:13:21 -07:00
David NadobaandFranz Busch fb7b79f346 Allow OCSPRequester to fail OCSPVerifierPolicy (#108)
* Support hard failures from OCSPRequester

* rename error result methods to nonTerminalError and terminalError from softFailure and harFailure

* rename query result in tests as well

* Update Sources/X509/OCSP/OCSPPolicy.swift

Co-authored-by: Franz Busch <privat@franz-busch.de>

* Add warning

---------

Co-authored-by: Franz Busch <privat@franz-busch.de>
2023-07-06 14:50:21 +01:00
David Nadoba 1849f5274a Store String in RelativeDistinguishedName.Attribute instead of ASN1Any if possible (#104)
* Store `String` in `RelativeDistinguishedName.Attribute` instead of `ASN1Any` if possible

* Add Equatable and Hashable test

* fix typo

* remove trys

* Apply review feedback

* update allocation numbers
2023-07-06 14:10:54 +01:00
David Nadoba 290123d2e9 Do not allocate for RelativeDistinguishedNames with just a single attribute (#101)
* Setup allocation test framework

* Add allocation test that decodes all WebPKI Roots

* Replace _WebPKI with inline PEM strings

* Fix test

* implement `TinyArray`

* save progress with local ASN.1 dependency

465 allocs

* Implement lazySet in swift-certificates

* test on all WebPKI roots

* Revert "test on all WebPKI roots"

This reverts commit 4af11bb087.

* remove PerformanceTests

* Add tests for TinyArray

* revert changes

* delete unused test

* Implement TinyArray

* update cmake

* “Hide” enum and support storing arrays of exactly one element in `.arbitrary`

* Add allocation tests for TinyArray

* make arrays of different sizes

* Remove array optimisation

* run append in a loop

* Move _TinyArray into a separate module

and apply review feedback

* update cmake files

* remove unused Foundation import

* Allocations are lower by “1” on Linux

* import new module

* Add loop

* update allocation numbers for Linux

* replace with do/catch with try!

* Fix copyright

* update allocations

* Move lazySet to swift-asn1

* update allocation counters

* Fix `update-alloc-limits-to-last-completed-ci-build`

* Use concrete type
2023-07-05 11:47:57 +01:00
David Nadoba edf406c600 Add integer initialisers on Certificate.SerialNumber (#106)
* Add integer initialisers on `Certificate.SerialNumber`

`Certificate.SerialNumber` can now be constructed from any `FixedWidthInteger` and also from `StaticBigInt`

* `StaticBigInt` is only available in Swift 5.8

* Do not realloc storage if we trim leading zeros
2023-06-30 12:15:07 +01:00
David Nadoba e8f5dadf79 Conform AuthorityInformationAccess to RangeReplaceableCollection (#105) 2023-06-29 06:22:43 -07:00
Max Desiatov 1beb546810 Add support for Musl libc (#103)
Since Musl is sufficiently different from Glibc (see https://wiki.musl-libc.org/functional-differences-from-glibc.html), it requires a different import, which now should be applied to files that have `import Glibc` in them.
2023-06-23 11:29:15 +01:00
Franz Busch 69def44d75 Use #if canImport(Darwin) where possible (#102) 2023-06-21 14:24:35 +02:00
David Nadoba 41dff30819 Implement TinyArray (#98)
* Implement TinyArray

* update cmake

* “Hide” enum and support storing arrays of exactly one element in `.arbitrary`

* Add allocation tests for TinyArray

* make arrays of different sizes

* Remove array optimisation

* run append in a loop

* Move _TinyArray into a separate module

and apply review feedback

* update cmake files

* remove unused Foundation import

* Allocations are lower by “1” on Linux
2023-06-20 01:51:53 -07:00