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