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