When building the byte view of a subject alternative name, NIOSSL reads
the `ASN1_STRING` member of the BoringSSL `GENERAL_NAME` union for every
entry without checking the name's type. The union only holds an
`ASN1_STRING` for the string-shaped GeneralName types (`dNSName`,
`rfc822Name`, `uniformResourceIdentifier`, `iPAddress`). For the other
types (`otherName`, `x400Address`, `directoryName`, `ediPartyName`,
`registeredID`) the union holds a different structure, so this reads the
buffer's base pointer and length out of unrelated memory.
The SAN list is parsed from an X.509 certificate, which is untrusted in
the usual TLS/mTLS case, and `contents` is reachable through the public,
albeit underscored, `_subjectAlternativeNames()` API.
NIOSSL should only interpret the union as an `ASN1_STRING` for the
string-shaped types and expose empty contents for the rest.
- In `_SubjectAlternativeNames.Storage.subscript`, switch on the GeneralName
type. Build the `ASN1_STRING`-backed byte buffer only for `dNSName`,
`rfc822Name`, `uniformResourceIdentifier` and `iPAddress`; expose an empty
buffer for every other type.
- Add a test that parses a certificate carrying an `otherName` SAN followed by a
`dNSName`, asserting the `otherName` has empty `contents` while the `dNSName`
is read normally.
Reading the `contents` of a non-string subject alternative name no longer reads
out of bounds; it returns empty. String-typed names are unaffected. NIOSSL's
built-in identity verification already filters by name type, so the default
handshake path was not affected; this fixes the behaviour for callers of
`_subjectAlternativeNames()` that read `contents` for arbitrary name types.
### Motivation
When a PSK cipher suite is negotiated on the client, BoringSSL's
gives our callback a buffer of length `PSK_MAX_IDENTITY_LEN` + 1, and
passes its full size as `max_identity_len`. The callback is expected to
populate the identity with a NUL-terminated string, which is relied upon
by the subsequent BoringSSL code, which calls `strdup`. However, our
code guarded the adopter-provided identity against the
`max_identity_len`, without taking into account the space for the NUL,
so it permitted identities of length `PSK_MAX_IDENTITY_LEN` and
clobbered the NUL, leading to UB.
### Modifications
- In `clientPSKCallback`, reject identities whose length is `>=
max_identity_len` (was `>`).
- NUL-terminate the copied identity explicitly. BoringSSL is
zero-initialising the buffer, but it's not documented to behaviour and
it doesn't hurt for us to be safe.
- Add a test that shows we accept an identity of `PSK_MAX_IDENTITY_LEN`
- Add a test that shows we reject an identity of `PSK_MAX_IDENTITY_LEN`
+ 1 bytes (previously accepted).
### Result
An adopter-supplied PSK client identity of exactly `max_identity_len`
bytes is now rejected instead of triggering an out-of-bounds read in
BoringSSL's `OPENSSL_strdup`. Identities up to `PSK_MAX_IDENTITY_LEN`
still work.
## Summary
`platformDefaultConfiguration()` in `SSLContext.swift` has branches for
Linux and Android but not FreeBSD. On FreeBSD the function is a no-op:
no CA trust roots are loaded, so every HTTPS client connection fails
immediately with `CERTIFICATE_VERIFY_FAILED`.
`LinuxCABundle.swift` already compiles for FreeBSD (`#if os(Linux) ||
os(FreeBSD)`) and defines `rootCAFilePath`/`rootCADirectoryPath`, but
the search path arrays contained only Linux distro paths — no FreeBSD
path was ever matched, so `rootCAFilePath` and `rootCADirectoryPath`
were always `nil`.
## Changes
**`SSLContext.swift`** — one line:
```diff
-#if os(Linux)
+#if os(Linux) || os(FreeBSD)
```
**`LinuxCABundle.swift`** — add FreeBSD paths to both search arrays:
```swift
// rootCAFileSearchPaths additions:
"/usr/local/etc/ssl/cert.pem", // security/openssl port
"/etc/ssl/cert.pem", // base system (FreeBSD 14+)
"/usr/local/share/certs/ca-root-nss.crt", // security/ca_root_nss port
// rootCADirectorySearchPaths addition:
"/usr/local/share/certs", // security/ca_root_nss port
```
## Testing
Verified on FreeBSD 15.1 aarch64 (NXP DPAA2, Swift 6.3.2-RELEASE). With
this fix, all HTTPS requests to `swift.org` and `download.swift.org`
succeed. Without it, every connection fails at the TLS handshake
regardless of which CA bundle is installed.
Tested as part of the swiftly FreeBSD port (swiftlang/swiftly#565),
where `HTTPClientTests` makes live HTTPS requests:
```
✔ Test getSwiftOrgGPGKeys() passed after 0.700 seconds.
✔ Test getSwiftToolchain() passed after 109.816 seconds.
✔ Test getSwiftlyLinuxReleases(url:) with 6 test cases passed after 31.636 seconds.
✔ Suite HTTPClientTests passed after 183.785 seconds.
```
🤖 Generated with [Claude Code](https://claude.ai/claude-code)
---------
Co-authored-by: lushan.ai <kequeue@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
`AnalysedCertificateHostname.init` already refuses to construct a
wildcard matcher when the certificate's first label begins with the IDNA
A-label prefix `xn--` (line 287). The symmetric case is not enforced: a
wildcard SAN whose own first label is plain ASCII can still expand into
a target hostname whose first label begins with `xn--`.
A SAN of the form `*-5wao1o.example.com` will currently match a target
hostname `xn--rksmrgs-5wao1o.example.com` (the IDNA A-label form of
`räksmörgås.example.com`). Both OpenSSL's `equal_wildcard` and CPython's
`ssl._dnsname_match` reject that case explicitly; this library accepts
it.
Verified by copying `AnalysedCertificateHostname` verbatim from `main`
into a standalone executable and running:
```
[OK ] Sanity: wildcard matches normal subdomain
cert SAN: *.example.com
target: foo.example.com
expected: true got: true
[OK ] Sanity: wildcard does NOT match different parent
cert SAN: *.example.com
target: foo.evil.com
expected: false got: false
[OK ] Sanity: cert that IS an A-label wildcard rejected at parse
cert SAN: xn--*.example.com
target: xn--anything.example.com
expected: false got: false
[BROKEN ] VULN: partial wildcard expansion produces A-label target
cert SAN: *-5wao1o.example.com
target: xn--rksmrgs-5wao1o.example.com
expected: false got: true
```
After the patch in this PR the BROKEN case becomes OK.
### Modifications
In `validMatchForName`, after splitting the target around its first
period, return `false` if the target's first label begins with `xn--`.
Mirrors the existing cert-side check at line 287 and the
`caseInsensitiveElementsEqual(asciiIDNAIdentifier)` idiom already in use
in this file.
### Result
Wildcard SANs no longer expand into IDNA A-label targets, matching the
behaviour of OpenSSL and CPython. The existing
`testDoesNotMatchIDNALabelWithWildcard` continues to cover the cert-side
variant; the target-side variant is the new case this patch addresses.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Default `TLSConfiguration.curves` is now [`.x25519_MLKEM768`, `.x25519`,
`.secp384r1`], enabling post-quantum hybrid key exchange out of the box.
Users can still set curves to nil to fall back to BoringSSL's built-in
curve list, or override with any custom set.
Updated `quantum-secure-tls.md` to reflect that PQ is enabled by default
and document how to customise or disable it.
Motivation:
NIOCertificateReloading provides updated versions of a certificate and
private key pair, in the form of a NIOSSLContextConfigurationOverride,
to be used when performing a TLS handshake in NIO. Prior to this change,
the Swift customPrivateKey callback did not see the override. It always
read the private key from the immutable TLSConfiguration if one was
provided at initialization. This configuration might have been nil and
resulted in a precondition failure if the user was expecting to set the
key on the first reloader run. Otherwise, it would have contained a
stale key.
Modifications:
- Store the NIOSSLContextConfigurationOverride in SSLConnection when
applyOverride() is called.
- Update the customKey computed property to check the stored override
first and fall back to the parent context.
- Add tests:
- Server configuration sets a native key, reloader switches to a custom
key for signing.
- Server configuration sets a custom key, reloader switches to a native
key for signing.
- Server configuration sets a native key, reloader switches to a custom
key for decryption.
- Client key and cert are set by reloader.
Result:
NIOCertificateReloading will work as expected with custom private keys.
The `caCerts` value is, from Swift's perspective, merely an
`OpaquePointer?`; logging its value as part of a `preconditionFailure()`
is not particularly useful. In addition, including it in the log message
causes GitHub's CodeQL code analysis to inaccurately report a
high-severity information disclosure vulnerability in any repo using it
which has `swift-nio-ssl` as a direct or indirect dependency. Since
logging it serves no useful purpose anyway, might as well get rid of it.
### Motivation:
In some scenarios a server might want to accept connections from both,
authenticated and not authenticated peers and defer decisions after the
handshake. This new options allows a host to only do TLS verificaiton if
the peer presents certificates and accept connections otherwise.
### Modifications:
Add a new associated value to the `none` case of
`CertificationVerification` to maintain backwards compatibility. This
option enables opportunistic verification.
### Result:
A new configuration case for TLS verification.
---------
Co-authored-by: aryan-25 <aryan_shah@apple.com>
Motivation:
Unfortunately, `internal import` doesn't do implementation-hiding in the
build system. This means that the C header files do become visible to
all dependencies, which can cause problems when the ssl.h headers from
elsewhere are included.
Modifications:
Revert to `@_implementationOnly` imports.
Result:
Better builds, unfortunately more warnings
### Motivation:
Swift 5.10 is no longer supported, we should bump the swift-tools
version.
### Modifications:
* Update Swift tools version to 6.0
* Correct the failing tests on macOS
### Result:
Code reflects our support window.
Currently, the certs returned by the sslContextCallback are added to the
context, rather than replacing the certs already in the context.
This means that, if a callback is used to return a new chain to be used,
the old and new chains are both presented (but only the new leaf). This
should not cause any problem, but it is inefficient
Change: Clear the additional certs before adding the new ones
Motivation:
It is sometimes useful, such as when converting between configuration
formats, to be able to recover the `TLSConfiguration` with which an
`NIOSSLContext` was created. This is not possible with the current API;
since the property is immutable, making it public poses no risk.
Modifications:
The `NIOSSLContext.configuration` property is now `public` instead of
`internal`. (Also, an extremely obsolete Linux testing note was removed
from `CONTRIBUTING.md`.)
Result:
This change has no functional impact; all behavior remains identical.
The only effect is to add the `configuration` property to the public API
of `NIOSSLContext`.
Motivation:
Users are currently able to register a custom callback in
`NIOSSLClientHandler` and `NIOSSLServerHandler` for verifiying the
certificates presented by the peer. However, there is no mechanism for
storing additional metadata for future use. This change adds support for
the peer's validated certificate chain to be returned from the custom
verification callback and later be accessed from the handler.
Modifications:
- Added a new custom verification callback type
`NIOSSLCustomVerificationCallbackWithMetadata`.
- This type is identical to the existing
`NIOSSLCustomVerificationCallback`, with the exception that callers must
complete the callback with a `NIOSSLVerificationResultWithMetadata`
(also introduced in this change). This result type can either be
initialized with no fields, or with a validated certificate chain.
- Added properties/methods to `NIOSSLHandler`, `Channel`, and
`ChannelPipeline` for accessing the validated certificate chain.
Result:
Users are now able to store the peer's validated certificate chain from
the custom verification callback and use the result downstream.
Motivation:
Documentation should accurately explain the methods.
Modifications:
Removed the phrase "providing a passphrase callback"
Result:
Documentation is more accurate
Motivation:
In #550 a use of `NIOSSLCertificafe(file:format:)` was replaced with
`NIOSSLCertificafe.loadPEMFile(_:).first`, which isn't necessarily the
same (the error flow is different for one). To avoid any subtle
behaioral changes revert back to the old API in that one instance.
Modifications:
- Use old API
Result:
Fewer behavioural changes
Motivation:
NIOSSLCertificate has an 'init' which loads a single cert from PEM or
DER encoded file. This, obviously, only loads the first PEM which is
very rarely what users actually want to do. This is a common source of
error when loading cert chains and is easy to miss in review.
Modifications:
- Deprecate the init and point users to the `fromPEMBytes` method for
PEM which returns an array of certs, and to a new `fromDERBytes` which
returns a single cert.
Result:
Harder to misuse API
Motivation:
The trust roots settings have sometimes got non-obvious impacts on which
validator is used. These are a legacy behaviour and so changing them is
likely to cause services to encounter challenging bugs, so it's probably
not worth fixing this behaviour without doing a deprecate-and-replace
cycle.
A deprecate-and-replace of TLSConfiguration is going to be necessary in
the near-term because it is a suboptimal structure that is carrying a
lot of load. For now, however, let's just make it possible for users to
diagnose what is going on.
Modifications:
- Document the existing behaviour
Result:
Users have a chance of figuring out what is going on.
Motivation:
When configuring for mTLS, there is really only one right way to do
that. This adds that behaviour.
Modifications:
- Add mTLSConfiguration option
- Add tests
Result:
Better behaviour for mTLS.
Resolves#542
Reverts apple/swift-nio-ssl#543
This may have resulted in a behavior change which would adversely affect
downstream, we should back it out whilst we investigate.
Motivation:
If a user sets the trust roots to a non-`none` value, they presumably
want to actually validate them. This patch enables an automatic setting
of validation if the trust roots are set.
Modifications:
- Use a didSet on TLSConfiguration to raise hostname validation when the
trustRoots are set.
- Fix up cases where the tests were doing the wrong thing
Result:
Safer APIs.
Motivation:
The certificate override callback incorrectly cached results on the
SSLContext, instead of the SSLConnection. The result is that it would
only fire once for a given SSLContext, instead of on every connection,
incorrectly caching the result indefinitely.
Modifications:
Move the callback state to SSLConnection
Write tests to validate that the callback is called the right
number of times.
Result:
Better behaviour.
This PR adds new API (`SSLPrivateKey/toDerBytes()`) to get the DER bytes
for a private key.
This is only supported for native (EVP) keys; if using a custom key, an
empty array of bytes will be returned instead.
This fixes linker errors such as
```
"CNIOBoringSSLShims_SSL_CTX_get_app_data(CNIOBoringSSL_ssl_ctx_st const*)", referenced from:
static NIOSSL.NIOSSLContext.(lookupFromRawContext in <...>)(ssl: Swift.OpaquePointer) -> NIOSSL.NIOSSLContext in SSLContext.swift.o
```
when building with Swift/C++ interoperability enabled.
This is similar to https://github.com/apple/swift-nio/pull/3251.
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.
Motivation:
While we've supported the hybrid quantum-resistant KEM for a while
(because BoringSSL has), users have had to define the constant
themselves.
This patch makes the quantum-resistant KEM part of our API.
Modifications:
- Expose x25519_MLKEM768 as a curve type.
- Add tests
Result:
More quantum-resistance.
Motivation:
While swift-nio-ssl supports mTLS on the server, there's no api
available to get the verified X509 certificate after the handshake
completes.
Additionally, the existing API for NIOSSLCertificate doesn't have an API
to access the issuer and subject names.
Result:
These changes add new APIs. Specifically:
- nioSSL_peerCertificate() to the channel extension. Similar to
retrieving the tls version, this gets the verified peer X509 certificate
after the handshake completes.
- subjectName extension to NIOSSLCertificate. Grabs the subjectName from
the BoringSSL X509 object as an array of SSLCertificateName
- issuerName extension to the NIOSSLCertificate. Grabs the issuerName
from the BoringSSL X509 object as an array of SSLCertificateName
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
When viewing the documentation, deprecated methods clutter up available
options, sometimes below, making those options hard to find for a
developer working out how to add or create a TLSConfiguration.
Modifications:
Adds a DocC extension file (markdown format) the provides curation
(organization of the symbols) to order by task and ideally usefulness,
with deprecated methods pushed downward.
Result:
The documentation at
https://swiftpackageindex.com/apple/swift-nio-ssl/main/documentation/niossl/tlsconfiguration
(and future releases) will include this organization and be easier to
read through for developers.
A number of statics in the product code aren't something the compiler
currently believes are Sendable. There are a few tweaks here:
1. Two pointer statics into BoringSSL. These are thread-safe, but the
compiler doesn't know. Mark them `nonisolated(unsafe)`.
2. One static `var` should be a static `let`.
3. One instance of reminding the compiler that closures that don't
capture anything are Sendable.
Motivation:
swift-nio-ssl has long had a flag to disable its own certificate
validation behaviour. This flag works fine, and had the desired effect.
However, this flag did not take account of the fact that
Security.framework _also_ validates the hostname. Due to an
implementation bug, setting .noHostnameVerification disabled only one of
the two checks.
Modifications:
- Correctly check the flag before passing a hostname to
Security.framework
- Write some tests to make sure the behaviour works in all modes.
Result:
Better, more consistent behaviour.
Motivation:
The sslContextCallback overrides modify the SSL_CTX object itself.
That's not useful: in addition to having a global effect, which is
rarely what we want, certain modifications don't apply that late, and
setting the credentials is one of them. The result is that the callback
didn't actually do anything. Not that useful.
Modifications:
- Extract the cert chain setting functions from NIOSSLContext and move
them to general-purpose functions.
- Add support there for calling them on a SSL * as well as on a SSL_CTX
*
- Call them in an override function on SSLConnection
- Call that!
- Add a bunch of tests.
Result:
The callback actually does what it should.
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.
## Motivation
It would be handy to provide an API to create PKCS#12 files from a list
of `NIOSSLCertificates` and a `NIOSSLPrivateKey`.
This would be particularly useful when dealing with
Network.framework/NIOTransportServices/Security.framework, which use
`SecIdentity`s for SSL. Two particular use cases are
https://github.com/apple/swift-nio-ssl/issues/484#issuecomment-2410375188
and `grpc-swift-nio-transport`, which would use this API for testing the
NIOTS transport implementation.
## Modifications
This PR adds a static method to `NIOSSLPKCS12Bundle` that creates a
PKCS#12 file from the given array of certificates + private key, and
returns it as an array of bytes.
## Result
PKCS#12 files can be created using NIOSSL.
Migrate CI to use GitHub Actions.
### Motivation:
To migrate to GitHub actions and centralised infrastructure.
### Modifications:
Changes of note:
* Disable warnings-as-errors until issues with recent NIO changes are
resolved
* Adopt swift-format using rules from SwiftNIO
* Remove scripts which are no longer needed
### Result:
Feature parity with old CI minus allocation tests which remain on the
old CI.
This PR adds the support to specify what ECs the handler supports when
doing the handshake.
```swift
var config = TLSConfiguration.makeClientConfiguration()
config.curves = [.x25519]
```
This patch has 3 parts: a commit to update the vendoring script, a
commit that contains the results of running the script, and then a fixup
for the API breaks we got.
Hello,
As I was trying to implement some HTTP calls using `async-http-client`
and TLS-PSK authentication, I realised that my server was not sending
any PSK hint.
The actual implementation of the clientPSKCallback makes the server psk
hint mandatory.
Similarly the implementation of the serverPSKCallback makes the server
hint mandatory.
Reading
[RFC4279](https://datatracker.ietf.org/doc/html/rfc4279#section-5.2) it
seems that on the opposite the server psk hint should be provided only
on application that mandate it.
> [5.2](https://datatracker.ietf.org/doc/html/rfc4279#section-5.2).
Identity Hint
> In the absence of an application profile specification specifying
> otherwise, servers SHOULD NOT provide an identity hint and clients
> MUST ignore the identity hint field. Applications that do use this
> field MUST specify its contents, how the value is chosen by the TLS
> server, and what the TLS client is expected to do with the value.
I made this PR to provide an empty string to the callbacks in the case
the server doesn't provide one.
Providing an optional might be a better solution in term of semantic but
it would break the API.
---------
Co-authored-by: Martial Lienert <mlienert@netatmo.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>