wahern / luaossl

Most comprehensive OpenSSL module in the Lua universe.
http://25thandclement.com/~william/projects/luaossl.html
Other
140 stars 49 forks source link

Support SSL_CTX_use_certificate_chain_file and SSL_CTX_use_private_key_file #194

Open Mehgugs opened 3 years ago

Mehgugs commented 3 years ago
Mehgugs commented 3 years ago

I'll do another commit adding tex when I'm finished with the code.

Support for DER encoded private keys (SSL_FILETYPE_ASN1) in SSL_CTX_use_PrivateKey_file() and SSL_use_PrivateKey_file() was added in 0.9.8.

Will this need to be reflected with a version pre-req somehow?

Simon-L commented 2 months ago

Hello, in the meantime how can one load a certificate and a key from files on the current version available from Luarocks?

Mehgugs commented 1 month ago

Hello, in the meantime how can one load a certificate and a key from files on the current version available from Luarocks?

local Pkey        = require "openssl.pkey"
local Crt         = require "openssl.x509"
local Chain       = require"openssl.x509.chain"

local function decode_fullchain(crtfile, iscontent)
    local crtf  = assert(io.open(crtfile, "r"))
    local crttxt = crtf:read"a"
    crtf:close()

    local crts, pos = {}, 1

    repeat
        local st, ed = crttxt:find("-----BEGIN CERTIFICATE-----", pos, true)
        if st then
            local st2, ed2 = crttxt:find("-----END CERTIFICATE-----", ed + 1, true)
            if st2 then
                table.insert(crts, crttxt:sub(st, ed2))
                pos = ed2+1
            end
        end
    until st == nil

    local chain = Chain.new()
    local primary = asserts(Crt.new(crts[1]))
    for i = 2, #crts do
        local crt = asserts(Crt.new(crts[i]))
        chain:add(crt)
    end
    return primary,chain
end

function example_usage(ctx, crtpath, keypath) 
    local keyfile = asserts(openf(keypath, "r"))
    local primary,crt = decode_fullchain(crtpath)
    asserts(ctx:setPrivateKey(Pkey.new(keyfile:read"a")))
    asserts(ctx:setCertificate(primary))
    asserts(ctx:setCertificateChain(crt))
    keyfile:close()
end

This is my "good enough" solution but it doesnt really address all the situtations covered by these two functions.

Apologies for not continuing to develop this PR further; I am a consumer of this library by way of lua-http and cqueues and it was easier for me to set up a reverse proxy to handle all the https and have the lua processes all run behind that.