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.

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