openresty resty_lua_http模块unable to get local issuer certificate异常处理

最近刚换工作,新公司作为一资讯公司有为客户提供相关SDK去接入公司系统进行一些信息查询作业。随之请求流量的增加,缺少网关层进行API保护,系统常常会因为流量暴增时间段搞垮。自然而然,作为招入公司重构原有系统职责中的开发计划的第一步自然就是打算先做网关了。之前主要是做Java开发,对Openresty做涉及到相关技术见解都很肤浅(欢迎大家拍砖),对中间学习使用Openresty所遇到一些异常在这里做个小记 。(持续更新中…)

模块:Resty_Lua_Http

发起SSL请求异常: 20: unable to get local issuer certificate

示例:

local http = require("resty.http")

local httpc = http.new()

local resp, err = httpc:request_uri("https://m.taobao.com", {
    method = "GET",
    path = "/#index",
    headers = {
        ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"
    },
})

if not resp then
    ngx.say("request error:", err)
    return
end

原因:nginx没有获得本地颁发者证书

解决方法:在nginx.conf http -> server 加入已安装OpenSSL根证书地址,见第(6,7行)

server {
    listen 8000;
    server_name _;
    resolver 8.8.8.8;
    --
    lua_ssl_verify_depth 2;
    lua_ssl_trusted_certificate /etc/ssl/certs/GlobalSign_Root_CA.pem;
    ---
    location /api {
        default_type "text/html";
        lua_code_cache off;
        content_by_lua_file /home/hf/IdeaProjects/apigateway/lua/http.lua;
    }
}

为OpenResty项目编写自定义Nginx C模块

有些时候,我们需要通过 Lua 代码操作 Nginx 里面的某些状态,但是想要的 API 并不存在于 OpenResty 之内。这时候,可以选择编写一个 Nginx C 模块,然后暴露出可供 Lua 调用的接口。

本文中,我们会分别探讨,如何通过 Nginx 变量或 FFI 的方式去提供 Lua 调用得到的接口。

文中的示例代码可以在 ngx_http_example_or_module 找到。

通过 Nginx 变量提供接口

ngx.var.variable= 在调用的时候,会先查找变量 variable 对应的 handler(一个在 Nginx 内注册的 C 函数),如果 handler 存在,会去调用该 handler。
这意味着,如果我们定义了一个 Nginx 变量和对应的 handler,我们就可以通过在 Lua 代码里调用 ngx.var.variable= 来触发该 handler。

空说无益,先上示例。

在 Nginx 里面我们可以通过 limit_rate 和 limit_rate_after 两个指令来限制响应给客户端的速率。前者决定了限速的多少,后者决定了从什么时候开始限速。当然更多的时候我们需要动态去调整这两个指标。

limit_rate 对应有一个 Nginx 内置的变量, $limit_rate,我们可以修改该变量来达到动态调整的目的。相关的 Lua 代码是 ngx.var.limit_rate = limit_rate。但是并不存在 $limit_rate_after 这样一个变量。

不用担心。因为我们可以自己加上。

// ngx_http_example_or_module.c
// 定义变量和它的 getter/setter
static ngx_http_variable_t  ngx_http_example_or_variables[] = {
    { ngx_string("limit_rate_after"), ngx_http_variable_request_set_size,
      ngx_http_variable_request_get_limit_rate_after,
      offsetof(ngx_http_request_t, limit_rate_after),
      NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 },
    { ngx_null_string, NULL, NULL, 0, 0, 0 }
};

// getter 和 setter 的实现在 GitHub 上的示例代码里有,这里就不贴上了。

通过 FFI 提供接口

不过在大多数情况下,我们并不需要借助变量来间接调用 Nginx C 函数。我们完全可以借助 LuaJIT 的 FFI,直接调用 Nginx C 函数。

lua-resty-murmurhash2 就是一个现成的例子。

下面让我们再看另外一个例子,通过 Lua 代码来获取当前的 Nginx 错误日志等级。

在开发中,我们有时需要在测试环境中通过日志来记录某个 table 的值,比如 ngx.log(ngx.INFO, cjson.encode(res))。

在生产环境里,我们会设置日志等级为 error,这样就不会输出 table 的值。但是日志等级无论是多少,cjson.encode 都是必然会被调用的。

不幸的是,这行代码所在的路径非常热,我们需要避免无谓的 json encode 操作。如果能获取实际的日志等级,判断是否为 error,来决定是否调用 cjson.encode,就能省下这一笔开销。

要实现这一功能,仅需加个获取当前配置的日志等级的 Nginx C 函数和对应的 Lua 接口。

我们可以像这样提供一个 Lua 接口:

-- lib/example_or.lua
...

if not pcall(ffi.typeof, "ngx_http_request_t") then
    ffi.cdef[[
        struct ngx_http_request_s;
        typedef struct ngx_http_request_s  ngx_http_request_t;
    ]]
end

ffi.cdef[[
int ngx_http_example_or_ffi_get_error_log_level(ngx_http_request_t *r);
]]

function _M.get_error_log_level()
    local r = getfenv(0).__ngx_req
    return tonumber(C.ngx_http_example_or_ffi_get_error_log_level(r))
end

对应的 Nginx C 函数很简单:

int
ngx_http_example_or_ffi_get_error_log_level(ngx_http_request_t *r)
{
    ngx_log_t                   *log;
    int                          log_level;

    if (r && r->connection && r->connection->log) {
        log = r->connection->log;

    } else {
        log = ngx_cycle->log;
    }

    log_level = log->log_level;
    if (log_level == NGX_LOG_DEBUG_ALL) {
        log_level = NGX_LOG_DEBUG;
    }

    return log_level;
}

使用时直接拿它跟特定的 Nginx 日志等级常量比较即可:

-- config.lua
-- 目前 Nginx 不支持动态变更日志等级,所以可以把日志等级缓存起来
local example_or = require "lib.example_or"
_M.log_leve = example_or.get_error_log_level()


-- in other file
local config = require "common.config"
local log_level = config.log_level
if log_level >= ngx.WARN then
    -- 错误日志等级是 warn 或者 info 一类
    ngx.log(ngx.WARN, "log a warning event")
else
    -- 错误日志等级是 error 一类
    ngx.log(ngx.WARN, "do not log another warning event")
end

OpenResty lua优化 – 避免全局变量的使用

lua-variable-scope

在代码中导入模块时应注意一些细节,推介使用如下格式:

local xxx = require('xxx')

而非:

require('xxx')

理由如下:从设计上讲,全局环境的生命周期和一个Nginx的请求的生命周期是相同的。为了做到会话隔离,每个请求都有自己的Lua全局变量环境。Lua模块在第一次请求打到服务器上的时候被加载起来,通过package.loaded表内建的require()完成缓存,为后续代码复用。并且一些Lua模块内的module()存在边际问题,对加载完成的模块设置成全局表变量,但是这个全局变量在请求处理最后将被清空,并且每个后续请求都拥有自己(干净)的全局空间。所以它将因为访问nil值收到Lua异常。

一般来说,在ngx_lua的上下文中使用Lua全局变量真的不是什么好主意:

  • 滥用全局变量的副作用会对并发场景产生副作用,比如当使用者把这些变量看作是本地变量的时候;

  • Lua的全局变量需要向上查找一个全局环境(只是一个Lua表),代价比较高;

  • 一些Lua的全局变量引用只是拼写错误,这会导致出错很难排查。

所以,我们极力推介在使用变量的时候总是使用local来定义以限定起生效范围是有理由的。

