curlcontrol.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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, 0)
  201. self.set_option(pycurl.MAXREDIRS, 50)
  202. self.set_option(pycurl.SSL_VERIFYHOST, 0)
  203. self.set_option(pycurl.SSL_VERIFYPEER, 0)
  204. if self.fakeheaders:
  205. from core.randomip import RandomIP
  206. if self.xforw:
  207. generate_random_xforw = RandomIP()
  208. xforwip = generate_random_xforw._generateip('')
  209. xforwfakevalue = ['X-Forwarded-For: ' + str(xforwip)]
  210. if self.xclient:
  211. generate_random_xclient = RandomIP()
  212. xclientip = generate_random_xclient._generateip('')
  213. xclientfakevalue = ['X-Client-IP: ' + str(xclientip)]
  214. if self.xforw:
  215. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue)
  216. if self.xclient:
  217. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue + xclientfakevalue)
  218. elif self.xclient:
  219. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xclientfakevalue)
  220. if self.headers:
  221. self.fakeheaders = self.fakeheaders + self.headers
  222. self.set_option(pycurl.HTTPHEADER, self.fakeheaders)
  223. if self.agent:
  224. self.set_option(pycurl.USERAGENT, self.agent)
  225. if self.referer:
  226. self.set_option(pycurl.REFERER, self.referer)
  227. if self.proxy:
  228. self.set_option(pycurl.PROXY, self.proxy)
  229. if self.ignoreproxy:
  230. self.set_option(pycurl.PROXY, "")
  231. if self.timeout:
  232. self.set_option(pycurl.CONNECTTIMEOUT, self.timeout)
  233. self.set_option(pycurl.TIMEOUT, self.timeout)
  234. if self.signals:
  235. self.set_option(pycurl.NOSIGNAL, self.signals)
  236. if self.tcp_nodelay:
  237. self.set_option(pycurl.TCP_NODELAY, self.tcp_nodelay)
  238. if self.cookie:
  239. self.set_option(pycurl.COOKIE, self.cookie)
  240. try:
  241. self.handle.perform()
  242. except:
  243. return
  244. if str(self.handle.getinfo(pycurl.HTTP_CODE)) in ["302", "301"]:
  245. self.set_option(pycurl.FOLLOWLOCATION, 1)
  246. def __request(self, relative_url=None):
  247. """
  248. Perform a request and returns the payload.
  249. """
  250. if self.fakeheaders:
  251. from core.randomip import RandomIP
  252. if self.xforw:
  253. """
  254. Set the X-Forwarded-For to use.
  255. """
  256. generate_random_xforw = RandomIP()
  257. xforwip = generate_random_xforw._generateip('')
  258. #xforwip = '127.0.0.1'
  259. xforwfakevalue = ['X-Forwarded-For: ' + str(xforwip)]
  260. if self.xclient:
  261. """
  262. Set the X-Client-IP to use.
  263. """
  264. generate_random_xclient = RandomIP()
  265. xclientip = generate_random_xclient._generateip('')
  266. #xclientip = '127.0.0.1'
  267. xclientfakevalue = ['X-Client-IP: ' + str(xclientip)]
  268. if self.xforw:
  269. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue)
  270. if self.xclient:
  271. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xforwfakevalue + xclientfakevalue)
  272. elif self.xclient:
  273. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + xclientfakevalue)
  274. if self.headers:
  275. # XXX sanitize user input
  276. self.fakeheaders = self.fakeheaders + self.headers
  277. self.set_option(pycurl.HTTPHEADER, self.fakeheaders)
  278. if self.agent:
  279. self.set_option(pycurl.USERAGENT, self.agent)
  280. if self.referer:
  281. self.set_option(pycurl.REFERER, self.referer)
  282. if self.proxy:
  283. self.set_option(pycurl.PROXY, self.proxy)
  284. if self.ignoreproxy:
  285. self.set_option(pycurl.PROXY, "")
  286. if relative_url:
  287. self.set_option(pycurl.URL,os.path.join(self.base_url,relative_url))
  288. if self.timeout:
  289. self.set_option(pycurl.CONNECTTIMEOUT, self.timeout)
  290. self.set_option(pycurl.TIMEOUT, self.timeout)
  291. if self.signals:
  292. self.set_option(pycurl.NOSIGNAL, self.signals)
  293. if self.tcp_nodelay:
  294. self.set_option(pycurl.TCP_NODELAY, self.tcp_nodelay)
  295. if self.cookie:
  296. self.set_option(pycurl.COOKIE, self.cookie)
  297. if self.followred:
  298. self.set_option(pycurl.FOLLOWLOCATION , 1)
  299. self.set_option(pycurl.MAXREDIRS, 50)
  300. if self.fli:
  301. self.set_option(pycurl.MAXREDIRS, int(self.fli))
  302. else:
  303. self.set_option(pycurl.FOLLOWLOCATION , 0)
  304. if self.fli:
  305. print "\n[E] You must launch --follow-redirects command to set correctly this redirections limit\n"
  306. return
  307. """
  308. Set the HTTP authentication method: Basic, Digest, GSS, NTLM or Certificate
  309. """
  310. if self.atype and self.acred:
  311. atypelower = self.atype.lower()
  312. if atypelower not in ( "basic", "digest", "ntlm", "gss" ):
  313. print "\n[E] HTTP authentication type value must be: Basic, Digest, GSS or NTLM\n"
  314. return
  315. acredregexp = re.search("^(.*?)\:(.*?)$", self.acred)
  316. if not acredregexp:
  317. print "\n[E] HTTP authentication credentials value must be in format username:password\n"
  318. return
  319. user = acredregexp.group(1)
  320. password = acredregexp.group(2)
  321. self.set_option(pycurl.USERPWD, "%s:%s" % (user,password))
  322. if atypelower == "basic":
  323. self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
  324. elif atypelower == "digest":
  325. self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_DIGEST)
  326. elif atypelower == "ntlm":
  327. self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_NTLM)
  328. elif atypelower == "gss":
  329. self.set_option(pycurl.HTTPAUTH, pycurl.HTTPAUTH_GSSNEGOTIATE)
  330. else:
  331. self.set_option(pycurl.HTTPAUTH, None)
  332. self.set_option(pycurl.HTTPHEADER, ["Accept:"])
  333. elif self.atype and not self.acred:
  334. print "\n[E] You specified the HTTP authentication type, but did not provide the credentials\n"
  335. return
  336. elif not self.atype and self.acred:
  337. print "\n[E] You specified the HTTP authentication credentials, but did not provide the type\n"
  338. return
  339. #if self.acert:
  340. # acertregexp = re.search("^(.+?),\s*(.+?)$", self.acert)
  341. # if not acertregexp:
  342. # print "\n[E] HTTP authentication certificate option must be 'key_file,cert_file'\n"
  343. # return
  344. # # os.path.expanduser for support of paths with ~
  345. # key_file = os.path.expanduser(acertregexp.group(1))
  346. # cert_file = os.path.expanduser(acertregexp.group(2))
  347. # self.set_option(pycurl.SSL_VERIFYHOST, 0)
  348. # self.set_option(pycurl.SSL_VERIFYPEER, 1)
  349. # self.set_option(pycurl.SSH_PUBLIC_KEYFILE, key_file)
  350. # self.set_option(pycurl.CAINFO, cert_file)
  351. # self.set_option(pycurl.SSLCERT, cert_file)
  352. # self.set_option(pycurl.SSLCERTTYPE, 'p12')
  353. # self.set_option(pycurl.SSLCERTPASSWD, '1234')
  354. # self.set_option(pycurl.SSLKEY, key_file)
  355. # self.set_option(pycurl.SSLKEYPASSWD, '1234')
  356. # for file in (key_file, cert_file):
  357. # if not os.path.exists(file):
  358. # print "\n[E] File '%s' doesn't exist\n" % file
  359. # return
  360. self.set_option(pycurl.SSL_VERIFYHOST, 0)
  361. self.set_option(pycurl.SSL_VERIFYPEER, 0)
  362. self.header.seek(0,0)
  363. self.payload = ""
  364. for count in range(0, self.retries):
  365. time.sleep(self.delay)
  366. if self.dropcookie:
  367. self.set_option(pycurl.COOKIELIST, 'ALL')
  368. nocookie = ['Set-Cookie: ', '']
  369. self.set_option(pycurl.HTTPHEADER, self.fakeheaders + nocookie)
  370. try:
  371. self.handle.perform()
  372. except:
  373. return
  374. return self.payload
  375. def get(self, url="", params=None):
  376. """
  377. Get a url.
  378. """
  379. if params:
  380. url += "?" + urllib.urlencode(params)
  381. self.set_option(pycurl.HTTPGET, 1)
  382. return self.__request(url)
  383. def post(self, cgi, params):
  384. """
  385. Post a url.
  386. """
  387. self.set_option(pycurl.POST, 1)
  388. self.set_option(pycurl.POSTFIELDS, params)
  389. return self.__request(cgi)
  390. def body(self):
  391. """
  392. Get the payload from the latest operation.
  393. """
  394. return self.payload
  395. def info(self):
  396. """
  397. Get an info dictionary from the selected url.
  398. """
  399. self.header.seek(0,0)
  400. url = self.handle.getinfo(pycurl.EFFECTIVE_URL)
  401. if url[:5] == 'http:':
  402. self.header.readline()
  403. m = mimetools.Message(self.header)
  404. else:
  405. m = mimetools.Message(StringIO())
  406. #m['effective-url'] = url
  407. m['http-code'] = str(self.handle.getinfo(pycurl.HTTP_CODE))
  408. m['total-time'] = str(self.handle.getinfo(pycurl.TOTAL_TIME))
  409. m['namelookup-time'] = str(self.handle.getinfo(pycurl.NAMELOOKUP_TIME))
  410. m['connect-time'] = str(self.handle.getinfo(pycurl.CONNECT_TIME))
  411. #m['pretransfer-time'] = str(self.handle.getinfo(pycurl.PRETRANSFER_TIME))
  412. #m['redirect-time'] = str(self.handle.getinfo(pycurl.REDIRECT_TIME))
  413. #m['redirect-count'] = str(self.handle.getinfo(pycurl.REDIRECT_COUNT))
  414. #m['size-upload'] = str(self.handle.getinfo(pycurl.SIZE_UPLOAD))
  415. #m['size-download'] = str(self.handle.getinfo(pycurl.SIZE_DOWNLOAD))
  416. #m['speed-upload'] = str(self.handle.getinfo(pycurl.SPEED_UPLOAD))
  417. m['header-size'] = str(self.handle.getinfo(pycurl.HEADER_SIZE))
  418. m['request-size'] = str(self.handle.getinfo(pycurl.REQUEST_SIZE))
  419. m['response-code'] = str(self.handle.getinfo(pycurl.RESPONSE_CODE))
  420. m['ssl-verifyresult'] = str(self.handle.getinfo(pycurl.SSL_VERIFYRESULT))
  421. m['content-type'] = (self.handle.getinfo(pycurl.CONTENT_TYPE) or '').strip(';')
  422. m['cookielist'] = str(self.handle.getinfo(pycurl.INFO_COOKIELIST))
  423. #m['content-length-download'] = str(self.handle.getinfo(pycurl.CONTENT_LENGTH_DOWNLOAD))
  424. #m['content-length-upload'] = str(self.handle.getinfo(pycurl.CONTENT_LENGTH_UPLOAD))
  425. #m['encoding'] = str(self.handle.getinfo(pycurl.ENCODING))
  426. return m
  427. @classmethod
  428. def print_options(cls):
  429. """
  430. Print selected options.
  431. """
  432. print "\n[-]Verbose: active"
  433. print "[-]Cookie:", cls.cookie
  434. print "[-]HTTP User Agent:", cls.agent
  435. print "[-]HTTP Referer:", cls.referer
  436. print "[-]Extra HTTP Headers:", cls.headers
  437. if cls.xforw == True:
  438. print "[-]X-Forwarded-For:", "Random IP"
  439. else:
  440. print "[-]X-Forwarded-For:", cls.xforw
  441. if cls.xclient == True:
  442. print "[-]X-Client-IP:", "Random IP"
  443. else:
  444. print "[-]X-Client-IP:", cls.xclient
  445. print "[-]Authentication Type:", cls.atype
  446. print "[-]Authentication Credentials:", cls.acred
  447. if cls.ignoreproxy == True:
  448. print "[-]Proxy:", "Ignoring system default HTTP proxy"
  449. else:
  450. print "[-]Proxy:", cls.proxy
  451. print "[-]Timeout:", cls.timeout
  452. if cls.tcp_nodelay == True:
  453. print "[-]Delaying:", "TCP_NODELAY activate"
  454. else:
  455. print "[-]Delaying:", cls.delay, "seconds"
  456. if cls.followred == True:
  457. print "[-]Follow 302 code:", "active"
  458. if cls.fli:
  459. print"[-]Limit to follow:", cls.fli
  460. else:
  461. print "[-]Delaying:", cls.delay, "seconds"
  462. print "[-]Retries:", cls.retries, "\n"
  463. def answered(self, check):
  464. """
  465. Check for occurence of a string in the payload from
  466. the latest operation.
  467. """
  468. return self.payload.find(check) >= 0
  469. def close(self):
  470. """
  471. Close the curl handle.
  472. """
  473. self.handle.close()
  474. self.header.close()
  475. self._closed = True
  476. def __del__(self):
  477. if not self._closed:
  478. self.close()