.. _lua-detection: Lua检测脚本 =========================== Lua可通过两种方式用于检测: * ``lua`` 规则关键字 * ``luaxform`` 转换器 .. note:: 规则中的Lua功能默认关闭,需在配置文件中启用。请查看 ``suricata.yaml`` 中的 ``security.lua`` 部分并启用 ``allow-rules``。 Lua规则关键字 ---------------- 语法: :: lua:[!]<脚本文件名>; 脚本文件将自动添加至默认规则目录。 Lua规则脚本需包含两个必要函数:``init`` 初始化函数和 ``match`` 匹配函数,详见下文。 默认情况下,脚本会在受限沙箱环境中运行。 初始化函数 ^^^^^^^^^^^^^ .. code-block:: lua function init (args) local needs = {} needs["http.request_line"] = tostring(true) return needs end 该函数声明需要检测的缓冲区。当前支持的缓冲区包括: * packet -- 完整数据包(含头部) * payload -- 数据包载荷(非流式) * buffer -- 当前粘性缓冲区 * stream * dnp3 * ssh * smtp * tls * http.uri * http.uri.raw * http.request_line * http.request_headers * http.request_headers.raw * http.request_body * http.response_headers * http.response_headers.raw * http.response_body 注意:所有HTTP缓冲区存在限制——单个脚本每次只能检测其中一个缓冲区。 匹配函数 ^^^^^^^^^^^^^^ .. code-block:: lua function match(args) a = tostring(args["http.request_line"]) if #a > 0 then if a:find("^POST%s+/.*%.php%s+HTTP/1.0$") then return 1 end end return 0 end 函数应返回1(匹配成功)或0(匹配失败)。上例检测HTTP请求行是否符合指定正则模式。 完整脚本示例: .. code-block:: lua function init (args) local needs = {} needs["http.request_line"] = tostring(true) return needs end function match(args) a = tostring(args["http.request_line"]) if #a > 0 then if a:find("^POST%s+/.*%.php%s+HTTP/1.0$") then return 1 end end return 0 end return 0 Lua转换器:``luaxform`` --------------------------- 详见 :ref:`lua-transform`。 Lua沙箱与可用函数 ----------------------------------- Lua规则脚本在沙箱环境中运行,具有以下限制: * 精简的标准库 * 仅允许使用特定函数 * 指令计数限制 * 内存分配限制 下表列出可用库及函数: ================== ================================================================= 包名 函数 ================== ================================================================= base assert, ipairs, next, pairs, print, rawequal, rawlen, select, tonumber, tostring, type, warn, rawget, rawset, error table concat, insert, move, pack, remove, sort, unpack string byte, char, dump, find, format, gmatch, gsub, len, lower, match, pack, packsize, rep, reverse, sub, unpack, upper math abs, acos, asin, atan, atan2, ceil, cos, cosh, deg, exp, floor, fmod, frexp, ldexp, log, log10, max, min, modf, pow, rad, random, randomseed, sin, sinh, sqrt, tan, tanh, tointeger, type, ult utf8 offset, len, codes, char, codepoint ================== ================================================================= 特别注意以下标准库不可用: * coroutine * package * 输入输出库 * 操作系统功能库 * debug库 此行为可通过 :ref:`suricata-yaml-lua-config` 中的 ``security.lua`` 配置修改。 .. note:: Suricata 8.0 已升级至 Lua 5.4,原生支持位运算和utf8操作。 完整Lua函数列表(含示例)参见 :ref:`lua-functions`(部分函数仅适用于lua-output功能)。