Fix duplicate bootpeer bug
[re6stnet.git] / re6st-conf.py
1 #!/usr/bin/env python
2 import argparse, os, subprocess, sqlite3, sys, xmlrpclib
3 from OpenSSL import crypto
4
5 def main():
6 parser = argparse.ArgumentParser(
7 description='Setup script for re6stnet')
8 _ = parser.add_argument
9 _('--ca-only', action='store_true',
10 help='To only get CA form server')
11 _('--server', required=True,
12 help='Address of the server delivering certifiactes')
13 _('--port', required=True, type=int,
14 help='Port to which connect on the server')
15 _('-d', '--dir', default='/etc/re6stnet',
16 help='Directory where the key and certificate will be stored')
17 _('-r', '--req', nargs=2, action='append',
18 help='Name and value of certificate request additional arguments')
19 _('--email', help='Your email address')
20 _('--token', help='The token you received')
21 config = parser.parse_args()
22
23 # Establish connection with server
24 s = xmlrpclib.ServerProxy('http://%s:%u' % (config.server, config.port))
25
26 # Get CA
27 ca = s.getCa()
28 with open(os.path.join(config.dir, 'ca.pem'), 'w') as f:
29 f.write(ca)
30
31 if config.ca_only:
32 sys.exit(0)
33
34 # Get token
35 if not config.token:
36 if not config.email:
37 config.email = raw_input('Please enter your email address : ')
38 _ = s.requestToken(config.email)
39 config.token = raw_input('Please enter your token : ')
40
41 # Generate key and cert request
42 pkey = crypto.PKey()
43 pkey.generate_key(crypto.TYPE_RSA, 2048)
44 key = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
45
46 req = crypto.X509Req()
47 subj = req.get_subject()
48 if config.req:
49 for arg in config.req:
50 setattr(subj, arg[0], arg[1])
51 req.set_pubkey(pkey)
52 req.sign(pkey, 'sha1')
53 req = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
54
55 # Get certificate
56 cert = s.requestCertificate(config.token, req)
57
58 # Store cert and key
59 with open(os.path.join(config.dir, 'cert.key'), 'w') as f:
60 f.write(key)
61 with open(os.path.join(config.dir, 'cert.crt'), 'w') as f:
62 f.write(cert)
63
64 # Generating dh file
65 if not os.access(os.path.join(config.dir, 'dh2048.pem'), os.F_OK):
66 subprocess.call(['openssl', 'dhparam', '-out', os.path.join(config.dir, 'dh2048.pem'), '2048'])
67
68 print "Certificate setup complete."
69
70 if __name__ == "__main__":
71 main()