TLS and HTTPS
suggest changeTLS (Transport Layer Security, which replaced SSL) protects a TCP connection in three ways:
- encryption: nobody on the network path can read the data
- integrity: nobody can change the data without being detected
- authentication: the client checks that the server holds a certificate for the name it wanted to reach, signed by a certificate authority (CA) it trusts. Optionally the server checks a certificate from the client as well (mutual TLS)
HTTPS is HTTP over TLS, and wss:// is WebSocket over TLS. Ruby does all of this with the openssl library that ships with Ruby, which wraps the system's OpenSSL. Net::HTTP and most gems use it underneath.
The HTTP client article shows the basics of HTTPS requests with Net::HTTP. This article goes one level down: it creates its own CA and certificates, writes TLS servers and clients on top of TCP sockets, explains what certificate verification checks and how it fails, and then covers mutual TLS, SNI, ALPN and secure WebSockets.
The examples were run with Ruby 4.0 and OpenSSL 3.6. Everything except the last two sections uses only the standard library.
Where Ruby finds trusted CAs
require 'openssl'
puts OpenSSL::OPENSSL_LIBRARY_VERSION
puts "CA file: #{OpenSSL::X509::DEFAULT_CERT_FILE} (override: #{OpenSSL::X509::DEFAULT_CERT_FILE_ENV})"
puts "CA dir: #{OpenSSL::X509::DEFAULT_CERT_DIR} (override: #{OpenSSL::X509::DEFAULT_CERT_DIR_ENV})"
p OpenSSL::SSL::SSLContext::DEFAULT_PARAMS.slice(:verify_mode, :verify_hostname)
OpenSSL 3.6.4 25 Aug 2026
CA file: C:/Ruby40-x64/lib/ruby/4.0.0/etc/ssl\cert.pem (override: SSL_CERT_FILE)
CA dir: C:/Ruby40-x64/lib/ruby/4.0.0/etc/ssl\certs (override: SSL_CERT_DIR)
{verify_mode: 1, verify_hostname: true}
On Linux the paths are usually /etc/ssl/certs or similar. They're kept up to date by the OS package manager. If you get certificate verify failed (unable to get local issuer certificate) for a public site, the CA bundle is usually missing or outdated. Point SSL_CERT_FILE at a current bundle. Don't turn verification off.
verify_mode: 1 is OpenSSL::SSL::VERIFY_PEER. These defaults apply when you call SSLContext#set_params, which Net::HTTP does for you.
Creating test certificates
Real servers get certificates from a public CA such as Let's Encrypt. For development and for internal services you can run your own CA. This script creates a CA, a server certificate for localhost/127.0.0.1 signed by it, and a client certificate for mutual TLS. It uses elliptic-curve P-256 keys, which are small and fast. OpenSSL::PKey::RSA.generate(2048) works the same way.
# certs.rb - create a test CA, a server certificate and a client certificate
require 'openssl'
def new_cert(subject:, key:, issuer: nil, issuer_key: key, serial:, days: 30)
cert = OpenSSL::X509::Certificate.new
cert.version = 2 # X.509 v3 (the field is zero-based)
cert.serial = serial
cert.subject = OpenSSL::X509::Name.parse(subject)
cert.issuer = issuer ? issuer.subject : cert.subject # self-signed if no issuer
cert.public_key = key
cert.not_before = Time.now - 60 # allow for small clock differences
cert.not_after = Time.now + days * 24 * 60 * 60
ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = issuer || cert
yield cert, ef
cert.add_extension(ef.create_extension('subjectKeyIdentifier', 'hash'))
cert.sign(issuer_key, 'SHA256')
end
# 1. The certificate authority: a self-signed certificate allowed to sign others
ca_key = OpenSSL::PKey::EC.generate('prime256v1')
ca = new_cert(subject: '/CN=Test Root CA', key: ca_key, serial: 1, days: 365) do |c, ef|
c.add_extension(ef.create_extension('basicConstraints', 'CA:TRUE', true))
c.add_extension(ef.create_extension('keyUsage', 'keyCertSign,cRLSign', true))
end
# 2. The server certificate, valid for localhost and 127.0.0.1
server_key = OpenSSL::PKey::EC.generate('prime256v1')
server = new_cert(subject: '/CN=localhost', key: server_key, serial: 2,
issuer: ca, issuer_key: ca_key) do |c, ef|
c.add_extension(ef.create_extension('basicConstraints', 'CA:FALSE', true))
c.add_extension(ef.create_extension('keyUsage', 'digitalSignature', true))
c.add_extension(ef.create_extension('extendedKeyUsage', 'serverAuth'))
c.add_extension(ef.create_extension('subjectAltName', 'DNS:localhost,IP:127.0.0.1'))
end
# 3. A client certificate for mutual TLS
client_key = OpenSSL::PKey::EC.generate('prime256v1')
client = new_cert(subject: '/CN=alice', key: client_key, serial: 3,
issuer: ca, issuer_key: ca_key) do |c, ef|
c.add_extension(ef.create_extension('basicConstraints', 'CA:FALSE', true))
c.add_extension(ef.create_extension('keyUsage', 'digitalSignature', true))
c.add_extension(ef.create_extension('extendedKeyUsage', 'clientAuth'))
end
File.write('ca.pem', ca.to_pem)
File.write('ca-key.pem', ca_key.private_to_pem) # keep this one secret!
File.write('server.pem', server.to_pem)
File.write('server-key.pem', server_key.private_to_pem)
File.write('client.pem', client.to_pem)
File.write('client-key.pem', client_key.private_to_pem)
puts Dir['*.pem'].sort
puts server.verify(ca_key) # signature check with the CA's public key
ca-key.pem
ca.pem
client-key.pem
client.pem
server-key.pem
server.pem
true
Things to know:
- clients match the host name against the subjectAltName (SAN) extension. The
CNin the subject is ignored for this. A certificate without a SAN entry for the name fails verification basicConstraints CA:TRUEis what allows a certificate to sign other certificates. Leaf certificates must haveCA:FALSEprivate_to_pemwrites the key unencrypted. To protect it with a password, useprivate_to_pem('aes-256-cbc', password)and read it back withOpenSSL::PKey.read(pem, password).pemfiles are Base64 text with-----BEGIN ...-----lines.to_dergives the binary form
The openssl command-line tool can create the same files. A Ruby script has the advantage of working the same way on every OS and in tests.
Inspecting a certificate
require 'openssl'
cert = OpenSSL::X509::Certificate.new(File.read('server.pem'))
puts "subject: #{cert.subject}"
puts "issuer: #{cert.issuer}"
puts "serial: #{cert.serial}"
puts "key: #{cert.public_key.class} #{cert.public_key.group.curve_name}"
puts "sig alg: #{cert.signature_algorithm}"
days_left = ((cert.not_after - Time.now) / 86_400).floor
puts "expires: #{cert.not_after.utc} (#{days_left} days left)"
cert.extensions.each { |e| puts " #{e.oid}: #{e.value}" }
puts "SHA-256: #{OpenSSL::Digest::SHA256.hexdigest(cert.to_der).scan(/../).first(8).join(':')}..."
ca = OpenSSL::X509::Certificate.new(File.read('ca.pem'))
store = OpenSSL::X509::Store.new
store.add_cert(ca)
puts "chain ok: #{store.verify(cert)}"
puts "localhost ok: #{OpenSSL::SSL.verify_certificate_identity(cert, 'localhost')}"
puts "example.com ok: #{OpenSSL::SSL.verify_certificate_identity(cert, 'example.com')}"
subject: /CN=localhost
issuer: /CN=Test Root CA
serial: 2
key: OpenSSL::PKey::EC prime256v1
sig alg: ecdsa-with-SHA256
expires: 2026-11-16 20:42:43 UTC (29 days left)
basicConstraints: CA:FALSE
keyUsage: Digital Signature
extendedKeyUsage: TLS Web Server Authentication
subjectAltName: DNS:localhost, IP Address:127.0.0.1
subjectKeyIdentifier: C4:78:6D:3E:B3:AC:C7:B1:65:1A:CE:3D:1F:BB:49:01:A6:4F:37:D5
SHA-256: cc:a6:b2:d5:db:56:52:3e...
chain ok: true
localhost ok: true
example.com ok: false
A TLS client does these two checks during the handshake: the certificate chains up to a trusted CA (X509::Store#verify), and it is valid for the host name (verify_certificate_identity).
A TLS server
A TLS server is a TCP server whose sockets are wrapped in OpenSSL::SSL::SSLSocket. The SSLContext holds the configuration shared by all connections: the certificate, the private key and the allowed protocol versions.
# tls_server.rb - a TLS echo server
require 'socket'
require 'openssl'
$stdout.sync = true
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert = OpenSSL::X509::Certificate.new(File.read('server.pem'))
ctx.key = OpenSSL::PKey.read(File.read('server-key.pem'))
ctx.min_version = OpenSSL::SSL::TLS1_2_VERSION
port = Integer(ENV.fetch('PORT', 9443))
server = OpenSSL::SSL::SSLServer.new(TCPServer.new('127.0.0.1', port), ctx)
server.start_immediately = false # accept only TCP; handshake in the thread
puts "listening on 127.0.0.1:#{port}"
loop do
Thread.new(server.accept) do |conn|
conn.accept # the TLS handshake
puts "client #{conn.io.remote_address.inspect_sockaddr}: #{conn.ssl_version} #{conn.cipher[0]}"
while (line = conn.gets)
conn.puts "echo: #{line}"
end
rescue OpenSSL::SSL::SSLError, SystemCallError, IOError => e
puts "error: #{e.message}"
ensure
conn.close
end
end
By default SSLServer#accept also does the TLS handshake. Since that happens in the accept loop, one slow or malicious client that never finishes the handshake would block everybody else. With start_immediately = false, accept returns as soon as the TCP connection is made and the handshake runs in the connection's own thread.
A failed handshake raises OpenSSL::SSL::SSLError. Catch it per connection: clients with the wrong CA, port scanners and plain HTTP requests to a TLS port all end up here.
A TLS client
# tls_client.rb - connect, verify the server, send a line
require 'socket'
require 'openssl'
host = 'localhost'
port = Integer(ENV.fetch('PORT', 9443))
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(ca_file: 'ca.pem') # VERIFY_PEER + hostname check + safe defaults
tcp = TCPSocket.new(host, port)
ssl = OpenSSL::SSL::SSLSocket.new(tcp, ctx)
ssl.hostname = host # sent as SNI and used for the hostname check
ssl.sync_close = true # closing ssl also closes tcp
ssl.connect # the TLS handshake
puts "protocol: #{ssl.ssl_version}"
puts "cipher: #{ssl.cipher.inspect}"
puts "server: #{ssl.peer_cert.subject} (issued by #{ssl.peer_cert.issuer})"
puts "verify: #{ssl.verify_result == OpenSSL::X509::V_OK ? 'ok' : ssl.verify_result}"
ssl.puts 'hello over TLS'
puts ssl.gets
ssl.close
With the server running (ruby tls_server.rb):
protocol: TLSv1.3
cipher: ["TLS_AES_256_GCM_SHA384", "TLSv1.3", 256, 256]
server: /CN=localhost (issued by /CN=Test Root CA)
verify: ok
echo: hello over TLS
and the server prints:
listening on 127.0.0.1:9443
client 127.0.0.1:65179: TLSv1.3 TLS_AES_256_GCM_SHA384
The important details:
- always call
set_params. A bareSSLContext.newhasverify_modeset toVERIFY_NONEand doesn't check the host name.set_paramsturns onVERIFY_PEERandverify_hostname, and if you don't passca_file,ca_pathorcert_store, it uses the system's trusted CAs - set
hostnamebeforeconnect. It's sent to the server as SNI (see below) and, withverify_hostname, checked against the certificate. Without it there is no host name check at all SSLSocketbehaves like any otherIO:gets,puts,read,writeandeach_lineall work
When verification fails
Verification failure is the system working as intended. Here are the most common failures, all against the server above:
require 'socket'
require 'openssl'
PORT = Integer(ENV.fetch('PORT', 9443))
def try(label, hostname:, **params)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(params)
ssl = OpenSSL::SSL::SSLSocket.new(TCPSocket.new('127.0.0.1', PORT), ctx)
ssl.hostname = hostname
ssl.sync_close = true
ssl.connect
puts "#{label}: connected, verify_result=#{ssl.verify_result}"
ssl.close
rescue OpenSSL::SSL::SSLError => e
puts "#{label}: #{e.message}"
end
# Only the system's CAs: our private CA isn't among them
try('system CAs', hostname: 'localhost')
# Right CA, but the certificate isn't valid for this name
try('wrong name', hostname: 'example.com', ca_file: 'ca.pem')
# Right CA and name
try('correct', hostname: 'localhost', ca_file: 'ca.pem')
# Verification turned off: "works" against anyone, including an attacker
try('VERIFY_NONE', hostname: 'example.com', verify_mode: OpenSSL::SSL::VERIFY_NONE)
system CAs: SSL_connect returned=1 errno=0 peeraddr=127.0.0.1:9443 state=error: certificate verify failed (unable to get local issuer certificate)
wrong name: SSL_connect returned=1 errno=0 peeraddr=127.0.0.1:9443 state=error: certificate verify failed (hostname mismatch)
correct: connected, verify_result=0
VERIFY_NONE: connected, verify_result=20
With VERIFY_NONE the connection is still encrypted, but to whom? Anyone who can intercept the traffic can present their own certificate, decrypt everything and pass it on. verify_result is 20 (V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY), and nobody looks at it. If a server uses a private CA, trust that CA with ca_file:, as shown here.
The server sees the client's rejection as a TLS alert:
error: SSL_accept returned=1 errno=0 peeraddr=127.0.0.1:65181 state=error: tlsv1 alert unknown ca (SSL alert number 48)
error: SSL_accept returned=1 errno=0 peeraddr=127.0.0.1:65182 state=error: ssl/tls alert bad certificate (SSL alert number 42)
To debug a TLS server without writing a client, use the openssl command-line tool:
openssl s_client -connect 127.0.0.1:9443 -servername localhost \
-CAfile ca.pem -verify_hostname localhost -brief
CONNECTION ESTABLISHED
Protocol version: TLSv1.3
Ciphersuite: TLS_AES_256_GCM_SHA384
Peer certificate: CN=localhost
Hash used: SHA256
Signature type: ecdsa_secp256r1_sha256
Verification: OK
Verified peername: localhost
Negotiated TLS1.3 group: X25519MLKEM768
Verifying certificates without connecting
OpenSSL::X509::Store checks a certificate on its own. This is useful for monitoring expiry or validating certificates uploaded by users. Store#time checks validity at a different moment:
require 'openssl'
ca = OpenSSL::X509::Certificate.new(File.read('ca.pem'))
ca_key = OpenSSL::PKey.read(File.read('ca-key.pem'))
store = OpenSSL::X509::Store.new
store.add_cert(ca)
def check(store, label, cert)
ok = store.verify(cert)
puts "#{label}: #{ok ? 'ok' : "#{store.error} #{store.error_string}"}"
end
check(store, 'server.pem', OpenSSL::X509::Certificate.new(File.read('server.pem')))
# A certificate that expired yesterday
key = OpenSSL::PKey::EC.generate('prime256v1')
old = OpenSSL::X509::Certificate.new
old.version = 2
old.serial = 99
old.subject = OpenSSL::X509::Name.parse('/CN=old.test')
old.issuer = ca.subject
old.public_key = key
old.not_before = Time.now - 10 * 86_400
old.not_after = Time.now - 86_400
old.sign(ca_key, 'SHA256')
check(store, 'expired', old)
# Signed by some other key: the signature doesn't match the CA
forged = old.dup
forged.not_after = Time.now + 86_400
forged.sign(OpenSSL::PKey::EC.generate('prime256v1'), 'SHA256')
check(store, 'forged', forged)
# Store#time checks validity at another moment, e.g. "will it still be valid in 60 days?"
store.time = Time.now + 60 * 86_400
check(store, 'server.pem in 60 days', OpenSSL::X509::Certificate.new(File.read('server.pem')))
server.pem: ok
expired: 10 certificate has expired
forged: 7 certificate signature failure
server.pem in 60 days: 10 certificate has expired
To check a live server's certificate, connect and look at ssl.peer_cert.not_after (or http.peer_cert with Net::HTTP).
HTTPS with Net::HTTP
Net::HTTP uses the same SSLContext options as keyword arguments to start: ca_file, cert_store, cert, key, min_version, verify_mode and so on. A common need is to trust the public CAs and an internal CA. Build an X509::Store with both:
# https_client.rb
require 'net/http'
port = Integer(ENV.fetch('PORT', 9443))
uri = URI("https://localhost:#{port}/whoami")
# Trust the system CAs *and* our private CA
store = OpenSSL::X509::Store.new
store.set_default_paths
store.add_file('ca.pem')
Net::HTTP.start(uri.host, uri.port, use_ssl: true, cert_store: store) do |http|
res = http.get(uri.path)
puts "no client cert: #{res.code} #{res.body}"
end
# Mutual TLS: present a client certificate and its private key
Net::HTTP.start(uri.host, uri.port, use_ssl: true, cert_store: store,
cert: OpenSSL::X509::Certificate.new(File.read('client.pem')),
key: OpenSSL::PKey.read(File.read('client-key.pem'))) do |http|
res = http.get(uri.path)
puts "with client cert: #{res.code} #{res.body}"
end
The server is WEBrick (gem install webrick) with our certificate. SSLVerifyClient: VERIFY_PEER makes it ask for a client certificate. Without VERIFY_FAIL_IF_NO_PEER_CERT it's optional, so the handler decides what to do when there isn't one:
# https_server.rb - HTTPS that asks for (but doesn't require) a client certificate
require 'webrick'
require 'webrick/https'
require 'openssl'
port = Integer(ENV.fetch('PORT', 9443))
server = WEBrick::HTTPServer.new(
BindAddress: '127.0.0.1',
Port: port,
SSLEnable: true,
SSLCertificate: OpenSSL::X509::Certificate.new(File.read('server.pem')),
SSLPrivateKey: OpenSSL::PKey.read(File.read('server-key.pem')),
SSLVerifyClient: OpenSSL::SSL::VERIFY_PEER, # request a client cert
SSLCACertificateFile: 'ca.pem', # ...signed by our CA
Logger: WEBrick::Log.new(File::NULL),
AccessLog: []
)
server.mount_proc('/whoami') do |req, res|
cert = req.client_cert
if cert
res.body = "hello, #{cert.subject.to_a.assoc('CN')[1]}\n"
else
res.status = 401
res.body = "client certificate required\n"
end
end
trap('INT') { server.shutdown }
server.start
no client cert: 401 client certificate required
with client cert: 200 hello, alice
In production, Ruby web apps usually sit behind a reverse proxy or load balancer (nginx, Caddy, a cloud load balancer) that terminates TLS and renews certificates. The app then speaks plain HTTP on a private network. Puma and Falcon can also serve TLS directly.
Mutual TLS with raw sockets
Mutual TLS is a common way for services to authenticate each other: each service gets a certificate from an internal CA, and the server only accepts clients whose certificate chains to that CA. To require a client certificate, add VERIFY_FAIL_IF_NO_PEER_CERT. This example also limits the server to TLS 1.3:
require 'socket'
require 'openssl'
def load_cert(path) = OpenSSL::X509::Certificate.new(File.read(path))
def load_key(path) = OpenSSL::PKey.read(File.read(path))
# Server: require a client certificate signed by our CA, TLS 1.3 only
sctx = OpenSSL::SSL::SSLContext.new
sctx.cert = load_cert('server.pem')
sctx.key = load_key('server-key.pem')
sctx.ca_file = 'ca.pem'
sctx.verify_mode = OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
sctx.min_version = OpenSSL::SSL::TLS1_3_VERSION
tcp = TCPServer.new('127.0.0.1', 0)
Thread.new do
loop do
conn = OpenSSL::SSL::SSLSocket.new(tcp.accept, sctx)
conn.sync_close = true
begin
conn.accept
cn = conn.peer_cert.subject.to_a.assoc('CN')[1]
conn.puts "hello, #{cn}"
rescue OpenSSL::SSL::SSLError => e
puts " [server] #{e.message[/state=.*/]}"
ensure
conn.close
end
end
end
def call(port, label, cert: nil, key: nil, max_version: nil)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(ca_file: 'ca.pem', cert: cert, key: key, max_version: max_version)
ssl = OpenSSL::SSL::SSLSocket.new(TCPSocket.new('127.0.0.1', port), ctx)
ssl.hostname = 'localhost'
ssl.sync_close = true
ssl.connect
# In TLS 1.3 the server checks the client certificate after the client's
# handshake is done, so a rejection shows up on the first read
puts "#{label}: #{ssl.gets || 'closed by server'}"
ssl.close
rescue OpenSSL::SSL::SSLError, SystemCallError => e
puts "#{label}: #{e.class}: #{e.message[/state=.*/] || e.message}"
end
port = tcp.addr[1]
call(port, 'with cert', cert: load_cert('client.pem'), key: load_key('client-key.pem'))
call(port, 'no cert')
call(port, 'TLS 1.2 client', cert: load_cert('client.pem'), key: load_key('client-key.pem'),
max_version: OpenSSL::SSL::TLS1_2_VERSION)
sleep 0.2
with cert: hello, alice
[server] state=error: peer did not return a certificate
no cert: Errno::ECONNRESET: An existing connection was forcibly closed by the remote host. - SSL_read
[server] state=error: unsupported protocol
TLS 1.2 client: OpenSSL::SSL::SSLError: state=error: tlsv1 alert protocol version (SSL alert number 70)
Note how the client without a certificate gets through connect and only fails on the first read. In TLS 1.3 the client's part of the handshake is complete before the server has looked at its certificate. Depending on the OS and timing, the failure shows up as OpenSSL::SSL::SSLError (certificate required alert) or as a connection reset, so rescue both.
The server's peer_cert is the verified client certificate. Use its subject (or a SAN) as the client's identity.
SNI and ALPN
SNI (Server Name Indication) is the host name the client sends at the start of the handshake. It's how one IP address and port serves different certificates for different domains. On the server, servername_cb gets the requested name and returns the SSLContext to use.
ALPN (Application-Layer Protocol Negotiation) lets client and server agree on the protocol inside TLS during the handshake. This is how HTTPS clients pick HTTP/2 (h2) or HTTP/1.1. The client offers a list with alpn_protocols, the server picks one in alpn_select_cb, and both read the result with alpn_protocol.
require 'socket'
require 'openssl'
ca = OpenSSL::X509::Certificate.new(File.read('ca.pem'))
ca_key = OpenSSL::PKey.read(File.read('ca-key.pem'))
# Issue a certificate for one host name, signed by our CA
def issue(name, ca, ca_key)
key = OpenSSL::PKey::EC.generate('prime256v1')
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = rand(2**64)
cert.subject = OpenSSL::X509::Name.parse("/CN=#{name}")
cert.issuer = ca.subject
cert.public_key = key
cert.not_before = Time.now - 60
cert.not_after = Time.now + 86_400
ef = OpenSSL::X509::ExtensionFactory.new(ca, cert)
cert.add_extension(ef.create_extension('subjectAltName', "DNS:#{name}"))
cert.sign(ca_key, 'SHA256')
[cert, key]
end
# One context per host name
contexts = %w[a.test b.test].to_h do |name|
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert, ctx.key = issue(name, ca, ca_key)
ctx.alpn_select_cb = ->(offered) { offered.include?('h2') ? 'h2' : 'http/1.1' }
[name, ctx]
end
default = contexts['a.test']
default.servername_cb = ->((_ssl, name)) { contexts.fetch(name, default) }
tcp = TCPServer.new('127.0.0.1', 0)
server = OpenSSL::SSL::SSLServer.new(tcp, default)
Thread.new do
loop do
conn = server.accept
conn.puts "server sent #{conn.cert.subject}, speaking #{conn.alpn_protocol}"
conn.close
rescue OpenSSL::SSL::SSLError
retry
end
end
def connect(port, name, alpn)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(ca_file: 'ca.pem')
ctx.alpn_protocols = alpn
ssl = OpenSSL::SSL::SSLSocket.new(TCPSocket.new('127.0.0.1', port), ctx)
ssl.hostname = name
ssl.sync_close = true
ssl.connect
puts "#{name}: cert=#{ssl.peer_cert.subject} alpn=#{ssl.alpn_protocol.inspect}"
puts " #{ssl.gets}"
ssl.close
end
port = tcp.addr[1]
connect(port, 'a.test', %w[h2 http/1.1])
connect(port, 'b.test', %w[http/1.1])
a.test: cert=/CN=a.test alpn="h2"
server sent /CN=a.test, speaking h2
b.test: cert=/CN=b.test alpn="http/1.1"
server sent /CN=b.test, speaking http/1.1
The client connects to 127.0.0.1 but sets hostname, so SNI and the host name check use a.test / b.test. The callback receives [ssl_socket, name] as one array, which ->((_ssl, name)) destructures. A client that sends no SNI (or an unknown name) gets the default context.
Secure WebSockets (wss://)
wss:// is a WebSocket over TLS. With the async-websocket gem from the WebSockets article, the only change is passing an ssl_context: to the endpoint. The handshake is an HTTP/1.1 upgrade, so both sides set ALPN to http/1.1:
require 'socket'
require 'openssl'
require 'async'
require 'async/http/server'
require 'async/http/endpoint'
require 'async/websocket/client'
require 'async/websocket/adapters/http'
require 'protocol/http/response'
Warning[:experimental] = false
server_ctx = OpenSSL::SSL::SSLContext.new
server_ctx.cert = OpenSSL::X509::Certificate.new(File.read('server.pem'))
server_ctx.key = OpenSSL::PKey.read(File.read('server-key.pem'))
server_ctx.alpn_protocols = ['http/1.1'] # WebSocket upgrades need HTTP/1.1
client_ctx = OpenSSL::SSL::SSLContext.new
client_ctx.set_params(ca_file: 'ca.pem')
client_ctx.alpn_protocols = ['http/1.1']
app = lambda do |request|
Async::WebSocket::Adapters::HTTP.open(request) do |connection|
while (message = connection.read)
connection.write("echo: #{message.buffer}")
connection.flush
end
end || Protocol::HTTP::Response[404, {}, ["Not a WebSocket request\n"]]
end
port = TCPServer.open('127.0.0.1', 0) { |s| s.addr[1] }
url = "wss://127.0.0.1:#{port}/chat"
server_endpoint = Async::HTTP::Endpoint.parse(url, ssl_context: server_ctx)
client_endpoint = Async::HTTP::Endpoint.parse(url, ssl_context: client_ctx)
Async do |task|
server = task.async { Async::HTTP::Server.new(app, server_endpoint).run }
Async::WebSocket::Client.connect(client_endpoint) do |connection|
connection.write('hello over wss')
connection.flush
puts connection.read.buffer
end
# Without our CA the handshake fails before any HTTP is sent
begin
Async::WebSocket::Client.connect(Async::HTTP::Endpoint.parse(url)) { }
rescue OpenSSL::SSL::SSLError => e
puts "default CAs: #{e.message[/certificate verify failed.*/]}"
end
server.stop
end
echo: hello over wss
default CAs: certificate verify failed (unable to get local issuer certificate)
The URL uses 127.0.0.1, which works because the server certificate has IP:127.0.0.1 in its SAN. This was run with async 2.46, async-http 0.105 and async-websocket 0.30.
Best practices
- Never use
VERIFY_NONEin real code, not even "temporarily". If verification fails, fix the CA bundle, trust the right private CA withca_file/cert_store, or fix the server's certificate - Always call
set_paramson client contexts and sethostnameon client sockets.Net::HTTP,async-httpand most HTTP gems already do this - Leave cipher suites and protocol defaults to OpenSSL. If you change anything, set
min_versiontoTLS1_2_VERSION; TLS 1.0 and 1.1 are obsolete - Serve the full chain: if your certificate was issued by an intermediate CA, the server must send the intermediate too (
ctx.extra_chain_cert = [intermediate], orctx.add_certificate(cert, key, [intermediate])). Browsers sometimes cope without it, but Ruby clients and other non-browser clients fail withunable to get local issuer certificate - Keep private keys out of source control, readable only by the service, and load them from files or a secrets manager
- Monitor certificate expiry (see
X509::Store#timeabove) and automate renewal. Let's Encrypt certificates last 90 days or less - Rescue
OpenSSL::SSL::SSLErrornext to the other network errors (SystemCallError,IOError, timeouts) and log the message. It usually says exactly what went wrong