luasec/samples/chain/server.lua
Matthew Wild 4cecbb2783 ssl: Add :getlocalchain() + :getlocalcertificate() to mirror the peer methods
These methods mirror the existing methods that fetch the peer certificate and
chain. Due to various factors (SNI, multiple key types, etc.) it is not always
trivial for an application to determine what certificate was presented to the
client. However there are various use-cases where this is needed, such as
tls-server-end-point channel binding and OCSP stapling.

Requires OpenSSL 1.0.2+ (note: SSL_get_certificate() has existed for a very
long time, but was lacking documentation until OpenSSL 3.0).
2022-09-21 18:40:10 +01:00

73 lines
1.9 KiB
Lua

--
-- Public domain
--
local socket = require("socket")
local ssl = require("ssl")
local util = require("util")
local params = {
mode = "server",
protocol = "any",
key = "../certs/serverAkey.pem",
certificate = "../certs/serverA.pem",
cafile = "../certs/rootA.pem",
verify = {"peer", "fail_if_no_peer_cert"},
options = "all",
}
local ctx = assert(ssl.newcontext(params))
local server = socket.tcp()
server:setoption('reuseaddr', true)
assert( server:bind("127.0.0.1", 8888) )
server:listen()
local conn = server:accept()
conn = assert( ssl.wrap(conn, ctx) )
assert( conn:dohandshake() )
util.show( conn:getpeercertificate() )
print("----------------------------------------------------------------------")
local expectedpeerchain = { "../certs/clientAcert.pem", "../certs/rootA.pem" }
local peerchain = conn:getpeerchain()
assert(#peerchain == #expectedpeerchain)
for k, cert in ipairs( peerchain ) do
util.show(cert)
local expectedpem = assert(io.open(expectedpeerchain[k])):read("*a")
assert(cert:pem() == expectedpem, "peer chain mismatch @ "..tostring(k))
end
local expectedlocalchain = { "../certs/serverAcert.pem" }
local localchain = assert(conn:getlocalchain())
assert(#localchain == #expectedlocalchain)
for k, cert in ipairs( localchain ) do
util.show(cert)
local expectedpem = assert(io.open(expectedlocalchain[k])):read("*a")
assert(cert:pem() == expectedpem, "local chain mismatch @ "..tostring(k))
if k == 1 then
assert(cert:pem() == conn:getlocalcertificate():pem())
end
end
local f = io.open(params.certificate)
local str = f:read("*a")
f:close()
util.show( ssl.loadcertificate(str) )
print("----------------------------------------------------------------------")
local cert = conn:getpeercertificate()
print( cert )
print( cert:digest() )
print( cert:digest("sha1") )
print( cert:digest("sha256") )
print( cert:digest("sha512") )
conn:close()
server:close()