-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpeepingtom.py
281 lines (261 loc) · 10.5 KB
/
peepingtom.py
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#!/usr/bin/env python
"""
Author: pirogue --<p1r06u3@gmail.com>
Purpose: peepingtom for windows(modify)
Created: 2017/4/12
Site: http://pirogue.org
"""
import sys
import urllib2
import subprocess
import re
import time
import os
import hashlib
import random
#=================================================
# MAIN FUNCTION
#=================================================
def main():
# depenency check
# print sys.path[0]
if not all([os.path.exists(sys.path[0]+'\phantomjs.exe'), os.path.exists(sys.path[0]+'\curl.exe')]):
print '[!] PhantomJS and cURL required.'
return
# parse options
import argparse
usage = """
PeepingTom - Tim Tomes (@LaNMaSteR53) (www.lanmaster53.com)
Dependencies:
- PhantomJS
- cURL
$ python ./%(prog)s <mode> <path>"""
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('-l', help='list input mode. path to list file.', dest='list_file', action='store')
parser.add_argument('-x', help='xml input mode. path to Nessus/Nmap XML file.', dest='xml_file', action='store')
parser.add_argument('-s', help='single input mode. path to target, remote URL or local path.', dest='target', action='store')
parser.add_argument('-o', help='output directory', dest='output', action='store')
parser.add_argument('-t', help='socket timeout in seconds. default is 8 seconds.', dest='timeout', type=int, action='store')
parser.add_argument('-v', help='verbose mode', dest='verbose', action='store_true', default=False)
parser.add_argument('-b', help='open results in browser', dest='browser', action='store_true', default=False)
opts = parser.parse_args()
# process options
# input source
if opts.list_file:
try:
targets = open(opts.list_file).read().split()
# print targets
except IOError:
print '[!] Invalid path to list file: \'%s\'' % opts.list_file
return
elif opts.xml_file:
# optimized portion of Peeper (https://github.com/invisiblethreat/peeper) by Scott Walsh (@blacktip)
import xml.etree.ElementTree as ET
try: tree = ET.parse(opts.xml_file)
except IOError:
print '[!] Invalid path to XML file: \'%s\'' % opts.xml_file
return
except ET.ParseError:
print '[!] Not a valid XML file: \'%s\'' % opts.xml_file
return
root = tree.getroot()
# print root.tag.lower()+'111'
if root.tag.lower() == 'nmaprun':
# parse nmap file
targets = parseNmap(root)
elif root.tag.lower() == 'nessusclientdata_v2':
# parse nessus file
targets = parseNessus(root)
print '[*] Parsed targets:'
for x in targets: print x
elif opts.target:
targets = [opts.target]
else:
print '[!] Input mode required.'
return
# storage location
if opts.output:
directory = opts.output
if os.path.isdir(directory):
print '[!] Output directory already exists: \'%s\'' % directory
return
else:
random.seed()
directory = time.strftime('%y%m%d_%H%M%S', time.localtime()) + '_%04d' % random.randint(1, 10000)
# connection timeout
timeout = opts.timeout if opts.timeout else 8
print '[*] Analyzing %d targets.' % (len(targets))
print '[*] Storing data in \'%s/\'' % (directory)
os.mkdir(directory)
report = 'peepingtom.html'
outfile = '%s/%s' % (directory, report)
# logic to gather screenshots and headers for the given targets
db = {'targets': []}
cnt = 0
tot = len(targets) * 2
previouslen = 0
# print "test"
try:
for target in targets:
# print type(target)
# print target
if target[-4:] == ':443' and target[0:4] != 'http':
target ='https://'+ target
elif target[0:4] != 'http':
# print target[0:4]
target = 'http://' + target
# print target
elif target[0:5] == 'http:' or target[0:6] == 'https:':
# print target
# continue
# Displays the target name to the right of the progress bar
# print opts.verbose
print target
# print target
if opts.verbose:
printProgress(cnt, tot, target, previouslen)
else:
printProgress(cnt, tot)
imgname = '%s.png' % re.sub('\W','',target)
srcname = '%s.txt' % re.sub('\W','',target)
imgpath = '%s/%s' % (directory, imgname)
srcpath = '%s/%s' % (directory, srcname)
# print "getCapture"
getCapture(target, imgpath, timeout)
# print "getCapture2"
cnt += 1
previouslen = len(target)
target_data = {}
target_data['url'] = target
target_data['imgpath'] = imgname
target_data['srcpath'] = srcname
target_data['hash'] = hashlib.md5(open(imgpath).read()).hexdigest() if os.path.exists(imgpath) else 'z'*32
target_data['headers'] = getHeaders(target, srcpath, timeout)
db['targets'].append(target_data)
cnt += 1
print printProgress(1,1)
except Exception as e:
print '[!] %s' % (e.__str__())
# build the report and exit
buildReport(db, outfile)
if opts.browser:
import webbrowser
path = os.getcwd()
w = webbrowser.get()
w.open('file://%s/%s/%s' % (path, directory, report))
print '[*] Done.'
#=================================================
# SUPPORT FUNCTIONS
#=================================================
def parseNmap(root):
http_ports = [80,8000,8080,8081,8082]
https_ports = [443,8443]
targets = []
# iterate through all host nodes
for host in root.iter('host'):
hostname = host.find('address').get('addr')
# hostname node doesn't always exist. when it does, overwrite address previously assigned to hostanme
hostname_node = host.find('hostnames').find('hostname')
if hostname_node is not None: hostname = hostname_node.get('name')
# iterate through all port nodes reported for the current host
for item in host.iter('port'):
state = item.find('state').get('state')
if state.lower() == 'open':
# service node doesn't always exist when a port is open
service = item.find('service').get('name') if item.find('service') is not None else ''
port = item.get('portid')
if 'http' in service.lower() or int(port) in (http_ports + https_ports):
proto = 'http'
if 'https' in service.lower() or int(port) in https_ports:
proto = 'https'
url = '%s://%s:%s' % (proto, hostname, port)
if not url in targets:
targets.append(url)
elif not service:
# show the host and port for unknown services
print '[-] Unknown service: %s:%s' % (hostname, port)
return targets
def parseNessus(root):
targets = []
for host in root.iter('ReportHost'):
name = host.get('name')
for item in host.iter('ReportItem'):
svc = item.get('svc_name')
plugname = item.get('pluginName')
if (svc in ['www','http?','https?'] and plugname.lower().startswith('service detection')):
port = item.get('port')
output = item.find('plugin_output').text.strip()
proto = guessProto(output)
url = '%s://%s:%s' % (proto, name, port)
if not url in targets:
targets.append(url)
return targets
def guessProto(output):
# optimized portion of Peeper (https://github.com/invisiblethreat/peeper) by Scott Walsh (@blacktip)
secure = re.search('TLS|SSL', output)
if secure:
return "https"
return "http"
def getCapture(url, imgpath, timeout):
cookie_file = 'cookies'
cmd = '.\phantomjs --ssl-protocol=any --ignore-ssl-errors=yes --cookies-file="%s" .\capture.js "%s" "%s" %d' % (cookie_file, url, imgpath, timeout*1000)
# print cmd
returncode, response = runCommand(cmd)
# delete cookie file
os.remove(cookie_file)
return returncode
def getHeaders(url, srcpath, timeout):
#cmd = 'curl -sILk %s --connect-timeout %d' % (url, timeout)
cmd = '.\curl -sLkD - %s -o %s --max-time %d' % (url, srcpath, timeout)
# print cmd+"222"
returncode, response = runCommand(cmd)
return response
def runCommand(cmd):
# print cmd+"111"
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
# print proc
stdout, stderr = proc.communicate()
# print stdout,"stdout"
response = ''
if stdout: response += str(stdout)
if stderr: response += str(stderr)
# print proc.returncode, response
return proc.returncode, response.strip()
def printProgress(cnt, tot, target='', previouslen=0):
percent = 100 * float(cnt) / float(tot)
if target and previouslen > len(target):
target = target + ' ' * (previouslen - len(target))
sys.stdout.write('[%-40s] %d%% %s\r' % ('='*int(float(percent)/100*40), percent, target))
sys.stdout.flush()
return ''
def buildReport(db, outfile):
live_markup = ''
error_markup = ''
dead_markup = ''
# process markup for live targets
for live in sorted(db['targets'], key=lambda k: k['hash']):
live_markup += "<tr><td class='img'><a href='{0}' target='_blank'><img src='{0}' onerror=\"this.parentNode.parentNode.innerHTML='No image available.';\" /></a></td><td class='head'><a href='{1}' target='_blank'>{1}</a> (<a href='{2}' target='_blank'>source</a>)<br /><pre>{3}</pre></td></tr>\n".format(live['imgpath'],live['url'],live['srcpath'],live['headers'])
# add markup to the report
file = open(outfile, 'w')
file.write("""
<!doctype html>
<head>
<style>
table, td, th {border: 1px solid black;border-collapse: collapse;padding: 5px;font-size: .9em;font-family: tahoma;}
table {width: 100%%;table-layout: fixed;min-width: 1000px;}
td.img {width: 40%%;}
img {width: 100%%;}
td.head {vertical-align: top;word-wrap: break-word;}
</style>
</head>
<body>
<table>
%s
</table>
</body>
</html>""" % (live_markup))
file.close()
#=================================================
# START
#=================================================
if __name__ == "__main__": main()