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