-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy
More file actions
206 lines (179 loc) · 5.82 KB
/
proxy
File metadata and controls
206 lines (179 loc) · 5.82 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
#!/usr/bin/env python3
import socket
import threading
import select
import signal
import sys
import time
import getopt
# Listen
LISTENING_ADDR = '127.0.0.1'
LISTENING_PORT = 700
if sys.argv[1:]:
LISTENING_PORT = int(sys.argv[1])
# Pass
PASS = ''
# CONST
BUFLEN = 4096 * 4
TIMEOUT = 60
DEFAULT_HOST = '127.0.0.1:111'
RESPONSE = b'HTTP/1.1 101 <b><font color="blue">FN Project</font></b>\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: foo\r\n\r\n'
class Server(threading.Thread):
def __init__(self, host, port):
super().__init__()
self.running = False
self.host = host
self.port = port
self.threads = []
self.threadsLock = threading.Lock()
self.logLock = threading.Lock()
def run(self):
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.soc.settimeout(2)
self.soc.bind((self.host, self.port))
self.soc.listen(5)
self.running = True
try:
while self.running:
try:
c, addr = self.soc.accept()
c.setblocking(1)
except socket.timeout:
continue
conn = ConnectionHandler(c, self, addr)
conn.start()
self.addConn(conn)
finally:
self.running = False
self.soc.close()
def printLog(self, log):
with self.logLock:
print(log)
def addConn(self, conn):
with self.threadsLock:
if self.running:
self.threads.append(conn)
def removeConn(self, conn):
with self.threadsLock:
self.threads.remove(conn)
def close(self):
self.running = False
with self.threadsLock:
for c in list(self.threads):
c.close()
class ConnectionHandler(threading.Thread):
def __init__(self, socClient, server, addr):
super().__init__()
self.clientClosed = False
self.targetClosed = True
self.client = socClient
self.client_buffer = b''
self.server = server
self.log = f'Connection: {addr}'
def close(self):
if not self.clientClosed:
try:
self.client.shutdown(socket.SHUT_RDWR)
self.client.close()
except:
pass
finally:
self.clientClosed = True
if not self.targetClosed:
try:
self.target.shutdown(socket.SHUT_RDWR)
self.target.close()
except:
pass
finally:
self.targetClosed = True
def run(self):
try:
self.client_buffer = self.client.recv(BUFLEN)
hostPort = self.findHeader(self.client_buffer, b'X-Real-Host') or DEFAULT_HOST
passwd = self.findHeader(self.client_buffer, b'X-Pass')
if PASS and passwd != PASS:
self.client.send(b'HTTP/1.1 400 WrongPass!\r\n\r\n')
elif hostPort.startswith('127.0.0.1') or hostPort.startswith('localhost'):
self.method_CONNECT(hostPort)
else:
self.client.send(b'HTTP/1.1 403 Forbidden!\r\n\r\n')
except Exception as e:
self.server.printLog(f'Error: {e}')
finally:
self.close()
self.server.removeConn(self)
def findHeader(self, head, header):
head = head.decode(errors='ignore')
header = header.decode(errors='ignore')
for line in head.split('\r\n'):
if line.startswith(header + ': '):
return line.split(': ', 1)[1]
return ''
def connect_target(self, host):
host, _, port = host.partition(':')
port = int(port) if port else 443
self.target = socket.create_connection((host, port))
self.targetClosed = False
def method_CONNECT(self, path):
self.log += f' - CONNECT {path}'
self.connect_target(path)
self.client.sendall(RESPONSE)
self.server.printLog(self.log)
self.doCONNECT()
def doCONNECT(self):
socs = [self.client, self.target]
count = 0
while True:
count += 1
recv, _, err = select.select(socs, [], socs, 3)
if err:
break
for in_ in recv:
try:
data = in_.recv(BUFLEN)
if data:
(self.client if in_ is self.target else self.target).sendall(data)
count = 0
else:
break
except:
break
if count == TIMEOUT:
break
def print_usage():
print('Usage: proxy.py -p <port>')
print(' proxy.py -b <bindAddr> -p <port>')
print(' proxy.py -b 0.0.0.0 -p 80')
def parse_args(argv):
global LISTENING_ADDR, LISTENING_PORT
try:
opts, _ = getopt.getopt(argv, "hb:p:", ["bind=", "port="])
except getopt.GetoptError:
print_usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print_usage()
sys.exit()
elif opt in ("-b", "--bind"):
LISTENING_ADDR = arg
elif opt in ("-p", "--port"):
LISTENING_PORT = int(arg)
def main():
print("\n:-------PythonProxy-------:")
print(f"Listening addr: {LISTENING_ADDR}")
print(f"Listening port: {LISTENING_PORT}\n")
print(":-------------------------:")
server = Server(LISTENING_ADDR, LISTENING_PORT)
server.start()
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
print('Stopping...')
server.close()
if __name__ == '__main__':
parse_args(sys.argv[1:])
main()