Commit f4e39ebc authored by Guillaume Bury's avatar Guillaume Bury

Peer discovery through server added

parent 814b158b
......@@ -27,6 +27,11 @@ class main(object):
# Database initializing
self.db = sqlite3.connect(self.config.db, isolation_level=None)
self.db.execute("""CREATE TABLE IF NOT EXISTS peers (
prefix text primary key not null,
ip text not null,
port integer not null,
proto text not null)""")
self.db.execute("""CREATE TABLE IF NOT EXISTS tokens (
token text primary key not null,
email text not null,
......@@ -105,13 +110,6 @@ class main(object):
# Get a new prefix
prefix = self._getPrefix(prefix_len)
# Get complete ipv6 address from prefix
#ip = hex(int(prefix.ljust(80, '0'),2))[2::] # XXX: do not hardcode
#ip6 = self.vifib
#for i in xrange(0, len(ip), 4):
# ip6 += ip[i:i+4] + ':'
#ip6 = ip6.rstrip(':')
# Create certificate
cert = crypto.X509()
#cert.set_serial_number(serial)
......@@ -133,5 +131,13 @@ class main(object):
traceback.print_exc()
raise
def getCa(self):
return crypto.dump_certificate(crypto.FILETYPE_PEM, self.ca)
def getPeerList(self, n):
assert 0 < n < 1000
return self.db.execute("SELECT ip, port, proto FROM peers ORDER BY random() LIMIT ?", (n,)).fetchall()
if __name__ == "__main__":
main()
......@@ -34,7 +34,7 @@ def main():
req = crypto.X509Req()
subj = req.get_subject()
if config.req:
while len(config.req) > 0:
while len(config.req) > 1:
key = config.req.pop(0)
value = config.req.pop(0)
setattr(subj, key, value)
......@@ -47,9 +47,9 @@ def main():
cert = s.requestCertificate(token,req)
# Store cert and key
with open(os.path.join(config.dir, 'ca.crt'), 'w') as f:
f.write(key)
with open(os.path.join(config.dir, 'cert.key'), 'w') as f:
f.write(key)
with open(os.path.join(config.dir, 'cert.crt'), 'w') as f:
f.write(cert)
with open(os.path.join(config.dir, 'ca.pem'), 'w') as f:
f.write(ca)
......
#!/usr/bin/env python
import argparse, errno, os, select, sqlite3, subprocess, sys, time
import argparse, errno, os, select, sqlite3, subprocess, sys, time, xmlrpclib
import traceback
import upnpigd
import openvpn
......@@ -11,22 +11,32 @@ connection_dict = {} # to remember current connections we made
free_interface_set = set(('client1', 'client2', 'client3', 'client4', 'client5',
'client6', 'client7', 'client8', 'client9', 'client10'))
# TODO : How do we get our vifib ip ?
# TODO : flag in some way the peers that are connected to us so we don't connect to them
# Or maybe we just don't care,
class PeersDB:
def __init__(self, dbPath):
self.proxy = xmlrpclib.ServerProxy('http://%s:%u' % (config.server, config.server_port))
log.log('Connectiong to peers database', 4)
self.db = sqlite3.connect(dbPath, isolation_level=None)
log.log('Initializing peers database', 4)
self.db.execute("""CREATE TABLE IF NOT EXISTS peers
( id INTEGER PRIMARY KEY AUTOINCREMENT,
try:
self.db.execute("""CREATE TABLE peers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT NOT NULL,
port INTEGER NOT NULL,
proto TEXT NOT NULL,
used INTEGER NOT NULL)""")
self.db.execute("CREATE INDEX IF NOT EXISTS _peers_used ON peers(used)")
used INTEGER NOT NULL default 0)""")
self.db.execute("CREATE INDEX _peers_used ON peers(used)")
self.db.execute("UPDATE peers SET used = 0")
except sqlite3.OperationalError, e:
if e.args[0] != 'table peers already exists':
raise RuntimeError
else:
self.populateDB(100)
def populateDB(self, n):
self.db.executemany("INSERT INTO peers (ip, port, proto) VALUES ?", self.proxy.getPeerList(n))
def getUnusedPeers(self, nPeers):
return self.db.execute("SELECT id, ip, port, proto FROM peers WHERE used = 0 "
......@@ -40,6 +50,12 @@ class PeersDB:
log.log('Updating peers database : unusing peer ' + str(id), 5)
self.db.execute("UPDATE peers SET used = 0 WHERE id = ?", (id,))
def ipFromPrefix(prefix, prefix_len):
tmp = hew(int(prefix, 2))[2::]
ip = VIFIB_NET
for i in xrange(0, len(ip), 4):
ip += tmp[i:i+4] + ':'
ip += ':'
def startBabel(**kw):
args = ['babeld',
......@@ -65,6 +81,10 @@ def getConfig():
parser = argparse.ArgumentParser(
description='Resilient virtual private network application')
_ = parser.add_argument
_('--server', required=True,
help='Address for peer discovery server')
_('--server-port', required=True,
help='Peer discovery server port')
_('--log-directory', default='/var/log',
help='Path to vifibnet logs directory')
_('--client-count', default=2, type=int,
......@@ -84,6 +104,8 @@ def getConfig():
help='Path to babeld state-file')
_('--verbose', '-v', default=0, type=int,
help='Defines the verbose level')
_('--cert', required=True,
help='Path to the certificate file')
# Temporary args - to be removed
_('--ip', required=True,
help='IPv6 of the server')
......@@ -91,8 +113,18 @@ def getConfig():
_('openvpn_args', nargs=argparse.REMAINDER,
help="Common OpenVPN options (e.g. certificates)")
openvpn.config = config = parser.parse_args()
with open(config.cert, 'r') as f:
cert = crypto.load_certificate(crypto.FILETYPE_PEM, f)
subject = cert.get_subject()
prefix_txt, prefix_len_txt = subject.serialNumber.split('/')
prefix = int(prefix_txt)
prefix_len = int(prefix_len_txt)
ip = ipFromPrefix(prefix)
print ip
if config.openvpn_args[0] == "--":
del config.openvpn_args[0]
config.openvpn_args.append('--cert')
config.openvpn_args.append(config.cert)
def startNewConnection(n):
try:
......@@ -100,7 +132,8 @@ def startNewConnection(n):
log.log('Establishing a connection with id %s (%s:%s)' % (id,ip,port), 2)
iface = free_interface_set.pop()
connection_dict[id] = ( openvpn.client( ip, '--dev', iface, '--proto', proto, '--rport', str(port),
stdout=os.open('%s/vifibnet.client.%s.log' % (config.log_directory, id), os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ),
stdout=os.open(os.path.join(config.log_directory, 'vifibnet.client.%s.log' % (id,)),
os.O_WRONLY|os.O_CREAT|os.O_TRUNC) ),
iface)
peers_db.usePeer(id)
except KeyError:
......@@ -177,7 +210,7 @@ def main():
# Establish connections
log.log('Starting openvpn server', 3)
serverProcess = openvpn.server(config.ip, write_pipe, '--dev', 'vifibnet',
stdout=os.open('%s/vifibnet.server.log' % (config.log_directory,), os.O_WRONLY | os.O_CREAT | os.O_TRUNC))
stdout=os.open(os.path.join(config.log_directory, 'vifibnet.server.log'), os.O_WRONLY | os.O_CREAT | os.O_TRUNC))
startNewConnection(config.client_count)
# Timed refresh initializing
......
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