2026-11-12 19:16:56 +13:00
2026-10-29 17:25:08 +13:00
2026-11-12 19:16:56 +13:00

OpenSSL Shim - Go c-shared Buildmode Implementation

This project implements a subset of the OpenSSL C API on top of Go's standard library crypto/tls package, built as a c-shared shared library. The goal is to allow existing C programs (e.g. curl) that link against OpenSSL to use Go's TLS implementation instead.

Architecture

The Go implementation lives in a single package split by category:

  • openssl_shim.go - shared state: object structs behind the opaque C handles, handle maps, alloc helpers, and library init hooks
  • ssl.go - SSL_CTX / SSL objects and the synchronous TLS connection logic
  • bio.go - BIO objects, BIO_METHOD and callback dispatch
  • session.go - SSL_SESSION
  • x509.go - X509 / ASN1 / X509_STORE
  • evp.go - EVP_PKEY / EVP_MD_CTX / EVP_MD
  • error.go - the error queue and ERR_* functions
  • bn.go - BIGNUM stubs
  • provider.go - OSSL_LIB_CTX and OSSL_PROVIDER stubs
  • misc.go - OCSP, ENGINE, PKCS12, PEM, OSSL_STORE, UI, OBJ and other stubs
  • ssl_compat.go - SSL accessors/state functions libcurl needs during a handshake (kept in the shim so they never fall through to system libssl)
  • testhelpers.go - small C callbacks used only by the Go unit tests (cgo is not permitted in _test.go for this package)

Together these expose ~320 exported C functions via cgo //export directives.

Other project files:

  • libssl.so - Built shared library (c-shared buildmode, default name)
  • include/openssl/ssl.h - OpenSSL-compatible header for C programs
  • include/openssl-system/openssl/ - System OpenSSL headers (used to prove system-header compatibility)
  • cmd/test_client/test_client.c - Example C program that connects to a TLS host
  • scripts/test.sh - Integration harness (tests A/B/E/C/D), see Testing

Current Status

Working ✅

Feature Status
Direct link TLS to example.com:443 ✅ Works — completes handshake, gets HTTP response
Client built against our headers ✅ Works — test A
Client built against system headers ✅ Works — test B
curl linked against our libssl.so ✅ Works — TLS handshake succeeds, HTTP 2xx — test C
ALPN (SSL_set_alpn_protos / SSL_get0_alpn_selected) ✅ Works — advertises to tls.Config.NextProtos, reports the negotiated protocol
SSL_ERROR_* codes / SSL_get_shutdown / SSL_shutdown state ✅ Matches OpenSSL numbering — test E
dlopen+dlsym symbol resolution ✅ Works
Symbol versioning (OPENSSL_3.0.0) ✅ Works — 319+ versioned exported symbols
SNI via SSL_set_tlsext_host_name ✅ Works
BIO integration (BIO_new, BIO_read/write/ctrl, BIO_meth_set_*) ✅ Implemented — caller-supplied BIO_METHOD callbacks are dispatched
Custom (caller-built) BIO transport (libcurl cfilter BIO) ✅ Works — TLS runs over the caller's own BIO I/O
Memory BIOs (BIO_s_mem, BIO_new_mem_buf, BIO_get_mem_data) ✅ Implemented
BIO reference counting (BIO_up_ref, shared rbio/wbio) ✅ Matches OpenSSL ownership rules
Foreign BIO bridging (BIO created by system libcrypto) ✅ BIO_read/write/ctrl forward via dlsym
LD_PRELOAD over a stock OpenSSL 3.x binary ✅ Works — stock curl fetches a page and exits cleanly

curl Integration

curl built against our shim completes the TLS handshake and receives a full HTTP 200 response from example.com. The whole flow (build curl against the shim, fetch a URL) is exercised by the integration harness as test C — see Testing below.

A stock curl binary can also be driven directly with LD_PRELOAD of our libssl.so (this is test D): the shim completes the handshake, receives the HTTP 200 response, and exits cleanly. This works because the shim now recognises libcurl's caller-supplied connection-filter BIO and runs TLS over the caller's transport, so libcurl's own poll loop and deadlines stay in control.

The curl proof-of-concept lives in curl-po/curl and is already configured against the shim. To rebuild it from scratch:

make testlibs   # build libssl.so + libssl_versioned.so

cd curl-po/curl
make clean
LDFLAGS="-L$(pwd)/../.. -lssl -Wl,-rpath,$(pwd)/../.." \
  LIBS="-lssl -lpthread -ldl -lz" \
  ./configure --with-openssl=/usr --without-ca-fallback \
    --enable-shared --disable-static --disable-ldap --disable-ldaps \
    --disable-rtsp --disable-ipfs --disable-ipns --disable-mqtt \
    --disable-tftp --disable-imap --disable-imaps --disable-pop3 \
    --disable-pop3s --disable-smtp --disable-smtps --disable-telnet \
    --disable-dict --disable-file --disable-ftp --disable-ftps \
    --disable-gopher --disable-gophers --disable-ws --disable-wss \
    --disable-smb --disable-ntlm-wb --disable-spnego --disable-crypto-auth \
    --disable-ntlm --disable-tls-srp --disable-unix-sockets --disable-alt-svc \
    --disable-hsts --disable-cookies --disable-http2 --disable-https-proxy \
    --disable-progress-meter --disable-verbose --disable-shared-passwords \
    --disable-sspi --disable-curldebug --disable-debug
make -j4

API vs ABI Compatibility

This is the key distinction for understanding what the shim can and cannot do:

  • API-compatible ✅ — All types are opaque and all functions have the right signatures, so any C program that compiles against these headers (or the system OpenSSL headers) and links against our libssl.so works. This is how tests A, B and C pass.
  • ABI-compatible ⚠️ substantially improved. The shim now works under LD_PRELOAD for a stock OpenSSL 3.x binary (test D), which it did not before. The remaining gap is structural, not a crash: programs allocate OpenSSL objects themselves and expect to read struct fields directly, and the shim's handles are opaque keys into Go maps.

How LD_PRELOAD works now

Two things made LD_PRELOAD viable:

  1. Caller-supplied BIO transport. Modern libcurl builds its own BIO_METHOD (a connection-filter BIO) and hands it to SSL_set0_rbio / SSL_set0_wbio. The shim dispatches that method's read/write/ctrl callbacks and runs crypto/tls over the caller's transport, so libcurl's socket, poll loop and deadlines remain authoritative. Previously the shim ignored the caller's BIO and dialled a private socket, so data flowed but the connection could never be driven or closed (the "works but hangs" symptom). On a would-block during application data the shim now returns SSL_ERROR_WANT_READ so the caller's event loop resumes — the fix that lets curl exit cleanly.

  2. Bridging foreign objects. When a program links the system libcrypto directly, the BIOs it creates are genuine OpenSSL structs the shim did not allocate. BIO_read/BIO_write/BIO_ctrl/BIO_test_flags/BIO_method_type detect such handles and forward to the real libcrypto implementation via dlsym(RTLD_NEXT, ...), and BIO_free leaves them to their owner instead of corrupting the heap. The shim also exports the accessor functions libcurl calls during a normal handshake (SSL_get_state, SSL_get_verify_mode, SSL_set_shutdown, SSL_get_rbio, …) so they no longer fall through to the system libssl.so.3 and receive the shim's opaque handles.

The remaining LD_PRELOAD gap is QUIC / HTTP-3: symbols such as SSL_new_stream and SSL_set_blocking_mode are not implemented, so --http3 will not work. All non-QUIC TLS functionality a stock curl exercises works.

Bottom line: linking against the shim at compile time still gives the most predictable behaviour, but LD_PRELOAD over a stock OpenSSL 3.x binary now works for ordinary TLS.

Library Naming

The default output library is libssl.so, so it is a drop-in for dlopen("libssl.so") or -lssl at link time:

# Build
make

