Skip to content

Instantly share code, notes, and snippets.

@sorz
Last active May 12, 2017
Embed
What would you like to do?
#!/usr/bin/python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('0.0.0.0', 6000))
while True:
data, addr = s.recvfrom(1024)
s.sendto(str(addr[1]), addr)
#!/usr/bin/env python
import random
import logging
import subprocess
import time
import socket
import requests
NAT_REQUEST_URL = 'https://vpn.sorz.org/ovpn/connect?port=%s'
SNAT_SERVER = ('vpn.sorz.org', 6000)
def get_default_param():
return ['bin\openvpn.exe',
'--client',
'--bind',
'--local', '0.0.0.0',
'--proto', 'udp',
'--dev', 'tun',
'--resolv-retry', 'infinite',
'--persist-key',
'--persist-tun',
'--ca', 'ca.crt',
'--cert', 'testclient.crt',
'--key', 'testclient.key',
'--ns-cert-type', 'server',
'--keepalive', '20', '60',
'--comp-lzo',
'--verb', '3',
'--mute', '20',
'--script-security', '2', 'system'
]
def main():
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
logging.info('Version 0.2a1')
port = random.randint(8192, 65535)
logging.info('Use random port %s.' % port)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', port))
sock.settimeout(3)
nat_port = None
for i in range(5):
try:
sock.sendto('orz', SNAT_SERVER)
nat_port = int(str(sock.recv(256)))
except socket.timeout:
logging.warn('Timeout, retry getting NAT port.')
continue
except ValueError:
logging.warn('Illegal value, retry getting NAT port.')
continue
sock.shutdown(socket.SHUT_RDWR)
sock.close()
if nat_port is None:
logging.error("Can't get NAT port. Using local bind port.")
nat_port = port
logging.info('NAT Port is %s.' % nat_port)
r = requests.get(NAT_REQUEST_URL % nat_port)
if r.status_code == 404:
logging.error('Server is offline.')
return
server = r.text.strip()
logging.info('Server address is %s.' % server)
logging.info('Waiting 2 seconds...')
time.sleep(2)
openvpn = get_default_param()
openvpn.extend(['--remote'] + server.split(':'))
openvpn.extend(('--lport', str(port)))
logging.info('Calling openvpn')
subprocess.call(openvpn)
if __name__ == '__main__':
main()
#!/usr/bin/env python
import socket
import sendudp
SNAT_BIND_PORT = 6001
SNAT_SERVER = ('sorz.org', 6002)
OPENVPN_BIND_PORT = 1194
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', SNAT_BIND_PORT))
sock.settimeout(20)
while True:
sock.sendto('\x00', SNAT_SERVER)
try:
sock.recv(1024) # Ignore ping response
data = sock.recv(1024) # Receiving users' connection request.
except socket.timeout:
continue
if data[0] != '\x03':
continue
print('a new connection from ' + data[1:])
client = data[1:].split(':')
sendudp.sendto(OPENVPN_BIND_PORT, (client[0], int(client[1])))
if __name__ == '__main__':
main()
# (...)
SNAT_SERVER_PORT = 6002
@app.route('/ovpn/connect')
def movpn_openvpn():
server = get_memcache().get('movpn.openvpn.server')
if not server:
return 'Server is not running.', 404
addr = request.remote_addr
if addr.startswith('::ffff:'):
addr = addr[7:]
port = request.args.get('port', 1194)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto('\x02%s:%s' % (addr, port), ('localhost', SNAT_SERVER_PORT))
return server
# (...)
#!/usr/bin/env python
import memcache
SNAT_SERVER_PORT = 6002 # local listening
OPENVPN_BIND_PORT = 1194
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('0.0.0.0', SNAT_SERVER_PORT))
mc = memcache.Client(['127.0.0.1:11211'])
server = mc.get('movpn.openvpn.server')
if server:
server = (server.split(':')[0], OPENVPN_BIND_PORT)
while True:
data, addr = s.recvfrom(1024)
if data[0] == '\x00': # From openvpn server
if addr != server:
server = addr
mc.set('movpn.openvpn.server', '%s:%s' % (server[0], OPENVPN_BIND_PORT))
s.sendto('\x01', addr)
elif data[0] == '\x02': # From local web server (user's conn request)
if addr[0] != '127.0.0.1':
print('\x02 != localhost')
continue
print('new connect from ' + data[1:])
s.sendto('\x03%s' % data[1:], server)
else:
print('unknown')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment