forked from csx163/sniproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sniproxy.py
82 lines (70 loc) · 2.52 KB
/
sniproxy.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
#!/usr/bin/env python
# coding:utf-8
# based on http://tools.ietf.org/html/rfc4366#section-3.1
# based on http://en.wikipedia.org/wiki/Server_Name_Indication
# based on http://www.infoq.com/cn/articles/HTTPS-Connection-Jeff-Moser
# based on http://blog.bjrn.se/2012/07/fun-with-tls-handshake.html
# based on http://nongnu.askapache.com/sniproxy/sniproxy.tgz
# contributor:
# Phus Lu <[email protected]>
import gevent.monkey
gevent.monkey.patch_all()
import gevent
import gevent.server
import io
import logging
import socket
import struct
def extract_server_name(packet):
if packet.startswith(b'\x16\x03'):
stream = io.BytesIO(packet)
stream.read(0x2b)
session_id_length = ord(stream.read(1))
stream.read(session_id_length)
cipher_suites_length, = struct.unpack('>h', stream.read(2))
stream.read(cipher_suites_length+2)
extensions_length, = struct.unpack('>h', stream.read(2))
extensions = {}
while True:
data = stream.read(2)
if not data:
break
etype, = struct.unpack('>h', data)
elen, = struct.unpack('>h', stream.read(2))
edata = stream.read(elen)
if etype == 0:
server_name = edata[5:].decode()
return server_name
def io_copy(dest, src, timeout=60, bufsize=8192):
"""forward socket"""
try:
while True:
data = src.recv(bufsize)
if not data:
break
src.sendall(data)
except Exception as ex:
logging.exception('io_copy error: %r', ex)
finally:
for sock in (dest, src):
try:
sock.close()
except Exception:
pass
class SNIProxy(gevent.server.StreamServer):
"""Echo server class"""
def __init__(self, *args, **kwargs):
gevent.server.StreamServer.__init__(self, *args, **kwargs)
def handle(self, sock, addr):
peername = writer.get_extra_info('peername')
logging.info('Accepted connection from {}'.format(peername))
data = sock.recv(1500)
server_name = extract_server_name(data)
logging.info('Attmpt open_connection to {}'.format(server_name))
remote = socket.create_connection((server_name, 443))
remote.sendall(data)
gevent.spawn(forward_socket, sock, remote)
gevent.spawn(forward_socket, remote, sock)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
SNIProxy(('127.0.0.1', 443)).serve_forever()