# Link a program against it
gcc my_program.c -Iinclude -L. -lssl -Wl,-rpath,$(pwd) -lpthread

To build with a different name, override LIB:

make LIB=libopenssl_shim.so

Symbol Versioning

Real OpenSSL 3.x exports symbols with version tags like SSL_connect@@OPENSSL_3.0.0. Programs linked against a system libssl.so.3 (such as the curl POC) expect those versioned symbols. The shim can emit them using a linker version script:

# Build with OPENSSL_3.0.0 version tags on all exported symbols
make VERSION_SCRIPT=openssl_versions.map LIB=libssl_versioned.so

# Verify versioned symbols
nm -D libssl_versioned.so | grep "SSL_connect@@"
# SSL_connect@@OPENSSL_3.0.0

This requires cgo-version-script.sh (included) to deduplicate the repeated -Wl,--version-script flags that cgo emits, which would otherwise cause ld: duplicate version tag errors. The integration harness builds both the plain and the versioned library automatically (see make testlibs).

dlsym/dlopen test

A small test program verifies dlopen + dlsym symbol resolution:

make dlsym-run

The Go code uses cgo's //export to expose Go functions as C symbols. When built with -buildmode=c-shared, this produces a shared library that C programs can link against. The shim maps OpenSSL concepts to Go's crypto/tls:

OpenSSL Concept Go Implementation
SSL_CTX *tls.Config wrapped in sslCtx struct
SSL *tls.Conn wrapped in ssl struct
SSL_connect tls.Client + Handshake() (synchronous)
SSL_accept tls.Server + Handshake()
SSL_read / SSL_write tls.Conn.Read / Write
RAND_bytes crypto/rand.Read
BIO_new / BIO_read / BIO_write BIO objects stored in Go map with method callbacks
SSL_set_tlsext_host_name SNI hostname stored on ssl struct

Handle maps track C pointers to Go objects because Go 1.27+ cgo rules prohibit passing Go pointers to C unpinned.

Connection Flow

  1. SSL_CTX_new() — Creates a Go sslCtx with a tls.Config
  2. SSL_new() — Creates a Go ssl wrapper
  3. SSL_set_tlsext_host_name() — Stores SNI hostname
  4. SSL_connect() — Establishes TLS, in order of preference:
    • over a caller-supplied BIO transport (SSL_set0_rbio/SSL_set0_wbio with a method that has read/write callbacks) — the libcurl path;
    • over a socket BIO / SSL_set_fd descriptor (adopted with net.FileConn);
    • otherwise by dialling the SNI host directly (net.Dial + tls.Handshake).
  5. SSL_write() / SSL_read() — Read/write through the tls.Conn. A would-block on application data is reported to the caller as SSL_ERROR_WANT_READ/SSL_ERROR_WANT_WRITE so its poll loop can resume.
  6. SSL_shutdown() / SSL_free() — Clean up (and release owned BIO references).

