main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #!/usr/bin/python3
  2. # -*- coding: iso-8859-15 -*-
  3. """
  4. This file is part of the cintruder project, https://cintruder.03c8.net
  5. Copyright (c) 2012/2020 psy <epsylon@riseup.net>
  6. cintruder is free software; you can redistribute it and/or modify it under
  7. the terms of the GNU General Public License as published by the Free
  8. Software Foundation version 3 of the License.
  9. cintruder is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  12. details.
  13. You should have received a copy of the GNU General Public License along
  14. with cintruder; if not, write to the Free Software Foundation, Inc., 51
  15. Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. """
  17. import os, traceback, hashlib, sys, time, socket, datetime
  18. import platform, subprocess, re, webbrowser, shutil
  19. from core.options import CIntruderOptions
  20. from core.crack import CIntruderCrack
  21. from core.ocr import CIntruderOCR
  22. from core.curl import CIntruderCurl
  23. from core.xml_export import CIntruderXML
  24. from core.update import Updater
  25. try:
  26. from urlparse import urlparse
  27. except:
  28. import urllib.request, urllib.parse, urllib.error
  29. from urllib.parse import urlparse
  30. # set to emit debug messages about errors (0 = off).
  31. DEBUG = 0
  32. class cintruder():
  33. """
  34. CIntruder application class
  35. """
  36. def __init__(self):
  37. self.captcha = ""
  38. self.optionOCR = []
  39. self.optionCrack = []
  40. self.optionParser = None
  41. self.optionCurl = None
  42. self.options = None
  43. self.word_sug = None
  44. self.train == 0
  45. self.crack == 0
  46. self.ignoreproxy = 1
  47. self.isurl = 0
  48. self.os_sys = platform.system()
  49. self._webbrowser = webbrowser
  50. self.GIT_REPOSITORY = 'https://code.03c8.net/epsylon/cintruder' # oficial code source [OK! 26/01/2019]
  51. self.GIT_REPOSITORY2 = 'https://github.com/epsylon/cintruder' # mirror source [since: 04/06/2018]
  52. def set_options(self, options):
  53. """
  54. Set cintruder options
  55. """
  56. self.options = options
  57. def create_options(self, args=None):
  58. """
  59. Create the program options for OptionParser.
  60. """
  61. self.optionParser = CIntruderOptions()
  62. self.options = self.optionParser.get_options(args)
  63. if not self.options:
  64. return False
  65. return self.options
  66. def set_webbrowser(self, browser):
  67. self._webbrowser = browser
  68. def banner(self):
  69. print('='*75)
  70. print("")
  71. print(" o8%8888, ")
  72. print(" o88%8888888. ")
  73. print(" 8'- -:8888b ")
  74. print(" 8' 8888 ")
  75. print(" d8.-=. ,==-.:888b ")
  76. print(" >8 `~` :`~' d8888 ")
  77. print(" 88 ,88888 ")
  78. print(" 88b. `-~ ':88888 ")
  79. print(" 888b \033[1;31m~==~\033[1;m .:88888 ")
  80. print(" 88888o--:':::8888 ")
  81. print(" `88888| :::' 8888b ")
  82. print(" 8888^^' 8888b ")
  83. print(" d888 ,%888b. ")
  84. print(" d88% %%%8--'-. ")
  85. print(" /88:.__ , _%-' --- - ")
  86. print(" '''::===..-' = --. `\n")
  87. print(self.optionParser.description, "\n")
  88. print('='*75)
  89. def get_attack_captchas(self):
  90. """
  91. Get captchas to brute force
  92. """
  93. captchas = []
  94. options = self.options
  95. p = self.optionParser
  96. if options.train:
  97. print(('='*75))
  98. print((str(p.version)))
  99. print(('='*75))
  100. print("Starting to 'train'...")
  101. print(('='*75))
  102. captchas = [options.train]
  103. if options.crack:
  104. print(('='*75))
  105. print((str(p.version)))
  106. print(('='*75))
  107. print("Starting to 'crack'")
  108. print(('='*75))
  109. captchas = [options.crack]
  110. if options.track:
  111. print(('='*75))
  112. print((str(p.version)))
  113. print(('='*75))
  114. print("Tracking captchas from url...")
  115. print(('='*75))
  116. captchas = [options.track]
  117. return captchas
  118. def train(self, captcha):
  119. """
  120. Learn mode:
  121. + Add words to the brute forcing dictionary
  122. """
  123. self.train_captcha(captcha)
  124. def train_captcha(self, captcha):
  125. """
  126. Learn mode:
  127. 1- Apply OCR to captcha/image and split into unities
  128. 2- Human-Recognize that unities like alphanumeric words (gui supported)
  129. 3- Move that words into dictionary (gui supported)
  130. """
  131. options = self.options
  132. # step 1: applying OCR techniques
  133. if options.name: # with a specific OCR module
  134. print("[Info] Loading module: [ "+ options.name + " ]\n")
  135. try:
  136. sys.path.append('mods/%s/'%(options.name))
  137. exec("from " + options.name + "_ocr" + " import CIntruderOCR") # import module
  138. except Exception:
  139. print("\n[Error] '"+ options.name+ "' module not found!\n")
  140. return #sys.exit(2)
  141. if options.setids: # with a specific colour ID
  142. setids = int(options.setids)
  143. if setids >= 0 and setids <= 255:
  144. self.optionOCR = CIntruderOCR(captcha, options)
  145. else:
  146. print("\n[Error] You must enter a valid RGB colour ID number (between 0 and 255)\n")
  147. return #sys.exit(2)
  148. else:
  149. self.optionOCR = CIntruderOCR(captcha, options)
  150. else: # using general OCR algorithm
  151. if options.setids: # with a specific colour ID
  152. setids = int(options.setids)
  153. if setids >= 0 and setids <= 255:
  154. self.optionOCR = CIntruderOCR(captcha, options)
  155. else:
  156. print("\n[Error] You must enter a valid RGB colour ID number (between 0 and 255)\n")
  157. return #sys.exit(2)
  158. else:
  159. self.optionOCR = CIntruderOCR(captcha, options)
  160. def crack(self, captcha):
  161. """
  162. Crack mode:
  163. + Brute force target's captcha against a dictionary
  164. """
  165. self.crack_captcha(captcha)
  166. def crack_captcha(self, captcha):
  167. """
  168. Crack mode: bruteforcing...
  169. """
  170. options = self.options
  171. if options.name:
  172. print("[Info] Loading module: ["+ str(options.name) + "] \n")
  173. try:
  174. sys.path.append('mods/%s/'%(options.name))
  175. exec("from " + options.name + "_crack" + " import CIntruderCrack")
  176. except Exception:
  177. print("\n[Error] '"+ options.name+ "' module not found!\n")
  178. return #sys.exit(2)
  179. self.optionCrack = CIntruderCrack(captcha)
  180. w = self.optionCrack.crack(options)
  181. self.word_sug = w
  182. else:
  183. self.optionCrack = CIntruderCrack(captcha)
  184. w = self.optionCrack.crack(options)
  185. self.word_sug = w
  186. def remote(self, captchas, proxy):
  187. """
  188. Get remote captchas
  189. """
  190. l = []
  191. if not os.path.exists("inputs/"):
  192. os.mkdir("inputs/")
  193. for captcha in captchas:
  194. c = self.remote_captcha(captcha, proxy)
  195. if c:
  196. l.append(c)
  197. return l
  198. else:
  199. return
  200. def remote_captcha(self, captcha, proxy):
  201. """
  202. Get remote captcha
  203. """
  204. if proxy:
  205. self.ignoreproxy=0
  206. self.optionCurl = CIntruderCurl(captcha, self.ignoreproxy, proxy)
  207. buf = self.optionCurl.request()
  208. if buf != "exit":
  209. m = hashlib.md5()
  210. m.update(captcha.encode('utf-8')+str(datetime.datetime.now()))
  211. c = "%s.gif"%(m.hexdigest())
  212. h = "inputs/" + str(c)
  213. f = open(h, 'wb')
  214. f.write(buf.getvalue())
  215. f.close
  216. buf.close
  217. return h
  218. else:
  219. return #sys.exit(2)
  220. def export(self, captchas):
  221. """
  222. Export results
  223. """
  224. if self.options.xml and not (self.options.train):
  225. self.optionXML = CIntruderXML(captchas)
  226. if self.word_sug == None:
  227. print("[Info] XML NOT created!. There are not words to suggest...")
  228. else:
  229. self.optionXML.print_xml_results(captchas, self.options.xml, self.word_sug)
  230. print("[Info] XML created: "+str(self.options.xml)+ "\n")
  231. def track(self, captchas, proxy, num_tracks):
  232. """
  233. Download captchas from url
  234. """
  235. for captcha in captchas:
  236. self.track_captcha(captcha, proxy, num_tracks)
  237. def track_captcha(self, captcha, proxy, num_tracks):
  238. """
  239. This technique is useful to create a dictionary of 'session based' captchas
  240. """
  241. options = self.options
  242. urlp = urlparse(captcha)
  243. self.domain = urlp.hostname
  244. if not os.path.exists("inputs/%s"%(self.domain)):
  245. os.mkdir("inputs/%s"%(self.domain))
  246. if proxy:
  247. self.ignoreproxy = 0
  248. buf = ""
  249. i=0
  250. while i < int(num_tracks) and buf != "exit":
  251. self.optionCurl = CIntruderCurl(captcha, self.ignoreproxy, proxy)
  252. buf = self.optionCurl.request()
  253. if options.verbose:
  254. print("\n[-]Connection data:")
  255. out = self.optionCurl.print_options()
  256. print('-'*45)
  257. if buf != "exit":
  258. m = hashlib.md5()
  259. m.update(captcha.encode('utf-8')+str(datetime.datetime.now()))
  260. h = "inputs/%s/%s.gif"%(self.domain, m.hexdigest())
  261. f = open(h, 'wb')
  262. f.write(buf.getvalue())
  263. f.close
  264. buf.close
  265. print("[Info] Saved: "+ str(h))
  266. print("------------")
  267. i=i+1
  268. if buf != "exit":
  269. print("\n=================")
  270. print("Tracking Results:")
  271. print("=================")
  272. print("\nNumber of tracked captchas: [ "+ str(num_tracks)+" ] \n")
  273. def run(self, opts=None):
  274. """
  275. Run cintruder
  276. """
  277. if opts:
  278. options = self.create_options(opts)
  279. self.set_options(options)
  280. options = self.options
  281. #step -1: run GUI/Web interface
  282. if options.web:
  283. self.create_web_interface()
  284. return
  285. #step -1: check/update for latest stable version
  286. if options.update:
  287. self.banner()
  288. try:
  289. print("\nTrying to update automatically to the latest stable version\n")
  290. Updater()
  291. except:
  292. print("Not any .git repository found!\n")
  293. print("="*30)
  294. print("\nTo have working this feature, you should clone CIntruder with:\n")
  295. print("$ git clone %s" % self.GIT_REPOSITORY)
  296. print("\nAlso you can try this other mirror:\n")
  297. print("$ git clone %s" % self.GIT_REPOSITORY2 + "\n")
  298. #step 0: list output results and get captcha targets
  299. if options.listmods:
  300. print("=====================================")
  301. print("Listing specific OCR exploit modules:")
  302. print("=====================================\n")
  303. top = 'mods/'
  304. for root, dirs, files in os.walk(top, topdown=False):
  305. for name in files:
  306. if name == 'DESCRIPTION':
  307. if self.os_sys == "Windows": #check for win32 sys
  308. subprocess.call("type %s/%s"%(root, name), shell=True)
  309. else:
  310. subprocess.call("cat %s/%s"%(root, name), shell=True)
  311. print("\n[Info] List end...\n")
  312. return
  313. if options.track_list:
  314. print("==============================")
  315. print("Listing last tracked captchas:")
  316. print("==============================\n")
  317. top = 'inputs/'
  318. tracked_captchas = []
  319. for root, dirs, files in os.walk(top, topdown=False):
  320. for name in files:
  321. path = os.path.relpath(os.path.join(root, name))
  322. if self.os_sys == "Windows": #check for win32 sys
  323. atime = os.path.getatime(path)
  324. else:
  325. date = os.stat(path)
  326. atime = time.ctime(date.st_atime)
  327. tracked_captchas.append([atime,str(" + "+name),str(" |-> "+path)])
  328. tracked_captchas=sorted(tracked_captchas,key=lambda x:x[0]) # sorted by accessed time
  329. ca = 0 # to control max number of results
  330. for t in tracked_captchas:
  331. ca = ca + 1
  332. print("-------------------------")
  333. for c in t:
  334. if ca < 26:
  335. print(c)
  336. else:
  337. break
  338. print("-------------------------")
  339. print("\n[Info] List end...\n")
  340. return
  341. captchas = self.get_attack_captchas()
  342. captchas = self.sanitize_captchas(captchas)
  343. captchas2track = captchas
  344. if self.isurl == 1 and (options.train or options.crack):
  345. if options.proxy:
  346. captchas = self.remote(captchas, options.proxy)
  347. else:
  348. captchas = self.remote(captchas, "")
  349. if options.verbose:
  350. print("\n[-] Connection data:")
  351. out = self.optionCurl.print_options()
  352. print('-'*45)
  353. #step 0: track
  354. if options.track:
  355. if options.s_num:
  356. num_tracks = int(options.s_num) # tracking number defined by user
  357. else:
  358. num_tracks = int(5) # default track connections
  359. if options.proxy:
  360. self.track(captchas2track, options.proxy, num_tracks)
  361. else:
  362. self.track(captchas2track, "", num_tracks)
  363. #step 1: train
  364. if options.train:
  365. try:
  366. if len(captchas) == 1:
  367. for captcha in captchas:
  368. if captcha is None:
  369. print("\n[Error] Applying OCR algorithm... Is that captcha supported?\n")
  370. if os.path.exists('core/images/previews'):
  371. shutil.rmtree('core/images/previews') # remove last OCR
  372. else:
  373. print("\n[Info] Target: "+ options.train+"\n")
  374. self.train(captcha)
  375. else:
  376. for captcha in captchas:
  377. if len(captchas) > 1 and captcha is None:
  378. pass
  379. else:
  380. print("\n[Info] Target: "+ options.train+"\n")
  381. self.train(captcha)
  382. except:
  383. print("[Error] Something wrong getting captcha. Aborting...\n")
  384. if options.xml:
  385. print("[Info] You don't need export to XML on this mode... File not generated!\n")
  386. #step 2: crack
  387. if options.crack:
  388. if len(captchas) == 1:
  389. for captcha in captchas:
  390. if captcha is None:
  391. print("\n[Error] Trying to bruteforce... Is that captcha supported?\n")
  392. if os.path.exists('core/images/previews'):
  393. shutil.rmtree('core/images/previews') # remove last OCR
  394. else:
  395. print("\n[Info] Target: "+ options.crack+"\n")
  396. self.crack(captcha)
  397. else:
  398. for captcha in captchas:
  399. if len(captchas) > 1 and captcha is None:
  400. pass
  401. else:
  402. print("\n[Info] Target: "+ options.crack+"\n")
  403. self.crack(captcha)
  404. if options.command:
  405. print("[Info] Executing tool connector... \n")
  406. if self.word_sug is not None:
  407. print("[Info] This is the word suggested by CIntruder: [ "+ str(self.word_sug)+ " ] \n")
  408. else:
  409. print("[Error] CIntruder hasn't any word to suggest... Handlering tool process aborted! ;(\n")
  410. sys.exit(2)
  411. if "CINT" in options.command: # check parameter CINT on command (*)
  412. # change cintruder suggested word for the users captchas input form parameter
  413. # and execute handlered tool with it.
  414. if self.word_sug is not None:
  415. cmd = options.command.replace("CINT", self.word_sug)
  416. subprocess.call(cmd, shell=True)
  417. else:
  418. cmd = options.command
  419. subprocess.call(cmd, shell=True)
  420. else:
  421. print("[Error] Captcha's parameter flag: 'CINT' is not present on: "+ str(options.command)+ "\n")
  422. #step 3: export
  423. if options.xml:
  424. self.export(captchas)
  425. def sanitize_captchas(self, captchas):
  426. """
  427. Sanitize correct input of source target(s)
  428. """
  429. options = self.options
  430. all_captchas = set()
  431. for captcha in captchas:
  432. # captcha from url
  433. if "http://" in captcha or "https://" in captcha:
  434. all_captchas.add(captcha)
  435. self.isurl = 1
  436. elif self.isurl == 0: # captcha from file
  437. (root, ext) = os.path.splitext(captcha)
  438. if ext != '.gif' and ext != '.jpg' and ext != '.jpeg' and ext != '.png': # by the moment
  439. captcha = None
  440. all_captchas.add(captcha)
  441. else:
  442. all_captchas.add(captcha)
  443. self.isurl = 0
  444. return all_captchas
  445. def create_web_interface(self):
  446. # launch webserver+gui
  447. from .webgui import ClientThread
  448. import webbrowser
  449. host = '0.0.0.0'
  450. port = 9999
  451. try:
  452. webbrowser.open('http://127.0.0.1:9999', new=1)
  453. tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  454. tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  455. tcpsock.bind((host,port))
  456. while True:
  457. tcpsock.listen(4)
  458. (clientsock, (ip, port)) = tcpsock.accept()
  459. newthread = ClientThread(ip, port, clientsock)
  460. newthread.start()
  461. except (KeyboardInterrupt, SystemExit):
  462. sys.exit()
  463. if __name__ == "__main__":
  464. app = cintruder()
  465. options = app.create_options()
  466. if options:
  467. app.set_options(options)
  468. app.run()