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.

323 lines
12 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. '''
  3. CypherMarketplace Forum Crawler (Selenium)
  4. crawler done
  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.ui import Select
  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.CypherMarketplace.parser import cyphermarketplace_links_parser
  24. from MarketPlaces.Utilities.utilities import cleanHTML
  25. counter = 1
  26. baseURL = 'http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.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. 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 = 'CypherMarketplace'
  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://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.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. input("Press ENTER when CAPTCHA is completed\n")
  106. # entering username and password into input boxes
  107. usernameBox = driver.find_element(by=By.XPATH, value='//input[@name="username"]')
  108. # Username here
  109. usernameBox.send_keys('beachyoga278') # sends string to the username box
  110. passwordBox = driver.find_element(by=By.XPATH, value='//input[@name="password"]')
  111. # Password here
  112. passwordBox.send_keys('sunfish278') # sends string to passwordBox
  113. input("Press ENTER when CAPTCHA is completed\n")
  114. # wait for listing page 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, '//input[@name="search"]')))
  117. def relogin(driver):
  118. # entering username and password into input boxes
  119. usernameBox = driver.find_element(by=By.XPATH, value='//input[@name="username"]')
  120. # Username here
  121. usernameBox.send_keys('beachyoga278') # sends string to the username box
  122. passwordBox = driver.find_element(by=By.XPATH, value='//input[@name="password"]')
  123. # Password here
  124. passwordBox.send_keys('sunfish278') # sends string to passwordBox
  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, '//input[@name="search"]')))
  129. # Saves the crawled html page, makes the directory path for html pages if not made
  130. def savePage(driver, page, url):
  131. cleanPage = cleanHTML(driver, 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 config, CURRENT_DATE
  140. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  141. fileName = getNameFromURL(url)
  142. if isDescriptionLink(url):
  143. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  144. else:
  145. fullPath = os.path.join(mainDir, 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
  163. links.append('http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/35a35d10-3cfb-11ea-9b14-65b8930c1372')
  164. # Carding
  165. links.append('http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/3d335a10-3cfb-11ea-9224-fdf701883e72')
  166. # Software
  167. links.append('http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/040ca140-3cfc-11ea-9364-87edd8c0a63f')
  168. # Exploit Kits
  169. links.append('http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/da5e6480-3cfb-11ea-b85f-9b6c3bb4c534')
  170. # Botnets
  171. links.append('http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/e3d58e10-3cfb-11ea-a343-ebe7c6036eb1')
  172. # Rats & Trojans
  173. links.append('http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/edf6e020-3cfb-11ea-9438-f7719eecbffe')
  174. # Digital Goods
  175. links.append('http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/fbf0b5b0-3cfb-11ea-827f-0dc5e9988952')
  176. return links
  177. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  178. #topic and description pages are crawled through here, where both types of pages are saved
  179. #@param: selenium driver
  180. def crawlForum(driver):
  181. print("Crawling the CypherMarketplace market")
  182. linksToCrawl = getInterestedLinks()
  183. i = 0
  184. while i < len(linksToCrawl):
  185. link = linksToCrawl[i]
  186. print('Crawling :', link)
  187. try:
  188. has_next_page = True
  189. count = 0
  190. while has_next_page:
  191. try:
  192. if driver.findElements(by=By.XPATH, value='//input[@name="username"]').size() > 0:
  193. relogin(driver)
  194. else:
  195. driver.get(link)
  196. except:
  197. driver.refresh()
  198. html = driver.page_source
  199. savePage(driver, html, link)
  200. list = productPages(html)
  201. for item in list:
  202. itemURL = urlparse.urljoin(baseURL, str(item))
  203. try:
  204. if driver.findElements(by=By.XPATH, value='//input[@name="username"]').size() > 0:
  205. relogin(driver)
  206. else:
  207. driver.get(itemURL)
  208. except:
  209. driver.refresh()
  210. savePage(driver, driver.page_source, item)
  211. driver.back()
  212. # # comment out
  213. # break
  214. #
  215. # # comment out
  216. # if count == 1:
  217. # break
  218. try:
  219. # temp = driver.find_element(by=By.XPATH, value=
  220. # '/html/body/div[2]/div/div/div[2]/div/nav/ul')
  221. link = driver.find_element(by=By.XPATH, value='//a[rel="next"]').get_attribute('href')
  222. if link == "":
  223. raise NoSuchElementException
  224. count += 1
  225. except NoSuchElementException:
  226. has_next_page = False
  227. except Exception as e:
  228. print(link, e)
  229. i += 1
  230. print("Crawling the CypherMarketplace market done.")
  231. # Returns 'True' if the link is a description link
  232. #@param: url of any url crawled
  233. #return: true if is a description page, false if not
  234. def isDescriptionLink(url):
  235. if 'product' in url:
  236. return True
  237. return False
  238. # Returns True if the link is a listingPage link
  239. #@param: url of any url crawled
  240. #return: true if is a Listing page, false if not
  241. def isListingLink(url):
  242. if 'category' in url:
  243. return True
  244. return False
  245. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  246. #@param: link from interested link list ie. getInterestingLinks()
  247. #return: list of description links that should be crawled through
  248. def productPages(html):
  249. soup = BeautifulSoup(html, "html.parser")
  250. return cyphermarketplace_links_parser(soup)
  251. # Drop links that "signout"
  252. # def isSignOut(url):
  253. # #absURL = urlparse.urljoin(url.base_url, url.url)
  254. # if 'signout' in url.lower() or 'logout' in url.lower():
  255. # return True
  256. #
  257. # return False
  258. def crawler():
  259. startCrawling()
  260. # print("Crawling and Parsing CypherMarketplace .... DONE!")