TLS 0.6.0
See the version list below for details.
dotnet add package TLS --version 0.6.0
NuGet\Install-Package TLS -Version 0.6.0
<PackageReference Include="TLS" Version="0.6.0" />
<PackageVersion Include="TLS" Version="0.6.0" />
<PackageReference Include="TLS" />
paket add TLS --version 0.6.0
#r "nuget: TLS, 0.6.0"
#:package TLS@0.6.0
#addin nuget:?package=TLS&version=0.6.0
#tool nuget:?package=TLS&version=0.6.0
TLS
A fully managed TLS and DTLS library for .NET.
Features
| Area | Support |
|---|---|
| Protocols | TLS 1.2, TLS 1.3, DTLS 1.2, DTLS 1.3 |
| Transports | TlsStream (over a Stream), TlsPipe (over an IDuplexPipe), DtlsTransport (over UDP or any IDatagramTransport), DtlsListener (many DTLS clients on one socket) |
| Sans-IO | TlsEngine and DtlsEngine: state machines that do no I/O and start no timers |
| Authentication | X.509 certificates, raw public keys (RFC 7250), external PSKs (with the RFC 9258 importer), client certificates, post-handshake client authentication in 1.3 |
| Key exchange | X25519, X448, P-256, P-384, P-521, and the post-quantum hybrids X25519MLKEM768, SecP256r1MLKEM768, SecP384r1MLKEM1024 |
| Resumption | Tickets, 1.2 session IDs, ticket keys shared across servers, a pluggable session store |
| Privacy | Encrypted Client Hello (client, shared-mode server, split-mode backend), GREASE, ClientHello padding and extension order |
| DTLS | Stateless cookies, connection IDs, return routability checks (RFC 9853), DTLS-SRTP, path MTU handling |
| Extensions | SNI, ALPN, OCSP stapling, certificate compression, record_size_limit, max_fragment_length, keying material exporters |
Usage
TLS client
using System.Net.Sockets;
using Tls;
using TlsConfiguration configuration = TlsConfiguration.CreateClient(new TlsClientOptions { TargetHost = "example.com" });
using TcpClient tcp = new();
await tcp.ConnectAsync("example.com", 443, cancellationToken);
await using TlsStream stream = new(tcp.GetStream(), configuration);
await stream.HandshakeAsync(cancellationToken);
await stream.WriteAsync("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"u8.ToArray(), cancellationToken);
After the handshake, ConnectionInfo describes what was negotiated: protocol, cipher suite, ALPN, server name and the peer's certificate.
TLS server
using CryptoBase.Abstractions.Signatures;
using CryptoBase.Signatures;
using CryptoBase.X509;
// The leaf first, then each issuer. The key must stay alive while connections may sign.
Certificate[] chain = Certificate.DecodePemAll(File.ReadAllText("chain.pem"));
using ISignatureKey key = SignatureKey.ImportFromPem(File.ReadAllText("key.pem"));
using TlsConfiguration configuration = TlsConfiguration.CreateServer(new TlsServerOptions
{
ServerCertificateContexts = [TlsCertificateContext.Create(chain, key)],
});
using TcpClient tcp = await tcpListener.AcceptTcpClientAsync(cancellationToken);
await using TlsStream stream = new(tcp.GetStream(), configuration);
await stream.HandshakeAsync(cancellationToken);
TlsPipe
TlsPipe runs TLS over an IDuplexPipe and is an IDuplexPipe itself. Use it for servers built on pipes, such as Kestrel:
// In a Kestrel connection middleware.
await using TlsPipe tls = new(context.Transport, configuration);
await tls.HandshakeAsync(context.ConnectionClosed);
IDuplexPipe transport = context.Transport;
context.Transport = tls;
try
{
await next(context);
}
finally
{
context.Transport = transport;
}
The pipe reads from the transport only when the application reads, so keep a read pending. Completing Output sends close_notify.
DTLS client
using DtlsConfiguration configuration = DtlsConfiguration.CreateClient(new DtlsClientOptions { TargetHost = "example.com" });
await using DtlsTransport client = await DtlsTransport.ConnectAsync(new DnsEndPoint("example.com", 4433), configuration, cancellationToken: cancellationToken);
await client.SendAsync("Hello, DTLS!"u8.ToArray(), cancellationToken);
byte[] buffer = new byte[DtlsEngine.MaxPlaintextRecordSize];
int length = await client.ReceiveAsync(buffer, cancellationToken); // -1 after the peer's close_notify
await client.ShutdownAsync(cancellationToken);
ConnectAsync owns its UDP socket. For another datagram transport, pass an IDatagramTransport to new DtlsTransport(datagrams, configuration) and call HandshakeAsync.
DTLS server
using DtlsConfiguration configuration = DtlsConfiguration.CreateServer(new DtlsServerOptions
{
ServerCertificateContexts = [TlsCertificateContext.Create(chain, key)],
});
// Failed handshakes never reach AcceptAsync; the server's LoggerFactory logs them.
await using DtlsListener listener = DtlsListener.Listen(new IPEndPoint(IPAddress.IPv6Any, 4433), configuration);
while (true)
{
DtlsTransport connection = await listener.AcceptAsync(cancellationToken);
_ = Task.Run(async () =>
{
await using (connection)
{
byte[] buffer = new byte[DtlsEngine.MaxPlaintextRecordSize];
int length;
while ((length = await connection.ReceiveAsync(buffer, cancellationToken)) >= 0)
{
await connection.SendAsync(buffer.AsMemory(0, length), cancellationToken);
}
}
});
}
Sans-IO engines
TlsEngine and DtlsEngine do no I/O. The caller moves bytes and runs the timers:
using DtlsEngine engine = new(configuration);
TlsEngineStatus status = engine.Handshake([], out _); // A client queues its first flight.
// Until status is Complete:
// - while (engine.HasPendingOutput): engine.DrainPendingOutput(buffer, out int written), then send buffer[..written] as one datagram;
// - on each datagram: status = engine.Handshake(datagram, out int consumed), and pass the rest again until it is empty;
// - when engine.GetNextTimeout() elapses: engine.HandleTimeout();
// - on a Needs* status: resolve it, for example with engine.AcceptWithDefaultValidation(), then call Handshake again.
// Afterwards: engine.Read(datagram, plaintext, out consumed, out written) and engine.Write(message, record, out written).
Configuration
A configuration is immutable and thread-safe. Create one and share it across connections.
Certificate validation
- The default
PlatformCertificateValidatorbuilds the chain to the system roots and matchesTargetHostagainst subjectAltName. It does not check revocation. - Set
CertificateValidatorto aTrustAnchorCertificateValidatorfor a private PKI, or to aFingerprintCertificateValidatorto pin certificates. - To check revocation, set
X509RevocationMode.OnlineorOfflineon the validator. ATrustAnchorCertificateValidatorthen also checks a stapled OCSP response. - On Windows the platform validator cannot verify Ed25519, Ed448 or SM2 chains.
Certificates and client authentication
TlsCertificateContext.Create(chain, key)takes the chain, leaf first, and an ECDSA, Ed25519, Ed448 or RSA (2048 bits or more) key. Keys in the certificate store, a TPM or a smart card come from CryptoBase.X509'sX509Certificate2.GetSignaturePrivateKey.ServerCertificateContextsandClientCertificateContextslist credentials in preference order. Each handshake takes the first one the peer accepts.ClientCertificateRequiredandClientCertificateRequestedcontrol client certificates. In TLS 1.3 and DTLS 1.3, a server can also request one after the handshake withNegotiateClientCertificateAsync.
Server name selection
A server configuration without credentials delegates to ServerConfigurationSelector:
using DtlsConfiguration router = DtlsConfiguration.CreateServer(new DtlsServerOptions
{
ServerConfigurationSelector = (clientHello, _) => ValueTask.FromResult(configurations.GetValueOrDefault(clientHello.ServerName ?? "")),
});
Server names arrive in lowercase. Returning null refuses the handshake.
Raw public keys
using DtlsConfiguration client = DtlsConfiguration.CreateClient(new DtlsClientOptions
{
ServerCertificateTypes = [TlsCertificateType.RawPublicKey],
RawPublicKeyValidationCallback = (_, key) => key.Encoded.Span.SequenceEqual(pinnedServerKey),
});
using DtlsConfiguration server = DtlsConfiguration.CreateServer(new DtlsServerOptions { ServerRawPublicKeys = [serverKey] });
Pre-shared keys
using DtlsConfiguration client = DtlsConfiguration.CreateClient(new DtlsClientOptions { PskIdentity = "device-1"u8.ToArray(), PskKey = secret });
using DtlsConfiguration server = DtlsConfiguration.CreateServer(new DtlsServerOptions { PskKeyResolver = LookupKeyAsync });
PskKeyResolverreturns the key for an identity, or null for an unknown one. Keys must be at least 16 bytes.- PSK handshakes use ECDHE by default.
UsePskWithoutForwardSecrecyandAllowPskWithoutForwardSecrecy(1.3), or listingTLS_PSK_WITH_*suites (1.2), opt out. - Identities travel in plaintext.
UsePskImporterimports keys per RFC 9258.
Resumption
Servers issue session tickets after certificate handshakes, and the 1.2 versions also resume by session ID. AllowResumption = false disables resumption. Servers that share a TlsResumptionKeyRing and a ResumptionScope resume each other's sessions:
DateTimeOffset now = DateTimeOffset.UtcNow;
TlsResumptionKey key = TlsResumptionKey.Generate(now, now + TimeSpan.FromDays(1), now + TimeSpan.FromDays(2));
using TlsResumptionKeyRing keys = new([key]);
using DtlsConfiguration server = DtlsConfiguration.CreateServer(new DtlsServerOptions
{
ServerCertificateContexts = [certificate],
ResumptionKeys = keys,
ResumptionScope = "telemetry-v1"u8.ToArray(),
});
// Later, on every server: add the next key before its EncryptFrom.
keys.Update([key, next]);
Encrypted Client Hello
// Server: publish configList in the ech parameter of the HTTPS or SVCB DNS record.
TlsEncryptedClientHelloKey key = TlsEncryptedClientHelloKey.Generate("public.example", configId: 1, maximumNameLength: 32);
byte[] configList = TlsEncryptedClientHelloKey.CreateConfigList([key]);
using TlsEncryptedClientHelloKeyRing echKeys = new([key]);
using DtlsConfiguration server = DtlsConfiguration.CreateServer(new DtlsServerOptions { ServerConfigurationSelector = SelectAsync, EncryptedClientHelloKeys = echKeys });
// Client: the library does not query DNS.
using DtlsConfiguration client = DtlsConfiguration.CreateClient(new DtlsClientOptions { TargetHost = "secret.example", EncryptedClientHelloConfigList = configList });
- ECH works in TLS 1.3 and DTLS 1.3. The server also needs a certificate for the public name.
- A client with a stale config fails with
TlsError.EncryptedClientHelloRejected.TlsException.EncryptedClientHelloRetryConfigListholds configs to retry with. - Rotate keys with
echKeys.Update.
ClientHello layout
TlsClientOptions options = new()
{
TargetHost = "example.com",
ClientHelloLayout = new TlsClientHelloLayout { PermuteExtensions = true, PaddedLength = 512 },
};
ClientHelloLayout changes the extension order, padding and GREASE of the ClientHello, not what it negotiates.
Other options
- Keying material:
ExportKeyingMaterialderives exporter output (RFC 5705, RFC 9846). - Logging: set
LoggerFactoryin the options. The library never logs keys, PSK identities, certificates or server names. - Timeouts: a DTLS handshake fails after
DtlsEngineOptions.HandshakeTimeout. TLS has no handshake timeout: use the cancellation token. - Load balancers: a connection stays on the server that created it.
DtlsListenerOptions.ConnectionIdGeneratorencodes routing data into connection IDs.
Behavior
- Closing:
ShutdownAsyncsends close_notify. Disposing sends it too if it was not sent. - Failures: a failure ends the connection, and every pending and later call throws it. A transport failure surfaces as an
IOExceptionwith the transport's exception inside. - Cancellation: canceling a TLS read leaves the connection as it is. Canceling a TLS write once part of it was sealed ends the write side.
- Callbacks: the transports run the validator, selector, PSK resolver and session store on the thread pool. An exception from them fails the handshake and is rethrown.
- Reentrancy: code that the library runs inside a call (clock, logger, transport) must not call methods of the same object that change state, or make a blocking call on any connection.
Algorithms
| Kind | Default | Only when listed |
|---|---|---|
| TLS 1.3 / DTLS 1.3 suites | TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256, TLS_AES_128_CCM_SHA256 |
TLS_AES_128_CCM_8_SHA256; in TLS 1.3 only, TLS_SM4_GCM_SM3, TLS_SM4_CCM_SM3 |
| TLS 1.2 / DTLS 1.2 suites | ECDHE_ECDSA and ECDHE_RSA with AES-GCM, ChaCha20-Poly1305 and (ECDSA) AES-CCM; ECDHE_PSK with AES-GCM, ChaCha20-Poly1305 and AES-CCM | CCM_8 suites; pure TLS_PSK_WITH_* suites |
| Key exchange | X25519MLKEM768, SecP256r1MLKEM768, SecP384r1MLKEM1024 (1.3 only), x25519, secp256r1, x448, secp384r1, secp521r1 | curveSM2 (TLS 1.3) |
| Signatures | ECDSA P-256/384/521, Ed25519, Ed448, RSASSA-PSS, RSASSA-PKCS1-v1_5 (1.2 handshakes and certificates) | sm2sig_sm3 (TLS 1.3) |
| Certificate compression | brotli, zlib | zstd (.NET 11) |
CipherSuites,KeyExchangeGroups,SignatureAlgorithmsand the compression lists override the defaults.- At the AEAD usage limit the 1.3 versions update keys, and the 1.2 versions close the connection with
TlsError.KeyUsageLimitReached. Prefer 1.3 for long-lived, high-volume connections. - CCM_8 suites need deployment safeguards against forgery, such as a closed network.
- The ShangMi suites (RFC 8998) need an SM2 certificate whose key is CryptoBase's
SM2Key. - For TPM and smart card client keys that cannot sign RSASSA-PSS, set
AllowLegacyRsaPkcs1ClientSignatureson both sides (RFC 9963).
Standards
| Area | RFCs |
|---|---|
| Protocols | DTLS 1.3 (RFC 9147), DTLS 1.2 (RFC 6347), TLS 1.3 (RFC 9846), TLS 1.2 (RFC 5246) |
| Connection IDs | RFC 9146, RFC 9147 Section 9, return routability check (RFC 9853) |
| Key exchange | RFC 7748, RFC 8422, ECDHE-MLKEM hybrids (RFC 10024, RFC 9954) |
| Signatures | RFC 8422, RFC 8032, RFC 8410, RFC 8017, RFC 4055, RFC 5756, RFC 9963 |
| 1.2 cipher suites | RFC 5289, RFC 7251, RFC 7905, RFC 4279, RFC 5487, RFC 5489, RFC 6655, RFC 8442 |
| ShangMi | RFC 8998 (TLS 1.3, opt-in) |
| External PSKs | RFC 9257, importer (RFC 9258) |
| Extensions | RFC 6066 (server_name, max_fragment_length, status_request), RFC 7301, RFC 7250, RFC 5764, RFC 7714, RFC 7627, RFC 5746, RFC 5077, RFC 7507 (servers), RFC 8449, RFC 8879, RFC 7685 (clients) |
| Exporters | RFC 5705, RFC 9846 Section 7.5 |
| Certificates | RFC 5280 path validation through CryptoBase.X509, RFC 9525 name matching |
| Encrypted Client Hello | RFC 9849, HPKE (RFC 9180) |
| Guidance | BCP 195 (RFC 9325, RFC 8996, RFC 9852 for TLS), RFC 10015, RFC 9155, RFC 9847, GREASE (RFC 8701) |
Not supported
- 0-RTT.
- TLS 1.0, TLS 1.1, DTLS 1.0, CBC and other non-AEAD suites.
- Renegotiation in TLS 1.2 and DTLS 1.2.
- Certificates combined with external PSKs (RFC 9973).
- Delegated credentials (RFC 9345), ticket requests (RFC 9149), False Start, key logging (RFC 9850).
- tls-unique channel binding and
TransportContext.GetChannelBinding. - DTLS over reliable transports (RFC 6083).
- The client-facing server of split-mode ECH.
docs/design.md explains why.
API
| Type | Purpose |
|---|---|
| TlsConfiguration | Shared TLS credentials and policy, from TlsClientOptions or TlsServerOptions. |
| TlsStream | TLS over a Stream. |
| TlsPipe | TLS over an IDuplexPipe. |
| TlsEngine | Sans-IO TLS; TlsEngineOptions set its clock and handshake message limit. |
| DtlsConfiguration | Shared DTLS credentials and policy, from DtlsClientOptions or DtlsServerOptions, and the stateless cookie exchange. |
| DtlsListener | Accepts DTLS connections on one UDP socket; DtlsListenerOptions set its limits. |
| DtlsTransport | One DTLS connection over an IDatagramTransport. |
| DtlsEngine | Sans-IO DTLS; DtlsEngineOptions set its MTU, clock, timeouts and connection ID. |
| TlsEngineBase, TlsConfigurationBase, TlsClientOptionsBase, TlsServerOptionsBase | What the TLS and DTLS types share. |
| TlsEncryptedClientHelloKeyRing | Rotating ECH keys of a server. |
| TlsResumptionKeyRing | Rotating ticket keys shared by servers. |
| ITlsSessionStore | Shared store of 1.2 sessions; TlsMemorySessionStore keeps them in memory. |
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- CryptoBase (>= 10.0.0)
- CryptoBase.X509 (>= 10.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 11.0.0)
- System.Threading.RateLimiting (>= 11.0.0)
-
net11.0
- CryptoBase (>= 10.0.0)
- CryptoBase.X509 (>= 10.0.0)
- System.Threading.RateLimiting (>= 11.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.