From fe3ed0bb743e754f28ef250e4c5875cc38b00beb Mon Sep 17 00:00:00 2001 From: DL6ER Date: Sun, 28 May 2023 08:08:34 +0200 Subject: [PATCH] Add LUA pihole.needLogin(remote_addr) Signed-off-by: DL6ER --- src/api/api.h | 4 ++++ src/api/auth.c | 2 -- src/lua/ftl_lua.c | 28 +++++++++++++++++++++++++++- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/api/api.h b/src/api/api.h index 2527f29e..973236ba 100644 --- a/src/api/api.h +++ b/src/api/api.h @@ -16,6 +16,10 @@ #include "webserver/cJSON/cJSON.h" #include "webserver/http-common.h" +// Commo definitions +#define LOCALHOSTv4 "127.0.0.1" +#define LOCALHOSTv6 "::1" + // API router int api_handler(struct mg_connection *conn, void *ignored); diff --git a/src/api/auth.c b/src/api/auth.c index 39ff96ed..46c4251c 100644 --- a/src/api/auth.c +++ b/src/api/auth.c @@ -89,8 +89,6 @@ static void sha256_hex(uint8_t *data, char *buffer) // Can we validate this client? // Returns -1 if not authenticated or expired // Returns >= 0 for any valid authentication -#define LOCALHOSTv4 "127.0.0.1" -#define LOCALHOSTv6 "::1" int check_client_auth(struct ftl_conn *api) { // Is the user requesting from localhost? diff --git a/src/lua/ftl_lua.c b/src/lua/ftl_lua.c index 4cdf5f0b..0555d116 100644 --- a/src/lua/ftl_lua.c +++ b/src/lua/ftl_lua.c @@ -24,6 +24,8 @@ #include #include "scripts/scripts.h" +#include "api/api.h" + int run_lua_interpreter(const int argc, char **argv, bool dnsmasq_debug) { if(argc == 1) // No arguments after this one @@ -197,12 +199,35 @@ static int pihole_include(lua_State *L) { return 0; // number of results } -// pihole.boxed_layout() +// pihole.boxedlayout() static int pihole_boxedlayout(lua_State *L) { lua_pushboolean(L, config.webserver.interface.boxed.v.b); return 1; // number of results } +// pihole.needLogin(remote_addr:str) +static int pihole_needLogin(lua_State *L) { + // Get remote_addr (first argument to LUA function) + const char *remote_addr = luaL_checkstring(L, 1); + + // Check if password is set + const bool has_password = config.webserver.api.pwhash.v.s != NULL && + strlen(config.webserver.api.pwhash.v.s) > 0; + + // Check if address is loopback + const bool is_loopback = strcmp(remote_addr, LOCALHOSTv4) == 0 || + strcmp(remote_addr, LOCALHOSTv6) == 0; + + // Check if local API authentication is enabled + const bool localAPIauth = config.webserver.api.localAPIauth.v.b; + + // Check if login is required + const bool need_login = has_password || (is_loopback && !localAPIauth); + + lua_pushboolean(L, need_login); + return 1; // number of results +} + static const luaL_Reg piholelib[] = { {"ftl_version", pihole_ftl_version}, {"hostname", pihole_hostname}, @@ -211,6 +236,7 @@ static const luaL_Reg piholelib[] = { {"webhome", pihole_webhome}, {"include", pihole_include}, {"boxedlayout", pihole_boxedlayout}, + {"needLogin", pihole_needLogin}, {NULL, NULL} };