웹사이트 검색

Docker 컨테이너에 Apache와 함께 ModSecurity 설치


이 페이지에서

  1. 요구 사항\n
  2. 시작하기\n
  3. 도커 설치
  4. ModSecurity용 Dockerfile 만들기
  5. Apache ModSecurity 이미지 빌드 및 컨테이너 시작
  6. ModSecurity 확인\n
  7. 결론

ModSecurity는 광범위한 레이어 7 공격으로부터 웹 애플리케이션을 보호하는 가장 널리 사용되는 무료 오픈 소스 WAF(웹 애플리케이션 방화벽)입니다. Apache 웹 서버 모니터링, 로깅 및 필터링 요청을 위해 설계되었습니다. SQL 인젝션, 교차 사이트 스크립팅, 트로이 목마, 악성 사용자 에이전트, 세션 하이재킹 등 여러 공격을 감지하고 중지하는 핵심 규칙 세트가 함께 제공됩니다.

이 튜토리얼에서는 Docker 컨테이너 내부에 Apache와 함께 ModSecurity 3를 설치하는 방법을 보여줍니다.

요구 사항

  • Ubuntu 20.04를 실행하는 서버.\n
  • 서버에 루트 암호가 구성되어 있습니다.\n

시작하기

먼저 시스템을 최신 버전으로 업데이트하는 것이 좋습니다. 다음 명령으로 업데이트할 수 있습니다.

apt-get update -y

시스템이 최신 상태이면 시스템에 일부 종속 항목을 설치해야 합니다. 다음 명령으로 모두 설치할 수 있습니다.

apt-get install apt-transport-https ca-certificates curl gnupg2 software-properties-common -y

모든 종속성이 설치되면 다음 단계로 진행할 수 있습니다.

도커 설치

다음으로 시스템에 Docker CE를 설치해야 합니다. 기본적으로 Docker의 최신 버전은 Ubuntu 기본 리포지토리에 포함되어 있지 않습니다. 따라서 Docker 공식 리포지토리를 APT에 추가해야 합니다.

먼저 다음 명령을 사용하여 Docker GPG 키를 다운로드하고 추가합니다.

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -

다음으로 다음 명령을 사용하여 APT 소스 목록에 Docker CE 리포지토리를 추가합니다.

echo "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -sc) stable" > /etc/apt/sources.list.d/docker-ce.list

리포지토리가 추가되면 다음 명령을 사용하여 리포지토리를 업데이트합니다.

apt-get update -y

리포지토리가 업데이트되면 다음 명령을 사용하여 최신 버전의 Docker CE를 설치합니다.

apt-get install docker-ce -y

Docker CE를 설치한 후 다음 명령을 사용하여 설치된 Docker CE 버전을 확인하십시오.

docker --version

다음과 같은 결과가 표시되어야 합니다.

Docker version 20.10.6, build 370c289

다음 명령을 사용하여 Docker 서비스의 상태를 확인할 수도 있습니다.

systemctl status docker

다음과 같은 결과가 표시되어야 합니다.

? docker.service - Docker Application Container Engine
     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2021-05-16 06:49:29 UTC; 38s ago
TriggeredBy: ? docker.socket
       Docs: https://docs.docker.com
   Main PID: 8964 (dockerd)
      Tasks: 8
     Memory: 40.6M
     CGroup: /system.slice/docker.service
             ??8964 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.365433228Z" level=warning msg="Your kernel does not support swap memory li>
May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.365916961Z" level=warning msg="Your kernel does not support cgroup blkio w>
May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.366112111Z" level=warning msg="Your kernel does not support cgroup blkio w>
May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.366653374Z" level=info msg="Loading containers: start."
May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.498790388Z" level=info msg="Default bridge (docker0) is assigned with an I>
May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.576691602Z" level=info msg="Loading containers: done."
May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.610542206Z" level=info msg="Docker daemon" commit=8728dd2 graphdriver(s)=o>
May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.611668583Z" level=info msg="Daemon has completed initialization"
May 16 06:49:29 ubunt4 systemd[1]: Started Docker Application Container Engine.
May 16 06:49:29 ubunt4 dockerd[8964]: time="2021-05-16T06:49:29.690496888Z" level=info msg="API listen on /run/docker.sock"
lines 1-21/21 (END)

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

ModSecurity용 Dockerfile 만들기

다음으로 Ubuntu 컨테이너 내부에 ModSecurity를 설치하려면 Dockerfile을 만들어야 합니다.

