웹사이트 검색

Ubuntu 22.04에서 Nginx와 함께 ModSecurity 3를 설치하는 방법


이 튜토리얼은 다음 OS 버전에 대해 존재합니다.

  • Ubuntu 22.04(Jammy Jellyfish)
  • Ubuntu 15.04(Vivid Vervet)

이 페이지에서

  1. 전제 조건
  2. 시작하기\n
  3. Ubuntu 22.04에 ModSecurity 설치
  4. ModSecurity 3 지원으로 Nginx 설치
  5. ModSecurity로 Nginx 구성
  6. ModSecurity 핵심 규칙 세트 설치\n
  7. Nginx용 Systemd 서비스 파일 생성
  8. ModSecurity 확인\n
  9. 결론

웹 사이트 및 웹 애플리케이션 보안은 모든 시스템 관리자에게 어려운 작업이 될 수 있습니다. DDoS 공격으로부터 웹 사이트를 보호하는 데 사용할 수 있는 오픈 소스 도구가 많이 있습니다. ModSecurity는 XSS(교차 사이트 스크립팅), SQL 삽입, 세션 하이재킹 등 여러 유형의 공격으로부터 웹 사이트를 보호하는 무료 오픈 소스 WAF(웹 애플리케이션 방화벽)입니다.

이 튜토리얼에서는 Ubuntu 22.04에서 Nginx와 함께 ModSecurity를 설치하는 방법을 보여줍니다.

전제 조건

  • Ubuntu 22.04를 실행하는 서버.\n
  • 루트 암호는 서버에서 구성됩니다.\n

시작하기

먼저 모든 소프트웨어 패키지를 최신 버전으로 업데이트하고 업그레이드하는 것이 좋습니다. 다음 명령을 실행하여 모두 업데이트할 수 있습니다.

apt update -y
apt upgrade -y

모든 패키지가 업데이트되면 다음 명령을 사용하여 다른 필수 패키지를 설치합니다.

apt install g++ flex bison curl apache2-dev doxygen libyajl-dev ssdeep liblua5.2-dev libgeoip-dev libtool dh-autoreconf libcurl4-gnutls-dev libxml2 libpcre++-dev libxml2-dev git liblmdb-dev libpkgconf3 lmdb-doc pkgconf zlib1g-dev libssl-dev -y

완료되면 다음 단계로 진행할 수 있습니다.

Ubuntu 22.04에 ModSecurity 설치

기본적으로 ModSecurity 패키지는 Ubuntu 기본 리포지토리에 포함되어 있지 않습니다. 따라서 소스에서 컴파일해야 합니다.

먼저 다음 명령을 사용하여 최신 버전의 ModSecurity를 다운로드합니다.

wget https://github.com/SpiderLabs/ModSecurity/releases/download/v3.0.8/modsecurity-v3.0.8.tar.gz

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

tar -xvzf modsecurity-v3.0.8.tar.gz

그런 다음 추출된 디렉터리로 이동하고 다음 명령을 사용하여 구성합니다.

cd modsecurity-v3.0.8
./build.sh
./configure

그런 다음 다음 명령으로 설치하십시오.

make
make install

ModSecurity 3 지원으로 Nginx 설치

다음으로 ModSecurity를 지원하는 Nginx를 설치해야 합니다. 먼저 다음 명령을 사용하여 ModSecurity-nginx 커넥터를 다운로드합니다.

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

그런 다음 다음 명령을 사용하여 Nginx 소스를 다운로드합니다.

wget https://nginx.org/download/nginx-1.20.2.tar.gz

다음으로 다음 명령을 사용하여 Nginx 소스를 추출합니다.

tar xzf nginx-1.20.2.tar.gz

다음으로 다음 명령을 사용하여 Nginx용 사용자를 생성합니다.

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

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

cd nginx-1.20.2
./configure --user=nginx --group=nginx --with-pcre-jit --with-debug --with-compat --with-http_ssl_module --with-http_realip_module --add-dynamic-module=/root/ModSecurity-nginx --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

