OpenResty 解析cookie特性
基于nginx_lua写个检测规则,主要检测 cookie中是否包含select from,并且后端使用php输出cookie内容,php代码如下:
<?php
echo $_COOKIE['id'];
?>
测试发送请求:
GET /t.php HTTP/1.1
Host: www.test.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) FGecko/20100101 Firefox/54.0
Accept: */*
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate, br
X-Requested-With: XMLHttpRequest
Cookie:id=select0*9from[2];
可以报警。
测试发送请求
GET /t.php HTTP/1.1
Host: www.test.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) FGecko/20100101 Firefox/54.0
Accept: */*
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate, br
X-Requested-With: XMLHttpRequest
Cookie:id=select0* 9from[2];
发现无法触发报警,但是后端php可以正常打印出信息
解析cookie是调用 resty\cookie.lua (https://github.com/cloudflare/lua-resty-cookie/blob/master/lib/resty/cookie.lua\ 代码,
while j <= len do
if state == EXPECT_KEY then
if byte(text_cookie, j) == EQUAL then
key = sub(text_cookie, i, j - 1)
state = EXPECT_VALUE
i = j + 1
end
elseif state == EXPECT_VALUE then
if byte(text_cookie, j) == SEMICOLON
or byte(text_cookie, j) == SPACE --会使用 空格和tab键 表示 一个cookie字段结束
or byte(text_cookie, j) == HTAB
then
value = sub(text_cookie, i, j - 1)
cookie_table[key] = value
key, value = nil, nil
state = EXPECT_SP
i = j + 1
end
elseif state == EXPECT_SP then
if byte(text_cookie, j) ~= SPACE
and byte(text_cookie, j) ~= HTAB
then
state = EXPECT_KEY
i = j
j = j - 1
end
end
j = j + 1
end
lua解析函数 当遇到 分号 空格 Tab 都会认为获得数值结束,而php 应该只会遇到 分号 才会认为结束,导致两者解析不同,最终出现上述情况。