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.

310 lines
11 KiB

  1. __author__ = 'Helium'
  2. '''
  3. LionMarketplace Marketplace 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.support.ui import WebDriverWait
  11. from selenium.webdriver.support import expected_conditions as EC
  12. from selenium.webdriver.common.by import By
  13. from PIL import Image
  14. import urllib.parse as urlparse
  15. import os, re, time
  16. from datetime import date
  17. import subprocess
  18. import configparser
  19. from bs4 import BeautifulSoup
  20. from MarketPlaces.Initialization.prepare_parser import new_parse
  21. from MarketPlaces.LionMarketplace.parser import lionmarketplace_links_parser
  22. from MarketPlaces.Utilities.utilities import cleanHTML
  23. config = configparser.ConfigParser()
  24. config.read('../../setup.ini')
  25. counter = 1
  26. baseURL = 'http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/'
  27. # Opens Tor Browser, crawls the website, then parses, then closes tor
  28. #acts like the main method for the crawler, another function at the end of this code calls this function later
  29. def startCrawling():
  30. opentor()
  31. # mktName = getMKTName()
  32. driver = getAccess()
  33. if driver != 'down':
  34. try:
  35. login(driver)
  36. crawlForum(driver)
  37. except Exception as e:
  38. print(driver.current_url, e)
  39. closetor(driver)
  40. # new_parse(forumName, baseURL, False)
  41. # Opens Tor Browser
  42. #prompts for ENTER input to continue
  43. def opentor():
  44. global pid
  45. print("Connecting Tor...")
  46. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  47. pid = pro.pid
  48. time.sleep(7.5)
  49. input('Tor Connected. Press ENTER to continue\n')
  50. return
  51. # Returns the name of the website
  52. #return: name of site in string type
  53. def getMKTName():
  54. name = 'LionMarketplace'
  55. return name
  56. # Return the base link of the website
  57. #return: url of base site in string type
  58. def getFixedURL():
  59. url = 'http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/'
  60. return url
  61. # Closes Tor Browser
  62. #@param: current selenium driver
  63. def closetor(driver):
  64. # global pid
  65. # os.system("taskkill /pid " + str(pro.pid))
  66. # os.system("taskkill /t /f /im tor.exe")
  67. print('Closing Tor...')
  68. driver.close()
  69. time.sleep(3)
  70. return
  71. # Creates FireFox 'driver' and configure its 'Profile'
  72. # to use Tor proxy and socket
  73. def createFFDriver():
  74. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  75. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  76. ff_prof.set_preference("places.history.enabled", False)
  77. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  78. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  79. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  80. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  81. ff_prof.set_preference("signon.rememberSignons", False)
  82. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  83. ff_prof.set_preference("network.dns.disablePrefetch", True)
  84. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  85. ff_prof.set_preference("permissions.default.image", 2)
  86. ff_prof.set_preference("browser.download.folderList", 2)
  87. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  88. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  89. ff_prof.set_preference('network.proxy.type', 1)
  90. ff_prof.set_preference("network.proxy.socks_version", 5)
  91. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  92. ff_prof.set_preference('network.proxy.socks_port', 9150)
  93. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  94. ff_prof.set_preference("javascript.enabled", False)
  95. ff_prof.update_preferences()
  96. service = Service(config.get('TOR', 'geckodriver_path'))
  97. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  98. return driver
  99. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  100. #return: return the selenium driver or string 'down'
  101. def getAccess():
  102. url = getFixedURL()
  103. driver = createFFDriver()
  104. try:
  105. driver.get(url)
  106. return driver
  107. except:
  108. driver.close()
  109. return 'down'
  110. # Manual captcha solver, waits fora specific element so that the whole page loads, finds the input box, gets screenshot of captcha
  111. # then allows for manual solving of captcha in the terminal
  112. #@param: current selenium web driver
  113. def login(driver):
  114. # wait for page to show up (This Xpath may need to change based on different seed url)
  115. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  116. (By.XPATH, "/html/body/div[2]/div[2]/div[2]/div[1]/div/div[2]/div")))
  117. # Saves the crawled html page, makes the directory path for html pages if not made
  118. def savePage(page, url):
  119. cleanPage = cleanHTML(page)
  120. filePath = getFullPathName(url)
  121. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  122. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  123. return
  124. # Gets the full path of the page to be saved along with its appropriate file name
  125. #@param: raw url as crawler crawls through every site
  126. def getFullPathName(url):
  127. from MarketPlaces.Initialization.markets_mining import CURRENT_DATE
  128. fileName = getNameFromURL(url)
  129. if isDescriptionLink(url):
  130. fullPath = r'..\LionMarketplace\HTML_Pages\\' + CURRENT_DATE + r'\\Description\\' + fileName + '.html'
  131. else:
  132. fullPath = r'..\LionMarketplace\HTML_Pages\\' + CURRENT_DATE + r'\\Listing\\' + fileName + '.html'
  133. return fullPath
  134. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  135. #@param: raw url as crawler crawls through every site
  136. def getNameFromURL(url):
  137. global counter
  138. name = ''.join(e for e in url if e.isalnum())
  139. if (name == ''):
  140. name = str(counter)
  141. counter = counter + 1
  142. return name
  143. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  144. #in this example, there are a couple of categories some threads fall under such as
  145. # Guides and Tutorials, Digital Products, and Software and Malware
  146. #as you can see they are categories of products
  147. def getInterestedLinks():
  148. links = []
  149. # Software/Malware
  150. links.append('http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/category/16')
  151. # # Carding
  152. # links.append('http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/category/20')
  153. # # Hacker for hire
  154. # links.append('http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/category/0b19f3a0-c7e8-11ec-997b-0dcb6b05ce1d')
  155. # # Phishing
  156. # links.append('http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/category/18098bb0-c7e8-11ec-95e9-45b5e8898cbd')
  157. # # Ransomware
  158. # links.append('http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/category/ce72cee0-c7e7-11ec-a86b-c1ff2d3b2020')
  159. # # Exploits
  160. # links.append('http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/category/e26387c0-c7e7-11ec-a708-ab6dc5117763')
  161. # # Spamming and Anti-Captcha
  162. # links.append('http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/category/f08a9380-c7e7-11ec-918c-ffef7c670c97')
  163. # hacked accounts
  164. #links.append('http://lionznqc2hg2wsp5vgruqait4cpknihwlje6hkjyi52lcl5ivyf7bcad.onion/category/fd47b4a0-c7e7-11ec-937b-61246c4b12b3')
  165. return links
  166. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  167. #topic and description pages are crawled through here, where both types of pages are saved
  168. #@param: selenium driver
  169. def crawlForum(driver):
  170. print("Crawling the LionMarketplace market")
  171. linksToCrawl = getInterestedLinks()
  172. visited = set(linksToCrawl)
  173. initialTime = time.time()
  174. count = 0
  175. i = 0
  176. while i < len(linksToCrawl):
  177. link = linksToCrawl[i]
  178. print('Crawling :', link)
  179. try:
  180. try:
  181. driver.get(link)
  182. except:
  183. driver.refresh()
  184. html = driver.page_source
  185. savePage(html, link)
  186. has_next_page = True
  187. while has_next_page:
  188. list = productPages(html)
  189. for item in list:
  190. itemURL = urlparse.urljoin(baseURL, str(item))
  191. try:
  192. driver.get(itemURL)
  193. except:
  194. driver.refresh()
  195. savePage(driver.page_source, item)
  196. driver.back()
  197. # comment out
  198. break
  199. # comment out
  200. if count == 1:
  201. count = 0
  202. break
  203. try:
  204. link = driver.find_element(by=By.XPATH, value=
  205. '/html/body/div[2]/div[2]/div/div[2]/nav/ul/li[5]/a').get_attribute('href')
  206. if link == "":
  207. raise NoSuchElementException
  208. try:
  209. driver.get(link)
  210. except:
  211. driver.refresh()
  212. html = driver.page_source
  213. savePage(html, link)
  214. count += 1
  215. except NoSuchElementException:
  216. has_next_page = False
  217. except Exception as e:
  218. print(link, e)
  219. i += 1
  220. # finalTime = time.time()
  221. # print finalTime - initialTime
  222. input("Crawling LionMarketplace forum done sucessfully. Press ENTER to continue\n")
  223. # Returns 'True' if the link is a description link
  224. #@param: url of any url crawled
  225. #return: true if is a description page, false if not
  226. def isDescriptionLink(url):
  227. if 'product' in url:
  228. return True
  229. return False
  230. # Returns True if the link is a listingPage link
  231. #@param: url of any url crawled
  232. #return: true if is a Listing page, false if not
  233. def isListingLink(url):
  234. if 'category' in url:
  235. return True
  236. return False
  237. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  238. #@param: link from interested link list ie. getInterestingLinks()
  239. #return: list of description links that should be crawled through
  240. def productPages(html):
  241. soup = BeautifulSoup(html, "html.parser")
  242. return lionmarketplace_links_parser(soup)
  243. # Drop links that "signout"
  244. # def isSignOut(url):
  245. # #absURL = urlparse.urljoin(url.base_url, url.url)
  246. # if 'signout' in url.lower() or 'logout' in url.lower():
  247. # return True
  248. #
  249. # return False
  250. def crawler():
  251. startCrawling()
  252. # print("Crawling and Parsing BestCardingWorld .... DONE!")