1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/python
import argparse, atexit, errno, os, subprocess, sqlite3, sys, time
from OpenSSL import crypto
from re6st import registry, utils
def create(path, text=None, mode=0666):
fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, mode)
try:
os.write(fd, text)
finally:
os.close(fd)
def loadCert(pem):
return crypto.load_certificate(crypto.FILETYPE_PEM, pem)
def main():
parser = argparse.ArgumentParser(
description="Setup script for re6stnet.",
formatter_class=utils.HelpFormatter)
_ = parser.add_argument
_('--registry', required=True, metavar='URL',
help="HTTP URL of the server delivering certificates.")
_('--is-needed', action='store_true',
help="Exit immediately after asking the registry CA. Status code is"
" non-zero if we're already part of the network, which means"
" re6st is already running or we're behind a re6st router.")
_('--ca-only', action='store_true',
help='Only fetch CA from registry and exit.')
_('-d', '--dir',
help="Directory where the key and certificate will be stored.")
_('-r', '--req', nargs=2, action='append', metavar=('KEY', 'VALUE'),
help="The registry only sets the Common Name of your certificate,"
" which actually encodes your allocated prefix in the network."
" You can repeat this option to add any field you want to its"
" subject.")
_('--email',
help="Email address where your token is sent. Use -r option if you"
" want to show an email in your certificate.")
_('--token', help="The token you received.")
_('--anonymous', action='store_true',
help="Request an anonymous certificate. No email is required but the"
" registry may deliver a longer prefix.")
config = parser.parse_args()
if config.dir:
os.chdir(config.dir)
conf_path = 're6stnet.conf'
ca_path = 'ca.crt'
cert_path = 'cert.crt'
key_path = 'cert.key'
dh_path = 'dh2048.pem'
# Establish connection with server
s = registry.RegistryClient(config.registry)
# Get CA
ca = s.getCa()
network = utils.networkFromCa(loadCert(ca))
if config.is_needed:
route, err = subprocess.Popen(('ip', '-6', '-o', 'route', 'get',
utils.ipFromBin(network)),
stdout=subprocess.PIPE).communicate()
sys.exit(err or route and
utils.binFromIp(route.split()[8]).startswith(network))
create(ca_path, ca)
if config.ca_only:
sys.exit()
# Generating dh file
if not os.access(dh_path, os.F_OK):
r = subprocess.call(('openssl', 'dhparam', '-out', dh_path, '2048'))
if r:
sys.exit(r)
req = crypto.X509Req()
try:
with open(cert_path) as f:
cert = loadCert(f.read())
components = dict(cert.get_subject().get_components())
components.pop('CN', None)
except IOError, e:
if e.errno != errno.ENOENT:
raise
components = {}
if config.req:
components.update(config.req)
subj = req.get_subject()
for k, v in components.iteritems():
if k == 'CN':
sys.exit("CN field is reserved.")
if v:
setattr(subj, k, v)
cert_fd = token_advice = None
try:
token = config.token
if config.anonymous:
if not (token is config.email is None):
parser.error("--anonymous conflicts with --email/--token")
token = ''
elif not token:
if not config.email:
config.email = raw_input('Please enter your email address: ')
s.requestToken(config.email)
token_advice = "Use --token to retry without asking a new token\n"
while not token:
token = raw_input('Please enter your token: ')
try:
with open(key_path) as f:
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
key = None
print "Reusing existing key."
except IOError, e:
if e.errno != errno.ENOENT:
raise
print "Generating 2048-bit key ..."
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
key = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
create(key_path, key, 0600)
req.set_pubkey(pkey)
req.sign(pkey, 'sha1')
req = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
# First make sure we can open certificate file for writing,
# to avoid using our token for nothing.
cert_fd = os.open(cert_path, os.O_CREAT | os.O_WRONLY, 0666)
print "Requesting certificate ..."
cert = s.requestCertificate(token, req)
if not cert:
token_advice = None
sys.exit("Error: invalid or expired token")
except:
if cert_fd is not None and not os.lseek(cert_fd, 0, os.SEEK_END):
os.remove(cert_path)
if token_advice:
atexit.register(sys.stdout.write, token_advice)
raise
os.write(cert_fd, cert)
os.ftruncate(cert_fd, len(cert))
os.close(cert_fd)
cert = loadCert(cert)
not_after = utils.notAfter(cert)
print("Setup complete. Certificate is valid until %s UTC"
" and will be automatically renewed after %s UTC" % (
time.asctime(time.gmtime(not_after)),
time.asctime(time.gmtime(not_after - registry.RENEW_PERIOD))))
if not os.path.lexists(conf_path):
create(conf_path, """\
registry %s
ca %s
cert %s
key %s
dh %s
# for udp only:
#pp 1194 udp
# increase re6stnet verbosity:
#verbose 3
# enable OpenVPN logging:
#ovpnlog
# increase OpenVPN verbosity:
#O--verb
#O3
""" % (config.registry, ca_path, cert_path, key_path, dh_path))
print "Sample configuration file created."
cn = utils.subnetFromCert(cert)
subnet = network + utils.binFromSubnet(cn)
print "Your subnet: %s/%u (CN=%s)" \
% (utils.ipFromBin(subnet), len(subnet), cn)
if __name__ == "__main__":
main()