From 7366832e12c7724306afb70e6e84502aa2153e3e Mon Sep 17 00:00:00 2001 From: ryan Date: Sun, 19 Jul 2026 14:57:51 +0800 Subject: [PATCH] =?UTF-8?q?fix(agent):=20=E5=86=85=E5=B5=8C=20resty.ipmatc?= =?UTF-8?q?her=EF=BC=8C=E7=A7=BB=E9=99=A4=E6=97=A0=E6=95=88=20opm=20?= =?UTF-8?q?=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OPM 无 api7/lua-resty-ipmatcher 账号导致镜像构建失败;改为 vendor api7 v0.6.1 并随 ManagedWAFLuaFiles 部署到 lua 目录。 --- docker/Dockerfile.agent | 1 - docs/changelog/index.md | 2 +- docs/plan/20260719-waf-ip-matcher-radix.md | 4 +- .../apps/agent/nginx/resty/ipmatcher.LICENSE | 201 +++++++++ internal/apps/agent/nginx/resty/ipmatcher.lua | 387 ++++++++++++++++++ internal/apps/agent/nginx/waf_assets.go | 8 + 6 files changed, 600 insertions(+), 3 deletions(-) create mode 100644 internal/apps/agent/nginx/resty/ipmatcher.LICENSE create mode 100644 internal/apps/agent/nginx/resty/ipmatcher.lua diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent index 5dcebac2..9e5519e3 100644 --- a/docker/Dockerfile.agent +++ b/docker/Dockerfile.agent @@ -28,7 +28,6 @@ FROM openresty/openresty:alpine RUN apk add --no-cache ca-certificates tzdata perl libmaxminddb su-exec libcap \ && ln -sf /usr/lib/libmaxminddb.so.0 /usr/lib/libmaxminddb.so \ && opm get anjia0532/lua-resty-maxminddb \ - && opm get api7/lua-resty-ipmatcher \ && addgroup -S openflare \ && adduser -S -G openflare -H -h /data -s /sbin/nologin openflare \ && mkdir -p /etc/openflare /data \ diff --git a/docs/changelog/index.md b/docs/changelog/index.md index 49a84a26..7304b1f4 100644 --- a/docs/changelog/index.md +++ b/docs/changelog/index.md @@ -32,7 +32,7 @@ sidebar: false - WAF 规则画布支持右键删除节点或连线,并屏蔽浏览器默认右键菜单。 - WAF 规则编辑器支持一键格式化布局,按流程层次自动整理节点位置。 - 优化边缘 WAF「安全防护」与「UA 检查」热路径:SQL/命令/XSS 等仅扫描 Query、Cookie、Referer 与有限 Body,避免对全部请求头做特征匹配;路径检测不再重复扫描完整 `request_uri`;无请求体时跳过 Body 读取;UA 分类仅小写一次并加速白名单匹配,显著降低开启基础防护时的 CPU 占用。 -- 优化边缘 WAF「IP 匹配」:IP 组与节点 IP/CIDR 在加载时编译为索引(优先 `lua-resty-ipmatcher` 基数树,否则 exact 哈希 + 预解析 CIDR),查询与名单规模解耦,避免大名单线性扫描打满 CPU。 +- 优化边缘 WAF「IP 匹配」:IP 组与节点 IP/CIDR 在加载时编译为索引(优先随 Agent 下发的 `resty.ipmatcher` 基数树,否则 exact 哈希 + 预解析 CIDR),查询与名单规模解耦,避免大名单线性扫描打满 CPU。 ## [v3.4.0] - 2026-07-19 diff --git a/docs/plan/20260719-waf-ip-matcher-radix.md b/docs/plan/20260719-waf-ip-matcher-radix.md index 17c001d1..5c26d776 100644 --- a/docs/plan/20260719-waf-ip-matcher-radix.md +++ b/docs/plan/20260719-waf-ip-matcher-radix.md @@ -21,7 +21,9 @@ ### 边缘 Agent 与 OpenResty * #### [MODIFY] `docker/Dockerfile.agent` - * `opm get api7/lua-resty-ipmatcher`(与 maxminddb 并列)。 + * **不**通过 OPM 安装 ipmatcher(`api7` 账号在 OPM 不存在)。 +* #### [NEW] `internal/apps/agent/nginx/resty/ipmatcher.lua`(vendor api7 v0.6.1) + * 随 `ManagedWAFLuaFiles` 部署到 `/resty/ipmatcher.lua`,由 `lua_package_path` 加载。 * #### [MODIFY] `internal/apps/agent/nginx/waf_runtime.lua` * 编译/查询 helper;重写 `matches_ip_values`。 * #### [MODIFY] `internal/apps/agent/nginx/waf_ip_groups.lua` diff --git a/internal/apps/agent/nginx/resty/ipmatcher.LICENSE b/internal/apps/agent/nginx/resty/ipmatcher.LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/internal/apps/agent/nginx/resty/ipmatcher.LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/apps/agent/nginx/resty/ipmatcher.lua b/internal/apps/agent/nginx/resty/ipmatcher.lua new file mode 100644 index 00000000..36de6b95 --- /dev/null +++ b/internal/apps/agent/nginx/resty/ipmatcher.lua @@ -0,0 +1,387 @@ +local base = require("resty.core.base") +local bit = require("bit") +local clear_tab = require("table.clear") +local new_tab = base.new_tab +local find_str = string.find +local tonumber = tonumber +local ipairs = ipairs +local pairs = pairs +local ffi = require "ffi" +local ffi_cdef = ffi.cdef +local ffi_copy = ffi.copy +local ffi_new = ffi.new +local C = ffi.C +local insert_tab = table.insert +local string = string +local setmetatable=setmetatable +local type = type +local error = error +local str_sub = string.sub +local str_byte = string.byte +local cur_level = ngx.config.subsystem == "http" and + require "ngx.errlog" .get_sys_filter_level() + +local AF_INET = 2 +local AF_INET6 = 10 +if ffi.os == "OSX" then + AF_INET6 = 30 +end + + +local _M = {_VERSION = 0.3} + + +ffi_cdef[[ + int inet_pton(int af, const char * restrict src, void * restrict dst); + uint32_t ntohl(uint32_t netlong); +]] + + +local parse_ipv4 +do + local inet = ffi_new("unsigned int [1]") + + function parse_ipv4(ip) + if not ip then + return false + end + + if C.inet_pton(AF_INET, ip, inet) ~= 1 then + return false + end + + return C.ntohl(inet[0]) + end +end +_M.parse_ipv4 = parse_ipv4 + +local parse_bin_ipv4 +do + local inet = ffi_new("unsigned int [1]") + + function parse_bin_ipv4(ip) + if not ip or #ip ~= 4 then + return false + end + + ffi_copy(inet, ip, 4) + return C.ntohl(inet[0]) + end +end + +local parse_ipv6 +do + local inets = ffi_new("unsigned int [4]") + + function parse_ipv6(ip) + if not ip then + return false + end + + if str_byte(ip, 1, 1) == str_byte('[') + and str_byte(ip, #ip) == str_byte(']') then + + -- strip square brackets around IPv6 literal if present + ip = str_sub(ip, 2, #ip - 1) + end + + if C.inet_pton(AF_INET6, ip, inets) ~= 1 then + return false + end + + local inets_arr = new_tab(4, 0) + for i = 0, 3 do + insert_tab(inets_arr, C.ntohl(inets[i])) + end + return inets_arr + end +end +_M.parse_ipv6 = parse_ipv6 + +local parse_bin_ipv6 +do + local inets = ffi_new("unsigned int [4]") + + function parse_bin_ipv6(ip) + if not ip or #ip ~= 16 then + return false + end + + ffi_copy(inets, ip, 16) + local inets_arr = new_tab(4, 0) + for i = 0, 3 do + insert_tab(inets_arr, C.ntohl(inets[i])) + end + return inets_arr + end +end + + +local mt = {__index = _M} + + + local ngx_log = ngx.log + local ngx_INFO = ngx.INFO +local function log_info(...) + if cur_level and ngx_INFO > cur_level then + return + end + + return ngx_log(ngx_INFO, ...) +end + + +local function split_ip(ip_addr_org) + local idx = find_str(ip_addr_org, "/", 1, true) + if not idx then + return ip_addr_org + end + + local ip_addr = str_sub(ip_addr_org, 1, idx - 1) + local ip_addr_mask = str_sub(ip_addr_org, idx + 1) + return ip_addr, tonumber(ip_addr_mask) +end +_M.split_ip = split_ip + + + local idxs = {} +local function gen_ipv6_idxs(inets_ipv6, mask) + clear_tab(idxs) + + for _, inet in ipairs(inets_ipv6) do + local valid_mask = mask + if valid_mask > 32 then + valid_mask = 32 + end + + if valid_mask == 32 then + insert_tab(idxs, inet) + else + insert_tab(idxs, bit.rshift(inet, 32 - valid_mask)) + end + + mask = mask - 32 + if mask <= 0 then + break + end + end + + return idxs +end + + +local function new(ips, with_value) + if not ips or type(ips) ~= "table" then + error("missing valid ip argument", 2) + end + + local parsed_ipv4s = {} + local parsed_ipv4s_mask = {} + local ipv4_match_all_value + + local parsed_ipv6s = {} + local parsed_ipv6s_mask = {} + local ipv6_values = {} + local ipv6s_values_idx = 1 + local ipv6_match_all_value + + local iter = with_value and pairs or ipairs + for a, b in iter(ips) do + local ip_addr_org, value + if with_value then + ip_addr_org = a + value = b + + else + ip_addr_org = b + value = true + end + + local ip_addr, ip_addr_mask = split_ip(ip_addr_org) + + local inet_ipv4 = parse_ipv4(ip_addr) + if inet_ipv4 then + ip_addr_mask = ip_addr_mask or 32 + if ip_addr_mask == 32 then + parsed_ipv4s[inet_ipv4] = value + + elseif ip_addr_mask == 0 then + ipv4_match_all_value = value + + else + local valid_inet_addr = bit.rshift(inet_ipv4, 32 - ip_addr_mask) + + parsed_ipv4s_mask[ip_addr_mask] = parsed_ipv4s_mask[ip_addr_mask] or {} + parsed_ipv4s_mask[ip_addr_mask][valid_inet_addr] = value + log_info("ipv4 mask: ", ip_addr_mask, + " valid inet: ", valid_inet_addr) + end + + goto continue + end + + local inets_ipv6 = parse_ipv6(ip_addr) + if inets_ipv6 then + ip_addr_mask = ip_addr_mask or 128 + if ip_addr_mask == 128 then + parsed_ipv6s[ip_addr] = value + + elseif ip_addr_mask == 0 then + ipv6_match_all_value = value + end + + parsed_ipv6s[ip_addr_mask] = parsed_ipv6s[ip_addr_mask] or {} + + local inets_idxs = gen_ipv6_idxs(inets_ipv6, ip_addr_mask) + local node = parsed_ipv6s[ip_addr_mask] + for i, inet in ipairs(inets_idxs) do + if i == #inets_idxs then + if with_value then + ipv6_values[ipv6s_values_idx] = value + node[inet] = ipv6s_values_idx + ipv6s_values_idx = ipv6s_values_idx + 1 + else + node[inet] = true + end + end + node[inet] = node[inet] or {} + node = node[inet] + end + + parsed_ipv6s_mask[ip_addr_mask] = true + + goto continue + end + + if not inet_ipv4 and not inets_ipv6 then + return nil, "invalid ip address: " .. ip_addr + end + + ::continue:: + end + + local ipv4_mask_arr = {} + for k, _ in pairs(parsed_ipv4s_mask) do + insert_tab(ipv4_mask_arr, k) + end + + local ipv6_mask_arr = {} + for k, _ in pairs(parsed_ipv6s_mask) do + insert_tab(ipv6_mask_arr, k) + end + + return setmetatable({ + ipv4 = parsed_ipv4s, + ipv4_mask = parsed_ipv4s_mask, + ipv4_mask_arr = ipv4_mask_arr, + ipv4_match_all_value = ipv4_match_all_value, + + ipv6 = parsed_ipv6s, + ipv6_mask = parsed_ipv6s_mask, + ipv6_mask_arr = ipv6_mask_arr, + ipv6_values = ipv6_values, + ipv6_match_all_value = ipv6_match_all_value, + }, mt) +end + +function _M.new(ips) + return new(ips, false) +end + +function _M.new_with_value(ips) + return new(ips, true) +end + + +local function match_ipv4(self, ip) + local ipv4s = self.ipv4 + local value = ipv4s[ip] + if value ~= nil then + return value + end + + local ipv4_mask = self.ipv4_mask + if self.ipv4_match_all_value ~= nil then + return self.ipv4_match_all_value -- match any ip + end + + for _, mask in ipairs(self.ipv4_mask_arr) do + local valid_inet_addr = bit.rshift(ip, 32 - mask) + + log_info("ipv4 mask: ", mask, + " valid inet: ", valid_inet_addr) + + value = ipv4_mask[mask][valid_inet_addr] + if value ~= nil then + return value + end + end + + return false +end + +local function match_ipv6(self, ip) + local ipv6s = self.ipv6 + if self.ipv6_match_all_value ~= nil then + return self.ipv6_match_all_value -- match any ip + end + + for _, mask in ipairs(self.ipv6_mask_arr) do + local node = ipv6s[mask] + local inet_idxs = gen_ipv6_idxs(ip, mask) + for _, inet in ipairs(inet_idxs) do + if not node[inet] then + break + else + node = node[inet] + if node == true then + return true + end + if type(node) == "number" then + -- fetch with the ipv6s_values_idx + return self.ipv6_values[node] + end + end + end + end + + return false +end + +function _M.match(self, ip) + local inet_ipv4 = parse_ipv4(ip) + if inet_ipv4 then + return match_ipv4(self, inet_ipv4) + end + + local inets_ipv6 = parse_ipv6(ip) + if not inets_ipv6 then + return false, "invalid ip address, not ipv4 and ipv6" + end + + local ipv6s = self.ipv6 + local value = ipv6s[ip] + if value ~= nil then + return value + end + + return match_ipv6(self, inets_ipv6) +end + + +function _M.match_bin(self, bin_ip) + local inet_ipv4 = parse_bin_ipv4(bin_ip) + if inet_ipv4 then + return match_ipv4(self, inet_ipv4) + end + + local inets_ipv6 = parse_bin_ipv6(bin_ip) + if not inets_ipv6 then + return false, "invalid ip address, not ipv4 and ipv6" + end + + return match_ipv6(self, inets_ipv6) +end + + +return _M diff --git a/internal/apps/agent/nginx/waf_assets.go b/internal/apps/agent/nginx/waf_assets.go index 2149a9db..1ecd0ef2 100644 --- a/internal/apps/agent/nginx/waf_assets.go +++ b/internal/apps/agent/nginx/waf_assets.go @@ -12,6 +12,12 @@ var openRestyWAFRuntimeLua string //go:embed waf_ip_groups.lua var openRestyWAFIPGroupsLua string +// Vendored from https://github.com/api7/lua-resty-ipmatcher v0.6.1 (Apache-2.0). +// OPM has no api7/lua-resty-ipmatcher package; deploy with Agent Lua assets instead. +// +//go:embed resty/ipmatcher.lua +var openRestyIPMatcherLua string + const openRestyWAFCheckLua = `local source = debug.getinfo(1, "S").source or "" if string.sub(source, 1, 1) == "@" then local script_path = string.sub(source, 2) @@ -30,5 +36,7 @@ func ManagedWAFLuaFiles() []protocol.SupportFile { {Path: "waf/runtime.lua", Content: openRestyWAFRuntimeLua}, {Path: "waf/ip_groups.lua", Content: openRestyWAFIPGroupsLua}, {Path: "waf/check.lua", Content: openRestyWAFCheckLua}, + // resty.ipmatcher under lua_package_path /?.lua + {Path: "resty/ipmatcher.lua", Content: openRestyIPMatcherLua}, } }