routes are now filtered on tunnel manager to anly take the interesting ones
[re6stnet.git] / registry.py
1 #!/usr/bin/env python
2 import argparse, math, random, select, smtplib, sqlite3, string, socket, time, traceback, errno
3 from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
4 from email.mime.text import MIMEText
5 from OpenSSL import crypto
6 import utils
7
8 # To generate server ca and key with serial for 2001:db8:42::/48
9 # openssl req -nodes -new -x509 -key ca.key -set_serial 0x120010db80042 -days 365 -out ca.crt
10
11 IPV6_V6ONLY = 26
12 SOL_IPV6 = 41
13
14
15 # Fix for librpcxml to avoid doing reverse dns on each request : it was causing a 5s delay on each request
16 import BaseHTTPServer
17
18
19 def not_insane_address_string(self):
20 host, port = self.client_address[:2]
21 return '%s (no getfqdn)' % host # used to call: socket.getfqdn(host)
22
23 BaseHTTPServer.BaseHTTPRequestHandler.address_string = not_insane_address_string
24 # end of the fix
25
26
27 class RequestHandler(SimpleXMLRPCRequestHandler):
28
29 def _dispatch(self, method, params):
30 return self.server._dispatch(method, (self,) + params)
31
32
33 class SimpleXMLRPCServer4(SimpleXMLRPCServer):
34
35 allow_reuse_address = True
36
37
38 class SimpleXMLRPCServer6(SimpleXMLRPCServer4):
39
40 address_family = socket.AF_INET6
41
42 def server_bind(self):
43 self.socket.setsockopt(SOL_IPV6, IPV6_V6ONLY, 1)
44 SimpleXMLRPCServer4.server_bind(self)
45
46
47 class main(object):
48
49 def __init__(self):
50 self.cert_duration = 365 * 86400
51 self.time_out = 86400
52 self.refresh_interval = 600
53 self.last_refresh = time.time()
54
55 # Command line parsing
56 parser = argparse.ArgumentParser(
57 description='Peer discovery http server for vifibnet')
58 _ = parser.add_argument
59 _('port', type=int, help='Port of the host server')
60 _('--db', required=True,
61 help='Path to database file')
62 _('--ca', required=True,
63 help='Path to ca.crt file')
64 _('--key', required=True,
65 help='Path to certificate key')
66 _('--mailhost', required=True,
67 help='SMTP server mail host')
68 self.config = parser.parse_args()
69
70 # Database initializing
71 self.db = sqlite3.connect(self.config.db, isolation_level=None)
72 self.db.execute("""CREATE TABLE IF NOT EXISTS peers (
73 prefix text primary key not null,
74 address text not null,
75 date integer default (strftime('%s','now')))""")
76 self.db.execute("CREATE INDEX IF NOT EXISTS peers_ping ON peers(date)")
77 self.db.execute("""CREATE TABLE IF NOT EXISTS tokens (
78 token text primary key not null,
79 email text not null,
80 prefix_len integer not null,
81 date integer not null)""")
82 try:
83 self.db.execute("""CREATE TABLE vpn (
84 prefix text primary key not null,
85 email text,
86 cert text)""")
87 except sqlite3.OperationalError, e:
88 if e.args[0] != 'table vpn already exists':
89 raise RuntimeError
90 else:
91 self.db.execute("INSERT INTO vpn VALUES ('',null,null)")
92
93 # Loading certificates
94 with open(self.config.ca) as f:
95 self.ca = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
96 with open(self.config.key) as f:
97 self.key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
98 # Get vpn network prefix
99 self.network = bin(self.ca.get_serial_number())[3:]
100 print "Network prefix : %s/%u" % (self.network, len(self.network))
101
102 # Starting server
103 server4 = SimpleXMLRPCServer4(('0.0.0.0', self.config.port), requestHandler=RequestHandler, allow_none=True)
104 server4.register_instance(self)
105 server6 = SimpleXMLRPCServer6(('::', self.config.port), requestHandler=RequestHandler, allow_none=True)
106 server6.register_instance(self)
107
108 # Main loop
109 while True:
110 try:
111 r, w, e = select.select([server4, server6], [], [])
112 except (OSError, select.error) as e:
113 if e.args[0] != errno.EINTR:
114 raise
115 else:
116 for r in r:
117 r._handle_request_noblock()
118
119 def requestToken(self, handler, email):
120 while True:
121 # Generating token
122 token = ''.join(random.sample(string.ascii_lowercase, 8))
123 # Updating database
124 try:
125 self.db.execute("INSERT INTO tokens VALUES (?,?,?,?)", (token, email, 16, int(time.time())))
126 break
127 except sqlite3.IntegrityError:
128 pass
129
130 # Creating and sending email
131 s = smtplib.SMTP(self.config.mailhost)
132 me = 'postmaster@vifibnet.com'
133 msg = MIMEText('Hello world !\nYour token : %s' % (token,))
134 msg['Subject'] = '[Vifibnet] Token Request'
135 msg['From'] = me
136 msg['To'] = email
137 s.sendmail(me, email, msg.as_string())
138 s.quit()
139
140 def _getPrefix(self, prefix_len):
141 assert 0 < prefix_len <= 128 - len(self.network)
142 for prefix, in self.db.execute("""SELECT prefix FROM vpn WHERE length(prefix) <= ? AND cert is null
143 ORDER BY length(prefix) DESC""", (prefix_len,)):
144 while len(prefix) < prefix_len:
145 self.db.execute("UPDATE vpn SET prefix = ? WHERE prefix = ?", (prefix + '1', prefix))
146 prefix += '0'
147 self.db.execute("INSERT INTO vpn VALUES (?,null,null)", (prefix,))
148 return prefix
149 raise RuntimeError # TODO: raise better exception
150
151 def requestCertificate(self, handler, token, cert_req):
152 try:
153 req = crypto.load_certificate_request(crypto.FILETYPE_PEM, cert_req)
154 with self.db:
155 try:
156 token, email, prefix_len, _ = self.db.execute("SELECT * FROM tokens WHERE token = ?", (token,)).next()
157 except StopIteration:
158 # TODO: return nice error message
159 raise
160 self.db.execute("DELETE FROM tokens WHERE token = ?", (token,))
161
162 # Get a new prefix
163 prefix = self._getPrefix(prefix_len)
164
165 # Create certificate
166 cert = crypto.X509()
167 #cert.set_serial_number(serial)
168 cert.gmtime_adj_notBefore(0)
169 cert.gmtime_adj_notAfter(self.cert_duration)
170 cert.set_issuer(self.ca.get_subject())
171 subject = req.get_subject()
172 subject.CN = "%u/%u" % (int(prefix, 2), prefix_len)
173 cert.set_subject(subject)
174 cert.set_pubkey(req.get_pubkey())
175 cert.sign(self.key, 'sha1')
176 cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
177
178 # Insert certificate into db
179 self.db.execute("UPDATE vpn SET email = ?, cert = ? WHERE prefix = ?", (email, cert, prefix))
180
181 return cert
182 except:
183 traceback.print_exc()
184 raise
185
186 def getCa(self, handler):
187 return crypto.dump_certificate(crypto.FILETYPE_PEM, self.ca)
188
189 def getBootstrapPeer(self, handler):
190 # TODO: Insert a flag column for bootstrap ready servers in peers
191 # ( servers which shouldn't go down or change ip and port as opposed to servers owned by particulars )
192 # that way, we also ascertain that the server sent is not the new node....
193 prefix, address = self.db.execute("SELECT prefix, address FROM peers ORDER BY random() LIMIT 1").next()
194 print "Sending bootstrap peer (%s, %s)" % (prefix, str(address))
195 return prefix, address
196
197 def declare(self, handler, address):
198 print "declaring new node"
199 client_address, address = address
200 #client_address, _ = handler.client_address
201 client_ip = utils.binFromIp(client_address)
202 if client_ip.startswith(self.network):
203 prefix = client_ip[len(self.network):]
204 prefix, = self.db.execute("SELECT prefix FROM vpn WHERE prefix <= ? ORDER BY prefix DESC LIMIT 1", (prefix,)).next()
205 self.db.execute("INSERT OR REPLACE INTO peers (prefix, address) VALUES (?,?)", (prefix, address))
206 return True
207 else:
208 # TODO: use log + DO NOT PRINT BINARY IP
209 print "Unauthorized connection from %s which does not start with %s" % (client_ip, self.network)
210 return False
211
212 def getPeerList(self, handler, n, client_address):
213 assert 0 < n < 1000
214 client_ip = utils.binFromIp(client_address)
215 if client_ip.startswith(self.network):
216 if time.time() > self.last_refresh + self.refresh_interval:
217 print "refreshing peers for dead ones"
218 self.db.execute("DELETE FROM peers WHERE ( date + ? ) <= CAST (strftime('%s', 'now') AS INTEGER)", (self.time_out,))
219 self.last_refesh = time.time()
220 print "sending peers"
221 return self.db.execute("SELECT prefix, address FROM peers ORDER BY random() LIMIT ?", (n,)).fetchall()
222 else:
223 # TODO: use log + DO NOT PRINT BINARY IP
224 print "Unauthorized connection from %s which does not start with %s" % (client_ip, self.network)
225 raise RuntimeError
226
227 if __name__ == "__main__":
228 main()