-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathwebDavDelivery.py
277 lines (234 loc) · 10.1 KB
/
webDavDelivery.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
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
#!/usr/bin/python
# -*- coding: utf8 -*-
import argparse
import socket
from datetime import datetime
import base64
from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
#======================================================================================================
# HELPERS FUNCTIONS
#======================================================================================================
def color(string, color=None):
"""
Author: HarmJ0y, borrowed from Empire
Change text color for the Linux terminal.
"""
attr = []
if color:
if color.lower() == "red":
attr.append('31')
elif color.lower() == "green":
attr.append('32')
elif color.lower() == "blue":
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
# bold
attr.append('1')
if string.strip().startswith("[!]"):
attr.append('31')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[+]"):
attr.append('32')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[?]"):
attr.append('33')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[*]"):
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
return string
#------------------------------------------------------------------------
def splitInChunks(s, n):
"""
Author: HarmJ0y, borrowed from Empire
Generator to split a string s into chunks of size n.
"""
for i in xrange(0, len(s), n):
yield s[i:i+n]
#------------------------------------------------------------------------
def b64encode(data):
return base64.b64encode(data)
#------------------------------------------------------------------------
def httpdate(dt):
"""Return a string representation of a date according to RFC 1123
(HTTP/1.1).
The supplied date must be in UTC.
"""
weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"][dt.month - 1]
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month, dt.year, dt.hour, dt.minute, dt.second)
#------------------------------------------------------------------------
def webdavdate(dt):
return "%02d-%02d-%02dT%02d:%02d:%02dZ" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
#------------------------------------------------------------------------
def powershellEncode(data):
"""
Author: HarmJ0y, borrowed from Empire
Encode a PowerShell command into a form usable by powershell.exe -enc ...
"""
return b64encode("".join([char + "\x00" for char in unicode(data)]))
#------------------------------------------------------------------------
# Class handling WebDav request parsing
#------------------------------------------------------------------------
class WebDavRequest(BaseHTTPRequestHandler):
def __init__(self, request_text):
self.rfile = StringIO(request_text)
self.raw_requestline = self.rfile.readline()
self.error_code = self.error_message = None
self.parse_request()
def send_error(self, code, message):
self.error_code = code
self.error_message = message
#------------------------------------------------------------------------
def optionsResponse():
responseHeader = "HTTP/1.1 200 OK\r\n"
responseHeader += "Server: nginx/1.6.2\r\n"
responseHeader += "Date: {}\r\n".format(httpdate(datetime.now()))
responseHeader += "Content-Length: 0\r\n"
responseHeader += "DAV: 1\r\n"
responseHeader += "Allow: GET,HEAD,PUT,DELETE,MKCOL,COPY,MOVE,PROPFIND,OPTIONS\r\n"
responseHeader += "Proxy-Connection: Close\r\n"
responseHeader += "Connection: Close\r\n"
responseHeader += "Age: 0\r\n\r\n"
return responseHeader
#------------------------------------------------------------------------
def propfindResponse(data=None, encode=True, chunkSize=250):
# Get current time
now = datetime.now().replace(microsecond=0)
# Prepare the response's body
body = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
body += "<D:multistatus xmlns:D=\"DAV:\">\r\n"
body += "<D:response>\r\n"
body += "<D:href>/</D:href>\r\n"
body += "<D:propstat>\r\n"
body += "<D:prop>\r\n"
body += "<D:creationdate>{}</D:creationdate>\r\n".format(webdavdate(now))
body += "<D:displayname></D:displayname>\r\n"
body += "<D:getcontentlanguage/>\r\n"
body += "<D:getcontentlength>4096</D:getcontentlength>\r\n"
body += "<D:getcontenttype/>\r\n"
body += "<D:getetag/>\r\n"
body += "<D:getlastmodified>{}</D:getlastmodified>\r\n".format(httpdate(now))
body += "<D:lockdiscovery/>\r\n"
body += "<D:resourcetype><D:collection/></D:resourcetype>\r\n"
body += "<D:source/>\r\n"
body += "<D:supportedlock/>\r\n"
body += "</D:prop>\r\n"
body += "<D:status>HTTP/1.1 200 OK</D:status>\r\n"
body += "</D:propstat>\r\n"
body += "</D:response>\r\n"
if data:
encodedData = b64encode(data) if encode else data
# Check if the encoded data contains special characters not suited for a 'Windows' filename
if (encodedData.find('/') != -1):
encodedData = encodedData.replace('/','_')
chunks = list(splitInChunks(encodedData, chunkSize))
i = 0
for chunk in chunks:
body += "<D:response>\r\n"
body += "<D:href>/{}</D:href>\r\n".format(chunk)
body += "<D:propstat>\r\n"
body += "<D:prop>\r\n"
body += "<D:creationdate>{}</D:creationdate>\r\n".format(webdavdate(now.replace(minute=(i%59))))
body += "<D:displayname>{}</D:displayname>\r\n".format(chunk)
body += "<D:getcontentlanguage/>\r\n"
body += "<D:getcontentlength>0</D:getcontentlength>\r\n"
body += "<D:getcontenttype/>\r\n"
body += "<D:getetag/>\r\n"
body += "<D:getlastmodified>{}</D:getlastmodified>\r\n".format(httpdate(now.replace(minute=(i%59))))
body += "<D:lockdiscovery/>\r\n"
body += "<D:resourcetype/>\r\n"
body += "<D:source/>\r\n"
body += "<D:supportedlock/>\r\n"
body += "</D:prop>\r\n"
body += "<D:status>HTTP/1.1 200 OK</D:status>\r\n"
body += "</D:propstat>\r\n"
body += "</D:response>\r\n"
i+=1
body += "</D:multistatus>\r\n"
responseHeader = "HTTP/1.1 207 Multi-Status\r\n"
responseHeader += "Server: nginx/1.6.2\r\n"
responseHeader += "Date: {}\r\n".format(httpdate(datetime.now()))
responseHeader += "Content-Length: {}\r\n".format(len(body))
responseHeader += "Proxy-Connection: Keep-Alive\r\n"
responseHeader += "Connection: Keep-Alive\r\n\r\n"
return responseHeader + body
#======================================================================================================
# MAIN FUNCTION
#======================================================================================================
if __name__ == '__main__':
#------------------------------------------------------------------------
# Parse arguments
parser = argparse.ArgumentParser()
#parser.add_argument("type", help="Type of base64 encoding to be used", choices=['powershell', 'standard'])
parser.add_argument("-f", "--singleFile", help="Path to the only file to be delivered", dest="singleFile")
parser.add_argument("-v", "--verbose", help="Path to the only file to be delivered", action="store_true", default=False, dest="verbose")
parser.add_argument("-s", "--size", help="Maximum size of each chunk (filename)", dest="size", default=250)
args = parser.parse_args()
chunkSize = int(args.size)
#------------------------------------------------------------------------
# Setup a TCP server listening on port 80
tcps = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcps.bind(('',80))
tcps.listen(1)
print color("[*] Pseudo WebDav server listening on port 80")
print color("[*] Waiting for incoming requests")
#------------------------------------------------------------------------
# Main server loop
try:
while True:
connection, clientAddr = tcps.accept()
try:
print color("[+] Connection received from [{}]".format(clientAddr))
# Receiving request - max size 4096 bytes - should fit any supported WebDav request
data = connection.recv(4096)
# Parsing the data received into a proper request object
request = WebDavRequest(data)
# If there's no error in parsing the data
if not request.error_code:
if args.verbose:
print color("[+] Data received:")
print color ("{}".format(data),'blue')
#-------------------------- OPTIONS --------------------------
if request.command == 'OPTIONS':
response = optionsResponse()
#-------------------------- PROPFIND --------------------------
if request.command == 'PROPFIND':
# WebDav client requesting metadata about a directory
if request.headers['Depth'] == '0':
response = propfindResponse(chunkSize=chunkSize)
# WebDav client requesting content of a directory
if request.headers['Depth'] == '1':
# If the script is supposed to deliver always the same file
if args.singleFile:
fileName = args.singleFile
# Else deliver the file requested in the path
else:
fileName = 'servedFiles' + request.path # The directory path is actually the file name requested
# Read all bytes from the file
try:
with open(fileName) as fileHandle:
fileBytes = bytearray(fileHandle.read())
fileHandle.close()
response = propfindResponse(fileBytes, chunkSize=chunkSize)
print color("[+] Delivering file [{}]".format(fileName))
except IOError:
print color("[!] Could not open or read file [{}]".format(fileName))
response = propfindResponse(chunkSize=chunkSize)
print color("[+] Sending WebDav response")
if args.verbose:
print color("[+] Data sent:")
print color("{}".format(response),'blue')
connection.send(response)
finally:
connection.close()
except KeyboardInterrupt:
pass
finally:
print color("[!] Stopping WebDav Server")
tcps.close()