-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcert-tool.py
executable file
·1949 lines (1432 loc) · 51.7 KB
/
cert-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
#
# Simple tool to manage SSL PKI infrastructure
#
# This script helps manage local CA, server certs, client certs, CRLs
# etc.
#
# Author: Sudhi Herle <sw @ herle.net>
# (c) Sudhi Herle
# License: GPLv2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
import os, sys, signal, glob
import string, textwrap, cStringIO
import shutil, ConfigParser, random
import subprocess, re, zipfile
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 = "(cert-tool) "
__version__ = "1.0"
__author__ = "Sudhi Herle <sw @ herle.net>"
__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"""
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
def randnum(n=4):
"""Return a 'n' decimal digit random number"""
l = 10L ** (n - 1)
#print "%ld <= x < %ld" % (l, l *10)
v = random.randint(l, (l * 10) - 1)
return v
#return "%ld" % v
def randpass(n):
"""Generate password n bytes long chosen from chars in
sampleset"""
sampleset = list(string.letters + string.digits)
random.shuffle(sampleset)
x = []
size = len(sampleset)
while n > 0:
if n > size:
s = size
else:
s = n
x += random.sample(sampleset, s)
n -= s
return ''.join(x)
def randenv():
"""Generate a random environment var name"""
a = randpass(8)
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
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, Verbose
db = DB
pwd = os.getcwd()
args = ['openssl', cmd, ] + argv
if use_config:
args += [ '-config', DB.sslconf ]
if Verbose:
args += [ '-verbose' ]
#os.chdir(db.crtdir)
env = os.environ.copy()
env.update(DB.config_file().ssl_env())
env.update(additional_env)
debug("PWD: %s", os.getcwd())
debug("OpenSSL: %s", ' '.join(args))
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
err = p.stderr.readlines()
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'"""
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 ..
""" % 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)
# Remove any stale temporaries
for f in glob.iglob(tmp + "*"):
os.unlink(f)
def create_file(fn, s):
"""Create file 'fn' with the contents from string 's'"""
tmp = fn + '.tmp'
fd = open(tmp, 'w')
fd.write(s)
fd.close()
debug("Created file %s..", fn)
rename(tmp, fn)
def rmfiles(*files):
"""Remove one or more files"""
debug("# rm -f %s", ' '.join(files))
for f in files:
os.unlink(f)
def rmtree(dn):
"""pythonic rm -rf"""
debug("# rm -rf %s .." % dn)
shutil.rmtree(dn, ignore_errors=True)
def _xxxpath(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'
_crtdir = 'certs'
_crldir = 'crl'
_crlfile = join('crl', 'crl.pem')
_serial = 'serial'
_index = 'index.txt'
def __init__(self, dbdir):
self.__dict__['dbdir'] = dbdir
self.__dict__['tooldb'] = None
debug("Using %s as the DB dir ..", dbdir)
def __getattr__(self, arg):
names = [arg]
if not arg.startswith('_'):
names.append('_' + arg)
# Order of lookups of dicts. We first look in the class instance
# and then the class itself.
dicts = [ self.__dict__, self.__class__.__dict__ ]
v = None
for n, d in [ (x,y) for x in names for y in dicts ]:
if n in d:
v = d[n]
break
if v is None:
raise AttributeError, arg
#debug("%s? => %s/%s", arg, self.dbdir, v)
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])
tbl[key] = x[1]
attr = bundle(tbl)
return attr
def config_file(self, force=False):
"""Return an instance of a parsed tool conf file"""
if force or self.tooldb is None:
cnf = self.toolconf
debug("Reading config file '%s' ...", cnf)
self.__dict__['tooldb'] = config_file(cnf)
self.tooldb.dump()
return self.tooldb
def section(self, arg):
"""Handy alias for config_file.section"""
return self.tooldb.section(arg)
def crldb(self):
"""Parse and return CRL entries"""
crl_file = self.crlfile
if not os.path.isfile(crl_file):
error(0, "No CRL or CRL is empty. Nothing to show")
return []
certdb = self.certdb()
# now, read the CRL and process the data
list_crl_exe = 'openssl crl -text -noout -in %s' % crl_file
crls = os.popen(list_crl_exe, 'r')
revoked = {}
for x in crls:
x = x.strip()
if not x.startswith('Serial Number:'):
continue
debug("Revoked %s", x)
serial = int(x.split(':')[1].strip())
if serial not in certdb:
error(0, 'Serial# %s is not in the certificate DB', serial)
continue
else:
d = certdb[serial]
if d.status != 'R':
error(0, "Serial# %s is not revoked?! ** Consistency error**!", serial)
else:
revoked[serial] = d
#d.serial = serial
#revoked.append(d)
#print '%s: %s' % (serial, d.cn)
crls.close()
return revoked
def certdb(self):
"""Parse index.txt"""
#global DB
#idx = DB.index
idx = self.index
fd = open(idx, 'rb')
db = {}
for x in fd:
v = x.strip().split()
status = v[0]
if status == 'V':
rest = ' '.join(v[4:])
serial = int(v[2])
else:
serial = int(v[3])
rest = ' '.join(v[5:])
details = self.split_cn(rest)
details.status = v[0]
details.serial = serial
db[serial] = details
debug("index: serial=%d/%x, rest=%s", serial, serial, details)
fd.close()
return db
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 update(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 PKI Certificate DB
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 CA 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"""
progress("Initializing DB dir %s ..", db.dbdir)
dirs = [db.dbdir, db.crtdir, db.crldir]
for d in dirs:
if not os.path.exists(d):
os.makedirs(d, 0700)
def run(self, args):
global DB
global SSL_conf_template, CA_Template
global Tool_conf_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
#print ssl, cnf
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)
# There can be no subst's in this file - since it is the one
# containing all the useful info.
create_file(cnf, Tool_conf_template)
# Fork an editor from here and let user update the file.
edit_file(cnf)
# Read the config file now and populate global dir.
db = DB.config_file(force=True)
# standard substitutions
subst = { 'Z': Z,
'date': today(),
#'ca_name': db['openssl.company'] + " Trust Authority",
'ca_name': 'Root_CA',
'ca_cert': 'ca.crt',
'ca_key': 'ca.key',
'dbdir': DB.dbdir,
}
subst.update(db.section('openssl'))
subst.update(db.section('general'))
debug("subst:\n%s\n", "".join([" %s=%s\n" % (a, b) for a, b in subst.items()]))
ssl_cnf = (SSL_conf_template + CA_Template) % subst
progress("Generating config files %s ..", ssl)
create_file(ssl, ssl_cnf)
e = db.ssl_env()
create_file(DB.serial, e['KEY_SERIAL'])
create_file(DB.index, "")
self.make_ca()
def make_ca(self):
"""create CA certs, DH keys etc."""
global DB
db = DB
cf = db.config_file()
env = cf.ssl_env()
co = cf['openssl.company']
xtra_env = {
'KEY_OU': co + ' SSL Certificates Division',
'KEY_CN': co + ' Root CA'
}
# For the root CA, we will do 20 year life time.
# Should be sufficient for most use cases.
env['KEY_DAYS'] = "%d" % int(20 * 365.25)
progress("Generating CA certificates ..")
openssl('genrsa', ['-out', join(db.crtdir, 'ca.key'), env['KEY_SIZE']])
openssl('req', ['-batch', '-days', env['KEY_DAYS'],
'-set_serial', env['KEY_CA_SERIAL'], '-new',
'-x509', '-key', join(db.crtdir, 'ca.key'),
'-out', join(db.crtdir, 'ca.crt'),
'-extensions', 'v3_ca'],
xtra_env)
class generic_cert_command(command):
"""Base class for generating any kind of certificate.
There will be three derived instances:
- server cert
- client cert
- intermediate CA cert
"""
# Need to set:
# KEY_OU="$KEY_CN client certificate"
# KEY_CN="[email protected]"
def __init__(self):
super(generic_cert_command, self).__init__()
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 certificate private key [%default]")
self.parser.add_option("-r", "--random",
dest="random", action="store_true",
default=False,
help="Generate random password(s) for encrypting the certificate private key [%default]")
self.parser.add_option("-i", "--inter",
dest="inter", type="string",
default=None, metavar='F',
help="Use intermediate CA 'F' to sign the certificate [%default]")
self.parser.add_option("-e", "--expiry",
dest="expiry", type="string",
default="+1Y", metavar='T',
help="Set the certificate to expire on date 'T' (can be relative \
date like +1Y, +1M, +1D etc.) [%default]")
def make_cert(self, user, passwd=None, def_config=True, xtra_ca_args=[]):
"""Add one user to the system"""
global DB
debug("Making new cert %s (%s) '%s' extension", user, passwd if passwd else ":NOPASS:", self.extension)
db = DB
cf = db.config_file()
if self.fqdn:
user = cf.fqdn(user)
email = 'certadmin@' + user
else:
user = cf.email(user)
email = user
xtra_env = {
'KEY_OU': cf.ou(),
'KEY_CN': user,
'KEY_EMAIL': email,
}
crt = join(DB.crtdir, user + '.crt')
key = join(DB.crtdir, user + '.key')
csr = join(DB.crtdir, user + '.csr')
args = ['-batch', '-days', "%d" % cf.expiry(), ]
rsa_args = []
csr_args = args + ['-new', '-key', key, '-out', csr, '-extensions', self.extension]
ca_args = args + ['-out', crt, '-in', csr , '-extensions', self.extension]
if passwd is not None:
passenv = randenv()
xtra_env[passenv] = passwd
rsa_args += ['-des3', '-passout', 'env:%s' % passenv ]
rsa_args += ['-out', key, "%d" % cf.keysize() ]
# Generate key & CSR
openssl('genrsa', rsa_args, xtra_env)
openssl('req', csr_args, xtra_env)
# Now, sign the CSR by the CA key
openssl('ca', ca_args + xtra_ca_args, xtra_env, use_config=def_config)
def run(self, args):
global DB
db = DB
cf = db.config_file()
opt, argv = self.parser.parse_args(args=args[1:])
if len(argv) < 1:
raise ex("Insufficient arguments. Try '%s --help'", self.name)
if opt.inter:
if opt.inter.find('.') < 0:
inter = cf.fqdn(opt.inter)
else:
inter = opt.inter
cnf = join(db.dbdir, inter + '.cnf')
if not os.path.isfile(cnf):
raise ex("Can't find intermediate CA config %s", cnf)
ca_crt = join(db.crtdir, inter + '.crt')
ca_key = join(db.crtdir, inter + '.key')
if not os.path.isfile(ca_crt):
raise ex("Can't find intermediate CA certificate %s", ca_crt)
if not os.path.isfile(ca_key):
raise ex("Can't find intermediate CA key %s", ca_key)
xtra_ca_args = ['-name', inter, '-config', cnf ]
def_config = False
caname = inter
else:
def_config = True
xtra_ca_args = ['-name', 'Root_CA',]
caname = 'ROOT_CA'
for v in argv:
crt = join(db.crtdir, v + '.crt')
if os.path.isfile(crt):
error(0, "Certificate %s' already exists!", v)
continue
if opt.random:
p = randpass(8)
print "Password for %s: %s" % (v, p)
elif opt.passwd is not None:
p = opt.passwd
else:
p = None
progress("Generating certificate %s and signing with %s", v, caname)
self.make_cert(v, p, def_config=def_config, xtra_ca_args=xtra_ca_args)
# Call hook function if one exists
self.cert_done_hook(v)
def cert_done_hook(self, nm):
pass
class client(generic_cert_command):
"""Generate one or more client certificates and private key.
client [options] name [name...]
'name' should preferably be of the form '[email protected]' -
e.g., like an email address.
If multiple names are specified and "--password" option is
chosen, then the same password is assigned to all the names.
"""
extension = 'usr_cert'
def __init__(self):
super(client, self).__init__()
self.name = 'client'
self.fqdn = False
self.cmd_aliases = []
class server(generic_cert_command):
"""Generate one or more server certificates and private key.
server [options] name [name...]
'name' should preferably be of the form 'sub.domain.com'
e.g., a fully qualified domain name.
If multiple names are specified and "--password" option is
chosen, then the same password is assigned to all the private
keys.
"""
extension = 'server_cert'
def __init__(self):
super(server, self).__init__()
self.name = 'server'
self.fqdn = True
self.cmd_aliases = []
class inter(generic_cert_command):
"""Generate one or more intermediate CA certificates.
inter [options] name [name...]
'name' will be something to use in future 'server' and/or
'client' commands.
"""
extension = 'v3_ca'
def __init__(self):
super(inter, self).__init__()
self.name = 'inter'
self.fqdn = True
self.cmd_aliases = ['intermediate_ca']
def cert_done_hook(self, nm):
global DB, CA_Template
db = DB
cf = db.config_file()
if nm.find('.') < 0:
nm = cf.fqdn(nm)
cnf = join(db.dbdir, nm + '.cnf')
# Now, generate a separate cnf file for the intermediate CA
subst = { 'Z': Z,
'date': today(),
'ca_name': nm,
'ca_cert': nm + '.crt',
'ca_key': nm + '.key',
'dbdir': db.dbdir,
}
subst.update(db.section('openssl'))
subst.update(db.section('general'))
progress("Creating an intermediate CA config %s ..", cnf)
create_file(cnf, CA_Template % subst)
# To build an intermediate CA:
# - build a req and sign with v3_ca extension
# - generate a new $inter.cnf file
# This file is a copy of default_ca but with the ca and key
# directives pointing to $inter.{crt,key}
#
# To sign with an intermediate CA:
# - use "-name" of ca to point to the section in $inter.cnf
# - point the 'ca' command to the $inter.cnf conf file:
# * -extfile $inter.crt
# * -extension inter_ca -- this should be in the extfile