-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_server.py
More file actions
283 lines (239 loc) · 11.6 KB
/
Copy pathproxy_server.py
File metadata and controls
283 lines (239 loc) · 11.6 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
'''
Proxy Server in Python.
Features: HTTP/HTTPS requests handling
Caching works fine for HTTPS but cannot render webpage properly for HTTP
Logging
Websites Blacklisting
IP Blacklisting
'''
import socket, sys, datetime, time
from _thread import start_new_thread
class Server:
# Constructors initializing basic architecture
def __init__(self, blacklisted_ips=False, blacklist_websites=False):
self.max_conn = 0
self.buffer_size = 0
self.socket = 0
self.port = 0
self.blacklisted_ip_lookup = blacklisted_ips
self.blacklist_websites_lookup = blacklist_websites
# Function to write log
def write_log(self, msg):
with open("log/log.txt", "a+") as file:
file.write(msg)
file.write("\n")
# Helper Function to get Time Stamp
def getTimeStampp(self):
return "[" + str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')) + "]"
# Function which triggers the server
def start_server(self, conn=5, buffer=4096, port=8080):
try:
self.write_log(self.getTimeStampp() + " \n\nStarting Server\n\n")
self.listen(conn, buffer, port)
except KeyboardInterrupt:
print(self.getTimeStampp() + " Interrupting Server.")
self.write_log(self.getTimeStampp() + " Interrupting Server.")
time.sleep(.5)
finally:
print(self.getTimeStampp() + " Stopping Server...")
self.write_log(self.getTimeStampp() + " Stopping Server")
sys.exit()
# Listener for incoming connections
def listen(self, No_of_conn, buffer, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))
s.listen(No_of_conn)
print(self.getTimeStampp() + " Listening...")
self.write_log(
self.getTimeStampp() + " Initializing Sockets [ready] Binding Sockets [ready] Listening...")
except:
print(self.getTimeStampp() + " Error: Cannot start listening...")
self.write_log(self.getTimeStampp() + " Error: Cannot start listening...")
sys.exit(1)
while True:
# Try to accept new connections and read the connection data in another thread
try:
conn, addr = s.accept()
# print(self.getTimeStampp() + " Request received from: ", addr)
self.write_log(
self.getTimeStampp() + " Request received from: " + addr[0] + " at port: " + str(addr[1]))
start_new_thread(self.connection_read_request, (conn, addr, buffer))
except Exception as e:
print(self.getTimeStampp() + " Error: Cannot establish connection..." + str(e))
self.write_log(self.getTimeStampp() + " Error: Cannot establish connection..." + str(e))
sys.exit(1)
s.close()
# helper Function to generate header to send response in HTTPS connections
def generate_header_lines(self, code, length):
h = ''
if code == 200:
# Status code
h = 'HTTP/1.1 200 OK\n'
h += 'Server: Jarvis\n'
elif code == 404:
# Status code
h = 'HTTP/1.1 404 Not Found\n'
h += 'Date: ' + time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + '\n'
h += 'Server: Jarvis\n'
h += 'Content-Length: ' + str(length) + '\n'
h += 'Connection: close\n\n'
return h
# Function to read request data
def connection_read_request(self, conn, addr, buffer):
# Try to split necessary info from the header
try:
request = conn.recv(buffer)
header = request.split(b'\n')[0]
requested_file = request
requested_file = requested_file.split(b' ')
url = header.split(b' ')[1]
# Stripping Port and Domain
hostIndex = url.find(b"://")
if hostIndex == -1:
temp = url
else:
temp = url[(hostIndex + 3):]
portIndex = temp.find(b":")
serverIndex = temp.find(b"/")
if serverIndex == -1:
serverIndex = len(temp)
# If no port in header i.e, if http connection then use port 80 else the port in header
webserver = ""
port = -1
if (portIndex == -1 or serverIndex < portIndex):
port = 80
webserver = temp[:serverIndex]
else:
port = int((temp[portIndex + 1:])[:serverIndex - portIndex - 1])
webserver = temp[:portIndex]
# Stripping requested file to see if it exists in cache
requested_file = requested_file[1]
print("Requested File ", requested_file)
# Stripping method to find if HTTPS (CONNECT) or HTTP (GET)
method = request.split(b" ")[0]
# Checking for blacklisted ips
if addr[0] in self.blacklisted_ip_lookup:
print(self.getTimeStampp() + " IP Blacklisted")
self.write_log(self.getTimeStampp() + " IP Blacklisted")
conn.close()
# Checking for blacklisted domains
target = webserver
target = target.replace(b"http://", b"").split(b".")[1].decode("utf-8")
try:
if target in self.blacklist_websites_lookup:
print(self.getTimeStampp() + " Website Blacklisted")
self.write_log(self.getTimeStampp() + " Website Blacklisted")
conn.close()
except:
pass
# If method is CONNECT (HTTPS)
if method == b"CONNECT":
print(self.getTimeStampp() + " CONNECT Request")
self.write_log(self.getTimeStampp() + " HTTPS Connection request")
self.https_proxy(webserver, port, conn, request, addr, buffer, requested_file)
# If method is GET (HTTP)
else:
print(self.getTimeStampp() + " GET Request")
self.write_log(self.getTimeStampp() + " HTTP Connection request")
self.http_proxy(webserver, port, conn, request, addr, buffer, requested_file)
except Exception as e:
# print(self.getTimeStampp() + " Error: Cannot read connection request..." + str(e))
# self.write_log(self.getTimeStampp() + " Error: Cannot read connection request..." + str(e))
return
# Function to handle HTTP Request
def http_proxy(self, webserver, port, conn, request, addr, buffer_size, requested_file):
# Stripping file name
requested_file = requested_file.replace(b".", b"_").replace(b"http://", b"_").replace(b"/", b"")
# Trying to find in cache
try:
print(self.getTimeStampp() + " Searching for: ", requested_file)
print(self.getTimeStampp() + " Cache Hit")
file_handler = open(b"cache/" + requested_file, 'rb')
self.write_log(self.getTimeStampp() + " Cache Hit")
response_content = file_handler.read()
file_handler.close()
response_headers = self.generate_header_lines(200, len(response_content))
conn.send(response_headers.encode("utf-8"))
time.sleep(1)
conn.send(response_content)
conn.close()
# If no cache hit, request from web
except Exception as e:
print(e)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((webserver, port))
s.send(request)
print(self.getTimeStampp() + " Forwarding request from ", addr, " to ", webserver)
self.write_log(
self.getTimeStampp() + " Forwarding request from " + addr[0] + " to host..." + str(webserver))
# Makefile for socket
file_object = s.makefile('wb', 0)
file_object.write(b"GET " + b"http://" + requested_file + b" HTTP/1.0\n\n")
# Read the response into buffer
file_object = s.makefile('rb', 0)
buff = file_object.readlines()
temp_file = open(b"cache/" + requested_file, "wb+")
for i in range(0, len(buff)):
temp_file.write(buff[i])
conn.send(buff[i])
print(self.getTimeStampp() + " Request of client " + str(addr) + " completed...")
self.write_log(self.getTimeStampp() + " Request of client " + str(addr[0]) + " completed...")
s.close()
conn.close()
except Exception as e:
print(self.getTimeStampp() + " Error: forward request..." + str(e))
self.write_log(self.getTimeStampp() + " Error: forward request..." + str(e))
return
# Function to handle HTTPS Connection
def https_proxy(self, webserver, port, conn, request, addr, buffer_size, requested_file):
# Stripping for filename
requested_file = requested_file.replace(b".", b"_").replace(b"http://", b"_").replace(b"/", b"")
# Trying to find in cache
try:
print(self.getTimeStampp() + " Searching for: ", requested_file)
file_handler = open(b"cache/" + requested_file, 'rb')
print("\n")
print(self.getTimeStampp() + " Cache Hit\n")
self.write_log(self.getTimeStampp() + " Cache Hit\n")
response_content = file_handler.read()
file_handler.close()
response_headers = self.generate_header_lines(200, len(response_content))
conn.send(response_headers.encode("utf-8"))
time.sleep(1)
conn.send(response_content)
conn.close()
# If no Cache Hit, request data from web
except:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# If successful, send 200 code response
s.connect((webserver, port))
reply = "HTTP/1.0 200 Connection established\r\n"
reply += "Proxy-agent: Jarvis\r\n"
reply += "\r\n"
conn.sendall(reply.encode())
except socket.error as err:
pass
# print(self.getTimeStampp() + " Error: No Cache Hit in HTTPS because " + str(err))
# self.write_log(self.getTimeStampp() + " Error: No Cache Hit in HTTPS beacuse" + str(err))
conn.setblocking(0)
s.setblocking(0)
print(self.getTimeStampp() + " HTTPS Connection Established")
self.write_log(self.getTimeStampp() + " HTTPS Connection Established")
while True:
try:
request = conn.recv(buffer_size)
s.sendall(request)
except socket.error as err:
pass
try:
reply = s.recv(buffer_size)
conn.sendall(reply)
except socket.error as e:
pass
if __name__ == "__main__":
# Provide a list of ips and domains if necessary to add in blacklist. Websites need only the domains without 'www.' and '.com'
server = Server(['127.0.0.81'],['facebook'])
server.start_server()