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.

319 lines
11 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'DarkWeb'
  2. '''
  3. DarkFox Forum 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, time
  16. from datetime import date
  17. import subprocess
  18. from bs4 import BeautifulSoup
  19. from MarketPlaces.Initialization.prepare_parser import new_parse
  20. from MarketPlaces.DarkFox.parser import darkfox_links_parser
  21. from MarketPlaces.Utilities.utilities import cleanHTML
  22. counter = 1
  23. baseURL = 'http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/'
  24. # Opens Tor Browser, crawls the website, then parses, then closes tor
  25. #acts like the main method for the crawler, another function at the end of this code calls this function later
  26. def startCrawling():
  27. mktName = getMKTName()
  28. driver = getAccess()
  29. if driver != 'down':
  30. try:
  31. captcha(driver)
  32. crawlForum(driver)
  33. except Exception as e:
  34. print(driver.current_url, e)
  35. closeDriver(driver)
  36. new_parse(mktName, baseURL, True)
  37. # Returns the name of the website
  38. #return: name of site in string type
  39. def getMKTName():
  40. name = 'DarkFox'
  41. return name
  42. # Returns credentials needed for the mkt
  43. def getCredentials():
  44. credentials = 'blank blank blank blank cap 0'
  45. return credentials
  46. # Return the base link of the website
  47. #return: url of base site in string type
  48. def getFixedURL():
  49. url = 'http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/'
  50. return url
  51. # Closes Tor Browser
  52. #@param: current selenium driver
  53. def closeDriver(driver):
  54. # global pid
  55. # os.system("taskkill /pid " + str(pro.pid))
  56. # os.system("taskkill /t /f /im tor.exe")
  57. print('Closing Tor...')
  58. driver.close()
  59. time.sleep(3)
  60. return
  61. # Creates FireFox 'driver' and configure its 'Profile'
  62. # to use Tor proxy and socket
  63. def createFFDriver():
  64. from MarketPlaces.Initialization.markets_mining import config
  65. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  66. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  67. # ff_prof.set_preference("places.history.enabled", False)
  68. # ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  69. # ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  70. # ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  71. # ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  72. # ff_prof.set_preference("signon.rememberSignons", False)
  73. # ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  74. # ff_prof.set_preference("network.dns.disablePrefetch", True)
  75. # ff_prof.set_preference("network.http.sendRefererHeader", 0)
  76. ff_prof.set_preference("permissions.default.image", 3)
  77. ff_prof.set_preference("browser.download.folderList", 2)
  78. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  79. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  80. ff_prof.set_preference('network.proxy.type', 1)
  81. ff_prof.set_preference("network.proxy.socks_version", 5)
  82. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  83. ff_prof.set_preference('network.proxy.socks_port', 9150)
  84. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  85. ff_prof.set_preference("javascript.enabled", False)
  86. ff_prof.update_preferences()
  87. service = Service(config.get('TOR', 'geckodriver_path'))
  88. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  89. driver.maximize_window()
  90. return driver
  91. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  92. #return: return the selenium driver or string 'down'
  93. def getAccess():
  94. url = getFixedURL()
  95. driver = createFFDriver()
  96. try:
  97. driver.get(url)
  98. return driver
  99. except:
  100. driver.close()
  101. return 'down'
  102. # Manual captcha solver, waits fora specific element so that the whole page loads, finds the input box, gets screenshot of captcha
  103. # then allows for manual solving of captcha in the terminal
  104. #@param: current selenium web driver
  105. def captcha(driver):
  106. '''
  107. # wait for captcha page show up
  108. WebDriverWait(driver, 100).until(EC.visibility_of_element_located((By.XPATH, "/html/body/div/div/form/button[1]")))
  109. # save captcha to local
  110. driver.find_element(by=By.XPATH, value="/html/body/div/div/form/div[1]/div[1]").screenshot(r'..\DarkFox\captcha.png')
  111. # open method used to open different extension image file
  112. im = Image.open(r'..\DarkFox\captcha.png')
  113. # This method will show image in any image viewer
  114. im.show()
  115. # wait until input space show up
  116. inputBox = driver.find_element(by=By.XPATH, value="/html/body/div/div/form/div[1]/div[2]/input")
  117. # ask user input captha solution in terminal
  118. userIn = input("Enter solution: ")
  119. # send user solution into the input space
  120. inputBox.send_keys(userIn)
  121. # click the verify(submit) button
  122. driver.find_element(by=By.XPATH, value="/html/body/div/div/form/button[1]").click()
  123. '''
  124. input("Press ENTER when CAPTCHA is completed\n")
  125. # wait for listing page show up (This Xpath may need to change based on different seed url)
  126. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  127. (By.XPATH, "/html/body/main/div/div/div[2]/div[1]/div[1]/form/div[1]/h1")))
  128. # Saves the crawled html page, makes the directory path for html pages if not made
  129. def savePage(driver, page, url):
  130. cleanPage = cleanHTML(driver, page)
  131. filePath = getFullPathName(url)
  132. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  133. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  134. return
  135. # Gets the full path of the page to be saved along with its appropriate file name
  136. #@param: raw url as crawler crawls through every site
  137. def getFullPathName(url):
  138. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  139. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  140. fileName = getNameFromURL(url)
  141. if isDescriptionLink(url):
  142. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  143. else:
  144. fullPath = os.path.join(mainDir, 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. # # Guides and Tutorials
  162. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/30739153-1fcd-45cd-b919-072b439c6e06')
  163. # # Digital Products
  164. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/0e384d5f-26ef-4561-b5a3-ff76a88ab781')
  165. # Software and Malware
  166. links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/6b71210f-f1f9-4aa3-8f89-bd9ee28f7afc')
  167. # # Services
  168. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/b9dc5846-5024-421e-92e6-09ba96a03280')
  169. # # Miscellaneous
  170. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/fd1c989b-1a74-4dc0-92b0-67d8c1c487cb')
  171. # # Hosting and Security
  172. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/5233fd6a-72e6-466d-b108-5cc61091cd14')
  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 DarkFox market")
  179. linksToCrawl = getInterestedLinks()
  180. i = 0
  181. while i < len(linksToCrawl):
  182. link = linksToCrawl[i]
  183. print('Crawling :', link)
  184. try:
  185. has_next_page = True
  186. count = 0
  187. while has_next_page:
  188. try:
  189. driver.get(link)
  190. except:
  191. driver.refresh()
  192. html = driver.page_source
  193. savePage(driver, html, link)
  194. list = productPages(html)
  195. for item in list:
  196. itemURL = urlparse.urljoin(baseURL, str(item))
  197. try:
  198. driver.get(itemURL)
  199. except:
  200. driver.refresh()
  201. savePage(driver, driver.page_source, item)
  202. driver.back()
  203. # comment out
  204. break
  205. # comment out
  206. if count == 1:
  207. break
  208. try:
  209. link = driver.find_element(by=By.XPATH, value=
  210. '/html/body/main/div/div[2]/div/div[2]/div/div/div/nav/a[2]').get_attribute('href')
  211. if link == "":
  212. raise NoSuchElementException
  213. count += 1
  214. except NoSuchElementException:
  215. has_next_page = False
  216. except Exception as e:
  217. print(link, e)
  218. i += 1
  219. print("Crawling the DarkFox market done.")
  220. # Returns 'True' if the link is a description link
  221. #@param: url of any url crawled
  222. #return: true if is a description page, false if not
  223. def isDescriptionLink(url):
  224. if 'product' in url:
  225. return True
  226. return False
  227. # Returns True if the link is a listingPage link
  228. #@param: url of any url crawled
  229. #return: true if is a Listing page, false if not
  230. def isListingLink(url):
  231. if 'category' in url:
  232. return True
  233. return False
  234. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  235. #@param: link from interested link list ie. getInterestingLinks()
  236. #return: list of description links that should be crawled through
  237. def productPages(html):
  238. soup = BeautifulSoup(html, "html.parser")
  239. return darkfox_links_parser(soup)
  240. # Drop links that "signout"
  241. def isSignOut(url):
  242. #absURL = urlparse.urljoin(url.base_url, url.url)
  243. if 'signout' in url.lower() or 'logout' in url.lower():
  244. return True
  245. return False
  246. def crawler():
  247. startCrawling()
  248. # print("Crawling and Parsing BestCardingWorld .... DONE!")