웹사이트 검색

CentOS 8에서 Nginx로 LibModsecurity 웹 애플리케이션 방화벽 설치


이 페이지에서

  1. 요구 사항\n
  2. 시작하기\n
  3. 필수 저장소 및 종속성 설치\n
  4. LibModsecurity 다운로드 및 컴파일
  5. LibModsecurity 지원으로 Nginx 다운로드 및 컴파일
  6. ModSecurity로 Nginx 구성
  7. Nginx용 Systemd 서비스 파일 생성
  8. 모드 보안 구성
  9. ModSecurity 테스트
  10. 결론

LibModSecurity는 다양한 종류의 사이버 공격으로부터 Nginx 서버를 보호하는 데 사용할 수 있는 무료 오픈 소스 웹 애플리케이션 방화벽입니다. SQL 인젝션, 교차 사이트 스크립팅, 트로이 목마 등을 포함한 핵심 규칙 세트가 함께 제공됩니다. 실시간으로 HTTP 트래픽을 모니터링하고 OWASP ModSecurity Core Rule Set을 사용하여 취약점에 대항하여 작동합니다. Apache, Nginx 및 IIS와 함께 사용할 수 있으며 Debian, Ubuntu 및 CentOS와도 호환됩니다.

이 튜토리얼에서는 CentOS 8에서 Nginx 지원으로 LibModSecurity를 다운로드하고 컴파일하는 방법을 보여줍니다.

요구 사항

  • CentOS 8을 실행하는 서버.\n
  • 루트 암호는 서버에서 구성됩니다.\n

시작하기

시작하기 전에 다음 명령을 사용하여 서버를 최신 버전으로 업데이트하십시오.

dnf update

서버가 최신 상태이면 다시 시작하여 변경 사항을 적용하십시오.

필수 리포지토리 및 종속성 설치

먼저 시스템에 EPEL 및 REMI 리포지토리를 설치합니다. 다음 명령으로 설치할 수 있습니다.

dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
dnf install https://rpms.remirepo.net/enterprise/remi-release-8.rpm

다음으로 다음 명령을 사용하여 필요한 모든 종속 항목을 설치합니다.

dnf install gcc-c++ flex bison yajl curl-devel zlib-devel pcre-devel autoconf automake git curl make libxml2-devel pkgconfig libtool httpd-devel redhat-rpm-config wget openssl openssl-devel nano

모든 패키지가 설치되면 PowerTool 리포지토리를 사용하여 다른 종속성을 설치할 수 있습니다.

dnf --enablerepo=PowerTools install doxygen yajl-devel

다음으로 다음 명령을 실행하여 REMI 리포지토리를 사용하여 GeoIP를 설치합니다.

dnf --enablerepo=remi install GeoIP-devel

모든 패키지가 설치되면 다음 단계로 진행할 수 있습니다.

LibModsecurity 다운로드 및 컴파일

먼저 LibModsecurity 소스를 다운로드하고 시스템에서 컴파일해야 합니다. 이렇게 하려면 디렉터리를 /opt로 변경하고 Git 리포지토리에서 최신 버전의 LibModsecurity를 다운로드합니다.

cd /opt/
git clone --depth 1 -b v3/master --single-branch https://github.com/SpiderLabs/ModSecurity

다음으로 디렉터리를 ModSecurity로 변경하고 다음 명령을 사용하여 libInjection 코드를 다운로드합니다.

cd ModSecurity
git submodule init
git submodule update

다음으로 다음 명령을 사용하여 LibModsecurity를 구성합니다.

./build.sh
./configure

마지막으로 다음 명령을 사용하여 LibModSecurity를 컴파일하고 설치합니다.

make
make install

이 시점에서 LibModsecurity가 시스템에 설치되었습니다. 이제 LibModsecurity 지원으로 Nginx 설치를 진행할 수 있습니다.

LibModsecurity 지원으로 Nginx 다운로드 및 컴파일

