curlcontrol.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-"
  3. # vim: set expandtab tabstop=4 shiftwidth=4:
  4. """
  5. $Id$
  6. This file is part of the xsser project, http://xsser.03c8.net
  7. Copyright (c) 2011/2018 psy <epsylon@riseup.net>
  8. xsser is free software; you can redistribute it and/or modify it under
  9. the terms of the GNU General Public License as published by the Free
  10. Software Foundation version 3 of the License.
  11. xsser is distributed in the hope that it will be useful, but WITHOUT ANY
  12. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  14. details.
  15. You should have received a copy of the GNU General Public License along
  16. with xsser; if not, write to the Free Software Foundation, Inc., 51
  17. Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  18. """
  19. import os, urllib, mimetools, pycurl, re, time, random
  20. try:
  21. from cStringIO import StringIO
  22. except ImportError:
  23. from StringIO import StringIO
  24. class Curl:
  25. """
  26. Class to control curl on behalf of the application.
  27. """
  28. cookie = None
  29. dropcookie = None
  30. referer = None
  31. headers = None
  32. proxy = None
  33. ignoreproxy = None
  34. tcp_nodelay = None
  35. xforw = None
  36. xclient = None
  37. atype = None
  38. acred = None
  39. #acert = None
  40. retries = 1
  41. delay = 0
  42. followred = 0
  43. fli = None
  44. agents = [] # user-agents
  45. try:
  46. f = open("core/fuzzing/user-agents.txt").readlines() # set path for user-agents
  47. except:
  48. f = open("fuzzing/user-agents.txt").readlines() # set path for user-agents when testing
  49. for line in f:
  50. agents.append(line)
  51. agent = random.choice(agents).strip() # set random user-agent
  52. def __init__(self, base_url="", fakeheaders=[ 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg', 'Connection: Keep-Alive', 'Content-type: application/x-www-form-urlencoded; charset=UTF-8']):
  53. self.handle = pycurl.Curl()
  54. self._closed = False
  55. self.set_url(base_url)
  56. self.verbosity = 0
  57. self.signals = 1
  58. self.payload = ""
  59. self.header = StringIO()
  60. self.fakeheaders = fakeheaders
  61. self.headers = None
  62. self.set_option(pycurl.SSL_VERIFYHOST, 0)
  63. self.set_option(pycurl.SSL_VERIFYPEER, 0)
  64. try:
  65. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_TLSv1_2) # max supported version by pycurl
  66. except:
  67. try:
  68. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_TLSv1_1)
  69. except: # use vulnerable TLS/SSL versions (TLS1_0 -> weak enc | SSLv2 + SSLv3 -> deprecated)
  70. try:
  71. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_TLSv1_0)
  72. except:
  73. try:
  74. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv3)
  75. except:
  76. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv2)
  77. self.set_option(pycurl.FOLLOWLOCATION, 0)
  78. self.set_option(pycurl.MAXREDIRS, 50)
  79. # this is 'black magic'
  80. self.set_option(pycurl.COOKIEFILE, '/dev/null')
  81. self.set_option(pycurl.COOKIEJAR, '/dev/null')
  82. self.set_timeout(30)
  83. self.set_option(pycurl.NETRC, 1)
  84. self.set_nosignals(1)
  85. def payload_callback(x):
  86. self.payload += x
  87. self.set_option(pycurl.WRITEFUNCTION, payload_callback)
  88. def header_callback(x):
  89. self.header.write(x)
  90. self.set_option(pycurl.HEADERFUNCTION, header_callback)
  91. def set_url(self, url):
  92. """
  93. Set the base url.
  94. """
  95. self.base_url = url
  96. self.set_option(pycurl.URL, self.base_url)
  97. return url
  98. def set_cookie(self, cookie):
  99. """
  100. Set the app cookie.
  101. """
  102. self.cookie = cookie
  103. self.dropcookie = dropcookie
  104. if dropcookie:
  105. self.set_option(pycurl.COOKIELIST, 'ALL')
  106. self.set_option(pycurl.COOKIE, None)
  107. else:
  108. self.set_option(pycurl.COOKIELIST, '')
  109. self.set_option(pycurl.COOKIE, self.cookie)
  110. return cookie
  111. def set_agent(self, agent):
  112. """
  113. Set the user agent.
  114. """
  115. self.agent = agent
  116. self.set_option(pycurl.USERAGENT, self.agent)
  117. return agent
  118. def set_referer(self, referer):
  119. """
  120. Set the referer.
  121. """
  122. self.referer = referer
  123. self.set_option(pycurl.REFERER, self.referer)
  124. return referer
  125. def set_headers(self, headers):
  126. """
  127. Set extra headers.
  128. """
  129. self.headers = headers
  130. self.headers = self.headers.split("\n")
  131. for headerValue in self.headers:
  132. header, value = headerValue.split(": ")
  133. if header and value:
  134. self.set_option(pycurl.HTTPHEADER, (header, value))
  135. return headers
  136. def set_proxy(self, ignoreproxy, proxy):
  137. """
  138. Set the proxy to use.
  139. """
  140. self.proxy = proxy
  141. self.ignoreproxy = ignoreproxy
  142. if ignoreproxy:
  143. self.set_option(pycurl.PROXY, "")
  144. else:
  145. self.set_option(pycurl.PROXY, self.proxy)
  146. return proxy
  147. def set_option(self, *args):
  148. """
  149. Set the given option.
  150. """
  151. apply(self.handle.setopt, args)
  152. def set_verbosity(self, level):
  153. """
  154. Set the verbosity level.
  155. """
  156. self.set_option(pycurl.VERBOSE, level)
  157. def set_nosignals(self, signals="1"):
  158. """
  159. Disable signals.
  160. curl will be using other means besides signals to timeout
  161. """
  162. self.signals = signals
  163. self.set_option(pycurl.NOSIGNAL, self.signals)
  164. return signals
  165. def set_tcp_nodelay(self, tcp_nodelay):
  166. """
  167. Set the TCP_NODELAY option.
  168. """
  169. self.tcp_nodelay = tcp_nodelay
  170. self.set_option(pycurl.TCP_NODELAY, tcp_nodelay)
  171. return tcp_nodelay
  172. def set_timeout(self, timeout):
  173. """
  174. Set timeout for requests.
  175. """
  176. self.set_option(pycurl.CONNECTTIMEOUT,timeout)
  177. self.set_option(pycurl.TIMEOUT, timeout)
  178. return timeout
  179. def set_follow_redirections(self, followred, fli):
  180. """
  181. Set follow locations parameters to follow redirection pages (302)
  182. """
  183. self.followred = followred
  184. self.fli = fli
  185. if followred:
  186. self.set_option(pycurl.FOLLOWLOCATION , 1)
  187. self.set_option(pycurl.MAXREDIRS, 50)
  188. if fli:
  189. self.set_option(pycurl.MAXREDIRS, fli)
  190. else:
  191. self.set_option(pycurl.FOLLOWLOCATION , 0)
  192. return followred
  193. def do_head_check(self, urls):
  194. """
  195. Send a HEAD request before to start to inject to verify stability of the target
  196. """
  197. for u in urls:
  198. self.set_option(pycurl.URL, u)
  199. self.set_option(pycurl.NOBODY,1)
  200. self.set_option(pycurl.FOLLOWLOCATION, 1)
  201. self.set_option(pycurl.MAXREDIRS, 50)
  202. self.set_option(pycurl.SSL_VERIFYHOST, 0)
  203. self.set_option(pycurl.SSL_VERIFYPEER, 0)
  204. try:
  205. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_TLSv1_2) # max supported version by pycurl
  206. except:
  207. try:
  208. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_TLSv1_1)
  209. except: # use vulnerable TLS/SSL versions (TLS1_0 -> weak enc | SSLv2 + SSLv3 -> deprecated)
  210. try:
  211. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_TLSv1_0)
  212. except:
  213. try:
  214. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv3)
  215. except:
  216. self.set_option(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv2)
  217. if self.fakeheaders:
  218. from core.randomip import RandomIP
  219. if self.xforw:
  220. generate_random_xforw = RandomIP()
  221. xforwip = generate_random_xforw._generateip('')
  222. xforwfakevalue = ['X-Forwarded-For: ' + str(xforwip)]
  223. if self.xclient:
  224. generate_random_xclient = RandomIP()
  225. xclientip = generate_random_xclient._generateip('')
  226. xclientfakevalue = ['X-Client-IP: ' + str(xclientip)]
  227. if self.xforw:
  228. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue)
  229. if self.xclient:
  230. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue + xclientfakevalue)
  231. elif self.xclient:
  232. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xclientfakevalue)
  233. if self.headers:
  234. self.fakeheaders = self.fakeheaders + self.headers
  235. self.set_option(pycurl.HTTPHEADER, self.fakeheaders)
  236. if self.agent:
  237. self.set_option(pycurl.USERAGENT, self.agent)
  238. if self.referer:
  239. self.set_option(pycurl.REFERER, self.referer)
  240. if self.proxy:
  241. self.set_option(pycurl.PROXY, self.proxy)
  242. if self.ignoreproxy:
  243. self.set_option(pycurl.PROXY, "")
  244. if self.timeout:
  245. self.set_option(pycurl.CONNECTTIMEOUT, self.timeout)
  246. self.set_option(pycurl.TIMEOUT, self.timeout)
  247. if self.signals:
  248. self.set_option(pycurl.NOSIGNAL, self.signals)
  249. if self.tcp_nodelay:
  250. self.set_option(pycurl.TCP_NODELAY, self.tcp_nodelay)
  251. if self.cookie:
  252. self.set_option(pycurl.COOKIE, self.cookie)
  253. try:
  254. self.handle.perform()
  255. except:
  256. return
  257. if str(self.handle.getinfo(pycurl.HTTP_CODE)) in ["302", "301"]:
  258. self.set_option(pycurl.FOLLOWLOCATION, 1)
  259. def __request(self, relative_url=None):
  260. """
  261. Perform a request and returns the payload.
  262. """
  263. if self.fakeheaders:
  264. from core.randomip import RandomIP
  265. if self.xforw:
  266. """
  267. Set the X-Forwarded-For to use.
  268. """
  269. generate_random_xforw = RandomIP()
  270. xforwip = generate_random_xforw._generateip('')
  271. xforwfakevalue = ['X-Forwarded-For: ' + str(xforwip)]
  272. if self.xclient:
  273. """
  274. Set the X-Client-IP to use.
  275. """
  276. generate_random_xclient = RandomIP()
  277. xclientip = generate_random_xclient._generateip('')
  278. xclientfakevalue = ['X-Client-IP: ' + str(xclientip)]
  279. if self.xforw:
  280. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue)
  281. if self.xclient:
  282. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue + xclientfakevalue)
  283. elif self.xclient:
  284. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xclientfakevalue)
  285. if self.headers:
  286. self.fakeheaders = self.fakeheaders + self.headers
  287. self.set_option(pycurl.HTTPHEADER, self.fakeheaders)
  288. if self.agent:
  289. self.set_option(pycurl.USERAGENT, self.agent)
  290. if self.referer:
  291. self.set_option(pycurl.REFERER, self.referer)
  292. if self.proxy:
  293. self.set_option(pycurl.PROXY, self.proxy)
  294. if self.ignoreproxy:
  295. self.set_option(pycurl.PROXY, "")
  296. if relative_url:
  297. self.set_option(pycurl.URL,os.path.join(self.base_url,relative_url))
  298. if self.timeout:
  299. self.set_option(pycurl.CONNECTTIMEOUT, self.timeout)
  300. self.set_option(pycurl.TIMEOUT, self.timeout)
  301. if self.signals:
  302. self.set_option(pycurl.NOSIGNAL, self.signals)
  303. if self.tcp_nodelay:
  304. self.set_option(pycurl.TCP_NODELAY, self.tcp_nodelay)
  305. if self.cookie:
  306. self.set_option(pycurl.COOKIE, self.cookie)
  307. if self.followred:
  308. self.set_option(pycurl.FOLLOWLOCATION , 1)
  309. self.set_option(pycurl.MAXREDIRS, 50)
  310. if self.fli:
  311. self.set_option(pycurl.MAXREDIRS, int(self.fli))
  312. else:
  313. self.set_option(pycurl.FOLLOWLOCATION , 0)
  314. if self.fli:
  315. print "\n[E] You must launch --follow-redirects command to set correctly this redirections limit\n"
  316. return
  317. """
  318. Set the HTTP authentication method: Basic, Digest, GSS, NTLM or Certificate
  319. """
  320. if self.atype and self.acred:
  321. atypelower = self.atype.lower()
  322. if atypelower not in ( "basic", "digest", "ntlm", "gss" ):
  323. print "\n[E] HTTP authentication type value must be: Basic, Digest, GSS or NTLM\n"
  324. return
  325. acredregexp = re.search("^(.*?)\:(.*?)$", self.acred)
  326. if not acredregexp:
  327. print "\n[E] HTTP authentication credentials value must be in format username:password\n"
  328. return
  329. user = acredregexp.group(1)
  330. password = acredregexp.group(2)
  331. self.set_option(pycurl.USERPWD, "%s:%s" % (user,password))
  332. if atypelower == "basic":
  333. self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
  334. elif atypelower == "digest":
  335. self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_DIGEST)
  336. elif atypelower == "ntlm":
  337. self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_NTLM)
  338. elif atypelower == "gss":
  339. self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_GSSNEGOTIATE)
  340. else:
  341. self.set_option(pycurl.HTTPAUTH, None)
  342. self.set_option(pycurl.HTTPHEADER, ["Accept:"])
  343. elif self.atype and not self.acred:
  344. print "\n[E] You specified the HTTP authentication type, but did not provide the credentials\n"
  345. return
  346. elif not self.atype and self.acred:
  347. print "\n[E] You specified the HTTP authentication credentials, but did not provide the type\n"
  348. return
  349. #if self.acert:
  350. # acertregexp = re.search("^(.+?),\s*(.+?)$", self.acert)
  351. # if not acertregexp:
  352. # print "\n[E] HTTP authentication certificate option must be 'key_file,cert_file'\n"
  353. # return
  354. # # os.path.expanduser for support of paths with ~
  355. # key_file = os.path.expanduser(acertregexp.group(1))
  356. # cert_file = os.path.expanduser(acertregexp.group(2))
  357. # self.set_option(pycurl.SSL_VERIFYHOST, 0)
  358. # self.set_option(pycurl.SSL_VERIFYPEER, 1)
  359. # self.set_option(pycurl.SSH_PUBLIC_KEYFILE, key_file)
  360. # self.set_option(pycurl.CAINFO, cert_file)
  361. # self.set_option(pycurl.SSLCERT, cert_file)
  362. # self.set_option(pycurl.SSLCERTTYPE, 'p12')
  363. # self.set_option(pycurl.SSLCERTPASSWD, '1234')
  364. # self.set_option(pycurl.SSLKEY, key_file)
  365. # self.set_option(pycurl.SSLKEYPASSWD, '1234')
  366. # for file in (key_file, cert_file):
  367. # if not os.path.exists(file):
  368. # print "\n[E] File '%s' doesn't exist\n" % file
  369. # return
  370. self.set_option(pycurl.SSL_VERIFYHOST, 0)
  371. self.set_option(pycurl.SSL_VERIFYPEER, 0)
  372. self.header.seek(0,0)
  373. self.payload = ""
  374. for count in range(0, self.retries):
  375. time.sleep(self.delay)
  376. if self.dropcookie:
  377. self.set_option(pycurl.COOKIELIST, 'ALL')
  378. nocookie = ['Set-Cookie: ', '']
  379. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + nocookie)
  380. try:
  381. self.handle.perform()
  382. except:
  383. return
  384. return self.payload
  385. def get(self, url="", params=None):
  386. """
  387. Get a url.
  388. """
  389. if params:
  390. url += "?" + urllib.urlencode(params)
  391. self.set_option(pycurl.HTTPGET, 1)
  392. return self.__request(url)
  393. def post(self, cgi, params):
  394. """
  395. Post a url.
  396. """
  397. self.set_option(pycurl.POST, 1)
  398. self.set_option(pycurl.POSTFIELDS, params)
  399. return self.__request(cgi)
  400. def body(self):
  401. """
  402. Get the payload from the latest operation.
  403. """
  404. return self.payload
  405. def info(self):
  406. """
  407. Get an info dictionary from the selected url.
  408. """
  409. self.header.seek(0,0)
  410. url = self.handle.getinfo(pycurl.EFFECTIVE_URL)
  411. if url[:5] == 'http:':
  412. self.header.readline()
  413. m = mimetools.Message(self.header)
  414. else:
  415. m = mimetools.Message(StringIO())
  416. #m['effective-url'] = url
  417. m['http-code'] = str(self.handle.getinfo(pycurl.HTTP_CODE))
  418. m['total-time'] = str(self.handle.getinfo(pycurl.TOTAL_TIME))
  419. m['namelookup-time'] = str(self.handle.getinfo(pycurl.NAMELOOKUP_TIME))
  420. m['connect-time'] = str(self.handle.getinfo(pycurl.CONNECT_TIME))
  421. #m['pretransfer-time'] = str(self.handle.getinfo(pycurl.PRETRANSFER_TIME))
  422. #m['redirect-time'] = str(self.handle.getinfo(pycurl.REDIRECT_TIME))
  423. #m['redirect-count'] = str(self.handle.getinfo(pycurl.REDIRECT_COUNT))
  424. #m['size-upload'] = str(self.handle.getinfo(pycurl.SIZE_UPLOAD))
  425. #m['size-download'] = str(self.handle.getinfo(pycurl.SIZE_DOWNLOAD))
  426. #m['speed-upload'] = str(self.handle.getinfo(pycurl.SPEED_UPLOAD))
  427. m['header-size'] = str(self.handle.getinfo(pycurl.HEADER_SIZE))
  428. m['request-size'] = str(self.handle.getinfo(pycurl.REQUEST_SIZE))
  429. m['response-code'] = str(self.handle.getinfo(pycurl.RESPONSE_CODE))
  430. m['ssl-verifyresult'] = str(self.handle.getinfo(pycurl.SSL_VERIFYRESULT))
  431. m['content-type'] = (self.handle.getinfo(pycurl.CONTENT_TYPE) or '').strip(';')
  432. m['cookielist'] = str(self.handle.getinfo(pycurl.INFO_COOKIELIST))
  433. #m['content-length-download'] = str(self.handle.getinfo(pycurl.CONTENT_LENGTH_DOWNLOAD))
  434. #m['content-length-upload'] = str(self.handle.getinfo(pycurl.CONTENT_LENGTH_UPLOAD))
  435. #m['encoding'] = str(self.handle.getinfo(pycurl.ENCODING))
  436. return m
  437. @classmethod
  438. def print_options(cls):
  439. """
  440. Print selected options.
  441. """
  442. print "\n[-]Verbose: active"
  443. print "[-]Cookie:", cls.cookie
  444. print "[-]HTTP User Agent:", cls.agent
  445. print "[-]HTTP Referer:", cls.referer
  446. print "[-]Extra HTTP Headers:", cls.headers
  447. if cls.xforw == True:
  448. print "[-]X-Forwarded-For:", "Random IP"
  449. else:
  450. print "[-]X-Forwarded-For:", cls.xforw
  451. if cls.xclient == True:
  452. print "[-]X-Client-IP:", "Random IP"
  453. else:
  454. print "[-]X-Client-IP:", cls.xclient
  455. print "[-]Authentication Type:", cls.atype
  456. print "[-]Authentication Credentials:", cls.acred
  457. if cls.ignoreproxy == True:
  458. print "[-]Proxy:", "Ignoring system default HTTP proxy"
  459. else:
  460. print "[-]Proxy:", cls.proxy
  461. print "[-]Timeout:", cls.timeout
  462. if cls.tcp_nodelay == True:
  463. print "[-]Delaying:", "TCP_NODELAY activate"
  464. else:
  465. print "[-]Delaying:", cls.delay, "seconds"
  466. if cls.followred == True:
  467. print "[-]Follow 302 code:", "active"
  468. if cls.fli:
  469. print"[-]Limit to follow:", cls.fli
  470. else:
  471. print "[-]Delaying:", cls.delay, "seconds"
  472. print "[-]Retries:", cls.retries, "\n"
  473. def answered(self, check):
  474. """
  475. Check for occurence of a string in the payload from
  476. the latest operation.
  477. """
  478. return self.payload.find(check) >= 0
  479. def close(self):
  480. """
  481. Close the curl handle.
  482. """
  483. self.handle.close()
  484. self.header.close()
  485. self._closed = True
  486. def __del__(self):
  487. if not self._closed:
  488. self.close()