this is based on calsyslab project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

326 lines
11 KiB

  1. __author__ = 'DarkWeb'
  2. '''
  3. HiddenMarket Market Crawler (Selenium)
  4. '''
  5. from selenium import webdriver
  6. from selenium.common.exceptions import NoSuchElementException
  7. from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
  8. from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
  9. from selenium.webdriver.firefox.service import Service
  10. from selenium.webdriver.common.by import By
  11. from selenium.webdriver.support import expected_conditions as EC
  12. from selenium.webdriver.support.ui import WebDriverWait
  13. from PIL import Image
  14. import urllib.parse as urlparse
  15. import os, re, time
  16. import subprocess
  17. import configparser
  18. from bs4 import BeautifulSoup
  19. from MarketPlaces.Initialization.prepare_parser import new_parse
  20. from MarketPlaces.HiddenMarket.parser import hiddenmarket_links_parser
  21. from MarketPlaces.Utilities.utilities import cleanHTML
  22. counter = 1
  23. baseURL = 'http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/'
  24. # Opens Tor Browser, crawls the website
  25. def startCrawling():
  26. # opentor()
  27. marketName = getMKTName()
  28. driver = getAccess()
  29. if driver != 'down':
  30. try:
  31. login(driver)
  32. crawlForum(driver)
  33. except Exception as e:
  34. print(driver.current_url, e)
  35. closetor(driver)
  36. new_parse(marketName, baseURL, True)
  37. # Opens Tor Browser
  38. def opentor():
  39. from MarketPlaces.Initialization.markets_mining import config
  40. global pid
  41. print("Connecting Tor...")
  42. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  43. pid = pro.pid
  44. time.sleep(7.5)
  45. input('Tor Connected. Press ENTER to continue\n')
  46. return
  47. # Login using premade account credentials and do login captcha manually
  48. def login(driver):
  49. # wait for login page
  50. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  51. (By.XPATH, "/html/body/div[3]/div[3]")))
  52. # entering username and password into input boxes
  53. # usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="username"]')
  54. # Username here
  55. # usernameBox.send_keys('ct1234')
  56. # passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="password"]')
  57. # Password here
  58. # passwordBox.send_keys('DementedBed1230')
  59. '''
  60. # wait for captcha page show up
  61. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  62. (By.XPATH, "/html/body/main/div/div/div/div/div/form/div[3]/div/div[1]/label/img")))
  63. # save captcha to local
  64. driver.find_element(by=By.XPATH, value='/html/body/main/div/div/div/div/div/form/div[3]/div/div[1]/label/img').screenshot(
  65. r'..\captcha.png')
  66. # This method will show image in any image viewer
  67. im = Image.open(r'..\captcha.png')
  68. im.show()
  69. # wait until input space show up
  70. inputBox = driver.find_element(by=By.XPATH, value='//*[@id="captcha"]')
  71. # ask user input captcha solution in terminal
  72. userIn = input("Enter solution: ")
  73. # send user solution into the input space
  74. inputBox.send_keys(userIn)
  75. # click the verify(submit) button
  76. driver.find_element(by=By.XPATH, value="/html/body/main/div/div/div/div/div/form/div[4]/button").click()
  77. '''
  78. # input("Press ENTER when CAPTCHA is completed\n")
  79. # wait for listing page show up (This Xpath may need to change based on different seed url)
  80. # WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  81. # (By.XPATH, '/html/body/main/div/div/div[1]/div/div[1]/div/h5')))
  82. # Returns the name of the website
  83. def getMKTName():
  84. name = 'HiddenMarket'
  85. return name
  86. # Return the link of the website
  87. def getFixedURL():
  88. url = 'http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/'
  89. return url
  90. # Closes Tor Browser
  91. def closetor(driver):
  92. # global pid
  93. # os.system("taskkill /pid " + str(pro.pid))
  94. # os.system("taskkill /t /f /im tor.exe")
  95. print('Closing Tor...')
  96. driver.quit()
  97. time.sleep(3)
  98. return
  99. # Creates FireFox 'driver' and configure its 'Profile'
  100. # to use Tor proxy and socket
  101. def createFFDriver():
  102. from MarketPlaces.Initialization.markets_mining import config
  103. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  104. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  105. # ff_prof.set_preference("places.history.enabled", False)
  106. # ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  107. # ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  108. # ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  109. # ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  110. # ff_prof.set_preference("signon.rememberSignons", False)
  111. # ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  112. # ff_prof.set_preference("network.dns.disablePrefetch", True)
  113. # ff_prof.set_preference("network.http.sendRefererHeader", 0)
  114. # ff_prof.set_preference("permissions.default.image", 3)
  115. # ff_prof.set_preference("browser.download.folderList", 2)
  116. # ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  117. # ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  118. ff_prof.set_preference('network.proxy.type', 1)
  119. ff_prof.set_preference("network.proxy.socks_version", 5)
  120. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  121. ff_prof.set_preference('network.proxy.socks_port', 9150)
  122. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  123. ff_prof.set_preference("javascript.enabled", False)
  124. ff_prof.update_preferences()
  125. service = Service(config.get('TOR', 'geckodriver_path'))
  126. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  127. driver.maximize_window()
  128. return driver
  129. def getAccess():
  130. url = getFixedURL()
  131. driver = createFFDriver()
  132. try:
  133. driver.get(url)
  134. return driver
  135. except:
  136. driver.close()
  137. return 'down'
  138. # Saves the crawled html page
  139. def savePage(driver, page, url):
  140. cleanPage = cleanHTML(driver, page)
  141. filePath = getFullPathName(url)
  142. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  143. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  144. return
  145. # Gets the full path of the page to be saved along with its appropriate file name
  146. def getFullPathName(url):
  147. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  148. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  149. fileName = getNameFromURL(url)
  150. if isDescriptionLink(url):
  151. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  152. else:
  153. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  154. return fullPath
  155. # Creates the file name from passed URL
  156. def getNameFromURL(url):
  157. global counter
  158. name = ''.join(e for e in url if e.isalnum())
  159. if name == '':
  160. name = str(counter)
  161. counter = counter + 1
  162. return name
  163. def getInterestedLinks():
  164. links = []
  165. # # Civil Software
  166. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/civil_softwares')
  167. # # Tutorials - Carding
  168. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/carding')
  169. # Digital - Hacks
  170. links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/hacks')
  171. # # Digital - Exploit Kit
  172. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/exploit_kit')
  173. # # 0Day
  174. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/0day')
  175. # # Digital Forensics
  176. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/digital_forensics')
  177. # # Tutorials - Mining
  178. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/mining')
  179. # # Tutorials - Worms
  180. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/worms')
  181. # # Tutorials - Viruses
  182. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/viruses')
  183. # # Tutorials - Trojans
  184. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/trojans')
  185. # # Tutorials - Botnets
  186. # links.append('http://mipx6eedtsvfgfcmbm3utjedgjez2w4dzjdrbhtd2mt3cicwhhzspxqd.onion/category/botnets')
  187. return links
  188. def crawlForum(driver):
  189. print("Crawling the HiddenMarket market")
  190. linksToCrawl = getInterestedLinks()
  191. i = 0
  192. while i < len(linksToCrawl):
  193. link = linksToCrawl[i]
  194. print('Crawling :', link)
  195. categoryLink = link
  196. maxNumPages = 0 # temp value.
  197. try:
  198. has_next_page = True
  199. count = 0
  200. pageCount = 1
  201. while has_next_page:
  202. try:
  203. driver.get(link)
  204. if pageCount == 1:
  205. maxNumPages = int(driver.find_element(by=By.CLASS_NAME, value='main')
  206. .find_element(by=By.CLASS_NAME, value='pages')
  207. .find_elements(By.CLASS_NAME, value='page')[-1].text)
  208. except:
  209. driver.refresh()
  210. html = driver.page_source
  211. savePage(driver, html, link)
  212. list = productPages(html)
  213. for item in list:
  214. itemURL = urlparse.urljoin(baseURL, str(item))
  215. try:
  216. driver.get(itemURL)
  217. except:
  218. driver.refresh()
  219. savePage(driver, driver.page_source, item)
  220. driver.back()
  221. # comment out
  222. # break
  223. # comment out
  224. if count == 1:
  225. break
  226. try:
  227. pageCount += 1
  228. if pageCount > maxNumPages:
  229. raise NoSuchElementException
  230. pageLink = "/" + str(pageCount) + "/"
  231. link = categoryLink + pageLink
  232. count += 1
  233. except NoSuchElementException:
  234. has_next_page = False
  235. except Exception as e:
  236. print(link, e)
  237. i += 1
  238. print("Crawling the HiddenMarket market done.")
  239. # Returns 'True' if the link is Topic link
  240. def isDescriptionLink(url):
  241. if 'product' in url:
  242. return True
  243. return False
  244. # Returns True if the link is a listingPage link
  245. def isListingLink(url):
  246. if 'category' in url:
  247. return True
  248. return False
  249. # calling the parser to define the links
  250. def productPages(html):
  251. soup = BeautifulSoup(html, "html.parser")
  252. return hiddenmarket_links_parser(soup)
  253. def crawler():
  254. startCrawling()
  255. # print("Crawling and Parsing BestCardingWorld .... DONE!")