먼저 Nginx에 대한 시스템 사용자 및 그룹을 생성해야 합니다. 다음 명령으로 만들 수 있습니다.

useradd -r -M -s /sbin/nologin -d /usr/local/nginx nginx

다음으로 Nginx를 다운로드하고 LibModsecurity 지원으로 컴파일해야 합니다.

이렇게 하려면 먼저 다음 명령을 사용하여 Git 리포지토리에서 ModSecurity-nginx 커넥터를 다운로드합니다.

cd /opt
git clone https://github.com/SpiderLabs/ModSecurity-nginx.git

다음으로 다음 명령을 사용하여 최신 안정 버전의 Nginx를 다운로드합니다.

wget http://nginx.org/download/nginx-1.17.6.tar.gz

다운로드가 완료되면 다음 명령을 사용하여 다운로드한 파일의 압축을 풉니다.

tar -xvzf nginx-1.17.6.tar.gz

다음으로 Nginx 디렉터리를 변경하고 다음 명령으로 구성합니다.

cd nginx-1.17.6
./configure --user=nginx --group=nginx --with-pcre-jit --with-debug --with-http_ssl_module --with-http_realip_module --add-module=/opt/ModSecurity-nginx

그런 다음 다음 명령을 사용하여 Nginx를 설치합니다.

make
make install

이 시점에서 Nginx는 LibModsecurity 지원과 함께 설치되었습니다. 이제 Nginx 구성을 진행할 수 있습니다.

ModSecurity로 Nginx 구성

먼저 샘플 ModSecurity 구성 파일을 Nginx 소스 디렉터리에서 Nginx 구성 디렉터리로 복사해야 합니다.

다음 명령으로 복사할 수 있습니다.

cp /opt/ModSecurity/modsecurity.conf-recommended /usr/local/nginx/conf/modsecurity.conf
cp /opt/ModSecurity/unicode.mapping /usr/local/nginx/conf/

다음으로 다음 명령을 사용하여 /usr/sbin/ 경로에 대한 Nginx 바이너리의 심볼릭 링크를 만듭니다.

ln -s /usr/local/nginx/sbin/nginx /usr/sbin/

다음으로 다음 명령을 사용하여 Nginx 로그 디렉터리를 만듭니다.

mkdir /var/log/nginx

그런 다음 다음 명령을 사용하여 Nginx 구성 파일을 엽니다.

nano /usr/local/nginx/conf/nginx.conf

다음과 같이 변경합니다.

user  nginx;
worker_processes  1;
pid  /run/nginx.pid;
events {
    worker_connections  1024;
}