먼저 디렉터리를 /opt로 변경하고 다음 명령을 사용하여 modsec_rules.conf 파일을 만듭니다.

cd /opt
nano modsec_rules.conf

다음 줄을 추가합니다.

Include "/etc/apache2/modsecurity.d/modsecurity.conf"
Include "/etc/apache2/modsecurity.d/owasp-crs/crs-setup.conf"
Include "/etc/apache2/modsecurity.d/owasp-crs/rules/*.conf"

파일을 저장하고 닫은 후 다음 명령을 사용하여 다른 파일을 만듭니다.

nano 000-default.conf

다음 줄을 추가합니다.

<VirtualHost *:80>
	modsecurity on
	modsecurity_rules_file /etc/apache2/modsecurity.d/modsec_rules.conf 
	ServerAdmin 
	DocumentRoot /var/www/html
	ErrorLog ${APACHE_LOG_DIR}/error.log
	CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

완료되면 파일을 저장하고 닫습니다. Dockerfile은 빌드 프로세스 중에 위의 파일을 Docker 컨테이너에 복사합니다.

마지막으로 다음 명령을 사용하여 Dockerfile을 만듭니다.

nano Dockerfile

다음 줄을 추가합니다.

# Install Modsecurity in a Docker container;
FROM ubuntu:latest
ARG DEBIAN_FRONTEND=noninteractive
# update/upgrade your system
RUN apt-get update -y

# Install Required Dependencies
RUN apt-get install -y 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 wget tar apache2

# Download LibModsecurity 
RUN wget https://github.com/SpiderLabs/ModSecurity/releases/download/v3.0.4/modsecurity-v3.0.4.tar.gz

# Extract the Downloaded File
RUN tar xzf modsecurity-v3.0.4.tar.gz && rm -rf modsecurity-v3.0.4.tar.gz

# Compile and Install LibModsecurity
RUN cd modsecurity-v3.0.4 && \
	./build.sh && ./configure && \
	make && make install

# Install ModSecurity-Apache Connector
RUN cd ~ && git clone https://github.com/SpiderLabs/ModSecurity-apache

RUN cd ~/ModSecurity-apache && \
	./autogen.sh && \
	./configure --with-libmodsecurity=/usr/local/modsecurity/ && \
	make && \
	make install

# Load the Apache ModSecurity Connector Module
RUN echo "LoadModule security3_module /usr/lib/apache2/modules/mod_security3.so" >> /etc/apache2/apache2.conf

# Configure ModSecurity
RUN mkdir /etc/apache2/modsecurity.d && \
	cp modsecurity-v3.0.4/modsecurity.conf-recommended /etc/apache2/modsecurity.d/modsecurity.conf && \
	cp modsecurity-v3.0.4/unicode.mapping /etc/apache2/modsecurity.d/ && \
	sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/apache2/modsecurity.d/modsecurity.conf
ADD modsec_rules.conf /etc/apache2/modsecurity.d/

# Install OWASP ModSecurity Core Rule Set (CRS) on Ubuntu
RUN git clone https://github.com/SpiderLabs/owasp-modsecurity-crs.git /etc/apache2/modsecurity.d/owasp-crs && \
	cp /etc/apache2/modsecurity.d/owasp-crs/crs-setup.conf.example /etc/apache2/modsecurity.d/owasp-crs/crs-setup.conf

# Activate ModSecurity
RUN mv /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/000-default.conf.old
ADD 000-default.conf /etc/apache2/sites-available/

EXPOSE 80
CMD apachectl -D FOREGROUND

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

위의 파일은 Ubuntu 이미지를 다운로드하고, 모든 종속성을 설치하고, ModSecurity를 다운로드하고, 컴파일하고, ModSecurity와 작동하도록 Apache를 구성합니다.

이 시점에서 Dockerfile이 준비되었습니다. 이제 다음 단계를 진행할 수 있습니다.

Apache ModSecurity 이미지 빌드 및 컨테이너 시작

이제 디렉터리를 /opt로 변경하고 다음 명령을 사용하여 Apache ModSecurity용 Docker 이미지를 빌드합니다.

cd /opt
docker build .

빌드 프로세스가 완료되면 다음과 같은 결과가 표시됩니다.

Step 13/17 : RUN git clone https://github.com/SpiderLabs/owasp-modsecurity-crs.git /etc/apache2/modsecurity.d/owasp-crs && 	cp /etc/apache2/modsecurity.d/owasp-crs/crs-setup.conf.example /etc/apache2/modsecurity.d/owasp-crs/crs-setup.conf
 ---> Running in 00dfa2a5cd23
