使用Lua保护Nginx远离CC攻击

NGINXLINUX2014-12-11 15:31

简单,以下方法不需要额外安装模块:

location ~ \.php$ {
    if ($cookie_ipaddr != "$remote_addr"){
        add_header Set-Cookie "ipaddr=$remote_addr";
        rewrite .* "$scheme://$host$uri" redirect;
        #rewrite .* "$scheme://localhost:$remote_port" redirect;
    }

    ... ...
}

进阶,返回JS跳转代码过滤模拟访问:

location ~ \.php$ {
    default_type text/html;
    if ($cookie_ipaddr != "$remote_addr"){
        add_header Set-Cookie "ipaddr=$remote_addr";
        return 200 "<script>location.reload()</script>\n";
    }

    ... ...
}

PERL,返回JS设置COOKIE并自动刷新:

http {
    perl_set $humanflag 'sub{use Digest::MD5 qw(md5_base64); md5_base64("Salt|",shift->variable("remote_addr"))}';
    ... ...
    server {
        ... ...
        location ~ \.php$ {
            default_type text/html;
            if ($cookie_humanflag != $humanflag){ #访问非text/html会异常,换用add_header设置Cookie避免js无法执行
                return 200 '<script>\ndocument.cookie="humanflag=$humanflag";\nlocation.reload();\n</script>\n';
            }
            ... ...
        }
    }
}

LUA,大同小异,需要安装扩展模块:apt-get install nginx-extras

location ~ \.php$ {
    rewrite_by_lua '
        local md5token = ngx.md5(ngx.var.remote_addr .. ngx.var.http_user_agent)
        if (ngx.var.cookie_humanflag ~= md5token) then
            ngx.header["Set-Cookie"] = "humanflag=" .. md5token
            return ngx.redirect(ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.uri)
        end
    ';

    ... ...
}

参考:
https://jiji262.github.io/wooyun_articles/drops/通过nginx配置文件抵御攻击.html


原文链接: http://blog.jtwo.me/use-lua-to-protect-nginx-away-from-cc-attack