먼저 modsecurity와 clamav가 설치되어 있고 정상 작동한다는 조건을 만족해야 합니다.

( modsecurity with clamav )

modsecurity 1.x대는 현재 더이상 지원되지 않으니 2.x대를 사용하시기 바랍니다.

이 글은 modsecurity 2.x대를 기준으로 작성 되었습니다.

요즘 빈번히 발생하는 web application의 remote inclusion공격에 사용되는 방법중 하나가 업로드시 확장자 체크를
피해(보통 php파일은 업로드를 제한하는 경우가 많으니 확장자를 jpg, txt등으로 변경하거나 gif등의 이미지안에
php코드를 삽입)공격하게 되는데 업로드 되는 파일 또는 이미지를 clamav를 이용해 검사하게 되면 좀더 안전한
웹서버 운영이 될것으로 보입니다. 특히 clamav의 경우는 기타 다른 백신들보다 php관련 프로그램들에 대한
검출 능력이 뛰어나고 검사 가능한 범위도 넓습니다. php의 shell_exec나 passthru공격에 대한 대비책으로
적당해 보입니다.


modsecurity 1.9.3 이상부터 사용가능한SecUploadApproveScript 지시자 (2.x대에서는 SecRule FILES_TMPNAMES
지시자를 사용해야 합니다)를 이용해 업로드 파일을 검사할수 있습니다.


modsecurity rule파일에 다음 부분을 추가

SecUploadDir /tmp/file_upload_dir #업로드파일이 위치할 디렉토리 - 변경가능
SecTmpDir /tmp/temporary_file_dir #임시 파일이 위치할 디렉토리 - 변경가능
SecRule FILES_TMPNAMES "@inspectFile /usr/bin/modsec-clamscan.pl"
  "t:none,phase:2,log,auditlog,deny,status:406"

status code, log, auditlog 설정여부는 사용자의 설정에 맞게 변경할수 있습니다.
modsec-clamscan.pl파일은 아래링크를 누르면 볼수 있습니다. 또한 첨부파일로 받을 수 있습니다.
파일의 위치는 위의 설정대로 /usr/bin에 저장하거나 위의 설정을 변경했다면  해당위치로 변경하면 됩니다.


 
#!/usr/bin/perl
#
# modsec-clamscan.pl
# ModSecurity for Apache (http://www.modsecurity.org)
# Copyright (c) 2002-2007 Breach Security, Inc. (http://www.breach.com)
#
# This script is an interface between mod_security and its
# ability to intercept files being uploaded through the
# web server, and ClamAV

# by default use the command-line version of ClamAV,
# which is slower but more likely to work out of the
# box
$CLAMSCAN = "/usr/bin/clamscan";

# using ClamAV in daemon mode is faster since the
# anti-virus engine is already running, but you also
# need to configure file permissions to allow ClamAV,
# usually running as a user other than the one Apache
# is running as, to access the files
# $CLAMSCAN = "/usr/bin/clamdscan";

if (@ARGV != 1) {
print "Usage: modsec-clamscan.pl <filename>n";
exit;
}

my ($FILE) = @ARGV;

$cmd = "$CLAMSCAN --stdout --disable-summary $FILE";
$input = `$cmd`;
$input =~ m/^(.+)/;
$error_message = $1;

$output = "0 Unable to parse clamscan output [$1]";

if ($error_message =~ m/: Empty file.?$/) {
$output = "1 empty file";
}
elsif ($error_message =~ m/: (.+) ERROR$/) {
$output = "0 clamscan: $1";
}
elsif ($error_message =~ m/: (.+) FOUND$/) {
$output = "0 clamscan: $1";
}
elsif ($error_message =~ m/: OK$/) {
$output = "1 clamscan: OK";
}

print "$outputn";


테스트에 사용된 파일은 gif98a형식의 헤더를 가지고 있지만 PHP코드가 embed되어 있는
(clamav 진단명: Exploit.Gif.PHPembedded)파일입니다. 파일을 열어보면 아래처럼 보입니다.

 GIF89aY???????EUR???EUR?EUREUR???EUREUR?EUR?EUREUREUREUREUR?????????????????????
??^H??^_^H^H??^H^S*활좧??^^J|^Pq줓?^X3N촪'!?^_;^^^L?dI"^WGj4H2cK?^XU??&?
<?php^M
$dir = @getcwd();$UNAME = @php_uname();$safemode=@ini_get('safe_mode');if
gif 헤더아래 php 코드가 보이는군요. 이제 이파일을 업로드를 해보겠습니다.


해당파일을 게시판에 업로드를 시도 하니 apache error log에 다음과 같은 로그가 남았습니다.
(필요한 정보외 다른정보는 짧게 줄였습니다 Array )
[Sun May 25 22:22:07 2008] [error] [client ... ] ModSecurity: Access denied with code 406 (phase 2). File "/file_location/20080525-..." rejected by the approver script "/usr/bin/modsec-clamscan.pl": 0 clamscan: Exploit.Gif.PHPembedded [hostname "free4u.wo.tc"] [uri "file_upload_script"] [unique_id "..."]
그리고 파일업로드가 되지 않습니다. 정확히는 modsecurity가 업로드를 거부하게 됩니다. modsec_audit log를 보면
클라이언트와 서버간의 헤더정보와 좀더 자세한 로그를 볼수 있습니다.

clamav를 사용한 업로드 파일 검사시 파일이 크거나 할 경우 서버의 cpu자원을 많이 점유할수 있으니 그부분은
업로드 파일 크기를 제한 하거나 clamav설정에서 검사할 최대 파일 크기를 설정하는 등의 방법이 필요할 것으로
보입니다.


첨부파일은 modsecurity 1.9.5에 포함된 modsec-clamscan.pl파일이고 modsecurity 2.x대에도 그대로
사용할수 있습니다.



2008.12.03 추가
modsec-clamscan.pl파일에서 

$CLAMSCAN = "/usr/bin/clamscan";

부분중 clamscan을
clamdscan으로 변경하면 이미 떠있는 clamd 데몬에 직접연결해 파일을 스캔하기때문에 검사속도가
비약적으로(?) 향상 됩니다. 이서버가 사양이 좋지 않아(?) clamscan으로 설정시 오래 걸리던 검색시간이
몇초 내외로 단축되었습니다. 다만 정확한 설정이 필요하고 자세한 로그가 남지 않기때문에 문제 발생시 쉽게
대처하기가 어려울수 있습니다.(수차례 테스트 결과 apache유저가 clamd.conf파일을 읽을수 있어야
clamdscan이 동작했습니다.
) clamdscan으로 변경시 업로드가 실패 또는 거부될경우 SecDebugLogLevel을 높게
설정한뒤 테스트 해보기시 바랍니다 :)

'Modsecurity' 카테고리의 다른 글

modsecurity를 이용한 apache의 chroot 운영  (0) 2008.11.11
modsecurity - SecRuleRemoveById  (0) 2008.07.09
ModSecurity 2.x & zeroboardXE  (0) 2008.05.05
GotRoot Rules for ModSecurity  (0) 2008.04.28
ModSecurity 2.5 Released  (0) 2008.04.01

+ Recent posts