-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ca.py
executable file
·517 lines (433 loc) · 15.9 KB
/
ca.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
#!/usr/bin/env python3
import sys
import os
import getopt
import yaml
BASE_CMD = os.path.basename(sys.argv[0])
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
CA_DIR = os.path.join(BASE_DIR, 'ca')
ROOT_DIR = os.path.join(CA_DIR, 'root')
CFG_DIR = os.path.join(CA_DIR, 'cfg')
KEY_DIR = os.path.join(CA_DIR, 'key')
REQ_DIR = os.path.join(CA_DIR, 'req')
CRT_DIR = os.path.join(CA_DIR, 'crt')
KEY_EXT = '.key'
REQ_EXT = '.csr'
CRT_EXT = '.crt'
ROOT_KEY = os.path.join(ROOT_DIR, 'ca' + KEY_EXT)
ROOT_CRT = os.path.join(ROOT_DIR, 'ca' + CRT_EXT)
SUBJ_CFG = os.path.join(CFG_DIR, 'subj.yaml')
def usage(command = ''):
print('USAGE')
if command == '':
print(' ' + BASE_CMD + ' help')
else:
print(' ' + BASE_CMD + ' ' + command + ' help')
if command == '':
print(' ' + BASE_CMD + ' <COMMAND> help')
print(' ' + BASE_CMD + ' <COMMAND> <SUBCOMMAND> help')
print('')
print('COMMANDS')
print(' init Generate root key and root certificate')
print(' key Manage private keys')
print(' request Manage certificate requests')
print(' certificate Manage certificates')
elif command == 'init':
print(' ' + BASE_CMD + ' ' + command + ' [OPTIONS] <country> <state> <city> <organization>')
print('')
print('OPTIONS')
print(' -f, --force Force initialize')
print(' -d, --days Valid for number of days (default: 36500)')
print('')
print('ARGUMENTS')
print(' country Uppercase two letter country code')
print(' state The state, either as string or short')
print(' city City of origin')
print(' organization Name of the CA')
elif command == 'key':
print(' ' + BASE_CMD + ' ' + command + ' <COMMAND> help')
print('')
print('COMMANDS')
print(' list List all keys')
print(' get Get key content')
print(' create Create a new key')
print(' delete Delete existing key')
elif command == 'key get':
print(' ' + BASE_CMD + ' ' + command + ' <domain>')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'key create':
print(' ' + BASE_CMD + ' ' + command + ' [OPTIONS] <domain>')
print('')
print('OPTIONS')
print(' -f, --force Overwrite existing files')
print(' -l, --length Key length (default: 2048)')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'key delete':
print(' ' + BASE_CMD + ' ' + command + ' <domain>')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'request':
print(' ' + BASE_CMD + ' ' + command + ' <COMMAND>')
print('')
print('COMMANDS')
print(' list List all request')
print(' get Get request content')
print(' create Create a new request')
print(' delete Delete existing request')
elif command == 'request get':
print(' ' + BASE_CMD + ' ' + command + ' <domain>')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'request create':
print(' ' + BASE_CMD + ' ' + command + ' [OPTIONS] <domain>')
print('')
print('OPTIONS')
print(' -f, --force Overwrite existing files')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'request delete':
print(' ' + BASE_CMD + ' ' + command + ' <domain>')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'certificate':
print(' ' + BASE_CMD + ' ' + command + ' <COMMAND> help')
print('')
print('COMMANDS')
print(' list List all certificates')
print(' get Get certificate content')
print(' create Create a new certificate')
# print(' revoke Revoke existing certificate')
print(' delete Delete existing certificate')
elif command == 'certificate get':
print(' ' + BASE_CMD + ' ' + command + ' <domain>')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'certificate create':
print(' ' + BASE_CMD + ' ' + command + ' [OPTIONS] <domain>')
print('')
print('OPTIONS')
print(' -f, --force Overwrite existing files')
print(' -d, --days Valid for number of days (default: 730)')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'certificate revoke':
print(' ' + BASE_CMD + ' ' + command + ' <domain>')
print('')
print('ARGUMENTS')
print(' domain Domain name')
elif command == 'certificate delete':
print(' ' + BASE_CMD + ' ' + command + ' [OPTIONS] <domain>')
print('')
print('OPTIONS')
print(' -a, --all Delete key and request as well')
print(' -k, --key Delete key as well')
print(' -r, --request Delete request as well')
print('')
print('ARGUMENTS')
print(' domain Domain name')
def init(args):
opts, args = getopt.getopt(args, 'fd:', ['force', 'days='])
if len(args) and args[0] == 'help':
usage('init')
return 0
force = False
days = 36500 # 100 years
for k,v in opts:
if k == '-f' or k == '--force':
force = True
elif k == '-d' or k == '--days':
days = int(v)
if len(args) < 3:
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('init')
return 1
country = args[0]
state = args[1]
city = args[2]
organization = args[3]
if not os.path.exists(ROOT_DIR):
os.makedirs(ROOT_DIR)
if not os.path.exists(CFG_DIR):
os.makedirs(CFG_DIR)
if not os.path.exists(KEY_DIR):
os.makedirs(KEY_DIR)
if not os.path.exists(REQ_DIR):
os.makedirs(REQ_DIR)
if not os.path.exists(CRT_DIR):
os.makedirs(CRT_DIR)
if os.path.exists(ROOT_KEY) and not force:
print('\033[31mError: Root key already exists! Use --force to overwrite it.\033[39m')
return 1
with open(SUBJ_CFG, 'w') as file:
subj = yaml.dump({'country': country, 'state': state, 'city': city, 'organization': organization}, file)
os.system('openssl genrsa -out "' + ROOT_KEY + '" 4096')
os.system('openssl req -x509 -new -nodes -key "' + ROOT_KEY + '" -sha512 -days ' + str(days) + ' -out "' + ROOT_CRT + '" -subj "/C=' + country + '/ST=' + state + '/L=' + city + '/O=' + organization + '"')
return 0
def key_list(args):
print('KEYS')
for key in os.listdir(KEY_DIR):
print(' ' + key.replace(KEY_EXT, ''))
return 0
def key_get(args):
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('key get')
return 0
domain = args[0]
os.system('cat "' + KEY_DIR + '/' + domain + KEY_EXT + '"')
return 0
def key_create(args):
opts, args = getopt.getopt(args, 'l:', ['length='])
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('key create')
return 0
force = False
domain = args[0]
length = 2048
for k,v in opts:
if k == '-f' or k == '--force':
force = True
if k == '-l' or k == '--length':
length = int(v)
key_file = os.path.join(KEY_DIR, domain + KEY_EXT)
if os.path.exists(key_file) and not force:
print('\033[31mError: Key file already exists! Use --force to overwrite it.\033[39m')
print('')
usage('key create')
return 1
os.system('openssl genrsa -out "' + key_file + '" ' + str(length))
return 0
def key_delete(args):
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('key delete')
return 0
domain = args[0]
try:
os.remove(os.path.join(KEY_DIR, domain + KEY_EXT))
except FileNotFoundError:
print('\033[31mError: Key not found!\033[39m')
print('')
usage('key delete')
return 1
return 0
def key(args):
if not len(args) or args[0] == 'help':
usage('key')
return 0
elif args[0] == 'get':
return key_get(args[1:])
elif args[0] == 'list':
return key_list(args[1:])
elif args[0] == 'create':
return key_create(args[1:])
elif args[0] == 'delete':
return key_delete(args[1:])
return 0
def request_list(args):
print('REQUESTS')
for req in os.listdir(REQ_DIR):
print(' ' + req.replace(REQ_EXT, ''))
return 0
def request_get(args):
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('request get')
return 0
domain = args[0]
os.system('cat "' + REQ_DIR + '/' + domain + REQ_EXT + '"')
return 0
def request_create(args):
opts, args = getopt.getopt(args, 'f', ['force'])
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('request create')
return 0
force = False
domain = args[0]
key_file = os.path.join(KEY_DIR, domain + KEY_EXT)
req_file = os.path.join(REQ_DIR, domain + REQ_EXT)
for k,v in opts:
if k == '-f' or k == '--force':
force = True
if os.path.exists(req_file) and not force:
print('\033[31mError: Request file already exists! Use --force to overwrite it.\033[39m')
print('')
usage('request create')
return 1
if not os.path.exists(key_file):
os.system('openssl genrsa -out "' + key_file + '" 2048')
with open(SUBJ_CFG, 'r') as file:
subj = yaml.full_load(file)
os.system('openssl req -new -sha512 -key "' + key_file + '" -subj "/C=' + subj['country'] + '/ST=' + subj['state'] + '/L=' + subj['city'] + '/O=' + subj['organization'] + '/CN=' + domain + '" -out ' + req_file)
return 0
def request_delete(args):
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('request delete')
return 0
domain = args[0]
try:
os.remove(os.path.join(REQ_DIR, domain + REQ_EXT))
except FileNotFoundError:
print('\033[31mError: Request not found!\033[39m')
print('')
usage('request delete')
return 1
return 0
def request(args):
if not len(args) or args[0] == 'help':
usage('request')
return 0
elif args[0] == 'get':
return request_get(args[1:])
elif args[0] == 'list':
return request_list(args[1:])
elif args[0] == 'create':
return request_create(args[1:])
elif args[0] == 'delete':
return request_delete(args[1:])
return 0
def certificate_list(args):
print('CERTIFICATES')
for crt in os.listdir(CRT_DIR):
print(' ' + crt.replace(CRT_EXT, ''))
return 0
def certificate_get(args):
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('certificate get')
return 0
domain = args[0]
os.system('cat "' + CRT_DIR + '/' + domain + CRT_EXT + '"')
return 0
def certificate_create(args):
opts, args = getopt.getopt(args, 'fd:', ['force', 'days='])
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('certificate create')
return 0
force = False
days = 730
domain = args[0]
key_file = os.path.join(KEY_DIR, domain + KEY_EXT)
req_file = os.path.join(REQ_DIR, domain + REQ_EXT)
crt_file = os.path.join(CRT_DIR, domain + CRT_EXT)
for k,v in opts:
if k == '-f' or k == '--force':
force = True
if k == '-d' or k == '--days':
days = int(v)
if os.path.exists(crt_file) and not force:
print('\033[31mError: Request file already exists! Use --force to overwrite it.\033[39m')
print('')
usage('request create')
return 1
if not os.path.exists(key_file) and not os.path.exists(req_file):
os.system('openssl genrsa -out "' + key_file + '" 2048')
if not os.path.exists(req_file):
with open(SUBJ_CFG, 'r') as file:
subj = yaml.full_load(file)
os.system('openssl req -new -sha512 -key "' + key_file + '" -subj "/C=' + subj['country'] + '/ST=' + subj['state'] + '/L=' + subj['city'] + '/O=' + subj['organization'] + '/CN=' + domain + '" -out ' + req_file)
os.system('printf "subjectAltName=DNS:' + domain + '" | openssl x509 -req -sha512 -in "' + req_file + '" -CA "' + ROOT_CRT + '" -CAkey "' + ROOT_KEY + '" -CAcreateserial -days ' + str(days) + ' -out "' + crt_file + '" -extfile -')
return 0
def certificate_revoke(args):
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('certificate revoke')
return 0
# TODO: Implement
return 0
def certificate_delete(args):
opts, args = getopt.getopt(args, 'akr', ['all', 'key', 'request'])
if not len(args) or args[0] == 'help':
if not len(args):
print('\033[31mError: Required argument missing!\033[39m')
print('')
usage('certificate delete')
return 0
domain = args[0]
delete_key = False
delete_request = False
for k,v in opts:
if k == '-a' or k == '--all':
delete_key = True
delete_request = True
if k == '-k' or k == '--key':
delete_key = True
if k == '-r' or k == '--request':
delete_request = True
if delete_key:
os.system('rm "' + os.path.join(KEY_DIR, domain + KEY_EXT) + '"')
if delete_request:
os.system('rm "' + os.path.join(REQ_DIR, domain + REQ_EXT) + '"')
os.system('rm "' + os.path.join(CRT_DIR, domain + CRT_EXT) + '"')
return 0
def certificate(args):
if not len(args) or args[0] == 'help':
usage('certificate')
return 0
elif args[0] == 'list':
return certificate_list(args[1:])
elif args[0] == 'create':
return certificate_create(args[1:])
# elif args[0] == 'revoke':
# return certificate_revoke(args[1:])
elif args[0] == 'delete':
return certificate_delete(args[1:])
return 0
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError as err:
print(err)
usage()
return 2
if not len(args) or args[0] == 'help':
usage()
return 0
elif args[0] == 'init':
return init(args[1:])
if not os.path.exists(SUBJ_CFG):
print('\033[31mError: CA not yet initialized!\033[39m')
print('')
usage()
return 1
if args[0] == 'key':
return key(args[1:])
elif args[0] == 'request':
return request(args[1:])
elif args[0] == 'certificate':
return certificate(args[1:])
if __name__ == '__main__':
sys.exit(main())