使用工具(lua-releng tool)[https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng]查找你的Lua源文件:

$ lua-releng     
Checking use of Lua global variables in file lib/foo/bar.lua ...  
    1       [1489]  SETGLOBAL       7 -1    ; contains
    55      [1506]  GETGLOBAL       7 -3    ; setvar
    3       [1545]  GETGLOBAL       3 -4    ; varexpand

上述输出说明文件lib/foo/bar.lua的1489行写入一个名为contains的全局变量,1506行读取一个名为setvar的全局变量,1545行读取一个名为varexpand的全局变量,

这个工具能保证Lua模块中的局部变量全部是用local关键字定义过的,否则将会抛出一个运行时库。这样能阻止类似变量这样的资源的竞争。理由请参考(Data Sharing within an Nginx Worker)[http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker]

使用nginx+lua(openresty)实现waf功能

一、了解WAF

1.1 什么是WAF

Web应用防护系统(也称:网站应用级入侵防御系统 。英文:Web Application Firewall,简称: WAF)。利用国际上公认的一种说法:Web应用 防火墙 是通过执行一系列针对HTTP/HTTPS的 安全策略 来专门为Web应用提供保护的一款产品。

1.2 WAF的功能

  • 支持IP白名单和黑名单功能,直接将黑名单的IP访问拒绝。
  • 支持URL白名单,将不需要过滤的URL进行定义。
  • 支持User-Agent的过滤,匹配自定义规则中的条目,然后进行处理(返回403)。
  • 支持CC攻击防护,单个URL指定时间的访问次数,超过设定值,直接返回403。
  • 支持Cookie过滤,匹配自定义规则中的条目,然后进行处理(返回403)。
  • 支持URL过滤,匹配自定义规则中的条目,如果用户请求的URL包含这些,返回403。
  • 支持URL参数过滤,原理同上。
  • 支持日志记录,将所有拒绝的操作,记录到日志中去

1.3 WAF的特点

  • 异常检测协议
    Web应用防火墙会对HTTP的请求进行异常检测,拒绝不符合HTTP标准的请求。并且,它也可以只允许HTTP协议的部分选项通过,从而减少攻击的影响范围。甚至,一些Web应用防火墙还可以严格限定HTTP协议中那些过于松散或未被完全制定的选项。

未分类

  • 增强的输入验证
    增强输入验证,可以有效防止网页篡改、信息泄露、木马植入等恶意网络入侵行为。从而减小Web服务器被攻击的可能性。
  • 及时补丁
    修补Web安全漏洞,是Web应用开发者最头痛的问题,没人会知道下一秒有什么样的漏洞出现,会为Web应用带来什么样的危害。WAF可以为我们做这项工作了——只要有全面的漏洞信息WAF能在不到一个小时的时间内屏蔽掉这个漏洞。当然,这种屏蔽掉漏洞的方式不是非常完美的,并且没有安装对应的补丁本身就是一种安全威胁,但我们在没有选择的情况下,任何保护措施都比没有保护措施更好。
  • 基于规则的保护和基于异常的保护
    基于规则的保护可以提供各种Web应用的安全规则,WAF生产商会维护这个规则库,并时时为其更新。用户可以按照这些规则对应用进行全方面检测。还有的产品可以基于合法应用数据建立模型,并以此为依据判断应用数据的异常。但这需要对用户企业的应用具有十分透彻的了解才可能做到,可现实中这是十分困难的一件事情。
  • 状态管理
    WAF能够判断用户是否是第一次访问并且将请求重定向到默认登录页面并且记录事件。通过检测用户的整个操作行为我们可以更容易识别攻击。状态管理模式还能检测出异常事件(比如登陆失败),并且在达到极限值时进行处理。这对暴力攻击的识别和响应是十分有利的。
  • 其他防护技术
    WAF还有一些安全增强的功能,可以用来解决WEB程序员过分信任输入数据带来的问题。比如:隐藏表单域保护、抗入侵规避技术、响应监视和信息泄露保护。

1.3 WAF与网络防火墙的区别

网络防火墙作为访问控制设备,主要工作在OSI模型三、四层,基于IP报文进行检测。只是对端口做限制,对TCP协议做封堵。其产品设计无需理解HTTP会话,也就决定了无法理解Web应用程序语言如HTML、SQL语言。因此,它不可能对HTTP通讯进行输入验证或攻击规则分析。针对Web网站的恶意攻击绝大部分都将封装为HTTP请求,从80或443端口顺利通过防火墙检测。
  
一些定位比较综合、提供丰富功能的防火墙,也具备一定程度的应用层防御能力,如能根据TCP会话异常性及攻击特征阻止网络层的攻击,通过IP分拆和组合也能判断是否有攻击隐藏在多个数据包中,但从根本上说他仍然无法理解HTTP会话,难以应对如SQL注入、跨站脚本、cookie窃取、网页篡改等应用层攻击。
  
web应用防火墙能在应用层理解分析HTTP会话,因此能有效的防止各类应用层攻击,同时他向下兼容,具备网络防火墙的功能。

二、使用nginx配置简单实现403和404

2.1 小试身手之rerurn 403

修改nginx配置文件在server中加入以下内容

   set $block_user_agent 0;
if ( $http_user_agent ~ "Wget|AgentBench"){
   set $block_user_agent 1;
}
if ($block_user_agent = 1) {
   return 403 ;
}

通过其他机器去wget,结果如下

未分类

2.2 小试身手之rerurn 404

在nginx配置文件中加入如下内容,让访问sql|bak|zip|tgz|tar.gz的请求返回404

location ~* ".(sql|bak|zip|tgz|tar.gz)$"{
      return 404
    }

在网站根目录下放一个tar.gz

[root@iZ28t900vpcZ www]# tar zcvf abc.tar.gz wp-content/

通过浏览器访问结果如下,404已生效

未分类

三、深入实现WAF

3.1 WAF实现规划

分析步骤如下:解析HTTP请求==》匹配规则==》防御动作==》记录日志

具体实现如下:

  • 解析http请求:协议解析模块
  • 匹配规则:规则检测模块,匹配规则库
  • 防御动作:return 403 或者跳转到自定义界面
  • 日志记录:记录到elk中,画出饼图,建议使用json格式

未分类

3.2 安装nginx+lua

由于nginx配置文件书写不方便,并且实现白名单功能很复杂,nginx的白名单也不适用于CC攻击,所以在这里使用nginx+lua来实现WAF,如果想使用lua,须在编译nginx的时候配置上lua,或者结合OpenResty使用,此方法不需要编译nginx时候指定lua

3.2.1 编译nginx的时候加载

环境准备:Nginx安装必备的Nginx和PCRE软件包。

[root@nginx-lua ~]# cd /usr/local/src 
[root@nginx-lua src]# wget http://nginx.org/download/nginx-1.9.4.tar.gz
[root@nginx-lua src]# wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.37.tar.gz

其次,下载当前最新的luajit和ngx_devel_kit (NDK),以及春哥编写的lua-nginx-module

[root@nginx-lua src]# wget http://luajit.org/download/LuaJIT-2.0..tar.gz
[root@nginx-lua src]# wget https://github.com/simpl/ngx_devel_kit/archive/v0.2.19.tar.gz
[root@nginx-lua src]# wget https://github.com/openresty/lua-nginx-module/archive/v0.9.16.tar.gz

最后,创建Nginx运行的普通用户

[root@nginx-lua src]# useradd -s /sbin/nologin -M www

