curlcontrol.py 20 KB

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