Commit 6e8eaee3 authored by Daniel STAN's avatar Daniel STAN

initial commit : tunnel

parents
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import socket
import subprocess
import getpass
import tempfile
import atexit
REDSOCKS_TPL = """
base {
// debug: connection progress & client list on SIGUSR1
log_debug = off;
// info: start and end of client session
log_info = on;
/* possible `log' values are:
* stderr
* "file:/path/to/file"
* syslog:FACILITY facility is any of "daemon", "local0"..."local7"
*/
log = "syslog:daemon";
// detach from console
daemon = off;
/* Change uid, gid and root directory, these options require root
* privilegies on startup.
* Note, your chroot may requre /etc/localtime if you write log to syslog.
* Log is opened before chroot & uid changing.
*/
user = %(user)s;
group = redsocks;
// chroot = "/var/chroot";
/* possible `redirector' values are:
* iptables - for Linux
* ipf - for FreeBSD
* pf - for OpenBSD
* generic - some generic redirector that MAY work
*/
redirector = iptables;
}
redsocks {
/* `local_ip' defaults to 127.0.0.1 for security reasons,
* use 0.0.0.0 if you want to listen on every interface.
* `local_*' are used as port to redirect to.
*/
local_ip = 127.0.0.1;
local_port = %(local_port)d;
// `ip' and `port' are IP and tcp-port of proxy-server
// You can also use hostname instead of IP, only one (random)
// address of multihomed host will be used.
ip = 127.0.0.1;
port = %(port)d;
// known types: socks4, socks5, http-connect, http-relay
type = socks5;
// login = "foobar";
// password = "baz";
}
"""
def _fresh_localhost_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',0))
p = s.getsockname()[1]
s.close()
return p
class Tunnel(object):
user = None
rules = None
redsocks_proc = None
def __init__(self, socks_port=1080):
self.user = os.getenv("SUDO_USER") or getpass.getuser()
self.rules = []
self.local_port = _fresh_localhost_port()
self.port = socks_port
def forward_ip(self, ip):
rule=(
'nat',
'OUTPUT',
[
'-p', 'tcp',
'--dst', ip,
'-m', 'owner',
'--uid', self.user,
'-j', 'REDIRECT',
'--to-port', str(self.local_port),
])
self.iptables(rule)
def iptables(self, rule, delete=False):
"""Rajoute ou supprime une règle donnée"""
if not delete:
self.rules.append(rule)
cmd = ['/sbin/iptables']
cmd += ['-t', rule[0]]
cmd.append('-D' if delete else '-I')
cmd.append(rule[1])
cmd += rule[2]
subprocess.check_call(cmd)
if delete:
self.rules.remove(rule)
else:
self.rules.append(rule)
def run_redsocks(self):
print "Running redsocks"
# self.iptables(('filter',
# 'OUTPUT',
# [
# '-m', 'owner',
# '!', '--uid', self.user,
# '-j', 'REJECT',
# ]))
infos = {
'local_port': self.local_port,
'port': self.port,
'user': self.user,
}
config_file = tempfile.NamedTemporaryFile(suffix='.cfg')
atexit.register(config_file.close)
config_file.write(REDSOCKS_TPL % infos)
config_file.flush()
self.config_file = config_file
cmd = ['/usr/sbin/redsocks', '-c', config_file.name]
self.redsocks_proc = subprocess.Popen(cmd)
def flush(self):
"""Vide les règles insérées depuis le début du script"""
for rule in self.rules:
self.iptables(rule, delete=True)
def run_ssh(self, host):
cmd = ['/usr/bin/ssh', host]
cmd = ['sudo', '-u', self.user] + cmd
cmd += ['-D', str(self.port)]
proc = subprocess.Popen(cmd)
os.waitpid(proc.pid, 0)
def clean_up(self):
print "Flushing rules"
self.flush()
if self.redsocks_proc:
print "Killing redsocks"
self.redsocks_proc.kill()
if __name__ == '__main__':
if len(sys.argv) <= 2:
print "Usage: tunnel.py $IP $SOCK_PORT"
exit(1)
tunnel = Tunnel(int(sys.argv[2]))
tunnel.forward_ip(sys.argv[1])
tunnel.run_redsocks()
print "Enter to flush"
print tunnel.local_port
raw_input()
tunnel.clean_up()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment