curlcontrol.py 20 KB

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