그런 다음 다음 명령으로 설치하십시오.

make
make modules
make install

다음으로 다음 명령을 사용하여 Nginx의 심볼릭 링크를 만듭니다.

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

다음으로 다음 명령을 사용하여 Nginx 버전을 확인합니다.

nginx -V

다음 출력에서 Nginx 버전을 얻을 수 있습니다.

nginx version: nginx/1.20.2
built by gcc 11.2.0 (Ubuntu 11.2.0-19ubuntu1) 
built with OpenSSL 3.0.2 15 Mar 2022
TLS SNI support enabled
configure arguments: --user=nginx --group=nginx --with-pcre-jit --with-debug --with-compat --with-http_ssl_module --with-http_realip_module --add-dynamic-module=/root/ModSecurity-nginx --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log

완료되면 ModSecurity로 Nginx 구성을 진행할 수 있습니다.

ModSecurity로 Nginx 구성

그런 다음 다음 명령을 사용하여 샘플 구성 파일을 복사합니다.

cp ~/modsecurity-v3.0.8/modsecurity.conf-recommended /usr/local/nginx/conf/modsecurity.conf
cp ~/modsecurity-v3.0.8/unicode.mapping /usr/local/nginx/conf/

다음으로 Nginx 구성 파일을 백업합니다.

cp /usr/local/nginx/conf/nginx.conf{,.bak}

다음으로 Nginx 구성 파일을 편집합니다.

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

기본 행을 제거하고 다음 행을 추가하십시오.

load_module modules/ngx_http_modsecurity_module.so;
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  nginx.example.com;
        modsecurity  on;
        modsecurity_rules_file  /usr/local/nginx/conf/modsecurity.conf;
        access_log  /var/log/nginx/access_example.log;
        error_log  /var/log/nginx/error_example.log;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

파일을 저장하고 닫은 후 다음 명령을 사용하여 ModSecurity를 활성화합니다.

sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /usr/local/nginx/conf/modsecurity.conf

완료되면 다음 단계로 진행할 수 있습니다.

ModSecurity 핵심 규칙 세트 설치

OWASP ModSecurity 핵심 규칙 세트는 OWASP Top Ten, 최소 오경보를 포함하여 광범위한 공격을 탐지하고 보호하기 위한 규칙 세트를 제공합니다.

먼저 다음 명령을 사용하여 OWASP 규칙 집합을 다운로드합니다.

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

다음으로 crs-setup.conf.example의 이름을 crs-setup.conf 파일로 바꿉니다.

cp /usr/local/nginx/conf/owasp-crs/crs-setup.conf{.example,}

그런 다음 다음 명령을 사용하여 규칙을 정의합니다.

