From 4e09cc2ad6443ec3213a44a45a488f88cca5ecb5 Mon Sep 17 00:00:00 2001 From: he2ss Date: Fri, 21 Jan 2022 21:31:23 +0100 Subject: [PATCH] fix ipv4 range support --- nginx/crowdsec.lua | 14 ++++++++++---- nginx/iputils.lua | 6 +++++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/nginx/crowdsec.lua b/nginx/crowdsec.lua index 0f3acd8..200608d 100644 --- a/nginx/crowdsec.lua +++ b/nginx/crowdsec.lua @@ -89,18 +89,18 @@ function item_to_string(item, scope) ip, cidr = iputils.splitRange(item, scope) end - local ip_network_address, isIPv4 = iputils.parseIPAddress(ip) - if isIPV4 then + local ip_network_address, is_ipv4 = iputils.parseIPAddress(ip) + if is_ipv4 then ip_version = "ipv4" if cidr == nil then cidr = 32 end else ip_version = "ipv6" + ip_network_address = ip_network_address.uint32[3]..":"..ip_network_address.uint32[2]..":"..ip_network_address.uint32[1]..":"..ip_network_address.uint32[0] if cidr == nil then cidr = 128 end - ip_network_address = ip_network_address.uint32[3]..":"..ip_network_address.uint32[2]..":"..ip_network_address.uint32[1]..":"..ip_network_address.uint32[0] end if ip_version == nil then @@ -257,7 +257,13 @@ function csmod.allowIp(ip) local ip_network_address = key_parts[3] local netmasks = iputils.netmasks_by_key_type[key_type] for i, netmask in pairs(netmasks) do - local item = key_type.."_"..table.concat(netmask, ":").."_"..iputils.ipv6_band(ip_network_address, netmask) + local item + if key_type == "ipv4" then + item = key_type.."_"..netmask.."_"..iputils.ipv4_band(ip_network_address, netmask) + end + if key_type == "ipv6" then + item = key_type.."_"..table.concat(netmask, ":").."_"..iputils.ipv6_band(ip_network_address, netmask) + end in_cache, remediation_id = runtime.cache:get(item) if in_cache ~= nil then -- we have it in cache ngx.log(ngx.DEBUG, "'" .. key .. "' is in cache") diff --git a/nginx/iputils.lua b/nginx/iputils.lua index d7bec0f..79f967a 100644 --- a/nginx/iputils.lua +++ b/nginx/iputils.lua @@ -98,6 +98,10 @@ function _M.ipv6_band(ip, netmask) return table.concat(res_table, ":") end +function _M.ipv4_band(ip, netmask) + return bit.band(ip, netmask) +end + function _M.splitRange(range) if range and type(range) == "string" then local ip_address, cidr = range:match("^([^/]+)/(%d+)") @@ -111,7 +115,7 @@ function _M.cidrToInt(cidr, ip_version) return nil end if ip_version == "ipv4" then - return tostring(ipv4_netmasks[32-(cidr+1)]) + return tostring(ipv4_netmasks[32-cidr+1]) end if ip_version == "ipv6" then return table.concat(ipv6_netmasks[128-cidr+1], ":")