-
Notifications
You must be signed in to change notification settings - Fork 1
/
pfi.py
executable file
·591 lines (528 loc) · 21.7 KB
/
pfi.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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
#!/usr/bin/python2.5
# PFI (Port Forwarding Interceptor)
#
#
# Stephen A. Ridley
# stephen@xipiter.com Dec 2008
from Tkinter import *
import tkFont #for fixed-width windows font problems
from tkMessageBox import *
from tkFileDialog import *
from threading import Thread
import socket
import asyncore
import sys
import os
import time
from binascii import hexlify
from binascii import unhexlify
class WindowList:
def __init__(self):
self.dict = {}
self.callbacks = []
def add(self, window):
window.after_idle(self.call_callbacks)
self.dict[str(window)] = window
def delete(self, window):
try:
del self.dict[str(window)]
except KeyError:
# Sometimes, destroy() is called twice
pass
self.call_callbacks()
def add_windows_to_menu(self, menu):
list = []
for key in self.dict.keys():
window = self.dict[key]
try:
title = window.get_title()
except TclError:
continue
list.append((title, window))
list.sort()
for title, window in list:
menu.add_command(label=title, command=window.wakeup)
def register_callback(self, callback):
self.callbacks.append(callback)
def unregister_callback(self, callback):
try:
self.callbacks.remove(callback)
except ValueError:
pass
def call_callbacks(self):
for callback in self.callbacks:
try:
callback()
except:
print "warning: callback failed in WindowList", \
sys.exc_type, ":", sys.exc_value
registry = WindowList()
add_windows_to_menu = registry.add_windows_to_menu
register_callback = registry.register_callback
unregister_callback = registry.unregister_callback
class ListedToplevel(Toplevel):
def __init__(self, master, **kw):
Toplevel.__init__(self, master, kw)
registry.add(self)
self.focused_widget = self
def destroy(self):
registry.delete(self)
Toplevel.destroy(self)
# If this is Idle's last window then quit the mainloop
# (Needed for clean exit on Windows 98)
if not registry.dict:
self.quit()
def update_windowlist_registry(self, window):
registry.call_callbacks()
def get_title(self):
# Subclass can override
return self.wm_title()
def wakeup(self):
try:
if self.wm_state() == "iconic":
self.wm_withdraw()
self.wm_deiconify()
self.tkraise()
self.focused_widget.focus_set()
except TclError:
# This can happen when the window menu was torn off.
# Simply ignore it.
pass
class MainWindow(Tk):
"""
This is just a small container class for the main Tk() window
class
"""
from Tkinter import Toplevel
def __init__(self):
Tk.__init__(self)
self.title(string="...ooo000OOO PFI (Port Forwarding Interceptor) OOO000ooo...")
self.out_win = OutputWindow(root=self)
self.stdout = self.out_win.stdout
self.stderr = self.out_win.stderr
class SecondaryWindow(Toplevel):
"""
This is a small container class for Toplevel type secondary windows.
"""
def __init__(self, parent=None):
Toplevel.__init__(self)
self.title(string="...ooo000OOO TRAFFIC EDITOR WINDOW OOO000ooo...")
self.editor_win = EditorWindow(root=self)
self.stdout = self.editor_win.stdout
self.stderr = self.editor_win.stderr
class EditorWindow:
"""
"""
def __init__(self, root=None):
self.root = root
self.top = top = root
self.tv_frame = tv_frame = Frame(top)
if os.name in ('nt', 'win', 'windows'): #Fix for windows fixed width font prob.
self.tv = tv = Text(tv_frame, name='text', padx=5, wrap='char',
foreground="black",
background="white",
font=tkFont.Font(family="FixedSys", size=8),
highlightcolor="white",
highlightbackground="purple",
width = 80,
height = 25)
else:
self.tv = tv = Text(tv_frame, name='text', padx=5, wrap='char',
foreground="black",
background="white",
highlightcolor="white",
highlightbackground="purple",
width = 80,
height = 25)
# state = 'disabled')
self.tv.bind("<Key>", self.key_handler)
self.vbar = vbar = Scrollbar(tv_frame, name='vbar')
vbar['command'] = tv.yview
vbar.pack(side=RIGHT, fill=Y)
tv['yscrollcommand'] = vbar.set
fontWeight = 'normal'
pass_button = Button(tv_frame, text="I am done modifying the traffic, pass it along!",
state="active", command=self.use_edit, activeforeground="green")
cancel_button = Button(tv_frame, text="Nevermind! Just pass the traffic as it was before I messed with it.",
state="active", command=self.cancel_edit, activeforeground="red")
cancel_button.pack(side=BOTTOM, fill=X)
pass_button.pack(side=BOTTOM, fill=X)
#probably should perform tv.config() here
tv_frame.pack(side=LEFT, fill=BOTH, expand=1)
tv.pack(side=TOP, fill=BOTH, expand=1)
tv.focus_set()
self.stderr = PseudoFile(self)
self.stdout = PseudoFile(self)
self.bufstate = 0 # 0 is nothing is ready yet
# 1 is that data is ready and can be read from
# self.textbuf
# 2 is that editting was cancelled
self.textbuf=""
def oprint(self, text_to_print):
"""
This function will be exposed externally to allow others to
print to our window.
"""
self.tv.insert(END, text_to_print)
def use_edit(self):
self.textbuf = self.tv.get("1.0", END)
self.bufstate = 1
self.clear_scrollback()
def cancel_edit(self):
self.textbuf = ""
self.bufstate = 2
self.clear_scrollback()
def clear(self):
self.bufstate = 0
self.textbuf = ""
self.clear_scrollback()
def key_handler(self, event):
"""
"""
pass
def clear_scrollback(self):
"""
Clear the scrollback of the text window.
"""
self.tv.delete("1.0", END)
class OutputWindow:
"""
"""
def __init__(self, root=None):
self.root = root
self.top = top = root
self.tv_frame = tv_frame = Frame(top)
if os.name in ('nt', 'win', 'windows'): #Fix for windows fixed width font prob.
self.tv = tv = Text(tv_frame, name='text', padx=5, wrap='char',
foreground="black",
background="white",
font=tkFont.Font(family="FixedSys", size=8),
highlightcolor="white",
highlightbackground="purple",
width = 80,
height = 25)
else:
self.tv = tv = Text(tv_frame, name='text', padx=5, wrap='char',
foreground="black",
background="white",
highlightcolor="white",
highlightbackground="purple",
width = 80,
height = 25)
self.tv.bind("<Key>", self.key_handler)
self.vbar = vbar = Scrollbar(tv_frame, name='vbar')
vbar['command'] = tv.yview
vbar.pack(side=RIGHT, fill=Y)
tv['yscrollcommand'] = vbar.set
fontWeight = 'normal'
def_trigger_button = Button(tv_frame, text="Select a file to execute as traffic comes in.",
state="active", command=self.set_plugin_trigger)
save_buffer_button = Button(tv_frame, text="Save scrollback buffer to file.",
state="active", command=self.save_buffer_to_file)
clear_button = Button(tv_frame, text="Clear scrollback buffer",
state="active", command=self.clear_scrollback)
def_trigger_button.pack(side=BOTTOM, fill=X)
save_buffer_button.pack(side=BOTTOM, fill=X)
clear_button.pack(side=BOTTOM, fill=X)
self.li = IntVar()
self.ri = IntVar()
remote_intercept = Checkbutton(tv_frame, text="Intercept on Remote Side?", variable=self.ri, onvalue=1, offvalue=0)
local_intercept = Checkbutton(tv_frame, text="Intercept on Local Side?", variable=self.li, onvalue=1, offvalue=0)
remote_intercept.pack(side=BOTTOM)
local_intercept.pack(side=BOTTOM)
#probably should perform tv.config() here
tv_frame.pack(side=LEFT, fill=BOTH, expand=1)
tv.pack(side=TOP, fill=BOTH, expand=1)
tv.focus_set()
self.stderr = PseudoFile(self)
self.stdout = PseudoFile(self)
self.plugin_filename = ""
# if os.name in ('nt', 'win', 'windows'):
# self.tmpdir = os.getenv("TEMP")
# else:
# self.tmpdir = os.getenv("TMPDIR")
# if self.tmpdir == None: # that environment variable didnt exist.
# showinfo("TEMP DIRECTORY NOT FOUND", "A directory suitable for my temp files could not be found, please point me at one. Thanks.")
# self.tmpdir = askdirectory()
# showinfo("TEMP DIRECTORY SELECTED", ("Using %s as my temp directory" % self.tmpdir))
def oprint(self, text_to_print):
"""
This function will be exposed externally to allow others to
print to our window.
"""
self.tv.insert(END, text_to_print)
def key_handler(self, event):
"""
"""
pass
def clear_scrollback(self):
"""
Clear the scrollback of the text window.
"""
self.tv.delete("1.0", END)
def set_plugin_trigger(self):
message = """
HOW PLUGINS WORK:
After this informational window you will be prompted to select a file.
This file will be executed with the same environment as PFI
and receive the bytes intercepted via STDIN in raw byte format.
The data "returned" from your plugin is passed back to PFI
on STDOUT and must also be in raw byte format
your_plugin.[sh,exe,bat,py,rb,whatever] <bytes written>
<num bytes> : The number of bytes that the plugin can
anticipate will be passed to it via STDIN
"""
showinfo("A BIT ABOUT HOW THIS WORKS", message)
f_h = askopenfile('r')
self.plugin_filename = f_h.name
message = "Passing all intercepted data to: %s" % f_h.name
showinfo("EXECUTABLE SELECTED", message)
f_h.close()
def save_buffer_to_file(self):
f_h = asksaveasfile('w')
if f_h is not None:
header = "\n=================\n PFI Log\n%s\n=================\n" % (time.asctime())
f_h.write(header)
data = self.tv.get("1.0", END)
f_h.write(data)
f_h.flush()
f_h.close()
message = ("Wrote %d bytes from scrollback buffer into logfile: %s") % (len(data), f_h.name)
showinfo("LOG FILE WRITTEN", message)
class PseudoFile:
"""
This is used to overload sys.stderr and sys.stdout.
the object reference passed in on "window_obj" must
have an "oprint" method.
"""
def __init__(self, window_obj, encoding=None):
self.encoding = encoding
self.window_obj = window_obj
def write(self, s):
self.window_obj.oprint(s)
def writelines(self, l):
map(self.write, l)
def flush(self):
pass
def isatty(self):
return True
class VisualizerWindow:
"""
This is the window that displays the TreeView of the compiled
Session object.
"""
def __init__(self, root=None):
self.root = root
self.vbar = vbar = Scrollbar(name='vbar')
self.top = top = root
self.tv_frame = tv_frame = Frame(top)
class forwarder(asyncore.dispatcher):
def __init__(self, ip, port, remoteip,remoteport,rootWindow, outputWindow, backlog=5):
asyncore.dispatcher.__init__(self)
self.remoteip=remoteip
self.remoteport=remoteport
self.localip = ip
self.localport = port
self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((ip,port))
self.listen(backlog)
self.rootWin = rootWindow
self.outputWin = outputWindow
def handle_accept(self):
conn, addr = self.accept()
# print '--- Connect --- '
print "Incoming connect on %s:%d." % (self.localip, self.localport)
sender(receiver(conn, self.rootWin, self.outputWin),self.remoteip,self.remoteport, self.rootWin, self.outputWin)
class receiver(asyncore.dispatcher):
def __init__(self,conn, rootWin, outputWin):
asyncore.dispatcher.__init__(self,conn)
self.from_remote_buffer=''
self.to_remote_buffer=''
self.sender=None
self.rootWin = rootWin
self.outputWin = outputWin
self.conn = conn
def handle_connect(self):
pass
def handle_read(self):
read = self.recv(4096)
tmp_buf = ""
saved_buf = read #used if the user edits
if (self.rootWin.out_win.li.get() == 1) and (self.rootWin.out_win.plugin_filename == ""): #Checkbox value
print "THE FOLLOWING %d BYTES WERE INTERCEPTED FROM THE LOCAL SIDE!." % (len(read))
print "(See the Editor Window to edit these bytes.)"
hexdump(read)
for byte in read:
tmp_buf+='\\'+'x'+hexlify(byte)
self.outputWin.editor_win.oprint(tmp_buf)
while self.outputWin.editor_win.bufstate not in (1,2):
pass
if (self.outputWin.editor_win.bufstate == 1):
print repr(self.outputWin.editor_win.textbuf.replace('\\x',''))
self.from_remote_buffer += unhexlify(self.outputWin.editor_win.textbuf.replace('\\x','').strip())
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
print "\nSending modified buffer."
hexdump(self.from_remote_buffer)
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
self.outputWin.editor_win.clear()
if self.outputWin.editor_win.bufstate == 2: #the user cancelled
self.from_remote_buffer += read
self.outputWin.editor_win.clear()
elif (self.rootWin.out_win.plugin_filename != ""):
print "%d BYTES WERE INTERCEPTED FROM THE LOCAL SIDE!." % (len(read))
print "Passing to the plugin %s" % (self.rootWin.out_win.plugin_filename)
h_in, h_out = os.popen2(self.rootWin.out_win.plugin_filename, 'b')
h_in.write(read)
h_in.close()
somedataread = False
fromplugin = ""
while 1:
try:
fromplugin+=h_out.next()
if len(fromplugin) > 0: #that means *some* data has been read
somedataread = True
except StopIteration: #this exception will hit until there is data ready
#we want to wait for it to hit *after* we've read
#some data, indicating that there is no more data ready
if somedataread == True:
print ("Got %d bytes returned from plugin" % len(fromplugin))
break
# showinfo("PLUGIN DATA RECEIVED!", "Got %d bytes back from plugin." % len(fromplugin))
hexdump(fromplugin)
self.from_remote_buffer += fromplugin
else:
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
hexdump(read)
self.from_remote_buffer += read
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
def writable(self):
return (len(self.to_remote_buffer) > 0)
def handle_write(self):
tmp_buf = ""
saved_buf = self.to_remote_buffer #used if the user edits
if (self.rootWin.out_win.ri.get() == 1) and (self.rootWin.out_win.plugin_filename == ""): #Checkbox value
print "THE FOLLOWING %d BYTES WERE INTERCEPTED FROM THE REMOTE SIDE!." % (len(self.to_remote_buffer))
print "(See the Editor Window to edit these bytes.)"
hexdump(self.to_remote_buffer)
for byte in self.to_remote_buffer:
tmp_buf+='\\'+'x'+hexlify(byte)
self.outputWin.editor_win.oprint(tmp_buf)
while self.outputWin.editor_win.bufstate not in (1,2):
pass
if (self.outputWin.editor_win.bufstate == 1):
print repr(self.outputWin.editor_win.textbuf.replace('\\x',''))
self.to_remote_buffer = unhexlify(self.outputWin.editor_win.textbuf.replace('\\x','').strip())
print "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
print "\nSending modified buffer."
hexdump(self.to_remote_buffer)
print "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
sent = self.send(self.to_remote_buffer)
self.outputWin.editor_win.clear()
if self.outputWin.editor_win.bufstate == 2: #the user cancelled
sent = self.send(self.to_remote_buffer)
self.outputWin.editor_win.clear()
elif (self.rootWin.out_win.plugin_filename != ""):
print "%d BYTES WERE INTERCEPTED FROM THE REMOTE SIDE!." % (len(self.to_remote_buffer))
print "Passing to the plugin %s" % (self.rootWin.out_win.plugin_filename)
h_in, h_out = os.popen2(self.rootWin.out_win.plugin_filename, 'b')
h_in.write(self.to_remote_buffer)
h_in.close()
somedataread = False
fromplugin = ""
while 1:
try:
fromplugin+=h_out.next()
if len(fromplugin) > 0: #that means *some* data has been read
somedataread = True
except StopIteration: #this exception will hit until there is data ready
#we want to wait for it to hit *after* we've read
#some data, indicating that there is no more data ready
if somedataread == True:
print ("Got %d bytes returned from plugin, data from PLUGIN below:" % len(fromplugin))
break
# showinfo("PLUGIN DATA RECEIVED!", "Got %d bytes back from plugin." % len(fromplugin))
hexdump(fromplugin)
sent = self.send(self.to_remote_buffer)
else:
print "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
hexdump(self.to_remote_buffer)
sent = self.send(self.to_remote_buffer)
print "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
#print '%04i <--'%sent
self.to_remote_buffer = self.to_remote_buffer[sent:]
def handle_close(self):
self.close()
if self.sender:
self.sender.close()
def hexdump(src, length=16):
N=0; result=''
FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)])
while src:
s,src = src[:length],src[length:]
hexa = ' '.join(["%02X"%ord(x) for x in s])
s = s.translate(FILTER)
result += "%08X: %-*s |%s|\n" % (N, length*3, hexa, s)
N+=length
print result
class sender(asyncore.dispatcher):
"""
This handles the remote connection.
"""
def __init__(self, receiver, remoteaddr,remoteport, rootWin, outputWin):
asyncore.dispatcher.__init__(self)
self.receiver=receiver
receiver.sender=self
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((remoteaddr, remoteport))
self.rootWin = rootWin
self.outputWin = outputWin
def handle_connect(self):
pass
def handle_read(self):
read = self.recv(4096)
# print '<-- %04i'%len(read)
self.receiver.to_remote_buffer += read
def writable(self):
return (len(self.receiver.from_remote_buffer) > 0)
def handle_write(self):
sent = self.send(self.receiver.from_remote_buffer)
# print '--> %04i'%sent
self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:]
def handle_close(self):
self.close()
self.receiver.close()
if __name__=='__main__':
import optparse
parser = optparse.OptionParser()
parser.add_option(
'-l','--local-ip',
dest='local_ip',default='127.0.0.1',
help='Local IP address to bind to')
parser.add_option(
'-p','--local-port',
type='int',dest='local_port',default=80,
help='Local port to bind to')
parser.add_option(
'-r','--remote-ip',dest='remote_ip',
help='Local IP address to bind to')
parser.add_option(
'-P','--remote-port',
type='int',dest='remote_port',default=80,
help='Remote port to bind to')
if len(sys.argv) == 1:
sys.argv.append("--help")
options, args = parser.parse_args()
rootWindow = MainWindow()
outputWindow = SecondaryWindow()
#We overload the normal stdout/stderr to go to our
#output window
global saved_stderr, saved_stdout
saved_stderr = sys.stderr
saved_stdout = sys.stdout
sys.stderr = rootWindow.stderr
sys.stdout = rootWindow.stdout
forwarder(options.local_ip,options.local_port,options.remote_ip,options.remote_port, rootWindow, outputWindow)
Thread(target=asyncore.loop, args=[]).start()
rootWindow.mainloop()
rootWindow.destroy()