利用Nginx+lua扩展+redis实现网站拒绝高频次IP访问

一:基础环境

CentOS6.2

nginx1.11.10

redis2.8.21

二:扩展安装

(1)先安装Nginx需要的一些类库:

yum install gcc

yum install gcc-c++

注:此步骤只是在你的系统没有安装 gcc/gcc-c++ 的情况下才需要自行编译安装。

(2)编译安装库LuaJit-2.0.3:

./configure --prefix=/usr/local/luajit

make PREFIX=/usr/local/luajit

make install PREFIX=/usr/local/luajit

在/etc/profile文件中增加环境变量,并执行 source /etc/profile 使之生效(非必须):

export LUAJIT_LIB=/usr/install/luajit/lib

export LUAJIT_INC=/usr/install/luajit/include/luajit-2.0

注:此步骤只是在你的系统没有安装 LuaJIT 的情况下才需要自行编译安装。

(3)下载模块依赖 pcre-8.34、zlib-1.2.8、ngx_devel_kit 和 lua-nginx-module,最后编译Nginx:

完整的参数可能这样:

nginx -V

nginx version: nginx/1.11.10

built by gcc 4.4.7 20120313 (Red Hat 4.4.7-11) (GCC)

built with OpenSSL 1.0.1e-fips 11 Feb 2013

TLS SNI support enabled

configure arguments: --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_image_filter_module --with-http_gzip_static_module --with-http_realip_module --add-module=src/http/modules/nginx_upstream_check_module --add-module=src/http/modules/ngx_cache_purge/ --with-http_sub_module --add-module=src/http/modules/nginx-http-concat --with-http_random_index_module --add-module=src/ngx_devel_kit-0.3.0 --add-module=src/lua-nginx-module-master --add-module=src/http/modules/ngx_http_substitutions_filter_module-master/

三:lua使用redis

(1)下载lua连接操作redis必须文件

https://github.com/openresty/lua-resty-redis/blob/master/lib/resty/redis.lua

可将此文件放置于新创建的文件夹下

/usr/local/lua-resty-redis/

(2)nginx中引用

lua_package_path "/usr/local/lua-resty/redis.lua;;";

注:连接redis扩展包的引用要写在server之外

四:lua连接redis

文件名叫intercept_ip.lua

local redis = require "resty.redis"

local cache = redis.new()

local ok , err = cache.connect(cache,"127.0.0.1","6379")

cache:set_timeout(60000)

如果redis配置了requirepass,需要加一行

ok , err = cache:auth("相应的验证密码")

五:实现记录客户端IP与访问时间并对频次进行限制

(1)访问频次设置为30秒10次,进行测试,具体值根据实际场景需求进行设置

ip_time_out = 30

connect_count = 10

local host_name = ngx.var.remote_addr

start_time , err = cache:get(host_name .. "_time")

ip_count , err = cache:get(host_name .."_count")

if is_bind == '1' then

    ngx.exit(403)

end

if start_time == ngx.null or os.time() - start_time > ip_time_out then

    res , err = cache:set(host_name .. "_time" , os.time())

    res , err = cache:set(host_name .. "_count" , 1)

else

    ip_count = ip_count + 1

    res , err = cache:incr(host_name .. "_count" )

    if ip_count >= connect_count then

        res , err = cache:set(host_name .. "_bind" , 1)

    end

end

以上针对IP访问次数进行了屏蔽,但问题依然存在。

第一:采集用的IP通常是不固定的,也就是说每隔一段时间,IP资源会重置,旧的IP资源可能会被分配到正常用户的客户端上。所以我们要对IP设置解封时间

第二:如果是公司接入专线,有可能几十人或者近百人同时访问。所以我们要做一个可以校验是否为浏览器的测试。

(2)根据以上问题对代码进行完善

--封禁IP时间

ip_bind_time = 30

--指定ip访问频率时间段

ip_time_out = 30

--指定ip访问频率计数最大值

connect_count = 10

local host_name = ngx.var.remote_addr

--连接redis

local redis = require "resty.redis"

local cache = redis.new()

local ok , err = cache.connect(cache,"127.0.0.1","6379")

local random = math.random(99999)

cache:set_timeout(60000)

--如果连接失败,跳转到脚本结尾

if not ok then

    goto A

end

--查询ip是否在封禁段内,若在则返回403错误代码

--因封禁时间会大于ip记录时间,故此处不对ip时间key和计数key做处理

is_bind , err = cache:get("bind_"..host_name)

--判断是否是被标记的ip,如果已经被标记则检测设置的cookie是否正常返回

--cookie正常返回则判断是浏览器行为,删除记录值,否则认为是非正常流量,返回403

