-
Notifications
You must be signed in to change notification settings - Fork 1
/
azel.py
364 lines (321 loc) · 11.3 KB
/
azel.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#! /usr/bin/python
# -*- coding: utf-8 -*-
import httplib
import urllib
from HTMLParser import HTMLParser
from sgmllib import SGMLParser
import re
import os.path # using dirname() on URI actually ;)
# Used to store Link properties the object way
class Link:
href = None
value = '' # the textual value of the link
title = None
def search(self, text):
text = unicode(text, 'utf-8')
if self.href == None: # no need to return None..
return None
m = re.search(text, self.href)
if m != None:
return self.href
if self.value != None:
m = re.search(text, self.value)
if m != None:
return self.href
if self.title != None:
m = re.search(text, self.title)
if m != None:
return self.href
class LinkParser(HTMLParser):
in_a = False
links = []
currentLink = None
def init(self):
self.links = []
self.currentLink = None
self.in_a = False
def handle_starttag(self, tag, attrs):
if self.in_a == True:
self.currentLink.value += self.get_starttag_text()
if tag == 'a':
self.in_a = True
self.currentLink = Link()
for key, value in attrs:
if key == 'href' and value:
self.currentLink.href = value
if key == 'title' and value:
self.currentLink.title = value
def handle_data(self, data):
if self.in_a == True:
self.currentLink.value += data + ' '
def handle_endtag(self, tag):
if tag == 'a':
self.in_a = False
if self.currentLink != None:
# print self.currentLink
self.links.append(self.currentLink)
link = self.currentLink
#print str(link.href)[:14], '#' * 4, link.value, '#' * 4, link.title
self.currentLink = None
if self.in_a == True:
self.currentLink.value += '</' + tag + '>'
# Basic parser to collect interesting fields
class MyHTMLParser(SGMLParser):
nbForms = 0
inForm = False
tagsofinterest = ('input', 'select', 'textarea')
# The URL of the form
targetURL = False
# The different names of the fields to post
fields = []
postdata = {}
# links management
links = [] # list of links found
currentLink = None
# iframes
iframes = []
# future targets in forms:
target = None
def __init__(self, verbose=0):
SGMLParser.__init__(self, verbose)
self.links = []
self.iframes = []
self.starting_description = False
def restart(self):
self.targetURL = False
self.inForm = False
self.fields = []
self.nbForms = 0
def start_iframe(self, attrs):
for key, value in attrs:
if key == 'src' and value != '':
self.iframes.append(value)
def start_a(self, attrs):
self.currentLink = Link()
for key, value in attrs:
if key == "title" and value:
self.currentLink.title = value
if key == "href" and value != '':
self.currentLink.href = value
# if value not in self.links:
# self.links.append(value)
# print self.get_starttag_text()
# self.starting_description = True
def end_a(self):
# return None
link = self.currentLink
# print 'completed', link.href, '###'*3, link.title, '###'*3
# print 'completed', link.href, '###'*3, link.value, '###'*3
self.links.append(link)
# self.currentLink = None
# print 'start text', self.get_starttag_text()
def handle_data(self, data):
if self.currentLink != None:
if self.starting_description:
# print 'started', data, '#######'
# print 'found', data
self.starting_description = False
self.currentLink.value = data
else:
# print 'adding', data
self.currentLink.value = data
def unknown_starttag(self, tag, attrs):
# if self.currentLink != None:
# print tag, attrs
if self.inForm == True:
for key in self.tagsofinterest:
if key == tag:
ntag = {}
for key, value in attrs:
ntag[key] = value
# print ntag
if ntag.has_key('type') and ntag['type'] == "hidden" and ntag.has_key('value'):
# we can directly fill values for hidden fields:
self.postdata[ntag['name']] = ntag['value']
elif ntag.has_key('name') and ntag['name'] != '':
self.postdata[ntag['name']] = ''
self.fields.append(ntag['name'])
if tag == "form":
self.inForm = True
self.nbForms += 1
# print 'forms', self.nbForms
for key, value in attrs:
if key == 'action':
self.targetURL = value
def unknown_endtag(self, tag):
if tag == "form":
self.inForm = False
class Azel: # Hommage to Elza macro language
# cookies to be sent
cookies = {}
cookiesList = []
cookies_set = False
display_cookies = False
# referer if any
referer = False
# reference to sgml parser
parser = False
# reference to httplib
http = False
response = False
ssl = False
host = ''
uri = '/'
url = ''
# data to POST
data = {}
content = None # page content (response.read())
proxyHost = False
proxyPort = False
def __init__(self):
self.parser = MyHTMLParser()
self.data = {}
self.cookies.clear()
def read(self):
if self.content == None:
self.content = self.response.read()
return self.content
def post(self, url=None):
self.request('POST', url)
def get(self, url=None):
self.request('GET', url)
def request(self, method, url):
self.content = None
# If url aint specified, used the one saved in the property by fillForm():
if url == '' or url == None:
url = self.url
self.parseURL(url)
if self.ssl == False:
if self.proxyHost != False:
self.http = httplib.HTTPConnection(self.proxyHost, self.proxyPort)
else:
self.http = httplib.HTTPConnection(self.host)
else:
self.http = httplib.HTTPSConnection(self.host)
if self.proxyHost != False:
print '->', method, self.url, '(proxy)'
self.http.putrequest(method, self.url)
else:
print '->', method, self.url
self.http.putrequest(method, self.uri)
# Set cookies if needed
if self.cookies_set == True:
if self.display_cookies == True:
print '== Cookies:', '; '.join(self.cookiesList)
self.http.putheader('Cookie', '; '.join(self.cookiesList))
if self.referer:
# print '== Referer:', self.referer
self.http.putheader('Referer', self.referer)
# Add data to post
if method == "POST":
self.http.putheader('Content-type', 'application/x-www-form-urlencoded')
self.http.putheader('Content-length', len(urllib.urlencode(self.data)))
try:
self.http.endheaders()
self.http.send(urllib.urlencode(self.data))
except Exception as e:
print 'Error:', e
exit()
# Always clean data
self.data = {}
# Set the new referer
self.referer = self.url
self.response = self.http.getresponse()
print '<-', self.response.status, self.response.reason
# print self.read()
# print self.response.msg
self.handleCookies()
self.handleRedirection()
def handleRedirection(self):
if str(self.response.status).startswith("3"):
redirect = self.response.getheader('Location')
self.get(redirect)
def handleCookies(self):
cookies = self.response.msg.getallmatchingheaders('set-cookie')
for cookie in cookies:
start = cookie.find(' ') + 1 # Skip Set-Cookie:
end = cookie.find(';')
cookie = cookie[start:end]
sep = cookie.find('=')
name = cookie[:sep]
value = cookie[sep+1:]
self.cookies[name] = value
# Prepare cookies for insertion in headers
self.cookiesList = []
self.cookies_set = False # reset completely cookies
for key in self.cookies.keys():
self.cookies_set = True
cookie = key + '=' + self.cookies[key]
self.cookiesList.append(cookie)
def parseURL(self, url):
offset = url.find('#')
if offset != -1:
url = url[:offset] # remove #links
self.url = url
relative = False
if url.startswith("http://"):
newURL = url[len("http://"):]
self.ssl = False
elif url.startswith("https://"):
newURL = url[len("https://"):]
self.ssl = True
else:
newURL = url
relative = True
if relative == False:
offset = newURL.find('/')
if offset == -1:
self.uri = '/'
self.host = newURL
else:
self.host = newURL[0:offset]
self.uri = newURL[offset:]
else: # relative == True:
if not newURL.startswith('/'): # fix urls like 'confirm' instead of /confirm:
self.uri = os.path.join(os.path.dirname(self.uri), newURL)
else:
self.uri = newURL
if self.ssl == True:
self.url = 'https://' + self.host + self.uri
else:
self.url = 'http://' + self.host + self.uri
def parse(self):
self.parser = MyHTMLParser()
self.parser.feed(self.read())
self.parser.close()
# Will prepare hidden fields and new url to POST
def fillForm(self, target=None):
self.parser = MyHTMLParser()
self.parser.postdata = {}
self.parser.targetURL = None
self.parser.target
self.parser.feed(self.read())
self.parser.close()
self.data = self.parser.postdata
self.url = self.parser.targetURL
def getLink(self, text):
content = self.read() # read the content received
p = LinkParser()
p.init() # reset links of lists
p.feed(unicode(content, 'utf-8'))
p.close()
for link in p.links:
if link.search(text):
return link.href
return None
# Parse all links using LinkParser:
def parseLinks(self, content):
p = LinkParser()
p.init()
p.links = [] # reset list of links
p.feed(unicode(content, 'utf-8'))
p.close()
return p.links
def getLinks(self, text):
content = self.read()
links = self.parseLinks(content)
match = []
for link in links:
if link.search(text):
match.append(link)
return match