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.

315 lines
11 KiB

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