-
Notifications
You must be signed in to change notification settings - Fork 10
/
OpenVPNConfig.py
executable file
·379 lines (328 loc) · 14.1 KB
/
OpenVPNConfig.py
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/
from __future__ import division, absolute_import, print_function, unicode_literals
import OpenSSL
import uuid
import random
import os
import json
import subprocess
import sys
sha256 = 'sha256'
if sys.version_info[:1] == (2,):
input = raw_input
sha256 = b'sha256'
def create_ca(size=2048, valid=315360000, CN=None):
"""
Creates a CA key and cert
size - The RSA key size to be used
valid - The time is seconds the key should be valid for
CN - The CN to be used for the cert. None will create a UUID
"""
if CN is None:
CN = 'CA-'+str(uuid.uuid4())
key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, size)
ca = OpenSSL.crypto.X509()
ca.set_version(2)
#ca.set_serial_number(1)
ca.get_subject().CN = CN
ca.gmtime_adj_notBefore(0)
ca.gmtime_adj_notAfter(valid)
ca.set_issuer(ca.get_subject())
ca.set_pubkey(key)
ca.add_extensions([
OpenSSL.crypto.X509Extension(b"basicConstraints", False, b"CA:TRUE"),
OpenSSL.crypto.X509Extension(b"keyUsage", False, b"keyCertSign, cRLSign"),
OpenSSL.crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=ca)
])
ca.add_extensions([
OpenSSL.crypto.X509Extension(b"authorityKeyIdentifier", False, b"keyid:always",issuer=ca)
])
ca.sign(key, sha256)
return ca, key
def create_cert(is_server, cacert, cakey, size=2048, valid=315360000, CN=None):
"""
Creates a client/server key and cert
is_server - Must be True for a server, False for a client
cacert - The OpenSSL.crypto.X509 object of the CA
cakey - The OpenSSL.crypto.PKey object of the CA
Optional:
size - The RSA key size to be used
valid - The time is seconds the key should be valid for
CN - The CN to be used for the cert. None will create a UUID
"""
if CN is None:
if is_server:
CN='server-'+str(uuid.uuid4())
else:
CN = 'client-'+str(uuid.uuid4())
key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, size)
cert = OpenSSL.crypto.X509()
cert.set_version(2)
cert.set_serial_number(random.randint(1, 99999999))
cert.get_subject().CN = CN
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(valid)
cert.set_issuer(cacert.get_subject())
cert.set_pubkey(key)
if is_server:
cert.add_extensions([
OpenSSL.crypto.X509Extension(b"basicConstraints", False, b"CA:FALSE"),
OpenSSL.crypto.X509Extension(b"keyUsage", False, b"digitalSignature,keyEncipherment"),
OpenSSL.crypto.X509Extension(b"extendedKeyUsage", False, b"serverAuth"),
OpenSSL.crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=cert),
OpenSSL.crypto.X509Extension(b"authorityKeyIdentifier", False, b"keyid:always",issuer=cacert),
OpenSSL.crypto.X509Extension(b"nsCertType", False, b"server")
])
else:
cert.add_extensions([
OpenSSL.crypto.X509Extension(b"basicConstraints", False, b"CA:FALSE"),
OpenSSL.crypto.X509Extension(b"keyUsage", False, b"digitalSignature"),
OpenSSL.crypto.X509Extension(b"extendedKeyUsage", False, b"clientAuth"),
OpenSSL.crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=cert),
OpenSSL.crypto.X509Extension(b"authorityKeyIdentifier", False, b"keyid:always",issuer=cacert),
OpenSSL.crypto.X509Extension(b"nsCertType", False, b"client")
])
cert.sign(cakey, sha256)
return cert, key
def gen_dhparams(size=2048):
"""
Generate Diffie Hellman parameters by calling openssl. Returns a string.
I don't like doing it like this but pyopenssl doesn't seem to
have a way to do this natively.
size - The size of the prime to generate.
"""
cmd = ['openssl', 'dhparam', '-out', 'dh.tmp', str(size)]
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
# Sometimes we get a non-zero exit code, no idea why...
print('Calling of openssl failed... Trying again')
subprocess.check_call(cmd)
with open('dh.tmp') as dh:
params = dh.read()
os.remove('dh.tmp')
return params
def gen_tlsauth_key():
"""Generate an openvpn secret key by calling openvpn. Returns a string."""
cmd = ['openvpn', '--genkey', '--secret', 'ta.tmp']
ret = subprocess.check_call(cmd)
with open('ta.tmp') as key:
key = key.read()
os.remove('ta.tmp')
return key
def _create_server_conf(name, confdict, port, cacert, serverkey, servercert, tls_auth=False, dh_params=None, path='.'):
if dh_params is None:
dh_params = gen_dhparams()
serverfile = open(os.path.join(path, name+'_server.ovpn'), 'w')
for key, value in confdict['both'].items():
if value is False:
continue
elif value is True:
serverfile.write(key + '\n')
elif isinstance(value, list):
for v in value:
serverfile.write(key + ' ' + v + '\n')
else:
serverfile.write(key + ' ' + value + '\n')
for key, value in confdict['server'].items():
if value is False:
continue
elif value is True:
serverfile.write(key + '\n')
elif isinstance(value, list):
for v in value:
serverfile.write(key + ' ' + v + '\n')
else:
serverfile.write(key + ' ' + value + '\n')
serverfile.write('port ' + port + '\n')
if 'meta' in confdict:
if confdict['meta'].get('embedkeys', True):
serverfile.write('<ca>\n'+cacert+'</ca>\n')
serverfile.write('<key>\n'+serverkey+'</key>\n')
serverfile.write('<cert>\n'+servercert+'</cert>\n')
serverfile.write('<dh>\n'+dh_params+'</dh>\n')
if tls_auth is not False:
serverfile.write('key-direction 0\n')
serverfile.write('<tls-auth>\n'+tls_auth+'</tls-auth>\n')
def _create_client_conf(name, confdict, host, port, cacert, clientkey, clientcert, tls_auth=False, path='.'):
clientfile = open(os.path.join(path, name+'_client.ovpn'), 'w')
clientfile.write('client\n')
clientfile.write('remote ' + host + ' ' + port + '\n')
for key, value in confdict['both'].items():
if value is False:
continue
elif value is True:
clientfile.write(key + '\n')
elif isinstance(value, list):
for v in value:
clientfile.write(key + ' ' + v + '\n')
else:
clientfile.write(key + ' ' + value + '\n')
for key, value in confdict['client'].items():
if value is False:
continue
elif value is True:
clientfile.write(key + '\n')
elif isinstance(value, list):
for v in value:
clientfile.write(key + ' ' + v + '\n')
else:
clientfile.write(key + ' ' + value + '\n')
if 'meta' in confdict:
if confdict['meta'].get('embedkeys', True):
clientfile.write('<ca>\n'+cacert+'</ca>\n')
clientfile.write('<key>\n'+clientkey+'</key>\n')
clientfile.write('<cert>\n'+clientcert+'</cert>\n')
if tls_auth is not False:
clientfile.write('key-direction 1\n')
clientfile.write('<tls-auth>\n'+tls_auth+'</tls-auth>\n')
def create_confs(name, confdict, path='.', host=None, port=None):
"""
Creates the client and server configs.
name - The name of the run which is prepended to the config file names
confdict - A dictionary representing the config parameters.
"""
if host is None:
host = str(input("Enter Hostname/IP: ")).rstrip()
if port is None:
port = str(input("Enter port number: ")).rstrip()
tls_auth = False
keysize = None
dhsize = None
if 'meta' in confdict:
if confdict['meta'].get('tls-auth', False):
tls_auth = gen_tlsauth_key()
keysize = confdict['meta'].get('keysize', 2048)
dhsize = confdict['meta'].get('dhsize', 2048)
# Create CA
cacert, cakey = create_ca(size=keysize)
text_cacert = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cacert).decode('ascii')
text_cakey = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, cakey).decode('ascii')
# Create a server
servercert, serverkey = create_cert(True, cacert, cakey, size=keysize)
serverkey = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, serverkey).decode('ascii')
servercert = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, servercert).decode('ascii')
_create_server_conf(name, confdict, port, text_cacert, serverkey, servercert, tls_auth=tls_auth, dh_params=gen_dhparams(dhsize), path=path)
# Create a client
clientcert, clientkey = create_cert(False, cacert, cakey, size=keysize)
clientkey = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, clientkey).decode('ascii')
clientcert = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, clientcert).decode('ascii')
_create_client_conf(name, confdict, host, port, text_cacert, clientkey, clientcert, tls_auth=tls_auth, path=path)
if 'meta' in confdict:
if confdict['meta'].get('savecerts', False):
try:
with open(name+'_client.cer', 'w') as fileout:
fileout.write(clientcert)
except Exception as e:
print('Unable to write', name+'_client.cer')
print(e)
try:
with open(name+'_client.key', 'w') as fileout:
fileout.write(clientkey)
except Exception as e:
print('Unable to write', name+'_client.key')
print(e)
try:
with open(name+'_server.cer', 'w') as fileout:
fileout.write(servercert)
except Exception as e:
print('Unable to write', name+'_server.cer')
print(e)
try:
with open(name+'_server.key', 'w') as fileout:
fileout.write(serverkey)
except Exception as e:
print('Unable to write', name+'_server.key')
print(e)
try:
with open(name+'_ca.cer', 'w') as fileout:
fileout.write(text_cacert)
except Exception as e:
print('Unable to write', name+'_ca.cer')
print(e)
try:
with open(name+'_ca.key', 'w') as fileout:
fileout.write(text_cakey)
except Exception as e:
print('Unable to write', name+'_ca.key')
print(e)
def _parse_args():
"""Parse command line args"""
import argparse
parser = argparse.ArgumentParser(description='Create OpenVPN client/server configs.')
parser.add_argument('-i', '--interactive', action='store_true', help='Interactively configure templates')
parser.add_argument('-t', '--template', help='The config file/directory to use', default=os.path.join(os.path.dirname(__file__), 'templates'))
parser.add_argument('-s', '--server', help='The hostname or ip of the server to use', default=None)
parser.add_argument('-p', '--port', help='The port number to use', default=None)
parser.add_argument('-n', '--name', help='The name to use when saving configs', default=None)
return parser.parse_args()
def _ask_template(templates):
"""Prompts user for the template to use"""
i = 1
print('Which template would you like to use?')
for template in templates:
print(i, ') ', template['meta']['name'], ': ', template['meta']['description'],sep='')
i += 1
ret = int(input('Enter selection: '))
while ret <= 0 or ret > i-1:
ret = int(input('Enter selection: '))
return templates[ret-1]
def _ask_interactive():
conf_changes = {'meta': {}, 'client': {}, 'server': {}}
ret = input('Would you like to allow more then one client to connect with the same config at the same time? [Y/n]: ').lower()
if ret == 'n':
conf_changes['server']['duplicate-cn'] = False
else:
conf_changes['server']['duplicate-cn'] = True
return conf_changes
def main():
args = _parse_args()
# Read in configs
confs = []
if os.path.isdir(args.template):
dir_list = os.listdir(args.template)
for filename in dir_list:
filename = os.path.join(args.template, filename)
if os.path.isfile(filename):
with open(filename, 'r') as fh:
try:
data = json.loads(fh.read())
except Exception as e:
print('WARNING:', filename, 'is not valid json.', e, file=sys.stderr)
continue
if 'meta' in data:
if 'name' not in data['meta']:
data['meta']['name'] = filename
if 'description' not in data['meta']:
data['meta']['description'] = ''
confs.append(data)
elif os.path.isfile(args.template):
with open(args.template, 'r') as fh:
try:
confs.append(json.loads(fh.read()))
except Exception as e:
print('WARNING:', args.template, 'is not valid json.', e, file=sys.stderr)
else:
print('ERROR:', args.template, 'is not valid file or dir.', file=sys.stderr)
if len(confs) == 0:
print('ERROR: No valid templates to use', file=sys.stderr)
exit(-1)
elif len(confs) == 1:
template = confs[0]
else:
template = _ask_template(confs)
name = args.name
if name is None:
name = input('Enter a name for the configs: ')
if args.interactive:
updates = _ask_interactive()
for key in updates:
template[key].update(updates[key])
create_confs(name, template, host=args.server, port=args.port)
if __name__ == "__main__":
main()