Cloning into '/etc/apache2/modsecurity.d/owasp-crs'...
Removing intermediate container 00dfa2a5cd23
 ---> b38c1d874d2f
Step 14/17 : RUN mv /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/000-default.conf.old
 ---> Running in 12c9e6d2c559
Removing intermediate container 12c9e6d2c559
 ---> 899e26019297
Step 15/17 : ADD 000-default.conf /etc/apache2/sites-available/
 ---> eb11751afd6c
Step 16/17 : EXPOSE 80
 ---> Running in 2f4ba47e2b66
Removing intermediate container 2f4ba47e2b66
 ---> dd59b0ac7c7c
Step 17/17 : CMD apachectl -D FOREGROUND
 ---> Running in 98b8cc77df0f
Removing intermediate container 98b8cc77df0f
 ---> f603dbc38018
Successfully built f603dbc38018

이제 다음 명령을 사용하여 모든 도커 이미지를 나열할 수 있습니다.

docker images

다음과 같은 결과가 표시되어야 합니다.

REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
           f603dbc38018   32 seconds ago   2.48GB
ubuntu       latest    7e0aa2d69a15   3 weeks ago      72.7MB

이제 위 출력에서 첫 번째 이미지 ID를 선택하고 다음 명령을 사용하여 Apache ModSecurity 컨테이너를 시작합니다.

docker run --name modsec-apache -ditp 80:80 f603dbc38018

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

40eb0e77e61635c3cee2bfaffbd9489bc7d20aa3e1befb52749de079aaadb528

이제 다음 명령을 사용하여 실행 중인 컨테이너를 확인할 수 있습니다.

docker ps

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

CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                               NAMES
40eb0e77e616   f603dbc38018   "/bin/sh -c 'apachec…"   17 seconds ago   Up 15 seconds   0.0.0.0:80->80/tcp, :::80->80/tcp   modsec-apache

보시다시피 ModSecurity 컨테이너가 시작되고 포트 80에서 수신 대기합니다.

ModSecurity 확인

이 시점에서 ModSecurity 컨테이너가 실행 중입니다. 이제 ModSecurity 규칙이 악의적인 요청을 차단하는지 여부를 테스트할 시간입니다.

이렇게 하려면 터미널을 열고 다음 명령을 실행합니다.

curl localhost?doc=/bin/ls

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

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access this resource.</p>
<hr>
<address>Apache/2.4.41 (Ubuntu) Server at localhost Port 80</address>
</body></html>

"403 Forbidden" 오류가 표시되어야 합니다. ModSecurity가 위의 요청을 차단했기 때문입니다.

자세한 내용은 Apache 로그를 확인할 수도 있습니다.

이렇게 하려면 먼저 다음 명령을 사용하여 컨테이너에 연결합니다.

docker exec -it modsec-apache /bin/bash

연결되면 다음 셸을 가져와야 합니다.

:/#

이제 다음 명령을 사용하여 Apache 로그를 확인합니다.

tail -f /var/log/apache2/error.log

ModSecurity가 악의적인 요청을 차단했는지 확인해야 합니다.

[Sun May 16 07:24:54.456327 2021] [mpm_event:notice] [pid 15:tid 140204464299072] AH00489: Apache/2.4.41 (Ubuntu) configured -- resuming normal operations
[Sun May 16 07:24:54.456352 2021] [core:notice] [pid 15:tid 140204464299072] AH00094: Command line: '/usr/sbin/apache2 -D FOREGROUND'
[Sun May 16 07:25:36.680515 2021] [:error] [pid 16:tid 140204216108800] [client 172.17.0.1:45298] ModSecurity: Warning. Matched "Operator `PmFromFile' with parameter `unix-shell.data' against variable `ARGS:doc' (Value: `/bin/ls' ) [file "/etc/apache2/modsecurity.d/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 "172.17.0.2"] [uri "/"] [unique_id "162114993662.860969"] [ref "o1,6v10,7t:urlDecodeUni,t:cmdLine,t:normalizePath,t:lowercase"]

결론

축하합니다! Docker 컨테이너 내부에 ModSecurity를 성공적으로 설치했습니다. 이제 Docker 환경에서 이 솔루션을 구현할 수 있는 충분한 지식을 갖추셨기를 바랍니다. 궁금한 점이 있으면 언제든지 문의해 주세요.