Commit 31222fbe authored by Guillaume Bury's avatar Guillaume Bury

Vifib works again

parent ecbe625a
import utils #!/usr/bin/env python
import sqlite3, xmlrpclib import sqlite3, xmlrpclib
import utils
class PeerManager: class PeerManager:
def __init__(self, dbPath): def __init__(self, dbPath):
utils.log('Connectiong to peers database', 4) utils.log('Connectiong to peers database', 4)
self.db = sqlite3.connect(dbPath, isolation_level=None) self.db = sqlite3.connect(dbPath, isolation_level=None)
...@@ -36,8 +37,8 @@ class PeerManager: ...@@ -36,8 +37,8 @@ class PeerManager:
def unusePeer(self, id): def unusePeer(self, id):
utils.log('Updating peers database : unusing peer ' + str(id), 5) utils.log('Updating peers database : unusing peer ' + str(id), 5)
self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,)) self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,))
def handle_message(msg): def handle_message(self, msg):
script_type, arg = msg.split() script_type, arg = msg.split()
if script_type == 'client-connect': if script_type == 'client-connect':
utils.log('Incomming connection from %s' % (arg,), 3) utils.log('Incomming connection from %s' % (arg,), 3)
......
#!/usr/bin/python -S #!/usr/bin/python -S
import os, sys
# example of os.environ # example of os.environ
{'X509_0_C': 'FR', {'X509_0_C': 'FR',
......
...@@ -2,8 +2,7 @@ ...@@ -2,8 +2,7 @@
import os, subprocess import os, subprocess
import utils import utils
# TODO: "Objectify" this module ? verbose = None
# Needed : verbose, network ( previous vifibnet), max-clients, dh, internalIp
def openvpn(*args, **kw): def openvpn(*args, **kw):
args = ['openvpn', args = ['openvpn',
...@@ -19,7 +18,7 @@ def openvpn(*args, **kw): ...@@ -19,7 +18,7 @@ def openvpn(*args, **kw):
# '--ping', '1', # '--ping', '1',
# '--ping-exit', '3', # '--ping-exit', '3',
'--group', 'nogroup', '--group', 'nogroup',
'--verb', str(utils.config.verbose), '--verb', str(verbose),
] + list(args) ] + list(args)
utils.log(str(args), 5) utils.log(str(args), 5)
return subprocess.Popen(args, **kw) return subprocess.Popen(args, **kw)
...@@ -27,7 +26,7 @@ def openvpn(*args, **kw): ...@@ -27,7 +26,7 @@ def openvpn(*args, **kw):
# TODO : set iface up when creating a server/client # TODO : set iface up when creating a server/client
# ! check working directory before launching up script ? # ! check working directory before launching up script ?
def server(serverIp, network, max_clients, pipe_fd, *args, **kw): def server(serverIp, network, max_clients, dh_path, pipe_fd, *args, **kw):
utils.log('Starting server', 3) utils.log('Starting server', 3)
return openvpn( return openvpn(
'--tls-server', '--tls-server',
...@@ -35,7 +34,7 @@ def server(serverIp, network, max_clients, pipe_fd, *args, **kw): ...@@ -35,7 +34,7 @@ def server(serverIp, network, max_clients, pipe_fd, *args, **kw):
'--up', 'ovpn-server %s/%u' % (serverIp, len(network)), '--up', 'ovpn-server %s/%u' % (serverIp, len(network)),
'--client-connect', 'ovpn-server ' + str(pipe_fd), '--client-connect', 'ovpn-server ' + str(pipe_fd),
'--client-disconnect', 'ovpn-server ' + str(pipe_fd), '--client-disconnect', 'ovpn-server ' + str(pipe_fd),
'--dh', utils.config.dh, '--dh', dh_path,
'--max-clients', str(max_clients), '--max-clients', str(max_clients),
*args, **kw) *args, **kw)
...@@ -62,11 +61,11 @@ def babel(network, internal_ip, interface_list, **kw): ...@@ -62,11 +61,11 @@ def babel(network, internal_ip, interface_list, **kw):
#'-C', 'in ip ::/0 le %s' % network_mask, #'-C', 'in ip ::/0 le %s' % network_mask,
# Don't route other addresses # Don't route other addresses
'-C', 'in deny', '-C', 'in deny',
'-d', str(utils.config.verbose), '-d', str(verbose),
'-s', '-s',
] ]
if utils.config.babel_state: #if utils.config.babel_state:
args += '-S', utils.config.babel_state # args += '-S', utils.config.babel_state
args = args + interface_list args = args + interface_list
utils.log(str(args), 5) utils.log(str(args), 5)
return subprocess.Popen(args, **kw) return subprocess.Popen(args, **kw)
......
import socket #!/usr/bin/env python
import uuid import socket, uuid
import log import log
# create an upd socket # create an upd socket
......
#!/usr/bin/env python
import os, random, traceback import os, random, traceback
import plib, utils, db import plib, utils, db
log = None
class TunnelManager: class TunnelManager:
def __init__(self, write_pipe, peer_db): def __init__(self, write_pipe, peer_db, client_count, refresh_count, openvpn_args):
self._write_pipe = write_pipe self._write_pipe = write_pipe
self._peer_db = peer_db self._peer_db = peer_db
self._connection_dict = {} self._connection_dict = {}
self._client_count = client_count self._client_count = client_count
self._refresh_count = refresh_count self._refresh_count = refresh_count
self._ovpn_args = openvpn_args
self.free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5', self.free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5',
'client6', 'client7', 'client8', 'client9', 'client10')) 'client6', 'client7', 'client8', 'client9', 'client10'))
...@@ -27,7 +31,7 @@ class TunnelManager: ...@@ -27,7 +31,7 @@ class TunnelManager:
del self.connection_dict[id] del self.connection_dict[id]
def _removeSomeTunnels(self): def _removeSomeTunnels(self):
for i in range(0, max(0, len(self._connection_dict) - self._clientCount + self._refresh_count)): for i in range(0, max(0, len(self._connection_dict) - self._client_count + self._refresh_count)):
peer_id = random.choice(self._connection_dict.keys()) peer_id = random.choice(self._connection_dict.keys())
kill(peer_id) kill(peer_id)
...@@ -40,13 +44,13 @@ class TunnelManager: ...@@ -40,13 +44,13 @@ class TunnelManager:
def _makeNewTunnels(self): def _makeNewTunnels(self):
try: try:
for peer_id, ip, port, proto in self._peer_db.getUnusedPeers(self._client_count - len(self._connection_dict), self._write_pipe): for peer_id, ip, port, proto in self._peer_db.getUnusedPeers(self._client_count - len(self._connection_dict)):
utils.log('Establishing a connection with id %s (%s:%s)' % (peer_id, ip, port), 2) utils.log('Establishing a connection with id %s (%s:%s)' % (peer_id, ip, port), 2)
iface = self.free_interface_set.pop() iface = self.free_interface_set.pop()
self._connection_dict[peer_id] = ( openvpn.client( ip, write_pipe, '--dev', iface, '--proto', proto, '--rport', str(port), self._connection_dict[peer_id] = ( plib.client( ip, self._write_pipe,
stdout=os.open(os.path.join(utils.config.log, 'vifibnet.client.%s.log' % (peer_id,)), '--dev', iface, '--proto', proto, '--rport', str(port), *self._ovpn_args,
os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ), stdout=os.open(os.path.join(log, 'vifibnet.client.%s.log' % (peer_id,)),
iface) os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ), iface)
self._peer_db.usePeer(peer_id) self._peer_db.usePeer(peer_id)
except KeyError: except KeyError:
utils.log("Can't establish connection with %s : no available interface" % ip, 2) utils.log("Can't establish connection with %s : no available interface" % ip, 2)
......
#!/usr/bin/env python
import miniupnpc import miniupnpc
import socket import socket
......
#!/usr/bin/env python
import argparse, time, struct, socket import argparse, time, struct, socket
from OpenSSL import crypto from OpenSSL import crypto
verbose = 0
def log(message, verbose_level): def log(message, verbose_level):
if config.verbose >= verbose_level: if verbose >= verbose_level:
print time.strftime("%d-%m-%Y %H:%M:%S : " + message) print time.strftime("%d-%m-%Y %H:%M:%S : " + message)
def binFromIp(ip): def binFromIp(ip):
ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip)) ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip))
return bin(client_ip1)[2:].rjust(64, '0') + bin(client_ip2)[2:].rjust(64, '0') return bin(client_ip1)[2:].rjust(64, '0') + bin(client_ip2)[2:].rjust(64, '0')
def ipFromBin(prefix): def ipFromBin(prefix):
prefix = hex(int(prefix, 2))[2:] prefix = hex(int(prefix, 2))[2:]
ip = '' ip = ''
...@@ -27,7 +29,7 @@ def networkFromCa(ca_path): ...@@ -27,7 +29,7 @@ def networkFromCa(ca_path):
with open(ca_path, 'r') as f: with open(ca_path, 'r') as f:
ca = crypto.load_certificate(crypto.FILETYPE_PEM, f.read()) ca = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
return bin(ca.get_serial_number())[3:] return bin(ca.get_serial_number())[3:]
def ipFromCert(network, cert_path): def ipFromCert(network, cert_path):
# Get ip from cert.crt # Get ip from cert.crt
with open(cert_path, 'r') as f: with open(cert_path, 'r') as f:
...@@ -35,25 +37,14 @@ def ipFromCert(network, cert_path): ...@@ -35,25 +37,14 @@ def ipFromCert(network, cert_path):
subject = cert.get_subject() subject = cert.get_subject()
prefix, prefix_len = subject.CN.split('/') prefix, prefix_len = subject.CN.split('/')
return ipFromPrefix(network, prefix, int(prefix_len)) return ipFromPrefix(network, prefix, int(prefix_len))
def ovpnArgs(optional_args, ca_path, cert_path) def ovpnArgs(optional_args, ca_path, cert_path):
# Treat openvpn arguments # Treat openvpn arguments
if optional_args[0] == "--": if optional_args[0] == "--":
del optional_args[0] del optional_args[0]
optional_args.append('--ca') optional_args.append('--ca')
optional_args.append(config.ca) optional_args.append(ca_path)
optional_args.append('--cert') optional_args.append('--cert')
optional_args.append(config.cert) optional_args.append(cert_path)
return optional_args return optional_args
\ No newline at end of file
...@@ -47,25 +47,30 @@ def main(): ...@@ -47,25 +47,30 @@ def main():
config = getConfig() config = getConfig()
network = utils.networkFromCa(config.ca) network = utils.networkFromCa(config.ca)
internal_ip = utils.ipFromCert(network, config.cert) internal_ip = utils.ipFromCert(network, config.cert)
openvpn_args = utils.ovpnArgs(config.openvpn_args, config.ca, config.cert)
# Init db and tunnels # Set global variables
peer_db = db.PeerManager(utils.config.db) tunnel.log = config.log
tunnel_manager = tunnelmanager.TunnelManager(write_pipe, peer_db, config.client_count, config.refresh_count) utils.verbose = plib.verbose = config.verbose
# Launch babel on all interfaces. WARNING : you have to be root to start babeld
babel = plib.babel(network, internal_ip, ['vifibnet'] + tunnel_manager.free_interface_set,
stdout=os.open(os.path.join(utils.config.log, 'vifibnet.babeld.log'),
os.O_WRONLY | os.O_CREAT | os.O_TRUNC), stderr=subprocess.STDOUT)
# Create and open read_only pipe to get server events # Create and open read_only pipe to get server events
utils.log('Creating pipe for server events', 3) utils.log('Creating pipe for server events', 3)
r_pipe, write_pipe = os.pipe() r_pipe, write_pipe = os.pipe()
read_pipe = os.fdopen(r_pipe) read_pipe = os.fdopen(r_pipe)
# Init db and tunnels
peer_db = db.PeerManager(config.db)
tunnel_manager = tunnel.TunnelManager(write_pipe, peer_db, config.client_count, config.refresh_count, openvpn_args)
# Launch babel on all interfaces. WARNING : you have to be root to start babeld
interface_list = ['vifibnet'] + list(tunnel_manager.free_interface_set)
babel = plib.babel(network, internal_ip, interface_list,
stdout=os.open(os.path.join(config.log, 'vifibnet.babeld.log'),
os.O_WRONLY | os.O_CREAT | os.O_TRUNC), stderr=subprocess.STDOUT)
# Establish connections # Establish connections
server_process = plib.server(internal_ip, network, config.max_clients, write_pipe, server_process = plib.server(internal_ip, network, config.max_clients, config.dh, write_pipe,
'--dev', 'vifibnet', *utils.ovpnArgs(config.openvpn_args, config.ca, config.cert), '--dev', 'vifibnet', *openvpn_args,
stdout=os.open(os.path.join(utils.config.log, 'vifibnet.server.log'), os.O_WRONLY | os.O_CREAT | os.O_TRUNC)) stdout=os.open(os.path.join(config.log, 'vifibnet.server.log'), os.O_WRONLY | os.O_CREAT | os.O_TRUNC))
tunnel_manager.refresh() tunnel_manager.refresh()
# Timed refresh initializing # Timed refresh initializing
...@@ -75,7 +80,7 @@ def main(): ...@@ -75,7 +80,7 @@ def main():
try: try:
while True: while True:
ready, tmp1, tmp2 = select.select([read_pipe], [], [], ready, tmp1, tmp2 = select.select([read_pipe], [], [],
max(0, next_refresh - timhttp://blogs.lesechos.fr/dominique-seux/de-mondialiser-les-telecoms-a11339.htmle.time())) max(0, next_refresh - time.time()))
if ready: if ready:
peer_db.handle_message(read_pipe.readline()) peer_db.handle_message(read_pipe.readline())
if time.time() >= next_refresh: if time.time() >= next_refresh:
......
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