-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathigorCA.py
executable file
·824 lines (732 loc) · 31.9 KB
/
igorCA.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
#!/usr/bin/env python3
# Enable coverage if installed and enabled through COVERAGE_PROCESS_START environment var
try:
import coverage
coverage.process_startup()
except ImportError:
pass
import sys
import igor
import os
import os.path
import shutil
import getpass
import tempfile
import subprocess
try:
import configparser
except ImportError:
import ConfigParser as configparser
import re
import json
import datetime
import argparse
import igorVar
import csv
#IS_IP=re.compile(r'^[0-9.:]*$') # Not good enough, but does not match hostnames
IS_IP=re.compile(r'^[0-9:]*$') # Matches only IPv6 IP addresses so IPv4 addresses are (incorrectly) seen as hostnames
class SSLConfigParser(configparser.RawConfigParser):
"""SSL Configuration files are case-dependent"""
SECTCRE = re.compile(
r'\[\s*' # [
r'(?P<header>[^]\s]+)' # very permissive!
r'\s*\]' # ]
)
def optionxform(self, optionstr):
return optionstr
def _distinguishedNameToDict(data):
# grr... Some openSSL implementations use / as separator, some use ,
rv = {}
if '/' in data:
dataItems = data.split('/')
for di in dataItems:
if not di: continue
diSplit = di.split('=')
k = diSplit[0]
v = '='.join(diSplit[1:])
rv[k] = v
else:
dataItems = data.split(',')
for di in dataItems:
if not di: continue
diSplit = di.split('=')
k = diSplit[0]
v = '='.join(diSplit[1:])
k = k.strip()
v = v.strip()
rv[k] = v
return rv
USAGE="""
Usage: %s [options] command [args]
Initialize or use igor Certificate Authority.
"""
class CAInterface:
"""Helper class to implement commands on local CA (using openSSL tool)"""
def __init__(self, parent, database):
self.parent = parent
self.caDatabase = os.path.join(database, 'ca')
self.intKeyFile = os.path.join(self.caDatabase, 'intermediate', 'private', 'intermediate.key.pem')
self.intCertFile = os.path.join(self.caDatabase, 'intermediate', 'certs', 'intermediate.cert.pem')
self.intAllCertFile = os.path.join(self.caDatabase, 'intermediate', 'certs', 'ca-chain.cert.pem')
self.intConfigFile = os.path.join(self.caDatabase, 'intermediate', 'openssl.cnf')
def isLocal(self):
return True
def isOK(self):
if not os.path.exists(self.caDatabase):
print("%s: No Igor CA self.database at %s" % (self.parent.argv0, self.caDatabase), file=sys.stderr)
return False
if not (os.path.exists(self.intKeyFile) and os.path.exists(self.intCertFile) and os.path.exists(self.intAllCertFile)):
print("%s: Intermediate key, certificate and chain don't exist in %s" % (self.parent.argv0, self.caDatabase), file=sys.stderr)
return False
return True
def ca_getRoot(self):
"""Return root certificate (in PEM form)"""
return open(self.intAllCertFile).read()
def ca_list(self):
"""Return list of all signatures signed"""
indexFile = os.path.join(self.caDatabase, 'intermediate', 'index.txt')
rv = []
try:
with open(indexFile) as fp:
rdr = csv.DictReader(fp, fieldnames=['status', 'timeStringExpired', 'timeStringRevoked', 'serial', 'filename', 'dn' ], dialect='excel-tab')
for row in rdr:
item = {}
item['status'] = dict(V='valid', R='revoked', E='expired').get(row['status'], 'unknown')
ts = row.get('timeStringExpired')
if ts:
dt = datetime.datetime.strptime(ts, '%y%m%d%H%M%SZ')
item['expires'] = dt.isoformat()
ts = row.get('timeStringRevoked')
if ts:
dt = datetime.datetime.strptime(ts, '%y%m%d%H%M%SZ')
item['revoked'] = dt.isoformat()
item['serial'] = row['serial']
item['dn'] = _distinguishedNameToDict(row['dn'])
rv.append(item)
except IOError:
return []
return rv
def ca_signCSR(self, csr):
#
# Save the CSR to a file
#
_, csrFile = tempfile.mkstemp('.csr')
open(csrFile, 'w').write(csr)
#
# Get commonName and subjectAltName from the CSR
#
dnDict = self.parent.get_distinguishedName('req', csrFile)
if not dnDict:
return None
commonName = dnDict['CN']
altNames = self.parent.get_altNamesFromReq(csrFile)
#
# Create signing config file
#
csrConfigFile = self.parent.gen_configFile(commonName, altNames)
if not csrConfigFile:
return None
#
# Sign CSR
#
_, certFile = tempfile.mkstemp('.cert')
ok = self.parent.runSSLCommand('ca',
'-config', csrConfigFile,
'-batch',
'-extensions', 'server_cert',
'-days', '3650',
'-notext',
'-md', 'sha256',
'-in', csrFile,
'-out', certFile
)
if not ok:
return None
cert = open(certFile).read()
return cert
def ca_revoke(self, number):
certFile = os.path.join(self.caDatabase, 'intermediate', 'newcerts', str(number)+'.pem')
if not os.path.exists(certFile):
print("%s: no such certificate: %s" % (self.parent.argv0, certFile), file=sys.stderr)
ok = self.parent.runSSLCommand('ca', '-config', self.intConfigFile, '-revoke', certFile)
if ok:
ok = self.ca_genCRL()
return ok
def ca_genCRL(self):
crlFile = os.path.join(self.parent.database, 'static', 'crl.pem')
ok = self.parent.runSSLCommand('ca', '-config', self.intConfigFile, '-gencrl', '-out', crlFile)
return ok
def ca_getCRL(self):
crlFile = os.path.join(self.parent.database, 'static', 'crl.pem')
return open(crlFile).read()
def get_distinguishedNameForCA(self):
return self.parent.get_distinguishedName('x509', self.intCertFile)
def get_csrConfigTemplate(self):
"""Return filename for an openssl config file to be used as a template for new reequests"""
return self.intConfigFile
class CARemoteInterface:
"""Helper class to implement commands on remote CA (using REST calls to Igor server)"""
def __init__(self, parent, igorServer):
self.parent = parent
# igorServer can either be a URL or an igorServer instance
if isinstance(igorServer, str):
igorServer = igorVar.IgorServer(igorServer)
self.igor = igorServer
def isLocal(self):
return False
def isOK(self):
try:
rv = self.igor.get('/plugin/ca/status', format='text/plain')
except igorVar.IgorError as e:
print("%s: %s" % (self.parent.argv0, e), file=sys.stderr)
return False
rv = rv.strip()
if rv:
print("%s: remote CA: %s" % (self.parent.argv0, rv), file=sys.stderr)
return not rv
def ca_getRoot(self):
return self.igor.get('/plugin/ca/root', format='text/plain')
def ca_list(self):
rv = self.igor.get('/plugin/ca/list', format='application/json')
return json.loads(rv)
def ca_signCSR(self, csr):
return self.igor.get('/plugin/ca/sign', format='text/plain', query=dict(csr=csr))
def ca_revoke(self, number):
rv = self.igor.get('/plugin/ca/revoke', format='text/plain', query=dict(number=number))
return not rv
def ca_getCRL(self):
return self.igor.get('/static/crl.pem', format='text/plain')
def get_distinguishedNameForCA(self):
dnString = self.igor.get('/plugin/ca/dn', format='application/json')
return json.loads(dnString)
def get_csrConfigTemplate(self):
rv = self.igor.get('/plugin/ca/csrtemplate', format='text/plain')
_, configFile = tempfile.mkstemp('.sslconfig')
open(configFile, 'w').write(rv)
return configFile
class IgorCA:
"""Interface to Certificate Authority for Igor.
Arguments:
argv0 (str): program name (for error messages and such)
igorServer (str): optional URL for Igor server to use as CA (default: use local CA through openSSL commands)
keySize (int): default keysize (default default: 2048 bits)
database (str): for local CA: the location of the Igor database (default: ~/.igor)
"""
def __init__(self, argv0, igorServer=None, keysize=None, database=None):
self.argv0 = argv0
self.keysize = keysize
# Find username even when sudoed
username = os.environ.get("SUDO_USER", getpass.getuser())
# Igor package source directory
self.igorDir = os.path.dirname(igor.__file__)
#
# Default self.database directory, CA directory and key/cert for signing.
#
if database:
self.database = database
elif 'IGORSERVER_DIR' in os.environ:
self.database = os.environ['IGORSERVER_DIR']
else:
self.database = os.path.join(os.path.expanduser('~'+username), '.igor')
if igorServer:
self.ca = CARemoteInterface(self, igorServer)
else:
self.ca = CAInterface(self, self.database)
def get_distinguishedName(self, type, configFile):
"""Helper that returns DN in key-value dict (from req or cert file)"""
fp = subprocess.Popen(['openssl', type, '-in', configFile, '-noout', '-subject'], stdout=subprocess.PIPE, universal_newlines=True)
data, _ = fp.communicate()
if not data.startswith('subject='):
print('%s: unexpected openssl x509 output: %s' % (self.argv0, data), file=sys.stderr)
return None
data = data[8:]
data = data.strip()
rv = _distinguishedNameToDict(data)
return rv
def runSSLCommand(self, *args):
args = ('openssl',) + args
print('+', ' '.join(args), file=sys.stderr)
sts = subprocess.call(args)
if sts != 0:
print('%s: openssl returned status %d' % (self.argv0, sts), file=sys.stderr)
return False
return True
def main(self, command, args):
if command == 'help':
self.cmd_help()
sys.exit(0)
if not os.path.exists(self.database):
print("%s: No Igor database at %s" % (self.argv0, self.database), file=sys.stderr)
sys.exit(1)
if command == 'initialize':
ok = self.cmd_initialize(*args)
if not ok:
sys.exit(1)
sys.exit(0)
if not self.ca.isOK():
sys.exit(1)
if not hasattr(self, 'cmd_' + command):
print('%s: Unknown command "%s". Use help for help.' % (self.argv0, command), file=sys.stderr)
sys.exit(1)
handler = getattr(self, 'cmd_' + command)
ok = handler(*args)
if not ok:
sys.exit(1)
sys.exit(0)
def get_altNamesFromReq(self, configFile):
"""Helper to get subjectAltName data from a request or certificate"""
fp = subprocess.Popen(['openssl', 'req', '-in', configFile, '-noout', '-text'], stdout=subprocess.PIPE, universal_newlines=True)
data, _ = fp.communicate()
data = data.splitlines()
while data and not 'X509v3 Subject Alternative Name' in data[0]:
del data[0]
if not data:
return None
del data[0]
# Now next line has subjectAltName.
fields = data[0].split(',')
rv = []
for f in fields:
f = f.strip()
f = f.replace('IP Address', 'IP')
rv.append(f)
return ','.join(rv)
def fix_altNames(self, names):
"""Helper to turn list of hostnames/ip addresses into subjectAltName"""
altNames = []
for n in names:
if IS_IP.match(n):
altNames.append('IP:' + n)
else:
altNames.append('DNS:' + n)
altNames = ','.join(altNames)
return altNames
def cmd_help(self, *args):
"""Show list of available commands"""
print(USAGE % self.argv0)
print(self._helpinfo())
return True
@classmethod
def _helpinfo(cls):
"""Return available command help"""
# Get attributes that refer to commands
names = dir(cls)
names = filter(lambda x: x.startswith('cmd_'), names)
names = sorted(names)
rv = []
for name in names:
handler = getattr(cls, name)
rv.append('%-10s\t%s' % (name[4:], handler.__doc__))
return '\n'.join(rv)
def cmd_initialize(self, rootIssuer=None, intermediateIssuer=None):
"""create CA infrastructure, root key and certificate and intermediate key and certificate"""
if not self.ca.isLocal():
print("%s: initialize should only be used for local CA" % self.argv0, file=sys.stderr)
return False
if not rootIssuer or not intermediateIssuer:
print("%s: requires both rootIssuer and intermediateIssuer identifiers" % self.argv0, file=sys.stderr)
return False
if os.path.exists(self.ca.intKeyFile) and os.path.exists(self.ca.intCertFile) and os.path.exists(self.ca.intAllCertFile):
print('%s: Intermediate key and certificate already exist in %s' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
if os.path.exists(self.ca.intKeyFile) or os.path.exists(self.ca.intCertFile) or os.path.exists(self.ca.intAllCertFile):
print('%s: Some key and certificate files already exist in %s.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
print('%s: Partial initialize failure, maybe? Remove directory %s and try again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
#
# Create infrastructure if needed
#
if not os.path.exists(self.ca.caDatabase):
# Old igor, probably: self.ca.caDatabase doesn't exist yet
print()
print('=============== Creating CA directories and infrastructure')
print()
src = os.path.join(self.igorDir, 'igorDatabase.empty')
caSrc = os.path.join(src, 'ca')
print('%s: Creating %s' % (self.argv0, caSrc), file=sys.stderr)
shutil.copytree(caSrc, self.ca.caDatabase)
#
# Create openssl.cnf files from openssl.cnf.in
#
for caGroup in ('root', 'intermediate'):
print()
print('=============== Creating config for', caGroup)
print()
caGroupDir = os.path.join(self.ca.caDatabase, caGroup)
caGroupConf = os.path.join(caGroupDir, 'openssl.cnf')
caGroupConfIn = os.path.join(caGroupDir, 'openssl.cnf.in')
if os.path.exists(caGroupConf):
print('%s: %s already exists' % (self.argv0, caGroupConf), file=sys.stderr)
print('%s: Partial initialize failure, maybe? Remove directory %s and try again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
# Insert igor directory name into config file
cfg = SSLConfigParser(allow_no_value=True)
cfg.readfp(open(caGroupConfIn), caGroupConfIn)
cfg.set('CA_default', 'igordir', self.database)
cfg.write(open(caGroupConf, 'w'))
#
# Create root key and certificate
#
rootKeyFile = os.path.join(self.ca.caDatabase, 'root', 'private', 'ca.key.pem')
rootCertFile = os.path.join(self.ca.caDatabase, 'root', 'certs', 'ca.cert.pem')
rootConfigFile = os.path.join(self.ca.caDatabase, 'root', 'openssl.cnf')
if os.path.exists(rootKeyFile) and os.path.exists(rootCertFile) and os.path.exists(rootConfigFile):
print()
print('=============== Root key and certificate already exist')
print()
else:
print()
print('=============== Creating root key and certificate')
print()
ok = self.runSSLCommand('genrsa', '-out', rootKeyFile, '2048' if self.keysize is None else self.keysize)
if not ok:
print('%s: Error during root key generation. Remove directory %s before trying again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
os.chmod(rootKeyFile, 0o400)
ok = self.runSSLCommand('req',
'-config', rootConfigFile,
'-key', rootKeyFile,
'-subj', rootIssuer,
'-new',
'-x509',
'-days', '7300',
'-sha256',
'-extensions', 'v3_ca',
'-out', rootCertFile
)
if not ok:
print('%s: Error during root request generation. Remove directory %s before trying again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
os.chmod(rootCertFile, 0o400)
ok = self.runSSLCommand('x509', '-noout', '-text', '-in', rootCertFile)
if not ok:
print('%s: Error during root certificate signing. Remove directory %s before trying again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
#
# Create intermediate key, CSR and certificate
#
print()
print('=============== Creating intermediate key and certificate')
print()
ok = self.runSSLCommand('genrsa', '-out', self.ca.intKeyFile, '2048' if self.keysize is None else self.keysize)
os.chmod(self.ca.intKeyFile, 0o400)
if not ok:
print('%s: Error during intermediate key generation. Remove directory %s before trying again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
intCsrFile = os.path.join(self.ca.caDatabase, 'intermediate', 'certs', 'intermediate.csr.pem')
ok = self.runSSLCommand('req',
'-config', self.ca.intConfigFile,
'-key', self.ca.intKeyFile,
'-subj', intermediateIssuer,
'-new',
'-sha256',
'-out', intCsrFile
)
if not ok:
print('%s: Error during intermediate request generation. Remove directory %s before trying again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
ok = self.runSSLCommand('ca',
'-config', rootConfigFile,
'-extensions', 'v3_intermediate_ca',
'-days', '3650',
'-notext',
'-md', 'sha256',
'-in', intCsrFile,
'-out', self.ca.intCertFile
)
if not ok:
print('%s: Error during intermediate certificate signing. Remove directory %s before trying again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
os.chmod(self.ca.intCertFile, 0o400)
#
# Verify the intermediate certificate
#
ok = self.runSSLCommand('verify',
'-CAfile', rootCertFile,
self.ca.intCertFile
)
if not ok:
print('%s: Error during intermediate certificate verification. Remove directory %s before trying again.' % (self.argv0, self.ca.caDatabase), file=sys.stderr)
return False
#
# Concatenate
#
ofp = open(self.ca.intAllCertFile, 'w')
ofp.write(open(self.ca.intCertFile).read())
ofp.write(open(rootCertFile).read())
ofp.close()
#
# Now lock out the root directory structure.
#
os.chmod(os.path.join(self.ca.caDatabase, 'root'), 0)
#
# And finally print the chained file
#
ok = self.runSSLCommand('x509', '-noout', '-text', '-in', self.ca.intAllCertFile)
if not ok:
return False
print()
print("=============== Igor CA initialized correctly")
print()
return True
def cmd_dn(self):
"""Return CA distinghuished name as a JSON structure"""
dnData = self.ca.get_distinguishedNameForCA()
json.dump(dnData, sys.stdout)
sys.stdout.write('\n')
return True
def do_dn(self):
"""Return CA distinghuished name as a JSON structure"""
dnData = self.ca.get_distinguishedNameForCA()
return json.dumps(dnData)
def cmd_selfCSR(self, *allNames):
"""Create secret key and CSR for Igor itself. Outputs CSR."""
csr = self.do_selfCSR(*allNames)
if not csr:
return False
sys.stdout.write(csr)
return True
def do_genCSR(self, keyFile, csrFile, csrConfigFile, allNames=[], keysize=None):
"""Create key and CSR for a service. Returns CSR."""
if len(allNames) < 1:
print('%s: genCSR requires ALL names (commonName first) as arguments' % self.argv0, file=sys.stderr)
print('for example: %s genCSR igor.local localhost 127.0.0.1' % self.argv0, file=sys.stderr)
return False
#
# Create key
#
if keysize == None:
keysize = self.keysize
ok = self.runSSLCommand('genrsa', '-out', keyFile, '2048' if keysize is None else str(keysize))
if not ok:
return None
os.chmod(keyFile, 0o400)
#
# Construct commonName and subjectAltNames
#
commonName = allNames[0]
altNames = self.fix_altNames(allNames)
#
# Create CSR config file
#
csrConfigFile = self.gen_configFile(commonName, altNames, csrConfigFile)
if not csrConfigFile:
return None
#
# Create CSR
#
if not csrFile:
_, csrFile = tempfile.mkstemp('.csr')
ok = self.runSSLCommand('req',
'-config', csrConfigFile,
'-key', keyFile,
'-new',
'-sha256',
'-out', csrFile
)
if not ok:
return None
csrData = open(csrFile).read()
return csrData
def do_signCSR(self, csr):
"""Sign a CSR. Returns certificate."""
return self.ca.ca_signCSR(csr)
def cmd_genCRL(self):
"""Generate CRL in static/crl.pem"""
if not self.ca.isLocal():
print("%s: genCRL should only be used for local CA" % self.argv0, file=sys.stderr)
return False
ok = self.ca.ca_genCRL()
return ok
def cmd_getCRL(self):
"""Output the CRL (Certificate Revocation List)"""
rv = self.ca.ca_getCRL()
print(rv)
return True
def cmd_revoke(self, number):
"""Revoke a certificate. Argument is the number of the certificate to revoke (see list)."""
ok = self.ca.ca_revoke(number)
return ok
do_revoke = cmd_revoke
def cmd_revokecn(self, cn):
"""Revoke certificate for a given Common Name, if one exists"""
seqno = self.do_current(cn)
if seqno:
self.do_revoke(seqno)
return True
do_revokecn = cmd_revokecn
def gen_configFile(self, commonName, altNames, configFile=None):
"""Helper function to create CSR or signing config file"""
if not configFile:
_, configFile = tempfile.mkstemp('.sslconfig')
dnDict = self.ca.get_distinguishedNameForCA()
if not dnDict:
return None
dnDict['CN'] = commonName
cfg = SSLConfigParser(allow_no_value=True)
cfgSource = self.ca.get_csrConfigTemplate()
cfg.readfp(open(cfgSource), cfgSource) # xxxjack
cfg.remove_section('req_distinguished_name')
cfg.add_section('req_distinguished_name')
for k, v in list(dnDict.items()):
cfg.set('req_distinguished_name', k, v)
# Set to non-interactive
cfg.set('req', 'prompt', 'no')
# Add the subjectAltName
cfg.set('req', 'req_extensions', 'req_ext')
cfg.add_section('req_ext')
cfg.set('req_ext', 'subjectAltName', altNames)
# And add subjectAltName to server_cert section
cfg.set('server_cert', 'subjectAltName', altNames)
# Write to CSR config file
ofp = open(configFile, 'w')
cfg.write(ofp)
ofp.close()
return configFile
def cmd_self(self, *allNames):
"""Create a server key and certificate for Igor itself, and sign it with the intermediate Igor CA key"""
igorKeyFile = os.path.join(self.database, 'igor.key')
igorCsrFile = os.path.join(self.database, 'igor.csr')
igorCsrConfigFile = os.path.join(self.database, 'igor.csrconfig')
igorCertFile = os.path.join(self.database, 'igor.crt')
if os.path.exists(igorKeyFile) and os.path.exists(igorCertFile):
print('%s: igor.key and igor.crt already exist in %s' % (self.argv0, self.database), file=sys.stderr)
return False
csr = self.do_genCSR(igorKeyFile, igorCsrFile, igorCsrConfigFile, allNames)
if not csr:
return False
cert = self.do_signCSR(csr)
if not cert:
return False
open(igorCertFile, 'w').write(cert)
# Verify it
ok = self.runSSLCommand('x509', '-noout', '-text', '-in', igorCertFile)
if not ok:
return False
return True
def cmd_getRoot(self):
"""Returns the signing certificate chain (for installation in browser or operating system)"""
sys.stdout.write(self.ca.ca_getRoot())
return True
def do_getRoot(self):
"""Returns the signing certificate chain (for installation in browser or operating system)"""
return self.ca.ca_getRoot()
def cmd_sign(self, csrfile=None, certfile=None):
"""Sign a Certificate Signing Request and return the certificate."""
if not csrfile or not certfile:
print("Usage: %s sign csrfile certfile" % sys.argv[0], file=sys.stderr)
return False
csrdata = open(csrfile).read()
certdata = sekf.do_signCSR(csrdata)
if not certdata:
return False
open(certfile, 'w').write(certdata)
return True
def cmd_gen(self, prefix=None, *allNames):
"""Generate a a server key and certificate for a named service and sign it with the intermediate Igor CA key."""
if not prefix or not allNames:
print("Usage: %s gen keyfilenameprefix commonName [subjectAltNames ...]" % sys.argv[0], file=sys.stderr)
return False
keyData, certData = self.do_gen(prefix=prefix, cn=allNames[0], altNames=allNames[1:])
if not certData:
return False
# Verify it
certFile = prefix + '.crt.pem'
ok = self.runSSLCommand('x509', '-noout', '-text', '-in', certFile)
if not ok:
return False
return True
def do_gen(self, cn, altNames=None, prefix=None):
"""Generate server key and certificate for CN (and optional altNames) and return as PEM strings"""
allNames = [cn]
if altNames:
allNames += altNames
if not prefix:
_, prefix = tempfile.mkstemp(prefix="igorCA")
keyFile = prefix + '.key.pem'
certFile = prefix + '.crt.pem'
csrFile = prefix + '.csr'
csrConfigFile = prefix + '.csrConfig'
csr = self.do_genCSR(keyFile, csrFile, csrConfigFile, allNames)
if not csr:
return None, None
certData = self.do_signCSR(csr)
open(certFile, 'w').write(certData)
keyData = open(keyFile, 'r').read()
return keyData, certData
def cmd_list(self, cn=None):
"""Return list of certificates signed (optional arguments restricts to single Common Name)."""
items = self.do_list(cn=cn)
for item in items:
for k,v in item.items():
print(f'{k}={v}', end=' ')
print()
return False
def do_list(self, cn=None):
"""Return list of certificates signed."""
rv = self.ca.ca_list()
if cn:
rv = filter(lambda item : item['dn'].get('CN') == cn, rv)
return rv
def cmd_current(self, cn):
"""Print current certificate serial for given Common Name"""
serial = self.do_current(cn)
if serial:
print(serial)
return True
return False
def do_current(self, cn):
"""Return current certificate serial for given Common Name (or None)"""
items = self.do_list(cn=cn)
items = list(filter(lambda item : item.get('status')=='valid', items))
if len(items) > 1:
print('%s: multiple valid certs for cn=%st' % (self.argv0, cn), file=sys.stderr)
return None
if not items:
return None
return items[0].get('serial')
def cmd_status(self):
"""Returns nothing if CA status is ok, otherwise error message"""
return self.ca.isOK()
def do_status(self):
"""Returns nothing if CA status is ok, otherwise error message"""
if self.ca.isOK():
return ""
return "CA server configuration error, or not initialized"
def cmd_csrtemplate(self):
"""Return template config file for for openSSL CSR request"""
fn = self.ca.get_csrConfigTemplate()
sys.stdout.write(open(fn).read())
def do_csrtemplate(self):
"""Return template config file for for openSSL CSR request"""
fn = self.ca.get_csrConfigTemplate()
return open(fn).read()
def argumentParser():
epilog = "Available commands:\n" + IgorCA._helpinfo()
parser = igorVar.igorArgumentParser(description="Igor Certificate and Key utility", epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("-s", "--keysize", metavar="BITS", help="Override key size (default: 2048)")
parser.add_argument("-r", "--remote", action="store_true", help="Use CA on remote Igor (default is on the local filesystem)")
parser.add_argument("-d", "--database", metavar="DIR", help="(local only) Database and scripts are stored in DIR (default: ~/.igor, environment IGORSERVER_DIR)")
parser.add_argument("action", help="Action to perform: help, initialize, ...", default="help")
parser.add_argument("arguments", help="Arguments to the action", nargs="*")
return parser
def main():
parser = argumentParser()
args = parser.parse_args()
igorServer = None
if args.remote:
if not args.noSystemRootCertificates and not os.environ.get('REQUESTS_CA_BUNDLE', None):
# The requests package uses its own set of certificates, ignoring the ones the user has added to the system
# set. By default, override that behaviour.
for cf in ["/etc/ssl/certs/ca-certificates.crt", "/etc/ssl/certs/ca-certificates.crt"]:
if os.path.exists(cf):
os.putenv('REQUESTS_CA_BUNDLE', cf)
os.environ['REQUESTS_CA_BUNDLE'] = cf
break
igorServer = igorVar.IgorServer(args.url, bearer_token=args.bearer, access_token=args.access, credentials=args.credentials, noverify=args.noverify, certificate=args.certificate)
m = IgorCA(sys.argv[0], igorServer, keysize=args.keysize, database=args.database)
if not args.action:
return m.main('help', [])
return m.main(args.action, args.arguments)
if __name__ == '__main__':
main()