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