-
Notifications
You must be signed in to change notification settings - Fork 4
/
ovpn-tool.py
executable file
·2548 lines (1925 loc) · 70.1 KB
/
ovpn-tool.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
#
# Comprehensive Tool to manage OpenVPN PKI infrastructure, config files
# and client certificates for users.
#
# Author: Sudhi Herle <[email protected]>
# Date: October 2007
# License: GPLv2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
import os, sys, signal
import string, textwrap, cStringIO
import shutil, ConfigParser, random
import subprocess, re, zipfile, itertools
from os.path import basename, dirname, abspath, normpath, join
from optparse import Option, OptionParser, OptionValueError
from datetime import datetime
import smtplib, random
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
# GLobal vars
Z = basename(sys.argv[0])
Quit_Loop = False
Debug = False
Verbose = False
DB = None
Prompt = "(ovpn-tool) "
Tool_conf_db = {}
User_db = None
__version__ = "0.9.5"
__author__ = "Sudhi Herle <[email protected]>"
__license__ = "GPLv2 [http://www.gnu.org/licenses/old-licenses/gpl-2.0.html]"
def sighandler(sig,frm):
"""Trivial signal handler"""
global Quit_Loop
Quit_Loop = True
def _exit(rc):
"""Wrapper around sys.exit() to close the user database"""
if User_db is not None:
User_db.finalize()
sys.exit(rc)
def error(doexit, fmt, *args):
"""Clone of the glibc error() function"""
sfmt = "%s: %s" % (Z, fmt)
sys.stdout.flush()
print >>sys.stderr, sfmt % args
sys.stderr.flush()
if doexit:
_exit(1)
def debug(fmt, *args):
"""Print a debug message"""
global Debug
if not Debug:
return
sfmt = "# %s" % fmt
print sfmt % args
sys.stdout.flush()
def progress(fmt, *args):
"""Print a progress message"""
global Verbose
if not Verbose:
return
print fmt % args
sys.stdout.flush()
def today():
"""Return today's time in string form"""
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S %Z")
return now
class randpass_gen(object):
"""Generate random, human readable passwords.
Clever algorithm is due to Herman Schaaf.
"""
initial_consonants = (set(string.ascii_lowercase) - set('aeiou')
# remove those easily confused with others
- set('qxc')
# add some crunchy clusters
| set(['bl', 'br', 'cl', 'cr', 'dr', 'fl',
'fr', 'gl', 'gr', 'pl', 'pr', 'sk',
'sl', 'sm', 'sn', 'sp', 'st', 'str',
'sw', 'tr'])
)
final_consonants = (set(string.ascii_lowercase) - set('aeiou')
# confusable
- set('qxcsj')
# crunchy clusters
| set(['ct', 'ft', 'mp', 'nd', 'ng', 'nk', 'nt',
'pt', 'sk', 'sp', 'ss', 'st'])
)
vowels = 'aeiou' # we'll keep this simple
def __init__(self, wordcount=2, spaces=False, capital=False):
# each syllable is consonant-vowel-consonant "pronounceable"
self.syllables = map(''.join, itertools.product(self.initial_consonants,
self.vowels,
self.final_consonants))
self.words = wordcount
self.spaces = spaces
self.capital = capital
random.shuffle(self.syllables)
def password(self, n=1):
"""Generate and return a list of passwords"""
random.shuffle(self.syllables)
x = []
sep = ' ' if self.spaces else ''
#print self.syllables
#print self.__class__.syllables
while n > 0:
n -= 1
g = random.sample(self.syllables, self.words)
if self.capital:
g = [ a.capitalize() for a in g ]
x.append(sep.join(g))
return x
# Keep a single global instance for now
RP = randpass_gen(wordcount=3, capital=True)
def randpass():
"""Generate password n bytes long chosen from chars in
sampleset"""
global RP
x = RP.password(1)
return x[0]
def randenv():
"""Generate a random environment var name"""
sampleset = list(string.letters + string.digits)
random.shuffle(sampleset)
x = []
n = 10
size = len(sampleset)
while n > 0:
if n > size:
s = size
else:
s = n
x += random.sample(sampleset, s)
n -= s
a = ''.join(x)
if a[0] in string.digits:
a = "x" + a
return a
class ex(Exception):
"""Our exception"""
def __init__(self, str, *args):
self.str = str % args
Exception.__init__(self, self.str)
def __repr__(self):
return self.str
__str__ = __repr__
def abbrev(wordlist):
"""abbrev - a simple function to generate an abbreviation table of
unambiguous words from an input wordlist.
Originally from perl4/perl5 sources.
Converted to Python by Sudhi Herle <[email protected]>
Copyright (C) 2004-2005 Free Software Foundation
Python code (C) 2005-2008 Sudhi Herle <[email protected]>
Licensed under the terms of Aritistic License (Perl) or GNU GPLv2.
Synopsis::
import abbrev
table = abbrev.abbrev(wordlist)
Stores all unambiguous truncations of each element of
`wordlist` as keys in a table. The values in the table are
the original list elements.
Example::
wordlist = [ "help", "hello", "sync", "show" ]
table = abbrev.abbrev(wordlist)
print table
# Read short-form from stdin
short_form = sys.stdin.readline().strip()
# Now, given an abbreviation of one of the words in
# 'wordlist', you can check if the abbreviation
# is unique like so:
if short_form not in table:
print "No unique abbreviation available"
This will print::
{'sy': 'sync', 'help': 'help', 'show': 'show',
'sync': 'sync', 'syn': 'sync', 'sh': 'show',
'hell': 'hello', 'hello': 'hello', 'sho': 'show'}
(The order of the keys may differ depending on your
platform)
"""
abbrev_seen = {}
table = {}
for word in wordlist:
table[word] = word[:]
l = len(word)-1
while l > 0:
ab = word[0:l]
if ab in abbrev_seen:
abbrev_seen[ab] = abbrev_seen[ab] + 1
else:
abbrev_seen[ab] = 0
ntimes = abbrev_seen[ab]
if ntimes == 0: # first time we're seeing this abbrev
table[ab] = word
elif ntimes == 1:
# This is the second time. So, 'ab' is ambiguous.
# And thus, can't be used in the final dict.
del table[ab]
else:
break
l = l - 1
# end of while len > 0
return table
def rename(a, b):
"""Rename a -> b.
On Win32, os.rename() fails for destination files that exist.
"""
if os.path.exists(b):
if os.path.isfile(b):
os.unlink(b)
elif os.path.isdir(b):
rmtree(b)
else:
raise ex, "Unknown file type for '%s'; can't rename!" % b
os.rename(a, b)
def openssl(cmd, argv, additional_env={}, use_config=True):
"""Convenient wrapper around the openssl command. It sets up some
standard environment variables and also changes directory to the
certificate db dir.
If additional_env is present, it is appended to the sub-processes'
environment.
If use_config is false, then the "-config $CONFIG_FILE" option won't
be passed on the openssl command line.
"""
global DB
pwd = os.getcwd()
args = ['openssl', cmd, ] + argv
if use_config:
args += [ '-config', DB.sslconf ]
os.chdir(DB.crtdir)
env = os.environ.copy()
env.update(Tool_conf_db.ssl_env())
env.update(additional_env)
env['KEY_DIR'] = DB.dbdir
debug("OpenSSL: %s", ' '.join(args))
p = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
err = ''
while p.poll() is None:
o = p.stdout.readline()
e = p.stderr.readline()
if o:
sys.stdout.write(o)
sys.stdout.flush()
if e:
err += e
sys.stderr.write(e)
sys.stdout.flush()
ex = p.wait()
if ex < 0:
error(0, "Process 'openssl %s' caught signal %d and died!",
cmd, -ex)
if len(err) > 0:
error(1, ''.join(err))
else:
_exit(1)
elif ex > 0:
error(0, "Process 'openssl %s' exited abnormally (code %d); error follows..", cmd, ex)
if len(err) > 0:
error(1, ''.join(err))
else:
_exit(1)
debug("OpenSSL %s: OK", cmd)
os.chdir(pwd)
def edit_file(filename):
"""Fork an editor and edit the file 'filename'"""
dn = dirname(filename)
tmp = filename + '.tmp_%d' % os.getpid()
shutil.copy2(filename, tmp)
ed = None
for k in [ 'EDITOR', 'VISUAL', ]:
ed = os.environ.get(k, None)
if ed is not None:
break
if ed is None:
error(0, "Can't find usable editor to edit %s", filename)
raise ex, "Please set environment var EDITOR appropriately"
argv = [ ed, tmp ]
debug("Calling '%s' ..", ' '.join(argv))
rc = subprocess.call(argv)
if rc < 0:
error(1, "Process '%s' caught signal %d and died!",
ed, -rc)
elif rc > 0:
error(1, "Process '%s' exited abnormally (code %d)", ed, rc)
rename(tmp, filename)
def create_file(fn, str, subst=None):
"""Create file 'fn' with the contents from string 'str'"""
tmp = fn + '.tmp'
fd = open(tmp, 'w')
if subst is not None:
fd.write(str % subst)
else:
fd.write(str)
fd.close()
rename(tmp, fn)
def rmfiles(*files):
"""Remove one or more files"""
for f in files:
os.unlink(f)
def rmtree(dir):
"""pythonic rm -rf"""
for root, dirs, files in os.walk(dir, 0):
for f in files:
here = join(root, f)
os.unlink(here)
for d in dirs:
here = join(root, d)
os.rmdir(here)
os.rmdir(dir)
def make_ovpn_secret(of, bits=2048):
"""Make a 2048 bit shared secret key for OpenVPN.
This secret key will prevent a majority of DoS attacks on the UDP
version of OpenVPN.
We are going to generate this key based on V1 of the OpenVPN tool.
"""
r = random.Random()
bb = bits / 8
v = []
n = 0
while bb > 0:
x = "%02x" % r.randint(0,255)
if (n % 16) == 0:
v.append('\n')
n += 1
bb -= 1
v.append(x)
fd = open(of, 'wb')
fd.write("""#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----%s
-----END OpenVPN Static key V1-----
""" % ''.join(v))
fd.close()
def read_db_file(a, *args):
"""Join one or more path components and read the contents of the file"""
fn = a
if args:
fn = os.path.join(a, *args)
fd = open(fn)
buf = fd.read()
fd.close()
return buf
def make_conf(zf, u):
"""Make a .ovpn config file named 'zf' for user 'u'."""
global Client_config_template
global DB
global Tool_conf_db
progress("Creating conf file %s for user %s ..", zf, u)
db = Tool_conf_db
srv = db.vpn_server()
#z = zipfile.ZipFile(zf, 'w', zipfile.ZIP_DEFLATED)
crt = "%s.crt" % u
key = "%s.key" % u
d = { 'today': today(),
'username': u,
'client': u,
'vpnserver': srv,
'proto': db['openvpn.proto'],
'vpnport': db.vpn_server_port(),
'ca_cert': read_db_file(DB.crtdir, 'ca.crt'),
'user_key': read_db_file(DB.crtdir, key),
'user_cert': read_db_file(DB.crtdir, crt),
'tls_secret': read_db_file(DB.secret)
}
#debug("user dict = \n%s\n", str(d))
cfg = Client_config_template % d
fd = open(zf, "w", 0600)
fd.write(cfg)
fd.close()
def _path(p):
"""Simplify the path by stripping out leading string of DBDIR"""
global DB
if p.startswith(DB.dbdir):
n = len(DB.dbdir)
return "DBDIR" + p[n:]
return p
class opt_parser(OptionParser):
"""Wrapper around option parser to override the meaning of
"exit()". In our case, we return StopIteration to break out of
the call chain and resume the main loop."""
def exit(self, status=0, msg=None):
if msg:
sys.stderr.write(msg)
# This exception
raise StopIteration
class config(object):
"""Abstraction of a DB config.
We make it easy to set just one variable the base-dir for the cert
storage. And, the __getattr__ override provides suitable instance
variables for all other paths that are within the base-dir tree.
"""
_sslconf = 'openssl.cnf'
_toolconf = 'ssltool.conf'
_userdb = 'passwd'
_crtdir = 'certs'
_crldir = 'crl'
_crlfile = join('crl', 'crl.pem')
_confdir = 'conf'
_serial = 'serial'
_index = 'index.txt'
_email = 'email.txt'
_secret = 'server_secret.key'
_serverconf = 'server.conf'
def __init__(self, dbdir):
self.__dict__['dbdir'] = dbdir
debug("Using %s as the DB dir ..", dbdir)
def __getattr__(self, arg):
priv = "_" + arg
v = getattr(self, priv)
if v is None:
raise AttributeError, arg
return normpath(join(self.dbdir, v))
def __setattr__(self, arg, val):
raise NotImplementedError, "Can't set %s=%s; This class is Read-Only" % (arg, val)
@staticmethod
def split_cn(s):
"""Split a string of the form
/C=US/ST=TX/L=Richardson/O=Snakeoil Industries Inc/[email protected]/[email protected]/[email protected]
into constituent parts"""
v = s.split('/')
tbl = {}
for i in v:
if i.find('=') < 0:
continue
x = i.split('=')
debug("CN %s => %s", s, repr(x))
key = string.lower(x[0])
val = x[1]
tbl[key] = val
attr = bundle(tbl)
return attr
def parse_index(self):
"""Parse index.txt"""
idx = DB.index
fd = open(idx, 'rb')
certdb = {}
for x in fd:
v = x.strip().split()
status = v[0]
if status == 'V':
rest = ' '.join(v[4:])
serial = v[2]
else:
serial = v[3]
rest = ' '.join(v[5:])
details = self.split_cn(rest)
details.status = v[0]
details.serial = serial
certdb[serial] = details
debug("index: serial=%s, rest=%s", serial, details)
fd.close()
return certdb
class bundle:
"""Simplistic class to make it easy for referring to instance
attributes (sort of like 'C struct')."""
def __init__(self, kwargs):
self.__dict__.update(kwargs)
def __setattr__(self, key, val):
self.__dict__[key] = val
def __repr__(self):
"""Print string representation"""
s = ""
for k, v in self.__dict__.items():
if not k.startswith('_'):
s += "%s=%s|" % (k, v)
return s
class command(object):
"""Abstraction of a command"""
def __init__(self):
self.name = "NONE"
self.cmd_aliases = []
def run(self, args):
"""Run the command"""
pass
def name(self):
return self.name
def help(self):
"""Display the doc string in a nicely formatted fashion"""
d = self.__doc__
if d is None:
return ""
x = cStringIO.StringIO(d)
h = x.readline()
h = x.readline().strip()
if len(h) == 0:
rest = ""
else:
rest = h + "\n"
for line in x:
rest += line
x.close()
return textwrap.dedent(rest)
def usage(self):
"""Construct the optparse help string and return it"""
if hasattr(self, "parser"):
usage = self.parser.format_help()
else:
usage = self.help()
return usage
def brief_help(self):
"""Return first line of the doc string"""
d = self.__doc__
if d is None:
return "*NONE*"
x = cStringIO.StringIO(d)
h = x.readline().strip()
x.close()
return h
def aliases(self):
"""Return the command and its aliases"""
a = [ self.name ]
if hasattr(self, "cmd_aliases"):
a += self.cmd_aliases
return a
class init(command):
"""Initialize a SSL Certificate DB for OpenVPN
init [options] [DBDIR]
If DBDIR is not given, the default from the command line is
used.
"""
def __init__(self):
super(init, self).__init__()
self.name = 'init'
self.parser = opt_parser(usage=self.help())
self.parser.add_option("", "--overwrite",
dest="overwrite", action="store_true", default=False,
help="Overwrite previous config and re-initialize DB")
self.parser.add_option("-p", "--passwd",
dest="passwd", action="store", type="string",
default=None, metavar="P",
help="Use password 'P' for encrypting the private key")
def cleanup(self, dn):
"""Cleanup a previous installation of DB dir"""
progress("Cleaning up existing install in %s", dn)
tmp = dn + '.tmp'
rename(dn, tmp)
rmtree(tmp)
def create_dirs(self, db):
"""Make required directories in the DB dir"""
os.makedirs(db.dbdir, 0700)
os.makedirs(db.crtdir, 0700)
os.makedirs(db.confdir, 0700)
os.makedirs(db.crldir, 0700)
def run(self, args):
global DB
global SSL_conf_template
global Tool_conf_template
global Email_template
opt, argv = self.parser.parse_args(args=args[1:])
if len(argv) > 0:
DB = config(argv[0])
# Don't set this vars unless db-dir is updated correctly
# above
ssl = DB.sslconf
cnf = DB.toolconf
if os.path.isfile(cnf) and os.path.isfile(ssl):
if opt.overwrite:
self.cleanup(DB.dbdir)
else:
raise ex, "Can't initialize in existing directory %s" % DB.dbdir
# Now, create the files from local templates
self.create_dirs(DB)
create_file(ssl, SSL_conf_template)
create_file(cnf, Tool_conf_template)
create_file(DB.email, Email_template)
create_file(DB.serial, "14")
create_file(DB.index, "")
print """
Starting Editor for
%s
Please edit the file and update the various fields appropriately
before using this tool to create new certificates.
Starting editor ..
""" % cnf
# Fork an editor from here and let user update the file.
edit_file(cnf)
# Read the config file now and populate global dir.
read_config()
self.make_ca()
self.generate_server_cert(opt.passwd)
self.make_server_conf()
def make_ca(self):
"""create CA certs, DH keys etc."""
global Tool_conf_db
db = Tool_conf_db
env = db.ssl_env()
co = db['openssl.company']
xtra_env = {
'KEY_OU': co + ' SSL Certificates Division',
'KEY_CN': co + ' CA Certificate',
}
progress("Generating CA certificates ..")
openssl('req', ['-batch', '-days', env['KEY_DAYS'],
'-nodes', '-set_serial', "13", '-new', '-x509',
'-keyout', 'ca.key', '-out', 'ca.crt'],
xtra_env)
progress("Generating DH param (%s bits) ..", env['KEY_SIZE'])
openssl('dhparam', ['-out', 'dh%s.pem' % env['KEY_SIZE'],
env['KEY_SIZE']], xtra_env, use_config=False)
def generate_server_cert(self, passwd):
"""Generate the OpenVPN Server certificate"""
global DB, Tool_conf_db
db = Tool_conf_db
# XXX OpenSSL 0.9.8e cannot handle time larger than 2038!
# It seems that OpenSSL 0.9.8e doesn't support the ASN.1
# "generalizedTime" format of time representation.
exp_yrs = 10
exp_days = exp_yrs * 365
server_name = db.vpn_server()
env = db.ssl_env()
xtra_env = {
'KEY_OU': db['openssl.company'] + ' SSL Certificates Division',
'KEY_CN': server_name,
'KEY_EMAIL': db['general.admin'],
}
crt = server_name + '.crt'
key = server_name + '.key'
csr = server_name + '.csr'
debug("OpenVPN server: %s", server_name)
args = ['-batch', '-days', "%d" % exp_days,
'-extensions', 'server', ]
csr_args = args + ['-new', '-keyout', key, '-out', csr, ]
ca_args = args + ['-out', crt, '-in', csr ]
if passwd is not None:
passenv = randenv()
xtra_env[passenv] = passwd
csr_args += ['-passout', 'env:%s' % passenv ]
else:
csr_args += [ '-nodes' ]
progress("Generating OpenVPN Server certificate ..")
# Generate CSR
openssl('req', csr_args, xtra_env)
# Now, sign the CSR by the CA key
openssl('ca', ca_args, xtra_env)
progress("OpenVPN server certificate is in %s.crt", server_name)
def make_server_conf(self):
"""Generate a usable OpenVPN server config file"""
global DB, Server_conf_template
global Tool_conf_db
db = Tool_conf_db
env = db.vpn_env()
server_name = db.vpn_server()
dhparam = 'dh%s.pem' % db['openssl.keysize']
# Add additional substitutions
env['vpnserver'] = server_name
env['vpnport'] = db.vpn_server_port()
env['today'] = today()
env['proto'] = db['openvpn.proto']
env['dhparam'] = dhparam
progress("Generating OpenVPN server config and zip file ..")
create_file(DB.serverconf, Server_conf_template, env)
make_ovpn_secret(DB.secret)
# Now, create a ZIP file containing the latest server config
# stuff.
files = [ server_name + '.crt', server_name + '.key',
'ca.crt', dhparam ]
zfname = join(DB.confdir, server_name + '.zip')
zf = zipfile.ZipFile(zfname, 'w', zipfile.ZIP_DEFLATED)
zf.write(DB.serverconf, server_name + '.conf')
zf.write(DB.secret, server_name + '.secret')
for f in files:
zf.write(join(DB.crtdir, f), f)
readme = """Congratulations!
Your OpenVPN server config is ready for use.
Please pick up a zipfile containing all the necessary files for
OpenVPN server here:
%s
Expand the contents of this file into the OpenVPN server
directory config - e.g., /etc/openvpn on Linux systems.
It is important to keep the permissions of the '.key' file very
strict. e.g., on Unix systems, do
chmod 0600 %s.key
chmod 0600 %s.secret
If required, please edit
%s
This template will be used for
sending out automated emails to your users with the appropriate
OpenVPN client config whenever a new user is added.
""" % (normpath(zfname), server_name, server_name, DB.email)
zf.writestr('README.txt', readme)
zf.close()
print readme
class client(command):
"""Generate one or more client certificates and private key.
client [options] user-id [user-id...]
'user-id' should preferably be of the form '[email protected]' -
e.g., like an email address.
If multiple users are specified and "--password" option is
chosen, then the same password is assigned to all the users.
Thus, it is recommended that "--random" option be chosen when
multiple users are specified on the command line.
"""
# Need to set:
# KEY_OU="$KEY_CN client certificate"
# KEY_CN="[email protected]"
def __init__(self):
super(client, self).__init__()
self.name = 'client'
self.cmd_aliases = [ 'adduser', 'newuser' ]
self.parser = opt_parser(usage=self.help())
self.parser.add_option("-p", "--passwd",
dest="passwd", action="store", type="string",
default=None, metavar="P",
help="Use password 'P' for encrypting the client certificate private key")
self.parser.add_option("-r", "--random",
dest="random", action="store_true",
default=False,
help="Generate random password(s) for encrypting the client certificate private key")
def adduser(self, user, passwd):
"""Add one user to the system"""
global DB, Tool_conf_db, User_db
debug("Adding user=%s pass=%s", user, passwd)
db = Tool_conf_db
env = db.ssl_env()
co = db['openssl.company']
xtra_env = {
'KEY_OU': co + ' SSL Certificates Division',
'KEY_CN': user,
'KEY_EMAIL': user,
}
exp = int(db['openssl.validity'])
exp_days = 365 * exp
crt = user + '.crt'
key = user + '.key'
csr = user + '.csr'
args = ['-batch', '-days', "%d" % exp_days, ]
csr_args = args + ['-new', '-keyout', key, '-out', csr, ]
ca_args = args + ['-out', crt, '-in', csr ]
ca_args += ['-notext']
if passwd is not None:
passenv = randenv()
xtra_env[passenv] = passwd
csr_args += ['-passout', 'env:%s' % passenv ]
else:
csr_args += [ '-nodes' ]
# Generate CSR
openssl('req', csr_args, xtra_env)
# Now, sign the CSR by the CA key
openssl('ca', ca_args, xtra_env)
# add to the user db
User_db[user] = passwd
# Make a zipfile out of the client's certs
db = Tool_conf_db
zf = join(DB.confdir, '%s.ovpn' % user)
if not os.path.exists(zf):
make_conf(zf, user)
def run(self, args):
global DB
global Tool_conf_db
opt, argv = self.parser.parse_args(args=args[1:])
if len(argv) < 1:
raise ex("Insufficient arguments. Try 'client --help'")
for v in argv:
crt = join(DB.crtdir, v + '.crt')