解压NDK和lua-nginx-module

[root@openstack-compute-node5 src]# tar zxvf v0.2.19.tar.gz
[root@openstack-compute-node5 src]# tar zxvf v0.9.16.tar.gz

安装LuaJIT Luajit是Lua即时编译器

[root@openstack-compute-node5 src]# tar zxvf LuaJIT-2.0.3.tar.gz 
[root@openstack-compute-node5 src]# cd LuaJIT-2.0.3
[root@openstack-compute-node5 LuaJIT-2.0.3]# make && make install

安装Nginx并加载模块

[root@openstack-compute-node5 src]# tar zxvf nginx-1.9.4.tar.gz 
[root@openstack-compute-node5 src]# cd nginx-1.9.4
[root@openstack-compute-node5 nginx-1.9.4]# export LUAJIT_LIB=/usr/local/lib
[root@openstack-compute-node5 nginx-1.9.4]# export LUAJIT_INC=/usr/local/include/luajit-2.0
[root@openstack-compute-node5 nginx-1.9.4]# ./configure --prefix=/usr/local/nginx --user=www --group=www     --with-http_ssl_module --with-http_stub_status_module --with-file-aio --with-http_dav_module --add-module=../ngx_devel_kit-0.2.19/ --add-module=../lua-nginx-module-0.9.16/ --with-pcre=/usr/local/src/pcre-8.37 
[root@openstack-compute-node5 nginx-1.5.12]# make -j2 && make install
[root@openstack-compute-node5 ~]# ln -s /usr/local/lib/libluajit-5.1.so.2 /lib64/libluajit-5.1.so.2   #一定创建此软连接,否则报错

安装完毕后,下面可以测试安装了,修改nginx.conf 增加第一个配置

location /hello {
                default_type 'text/plain';
                content_by_lua 'ngx.say("hello,lua")';
        }
[root@openstack-compute-node5 ~]# /usr/local/nginx-1.9.4/sbin/nginx –t
[root@openstack-compute-node5 ~]# /usr/local/nginx-1.9.4/sbin/nginx

效果如下

未分类

3.2.3 Openresty部署

安装依赖包

[root@iZ28t900vpcZ ~]#yum install -y readline-devel pcre-devel openssl-devel

下载并编译安装openresty

[root@iZ28t900vpcZ ~]#cd /usr/local/src
[root@iZ28t900vpcZ src]#wget https://openresty.org/download/ngx_openresty-1.9.3.2.tar.gz
[root@iZ28t900vpcZ src]#tar zxf ngx_openresty-1.9.3.2.tar.gz
[root@iZ28t900vpcZ src]#cd ngx_openresty-1.9.3.2
[root@iZ28t900vpcZ ngx_openresty-1.9.3.2]# ./configure --prefix=/usr/local/openresty-1.9.3.2 --with-luajit --with-http_stub_status_module --with-pcre --with-pcre-jit
[root@iZ28t900vpcZ ngx_openresty-1.9.3.2]#gmake && gmake install
ln -s /usr/local/openresty-1.9.3.2/ /usr/local/openresty

测试openresty安装

[root@iZ28t900vpcZ ~]#vim /usr/local/openresty/nginx/conf/nginx.conf
server {
    location /hello {
            default_type text/html;
            content_by_lua_block {
                ngx.say("HelloWorld")
            }
        }
}

测试并启动nginx

[root@iZ28t900vpcZ ~]#/usr/local/openresty/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/openresty-1.9.3.2/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/openresty-1.9.3.2/nginx/conf/nginx.conf test is successful
[root@iZ28t900vpcZ ~]#/usr/local/openresty/nginx/sbin/nginx

3.2.4 WAF部署

在github上克隆下代码

[root@iZ28t900vpcZ ~]#git clone https://github.com/unixhot/waf.git
[root@iZ28t900vpcZ ~]#cp -a ./waf/waf /usr/local/openresty/nginx/conf/

修改Nginx的配置文件,加入(http字段)以下配置。注意路径,同时WAF日志默认存放在/tmp/日期_waf.log

#WAF
    lua_shared_dict limit 50m;  #防cc使用字典,大小50M
    lua_package_path "/usr/local/openresty/nginx/conf/waf/?.lua";
    init_by_lua_file "/usr/local/openresty/nginx/conf/waf/init.lua";
    access_by_lua_file "/usr/local/openresty/nginx/conf/waf/access.lua";
[root@openstack-compute-node5 ~]# /usr/local/openresty/nginx/sbin/nginx –t
[root@openstack-compute-node5 ~]# /usr/local/openresty/nginx/sbin/nginx

根据日志记录位置,创建日志目录

[root@iZ28t900vpcZ ~]#mkdir /tmp/waf_logs
[root@iZ28t900vpcZ ~]#chown nginx.nginx /tmp/waf_logs

3.3 学习模块

3.3.1 学习配置模块

WAF上生产之前,建议不要直接上生产,而是先记录日志,不做任何动作。确定WAF不产生误杀

config.lua即WAF功能详解

[root@iZ28t900vpcZ waf]# pwd
/usr/local/nginx/conf/waf
[root@iZ28t900vpcZ waf]# cat config.lua
--WAF config file,enable = "on",disable = "off" 
--waf status    
config_waf_enable = "on"   #是否开启配置
--log dir 
config_log_dir = "/tmp/waf_logs"    #日志记录地址
--rule setting 
config_rule_dir = "/usr/local/nginx/conf/waf/rule-config"                                                                  
                         #匹配规则缩放地址
--enable/disable white url 
config_white_url_check = "on"  #是否开启url检测
--enable/disable white ip 
config_white_ip_check = "on"   #是否开启IP白名单检测
--enable/disable block ip 
config_black_ip_check = "on"   #是否开启ip黑名单检测
--enable/disable url filtering 
config_url_check = "on"      #是否开启url过滤
--enalbe/disable url args filtering 
config_url_args_check = "on"   #是否开启参数检测
--enable/disable user agent filtering 
config_user_agent_check = "on"  #是否开启ua检测
--enable/disable cookie deny filtering 
config_cookie_check = "on"    #是否开启cookie检测
--enable/disable cc filtering 
config_cc_check = "on"   #是否开启防cc攻击
--cc rate the xxx of xxx seconds 
config_cc_rate = "10/60"   #允许一个ip60秒内只能访问10此
--enable/disable post filtering 
config_post_check = "on"   #是否开启post检测
--config waf output redirect/html 
config_waf_output = "html"  #action一个html页面,也可以选择跳转
--if config_waf_output ,setting url 
config_waf_redirect_url = "http://www.baidu.com" 
config_output_html=[[  #下面是html的内容
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta http-equiv="Content-Language" content="zh-cn" /> 
<title>网站防火墙</title> 
</head> 
<body> 
<h1 align="center"> # 您的行为已违反本网站相关规定,注意操作规范。
</body> 
</html> 
]] 

3.4 学习access.lua的配置

[root@iZ28t900vpcZ waf]# pwd
/usr/local/openresty/nginx/conf/waf
[root@iZ28t900vpcZ waf]# cat access.lua 
require 'init'
function waf_main()
    if white_ip_check() then
    elseif black_ip_check() then
    elseif user_agent_attack_check() then
    elseif cc_attack_check() then
    elseif cookie_attack_check() then
    elseif white_url_check() then
    elseif url_attack_check() then
    elseif url_args_attack_check() then
    --elseif post_attack_check() then
    else
        return  
    end
