264 Commits
Author SHA1 Message Date
Franz Busch 2a439aff65 Guard Security.framework usage with canImport(Security) (#614)
The certificate validation code only needs the `Security` framework, not
`Darwin`.
2026-11-09 10:17:57 +01:00
Goutam Adwant 15e0b9e495 Avoid flushing buffered writes on closed TLS channels (#610)
## Summary

- Discard buffered actions when `NIOSSLHandler.flush` runs after the
handler reaches `.closed`, failing pending write promises with
`ChannelError.ioOnClosedChannel`.
- Add regression coverage for handshake EOF, remote half closure, and
flush-before-close behavior.

## Motivation

During handshake failure, a downstream `errorCaught` callback can flush
a write that TLS buffered before closing. The closed handler cannot
encode that write, so `doUnbufferActions` repeats until its no-progress
assertion aborts a debug build. The new closed-state path avoids
entering that loop.

## Testing

- Before the fix, the full-closure and half-closure regressions each
reproduced the `doUnbufferActions(context:) looped too many times`
assertion.
- After the fix, `swift test --jobs 4` passed all 344 tests using Swift
6.4 on Linux arm64.
- macOS execution has not been verified for this change.

Fixes #609
2026-10-12 10:33:56 +01:00
Cory Benfield 86458a336b Update BoringSSL to 8eb25be6fa18d475291122887a7bccd3762ff236 (#607)
As a standard pattern, the vendoring script needed some changes, as did
our internal code.

The biggest change here is that BoringSSL has changed its name mangling
scheme. This causes us to no longer need to explicitly write the prefix
out anymore: in fact, doing that causes compiler errors. So this patch
rewrites the code to resolve that issue.

Along the way, I've also added some checks for making sure the name
mangling is correct.
2026-10-09 17:19:47 +00:00
SteveandCory Benfield 71034b87bc Avoid unconditional plaintext read buffer reallocations (#598)
### Motivation

Fixes #227.

`NIOSSLHandler` initially reserves one maximum TLS record, while the
read loop immediately asks for another record's worth of writable space
after consuming the first. Reserve two records up front so the normal
loop does not force an unconditional buffer growth.

The test-only capacity accessor follows the existing `ByteBufferBIO`
test seam pattern and verifies the reservation at handler installation.

### Testing

- Negative control on current `main`: expected 32768 bytes, received
16384
- Focused regression: passed
- Full macOS suite: 325 tests passed
- Production build with the Swift 6.3 CI warning, dependency-import, and
explicit-Sendable flags: passed
- Release benchmark package build: passed
- Renegotiation integration test: passed
- `git diff --check`: passed
- Commit signature: verified

### Maintainer note

This is a patch-level performance fix. The fork author cannot apply the
required `🔨 semver/patch` label to the upstream PR, so a maintainer will
need to add it.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-09-07 17:52:56 +01:00
SteveandCory Benfield 76afd00803 fix: close before forwarding fatal input closure (#604)
## Motivation

Follow up #603 by making its fatal input-closure path safe against
synchronous downstream reentrancy.

While an additional certificate verification future is pending,
`userInboundInputClosedTriggered` forwards `ChannelEvent.inputClosed`
before `channelClose` changes the handler state. A downstream handler
can synchronously complete that future from the callback, re-enter the
handshake while the state still says `.additionalVerification`, and
attempt to reactivate a connection whose input has already closed.

## Modifications

- Mark fatal handshake input closure as `.closed` before firing
downstream error and input-closed events.
- Strengthen the existing additional-verification regression so a
downstream input-closed handler completes the verification future
synchronously.
- Preserve the post-handshake ragged-EOF and remote-half-closure
behavior from #603.

## Testing

`swift test --filter
NIOSSLIntegrationTest.testInputClosedDuringAdditionalVerificationClosesTheChannel`

Result: 1 test passed. The commit is signed and based directly on the
merge commit for #603 (`03827c1a9fdb2b6b00a4e93ede8861520263af8c`).

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-09-07 16:24:22 +00:00
Eirik Botten Nicolaysen f7daec2a9b Accept every c_rehash collision suffix, not just .0 (#602)
`_isRehashFormat` recognises only a one-digit collision suffix, so
`openssl rehash` links from `.10` upward are not seen as c_rehash links
at all.

### The three barriers

On `main` the name check is:

```swift
guard let lastPathComponent = utf8PathSplitView.last,
    lastPathComponent.count == 10
else { return false }
let filenameParts = lastPathComponent.split(separator: UInt8(ascii: "."))

guard filenameParts.count == 2,
    let filename = filenameParts.first,
    let fileExtension = filenameParts.last,
    fileExtension.count == 1,
    filename.count == 8,
    filename.allSatisfy({ $0.isHexDigit }),
    fileExtension.first == UInt8(ascii: "0")
else { return false }
```

Three things reject a valid link independently:

1. `lastPathComponent.count == 10` — rejects any name longer than
`HHHHHHHH.D` before the extension is examined at all.
2. `fileExtension.count == 1` — rejects any suffix of more than one
digit.
3. `fileExtension.first == UInt8(ascii: "0")` — rejects every suffix
that does not begin with `0`, which for the ids OpenSSL actually writes
means everything except `.0`.

Relaxing any one of them is not enough on its own.

### Consequence

The filter lives in `loadVerifyLocations(_:context:sendCANames:)`, which
calls `_isRehashFormat` over the directory contents when `sendCANames`
is set, loads each surviving link as a PEM certificate, and passes it to
`addCACertificateNameToList` so its CA name reaches the client CA list.
(`addRootCertificate` is a different function; it adds a certificate to
the trust store and does not walk the directory.)

A CA that lost the hash race is therefore skipped, so its name is absent
from the CertificateRequest, and a client holding a certificate from
that CA has no reason to send it. The failure is quiet: nothing errors,
the handshake just proceeds without the client certificate.

### The change

- `fileExtension.allSatisfy({ $0.isDecimalDigit })` replaces the `==
"0"` comparison, mirroring the `isHexDigit` check on the line above.
`isDecimalDigit` is added to the same `UTF8.CodeUnit` extension as
`isHexDigit`, in the same shape, reusing the existing
`asciiZero`/`asciiNine` constants.
- `fileExtension.count == 1` becomes `!fileExtension.isEmpty`. Emptiness
still has to be excluded explicitly, because `allSatisfy` is vacuously
true on an empty collection.
- `lastPathComponent.count == 10` is removed rather than relaxed to `>=
10`. It is redundant once the parts are checked: `filenameParts.count ==
2`, `filename.count == 8` and a non-empty all-digits extension already
pin the name to 8 + 1 + digits. A second, looser length check would only
be another thing to keep in sync.
- The split passes `omittingEmptySubsequences: false`. This is
load-bearing. With the default behaviour `Collection.split` discards
empty pieces, so `.7f44456a.0`, `7f44456a..0` and `7f44456a.0.` collapse
to the same two parts as `7f44456a.0`. The removed `count == 10` check
had been rejecting exactly those three by accident; the explicit split
replaces that accident with an intentional rule, and the reasoning is
recorded at the call site.

No upper bound on the number of digits is imposed. The reasoning, and
the OpenSSL sources it rests on, are in a comment on this PR.

### Tests

`testRehashFormat` already asserts a non-digit extension (`.z`) is
rejected; `.a` is added next to it, since a hex-but-not-decimal
character is the case most likely to regress if someone reaches for
`isHexDigit` here.

`testRehashFormatAcceptsCollisionSuffixes` creates real symlinks and
covers:

- accepted: 0, 1, 9, 10, 123, 255.
- rejected: `.7f44456a.0`, `7f44456a..0`, `7f44456a.0.`, `7f44456a.`,
`7f44456a.0.1` and `7f44456a.r0`.

Every assertion carries a message saying why that name is in the list.
The rejected names are real symlinks to a real certificate, so the name
check is the only thing that can reject them. Only the first three
depend on the explicit split; the comment in the test says what rejects
the other three, so nobody reads the split as decorative.

The existing `getRehashFilename` helper is used unchanged. It formats
with `%08lx.%d` and already produces `.10`, `.123` and `.255` correctly.

One existing assertion changes meaning. `testRehashFormat` builds
`7f44456a.1` for its "in rehash format, but not a symlink" case, and on
`main` that passes for the wrong reason: the name is rejected at the
`"0"` comparison, before the symlink check it is meant to exercise. I
confirmed this by passing a nonexistent path through the function, where
reaching `lstat` is observable as a throw:

| Source | `_isRehashFormat("/etc/ssl/certs/7f44456a.1")` |
| --- | --- |
| `main` | returns `false`, does not throw — rejected at the name check
|
| this PR | throws — the name is accepted and execution reaches the
symlink check |

After this change the assertion exercises what it was written for.

### Verification

Run in `swift:6.2-noble`, the image the Linux 6.2 leg of the shared
matrix names (`apple/swift-nio`, `scripts/generate_matrix.sh` line 78):

```
docker run --rm -v "$PWD":/src -w /src swift:6.2-noble swift test --scratch-path .build-linux
```

| Run | Result |
| --- | --- |
| `apple:main` (03827c1), unmodified | `Executed 339 tests, with 0
failures (0 unexpected)` |
| PR head before this commit, unmodified | `Executed 340 tests, with 0
failures (0 unexpected)` |
| With this change | `Executed 340 tests, with 0 failures (0
unexpected)` |
| With this change, the matrix's 6.2 argument overrides | `Executed 340
tests, with 0 failures (0 unexpected)` |
| New test against `apple:main` source | 5 failures: `.1`, `.9`, `.10`,
`.123`, `.255` |
| New test against this branch's first commit | 3 failures: `.10`,
`.123`, `.255` |
| New test against a variant keeping the default split | 3 failures:
`.7f44456a.0`, `7f44456a..0`, `7f44456a.0.` |

The last three are negative controls, showing the new assertions have
teeth in both directions. `swift format lint` reports only the
pre-existing `OrderedImports` warnings, unchanged from the baseline.

The `.10` case was reported by @stephenlclarke; I reproduced it here
before changing anything.

---

The code in this pull request was written with Claude Fable 5.1. The
verification above and this description were written with Claude Opus 5.
I have reviewed and tested the change, and I am responsible for its
content.
2026-09-07 16:22:32 +01:00
Sam Amin 03827c1a9f Close the channel when input closes during the TLS handshake (#603)
### Motivation

`NIOSSLHandler` treats input closure during the handshake as a fatal
handshake
failure: `userInboundInputClosedTriggered` synthesises
`NIOSSLError.handshakeFailed(.sslError([.eofDuringHandshake]))`, fires
it, and
forwards `ChannelEvent.inputClosed`. Unlike every other fatal handshake
failure
it then returns without closing the channel and without leaving
`.handshaking`.

When the channel has `allowRemoteHalfClosure` set, nothing else closes
it
either — NIO deliberately does not close on FIN, and a pipeline still
waiting on
ALPN may contain no handler that owns the closure. The descriptor stays
in
`CLOSE_WAIT` for the lifetime of the process, and a graceful shutdown
that waits
on all child channels never completes.

Compare `doHandshakeStep`'s `.failed` branch, which fires the same
`handshakeFailed` error and then calls `channelClose`. Both are fatal;
only one
closed.

A related hole sits underneath. `channelClose` and `channelInactive`
complete
`shutdownPromise` and `closePromise` but never `closeOutputPromise`. A
`close(mode: .output)` issued while handshaking is buffered with its
promise
stored there, and `discardBufferedActions` only fails `.write` promises,
so that
promise was never completed: the caller hangs, or trips NIO's
leaked-promise
`fatalError`. Closing the channel on this path makes it reliably
reachable.

### Modifications

- In `userInboundInputClosedTriggered`, mark `.handshaking` and
`.additionalVerification` as fatal and call `channelClose` after firing
the
error and forwarding `inputClosed`. The post-handshake ragged-EOF branch
is
  unchanged: half closure is legitimate once the connection is up.
- Complete `closeOutputPromise` in `channelClose` and `channelInactive`,
  alongside the promises they already fail.
- Added tests for input closure during the handshake (`EmbeddedChannel`
and real
  sockets), during additional peer certificate verification — including
completing the verification callback after the close — and for the
buffered
`close(mode: .output)` promise. A control test asserts that input
closure
after the handshake still fires `uncleanShutdown`, forwards
`inputClosed`, and
  leaves the channel open.

### Result

A peer that connects and half-closes before completing the handshake no
longer
leaks a descriptor. Post-handshake half closure is unaffected.

Two observable changes for callers on the mid-handshake path: buffered
writes
now fail with `ChannelError.ioOnClosedChannel` rather than the TLS
error, and
`errorCaught` fires once rather than twice. Both match the existing
`doHandshakeStep(.failed)` behaviour.
2026-09-02 13:38:37 +00:00
Cory Benfield dea6ebb773 Fix comparing TLSConfiguration objects with some closures (#600)
Motivation:

TLSConfiguration aims to produce an equality comparison even though it
contains closures. Unfortunately, the way it does this is subject to
some bugs. Specifically, we pass the closure directly to the generic
method `withUnsafeByes` which can in some cases force the compiler to
emit a reabstraction thunk. This happens at the point of comparison, and
so we can end up at a point where a TLSConfiguration object compares
unequal _to itself_, which is not great.

Modifications:

Defend against the reabstraction thunks by temporarily storing the
closures inside a struct, which can be passed to the generic method
without the reabstraction thunks.

Adds a helper for comparisons as well to make this more likely to get
correct implementations going forward.

Result:

Correct comparisons.
2026-08-27 14:41:38 +01:00
Rafael CepedaandAryan Shah 8d8f7844d7 Don't crash when a peer completes an optionalVerification handshake without a certificate (#590)
## Motivation

When a `NIOSSLHandler` is created with an
`additionalPeerCertificateVerificationCallback`
(via `_makeSSLServerHandler` / `_makeSSLClientHandler`) and the
`TLSConfiguration` uses
`.optionalVerification`, the peer is allowed to complete the handshake
*without* presenting
  a certificate.

In that situation `doHandshakeStep` reached the additional-verification
branch, called
`connection.getPeerCertificate()`, got `nil`, and hit a
`preconditionFailure`, aborting the
  entire process.

The constructor precondition did not catch this because
`.optionalVerification` is
`.none(validatePresentedCertificates: true)`, which is distinct from
`.none` and therefore
  passes the `!= .none` check.

  ## Modifications

  - In `NIOSSLHandler.doHandshakeStep`, only invoke the
`additionalPeerCertificateVerificationCallback` when the peer actually
presented a
certificate. The callback binding and the `getPeerCertificate()` binding
are now combined
into a single `if let ..., let ...`; if no certificate was presented the
handshake
completes normally without invoking the callback. This preserves the
previous behaviour
of only calling `getPeerCertificate()` when a callback is set
(short-circuit ordering).
  - Removed the now-unreachable `preconditionFailure`.
- Added an integration test that stands up a server with
`.optionalVerification` and an
`additionalPeerCertificateVerificationCallback`, connects a client that
presents no
certificate, and asserts the connection is handled without crashing the
process.

  ## Result

A peer that completes an `.optionalVerification` handshake without
presenting a certificate
no longer crashes the process. The additional verification callback
still runs, unchanged,
whenever a certificate *is* presented, so behaviour for the
certificate-present path is
unaffected. `.optionalVerification` +
`additionalPeerCertificateVerificationCallback` is now
a genuinely supported combination, matching what the constructor
precondition already
  advertised.

---------

Co-authored-by: Aryan Shah <aryan_shah@apple.com>
2026-08-17 14:48:31 +01:00
Si Beaumont d930168b86 Merge commit from fork
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.
2026-07-15 13:05:47 +01:00
Si Beaumont fd221573c7 Reserve a byte for the NUL terminator in the PSK client identity (#588)
### 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.
2026-07-10 11:13:08 +01:00
f6b21a8b27 NIOSSL: enable CA trust roots for FreeBSD (#587)
## 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>
2026-06-29 08:58:12 +01:00
Karan KuraniandCory Benfield e168589846 Reject partial wildcard SAN matches that produce IDNA A-label first label (#580)
### 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>
2026-06-25 11:04:38 +01:00
Rafael Cepeda 73f8803df4 Enable x25519_MLKEM768 by default (#582)
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.
2026-06-01 17:24:41 +01:00
Allison df9c340602 Set custom private keys via sslContextOverride (#573)
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.
2026-03-06 11:56:02 +00:00
Gwynne Raskind 88c4694e15 Do not log the caCerts value if PKCS#12 parsing goes haywire (#571)
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.
2026-02-23 18:49:58 +00:00
Raphaelandaryan-25 173cc69a05 Enable opportunistic TLS verification (#565)
### 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>
2025-10-29 14:57:22 +00:00
Cory Benfield c1bcde58f6 Revert to @_implementationOnly import (#562)
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
2025-10-28 15:52:53 +00:00
Orhan Yigit Yazicilar 4a1819a281 Drop Swift 5.10 (#559)
### 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.
2025-09-25 13:45:48 +01:00
hamzahrmalik 6ae36f2273 Make sslContextCallback overrides replace the existing chain, rather than adding to it (#557)
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
2025-09-16 15:29:14 +01:00
Gwynne Raskind 737e550e60 Make NIOSSLContext.configuration public. (#556)
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`.
2025-08-27 10:29:08 +00:00
aryan-25 1d4afc64e8 Allow the peer's validated certificate chain to be returned in the custom verification handler (#553)
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.
2025-08-21 12:55:53 +01:00
Cory Benfield 191e95e74c Remove incorrect documentation (#555)
Motivation:

Documentation should accurately explain the methods.

Modifications:

Removed the phrase "providing a passphrase callback"

Result:

Documentation is more accurate
2025-08-15 07:55:36 +00:00
George Barnett 385f5bd783 Avoid small behaviour change in #550 (#551)
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
2025-07-15 13:16:38 +00:00
George Barnett 5108dbdec9 Deprecate NIOSSLCertificate(file:format:) (#550)
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
2025-07-15 13:20:55 +01:00
Rafael Cepeda f64263a41f Enabled -require-explicit-sendable compiler flag (#549)
Enabled -require-explicit-sendable compiler flag and fixed the errors
highlighted by the compiler.
2025-07-10 18:49:30 +01:00
Cory Benfield dacd828b9c Add documentation of how trust roots settings affect validators (#548)
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.
2025-07-09 15:24:14 +01:00
Cory Benfield 8d6730f567 Add mTLSConfiguration option for TLSConfiguration (#545)
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
2025-07-07 10:18:27 +00:00
Rick Newton-Rogers f19bb9918d Revert "Enable certificate verification if trustRoots are set to non-nil" (#544)
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.
2025-07-03 16:14:23 +00:00
Cory Benfield 34486a9057 Enable certificate verification if trustRoots are set to non-nil (#543)
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.
2025-07-02 17:35:14 +00:00
Cory Benfield 36b48956eb Fix incorrect callback caching (#541)
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.
2025-06-16 14:43:38 +01:00
Gus Cairo 9173d857de Add toDerBytes to SSLPrivateKey (#540)
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.
2025-06-16 11:35:42 +01:00
Egor Zhdan 43e4c3c7be Make CNIOBoringSSLShims compatible with C++ interop (#538)
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.
2025-05-28 15:21:29 +01:00
Rick Newton-Rogers 4b38f35946 Drop Swift 5.9 (#536)
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.
2025-05-05 12:13:41 +01:00
Cory Benfield 8061e1edd9 Add explicit API support for X25519_MLKEM768 hybrid KEM (#535)
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.
2025-04-30 10:41:13 +01:00
Jeff DaveyandCory Benfield 874ad69680 Add subjectName, issuerName, and access to the peerCert (#533)
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>
2025-04-23 13:39:24 +00:00
Zane Enders 6df102a39c Fix typo in NIOSSLServerHandler documentation. (#534)
Motivation:

NIOSSLServerHandler miss named NIOSSLClientHandler in documentation.

Modifications:

Fix Typo.

Result:

Correct name in documentation.
2025-04-22 09:20:11 +00:00
Joseph Heck 66cfda0cbd Add DocC extension page to provide curation for TLSConfiguration (#532)
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.
2025-04-16 10:22:38 +01:00
Cory Benfield f1baaad333 Clean up Sendability issues in examples & performance tester (#528) 2025-04-11 10:13:37 +00:00
Cory Benfield a6a52bf020 Remove some redundant suppressed conformances (#522)
These suppressed conformances are not necessary, as they are redundant
with the suppressed conformance on the parent class.
2025-04-11 11:09:24 +01:00
Cory Benfield 5fe3ed5d32 Fix sendability issues in Universal Bootstrap (#527) 2025-04-11 09:19:31 +00:00
Cory Benfield a919f04adb Swap some implementation only imports to internal imports (#521) 2025-04-11 09:14:31 +00:00
Cory Benfield 1c130a82a7 Clean up Sendability errors in pipelines and promises (#524) 2025-04-11 08:59:11 +00:00
Cory Benfield f6a4469c1b Clean up sendability of statics (#523)
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.
2025-04-11 08:52:42 +00:00
Cory Benfield 56bc59f677 Cleanup missing internal Sendable annotation and missing preconcurrency import (#525)
The backing storage for SubjectAlternativeNames is Sendable (it's
immutable), and Security hasn't been annotated with sendability.
2025-04-11 08:40:50 +00:00
Cory Benfield 357dd88efb Clarify that we don't hop ELs in our callbacks (#526) 2025-04-11 09:36:46 +01:00
Cory Benfield 049520bf7d Update BoringSSL to 817ab07ebb53da35afea409ab9328f578492832d (#506)
This PR updates BoringSSL to a newer commit.

Relatedly, this also lifts our minimum C++ version to C++17, to match
BoringSSL.
2025-02-10 15:43:01 +00:00
Cory Benfield 94d63e782b Actually disable hostname validation on Apple platforms when asked (#502)
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.
2025-01-03 09:36:35 +00:00
Cory Benfield bdd5269d0c Fix issues compiling on nightly-main image (#500) 2024-12-18 11:06:08 +00:00
Cory Benfield 3cb4d5ad12 Correctly override connection state using sslContextCallback (#499)
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.
2024-12-18 10:57:06 +00:00