http {
    include	  mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
	listen       80;
        server_name  your-server-ip;
        modsecurity  on;
        modsecurity_rules_file  /usr/local/nginx/conf/modsecurity.conf;
        access_log  /var/log/nginx/access.log;
        error_log  /var/log/nginx/error.log;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

완료되면 파일을 저장하고 닫습니다. 그런 다음 다음 명령을 사용하여 Nginx에서 구문 오류를 확인합니다.

nginx -t

다음 출력이 표시되어야 합니다.

nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

이 시점에서 Nginx가 구성되었습니다. Nginx용 systemd 서비스 파일 생성을 진행할 수 있습니다.

Nginx용 Systemd 서비스 파일 생성

다음으로 Nginx 서비스를 관리하기 위해 systemd 파일을 생성해야 합니다. 다음 명령으로 만들 수 있습니다.

nano /etc/systemd/system/nginx.service

다음 줄을 추가합니다.

[Unit]
Description=The nginx server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
PrivateTmp=true

[Install]
WantedBy=multi-user.target

완료되면 파일을 저장하고 닫습니다. 그런 다음 다음 명령을 사용하여 systemd 데몬을 다시 로드합니다.

systemctl daemon-reload

그런 다음 Nginx 서비스를 시작하고 다음 명령을 사용하여 시스템 재부팅 후 시작되도록 활성화합니다.

systemctl start nginx
systemctl enable --now nginx

다음 출력이 표시되어야 합니다.

Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /etc/systemd/system/nginx.service.

다음으로 다음 명령을 사용하여 Nginx 서비스를 확인합니다.

systemctl status nginx

다음 출력이 표시되어야 합니다.

? nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/etc/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2019-12-30 10:20:01 EST; 41s ago
  Process: 17730 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
  Process: 17728 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
  Process: 17727 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
 Main PID: 17732 (nginx)
    Tasks: 2 (limit: 6102)
   Memory: 5.0M
   CGroup: /system.slice/nginx.service
           ??17732 nginx: master process /usr/sbin/nginx
           ??17733 nginx: worker process

Dec 30 10:20:00 nginx systemd[1]: Starting The nginx HTTP and reverse proxy server...
Dec 30 10:20:00 nginx nginx[17728]: nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
Dec 30 10:20:00 nginx nginx[17728]: nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
Dec 30 10:20:01 nginx systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument
Dec 30 10:20:01 nginx systemd[1]: Started The nginx HTTP and reverse proxy server.

이 시점에서 Nginx가 시작되어 실행 중입니다. 이제 ModSecurity 구성을 진행할 수 있습니다.

모드 보안 구성

기본적으로 ModSecurity는 탐지 전용 모드로 설정됩니다. 따라서 ModSecurity 규칙 엔진을 켜야 합니다. modsecurity.conf 파일을 편집하여 이를 수행할 수 있습니다.

nano /usr/local/nginx/conf/modsecurity.conf

다음 줄을 찾으십시오.

SecRuleEngine DetectionOnly

그리고 다음 줄로 바꿉니다.

SecRuleEngine On

또한 다음 행을 찾으십시오.

/var/log/modsec_audit.log

그리고 다음 줄로 바꿉니다.

/var/log/nginx/modsec_audit.log

완료되면 파일을 저장하고 닫습니다.

다음으로 다음 명령을 사용하여 Git 리포지토리에서 ModSecurity Core Rule Set의 최신 버전을 다운로드합니다.

git clone https://github.com/SpiderLabs/owasp-modsecurity-crs.git /usr/local/nginx/conf/owasp-crs

다운로드한 후 다음 명령을 사용하여 CRS 예제 구성 파일의 이름을 바꿉니다.

mv /usr/local/nginx/conf/owasp-crs/crs-setup.conf.example /usr/local/nginx/conf/owasp-crs/crs-setup.conf

다음으로 /usr/local/nginx/conf/modsecurity.conf 파일을 편집하여 이러한 규칙을 사용하도록 ModeSecurity를 구성합니다.

nano /usr/local/nginx/conf/modsecurity.conf

파일 끝에 다음 줄을 추가합니다.

Include owasp-crs/crs-setup.conf
Include owasp-crs/rules/*.conf

완료되면 파일을 저장하고 닫습니다. 그런 다음 Nginx 서비스를 다시 시작하여 변경 사항을 구현합니다.

systemctl restart nginx

ModSecurity 테스트

이제 ModSecurity가 설치 및 구성되었습니다. 작동 여부를 테스트할 시간입니다.

명령 주입에 대해 ModSecurity를 테스트하려면 웹 브라우저를 열고 URL http://localhost/index.html?exec=/bin/bash를 입력하십시오. 다음 페이지에 403 Forbidden 오류가 표시되어야 합니다.

CSS 공격에 대해 ModSecurity를 테스트하려면 터미널을 열고 다음 명령을 실행하십시오.

curl http://localhost/?q="><script>alert(1)</script>"

다음 출력이 표시되어야 합니다.

<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.17.6</center>
</body>
</html>

결론

축하합니다! Nginx로 LibModSecurity를 성공적으로 다운로드하고 컴파일했습니다. 이제 다양한 공격으로부터 서버가 보호됩니다. 자세한 내용은 ModSecurity Doc에서 ModSecurity 설명서를 참조하십시오.