ADR 0022 — TLS and X.509: the corelib over OpenSSL, not the framework’s IL
- Status: Accepted (2026-11-06). Implemented: X.509 certificates and chains (step 1),
SslStreamclient and server andhttps://throughHttpClient(step 2), on Linux; the same code on macOS arm64 over Homebrew’s OpenSSL 3 and on Windows x64 over the OpenSSL 3 DLLs (addenda, 2026-11-07).
Context
HttpClient works over plain HTTP/1.1 (ADR 0013, “Mixed assemblies”); https://, SslStream
and the certificate types were explicit NotSupportedExceptions. NativeAOT parity (ADR 0016) needs TLS: Kestrel’s
HTTPS, HttpClient to real servers, SslStream itself. .NET’s own stack on Linux is
System.Net.Security (the SslStream state machine, Interop.OpenSsl) over System.Security.Cryptography
(X509Certificate2, chains, PKCS#12, keys), whose native half is libSystem.Security.Cryptography.Native.OpenSsl, a
shim over libssl/libcrypto that the shared framework ships and the NativeAOT runtime pack ships as a static archive.
Options measured
- Framework IL, like System.IO.Compression or System.Net.Http (the route the other framework libraries took).
--framework-il System.Security.CryptographyandSystem.Net.Securityboth stop at the first gate: “it calls native code of the .NET runtime (libSystem.Native)”. These assemblies call the wholelibSystem.Native(file reads for the certificate stores, environment,SystemNative_*helpers), which carries .NET’s signal handling and child-process machinery and whichNativeAotPackdeliberately lets only System.Formats.Tar and ZipFile call (it would compete with csharpc’s runtime). Past that gate the work is large and open-ended:System.Security.Cryptographyholds types the corelib already implements as shadows (RSA,Aes,SymmetricAlgorithm,HashAlgorithmName,RandomNumberGenerator, the hash classes,CryptoStream). The ILRSAOpenSsl/X509Certificate2code derives from and calls members of those (ImportPkcs8PrivateKey, …) that the shadows lack, so it needs either a complete second RSA/hash surface or removing the shadows, which moves every existing crypto sample onto the shim and onto IL.- The shim’s static archive links, but its callers marshal
SafeHandles throughLibraryImportstubs (SafeHandleMarshaller<T>: one of the open blockers of docs/18-compatibility.md), pass delegates as native callbacks (ALPN selection, verification, client-certificate and SNI callbacks) and rely onArrayPool,ValueTaskstate machines andMemory<byte>pinning inSslStream’s I/O (about 4 000 lines,SslStream.IO.cs/.Protocol.cs). - A program using
SslStreamwould link System.Security.Cryptography’s lowering closure (certificate stores, PKCS#7, CMS-adjacent code), the way Regex links its engine: hundreds of KB, minutes at-O2. - It would still need a port for macOS (Security.framework shim) and Windows (the same assemblies, but SChannel
P/Invokes and
SafeHandles), neither reachable from the framework IL without those same blockers.
- The corelib over OpenSSL directly (what
Crypto/Rsa.csandCrypto/AesNative.csalready do for RSA and AES):X509Certificate/X509Certificate2,X509Chain, the collections and the loaders are written in C# in the corelib, reading DER themselves (the fields the API reports) and calling libcrypto for what needs it (PKCS#12 and PEM decoding, private keys, chain verification);SslStreamfollows over libssl with memory BIOs. libcrypto/libssl are opened on first use (DllImport("libssl.so.3")), the same dependency every .NET Linux app has, so programs that don’t use TLS don’t load them and nothing is linked statically.
Decision
Option 2. The shadow classes keep .NET’s public surface and exception types and messages, copy .NET’s managed
logic where it is portable (X509Certificate.ToString(true), thumbprints, name formatting after
X500NameEncoder, the chain status mapping after OpenSslX509ChainProcessor) and call OpenSSL 3 for the
cryptographic work, like the shim does. What isn’t implemented is an explicit diagnostic (a compile-time
CSLLVM0002 where the member is absent from the shadow, a NotSupportedException naming the feature where it can’t
be): certificate extensions (X509Certificate2.Extensions and the typed extension classes), stores, PKCS#7,
exporting a PFX, GetNameInfo for names without CN/OU/O, revocation checking, ECDSA/DSA key getters.
Why not both: with the shadows in place the framework-IL route is closed by construction (a type csharpc implements
makes its assembly ineligible, ADR 0013), and the shadows are cheaper, smaller and let LLVM see through the
wrappers. When a future port of the framework’s own stack becomes possible (libSystem.Native admitted for these
assemblies, SafeHandleMarshaller), the corelib shadows can be removed type by type; the samples are the oracle
(recorded from .NET) for that switch.
SslStream
SslStream and AuthenticatedStream are corelib shadows (corelib/Net/SslStream.cs) over libssl 3 with a memory-BIO pair:
the handshake and the data path move TLS records between the BIOs and the inner stream, synchronously or asynchronously
(one code path, sync selects Stream.Read or ReadAsync). The certificate validation runs inside libssl’s certificate-verify
callback (SSL_CTX_set_cert_verify_callback, an [UnmanagedCallersOnly] function that finds its stream through the SSL*),
as .NET’s CertValidationInCallback does on Linux: a rejected certificate aborts the handshake before the client’s Finished,
the alert goes out, and the peer sees SSL_ERROR_SSL. The validation logic is a copy of VerifyRemoteCertificateCore
(policy errors, name check through X509_check_host/X509_check_ip, chain policy and extra store from the peer’s chain, the
callback or the default decision) and so are the exception types and messages, which the samples compare with .NET’s. The handshake reads whole TLS
records and applies .NET’s frame check (“Cannot determine the frame size or a corrupted frame was received.”) before libssl
sees a byte. ALPN (client list, server selection through SSL_select_next_proto), TLS 1.2 / 1.3 selection, client certificates,
mutual authentication, SNI (TargetHostName on the server), ShutdownAsync and the close-notify end of stream are covered.
Not implemented, explicit diagnostics (a NotSupportedException naming the feature): ServerCertificateSelectionCallback,
ServerOptionsSelectionCallback / SslClientHelloInfo, LocalCertificateSelectionCallback, CipherSuitesPolicy,
SslStreamCertificateContext, NegotiateClientCertificateAsync, channel bindings (TransportContext.GetChannelBinding),
CipherAlgorithm / HashAlgorithm / KeyExchangeAlgorithm and their strengths (NegotiatedCipherSuite works).
Known difference: .NET resumes the TLS sessions of clients without a validation callback (its SslSessionsCache), and a
resumed session skips libssl’s verify callback, so a certificate rejected on a later connection to the same host fails after
the handshake with the bare validation AuthenticationException instead of the one wrapped in “Authentication failed, see
inner exception.”; csharpc never resumes client sessions (the server side can, through libssl’s own cache). The samples
order their failing connections first for that reason.
Platforms
Linux (glibc, x86-64 and arm64), macOS arm64 and Windows x64 (addenda below). WASI (no sockets) keeps the previous
explicit NotSupportedException (“TLS and X.509 certificates … are not supported by csharpc yet”); https:// keeps
failing with that diagnostic there. Each sample is listed in tests/platform-skips.txt as a known gap for WASI.
Addendum (2026-11-07): macOS arm64 over OpenSSL 3
.NET on macOS uses Security.framework (SecKey/SecCertificate/SecTrust for certificates and chains, SecureTransport’s
SSLContext for SslStream). Options for csharpc:
- Security.framework through
[DllImport](CoreFoundationCFData/CFArray/CFDictionarymarshalling,SecPKCS12Import, which needs a keychain for the private key,SecTrustEvaluate,SSLCreateContextwith read/write callbacks). Zero dependencies and the system trust store, but it is a second implementation ofX509Certificate2,X509Chain,RSAand the wholeSslStreamstate machine, SecureTransport (deprecated since macOS 10.15) has no TLS 1.3, and none of it can be debugged locally: every iteration is a CI round trip. - Network.framework: block- and queue-based (
nw_connection), owns the socket; it cannot sit on a managedStreamasSslStreammust. Rejected. - The existing OpenSSL 3 code, bound to Homebrew’s
openssl@3(chosen). The corelib’s X.509, chain, RSA andSslStreamcode is identical on Linux and macOS; only the library path differs (/opt/homebrew/opt/openssl@3/lib/libcrypto.3.dylib,libssl.3.dylib, inOssl.Crypto/Ossl.Ssl; Apple silicon’s Homebrew prefix is fixed, and an absolute path makes a missing library aDllNotFoundExceptionnaming it). The corelib guard isCSHARPC_OPENSSL(defined for Linux, macOS and Windows targets by the driver), replacingCSHARPC_TARGET_LINUXon the TLS code. The samples 1100-1103 and 553 are the oracle, run onmacos-arm64CI.
Cost. Binary size: nothing for programs that use no certificate, TLS or RSA type (the bindings are reached only from those
classes, nothing is linked statically and the dylibs are opened on first use, so the macOS size budgets are untouched);
a program that uses them carries what it carries on Linux (measured on Linux x86-64, stripped: X.509 loading, about
0.8 MB; HttpClient with https:// and an SslStream server, about 3.9 MB). Run-time: macOS programs that use these types need
brew install openssl@3 on the machine, the way Linux programs need libssl.so.3; RSA.Create() joins them, because a
certificate’s private key and an RSA key are the same EVP_PKEY. The hardening posture is that of the Linux build.
What differs from .NET on macOS, and stays so until the Security.framework follow-up:
- Trust. The default chain root set is OpenSSL’s (
SSL_CERT_FILE/SSL_CERT_DIR, Homebrew’scert.pem) plus the bundle macOS keeps at/etc/ssl/cert.pem, not the keychain: roots or distrust settings added in Keychain Access are not seen.X509Storestays out of scope. - Protocols. TLS 1.3 works (OpenSSL), where .NET’s SecureTransport stops at TLS 1.2 (the live run of sample 1101 shows
SslProtocols.Tls13failing under .NET on macOS): a deliberate superset, so the sample skips that case on macOS. LikewiseRSA(sample 553): .NET’s SecKey-based RSA reports other legal key sizes, refuses keys under 1024 bits and doesn’t throwObjectDisposedExceptionfromExportParameters; csharpc keeps the OpenSSL behaviour of Linux there. - Messages that follow .NET’s macOS backend (compared by the live samples): a failed certificate validation is thrown as
the
AuthenticationExceptionitself, not wrapped in “Authentication failed, see inner exception.” as on Linux (.NET validates after SecureTransport’s handshake); chain status texts for an untrusted root and an expired certificate are Security.framework’s (“The certificate was not trusted.”, “An expired certificate was detected.”), other statuses keep OpenSSL’s text; unreadable certificate data is “Unknown format in import.”; a missing certificate file is the file system’s exception; a protocol version mismatch has “bad protocol version” as inner exception message. - Everything the Linux list above names as not implemented (callbacks that select the certificate,
CipherSuitesPolicy,SslStreamCertificateContext, revocation, PKCS#7, extensions, stores) keeps its explicit “not supported by csharpc yet” diagnostic on macOS too.
The zero-dependency route (option 1) remains the follow-up: it would replace Ossl per type behind the same shadows,
with the samples as the oracle, and make the OpenSSL path optional on macOS.
Addendum: Windows over OpenSSL (2026-11-07, issue #134)
.NET’s Windows stack is CNG/CryptoAPI for keys and certificates and SChannel (SSPI) for SslStream. Two ways to get
SslStream, X509Certificate2, X509Chain and https:// there:
- SChannel and crypt32 (what .NET does): no extra DLL, but a second implementation of everything this ADR built:
the SSPI record loop (
InitializeSecurityContext/AcceptSecurityContext/EncryptMessage/DecryptMessageover buffer descriptors),PFXImportCertStoreandCertGetCertificateChainbehind a different certificate model, a second mapping of chain status and policy errors, and no way to debug it except on a Windows machine (CI iterations of ten minutes). - The same corelib code over OpenSSL 3 for Windows (chosen):
OpenSsl.csbindslibcrypto-3-x64.dllandlibssl-3-x64.dll(the names of the official and MSYS2 builds) on Windows, loaded on first use from the executable’s directory orPATH;SslStream,X509*andRSAare unchanged (aCSHARPC_OPENSSLdefine, set for Linux and Windows targets, replaces theCSHARPC_TARGET_LINUXguards). The Linux samples, recorded from .NET, are the oracle and run unchanged, and the stack can be exercised under Wine with the DLLs next to the executable.
What the choice costs:
- A run-time dependency: unlike Linux, where libssl.so.3 is a system library, Windows doesn’t ship OpenSSL. A program
that uses certificates,
SslStream,https://orRSA.Create()must ship the two DLLs (OpenSSL 3.x, x64) next to its executable or have them onPATH; without them the first use throwsDllNotFoundException: Unable to load DLL 'libssl-3-x64.dll' ..., the diagnostic of any P/Invoke. Programs that use none of it load nothing and are byte-identical in size. CI downloads MSYS2’s OpenSSL 3.6 package (pinned release and checksum,setup-toolchain) and puts the two DLLs onPATH. - Windows
longis 32 bits: the bindings that mirror C’slong/unsigned long(d2i_*lengths, theSSL_ctrlfamily,ERR_get_error) useOsslLong/OsslULong, 32-bit on Windows and 64-bit elsewhere. - Trust: OpenSSL has no system store on Windows, so
X509ChainTrustMode.Systemloads theROOTcertificate stores of the current user and the local machine (CertOpenStore/CertEnumCertificatesInStore, read once) as trust anchors. Not consulted: roots Windows would download on demand (the AuthRoot program), theCAintermediate store (servers send their intermediates), certificate revocation.X509Storestays an explicit diagnostic. - RSA:
RSA.Create()uses the same OpenSSL on Windows (it was a CNG known gap); CNG can replace it later, for programs that use RSA without TLS, without touching the TLS code. - Observable differences from SChannel, found by comparing with .NET on a Windows runner: a rejected certificate is thrown as the validation failure itself (csharpc matches that on Windows, where OpenSSL’s callback wraps it on Linux); servers send no TLS 1.3 session tickets on Windows (a client that closes without reading them makes Windows reset the connection and discard the server’s unread close_notify); the inner exception text of a failed handshake is the library’s own, how many server handshakes complete before a client rejects the certificate is the stack’s, and a peer that leaves unread data ends a read as EOF or a reset. The TLS samples print only what .NET defines and normalize these.
- Texts from the TLS library: error messages that come from OpenSSL (
error:...) differ from SChannel’s where .NET reports the OS’s, as on Linux; a sample that prints them is alive:entry on Windows if .NET’s output differs.
SChannel remains the zero-dependency follow-up: it can be added behind the same SslStream shadow as a second backend
(an SSPI-based stream plus a CNG-backed certificate type) when shipping OpenSSL is not acceptable.
Consequences
X509CertificateCollectionderives fromSystem.Collections.CollectionBaseas in .NET (a shadow of it at the time, ADR 0013; the framework’s own IL since ADR 0023, #271).SortedList,QueueandStack, whichCookieContaineruses, come from IL.- Programs that use no certificate or TLS type are byte-identical in size and speed: the OpenSSL bindings are only reached from the new classes.
- The OpenSSL library is a run-time dependency of programs that use these types (libssl.so.3 / libcrypto.so.3, OpenSSL 3).
A machine without it gets the
DllNotFoundExceptionof any P/Invoke, where .NET would fail with its own message. https://works throughSocketsHttpHandlerunchanged (its IL callsSslStream.AuthenticateAsClientAsync(options)); programs that don’t use TLS don’t link any of it.- The certificate’s private key stays an OpenSSL
EVP_PKEY(GetRSAPrivateKey()shares it), so SslStream hands it to libssl without re-importing.
Addendum: Windows without OpenSSL, a spike (2026-11-08, issue #143)
Question: can Windows drop the OpenSSL DLLs by compiling .NET’s own System.Net.Security (SSPI/SChannel) and
System.Security.Cryptography (CNG, crypt32) from the shared framework’s IL, as ADR 0013 did for the compression and
HTTP libraries? The framework’s Windows build of those assemblies P/Invokes sspicli, bcrypt, ncrypt and crypt32
directly (no native shim of its own), so nothing has to be linked besides the OS DLLs, which the bindings load on
first use like any [DllImport].
The opt-in switch. CSHARPC_WINDOWS_NATIVE_TLS=1 (Windows targets only, never the default, no effect on any other
program) does two things: the corelib is built without CSHARPC_OPENSSL and with CSHARPC_NATIVE_TLS, and
Frontend/NativeTls.cs removes the shadows of the OpenSSL-backed family (X509Certificates.*, Oid*, AsnEncodedData,
RSA*, Asymmetric*, Cng*/Csp*, ECDsa/DSA factories, SslStream, AuthenticatedStream, Ssl* options and
contexts, PbeParameters) from the shadow index and from the “types csharpc implements” set that decides eligibility.
System.Security.Cryptography and System.Net.Security become mixed assemblies (ADR 0013): the hash, HMAC, AES,
CryptoStream, random and Negotiate shadows stay, everything else is IL. The framework directory must be the Windows
one (on a Windows host it is; a cross compile from Linux points CSHARPC_SHARED_FRAMEWORK at
Microsoft.NETCore.App.Runtime.win-x64/runtimes/win-x64/lib/net11.0, because the Linux shared framework holds the
Linux build of these assemblies, with Interop.OpenSsl in place of Interop.BCrypt).
What blocked it. Compiling samples 1100, 553, 1101, 1102, 1103 and 1231 for x86_64-w64-windows-gnu against the
Windows IL (the lowering stops a method at its first unsupported construct, so the list is the reachable closure; an
--il-survey over all three assemblies, 11 427 IL methods, adds only the rows marked survey):
| # | Construct | Methods hit | Where | Effort | Fix |
|---|---|---|---|---|---|
| 1 | BigInteger(byte[]), BigInteger(ReadOnlySpan<byte>, bool, bool) |
4 | Formats.Asn1 OIDs, DER integers | small | BigIntegerOps.FromBytes |
| 2 | BigInteger.op_BitwiseAnd, op_RightShift (+ Or, Xor, LeftShift) |
2 | Asn1 EncodeSubIdentifier |
small | two’s complement over ToByteArray |
| 3 | BigInteger.GetBitLength, GetByteCount, TryWriteBytes, ToByteArray(bool, bool) |
2 | crypto key sizes | small | same file |
| 4 | OperatingSystem.IsWindowsVersionAtLeast |
3 | Interop.BCrypt static init |
small | RtlGetVersion (already read by Environment.OSVersion) |
| 5 | MemoryManager<T> base class (Memory, derivation) |
3 | SslStream.Read/Write(Span), PKCS#12 loader, MemoryMappedFiles |
medium | shadow; a Memory<T> is {pointer, length} (objects never move) |
| 6 | nint.ToPointer() |
3 | crypt32 structs (CERT_CONTEXT*) |
trivial | ShadowInstance |
| 7 | MemoryExtensions.ToLowerInvariant(span, span) |
2 | CngKey curve names |
trivial | corelib |
| 8 | Convert.TryFromBase64Chars |
4 | PEM, PKCS | trivial | corelib |
| 9 | PinnedGCHandle<T> |
7 | BCryptExportKey, RSA/PKCS key formats |
small | shadow over GCHandle; GetAddressOfObjectData is the address past the method table, as in .NET |
| 10 | Activator.CreateInstance<Lock>() |
1 | LazyInitializer.EnsureInitialized(ref Lock) |
trivial | codegen special case |
| 11 | AnsiStringMarshaller.ManagedToUnmanagedIn |
1 | LibraryImport of CertFindExtension(string, ...) |
trivial | nested shadow like the UTF-8 one |
| 12 | survey: HashAlgorithm.HashCore(ReadOnlySpan<byte>) override |
100 | HMACMD5/SHA* IL bodies (members-only shadows, unreachable) |
none | not needed: those methods are shadowed |
| 13 | survey: NegotiateAuthentication.IsEncrypted/IsServer, Base64.EncodeToUtf8/DecodeFromUtf8 (5-argument), Vector<byte/ushort>, Interlocked.Decrement on a ref-struct field |
1 to 3 each | NegotiateStream, ConcurrencyBlock |
small each | open; none is reachable from the samples |
Eleven distinct constructs, all fixed (sample 1250_bcl_framework_crypto_surface records them from real .NET and runs
on every platform); after them all six samples compile for Windows with no diagnostic, and the executables link without
a single unresolved symbol (the OS DLLs are bound on first use). None of SafeHandle marshalling, the SSPI structs
(SecBufferDesc, SecHandle), the CNG key blobs or the function-pointer P/Invokes was a blocker: the
LibraryImport-generated stubs are plain IL over DllImports, which the front-end already lowers.
Cost, measured (cross compile on Linux x86-64 for x86_64-w64-windows-gnu, -O2, stripped, CPU seconds on a shared
machine, so wall clock is not comparable):
| Program | OpenSSL path | Native route |
|---|---|---|
| 1100 (load PKCS#12/PEM/DER, chains) | 737 KB; lower 10.5 s, optimize 53 s, codegen 29 s | 2 063 KB (2.8x); lower 35.6 s, optimize 72 s, codegen 61 s; 2 764 IL + 4 224 corelib methods against 0 + 2 269 |
| 1103 (HttpClient over https, SslStream server) | 3 363 KB; lower 38 s, optimize + codegen 220 s | 5 024 KB (+49 %); lower 47 s, optimize + codegen 299 s (+35 %); 5 241 IL + 8 377 corelib methods against 2 871 + 6 866 |
Programs that use no TLS, X.509 or RSA type are unaffected on either path. The native route is bigger and slower to compile because the OpenSSL path wraps one C library in a few thousand lines of corelib, where the native one compiles .NET’s whole managed stack over the OS (the SChannel record loop, the certificate model, PKCS#12/PKCS#7/CMS parsing).
Runtime evidence. Wine 10 runs the 1100 executable far enough to print the subject, issuer, serial, thumbprints
and hash of the PFX certificate exactly as the sample expects (the PKCS#12 import ran through .NET’s own CertificatePal
over crypt32/ncrypt), then stops at SystemTimeToTzSpecificLocalTimeEx, which Wine 10 lacks; 553 generates an RSA key
through RSACng, exports its parameters and makes and verifies a PSS signature, then stops in Wine’s GnuTLS-backed PKCS#1 encryption. Neither is csharpc’s.
On a real Windows runner (targeted CI run, windows-x64, the switch exported by tests/platform.sh and the
OpenSSL DLL step of setup-toolchain disabled, so nothing but the OS provides cryptography): samples 1100, 1101, 1102,
1103, 1231, 553 and 1250 pass at -O0 and -O2, 14 of 14. The one difference of the first run, sample 1102’s “certificate
without a key” case, was WindowsIdentity’s static AsyncLocal<T> with a value-changed handler (reached by
SslStream’s server-side checks) throwing NotSupportedException; the handler is now called on assignments (it is still
not called on execution-context switches, which only matters to impersonation), after which 1102 passes too. The
samples that are live: entries on Windows (1100-1103, 553) compare against real .NET run on the same runner, so these
passes are against SChannel’s and CNG’s own messages, not an approximation of them.
Recommendation: go, as the Windows end state, behind the switch until the open items below are closed. The feared blocker, a large unsupported-construct surface in the SSPI/CNG interop, did not exist: the whole closure needed eleven small, general BCL fixes plus one handler. The costs are size (about +1.7 MB for an https client) and compile time (about +35 %), which the OpenSSL path does not pay; against that stand no run-time dependency, security fixes through the OS, SChannel’s exact exception texts and deleting the Windows half of the OpenSSL surface.
Open items before it can become the Windows default (follow-up work, not this spike):
- the size and compile-time budget: a size regression is a bug (AGENTS.md), and this one is the price of compiling the framework instead of wrapping a C library; trimming the closure (certificate stores, PKCS#7/CMS, ECDSA/DSA/ML-DSA key types that nothing reaches) is the lever, and the owner decides whether the remainder is acceptable;
- the full Windows suite and the TLS-adjacent suites (programs, ASP.NET Core HTTPS) with the switch on, and sample
platform-skipsfor Windows revisited (thelive:entries could become plain passes); - a driver option under NativeAOT’s names instead of the environment variable, and the same for RSA/AES users who need
no TLS (
RSA.Create()through CNG alone, withoutSystem.Net.Security); - X509Store, revocation and the other members the shadows refused become available for free through the framework’s code; each needs a sample recorded on Windows.
Addendum: macOS without OpenSSL, a spike (2026-11-08, issue #144)
Question: can macOS drop Homebrew’s OpenSSL by compiling .NET’s own macOS System.Net.Security and
System.Security.Cryptography from IL and linking the shim they P/Invoke, as ADR 0013 and PR #126 did for compression?
The shim is in the runtime pack. Microsoft.NETCore.App.Runtime.NativeAOT.osx-arm64 (the shared framework’s version,
11.0.0-rc.2.26504.105) ships libSystem.Security.Cryptography.Native.Apple.a (657 KB: 153 AppleCryptoNative_* entry
points over Security.framework, Network.framework and CryptoKit, with a Swift member for AES-GCM, ChaCha20-Poly1305, HKDF and X25519) and
libSystem.Net.Security.Native.a (33 KB: 21 NetSecurityNative_*, GSS.framework). It also ships the macOS managed assemblies
(runtimes/osx-arm64/lib/net11.0), so the macOS IL can be read, and its closure lowered, on a Linux machine. Every
AppleCryptoNative_* / NetSecurityNative_* that the macOS IL imports is exported by the archives, except
AppleCryptoNative_SecKeychainCreateTemporary, which no sample reaches. Link requirements: the frameworks Security, CoreFoundation,
Foundation, CryptoKit, Network (and GSS for Negotiate), -lobjc, and the Swift runtime of the OS (/usr/lib/swift, in the dyld
shared cache since macOS 10.14.4; the SDK holds its stubs): Toolchain.AppleShimLinkFlags adds -L<sdk>/usr/lib/swift,
-rpath /usr/lib/swift and those libraries when the archive is linked. Run-time floor: macOS 10.15 (CryptoKit).
The opt-in switch. CSHARPC_MACOS_NATIVE_TLS=1 (macOS targets only, never the default) is the Windows switch’s macOS twin
(Frontend/NativeTls.cs, the partial IL-first family of ADR 0023): the OpenSSL-backed X.509 / RSA / SslStream shadows are not mapped, the
corelib is built without CSHARPC_OPENSSL, the two assemblies become mixed, and NativeAotPack lists the two shims (bindable only in this
mode: on Linux the same module names belong to IL csharpc shadows). A mixed assembly’s shims are collected too, so the driver links
the archives. A cross compile from Linux uses a directory of the pack’s managed libraries plus its System.Private.CoreLib.dll as
CSHARPC_SHARED_FRAMEWORK.
What blocked it. Compiling 553, 1100, 1101, 1102, 1103 and 1231 for arm64-apple-macosx against the macOS IL. After the eleven
constructs of the Windows spike (#185, all general BCL members), the macOS closure needed three more:
| # | Construct | Where | Effort | Fix |
|---|---|---|---|---|
| 1 | SHA1/SHA384/SHA512.HashData(ReadOnlySpan<byte>, Span<byte>) and TryHashData (SHA256 had them) |
ManagedCertificateFinder |
trivial | corelib Hashing.cs |
| 2 | GCHandle<T> (typed strong handle: ctor, Target, FromIntPtr, ToIntPtr, Dispose) |
SafeDeleteSslContext: the connection pointer SecureTransport hands back to its read/write callbacks |
small | shadow over GCHandle (corelib/GCHandleOfT.cs), like PinnedGCHandle<T> |
| 3 | a generic static abstract interface method called through a type parameter (TIOAdapter.WaitAsync<int>) |
SslStream.ReadAsyncInternal<TIOAdapter> (the same SslStream code as on Windows, where the Windows spike did not report it) |
small | codegen: look the implementation up for the member’s definition and construct it with the call’s type arguments |
Sample 1272_bcl_framework_apple_tls_surface records 1 to 3 from real .NET and runs on every platform. Nothing else was a
blocker: the SafeHandle marshalling, the LibraryImport stubs, the Swift/Objective-C shim boundary (plain C entry points),
function-pointer callbacks and the P/Invoke structs all lowered.
Cost, measured (cross compile on Linux, arm64-apple-macosx, -O2, relocatable object, so no linker and no strip; CPU seconds on a
shared machine). Sample 1100: OpenSSL route 1.23 MB object, 0.65 MB of sections, lower 9.5 s + optimize 40 s + emit 26 s CPU;
native route 3.60 MB object, 1.85 MB of sections (2.9x, the Windows spike’s 2.8x), lower 26 s + optimize 98 s + emit 45 s CPU (2.2x), 2 264 IL +
3 975 corelib methods against 0 + 2 244. The Apple archives add at most about 100 KB of code (the Swift member is 56 KB of it) when
the executable is linked.
Linked executables on the macos-arm64 runner (-O2, stripped, native compile on the runner, wall clock): sample 1100
734 KB (OpenSSL route) against 2 029 KB (native, 2.8x), compile 18.3 s against 24.3 s (+33 %); sample 1103 (HttpClient over https
and an SslStream server) 3 335 KB against 4 756 KB (+43 %), compile 30.4 s against 34.9 s (+15 %). The native executables link
Security, CoreFoundation, Foundation, CryptoKit, Network (and GSS for 1103) and the Swift runtime from /usr/lib/swift;
otool -L shows no OpenSSL, and the OpenSSL-route executable links nothing of the kind (it dlopens Homebrew’s libraries).
Runtime evidence (targeted run on macos-arm64, the switch exported, /opt/homebrew/opt/openssl@3 and its Cellar
moved away so that the OpenSSL route cannot load): samples 1100, 1101, 1102, 1103, 553, 1231, 1250 and 1272 pass at -O0 and -O2, 16 of 16.
They compare against real .NET run on the same runner, so they pass against Security.framework’s and SecureTransport’s own messages,
not an approximation of them.
Recommendation: go, as the macOS end state, behind the switch until the open items are closed. The feared blockers did not exist: the Swift/Objective-C shim is reached through C entry points, and the closure needed three small general fixes on top of the Windows ones. The price is the Windows one (size about 2.9x and compile time about 2x for a TLS program, in return for no run-time dependency, .NET’s exact macOS behaviour, the system keychain trust, and deleting the OpenSSL requirement on macOS).
Open items before it can be the macOS default:
- the size and compile-time budget (trimming the closure is the lever, as on Windows); the owner decides whether the remainder is acceptable;
- the full macOS suite and the TLS-adjacent suites (programs, ASP.NET Core HTTPS) with the switch on, and
platform-skipsfor macOS revisited (the TLS 1.3 and RSA key-size differences of the OpenSSL route disappear with it); - a driver option under NativeAOT’s names instead of the environment variable;
X509Store, revocation, keychain-backed keys and the members the shadows refused are now .NET’s code; each needs a sample recorded on macOS;libSystem.Net.Security.Native(Negotiate/NTLM/Kerberos through GSS) is linked but unexercised;AppleCryptoNative_SecKeychainCreateTemporaryis not in the archive.
Addendum: Linux over the pack’s shims, an opt-in mode (2026-11-08, issues #208, #210)
Question (owner decision of 2026-11-08, #187): link upstream’s native shims instead of csharpc’s own glue. The inventory is in #208:
on linux-x64 and linux-arm64 the NativeAOT runtime pack ships libSystem.Native.a (277 SystemNative_*) and
libSystem.Security.Cryptography.Native.OpenSsl.a (415 CryptoNative_*; every OpenSSL function is a pointer it fills with dlsym
on first use, so there is no link-time OpenSSL dependency), and they export every entry point the shared framework’s IL imports
(237 and 397 distinct). osx-arm64 has libSystem.Native.a and the Apple crypto shim (#202); win-x64 has neither.
The mode. CSHARPC_LINUX_NATIVE_TLS=1 (glibc Linux only, never the default) is the Windows and macOS switches’ Linux twin
(Frontend/NativeTls.cs, the partial IL-first family of ADR 0023): the OpenSSL-backed X.509 / RSA / SslStream shadows are not
mapped, the corelib is built without CSHARPC_OPENSSL, System.Security.Cryptography and System.Net.Security are compiled from
the shared framework’s IL (hash, HMAC, AES and Negotiate shadows stay), and NativeAotPack links the OpenSSL shim and lets those
two assemblies call libSystem.Native (for certificate files, environment and the like). The glue of Crypto/OpenSsl.cs
(the corelib’s own libssl/libcrypto bindings) is not compiled in this mode: CryptoNative_* replaces it.
What it needed, all general members and none specific to a library (sample 1273_bcl_linux_tls_surface): the span overloads of
DateTime.ParseExact/TryParseExact, Convert.TryToBase64Chars, GC.GetGeneration(object), the typed WeakGCHandle<T>, default
ValueType.Equals/GetHashCode of a struct that holds a BCL InlineArray (chain processing boxes one into its event log), and an
[UnsafeAccessor] whose type is named by a string: the certificate downloader reaches HttpClient that way, inside a try/catch that
gives up when the type cannot be loaded, so csharpc lowers such an accessor to the MissingMethodException .NET throws for a missing
member and AIA/CRL downloads are skipped, as under NativeAOT without System.Net.Http.
Cost, measured (Linux x86-64, -O2, stripped; sizes of the executables):
| Sample | Shadows (default) | IL over the shims | Ratio |
|---|---|---|---|
| 1100_x509_certificates | 827 KB | 3,116 KB | 3.8x |
| 553_rsa | 626 KB | 1,107 KB | 1.8x |
| 1101_sslstream_loopback | 1,222 KB | 3,709 KB | 3.0x |
| 1102_sslstream_validation | 1,196 KB | 3,676 KB | 3.1x |
| 1103_httpclient_https | 3,925 KB | 5,956 KB | 1.5x |
All five are byte-identical to .NET on both routes. A program that uses no TLS, X.509 or RSA type is unchanged (hello with
libSystem.Native.a on the link line is byte-identical, and no budget program reaches a shim).
What deleting the glue needs. Nothing becomes unreachable while the shadows are the default, so this mode deletes no lines yet.
Of the 2,886 lines the ownership map calls glue: Crypto/OpenSsl.cs (282) and the X.509/RSA/Tls/SslStream shadows it serves
(about 4,300) go if this route becomes the Linux default, which is the owner’s call (security, speed, size pull apart: size 1.5 to
3.8x for a TLS program, the macOS and Windows spikes measured 2.9x and a longer compile). Crypto/AesNative.cs (440) goes with the Aes
and hash shadows. IO/Posix.cs (243), Net/NetNative.cs (831) and Net/SocketEngine.cs (585) serve File, Directory, FileStream,
Environment, Process and Socket, which are corelib types (System.Private.CoreLib is csharpc’s contract, #191 part B) or shadows
of assemblies that also carry signal handling and child-process machinery (Console, Process, Pipes, Sockets); IO/Win32.cs (402) and
IO/ConsoleKeysWindows.cs (103) have no shim in the pack at all (the Windows IL binds the OS DLLs). They are kept, and no library-specific
shim is added.
Addendum: Linux default is the framework’s IL over C# contracts (2026-11-21, #423, #449)
On Linux, System.Security.Cryptography and System.Net.Security are now compiled from the shared framework’s IL by default, without
linking the pack’s shims: their CryptoNative_* and NetSecurityNative_* P/Invokes bind to C# ports of the shims over OpenSSL 3 and
libgssapi_krb5 (corelib/Crypto/CryptoNative*.cs, corelib/Net/NetSecurityNative.cs), the same mechanism as the file-system and
socket contracts. TLS stays on OpenSSL; certificate validation, host-name checks and chain policy are the framework’s IL. The corelib is
built without CSHARPC_OPENSSL for Linux targets and the OpenSSL-backed copies (Crypto/OpenSsl.cs, the X.509/RSA/SslStream/Negotiate
files) are compiled only for macOS, Windows and WASI (#449). CSHARPC_LINUX_NATIVE_TLS=1 still links the pack’s shims instead.
Measurements and the security review of the contracts: System.Net.Security.md (TLS throughput
0.29x the copies’ time and 0.95x NativeAOT’s; TLS executables 1.5x to 3.3x the copies’ size, still smaller than NativeAOT’s).