-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.py
254 lines (189 loc) · 7.65 KB
/
proxy.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
#!/usr/bin/python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
# Run this example with:
# python proxy.py
#
# Then configure your web browser to use localhost:8080 as a proxy and
# visit a URL. This proxy is proxying the connection to that URL's
# host.
from random import randint
import sys
import thread
import urlparse
from StringIO import StringIO
from scapy.all import sniff, NoPayload
from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver
from twisted.web import proxy, http
from config import *
from utils import *
### Global Variables ########################################################
global SRC
SRC = None
global active_clients
active_clients = {} # port -> clientFactory
global send_proxy
send_proxy = None
### Receiver ################################################################
def process_packet(pkt):
tcp = pkt.payload
while (not isinstance(tcp, NoPayload)) and (tcp.name != 'TCP'):
tcp = tcp.payload
if isinstance(tcp, NoPayload): return pkt.summary()
global active_clients
our_sport = tcp.dport
if not our_sport in active_clients: return pkt.summary()
send_proxy_client = active_clients[our_sport]
send_proxy_client.received_from_sniff(tcp)
return pkt.summary()
### Send Proxy ##############################################################
class SemiTransport(StringIO):
def __init__(self, *args, **kwargs):
StringIO.__init__(self, *args, **kwargs)
self.disconnecting = False
class SendProxyConnection(LineReceiver):
def connectionLost(self, reason):
print "Connection lost!"
print reason
sys.exit(2)
def lineReceived(self, line):
parts = line.split()
if parts[0] == "HELLO":
global SRC
SRC = parts[1]
print "Connected to the proxy server as (%s)" % SRC
else:
port = int(parts[0])
global active_clients
active_clients[port].received_from_send_proxy(parts[1:])
class SendProxyConnectionFactory(ClientFactory):
def clientConnectionFailed(self, connector, reason):
print "Connection failed!"
print reason
sys.exit(1)
def buildProtocol(self, addr):
global send_proxy
send_proxy = SendProxyConnection()
return send_proxy
class HttpSendProxyClient(http.HTTPClient):
def __init__(self,
src, dst, sport, dport,
command, rest, version,
headers, data, father):
self.src = src
self.dst = dst
self.sport = sport
self.dport = dport
self.father = father
self.command = command
self.rest = rest
if "proxy-connection" in headers:
del headers["proxy-connection"]
headers["connection"] = "close"
headers.pop('keep-alive', None)
self.headers = headers
self.data = data
self.version = version
self.response = {}
self.has_sent_request = False
self.transport = SemiTransport()
self._finished = False
# Drop packets generated by OS related to our connection
# (To avoid connection reset)
sys_command("iptables -A OUTPUT -s %s -d %s -p tcp --sport %d --dport %d -j DROP" % (self.src, self.dst, self.sport, self.dport))
global send_proxy
send_proxy.sendLine("CONNECT\t%s\t%s\t%d\t%d" % (src, dst, sport, dport))
def handleStatus(self, version, code, message):
self.father.setResponseCode(int(code), message)
def handleResponsePart(self, buffer):
self.father.write(buffer)
def handleResponseEnd(self):
"""
Finish the original request, indicating that the response has been
completely written to it, and disconnect the outgoing transport.
"""
if not self._finished:
self._finished = True
self.father.finish()
self.transport.close()
def received_from_sniff(self, tcp_pkt):
if not self.has_sent_request:
self.sendCommand(self.command, self.rest)
for header, value in self.headers.items():
self.sendHeader(header, value)
self.endHeaders()
self.transport.write(self.data)
req = self.transport.getvalue()
if '\t' in req:
print "----------------------------------------------------"
print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
print "----------------------------------------------------"
sys.exit(3)
else:
req = req.replace('\n', '\t')
print "ACK\t%d\t%d" % (self.sport, tcp_pkt.seq + 1)
send_proxy.sendLine("ACK\t%d\t%d" % (self.sport, tcp_pkt.seq + 1))
print "PUSH\t%d\t%d\t%s" % (self.sport, tcp_pkt.seq, req)
send_proxy.sendLine("PUSH\t%d\t%d\t%s" % (self.sport, tcp_pkt.seq, req))
self.has_sent_request = True
else:
self.response[tcp_pkt.seq] = tcp_pkt.payload
my_ack = tcp_pkt.seq + len(tcp_pkt.payload)
if tcp_pkt.flags % 2 == 1:
print "CLOSE\t%d\t%d" % (self.sport, my_ack)
send_proxy.sendLine("CLOSE\t%d\t%d" % (self.sport, my_ack))
self.dataReceived(combine(self.response))
else:
print "ACK\t%d\t%d" % (self.sport, my_ack)
send_proxy.sendLine("ACK\t%d\t%d" % (self.sport, my_ack))
def received_from_send_proxy(self, parts):
if parts[0] == "CLOSE":
# Undo
sys_command("iptables -D OUTPUT -s %s -d %s -p tcp --sport %d --dport %d -j DROP" % (self.src, self.dst, self.sport, self.dport))
### HTTP Proxy ##############################################################
class HttpProxyRequest(proxy.ProxyRequest):
protocols = {'http': HttpSendProxyClient}
def process(self):
parsed = urlparse.urlparse(self.uri)
protocol = parsed[0]
if not protocol in self.protocols:
self.setResponseCode(501, "Gateway error")
self.responseHeaders.addRawHeader("Content-Type", "text/html")
self.write("<H1>Protocol not supported</H1>")
self.finish()
return #XXX
host = parsed[1]
port = self.ports[protocol]
if ':' in host:
host, port = host.split(':')
port = int(port)
rest = urlparse.urlunparse(('', '') + parsed[2:])
if not rest:
rest = rest + '/'
headers = self.getAllHeaders().copy()
if 'host' not in headers:
headers['host'] = host
self.content.seek(0, 0)
s = self.content.read()
class_ = self.protocols[protocol]
while True:
sport = randint(49000, 50000)
global active_clients
if sport not in active_clients:
global SRC
active_clients[sport] = class_(SRC, host, sport, port,
self.method, rest, self.clientproto,
headers, s, self)
break
class HttpProxy(proxy.Proxy):
requestFactory = HttpProxyRequest
class ProxyFactory(http.HTTPFactory):
def buildProtocol(self, addr):
return HttpProxy()
### Start! ##################################################################
thread.start_new_thread(sniff, (), {'prn': process_packet, 'filter': "tcp"})
reactor.connectTCP(SEND_PROXY_ADDR, SEND_PROXY_PORT, SendProxyConnectionFactory())
reactor.listenTCP(HTTP_PROXY_PORT, ProxyFactory())
reactor.run()