keyless_tls is designed so that the tunnel application handles the TLS handshake and traffic encryption/decryption, while only the CertificateVerify signature is delegated to a remote signer.
- TLS engine, session keys, traffic crypto:
tunneling app - TLS signing (
CertificateVerify): remoterelay signer - Signer transport:
HTTPS + JSONwith mandatorymTLS
This repository supports two usage modes:
- Use as an SDK library (
keylesspackage) - Run the provided binaries under
cmd/*
- I want keyless remote signing for my TLS app: transcript-bound keyless mode (
keyless+keyless/t13server) - I want to run it immediately and validate behavior: Binary mode
The tunnel app keeps only the public certificate chain (cert PEM) and does not hold the private key.
The keyless SDK provides a remote transcript signer: the TLS 1.3 handshake is performed by the tunnel
app (via keyless/t13server), and only the CertificateVerify transcript signature is delegated to the
remote signer over /v1/sign.
keyless.NewRemoteSigner: create a remote transcript signer clientkeyless/t13server: TLS 1.3 server engine that signs its handshake through aTranscriptSigner(it implementsnet.Connand integrates withhttp.Server)keyless.NewServerTLSConfig: build atls.Configfor deployments that hold a local private key
package main
import (
"log"
"net"
"net/http"
"os"
"github.com/gosuda/keyless_tls/keyless"
"github.com/gosuda/keyless_tls/keyless/t13server"
)
// keylessListener upgrades raw TCP connections into transcript-bound keyless TLS connections.
type keylessListener struct {
net.Listener
tlsSrv *t13server.Server
}
// binding is application-specific authorization context carried with the
// exact TLS transcript to the remote signer. Real deployments should derive
// this per connection/route/tenant and validate it on the signer side.
var binding = []byte("example-app")
func (l *keylessListener) Accept() (net.Conn, error) {
raw, err := l.Listener.Accept()
if err != nil {
return nil, err
}
return l.tlsSrv.NewConn(raw, binding), nil
}
func main() {
certPEM := mustRead("certs/public-chain.crt")
rSigner, err := keyless.NewRemoteSigner(keyless.RemoteSignerConfig{
Endpoint: "127.0.0.1:9443",
ServerName: "relay.internal",
KeyID: "relay-cert",
RootCAPEM: mustRead("certs/relay-ca.crt"),
ClientCertPEM: mustRead("certs/tunnel-client.crt"),
ClientKeyPEM: mustRead("certs/tunnel-client.key"),
})
if err != nil {
log.Fatal(err)
}
defer rSigner.Close()
tlsSrv, err := t13server.NewServer(t13server.Config{
CertPEM: certPEM,
KeyID: "relay-cert",
TranscriptSigner: rSigner,
})
if err != nil {
log.Fatal(err)
}
lis, err := net.Listen("tcp", ":8443")
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("ok\n"))
})
srv := &http.Server{Handler: mux}
log.Fatal(srv.Serve(&keylessListener{Listener: lis, tlsSrv: tlsSrv}))
}
func mustRead(path string) []byte {
b, err := os.ReadFile(path)
if err != nil {
panic(err)
}
return b
}A runnable version lives in examples/tunnel-http. The binding shown above is only an
example value; production integrations should derive an opaque binding from the connection's
authorization context and configure a TranscriptValidator that verifies that binding before
the signer produces a CertificateVerify signature.
The signer bounds in-flight private-key operations globally (32 by default)
and per key (8 by default). It does not queue an unbounded number of
operations: requests that cannot acquire a slot fail immediately with HTTP
429 Too Many Requests and Retry-After: 1. Direct callers of
signer.Service receive signer.ErrOverloaded. The counters are available
through Service.RejectedSigns().
The HTTPS signing handler also limits each mTLS client certificate to four
concurrent requests and a token bucket of 20 requests/second, burst 40.
The aggregate request limit is 128, or the configured per-client concurrency
when that is higher. Server read deadlines bound incomplete request bodies so
they cannot retain request admission slots indefinitely.
In explicit insecure/demo mode without mTLS, limits apply to the network
source IP instead. Configure the signer binary with -max-signs,
-max-signs-per-key, -max-client-concurrent, -client-rate, and
-client-burst to match the HSM capacity and expected traffic.
The public t13server.Server bounds simultaneous handshakes to 64 total
and eight per source IP, plus a 20/s per-source bucket (burst 40). Admission
happens before parsing ClientHello or invoking the remote signer, including
when callers use NewConn directly. Excess handshakes fail with
t13server.ErrHandshakeOverloaded; failures can be measured through
Server.RejectedHandshakes(). Use the t13server.Config admission fields or
the examples/tunnel-http flags (-max-handshakes,
-max-handshakes-per-source, -handshake-rate, -handshake-burst) to
adjust capacity. The source-IP limits use the actual TCP peer address.
If a reverse proxy or NAT concentrates many independent users under one IP,
adjust the per-source limits and enforce additional limits at that ingress.
These controls bound resource consumption but do not authenticate a public TLS peer before CertificateVerify. Put an L4 connection limit in front of Internet-facing listeners as additional protection against distributed floods.
If the signer endpoint is protected by a rotating access token, attach it with
RemoteSignerConfig.Headers. The callback runs for every /v1/sign request and
must be safe for concurrent use:
remoteSignerCfg.Headers = func() http.Header {
h := make(http.Header)
h.Set("X-Portal-Access-Token", currentAccessToken())
return h
}If a deployment holds its private key locally, keyless.NewServerTLSConfig builds a standard
tls.Config for Go's TLS stack. This path does not involve the remote signer.
keyless.NewServerTLSConfig can pass ECH keys through to Go's TLS stack for
local-key deployments:
tlsConf, err := keyless.NewServerTLSConfig(keyless.ServerTLSConfig{
CertPEM: certPEM,
Signer: localSigner,
EncryptedClientHelloKeys: []tls.EncryptedClientHelloKey{
{
Config: echConfig,
PrivateKey: echPrivateKey,
SendAsRetry: true,
},
},
})The tunnel app must have the ECH private key because it owns the TLS handshake
and decrypts ClientHello. The remote signer still only signs
CertificateVerify; it does not receive ECH secrets or traffic keys.
ECH config generation and publication are intentionally external to this SDK. Distribute the matching ECHConfigList to clients through your chosen control plane, typically DNS HTTPS/SVCB records.
Client-side ECH fallback is intentionally opt-in because it trades SNI privacy
for availability. Use DialClientTLS with AllowECHFallback to retry once
without ECH only when Go reports tls.ECHRejectionError:
tlsConf, err := keyless.NewClientTLSConfigWithOptions(keyless.ClientTLSConfigOptions{
ServerName: "app.example.com",
RootCAPEM: rootCAPEM,
EncryptedClientHelloConfigList: echConfigList,
})
if err != nil {
// handle error
}
conn, err := keyless.DialClientTLS(ctx, "tcp", "app.example.com:443", keyless.ClientDialConfig{
TLSConfig: tlsConf,
AllowECHFallback: true,
})If you are implementing your own relay/proxy with this library, use the relay/l4
APIs to inspect ClientHello and route by SNI/ALPN while keeping all policy in caller code.
l4.InspectClientHello(conn, timeout): parseServerName/ALPNProtocols/ECHOfferedand return a wrappednet.Connl4.Proxy.DialByClientHello(ctx, info, parseErr): caller decides route/fallback/reject policy
How this works in practice:
- incoming TCP connection arrives
- library reads only visible ClientHello metadata (no TLS termination)
- your callback receives
info.ServerName,info.ALPNProtocols,info.ECHOffered, andparseErr - your code selects upstream target (or rejects)
- relay continues raw TCP forwarding; TLS payload stays opaque to the relay
Typical SDK routing policies:
- Multi-tenant host routing:
app1.example.com -> tenant A,app2.example.com -> tenant B - Protocol-aware routing:
h2preferred upstream vshttp/1.1upstream - Default fallback for unmatched visible SNI, including ECH outer SNI misses
- Strict security mode: reject when ClientHello parse fails
- Compatibility mode: fallback to default upstream when parse fails
Relay ECH policy is intentionally simple: the relay sees only the visible outer
SNI and whether ECH was offered. It does not see the encrypted inner SNI or TLS
payload. When info.ECHOffered is true, info.ServerName is the outer public
name. Route by that outer name, use the default upstream for unmatched outer SNI
when configured, or reject.
Concrete policy example (easy to adapt):
routes := map[string]string{
"app1.demo.local": "127.0.0.1:9001",
"app2.demo.local": "127.0.0.1:9002",
}
proxy := &l4.Proxy{
ListenAddr: ":443",
ClientHelloTimeout: 2 * time.Second,
DialByClientHello: func(ctx context.Context, info l4.ClientHelloInfo, parseErr error) (net.Conn, error) {
d := net.Dialer{Timeout: 3 * time.Second}
// 1) Decide what to do with non-TLS / invalid ClientHello
if parseErr != nil {
// strict mode: return nil, parseErr
// compatibility mode: send to default route
return d.DialContext(ctx, "tcp", "127.0.0.1:9011")
}
// 2) SNI host-based route
if target, ok := routes[strings.ToLower(strings.TrimSuffix(info.ServerName, "."))]; ok {
return d.DialContext(ctx, "tcp", target)
}
// 3) Optional ALPN-aware split
for _, proto := range info.ALPNProtocols {
if proto == "h2" {
return d.DialContext(ctx, "tcp", "127.0.0.1:9443")
}
}
// 4) Default route
return d.DialContext(ctx, "tcp", "127.0.0.1:9011")
},
}For a complete runnable SDK-style routing sample with 10 hosts, see examples/relay-10-targets.
- Deploy only the public certificate chain (
cert PEM) in the tunnel app - Configure signer endpoint/server name/
KeyID/root CA - Provide mTLS client materials (
client cert/key) - Call
remoteSigner.Close()on shutdown
cmd/ contains production-oriented main packages (runnable binaries).
Example applications are separated under examples/.
cmd/relay-signer: remote signer HTTPS servercmd/relay-l4: L4 TCP relay with optional SNI-based route mappingexamples/tunnel-http: example tunnel HTTP server integrated with the SDKexamples/relay-10-targets: one relay server routing to 10 target hosts via SNI
If you are building your own relay/proxy, use relay/l4.InspectClientHello to read
ClientHello metadata (ServerName, ALPNProtocols) without terminating TLS.
The helper returns a wrapped net.Conn that replays already-read bytes, so your
relay can continue normal TCP forwarding after routing decisions.
relay/l4.Proxy also supports callback-based dialing through
DialByClientHello(ctx, info, parseErr), so all policy decisions (fallback, reject,
default route) remain in caller code.
- Run signer server
go run ./cmd/relay-signer \
-listen :9443 \
-key-id relay-cert \
-tls-cert certs/relay-server.crt \
-tls-key certs/relay-server.key \
-client-ca certs/client-ca.crt \
-sign-key certs/relay-signing.keyrelay-signer warns at startup when no TranscriptValidator is configured: the
library then signs every structurally valid request, which is the generic
primitive. Deciding what a request's binding must contain — lease, stream,
hostname, anything — is deployment policy, so production deployments run a
signer with a validator that authorizes the binding (and transcript) field
before a CertificateVerify signature is produced.
- Run tunnel app
go run ./examples/tunnel-http \
-listen :8443 \
-cert certs/public-chain.crt \
-signer-addr 127.0.0.1:9443 \
-signer-name relay.internal \
-key-id relay-cert \
-client-cert certs/tunnel-client.crt \
-client-key certs/tunnel-client.key \
-root-ca certs/relay-ca.crt- Run L4 relay
go run ./cmd/relay-l4 \
-listen :443 \
-route app1.example.com=127.0.0.1:8443 \
-default-upstream 127.0.0.1:8443SNI route mode (-route can be repeated):
go run ./cmd/relay-l4 \
-listen :443 \
-route app1.example.com=127.0.0.1:8441 \
-route app2.example.com=127.0.0.1:8442 \
-default-upstream 127.0.0.1:8440cmd/relay-l4 does not enforce routing policy. Caller-side policy is controlled by flags,
including whether ClientHello parse failures may use the default upstream.
Useful cmd/relay-l4 route-mode flags:
-route host=upstream(repeatable): explicit SNI mapping-default-upstream: fallback target for unknown visible SNI, including ECH outer SNI misses-allow-parse-error: allow non-TLS/invalid ClientHello to use fallback-clienthello-timeout: maximum ClientHello inspection time-max-connections: simultaneous relay connection cap, including ClientHello inspection (default 1,024)-max-connections-per-ip: simultaneous connections allowed from one source IP (default 64)-idle-timeout: close established connections after this period without traffic in either direction (default 2 minutes)
These limits apply before routing and remain in force after routing. SDK users can set
l4.Proxy.MaxConnections, MaxConnectionsPerIP, and IdleTimeout. A zero value
selects the same safe defaults; negative values are rejected by Proxy.Serve.
The inspector rejects TLS handshake records larger than 16 KiB and bounds fragmented
ClientHello inspection to 64 KiB of handshake data, 128 KiB of captured traffic,
and 128 records. Inspection-limit errors are rejected before routing, including
when parse-error fallback is enabled. Cancellation closes admitted connections
and their upstreams.
examples/relay-10-targets demonstrates a practical ingress layout:
- one public relay listener
- ten target tunnel apps
- SNI-based target selection implemented by caller code
Run the example relay:
go run ./examples/relay-10-targets \
-listen :443 \
-upstream-host 127.0.0.1 \
-base-port 9001 \
-domain demo.local \
-default-upstream 127.0.0.1:9011Generated static routes:
app1.demo.local -> 127.0.0.1:9001app2.demo.local -> 127.0.0.1:9002app3.demo.local -> 127.0.0.1:9003app4.demo.local -> 127.0.0.1:9004app5.demo.local -> 127.0.0.1:9005app6.demo.local -> 127.0.0.1:9006app7.demo.local -> 127.0.0.1:9007app8.demo.local -> 127.0.0.1:9008app9.demo.local -> 127.0.0.1:9009app10.demo.local -> 127.0.0.1:9010
Policy remains caller-owned:
- known SNI: route to mapped upstream
- unknown visible SNI: route to
-default-upstreamwhen configured - ECH with no matching outer SNI route: route to
-default-upstreamwhen configured - non-TLS or invalid ClientHello: route to
-default-upstreamwhen configured, otherwise reject
Important flags for examples/relay-10-targets:
-listen: public relay address-upstream-host: host used for generated targets-base-port: first target port (app1)-domain: host suffix used for SNI matching-default-upstream: optional fallback upstream for unknown visible SNI and ECH outer SNI misses-dial-timeout: upstream dial timeout-clienthello-timeout: ClientHello inspection timeout
Signer and tunnel clients must use mutual TLS in production. relay/server.ListenAndServe rejects a missing ClientCAPEM before opening a listener. The only exception is the explicit insecure local/demo mode: server.Config.AllowInsecureNoClientAuth (or the binary's -allow-insecure-no-client-auth). Never expose a demo-mode signer to untrusted networks.
go run ./cmd/relay-signer \
-listen :9443 \
-key-id relay-cert \
-tls-cert certs/relay-server.crt \
-tls-key certs/relay-server.key \
-client-ca certs/client-ca.crt \
-sign-key certs/relay-signing.key
go run ./examples/tunnel-http \
-listen :8443 \
-cert certs/public-chain.crt \
-signer-addr 127.0.0.1:9443 \
-signer-name relay.internal \
-key-id relay-cert \
-client-cert certs/tunnel-client.crt \
-client-key certs/tunnel-client.key \
-root-ca certs/relay-ca.crtkeyless_tls owns the mechanism, and only the mechanism:
- the signer receives the transcript of the actual TLS connection it terminates;
- TLS 1.3 transcript, hash, and key-schedule correctness;
- record and handshake-message framing, fragmentation, timeouts, cancellation;
- TLS 1.3 exporter derivation (
Conn.ExportKeyingMaterial); - generic transport and opaque binding plumbing (the binding is bytes the library never interprets).
Consumers own the policy:
- whether a binding is mandatory and what it means (relay stream, lease, hostname, tenant);
- whether unvalidated transcript signing is forbidden (configure a
TranscriptValidatorto enforce it); - which ALPN/profile to expose, whether the signer deployment requires mTLS, and any additional KeyID-specific restrictions beyond supported key/algorithm pairs.
A generic arbitrary-digest signing endpoint is deliberately absent: transcript binding is the library's core guarantee, not one deployment's hardening choice.
- Store private keys only in
relay-signer; never distribute them to tunnel apps - Keep only the public certificate chain in tunnel apps
- Enforce signer mTLS and pair it with
KeyID-scoped ACLs - Signer sockets are bounded before TLS authentication: 256 concurrent connections globally, 64 per source IP.
- The signer enforces a 5-second TLS handshake/header deadline, 10-second request-read deadline, 15-second write deadline, 30-second idle deadline, and 16 KiB maximum HTTP headers.
- Applications can override these bounds via
server.Config.Limits; zero values use the safe defaults. Set the per-source connection cap for the peer addresses the signer actually sees: behind a reverse proxy, that may be the proxy's IP rather than each original client.
The signing protocol has a single endpoint with a transcript-bound contract. The request
carries the TLS 1.3 handshake transcript; the signer validates it and returns the
CertificateVerify signature. There is no arbitrary-digest signing endpoint.
Only ECDSA P-256 keys accept ECDSA_SHA256, RSA keys accept RSA_PSS_SHA256,
and Ed25519 keys accept Ed25519. A mismatched key and algorithm returns
HTTP 400 without signing.
Request:
{
"key_id": "relay-cert",
"algorithm": "RSA_PSS_SHA256",
"binding": "<base64>",
"client_hello": "<base64>",
"server_hello": "<base64>",
"encrypted_extensions": "<base64>",
"certificate": "<base64>",
"timestamp_unix": 1735628400,
"nonce": "c4d76ad40f5d8f95a1fe4b2f1c922f4a"
}Response:
{
"key_id": "relay-cert",
"algorithm": "RSA_PSS_SHA256",
"signature": "<base64>"
}The /v1/sign contract changed from the legacy digest-based schema to the transcript-bound
schema above. This is an intentional breaking change: mixed old/new deployments are unsupported.
| client \ server | new server (transcript-bound) | old server (≤ legacy digest schema) |
|---|---|---|
| new client | works | broken: legacy server rejects the transcript request schema |
| old client (digest) | rejected with HTTP 400 (missing required handshake transcript field) |
works (legacy) |
The relay tests pin the break: a legacy digest-shaped request to /v1/sign is rejected with
400 Bad Request, never silently reinterpreted. Deployments that still run the legacy digest
contract must upgrade clients and servers together.
keyless: SDK for application developers (tunnel app integration point)keyless/signerclient: remote signer client implementationrelay/signrpc: signer JSON request/response typesrelay/signer: signing service/key storerelay/server: signer HTTPS (mandatory mTLS) server launcherkeyless/lifecycle: per-lease mTLS identity management (issue, renew, validate, disk-backed encrypted store)relay/l4: TCP passthrough relay + optional ClientHello (SNI/ALPN) inspection hook
This implementation is at an early stage. Before production use, consider adding:
- replay cache
- rate limiting
- key rotation policy
- observability (OTel/metrics/log correlation)