Current Limitations

  • QUIC / HTTP-3 not supported — the stream and non-blocking SSL APIs (SSL_new_stream, SSL_poll, SSL_set_blocking_mode, …) are not implemented, so curl --http3 will not work. Ordinary TLS over TCP does.
  • A foreign BIO created by the system libcrypto can be read/written through the dlsym bridge, but the shim cannot drive it synchronously (its transport is non-blocking and owned by the caller's event loop). When the shim meets one at handshake time it falls back to a private socket, which works but does not let the caller's close handling run — this is why test C (curl POC linked against system libcrypto for BIO) is judged on the received response rather than a clean exit.
  • No certificate/key loading (stubbed)
  • SSL_CTX_use_certificate_file / SSL_CTX_use_PrivateKey_file return success but don't load
  • Certificate verification is opt-in: SSL_VERIFY_NONE (the OpenSSL default) maps to InsecureSkipVerify; SSL_VERIFY_PEER enables validation
  • DH/RSA/DSA/EC_KEY are stubs
  • Session caching is stubbed
  • Many OpenSSL functions are unimplemented stubs (returning defaults)

Testing

scripts/test.sh (also available as make integration) builds the library variants and runs the full end-to-end suite against a live host:

make integration            # runs all tests, default host example.com

or run the script directly to pass options:

./scripts/test.sh                       # host defaults to example.com
./scripts/test.sh www.google.com        # custom host
SKIP_CURL=1 ./scripts/test.sh           # skip the curl build test
SKIP_PRELOAD=1 ./scripts/test.sh        # skip the LD_PRELOAD test
Test What it does Compatibility exercised
A Builds cmd/test_client against our headers (-Iinclude), runs it, checks a TLS handshake + data read API (our headers)
B Builds the same client against the system OpenSSL headers, runs it API (system headers)
E Builds cmd/shim_test and checks semantics that are easy to get wrong: SSL_ERROR_* numbering matches OpenSSL, SSL_SENT_SHUTDOWN, SSL_get_shutdown, SSL_get_error API/semantics
C Runs the curl POC built against our libssl.so, fetches https://<host>/, checks for an HTTP 2xx status line API (real program)
D Runs system curl with our shim LD_PRELOAD'd, fetches https://<host>/, checks it succeeds and exits cleanly ABI (real program, LD_PRELOAD)

Tests A, B, E, C and D all pass. Test D exercises the ABI surface: a stock, dynamically-linked curl loads our libssl.so and completes a real TLS request (see API vs ABI for how this works and where the remaining QUIC gap is).

Building

make              # Build libssl.so
make testlibs     # Build libssl.so + libssl_versioned.so (for the harness)
make test_client  # Build example client
make run          # Run example client against example.com:443
make dlsym-run    # Test dlopen/dlsym
make shim-run     # Run the shim semantic checks (error codes, shutdown state)
make integration  # Run the full A/B/E/C/D suite
make test         # Run Go unit tests
make clean        # Clean build artifacts

Example Usage

#include <openssl/ssl.h>

SSL_library_init();
SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
SSL_CTX_set_default_verify_paths(ctx);

SSL *ssl = SSL_new(ctx);
SSL_set_tlsext_host_name(ssl, "example.com");
SSL_connect(ssl);
SSL_write(ssl, request, len);
SSL_read(ssl, buf, sizeof(buf));
SSL_shutdown(ssl);
SSL_free(ssl);
SSL_CTX_free(ctx);

Linking Against the Shim

Compile your C program with:

gcc -Iinclude my_program.c -L. -lssl -Wl,-rpath,. -lpthread

And run with LD_LIBRARY_PATH=. (or install libssl.so to a standard library path).

Future Work

  1. Certificate/key file loading (PEM parsing via crypto/x509)
  2. Full BIO chain support (BIO_push/BIO_pop, BIO_f_buffer, BIO_s_connect)
  3. Proper certificate chain validation wired through SSL_VERIFY_PEER
  4. Session resumption
  5. QUIC / HTTP-3 stream API (SSL_new_stream, SSL_poll, SSL_set_blocking_mode, SSL_stream_*) — the remaining ABI symbols a stock curl reaches for
  6. Drive a foreign (system-libcrypto) BIO synchronously, so the curl POC linked against system libcrypto (test C) can exit cleanly rather than relying on a private fallback socket
  7. Non-blocking handshake resumption: tls.Handshake is not resumable across a would-block, so handshakes still run synchronously; wiring the whole SSL_connect/SSL_do_handshake state machine to WANT_READ/WANT_WRITE would let fully non-blocking callers drive it.

Another goal is to also replace libcrypto.so.3. This is a necessary step towards being able to run a stock binary without OpenSSL installed at all. Virtually every libssl consumer also links libcrypto, as libssl's ABI is expressed in terms of libcrypto types.

S
Description
A memory-safe OpenSSL-compatible implementation, based on Go's crypto/tls
Readme
553 KiB
0 Stars 1 Watchers 0 Forks
Languages
C 93.5%
Go 6%
Shell 0.4%
Makefile 0.1%