From 0fb21243fe91eadb0062fc2b6161cd6be280657f Mon Sep 17 00:00:00 2001 From: Paul Kulchenko Date: Sun, 20 Feb 2022 14:38:46 -0800 Subject: [PATCH] Update redbean to add GetSslIdentity This returns cert->subject or psk identity from the current SSL session. --- tool/net/help.txt | 4 ++++ tool/net/redbean.c | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/tool/net/help.txt b/tool/net/help.txt index f5b21d872..c17ac3250 100644 --- a/tool/net/help.txt +++ b/tool/net/help.txt @@ -672,6 +672,10 @@ FUNCTIONS GetScheme() → str Returns scheme from Request-URL, if any. + GetSslIdentity() → str + Returns certificate subject or PSK identity from the current SSL + session. `nil` is returned for regular (non-SSL) connections. + GetStatus() → int Returns current status (as set by an earlier SetStatus call) or `nil` if the status hasn't been set yet. diff --git a/tool/net/redbean.c b/tool/net/redbean.c index 78d7b5c9b..4cab7f5ba 100644 --- a/tool/net/redbean.c +++ b/tool/net/redbean.c @@ -372,6 +372,7 @@ static int client; static int changeuid; static int changegid; static int statuscode; +static int sslpskindex; static int oldloglevel; static int maxpayloadsize; static int messageshandled; @@ -1473,6 +1474,8 @@ static int TlsRoutePsk(void *ctx, mbedtls_ssl_context *ssl, psks.p[i].identity_len)) { DEBUGF("(ssl) TlsRoutePsk(%`'.*s)", identity_len, identity); mbedtls_ssl_set_hs_psk(ssl, psks.p[i].key, psks.p[i].key_len); + // keep track of selected psk to report its identity + sslpskindex = i+1; // use index+1 to check against 0 (when not set) return 0; } } @@ -1492,6 +1495,7 @@ static bool TlsSetup(void) { g_bio.a = 0; g_bio.b = 0; g_bio.c = 0; + sslpskindex = 0; for (;;) { if (!(r = mbedtls_ssl_handshake(&ssl)) && TlsFlush(&g_bio, 0, 0) != -1) { LockInc(&shared->c.sslhandshakes); @@ -3194,6 +3198,23 @@ static int LuaGetStatus(lua_State *L) { return 1; } +static int LuaGetSslIdentity(lua_State *L) { + const mbedtls_x509_crt *cert; + OnlyCallDuringRequest(L, "GetSslIdentity"); + if (!usessl) + lua_pushnil(L); + else + if (sslpskindex) { + lua_pushlstring(L, psks.p[sslpskindex-1].identity, + psks.p[sslpskindex-1].identity_len); + } else { + cert = mbedtls_ssl_get_peer_cert(&ssl); + lua_pushstring(L, cert ? gc(FormatX509Name(&cert->subject)) : ""); + } + return 1; +} + + static int LuaServeError(lua_State *L) { return LuaRespond(L, ServeError); } @@ -5601,6 +5622,7 @@ static const luaL_Reg kLuaFuncs[] = { {"GetRemoteAddr", LuaGetRemoteAddr}, // {"GetScheme", LuaGetScheme}, // {"GetServerAddr", LuaGetServerAddr}, // + {"GetSslIdentity", LuaGetSslIdentity}, // {"GetStatus", LuaGetStatus}, // {"GetTime", LuaGetTime}, // {"GetUrl", LuaGetUrl}, //