본문 바로가기

엔지니어/Linux

Centos6 + Apache 2.2 + Mod Security 2.8 setting

728x90
반응형

    Centos6 + Apache 2.2 + Mod Security 2.8 setting


 패키지 설치

yum -y install pcre-devel.x86_64

yum -y install apr-util-devel

 
modsecurity 설치

tar zxvf modsecurity-2.8.0.tar.gz

cd modsecurity-2.8.0

./configure  --with-apxs=/usr/local/apache/bin/apxs
   make && make install


   INSTALL text 파일안 설명대로 설치
   krcert.or.kr 에서 제공하는 룰셋은 오래전 룰셋이라 OWASP에서 제공하는 룰셋으로 셋팅한다.

 unzip SpiderLabs-owasp-modsecurity-crs-2.2.9-5-gebe8790.zip

mv SpiderLabs-owasp-modsecurity-crs-ebe8790  /usr/local/apache2.2/conf/crs

 

cd  /usr/local/apache2.2/conf/crs

cp  modsecurity_crs_10_setup.conf.example  modsecurity_crs_10_setup.conf

 

ln -s /usr/local/apache2.2/conf/crs/modsecurity_crs_10_setup.conf  activated_rules/modsecurity_crs_10_setup.conf




##아래 명령어는 한줄로 입력

for f in `ls base_rules/` ; do  ln -s /usr/local/apache2.2/conf/crs/base_rules/$f activated_rules/$f ; done

for f in `ls optional_rules/ | grep comment_spam` ; do  ln -s /usr/local/apache2.2/conf/crs/optional_rules/$f activated_rules/$f ; done

 

 

 

httpd.conf 에 아래 내용 추가

<IfModule security2_module>

