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.

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