echo -e "Include owasp-crs/crs-setup.conf
Include owasp-crs/rules/*.conf" >> /usr/local/nginx/conf/modsecurity.conf

그런 다음 다음 명령어를 사용하여 구성 오류가 있는지 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용 Systemd 서비스 파일 생성

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

nano /etc/systemd/system/nginx.service

다음 줄을 추가합니다.

[Unit]
Description=A high performance web server and a reverse proxy server
Documentation=man:nginx(8)
After=network.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -q -g 'daemon on; master_process on;'
ExecStart=/usr/local/nginx/sbin/nginx -g 'daemon on; master_process on;'
ExecReload=/usr/local/nginx/sbin/nginx -g 'daemon on; master_process on;' -s reload
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid
TimeoutStopSec=5
KillMode=mixed

[Install]
WantedBy=multi-user.target

파일을 저장하고 닫은 다음 systemd 데몬을 다시 로드하여 변경 사항을 적용합니다.

systemctl daemon-reload

다음으로 다음 명령을 사용하여 Nginx를 시작하고 활성화합니다.

systemctl start nginx
systemctl enable nginx

다음 명령을 사용하여 Nginx 상태를 확인할 수 있습니다.

systemctl status nginx

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

? nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/etc/systemd/system/nginx.service; disabled; vendor preset: enabled)
     Active: active (running) since Tue 2022-10-11 15:40:39 UTC; 6s ago
       Docs: man:nginx(8)
    Process: 68438 ExecStartPre=/usr/local/nginx/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 68439 ExecStart=/usr/local/nginx/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 68440 (nginx)
      Tasks: 2 (limit: 4579)
     Memory: 20.0M
        CPU: 293ms
     CGroup: /system.slice/nginx.service
             ??68440 "nginx: master process /usr/local/nginx/sbin/nginx -g daemon on; master_process on;"
             ??68441 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" >

Oct 11 15:40:38 ubuntu2204 systemd[1]: Starting A high performance web server and a reverse proxy server...
Oct 11 15:40:39 ubuntu2204 systemd[1]: Started A high performance web server and a reverse proxy server.

완료되면 다음 단계로 진행할 수 있습니다.

ModSecurity 확인

Nginx로 Modsecurity를 설치 및 구성한 후. 테스트할 시간입니다. 다음 명령을 실행하여 명령 주입에 대한 Modsecurity를 테스트합니다.

curl localhost?doc=/bin/ls

모든 것이 괜찮다면 \403 Forbidden\ 마사지를 받을 것입니다.

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

다음 명령을 사용하여 Modesecurity 로그를 확인할 수도 있습니다.

tail /var/log/modsec_audit.log

다음 출력에 ModSecurity 로그가 표시되어야 합니다.

ModSecurity: Warning. Matched "Operator `PmFromFile' with parameter `unix-shell.data' against variable `ARGS:doc' (Value: `/bin/ls' ) [file "/usr/local/nginx/conf/owasp-crs/rules/REQUEST-932-APPLICATION-ATTACK-RCE.conf"] [line "496"] [id "932160"] [rev ""] [msg "Remote Command Execution: Unix Shell Code Found"] [data "Matched Data: bin/ls found within ARGS:doc: /bin/ls"] [severity "2"] [ver "OWASP_CRS/3.2.0"] [maturity "0"] [accuracy "0"] [tag "application-multi"] [tag "language-shell"] [tag "platform-unix"] [tag "attack-rce"] [tag "paranoia-level/1"] [tag "OWASP_CRS"] [tag "OWASP_CRS/WEB_ATTACK/COMMAND_INJECTION"] [tag "WASCTC/WASC-31"] [tag "OWASP_TOP_10/A1"] [tag "PCI/6.5.2"] [hostname "127.0.0.1"] [uri "/"] [unique_id "166550286018.572845"] [ref "o1,6v10,7t:urlDecodeUni,t:cmdLine,t:normalizePath,t:lowercase"]
ModSecurity: Access denied with code 403 (phase 2). Matched "Operator `Ge' with parameter `5' against variable `TX:ANOMALY_SCORE' (Value: `5' ) [file "/usr/local/nginx/conf/owasp-crs/rules/REQUEST-949-BLOCKING-EVALUATION.conf"] [line "80"] [id "949110"] [rev ""] [msg "Inbound Anomaly Score Exceeded (Total Score: 5)"] [data ""] [severity "2"] [ver "OWASP_CRS/3.2.0"] [maturity "0"] [accuracy "0"] [tag "application-multi"] [tag "language-multi"] [tag "platform-multi"] [tag "attack-generic"] [hostname "127.0.0.1"] [uri "/"] [unique_id "166550286018.572845"] [ref ""]

---IcTYGSZl---I--

---IcTYGSZl---J--

---IcTYGSZl---Z--

결론

축하합니다! Ubuntu 22.04에서 Nginx와 함께 ModSecurity를 성공적으로 설치했습니다. 이제 프로덕션 환경에서 ModSecurity를 구현하여 DDoS 공격을 방어할 수 있습니다. 궁금한 점이 있으면 언제든지 문의해 주세요.