#                Include conf/crs/modsecurity_crs_10_setup.conf

                Include conf/crs/activated_rules/*.conf

</IfModule>

 

 

modsecurity_crs_10_setup.conf  에서 아래 내역을 변경한다, 아래 처럼 auditlog 를 추가
(아래 기본 환경설정 및 지시자 의 2번 을 참조)


원본
SecDefaultAction "phase:1,deny,log"
SecDefaultAction "phase:2,deny,log"


수정내역
SecDefaultAction "phase:1,deny,log,auditlog"
SecDefaultAction "phase:2,deny,log,auditlog"

 


아래 4개 옵션을 넣어준다.

SecRuleEngine On
SecAuditEngine On
SecAuditLog /usr/local/apache2.2/logs/modsec_audit.log
SecAuditLogParts ABCFHZ
SecDataDir /tmp

 

아파치 기동 후 정상적으로 로그가 쌓이는지 차단되는지를 확인 한다.

 

 

[추가 정보 ] 기본 환경설정 및 지시자(mod_security.conf)

1) SecRuleEngine On | Off | DetectionOnly

ModSecurity 기능을 활성화(enable) 시킨다.

o On : ModSecurity 기능 활성화

o Off : ModSecurity 기능 비활성화

o DetectionOnly : 활성화는 하지만 차단하지 않고 탐지만 한다.

 

2) SecAuditEngine On | Off | RelevantOnly

감사 로깅에 대한 설정을 구성한다.

o On : 모든 트랜젝션 로깅

o Off : 모든 트랜젝션 로깅하지 않음

o RelevantOnly : Error 또는, Warning 의 트랜젝션, 그리고 SecAuditLogRelevantStatus에 정의

된 상태코드와 일치하는 트랜젝션만 로깅

 

3) SecAuditLog logs/modsec_audit.log

감사 로그 파일의 경로를 정의한다.

) SecAuditLog /usr/local/apache2/logs/modsec_audit.log

 

4) SecAuditLogParts

로그 파일에 기록할 항목을 정의한다.   예) SecAuditLogParts ABCFHZ


         A audit log header (필수)
    
       B request header
    
       C request body (request body가 존재하고 modsecurity request body를 검사하도록 설정되어 있는 경우에만)
           
       D보류중, response header의 중개 (현재 지원 안 됨)

  E response body 중간 단계(현재 modsecurity response body를 검사하며 감사로깅 엔진이
               이를 저장하게끔 설정되어 있는 경우에만)

         F최종 response header
           (마지막 컨텐츠 전달 과정에서 아파치에 의해 매번 추가 되는 날짜와 서버 헤더를 제외한)

       G 실제 response body(현재 지원 안됨)

         H감사 로그 트레일러

       I  이 옵션은 C를 대체하는 옵션이다. multipart/form-data 인코딩이 사용되었을때를 제외한
             모든 경우엔 C와 같은 데이터를 기록한다.

        J보류중, multipart/form-data 인코딩을 사용하는 파일 업로드에 대한 정보를 포함할 때 효과가 있다.
     
        Z로그의 끝을 의미한다. (필수)

 


5) SecAuditLogRelevantStatus REGEX]

감사로깅의 목적과 관련된 response 상태코드의 값을 설정한다.

o 매개변수에는 정규표현식이 들어간다.

) SecAuditLogRelevantStatus ^[45]

 

 

6) SecAuditLogType Serial | Concurrent
         감사로깅 구조의 타입을 설정한다.
         o Serial - 모든 로그는 메인 로그파일에 저장된다. 일시적으로 편리할 순 있지만
              하나의 파일에만 기록되기 때문에 느려질 수 있다.
         o Concurrent - 로그가 각 트랜잭션 별로 나누어 저장된다.
             이 방식은 로그파일을 원격 ModSecurity Console host로 보낼 때 사용하는 방식이다.

 

7) SecDefaultAction "log, auditlog, deny, status:403, phase:2, t:lowercase"

룰이 매칭되면 기본적으로 취할 행동을 정의한다 룰이 특정 액션들에 대한 개별 룰을

적용하거나 다른 SecDefaultAction이 정의되어있지 않다면 최초 지정된 SecDefaultAction의 설정을 따른다.
위의 예는 룰이 매칭 되었을 때 차단하며 로그를 남기고, 403 상태코드 페이페이지를 보여주며 필터링 단계는 “2”이다.
기본적으로 대문자는 모두 소문자로 바뀌어 필터링 된다.

 

 8) SecRequestBodyAccess On | Off

Request 값에서 Body 부분에 대한 처리를 어떻게 할 것인지 구성한다.

o On : RequestBody 접근을 시도한다.

o Off : RequestBody 접근시도를 하지 않는다.

이 지시자는 Request 값에서의 POST_PAYLOAD를 검사할 때 필요하다. POST값을 필터링하기 위해서는 
phase:2REQUESET_BODY 변수/로케이션, 3가지가 모두 구성되어야만 처리가 가능

 

 

9) SecReponseBodyAccess On | Off

Response 값에서 Body 부분에 대한 처리를 어떻게 할 것인지 구성한다.

o On : ResponseBody 접근을 시도한다. (그러나 MIME 타입과 일치해야만 한다.)

o Off : ResponseBody 접근시도를 하지 않는다.

이 지시자는 html 응답을 조사하기 위해 필요하다. "phase:4"의 처리 단계와 RESPONSE_BODY 변수/로케이션,
3가지가 설정되어 있지 않으면, response body를 검사할 수 없다.

 

 10) SecResponseBodyLimit

ModSecurityResponse Body 크기로 할당할 수 있는 메모리 최대 크기를 설정한다.

o SecRequestBodyLimit 524228

이 값을 넘어가면 서버는 500 내부 서버 오류 메시지만 표시할 것이다.

 

11) SecReponseBodyMimeType mime/type

Response 값에서 Body 값을 버퍼링할 MIME 타입을 설정한다.

o SecResponseBodyMimeType text/plain text/html // 기본값

Mime 타입은 복수로 추가할 수 있다.

 

12) SecReponseBodyMimeTypesClear

ResponseBody의 버퍼링을 위해 Mime 타입의 목록을 지우며, 처음에 위치시킨다.

o SecResponseBodyMimeType





1.  mod_unique_id module 추가
    기본적으로 mod_unique_id 모듈을 apache install 시 설치해야되나 빠져있다면
    apache source를 다운받아서 해당 모듈만 복사한다.
  
    # cd /usr/local/src
    # wget http://mirror.apache-kr.org/httpd/httpd-2.2.27.tar.gz
    # tar xvfz httpd-2.2.27.tar.gz
    # cd httpd-2.2.27/modules/metadata
    # /usr/local/apache/bin/apxs -cia mod_unique_id.c
    # /etc/rc.d/init.d/httpd restart (/usr/local/apache/bin/apachectl restart)

2. 컴파일전 설치되어야할 라이브러리들이 다 설치되어 있는지 확인한다.
   해당 사이트를 참고

3. 컴파일
   # ./autogen.sh
   #./configure \
    --with-apxs=/usr/local/apache/bin/apxs \
    --with-libxml=/usr \
    --with-apr=/usr/local/apache/bin/apr-1-config \
    --with-apu=/usr/local/apache/bin/apu-1-config
   # make
   # make install

4
5. httpd.conf 에 아래 내용 추가

   LoadModule unique_id_module   modules/mod_unique_id.so
   LoadFile  /usr/lib64/libxml2.so
   LoadFile  /usr/lib64/liblua-5.1.so
   LoadModule security2_module    modules/mod_security2.so

    <IfModule security2_module>
       Include conf/crs/modsecurity_crs_10_setup.conf
       Include conf/crs/activated_rules/*.conf
    </IfModule>

6. crs/activated_rules 디렉토리의 modsecurity_crs_10_setup.conf 심볼릭 링크 삭제
   httpd.conf 에 include되는 modsecurity_crs_10_setup.conf 파일을 아래 activated_rules/*.conf 으로 모든 파일을
   불러오는데 modsecurity_crs_10_setup.conf이 2번 불려오게 되서 apache error_log에
   ModSecurity: Found another rule with the same id 에러가 발생하게 된다.
   Include conf/crs/activated_rules/*.conf 만 하던지 심볼릭 링크를 삭제하던지 2번 불려지지 않게 한다.

7. httpd restart

8. www.your-domain.com/?foo=/etc/passwd 해서 apache error_log에 ModSecurity: Access denied.....이런 메세지가 나오면
   제대로 작동하는것이다.

9. 개발서버 IP로 접속이 안되면  modsecurity_crs_21_protocol_anomalies.conf 파일의 98번 라인을 주석처리하여 롤을
   없앤다.
   error_log를 보면 어떤 롤파일의 몇번째 롤 때문에 오류가 나는지 나오므로 그걸보고 하나씩 롤을 수정하면 된다.






추가적으로 IP화이트 하려면 mod_security.conf 그러니까 기본 설정파일안에 보면 
SecRule REMOTE_ADDR "@ipMatch 192.168.0.150"  "id:'900005', phase:1,  t:none, ctl:ruleEngine=DetectionOnly,
  setvar:tx.regression_testing=1, \nolog, pass"
이런식으로 정의가 되어있다 이양식대로 사용하면됨


2015-03-15---------------------------------------------------------------------------------------------------------------------------------------------------------------
centos6 + modsecurity2.9 + apache 2.2

1.  mod_unique_id module 추가
    기본적으로 mod_unique_id 모듈을 apache install 시 설치해야되나 빠져있다면
    apache source를 다운받아서 해당 모듈만 복사한다.
  
    # cd /usr/local/src
    # wget http://mirror.apache-kr.org/httpd/httpd-2.2.27.tar.gz
    # tar xvfz httpd-2.2.27.tar.gz
    # cd httpd-2.2.27/modules/metadata
    # /usr/local/apache/bin/apxs -cia mod_unique_id.c
    # /etc/rc.d/init.d/httpd restart (/usr/local/apache/bin/apachectl restart)

2. 컴파일전 설치되어야할 라이브러리들이 다 설치되어 있는지 확인한다.
   https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#Installation_for_Apache
   해당 사이트를 참고

3. 컴파일
   # ./autogen.sh
   #./configure \
    --with-apxs=/usr/local/apache/bin/apxs \
    --with-libxml=/usr \
    --with-apr=/usr/local/apache/bin/apr-1-config \
    --with-apu=/usr/local/apache/bin/apu-1-config
./autogen.sh
# ./configure --with-apxs=/usr/local/apache/bin/apxs --with-apr=/usr/local/apr/bin/apr-1-config --with-apu=/usr/local/apr-util/bin/apu-1-config --with-lua --with-pcre=/usr/local/bin/pcre-config    

# make
   # make install

4. https://www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_Set_Project 에서 최근 롤셋을 다운
   INSTALL text 파일안 설명대로 설치
   krcert.or.kr 에서 제공하는 룰셋은 오래전 룰셋이라 OWASP에서 제공하는 룰셋으로 셋팅한다.

5. httpd.conf 에 아래 내용 추가

   LoadModule unique_id_module   modules/mod_unique_id.so
   LoadFile  /usr/lib64/libxml2.so
   LoadFile  /usr/lib64/liblua-5.1.so
   LoadModule security2_module    modules/mod_security2.so

    <IfModule security2_module>
       Include conf/crs/modsecurity_crs_10_setup.conf
       Include conf/crs/activated_rules/*.conf
    </IfModule>

6. crs/activated_rules 디렉토리의 modsecurity_crs_10_setup.conf 심볼릭 링크 삭제
   httpd.conf 에 include되는 modsecurity_crs_10_setup.conf 파일을 아래 activated_rules/*.conf 으로 모든 파일을
   불러오는데 modsecurity_crs_10_setup.conf이 2번 불려오게 되서 apache error_log에
   ModSecurity: Found another rule with the same id 에러가 발생하게 된다.
   Include conf/crs/activated_rules/*.conf 만 하던지 심볼릭 링크를 삭제하던지 2번 불려지지 않게 한다.

7. httpd restart

8. www.your-domain.com/?foo=/etc/passwd 해서 apache error_log에 ModSecurity: Access denied.....이런 메세지가 나오면
   제대로 작동하는것이다.

9. 개발서버 IP로 접속이 안되면  modsecurity_crs_21_protocol_anomalies.conf 파일의 98번 라인을 주석처리하여 롤을
   없앤다.
   error_log를 보면 어떤 롤파일의 몇번째 롤 때문에 오류가 나는지 나오므로 그걸보고 하나씩 롤을 수정하면 된다.


########################################################################################################

 How do I whitelist an IP address so it can pass through ModSecurity?

The first issue to realize is that in ModSecurity 2.0, the allow action is only applied to the current phase. This means that if a rule matches in a subsequent phase it may still take a disruptive action. The recommended rule configuration to allow a remote IP address to bypass ModSecurity rules is to do the following (where 192.168.1.100 should be substituted with the desired IP address):

SecRule REMOTE_ADDR "^192\.168\.1\100$" phase:1,nolog,allow,ctl:ruleEngine=Off

If you want to allow uninterrupted access to the remote IP address, however you still want to log rule alerts, then you can use this rule -

SecRule REMOTE_ADDR "^192\.168\.1\100$" phase:1,nolog,allow,ctl:ruleEngine=DetectionOnly

If you want to disable both the rule and audit engines, then you can optionally add another ctl action:

SecRule REMOTE_ADDR "^192\.168\.1\100$" phase:1,nolog,allow,ctl:ruleEngine=Off,ctl:auditEngine=Off





반응형