Diff

mod_firewall/conditions.lib.lua @ 5727:ad5c77793750

mod_firewall: Add FROM COUNTRY condition based on GeoIP DB
author Kim Alvefur <zash@zash.se>
date Sun, 12 Nov 2023 16:37:47 +0100
parent 5535:eeccec0955a1
child 5815:14e17927c0ec
line wrap: on
line diff
--- a/mod_firewall/conditions.lib.lua	Sun Nov 12 16:14:09 2023 +0100
+++ b/mod_firewall/conditions.lib.lua	Sun Nov 12 16:37:47 2023 +0100
@@ -381,4 +381,30 @@
 	};
 end
 
+-- FROM COUNTRY: SE
+-- FROM COUNTRY: code=SE
+-- FROM COUNTRY: SWE
+-- FROM COUNTRY: code3=SWE
+-- FROM COUNTRY: continent=EU
+-- FROM COUNTRY? --> NOT FROM COUNTRY: -- (for unknown/invalid)
+-- TODO list support?
+function condition_handlers.FROM_COUNTRY(geoip_spec)
+	local condition = "==";
+	if not geoip_spec then
+		geoip_spec = "--";
+		condition = "~=";
+	end
+	local field, country = geoip_spec:match("(%w+)=(%w+)");
+	if not field then
+		if #geoip_spec == 3 then
+			field, country = "code3", geoip_spec;
+		elseif #geoip_spec == 2 then
+			field, country = "code", geoip_spec;
+		else
+			error("Unknown country code type");
+		end
+	end
+	return ("get_geoip(session.ip, %q) %s %q"):format(field:lower(), condition, country:upper()), { "geoip_country" };
+end
+
 return condition_handlers;