if is_bind == '1' then

    is_token , err = cache:get("token_"..host_name)

    if (ngx.var.cookie_token == is_token)then

        res , err = cache:del("bind_"..host_name)

        res , err = cache:del("token_"..host_name)

        res , err = cache:del("count_"..host_name)

        res , err = cache:del("time_"..host_name)

        goto A

    else

        res , err = cache:del("token_"..host_name)

        ngx.exit(403)

    end

    goto A

end

start_time , err = cache:get("time_"..host_name

ip_count , err = cache:get("count_"..host_name)

--如果ip记录时间大于指定时间间隔或者记录时间或者不存在ip时间key则重置时间key和计数key

--如果ip时间key小于时间间隔,则ip计数+1,且如果ip计数大于ip频率计数,则设置ip的封禁key为1

--同时设置封禁key的过期时间为封禁ip的时间

if start_time == ngx.null or os.time() - start_time > ip_time_out then

    res , err = cache:set("time_"..host_name , os.time())

    res , err = cache:set("count_"..host_name , 1)

else

    ip_count = ip_count + 1

    res , err = cache:incr("count_"..host_name)

    if ip_count >= connect_count then

        res , err = cache:set("bind_"..host_name,1)

        res , err = cache:expire("bind_"..host_name,ip_bind_time)

        local token = ngx.md5(random)

        res , err = cache:set("token_"..host_name,token)

        ngx.header["Set-Cookie"] = {"token="..token}

    end

end

--结尾标记

::A::

local ok, err = cache:close()

以上我们完成了对访问客户端IP甄别以及频次限制的nginx_lua脚本,但每个客户端IP从访问到结束,如果走完了被屏蔽的流程,会产生4个key。如果没产生屏蔽,则会留下两个key。造成了redis中key的臃肿。我们可以使用redis hash进行优化一下

(3)优化脚本

if not ok then

    goto A

end

--查询ip是否在封禁段内,若在则返回403错误代码

--因封禁时间会大于ip记录时间,故此处不对ip时间key和计数key做处理

is_bind , err = cache:hget(host_name , "bind")

--判断是否是被标记的ip,如果已经被标记则检测设置的cookie是否正常返回

--cookie正常返回则判断是浏览器行为,删除记录值,否则认为是非正常流量,返回403

if is_bind == '1' then

    is_token , err = cache:hget(host_name , "token")

    if (ngx.var.cookie_token == is_token)then

        res , err = cache:hdel(host_name , "bind")

        res , err = cache:hdel(host_name , "token")

        res , err = cache:hdel(host_name , "count")

        res , err = cache:hdel(host_name , "time")

        goto A

    else

        res , err = cache:hdel(host_name , "token")

        ngx.exit(403)

    end

    goto A

end

start_time , err = cache:hget(host_name , "time")

ip_count , err = cache:hget(host_name , "count")

--如果ip记录时间大于指定时间间隔或者记录时间或者不存在ip时间key则重置时间key和计数key

--如果ip时间key小于时间间隔,则ip计数+1,且如果ip计数大于ip频率计数,则设置ip的封禁key为1

--同时设置封禁key的过期时间为封禁ip的时间

if start_time == ngx.null or os.time() - start_time > ip_time_out then

    res , err = cache:hset(host_name , "time" , os.time())

    res , err = cache:hset(host_name , "count" , 1)

else

    ip_count = ip_count + 1

    res , err = cache:hincrby(host_name , "count" , 1)

    if ip_count >= connect_count then

        res , err = cache:hset(host_name , "bind" , 1)

        res , err = cache:expire(host_name , ip_bind_time)

        local token = ngx.md5(random)

        res , err = cache:hset(host_name , "token" , token)

        ngx.header["Set-Cookie"] = {"token="..token}

    end

end

--结尾标记

::A::

local ok, err = cache:close()

六:nginx中引用此脚本

location / {

    access_by_lua_file conf/intercept_ip.lua;

}

七:结束语

在实际生产场景应用中我们会考虑更多的因素,所以脚本只是根据一部分需求进行的实现,还有更多的需求需要去完善。

防采集,防cc攻击仅仅只是应对策略,我们无法完全禁止采集行为,但可以通过此类方式大大提高攻击者的成本,进而保证自身的安全与稳定。

例如:

我们设置访问频次为每分钟访问70次属于正常行为

采集者通过测试发现了这个频次,将程序的访问频次设置为每秒钟1次,这样虽然保证了网站的稳定性,但数据依然是被拿走了。

因此,此脚本仍然有完善的空间,利用更合适的算法去细化访问的规则。

欢迎拍砖讨论,转载请注明出处,不胜感激。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容