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.

297 lines
10 KiB

  1. __author__ = 'Helium'
  2. '''
  3. BlackPyramid Forum Crawler (Selenium)
  4. cannot use bc no links are used
  5. kept in case issues are solved
  6. '''
  7. from selenium import webdriver
  8. from selenium.common.exceptions import NoSuchElementException
  9. from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
  10. from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
  11. from selenium.webdriver.firefox.service import Service
  12. from selenium.webdriver.support.ui import WebDriverWait
  13. from selenium.webdriver.support import expected_conditions as EC
  14. from selenium.webdriver.common.by import By
  15. from PIL import Image
  16. import urllib.parse as urlparse
  17. import os, re, time
  18. from datetime import date
  19. import subprocess
  20. import configparser
  21. from bs4 import BeautifulSoup
  22. from MarketPlaces.Initialization.prepare_parser import new_parse
  23. from MarketPlaces.BlackPyramid.parser import blackpyramid_links_parser
  24. from MarketPlaces.Utilities.utilities import cleanHTML
  25. counter = 1
  26. baseURL = 'http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/login/'
  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. mktName = getMKTName()
  31. driver = getAccess()
  32. if driver != 'down':
  33. try:
  34. login(driver)
  35. crawlForum(driver)
  36. except Exception as e:
  37. print(driver.current_url, e)
  38. closeDriver(driver)
  39. new_parse(mktName, baseURL, True)
  40. # Returns the name of the website
  41. #return: name of site in string type
  42. def getMKTName():
  43. name = 'BlackPyramid'
  44. return name
  45. # Return the base link of the website
  46. #return: url of base site in string type
  47. def getFixedURL():
  48. url = 'http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/'
  49. return url
  50. # Closes Tor Browser
  51. #@param: current selenium driver
  52. def closeDriver(driver):
  53. # global pid
  54. # os.system("taskkill /pid " + str(pro.pid))
  55. # os.system("taskkill /t /f /im tor.exe")
  56. print('Closing Tor...')
  57. driver.close()
  58. time.sleep(3)
  59. return
  60. # Creates FireFox 'driver' and configure its 'Profile'
  61. # to use Tor proxy and socket
  62. def createFFDriver():
  63. from MarketPlaces.Initialization.markets_mining import config
  64. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  65. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  66. ff_prof.set_preference("places.history.enabled", False)
  67. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  68. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  69. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  70. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  71. ff_prof.set_preference("signon.rememberSignons", False)
  72. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  73. ff_prof.set_preference("network.dns.disablePrefetch", True)
  74. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  75. ff_prof.set_preference("permissions.default.image", 3)
  76. ff_prof.set_preference("browser.download.folderList", 2)
  77. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  78. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  79. ff_prof.set_preference('network.proxy.type', 1)
  80. ff_prof.set_preference("network.proxy.socks_version", 5)
  81. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  82. ff_prof.set_preference('network.proxy.socks_port', 9150)
  83. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  84. ff_prof.set_preference("javascript.enabled", False)
  85. ff_prof.update_preferences()
  86. service = Service(config.get('TOR', 'geckodriver_path'))
  87. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  88. driver.maximize_window()
  89. return driver
  90. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  91. #return: return the selenium driver or string 'down'
  92. def getAccess():
  93. url = getFixedURL()
  94. driver = createFFDriver()
  95. try:
  96. driver.get(url)
  97. return driver
  98. except:
  99. driver.close()
  100. return 'down'
  101. # Manual captcha solver, waits fora specific element so that the whole page loads, finds the input box, gets screenshot of captcha
  102. # then allows for manual solving of captcha in the terminal
  103. #@param: current selenium web driver
  104. def login(driver):
  105. # wait for login page
  106. login_link = driver.find_element(by=By.XPATH, value='/html/body/div/div/div[3]/div/main/div/div/div/div[2]/div/div/div/section[1]/input[1]')
  107. login_link.click() # open tab with url
  108. # entering username and password into input boxes
  109. usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="username"]')
  110. # Username here
  111. usernameBox.send_keys('ChipotleSteakBurrito')
  112. passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="password"]')
  113. # Password here
  114. passwordBox.send_keys('BlackBeans')
  115. input("Press ENTER when CAPTCHA is completed\n")
  116. # wait for listing page show up (This Xpath may need to change based on different seed url)
  117. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  118. (By.XPATH, '/html/body/div[2]/form/nav/nav/ul/li[2]/div/a/span[1]')))
  119. # Saves the crawled html page, makes the directory path for html pages if not made
  120. def savePage(driver, page, url):
  121. cleanPage = cleanHTML(driver, page)
  122. filePath = getFullPathName(url)
  123. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  124. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  125. return
  126. # Gets the full path of the page to be saved along with its appropriate file name
  127. #@param: raw url as crawler crawls through every site
  128. def getFullPathName(url):
  129. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  130. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  131. fileName = getNameFromURL(url)
  132. if isDescriptionLink(url):
  133. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  134. else:
  135. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  136. return fullPath
  137. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  138. #@param: raw url as crawler crawls through every site
  139. def getNameFromURL(url):
  140. global counter
  141. name = ''.join(e for e in url if e.isalnum())
  142. if (name == ''):
  143. name = str(counter)
  144. counter = counter + 1
  145. return name
  146. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  147. #in this example, there are a couple of categories some threads fall under such as
  148. # Guides and Tutorials, Digital Products, and Software and Malware
  149. #as you can see they are categories of products
  150. def getInterestedLinks():
  151. links = []
  152. # Hacking Guides
  153. links.append('http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/search/results/')
  154. # # Exploits
  155. # links.append('http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/search/results/')
  156. # # botnets/malware
  157. # links.append('http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/search/results/')
  158. # # fraud software
  159. # links.append('http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/search/results/')
  160. # # Other Tools
  161. # links.append('http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/search/results/')
  162. # # Services
  163. # links.append('http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/search/results/')
  164. return links
  165. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  166. #topic and description pages are crawled through here, where both types of pages are saved
  167. #@param: selenium driver
  168. def crawlForum(driver):
  169. print("Crawling the BlackPyramid market")
  170. linksToCrawl = getInterestedLinks()
  171. i = 0
  172. while i < len(linksToCrawl):
  173. link = linksToCrawl[i]
  174. print('Crawling :', link)
  175. try:
  176. has_next_page = True
  177. count = 0
  178. while has_next_page:
  179. try:
  180. clicker = driver.find_element(by=By.XPATH, value='/html/body/div[2]/form/nav/nav/ul/li[2]/div/a')
  181. clicker.click() # open tab with url
  182. driver.get(link)
  183. except:
  184. driver.refresh()
  185. html = driver.page_source
  186. savePage(driver, html, link)
  187. list = productPages(html)
  188. for item in list:
  189. itemURL = urlparse.urljoin(baseURL, str(item))
  190. try:
  191. driver.get(itemURL)
  192. except:
  193. driver.refresh()
  194. savePage(driver, driver.page_source, item)
  195. driver.back()
  196. # comment out
  197. break
  198. # comment out
  199. if count == 1:
  200. break
  201. try:
  202. clicker = driver.find_element(by=By.XPATH, value=
  203. '/html/body/center/div[4]/div/div[3]/div[23]/div[2]/input[1]')
  204. if clicker == "":
  205. raise NoSuchElementException
  206. count += 1
  207. except NoSuchElementException:
  208. has_next_page = False
  209. except Exception as e:
  210. print(link, e)
  211. i += 1
  212. print("Crawling the BlackPyramid market done.")
  213. # Returns 'True' if the link is a description link
  214. #@param: url of any url crawled
  215. #return: true if is a description page, false if not
  216. def isDescriptionLink(url):
  217. if 'products' in url:
  218. return True
  219. return False
  220. # Returns True if the link is a listingPage link
  221. #@param: url of any url crawled
  222. #return: true if is a Listing page, false if not
  223. def isListingLink(url):
  224. if 'search' in url:
  225. return True
  226. return False
  227. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  228. #@param: link from interested link list ie. getInterestingLinks()
  229. #return: list of description links that should be crawled through
  230. def productPages(html):
  231. soup = BeautifulSoup(html, "html.parser")
  232. return blackpyramid_links_parser(soup)
  233. def crawler():
  234. startCrawling()
  235. # print("Crawling and Parsing BlackPyramid .... DONE!")