-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathhttpshell.py
More file actions
397 lines (314 loc) · 11.7 KB
/
Copy pathhttpshell.py
File metadata and controls
397 lines (314 loc) · 11.7 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import http
import json
import loggers
import os
import re
import readline
import sys
import Cookie
from urlparse import urlparse
from urllib import urlencode
class HttpShell(object):
def __init__(self, args):
self.http_commands = {
"head": self.head,
"get": self.get,
"post": self.post,
"put": self.put,
"delete": self.delete,
"trace": self.trace,
"options": self.options,
"cd": self.set_path,
}
self.meta_commands = {
"help": self.help,
"?": self.help,
"headers": self.modify_headers,
"tackons": self.modify_tackons,
"cookies": self.modify_cookies,
"open": self.open_host,
"debuglevel": self.set_debuglevel,
"quit": self.exit
}
# dispatch map is http + meta maps
self.dispatch = dict(
self.http_commands.items() + self.meta_commands.items())
self.url = None
self.path = None
self.query = None
self.args = args
self.headers = {}
self.tackons = {}
self.cookies = {}
self.args.debuglevel = 0
# all printing is done via the logger, that way a non-ANSI printer
# will be a lot easier to add retroactively
self.logger = loggers.AnsiLogger()
self.init_readline()
# setup host and initial path
self.init_host(self.args.url)
def init_readline(self):
httpsh_dir = os.path.join(os.path.expanduser("~"), ".httpshell/")
if not os.path.isdir(httpsh_dir):
os.mkdir(httpsh_dir)
self.history_file = os.path.join(httpsh_dir, ".history")
try:
readline.read_history_file(self.history_file)
except IOError:
pass
# sets up tab command completion
readline.set_completer(self.complete)
readline.parse_and_bind("tab: complete")
def init_host(self, url):
# url parse needs a proceeding "//" for default scheme param to work
if not "//" in url[:8]:
url = "//" + url
self.url = urlparse(url, "http")
if not self.url.netloc:
self.logger.print_error("Invalid URL")
self.exit()
self.path = self.url.path if self.url.path else "/"
self.query = self.url.query
# dispatch methods
def head(self, path, pipe=None):
http.Http(self.args, self.logger, "HEAD").run(
self.url, path, pipe, self.headers, self.cookies)
def get(self, path, pipe=None):
http.Http(self.args, self.logger, "GET").run(
self.url, path, pipe, self.headers, self.cookies)
def post(self, path, pipe=None):
body = self.input_body()
if body:
http.Http(self.args, self.logger, "POST").run(
self.url, path, pipe, self.headers, self.cookies, body)
def put(self, path, pipe=None):
body = self.input_body()
if body:
http.Http(self.args, self.logger, "PUT").run(
self.url, path, pipe, self.headers, self.cookies, body)
def delete(self, path, pipe=None):
http.Http(self.args, self.logger, "DELETE").run(
self.url, path, pipe, self.headers, self.cookies)
def trace(self, path, pipe=None):
http.Http(self.args, self.logger, "TRACE").run(
self.url, path, pipe, self.headers, self.cookies)
def options(self, path, pipe=None):
http.Http(self.args, self.logger, "OPTIONS").run(
self.url, path, pipe, self.headers, self.cookies)
def help(self):
self.logger.print_help()
# handles .headers meta-command
def modify_headers(self, header=None):
if header and len(header) > 0:
# header will be header:[value]
a = header.split(":", 1)
key = a[0]
if len(a) > 1:
value = a[1]
if len(value) > 0:
self.headers[key] = value
elif key in self.headers:
del self.headers[key] # if no value provided, delete
else:
self.logger.print_error("Invalid syntax.")
else:
# print send headers
self.logger.print_headers(self.headers.items(), sending=True)
# handles params meta-command
def modify_tackons(self, args=None):
if args and len(args) > 0:
# args will be param=[value]
if not "=" in args: # it's not foo=bar it's just foo
self.tackons[args] = ""
else:
a = args.split("=", 1)
key = a[0]
if len(a) > 1:
value = a[1]
if len(value) > 0:
self.tackons[key] = value
elif key in self.tackons:
del self.tackons[key] # if no value provided, delete
else:
# print send tackons
self.logger.print_tackons(self.tackons.items())
def modify_cookies(self, args=None):
if args and len(args) > 0:
# args will be cookie=[value]
cookie = None
if not self.url.netloc in self.cookies:
cookie = Cookie.SimpleCookie()
self.cookies[self.url.netloc] = cookie
else:
cookie = self.cookies[self.url.netloc]
if args and len(args) > 0:
# cookie will be cookie=[value]
a = args.split("=", 1)
key = a[0]
if len(a) > 1:
value = a[1]
if len(value) > 0:
cookie[key] = value
else:
for morsel in cookie.values():
if morsel.key == key:
del cookie[morsel.key]
else:
self.logger.print_error("Invalid syntax.")
elif self.url.netloc in self.cookies:
self.logger.print_cookies(self.cookies[self.url.netloc])
# changes the current host
def open_host(self, url=None):
if url:
self.init_host(url)
# handles cd <path> command
def set_path(self, path):
path = path.split("?")[0] # chop off any query params
if path == "..":
path = "".join(self.path.rsplit("/", 1)[:1])
self.path = path if path else "/"
def set_debuglevel(self, level=None):
if not level:
self.logger.print_text(str(self.args.debuglevel))
else:
try:
self.args.debuglevel = int(level)
except:
pass
# converts tackon dict to query params
def dict_to_query(self, map):
l = []
for k, v in sorted(map.items()):
s = k
if(v):
s += "=" + str(v)
l.append(s)
return "&".join(l)
# combine two query strings into one
def combine_queries(self, a, b):
s = ""
if a and len(a) > 0:
s = a
if b and len(b) > 0:
s += "&"
if b and len(b) > 0:
s += b
return s
# modifies the path for tackon query params
def mod_path(self, path, query=None):
q = self.combine_queries(
query, self.dict_to_query(self.tackons))
if len(q) > 0:
return path + "?" + q
else:
return path
# readline complete handler
def complete(self, text, state):
match = [s for s in self.dispatch.keys() if s
and s.startswith(text)] + [None]
return match[state]
# read lines of input for POST/PUT
def input_body(self):
list = []
while True:
line = raw_input("... ")
if len(line) == 0:
break
list.append(line)
# join list to form string
params = "".join(list)
if params[:2] == "@{": # magic JSON -> urlencode invoke char
params = self.json_to_urlencode(params[1:])
return params
# converts JSON to url encoded for easier posting forms
def json_to_urlencode(self, json_string):
params = None
try:
o = json.loads(json_string)
params = urlencode(o)
except ValueError:
self.logger.print_error("Malformed JSON.")
return params
@property
def prompt(self):
host = None
if "@" in self.url.netloc: # hide password in prompt
split = re.split("@|:", self.url.netloc)
host = split[0] + "@" + split[-1]
else:
host = self.url.netloc
return "{0}:{1}> ".format(host, self.path)
def input_loop(self):
command = None
while True:
try:
# a valid command line will be <command> [path] [| filter]
input = raw_input(self.prompt).split()
# ignore blank input
if not input or len(input) == 0:
continue
# command will be element 0 in the array from split
command = input.pop(0).lower()
if command in self.dispatch:
# push arguments to the stack for command
args = self.parse_args(input, command)
# invoke command via dispatch table
try:
self.dispatch[command](*args)
except Exception as e:
self.logger.print_error("Error: {0}".format(e))
else:
self.logger.print_error("Invalid command.")
except (EOFError, KeyboardInterrupt):
break
print
self.exit()
# parses input to set up the call stack for dispatch commands
def parse_args(self, args, command):
stack = []
# ignore meta-commands
if command not in self.meta_commands:
path = None
pipe = None
if len(args) > 0:
# element 0 of args array will be the path element
path = args.pop(0)
# there's a pipe in my path!
# user didn't use whitespace between path and pipe character
# also accounts for if the user did not supply a path
if "|" in path:
s = path.split("|", 1)
path = s.pop(0)
args.insert(0, "".join(s))
# pipe, if exists, will be first element in array now
if len(args) > 0:
pipe = " ".join(args).strip()
if pipe[0] == "|":
pipe = pipe[1:]
# account for requests from relative dirs
if path and not path[0] in "/.":
path = "{0}{1}{2}".format(
self.path,
"/" if self.path[-1] != "/" else "",
path)
# push the path on the stack for command method
# if it's empty the user did not supply one so use self.path
if path:
query = None
a = path.split("?") # chop query params
if len(a) > 1:
path = a[0]
query = a[1]
stack.append(self.mod_path(path, query))
else:
stack.append(self.mod_path(self.path, self.query))
if pipe:
stack.append(pipe)
else:
if len(args) > 0:
# meta-commands to their own arg parsing
stack.append(" ".join(args))
return stack
def exit(self, args=None):
readline.write_history_file(self.history_file)
sys.exit(0)