end
waf_main()

书写书序:先检查白名单,通过即不检测;再检查黑名单,不通过即拒绝,检查UA,UA不通过即拒绝;检查cookie;URL检查;URL参数检查,post检查;

3.5 启用WAF并测试

3.5.1模拟sql注入即url攻击

显示效果如下

未分类

日志显示如下,记录了UA,匹配规则,URL,客户端类型,攻击的类型,请求的数据

未分类

3.5.2 使用ab压测工具模拟防cc攻击

[root@linux-node3 ~]# ab -c 100 -n 100 http://www.chuck-blog.com/index.php
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking www.chuck-blog.com (be patient).....done
Server Software:        openresty
Server Hostname:        www.chuck-blog.com
Server Port:            80
Document Path:          /index.php
Document Length:        0 bytes
Concurrency Level:      100
Time taken for tests:   0.754 seconds
Complete requests:      10
Failed requests:        90 #config.lua中设置的,60秒内只允许10个请求
Write errors:           0
Non-2xx responses:      90
Total transferred:      22700 bytes
HTML transferred:       0 bytes
Requests per second:    132.65 [#/sec] (mean)
Time per request:       753.874 [ms] (mean)
Time per request:       7.539 [ms] (mean, across all concurrent requests)
Transfer rate:          29.41 [Kbytes/sec] received
Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       23   69  20.2     64     105
Processing:    32  180 144.5    157     629
Waiting:       22  179 144.5    156     629
Total:         56  249 152.4    220     702
Percentage of the requests served within a certain time (ms)
  50%    220
  66%    270
  75%    275
  80%    329
  90%    334
  95%    694
  98%    701
  99%    702
  100%    702 (longest request)

3.5.3 模拟ip黑名单
将请求ip放入ip黑名单中

[root@iZ28t900vpcZ rule-config]# echo “1.202.193.133” >>/usr/local/openresty/nginx/conf/waf/rule-config/blackip.rule

3.5.4 模拟ip白名单
将请求ip放入ip白名单中,此时将不对此ip进行任何防护措施,所以sql注入时应该返回404

[root@iZ28t900vpcZ rule-config]# echo “1.202.193.133” >>/usr/local/openresty/nginx/conf/waf/rule-config/whiteip.rule

3.5.5 模拟URL参数检测
浏览器输入www.chuck-blog.com/?a=select * from table
详细规定在arg.rule中有规定,对请求进行了规范

[root@iZ28t900vpcZ rule-config]# /usr/local/openresty/nginx/conf/waf/rule-config/cat args.rule 
../
:$
${
select.+(from|limit)
(?:(union(.*?)select))
having|rongjitest
sleep((s*)(d*)(s*))
benchmark((.*),(.*))
base64_decode(
(?:fromW+information_schemaW)
(?:(?:current_)user|database|schema|connection_id)s*(
(?:etc/W*passwd)
into(s+)+(?:dump|out)files*
groups+by.+(
xwork.MethodAccessor
    (?:define|eval|file_get_contents|include|require|require_once|shell_exec|phpinfo|system|passthru|preg_w+|execute|echo|print|print_r|var_dump|(fp)open|alert|showmodaldialog)(
xwork.MethodAccessor
    (gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data):/
java.lang
    $_(GET|post|cookie|files|session|env|phplib|GLOBALS|SERVER)[
    <(iframe|script|body|img|layer|div|meta|style|base|object|input)
(onmouseover|onerror|onload)=
[root@iZ28t900vpcZ rule-config]# pwd
/usr/local/openresty/nginx/conf/waf/rule-config

四、防cc攻击利器之httpgrard

4.1 httpgrard介绍

HttpGuard是基于openresty,以lua脚本语言开发的防cc攻击软件。而openresty是集成了高性能web服务器Nginx,以及一系列的Nginx模块,这其中最重要的,也是我们主要用到的nginx lua模块。HttpGuard基于nginx lua开发,继承了nginx高并发,高性能的特点,可以以非常小的性能损耗来防范大规模的cc攻击。

4.2 httpgrard防cc特效

  • 限制访客在一定时间内的请求次数
  • 向访客发送302转向响应头来识别恶意用户,并阻止其再次访问
  • 向访客发送带有跳转功能的js代码来识别恶意用户,并阻止其再次访问
  • 向访客发送cookie来识别恶意用户,并阻止其再次访问
  • 支持向访客发送带有验证码的页面,来进一步识别,以免误伤
  • 支持直接断开恶意访客的连接
  • 支持结合iptables来阻止恶意访客再次连接
  • 支持白名单功能
  • 支持根据统计特定端口的连接数来自动开启或关闭防cc模式
  • 详见github地址,在后续的博文中会加入此功能

五、WAF上线

  • 初期上线只记录日志,不开启WAF,防止误杀
  • WAF规则管理使用saltstack工具
  • 要知道并不是有了WAF就安全,存在人为因素

用openresty实现动态upstream反向代理

前言

此文的读者定义为对openresty有一定了解的读者。

openresty:
https://github.com/openresty/lua-nginx-module

此文要讲什么

大家都知道openresty可以用ngx.location.capture和ngx.exec来实现内部跳转,
下面要讲怎么将ngx.location.capture和ngx.exec与upstream模块结合起来,实现一个动态的upstream。

下面的演示中:

80端口表示首次请求入口
8080端口表示upstream的出口

直接上配置和源码

配置: conf/nginx.conf

    worker_processes  1;  
    error_log logs/error.log;  
    events {  
        worker_connections 1024;  
    }  

    http {  

        log_format  main  '$msec $status $request $request_time '  
                          '$http_referer $remote_addr [ $time_local ] '  
                          '$upstream_response_time $host $bytes_sent '  
                          '$request_length $upstream_addr';  

        access_log  logs/access.log main buffer=32k flush=1s;  


        upstream remote_hello {  
            server 127.0.0.1:8080;  
        }  

        upstream remote_world {  
            server 127.0.0.1:8080;  
        }  

        server {  
            listen 80;  

            location /capture {  
                content_by_lua '  
                    local test = require "lua.test"  
                    test.capture_test()  
                ';  
            }  

            location /exec {  
                content_by_lua '  
                    local test = require "lua.test"  
                    test.exec_test()  
                ';  
            }  

            location /upstream {  
                internal;  

                set $my_upstream $my_upstream;  
                set $my_uri $my_uri;  
                proxy_pass http://$my_upstream$my_uri;  
            }  
        }  


        server {  
            listen 8080;  
            location /hello {  
                echo "hello";  
            }  

            location /world {  
                echo "world";  
            }  
        }  
    }  

源码: lua/test.lua

    local _M = { _VERSION = '1.0' }  

    function _M:capture_test()  
        local res = ngx.location.capture("/upstream",  
            {  
                 method = ngx.HTTP_GET,  
                 vars = {  
                     my_upstream = "remote_hello",  
                     my_uri = "/hello",  
                 },  
            }  
        )  
        if res == nil or res.status ~= ngx.HTTP_OK then  
            ngx.say("capture failed")  
            return  
        end  
        ngx.print(res.body)  
    end  

    function _M:exec_test()  
        ngx.var.my_upstream = "remote_world"  
        ngx.var.my_uri = "/world"  
        ngx.exec("/upstream")  
    end  

    return _M  

运行效果

未分类

OpenResty json 删除转义符

OpenResty 中删除 json 中的转义符

cjson 在 encode 时 “/” 会自动添加转义符 “”; 在 decode 时也会自动将转义符去掉。工作中有个特殊需求,需要手工删除转义符。记录备忘,代码如下:

#! /usr/bin/env lua
json = require "cjson"

result = {}
result["stream"] = "lufei"
result["app"] = "live/cartoon"
oldStr = json.encode(result)
local from, to, err = ngx.re.find(oldStr, [[\]])
ngx.say(from, to)
newStr, n, err = ngx.re.gsub(oldStr, [[\/]], [[/]])
ngx.say("oldStr: "..oldStr)
ngx.say("newStr: "..newStr )
t = json.decode(newStr)
ngx.say(t["app"])
dill@bunbun:~/openresty-test/locations$ curl -i localhost:6699/test
HTTP/1.1 200 OK
Server: openresty/1.11.2.2
Date: Wed, 19 Jul 2017 04:38:07 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive

1313
oldStr: {"app":"live/cartoon","stream":"lufei"}
newStr: {"app":"live/cartoon","stream":"lufei"}
live/cartoon

openresty设置用于access_log的自定义变量

期望:在access_log打印自定义变量define_error_code

nginx配置:

    worker_processes  1;  

    events {  
        worker_connections  1024;  
    }  


    http {  

        log_format main '[$time_local] $request $status $remote_addr $define_error_code';  

        server {  
            listen       80;  

            location / {  
                set $define_error_code '';  
                content_by_lua_block {  
                    ngx.var.define_error_code = 9527  
                    ngx.say("hello world")  
                }  
            }  

            access_log logs/access.log main;  
            error_log logs/error.log;  
        }  

    }  

测试结果:

未分类

OpenResty(Nginx Lua)获取Nginx Worker CPU使用率

在上文我们介绍了三种获取进程cpu使用率的方法,本文介绍使用openresty来获取所有nginx worker的cpu使用率,然后提供一个接口来输出cpu使用率。由于收集cpu使用率需要获取两次,两次之间需要等待一些时间,为了保证此接口的性能,决定不采用接口实时统计,采用后台定时统计,然后接口查询其数据就行。
所有步骤思路为:

  1. 在init_worker阶段获取所有的worker pid
  2. 在init_worker阶段启动一个定时器来统计所有nginx worker cpu使用率并存储到共享字典
  3. 接口查询共享字典中的结果返回给客户端

int_worker定时统计cpu使用率

http {
    [...]
    lua_shared_dict dict 10m;
    init_worker_by_lua_block {
        -- 获取所有worker pid到字典
        local worker_pid = ngx.worker.pid()
        local worker_id = ngx.worker.id()
        ngx.shared.dict:set(worker_id,worker_pid)

        -- 统计cpu使用率函数
        local function count_cpu_usage(premature)
            -- 首次获取cpu时间
            local worker_cpu_total1 = 0
            local cpu_total1 = 0

            local worker_count = ngx.worker.count()

            for i=0, worker_count - 1 do    
                local worker_pid = ngx.shared.dict:get(i)
                local fp = io.open("/proc/"..worker_pid.."/stat","r")
                local data = fp:read("*all")
                fp:close()
                local res, err = ngx.re.match(data, "(.*? ){13}(.*?) (.*?) ", "jio")
                worker_cpu = res[2] + res[3]
                worker_cpu_total1 = worker_cpu_total1 + worker_cpu
            end

            local fp = io.open("/proc/stat","r")
            local cpu_line = fp:read()
            fp:close()
            local iterator, err = ngx.re.gmatch(cpu_line,"(\d+)")
            while true do
                local m, err = iterator()
                if not m then
                    break
                end

                cpu_total1 = cpu_total1 + m[0]
            end

            -- 第二次获取cpu时间
            ngx.sleep(0.5)
            local worker_cpu_total2 = 0
            local cpu_total2 = 0

            for i=0, worker_count -1 do    
                local worker_pid = ngx.shared.dict:get(i)
                local fp = io.open("/proc/"..worker_pid.."/stat","r")
                local data = fp:read("*all")
                fp:close()
                local res, err = ngx.re.match(data, "(.*? ){13}(.*?) (.*?) ", "jio")
                worker_cpu = res[2] + res[3]
                worker_cpu_total2 = worker_cpu_total2 + worker_cpu
            end

            local fp = io.open("/proc/stat","r")
            local cpu_line = fp:read()
            fp:close()
            local iterator, err = ngx.re.gmatch(cpu_line,"(\d+)")
            while true do
                local m, err = iterator()
                if not m then
                    break
                end

                cpu_total2 = cpu_total2 + m[0]
            end

            -- 获取cpu核心数
            local cpu_core = 0
            local fp = io.open("/proc/cpuinfo")
            local data = fp:read("*all")
            fp:close()
            local iterator, err = ngx.re.gmatch(data, "processor","jio")
            while true do
                local m, err = iterator()
                if not m then
                    break
                end
                cpu_core = cpu_core + 1
            end

            -- 计算出cpu时间
            local nginx_workers_cpu_time = ((worker_cpu_total2 - worker_cpu_total1) / (cpu_total2 - cpu_total1)) * 100*cpu_core
            nginx_workers_cpu_time = string.format("%d", nginx_workers_cpu_time)
            ngx.shared.dict:set("nginx_workers_cpu_time",nginx_workers_cpu_time)
        end


        -- 定时任务
        local function count_cpu_usage_timed_job()
            -- 定义间隔执行时间
            local delay = 2
            local count
            count = function(premature)
                if not premature then
                    local ok, err = pcall(count_cpu_usage, premature)
                    if not ok then
                        log(ERR, "count cpu usage error:",err)
                    end    
                    local ok, err = ngx.timer.at(delay, count)
                    if not ok then
                        return
                    end
                end
            end
            local ok, err = ngx.timer.at(delay, count)
            if not ok then
                return
            end
        end

        -- 执行定时任务
        count_cpu_usage_timed_job()
    }
    [...]
}

定义获取cpu使用率的接口

location /cpu {
    content_by_lua_block {
        local nginx_workers_cpu_time = ngx.shared.dict:get(nginx_workers_cpu_time)
        ngx.header.content_type = 'text/plain'
        ngx.say("nginx_workers_cpu_time")
    }
}

OpenResty(Nginx Lua)统计网站访问信息

背景

之前的一篇文章openresty(nginx lua)统计域名状态码、平均响应时间和流量实现了对域名状态码,平均响应时间和流量的统计。但之前的统计方法没有实现当某一域名404或500等状态码超过一定数量后发送具体的url来快速定位位置。这个功能我们其实是通过统计网站日志来实现了。为了摆脱对网站日志的依赖以及提高统计性能,我们尝试把此功能也用nginx lua来实现。具体的使用方法与之前的文章一样,这里只是更新了两个lua脚本。

使用方法

1、获取域名devops.webres.wang 404状态码数量

  1. curl -s "localhost/domain_status?count=status&host=devops.webres.wang&status=404"

输出:
10 688
第一列为状态码数量,第二列为域名请求总数
2、获取当域名devops.webres.wang 404状态码超过50个时,输出前10个url

  1. curl -s "localhost/domain_status?count=statusUrl&host=devops.webres.wang&status=404&exceed=50&output=10"

输出:
/hello-world 90
/centos 10

第一列为url,第二列为url请求次数。
3、获取域名devops.webres.wang upstream一分钟内平均耗时

  1. curl -s "localhost/domain_status?count=upT&host=devops.webres.wang"

输出:
0.02 452
第一列为upstream平均耗时,第二列为域名总请求次数。
4、获取当域名devops.webres.wang upstream平均耗时超过0.5秒时,输出其url

  1. curl -s "localhost/domain_status?count=upTUrl&host=devops.webres.wang&exceed=0.5"

输出:
/hello.php 0.82 52
第一列为url,第二列为此url平均耗时,第三列为此url请求次数。监控此接口数据可以快速定位出具体哪些url慢了。
5、获取域名devops.webres.wang request time平均耗时

  1. curl -s "localhost/domain_status?count=reqT&host=devops.webres.wang"

输出:
1.82 52
第一列为平均耗时,第二列为域名请求数。request time是指完成整个请求所需要的时间(包括把数据传输到用户浏览器的时间)。对于php请求,upstream time指的是nginx把php请求传给fastcgi到完成数据接收所需时间。所以request time永远大于upstream time。
6、获取域名devops.webres.wang占用的带宽(单位:字节/秒)

  1. curl -s "localhost/domain_status?count=flow&host=devops.webres.wang"

输出:
1024 52
第一列为此域名一分钟内平均传输速率,单位为字节/秒,第二列为域名请求总数。

相关脚本

log_acesss.lua

  1. local access = ngx.shared.access
  2. local host = ngx.var.host or "unknow"
  3. local status = ngx.var.status
  4. local body_bytes_sent = ngx.var.body_bytes_sent
  5. local request_time = ngx.var.request_time
  6. local upstream_response_time = ngx.var.upstream_response_time or 0
  7. local request_uri = ngx.var.request_uri or "/unknow"
  8. local timestamp = ngx.time()
  9. local expire_time = 70
  10.  
  11. local status_key = table.concat({host,"-",status,"-",timestamp})
  12. local flow_key = table.concat({host,"-flow-",timestamp})
  13. local req_time_key = table.concat({host,"-reqt-",timestamp})
  14. local up_time_key = table.concat({host,"-upt-",timestamp})
  15. local total_key = table.concat({host,"-total-",timestamp})
  16.  
  17. — 域名总请求数
  18. local n,e = access:incr(total_key,1)
  19. if not n then
  20. access:set(total_key, 1, expire_time)
  21. end
  22.  
  23. — 域名状态码请求数
  24. local n,e = access:incr(status_key,1)
  25. if not n then
  26. access:set(status_key, 1, expire_time)
  27. end
  28.  
  29. — 域名流量
  30. local n,e = access:incr(flow_key,body_bytes_sent)
  31. if not n then
  32. access:set(flow_key, body_bytes_sent, expire_time)
  33. end
  34.  
  35. — 域名请求耗时
  36. local n,e = access:incr(req_time_key,request_time)
  37. if not n then
  38. access:set(req_time_key, request_time, expire_time)
  39. end
  40.  
  41. — 域名upstream耗时
  42. local n,e = access:incr(up_time_key,upstream_response_time)
  43. if not n then
  44. access:set(up_time_key, upstream_response_time, expire_time)
  45. end
  46.  
  47. — 获取不带参数的uri
  48. local m, err = ngx.re.match(request_uri, "(.*?)\?")
  49. local request_without_args = m and m[1] or request_uri
  50.  
  51. — 存储状态码大于400的url
  52. if tonumber(status) >= 400 then
  53. — 拼接url,状态码,字节数等字段
  54. local request_log_t = {}
  55. table.insert(request_log_t,host)
  56. table.insert(request_log_t,request_without_args)
  57. table.insert(request_log_t,status)
  58. local request_log = table.concat(request_log_t," ")
  59.  
  60. — 把拼接的字段储存在字典中
  61. local log_key = table.concat({"status-",timestamp})
  62. local request_log_dict = access:get(log_key) or ""
  63. if request_log_dict == "" then
  64. request_log_dict = request_log
  65. else
  66. request_log_dict = table.concat({request_log_dict,"n",request_log})
  67. end
  68. access:set(log_key, request_log_dict, expire_time)
  69. end
  70.  
  71. — 存储upstream time大于0.5的url
  72. if tonumber(upstream_response_time) > 0.5 then
  73. — 拼接url,状态码,字节数等字段
  74. local request_log_t = {}
  75. table.insert(request_log_t,host)
  76. table.insert(request_log_t,request_without_args)
  77. table.insert(request_log_t,upstream_response_time)
  78. local request_log = table.concat(request_log_t," ")
  79.  
  80. — 把拼接的字段储存在字典中
  81. local log_key = table.concat({"upt-",timestamp})
  82. local request_log_dict = access:get(log_key) or ""
  83. if request_log_dict == "" then
  84. request_log_dict = request_log
  85. else
  86. request_log_dict = table.concat({request_log_dict,"n",request_log})
  87. end
  88. access:set(log_key, request_log_dict, expire_time)
  89. end

domain_status.lua

  1. — 各参数用法:
  2. — count=status,host=xxx.com,status=404 统计xxx.com域名一分钟内404状态码个数.
  3. — count=statusUrl,host=xxx.com,status=404,exceed=50,output=30 当xxx.com域名404状态码一分钟内超过50个时,输出前30个url,否则返回空.
  4.  
  5. — count=upT,host=xxx.com 统计xxx.com域名一分钟内平均upsteam耗时
  6. — count=upTUrl,host=xxx.com,exceed=0.5 输出upstreamTime超过0.5秒的url,没有就返回空
  7.  
  8. — count=reqT,host=xxx.com 统计xxx.com域名一分钟内平均请求耗时
  9. — count=flow,host=xxx.com 统计xxx.com域名一分钟内流量(单位字节/秒)
  10.  
  11. — 函数: 获取迭代器值
  12. local get_field = function(iterator)
  13.     local m,err = iterator
  14.     if err then
  15.         ngx.log(ngx.ERR, "get_field iterator error: ", err)
  16.         ngx.exit(ngx.HTTP_OK)
  17.     end
  18.     return m[0]
  19. end
  20.  
  21. — 函数: 按值排序table
  22. local getKeysSortedByValue = function (tbl, sortFunction)
  23.   local keys = {}
  24.   for key in pairs(tbl) do
  25.     table.insert(keys, key)
  26.   end
  27.  
  28.   table.sort(keys, function(a, b)
  29.     return sortFunction(tbl[a], tbl[b])
  30.   end)
  31.  
  32.   return keys
  33. end
  34.  
  35. — 函数: 判断table是否存在某元素
  36. local tbl_contain = function(table,element)
  37.     for k in pairs(table) do
  38.         if k == element then
  39.             return true
  40.         end
  41.     end
  42.     return false
  43. end
  44.  
  45. local access = ngx.shared.access
  46. local now = ngx.time()
  47. local one_minute_ago = now – 60
  48.  
  49. — 获取参数
  50. local args = ngx.req.get_uri_args()
  51. local count_arg = args["count"]
  52. local host_arg = args["host"]
  53. local status_arg = args["status"]
  54. local exceed_arg = args["exceed"]
  55. local output_arg = args["output"]
  56. local count_t = {["status"]=0,["statusUrl"]=0,["upT"]=0,["upTUrl"]=0,["reqT"]=0,["flow"]=0}
  57.  
  58. — 检查参数是否满足
  59. if not tbl_contain(count_t,count_arg) then
  60.     ngx.print("count arg invalid.")
  61.     ngx.exit(ngx.HTTP_OK)
  62. end
  63.  
  64. if not host_arg then
  65.     ngx.print("host arg not found.")
  66.     ngx.exit(ngx.HTTP_OK)
  67. end
  68.  
  69. if count_arg == "status" and not status_arg then
  70.     ngx.print("status arg not found.")
  71.     ngx.exit(ngx.HTTP_OK)
  72. end
  73.  
  74. if count_arg == "statusUrl" and not (status_arg and exceed_arg and output_arg)  then
  75.     ngx.print("status or exceed or output arg not found.")
  76.     ngx.exit(ngx.HTTP_OK)
  77. end
  78.  
  79. if count_arg == "upTUrl" and not exceed_arg then
  80.     ngx.print("exceed arg not found.")
  81.     ngx.exit(ngx.HTTP_OK)
  82. end
  83.  
  84. — 检查参数是否合法
  85. if status_arg and ngx.re.find(status_arg, "^[0-9]{3}$") == nil then
  86.     ngx.print("status arg must be a valid httpd code.")
  87.     ngx.exit(ngx.HTTP_OK)
  88. end
  89.  
  90. if exceed_arg and ngx.re.find(exceed_arg, "^[0-9.]+$") == nil then
  91.     ngx.print("exceed arg must be a number.")
  92.     ngx.exit(ngx.HTTP_OK)
  93. end
  94.  
  95. if output_arg and ngx.re.find(output_arg, "^[0-9]+$") == nil then
  96.     ngx.print("output arg must be a number.")
  97.     ngx.exit(ngx.HTTP_OK)
  98. end
  99.  
  100. — 开始统计
  101. local url
  102. local status_code
  103. local upstream_time
  104. local status_total = 0
  105. local host
  106. local req_total = 0
  107. local flow_total = 0
  108. local reqtime_total = 0
  109. local upstream_total = 0
  110. local status_url_t = {}
  111. local upstream_url_t = {}
  112. local upstream_url_count_t = {}
  113.  
  114. local status_log
  115. local upt_log
  116.  
  117. for second_num=one_minute_ago,now do
  118.     local flow_key = table.concat({host_arg,"-flow-",second_num})
  119.     local req_time_key = table.concat({host_arg,"-reqt-",second_num})
  120.     local up_time_key = table.concat({host_arg,"-upt-",second_num})
  121.     local total_req_key = table.concat({host_arg,"-total-",second_num})
  122.     local log_key
  123.     local log_line
  124.  
  125.     — 合并状态码大于等于400的请求日志到变量status_log
  126.     log_key = table.concat({"status-",second_num})
  127.     log_line = access:get(log_key) or ""
  128.     if not (log_line == "") then
  129.         status_log = table.concat({log_line,"n",status_log})
  130.     end
  131.  
  132.     — 合并upstream time大于0.5秒的请求日志到变量upt_log
  133.     log_key = table.concat({"upt-",second_num})
  134.     log_line = access:get(log_key) or ""
  135.     if not (log_line == "") then
  136.         upt_log = table.concat({log_line,"n",upt_log})
  137.     end
  138.  
  139.     — 域名总请求数
  140.     local req_sum = access:get(total_req_key) or 0
  141.     req_total = req_total + req_sum
  142.  
  143.     if count_arg == "status" or count_arg == "statusUrl" then
  144.         local status_key = table.concat({host_arg,"-",status_arg,"-",second_num})
  145.         local status_sum = access:get(status_key) or 0
  146.         status_total = status_total + status_sum
  147.     end
  148.  
  149.     if count_arg == "flow" then
  150.         local flow_sum = access:get(flow_key) or 0
  151.         flow_total = flow_total + flow_sum
  152.     end
  153.  
  154.     if count_arg == "reqT" then
  155.         local req_time_sum = access:get(req_time_key) or 0
  156.         reqtime_total = reqtime_total + req_time_sum
  157.     end
  158.  
  159.     if count_arg == "upT" then
  160.         local up_time_sum = access:get(up_time_key) or 0
  161.         upstream_total = upstream_total + up_time_sum
  162.     end
  163. end
  164.  
  165. — 统计状态码url
  166. if count_arg == "statusUrl" and status_log and not (status_log == "") then
  167.     local iterator, err = ngx.re.gmatch(status_log,".+n")
  168.     if not iterator then
  169.         ngx.log(ngx.ERR, "status_log iterator error: ", err)
  170.         return
  171.     end
  172.     for line in iterator do
  173.         if not line[0] then
  174.             ngx.log(ngx.ERR, "line[0] is nil")
  175.             return
  176.         end
  177.         local iterator, err = ngx.re.gmatch(line[0],"[^ n]+")
  178.         if not iterator then
  179.             ngx.log(ngx.ERR, "line[0] iterator error: ", err)
  180.             return
  181.         end
  182.  
  183.         host = get_field(iterator())
  184.         url = get_field(iterator())
  185.         status_code = get_field(iterator())
  186.  
  187.         if status_code == status_arg then
  188.             if status_url_t[url] then
  189.                 status_url_t[url] = status_url_t[url] + 1
  190.             else
  191.                 status_url_t[url] = 1
  192.             end
  193.         end
  194.  
  195.     end   
  196. end
  197.  
  198. — 统计upstream time大于0.5秒url
  199. if count_arg == "upTUrl" and upt_log and not (upt_log == "") then
  200.     local iterator, err = ngx.re.gmatch(upt_log,".+n")
  201.     if not iterator then
  202.         ngx.log(ngx.ERR, "upt_log iterator error: ", err)
  203.         return
  204.     end
  205.     for line in iterator do
  206.         if not line[0] then
  207.             ngx.log(ngx.ERR, "line[0] is nil")
  208.             return
  209.         end
  210.         local iterator, err = ngx.re.gmatch(line[0],"[^ n]+")
  211.         if not iterator then
  212.             ngx.log(ngx.ERR, "line[0] iterator error: ", err)
  213.             return
  214.         end
  215.  
  216.         host = get_field(iterator())
  217.         url = get_field(iterator())
  218.         upstream_time = get_field(iterator())
  219.         upstream_time = tonumber(upstream_time) or 0
  220.  
  221.         — 统计各url upstream平均耗时
  222.         if host == host_arg then
  223.             if upstream_url_t[url] then
  224.                 upstream_url_t[url] = upstream_url_t[url] + upstream_time
  225.             else
  226.                 upstream_url_t[url] = upstream_time
  227.             end
  228.  
  229.             if upstream_url_count_t[url] then
  230.                 upstream_url_count_t[url] = upstream_url_count_t[url] + 1
  231.             else
  232.                 upstream_url_count_t[url] = 1
  233.             end
  234.         end   
  235.     end   
  236. end
  237.  
  238. — 输出结果
  239. if count_arg == "status" then
  240.     ngx.print(status_total," ",req_total)
  241.  
  242. elseif count_arg == "flow" then
  243.     ngx.print(flow_total," ",req_total)
  244.  
  245. elseif count_arg == "reqT" then
  246.     local reqt_avg = 0
  247.     if req_total == 0 then
  248.         reqt_avg = 0
  249.     else
  250.         reqt_avg = reqtime_total/req_total
  251.     end
  252.     ngx.print(reqt_avg," ",req_total)
  253.  
  254. elseif count_arg == "upT" then
  255.     local upt_avg = 0
  256.     if req_total == 0 then
  257.             upt_avg = 0
  258.     else
  259.             upt_avg = upstream_total/req_total
  260.     end
  261.     ngx.print(upt_avg," ",req_total)
  262.  
  263. elseif count_arg == "statusUrl" then
  264.     if status_total > tonumber(exceed_arg) then
  265.         — 排序table
  266.         status_url_t_key = getKeysSortedByValue(status_url_t, function(a, b) return a > b end)
  267.         local output_body = ""
  268.         for i, uri in ipairs(status_url_t_key) do
  269.             if output_body == "" then
  270.                 output_body = table.concat({uri," ",status_url_t[uri]})
  271.             else   
  272.                 output_body = table.concat({output_body,"n",uri," ",status_url_t[uri]})
  273.             end
  274.             if i >= tonumber(output_arg) then
  275.                 ngx.print(output_body)
  276.                 ngx.exit(ngx.HTTP_OK)
  277.             end               
  278.         end
  279.  
  280.         ngx.print(output_body)
  281.         ngx.exit(ngx.HTTP_OK)
  282.     end
  283.  
  284. elseif count_arg == "upTUrl" then
  285.     local max_output = 30
  286.     local total_time = 0
  287.     local total_count = 0
  288.     local output_body = ""
  289.     local i = 0
  290.     for url in pairs(upstream_url_t) do
  291.         i = i + 1
  292.         total_time = upstream_url_t[url]
  293.         total_count = upstream_url_count_t[url]
  294.         avg_time = upstream_url_t[url] / upstream_url_count_t[url]
  295.         if avg_time > tonumber(exceed_arg) then
  296.             output_body = table.concat({url," ",avg_time," ",total_count,"n",output_body})
  297.         end
  298.  
  299.         if i >= max_output then
  300.             ngx.print(output_body)
  301.             ngx.exit(ngx.HTTP_OK)
  302.         end           
  303.     end
  304.     ngx.print(output_body)
  305.     ngx.exit(ngx.HTTP_OK)
  306.  
  307. end

openresty(nginx lua)统计域名状态码、平均响应时间和流量

背景

 

之前我们统计域名状态码、平均响应时间和流量的方法是:在每台机器添加一个定时脚本,来获取每个域名最近一分钟的访问日志到临时文件。然后zabbix再对这个一分钟日志临时文件作相关统计。一直运行良好,最近发现某台服务器突然负载增高。使用iotop查看发现获取最近一分钟日志的脚本占用的IO特别高。停止这个定时任务之后恢复正常。于是就打算使用nginx lua来替换目前的方法。新的方法具有统计时占用资源少,实时的特点。

 

方法介绍

 

使用nginx lua统计网站相关数据的方法为(我们以统计devops.webres.wang 404状态码为例):
记录过程:

  • 1、定义了一个共享词典access,获取当前时间戳,获取当前域名,如devops.webres.wang;
  • 2、我们定义用来存储状态码的词典key为,devops.webres.wang-404-当前时间戳;
  • 3、自增1 key(devops.webres.wang-404-当前时间戳)的值;
  • 4、循环2,3步。

 

查询过程:
提供一个接口,来累加key为devops.webres.wang-404-(前60秒时间戳-当前时间戳)的值,返回结果。

 

方法实现

 

nginx.conf设置

  1. http {
  2. […]
  3. lua_shared_dict access 10m;
  4. log_by_lua_file conf/log_acesss.lua;
  5. server {
  6. […]
  7.    location /domain_status {
  8.         default_type text/plain;
  9.         content_by_lua_file "conf/domain_status.lua";
  10.     }
  11. […]
  12. }
  13. […]
  14. }

 

log_access.lua

  1. local access = ngx.shared.access
  2. local host = ngx.var.host
  3. local status = ngx.var.status
  4. local body_bytes_sent = ngx.var.body_bytes_sent
  5. local request_time = ngx.var.request_time
  6. local timestamp = os.date("%s")
  7. local expire_time = 70
  8.  
  9. local status_key = table.concat({host,"-",status,"-",timestamp})
  10. local flow_key = table.concat({host,"-flow-",timestamp})
  11. local req_time_key = table.concat({host,"-reqt-",timestamp})
  12. local total_req_key = table.concat({host,"-total_req-",timestamp})
  13.  
  14. — count total req
  15. local total_req_sum = access:get(total_req_key) or 0
  16. total_req_sum = total_req_sum + 1
  17. access:set(total_req_key, total_req_sum, expire_time)
  18.  
  19. — count status
  20. local status_sum = access:get(status_key) or 0
  21. status_sum = status_sum + 1
  22. access:set(status_key, status_sum, expire_time)
  23.  
  24. — count flow
  25. local flow_sum = access:get(flow_key) or 0
  26. flow_sum = flow_sum + body_bytes_sent
  27. access:set(flow_key, flow_sum, expire_time)
  28.  
  29. — count request time
  30. local req_sum = access:get(req_time_key) or 0
  31. req_sum = req_sum + request_time
  32. access:set(req_time_key, req_sum, expire_time)

domain_status.lua

 

  1. local access = ngx.shared.access
  2. local args = ngx.req.get_uri_args()
  3. local count = args["count"]
  4. local host = args["host"]
  5. local status = args["status"]
  6. local one_minute_ago = tonumber(os.date("%s")) – 60
  7. local now = tonumber(os.date("%s"))
  8.  
  9. local status_total = 0
  10. local flow_total = 0
  11. local reqt_total = 0
  12. local req_total = 0
  13.  
  14. if not host then
  15.         ngx.print("host arg not found.")
  16.         ngx.exit(ngx.HTTP_OK)
  17. end
  18.  
  19. if count == "status" and not status then
  20.         ngx.print("status arg not found.")
  21.         ngx.exit(ngx.HTTP_OK)
  22. end
  23.  
  24. if not (count == "status" or count == "flow" or count == "reqt") then
  25.         ngx.print("count arg invalid.")
  26.         ngx.exit(ngx.HTTP_OK)
  27. end
  28.  
  29. for second_num=one_minute_ago,now do
  30.         local flow_key = table.concat({host,"-flow-",second_num})
  31.         local req_time_key = table.concat({host,"-reqt-",second_num})
  32.         local total_req_key = table.concat({host,"-total_req-",second_num})
  33.  
  34.         if count == "status" then
  35.                 local status_key = table.concat({host,"-",status,"-",second_num})
  36.                 local status_sum = access:get(status_key) or 0
  37.                 status_total = status_total + status_sum
  38.         elseif count == "flow" then
  39.                 local flow_sum = access:get(flow_key) or 0
  40.                 flow_total = flow_total + flow_sum
  41.         elseif count == "reqt" then
  42.                 local req_sum = access:get(total_req_key) or 0
  43.                 local req_time_sum = access:get(req_time_key) or 0
  44.                 reqt_total = reqt_total + req_time_sum
  45.                 req_total = req_total + req_sum
  46.         end
  47. end
  48.  
  49. if count == "status" then
  50.         ngx.print(status_total)
  51. elseif count == "flow" then
  52.         ngx.print(flow_total)
  53. elseif count == "reqt" then
  54.         if req_total == 0 then
  55.                 reqt_avg = 0
  56.         else
  57.                 reqt_avg = reqt_total/req_total
  58.         end
  59.         ngx.print(reqt_avg)
  60. end

使用说明

1、获取域名状态码
如请求devops.webres.wang一分钟内404状态码数量
请求接口http://$host/domain_status?count=status&host=devops.webres.wang&status=404
2、获取域名流量
请求接口http://$host/domain_status?count=flow&host=devops.webres.wang
3、获取域名一分钟内平均响应时间
请求接口http://$host/domain_status?count=reqt&host=devops.webres.wang