Nginx와 Lua를 활용한 맞춤형 WAF 구현

Nginx와 Lua를 활용한 맞춤형 WAF 구현

기능 목록

  • IP 화이트리스트와 블랙리스트 기능 지원, 블랙리스트에 등록된 IP 접근 차단
  • URL 화이트리스트 지원, 필터링이 필요 없는 URL 정의
  • User-Agent 필터링, 사용자 정의 규칙과 일치하는 항목 처리 후 403 반환
  • CC 공격 방어, 특정 URL에 대한 시간당 접근 횟수 제한 초과 시 403 반환
  • 쿠키 필터링, 사용자 정의 규칙과 일치하는 항목 처리 후 403 반환
  • URL 필터링, 사용자 정의 규칙과 일치하는 항목이 포함된 경우 403 반환
  • URL 파라미터 필터링, 원리는 위와 동일
  • 로그 기록, 모든 거부 작업을 로그에 기록
  • JSON 형식의 로그 기록, ELKStack을 통한 공격 로그 수집, 저장, 검색 및 표시 용이

Nginx + Lua 배치

의존 패키지 설치:

# yum install -y readline-devel pcre-devel openssl-devel
# cd /usr/local/src
OpenResty 다운로드 및 컴파일 설치
# wget https://openresty.org/download/ngx_openresty-1.9.3.2.tar.gz
# tar zxf ngx_openresty-1.9.3.2.tar.gz
# cd 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
# gmake && gmake install
# ln -s /usr/local/openresty-1.9.3.2/ /usr/local/openresty

OpenResty 설치 확인:

vim /usr/local/openresty/nginx/conf/nginx.conf
server {
    location /hello {
        default_type text/html;
        content_by_lua_block {
            ngx.say("안녕하세요")
        }
    }
}
# /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: the configuration file /usr/local/openresty-1.9.3.2/nginx/conf/nginx.conf test is successful
# /usr/local/openresty/nginx/sbin/nginx

테스트:

curl http://192.168.199.33/hello

WAF 배치:

git clone https://github.com/unixhot/waf.git
cp -a ./waf/waf /usr/local/openresty/nginx/conf/

Nginx 설정 파일에 다음 구성을 추가하세요. 경로에 주의하십시오. WAF 로그는 기본적으로 /tmp/날짜_waf.log에 저장됩니다.

    lua_shared_dict limit 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";

Nginx 재로드:

/usr/local/openresty/nginx/sbin/nginx -t
/usr/local/openresty/nginx/sbin/nginx -s reload

테스트:

sql 확장자로 끝나는 파일에 접속

또는 특정 페이지로 직접 리디렉션:

config.lua 수정:

config_waf_output = "redirect"    # 기본값은 html
config_waf_redirect_url = "http://www.example.com/error/"   # 사용자 정의 URL

구문 테스트 및 Nginx 재로드:

[root@localhost waf]# /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: the configuration file /usr/local/openresty-1.9.3.2/nginx/conf/nginx.conf test is successful
[root@localhost waf]# /usr/local/openresty/nginx/sbin/nginx -s reload

리디렉션이 작동하는지 다시 접속하여 확인

규칙은 url.rule 파일 참조

CC 공격 방어:

ab 명령어를 예로 들면:

1분 내에 다시 접속:

처음 비2xx 요청은 89개(성공 11개)

두 번째 비2xx 요청은 100개(성공 0개)

whiteip.rule IP 화이트리스트(IP를 직접 작성하면 재시작 불필요)

blackip.rule IP 블랙리스트(IP를 직접 작성하면 재시작 불필요)

태그: nginx Lua WAF OpenResty 웹보안

6월 12일 16:11에 게시됨