1
|
import json
|
2
|
from datetime import datetime
|
3
|
from itertools import chain
|
4
|
from json import JSONDecodeError
|
5
|
|
6
|
from flask import request
|
7
|
from injector import inject
|
8
|
|
9
|
from src.constants import CA_ID, \
|
10
|
SSL_ID, SIGNATURE_ID, AUTHENTICATION_ID, \
|
11
|
DATETIME_FORMAT, ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID # TODO DATABASE_FILE - not the Controller's
|
12
|
from src.controllers.return_codes import *
|
13
|
from src.exceptions.database_exception import DatabaseException
|
14
|
from src.exceptions.unknown_exception import UnknownException
|
15
|
from src.model.subject import Subject
|
16
|
from src.services.certificate_service import CertificateService, RevocationReasonInvalidException, \
|
17
|
CertificateStatusInvalidException, CertificateNotFoundException, CertificateAlreadyRevokedException, \
|
18
|
CertificateCannotBeSetToValid
|
19
|
# responsibility.
|
20
|
from src.services.key_service import KeyService
|
21
|
from src.utils.logger import Logger
|
22
|
from src.utils.util import dict_to_string
|
23
|
|
24
|
TREE_NODE_TYPE_COUNT = 3
|
25
|
|
26
|
FILTERING = "filtering"
|
27
|
ISSUER = "issuer"
|
28
|
US = "usage"
|
29
|
NOT_AFTER = "notAfter"
|
30
|
NOT_BEFORE = "notBefore"
|
31
|
COMMON_NAME = "CN"
|
32
|
ID = "id"
|
33
|
USAGE = "usage"
|
34
|
SUBJECT = "subject"
|
35
|
VALIDITY_DAYS = "validityDays"
|
36
|
CA = "CA"
|
37
|
ISSUED_BY = "issuedby"
|
38
|
STATUS = "status"
|
39
|
REASON = "reason"
|
40
|
REASON_UNDEFINED = "unspecified"
|
41
|
|
42
|
E_NO_ISSUER_FOUND = {"success": False, "data": "No certificate authority with such unique ID exists."}
|
43
|
E_NO_CERTIFICATES_FOUND = {"success": False, "data": "No such certificate found."}
|
44
|
E_NO_CERTIFICATE_ALREADY_REVOKED = {"success": False, "data": "Certificate is already revoked."}
|
45
|
E_NO_CERT_PRIVATE_KEY_FOUND = {"success": False,
|
46
|
"data": "Internal server error (certificate's private key cannot be found)."}
|
47
|
E_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."}
|
48
|
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."}
|
49
|
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."}
|
50
|
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."}
|
51
|
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."}
|
52
|
|
53
|
|
54
|
class CertController:
|
55
|
KEY_MAP = {'CA': CA_ID, 'SSL': SSL_ID, 'digitalSignature': SIGNATURE_ID, 'authentication': AUTHENTICATION_ID}
|
56
|
INVERSE_KEY_MAP = {k: v for v, k in KEY_MAP.items()}
|
57
|
|
58
|
@inject
|
59
|
def __init__(self, certificate_service: CertificateService, key_service: KeyService):
|
60
|
self.certificate_service = certificate_service
|
61
|
self.key_service = key_service
|
62
|
|
63
|
def create_certificate(self):
|
64
|
"""create new certificate
|
65
|
|
66
|
Create a new certificate based on given information
|
67
|
|
68
|
:param body: Certificate data to be created
|
69
|
:type body: dict | bytes
|
70
|
|
71
|
:rtype: CreatedResponse
|
72
|
"""
|
73
|
|
74
|
Logger.info(f"\n\t{request.referrer}"
|
75
|
f"\n\t{request.method} {request.path} {request.scheme}")
|
76
|
|
77
|
required_keys = {SUBJECT, USAGE, VALIDITY_DAYS} # required fields of the POST req
|
78
|
|
79
|
if request.is_json: # accept JSON only
|
80
|
body = request.get_json()
|
81
|
|
82
|
Logger.info(f"\n\tRequest body:"
|
83
|
f"\n{dict_to_string(body)}")
|
84
|
|
85
|
if not all(k in body for k in required_keys): # verify that all keys are present
|
86
|
Logger.error(f"Invalid request, missing parameters")
|
87
|
return E_MISSING_PARAMETERS, C_BAD_REQUEST
|
88
|
|
89
|
if not isinstance(body[VALIDITY_DAYS], int): # type checking
|
90
|
Logger.error(f"Invalid request, wrong parameter '{VALIDITY_DAYS}'.")
|
91
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
92
|
|
93
|
subject = Subject.from_dict(body[SUBJECT]) # generate Subject from passed dict
|
94
|
|
95
|
if subject is None: # if the format is incorrect
|
96
|
Logger.error(f"Invalid request, wrong parameter '{SUBJECT}'.")
|
97
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
98
|
|
99
|
usages_dict = {}
|
100
|
|
101
|
if not isinstance(body[USAGE], dict): # type checking
|
102
|
Logger.error(f"Invalid request, wrong parameter '{USAGE}'.")
|
103
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
104
|
|
105
|
for k, v in body[USAGE].items(): # for each usage
|
106
|
if k not in CertController.KEY_MAP: # check that it is a valid usage
|
107
|
Logger.error(f"Invalid request, wrong parameter '{USAGE}'[{k}].")
|
108
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST # and throw if it is not
|
109
|
usages_dict[CertController.KEY_MAP[k]] = v # otherwise translate key and set
|
110
|
|
111
|
key = self.key_service.create_new_key() # TODO pass key
|
112
|
|
113
|
if CA not in body or body[CA] is None: # if issuer omitted (legal) or none
|
114
|
cert = self.certificate_service.create_root_ca( # create a root CA
|
115
|
key,
|
116
|
subject,
|
117
|
usages=usages_dict, # TODO ignoring usages -> discussion
|
118
|
days=body[VALIDITY_DAYS]
|
119
|
)
|
120
|
else:
|
121
|
issuer = self.certificate_service.get_certificate(body[CA]) # get base issuer info
|
122
|
|
123
|
if issuer is None: # if such issuer does not exist
|
124
|
Logger.error(f"No certificate authority with such unique ID exists 'ID = {key.private_key_id}'.")
|
125
|
self.key_service.delete_key(key.private_key_id) # free
|
126
|
return E_NO_ISSUER_FOUND, C_BAD_REQUEST # and throw
|
127
|
|
128
|
issuer_key = self.key_service.get_key(issuer.private_key_id) # get issuer's key, which must exist
|
129
|
|
130
|
if issuer_key is None: # if it does not
|
131
|
Logger.error(f"Internal server error (corrupted database).")
|
132
|
self.key_service.delete_key(key.private_key_id) # free
|
133
|
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR # and throw
|
134
|
|
135
|
f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
|
136
|
self.certificate_service.create_end_cert
|
137
|
|
138
|
# noinspection PyTypeChecker
|
139
|
cert = f( # create inter CA or end cert
|
140
|
key, # according to whether 'CA' is among
|
141
|
subject, # the usages' fields
|
142
|
issuer,
|
143
|
issuer_key,
|
144
|
usages=usages_dict,
|
145
|
days=body[VALIDITY_DAYS]
|
146
|
)
|
147
|
|
148
|
if cert is not None:
|
149
|
return {"success": True,
|
150
|
"data": cert.certificate_id}, C_CREATED_SUCCESSFULLY
|
151
|
else: # if this fails, then
|
152
|
Logger.error(f"Internal error: The certificate could not have been created.")
|
153
|
self.key_service.delete_key(key.private_key_id) # free
|
154
|
return {"success": False, # and wonder what the cause is,
|
155
|
"data": "Internal error: The certificate could not have been created."}, C_BAD_REQUEST
|
156
|
# as obj/None carries only one bit
|
157
|
# of error information
|
158
|
else:
|
159
|
Logger.error(f"The request must be JSON-formatted.")
|
160
|
return E_NOT_JSON_FORMAT, C_BAD_REQUEST # throw in case of non-JSON format
|
161
|
|
162
|
def get_certificate_by_id(self, id):
|
163
|
"""get certificate by ID
|
164
|
|
165
|
Get certificate in PEM format by ID
|
166
|
|
167
|
:param id: ID of a certificate to be queried
|
168
|
:type id: dict | bytes
|
169
|
|
170
|
:rtype: PemResponse
|
171
|
"""
|
172
|
|
173
|
Logger.info(f"\n\t{request.referrer}"
|
174
|
f"\n\t{request.method} {request.path} {request.scheme}"
|
175
|
f"\n\tCertificate ID = {id}")
|
176
|
try:
|
177
|
v = int(id)
|
178
|
except ValueError:
|
179
|
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
|
180
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
181
|
|
182
|
cert = self.certificate_service.get_certificate(v)
|
183
|
|
184
|
if cert is None:
|
185
|
Logger.error(f"No such certificate found 'ID = {v}'.")
|
186
|
return E_NO_CERTIFICATES_FOUND, C_NO_DATA
|
187
|
else:
|
188
|
return {"success": True, "data": cert.pem_data}, C_SUCCESS
|
189
|
|
190
|
def get_certificate_details_by_id(self, id):
|
191
|
"""get certificate's details by ID
|
192
|
|
193
|
Get certificate details by ID
|
194
|
|
195
|
:param id: ID of a certificate whose details are to be queried
|
196
|
:type id: dict | bytes
|
197
|
|
198
|
:rtype: CertificateResponse
|
199
|
"""
|
200
|
|
201
|
Logger.info(f"\n\t{request.referrer}"
|
202
|
f"\n\t{request.method} {request.path} {request.scheme}"
|
203
|
f"\n\tCertificate ID = {id}")
|
204
|
|
205
|
try:
|
206
|
v = int(id)
|
207
|
except ValueError:
|
208
|
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
|
209
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
210
|
|
211
|
cert = self.certificate_service.get_certificate(v)
|
212
|
|
213
|
if cert is None:
|
214
|
Logger.error(f"No such certificate found 'ID = {v}'.")
|
215
|
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
|
216
|
|
217
|
data = self.cert_to_dict_full(cert)
|
218
|
if data is None:
|
219
|
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
|
220
|
|
221
|
try:
|
222
|
state = self.certificate_service.get_certificate_state(v)
|
223
|
data["status"] = state
|
224
|
except CertificateNotFoundException:
|
225
|
Logger.error(f"No such certificate found 'ID = {id}'.")
|
226
|
|
227
|
return {"success": True, "data": data}, C_SUCCESS
|
228
|
|
229
|
def get_certificate_list(self):
|
230
|
"""get list of certificates
|
231
|
|
232
|
Lists certificates based on provided filtering options
|
233
|
|
234
|
:param filtering: Filter certificate type to be queried
|
235
|
:type filtering: dict | bytes
|
236
|
|
237
|
:rtype: CertificateListResponse
|
238
|
"""
|
239
|
|
240
|
Logger.info(f"\n\t{request.referrer}"
|
241
|
f"\n\t{request.method} {request.path} {request.scheme}")
|
242
|
|
243
|
targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID} # all targets
|
244
|
issuer_id = -1
|
245
|
|
246
|
# the filtering parameter can be read as URL argument or as a request body
|
247
|
if request.is_json or FILTERING in request.args.keys(): # if the request carries JSON data
|
248
|
if request.is_json:
|
249
|
data = request.get_json() # get it
|
250
|
else:
|
251
|
try:
|
252
|
data = {FILTERING: json.loads(request.args[FILTERING])}
|
253
|
except JSONDecodeError:
|
254
|
Logger.error(f"The request must be JSON-formatted.")
|
255
|
return E_NOT_JSON_FORMAT, C_BAD_REQUEST
|
256
|
|
257
|
Logger.info(f"\n\tRequest body:"
|
258
|
f"\n{dict_to_string(data)}")
|
259
|
|
260
|
if FILTERING in data: # if the 'filtering' field exists
|
261
|
if isinstance(data[FILTERING], dict): # and it is also a 'dict'
|
262
|
if CA in data[FILTERING]: # containing 'CA'
|
263
|
if isinstance(data[FILTERING][CA], bool): # which is a 'bool',
|
264
|
if data[FILTERING][CA]: # then filter according to 'CA'.
|
265
|
targets.remove(CERTIFICATE_ID)
|
266
|
else:
|
267
|
targets.remove(ROOT_CA_ID)
|
268
|
targets.remove(INTERMEDIATE_CA_ID)
|
269
|
else:
|
270
|
Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{CA}'.")
|
271
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
272
|
if ISSUED_BY in data[FILTERING]: # containing 'issuedby'
|
273
|
if isinstance(data[FILTERING][ISSUED_BY], int): # which is an 'int'
|
274
|
issuer_id = data[FILTERING][ISSUED_BY] # then get its children only
|
275
|
else:
|
276
|
Logger.error(f"Invalid request, wrong parameters '{FILTERING}'.")
|
277
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
278
|
if issuer_id >= 0: # if filtering by an issuer
|
279
|
try:
|
280
|
children = self.certificate_service.get_certificates_issued_by(issuer_id) # get his children
|
281
|
except CertificateNotFoundException: # if id does not exist
|
282
|
Logger.error(f"No such certificate found 'ID = {issuer_id}'.")
|
283
|
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND # throw
|
284
|
|
285
|
certs = [child for child in children if child.type_id in targets]
|
286
|
|
287
|
elif len(targets) == TREE_NODE_TYPE_COUNT: # = 3 -> root node,
|
288
|
# intermediate node,
|
289
|
# or leaf node
|
290
|
|
291
|
# if filtering did not change the
|
292
|
# targets,
|
293
|
certs = self.certificate_service.get_certificates() # fetch everything
|
294
|
else: # otherwise fetch targets only
|
295
|
certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
|
296
|
else:
|
297
|
certs = self.certificate_service.get_certificates() # if no params, fetch everything
|
298
|
|
299
|
if certs is None:
|
300
|
Logger.error(f"Internal server error (unknown origin).")
|
301
|
return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
|
302
|
elif len(certs) == 0:
|
303
|
# TODO check log level
|
304
|
Logger.warning(f"No such certificate found (empty list).")
|
305
|
return E_NO_CERTIFICATES_FOUND, C_NO_DATA
|
306
|
else:
|
307
|
ret = []
|
308
|
for c in certs:
|
309
|
data = self.cert_to_dict_partial(c)
|
310
|
if data is None:
|
311
|
Logger.error(f"Internal server error (corrupted database).")
|
312
|
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
|
313
|
ret.append(
|
314
|
data
|
315
|
)
|
316
|
return {"success": True, "data": ret}, C_SUCCESS
|
317
|
|
318
|
def get_certificate_root_by_id(self, id):
|
319
|
"""get certificate's root of trust chain by ID
|
320
|
|
321
|
Get certificate's root of trust chain in PEM format by ID
|
322
|
|
323
|
:param id: ID of a child certificate whose root is to be queried
|
324
|
:type id: dict | bytes
|
325
|
|
326
|
:rtype: PemResponse
|
327
|
"""
|
328
|
|
329
|
Logger.info(f"\n\t{request.referrer}"
|
330
|
f"\n\t{request.method} {request.path} {request.scheme}"
|
331
|
f"\n\tCertificate ID = {id}")
|
332
|
|
333
|
try:
|
334
|
v = int(id)
|
335
|
except ValueError:
|
336
|
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
|
337
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
338
|
|
339
|
cert = self.certificate_service.get_certificate(v)
|
340
|
|
341
|
if cert is None:
|
342
|
Logger.error(f"No such certificate found 'ID = {v}'.")
|
343
|
return E_NO_CERTIFICATES_FOUND, C_NO_DATA
|
344
|
|
345
|
trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
|
346
|
if trust_chain is None or len(trust_chain) == 0:
|
347
|
Logger.error(f"No such certificate found (empty list).")
|
348
|
return E_NO_CERTIFICATES_FOUND, C_NO_DATA
|
349
|
|
350
|
return {"success": True, "data": trust_chain[-1].pem_data}, C_SUCCESS
|
351
|
|
352
|
def get_certificate_trust_chain_by_id(self, id):
|
353
|
"""get certificate's trust chain by ID (including root certificate)
|
354
|
|
355
|
Get certificate trust chain in PEM format by ID
|
356
|
|
357
|
:param id: ID of a child certificate whose chain is to be queried
|
358
|
:type id: dict | bytes
|
359
|
|
360
|
:rtype: PemResponse
|
361
|
"""
|
362
|
|
363
|
Logger.info(f"\n\t{request.referrer}"
|
364
|
f"\n\t{request.method} {request.path} {request.scheme}"
|
365
|
f"\n\tCertificate ID = {id}")
|
366
|
|
367
|
try:
|
368
|
v = int(id)
|
369
|
except ValueError:
|
370
|
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
|
371
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
372
|
|
373
|
cert = self.certificate_service.get_certificate(v)
|
374
|
|
375
|
if cert is None:
|
376
|
Logger.error(f"No such certificate found 'ID = {v}'.")
|
377
|
return E_NO_CERTIFICATES_FOUND, C_NO_DATA
|
378
|
|
379
|
if cert.parent_id is None:
|
380
|
Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.")
|
381
|
return E_NO_CERTIFICATES_FOUND, C_NO_DATA
|
382
|
|
383
|
trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
|
384
|
|
385
|
ret = []
|
386
|
for intermediate in trust_chain:
|
387
|
ret.append(intermediate.pem_data)
|
388
|
|
389
|
return {"success": True, "data": "".join(ret)}, C_SUCCESS
|
390
|
|
391
|
def set_certificate_status(self, id):
|
392
|
"""
|
393
|
Revoke a certificate given by ID
|
394
|
- revocation request may contain revocation reason
|
395
|
- revocation reason is verified based on the possible predefined values
|
396
|
- if revocation reason is not specified 'undefined' value is used
|
397
|
:param id: Identifier of the certificate to be revoked
|
398
|
:type id: int
|
399
|
|
400
|
:rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
|
401
|
"""
|
402
|
|
403
|
Logger.info(f"\n\t{request.referrer}"
|
404
|
f"\n\t{request.method} {request.path} {request.scheme}"
|
405
|
f"\n\tCertificate ID = {id}")
|
406
|
|
407
|
required_keys = {STATUS} # required keys
|
408
|
|
409
|
# check if the request contains a JSON body
|
410
|
if request.is_json:
|
411
|
request_body = request.get_json()
|
412
|
|
413
|
Logger.info(f"\n\tRequest body:"
|
414
|
f"\n{dict_to_string(request_body)}")
|
415
|
|
416
|
# try to parse certificate identifier -> if it is not int return error 400
|
417
|
try:
|
418
|
identifier = int(id)
|
419
|
except ValueError:
|
420
|
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
|
421
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
422
|
|
423
|
# verify that all required keys are present
|
424
|
if not all(k in request_body for k in required_keys):
|
425
|
Logger.error(f"Invalid request, missing parameters.")
|
426
|
return E_MISSING_PARAMETERS, C_BAD_REQUEST
|
427
|
|
428
|
# get status and reason from the request
|
429
|
status = request_body[STATUS]
|
430
|
reason = request_body.get(REASON, REASON_UNDEFINED)
|
431
|
try:
|
432
|
# set certificate status using certificate_service
|
433
|
self.certificate_service.set_certificate_revocation_status(identifier, status, reason)
|
434
|
except (RevocationReasonInvalidException, CertificateStatusInvalidException):
|
435
|
# these exceptions are thrown in case invalid status or revocation reason is passed to the controller
|
436
|
Logger.error(f"Invalid request, wrong parameters.")
|
437
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
438
|
except CertificateAlreadyRevokedException:
|
439
|
Logger.error(f"Certificate is already revoked 'ID = {identifier}'.")
|
440
|
return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST
|
441
|
except CertificateNotFoundException:
|
442
|
Logger.error(f"No such certificate found 'ID = {identifier}'.")
|
443
|
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
|
444
|
except CertificateCannotBeSetToValid as e:
|
445
|
return {"success": False, "data": str(e)}, C_BAD_REQUEST
|
446
|
return {"success": True,
|
447
|
"data": "Certificate status updated successfully."}, C_SUCCESS
|
448
|
# throw an error in case the request does not contain a json body
|
449
|
else:
|
450
|
Logger.error(f"The request must be JSON-formatted.")
|
451
|
return E_NOT_JSON_FORMAT, C_BAD_REQUEST
|
452
|
|
453
|
def cert_to_dict_partial(self, c):
|
454
|
"""
|
455
|
Dictionarizes a certificate directly fetched from the database. Contains partial information.
|
456
|
:param c: target cert
|
457
|
:return: certificate dict (compliant with some parts of the REST API)
|
458
|
"""
|
459
|
|
460
|
# TODO check log
|
461
|
Logger.debug(f"Function launched.")
|
462
|
|
463
|
c_issuer = self.certificate_service.get_certificate(c.parent_id)
|
464
|
if c_issuer is None:
|
465
|
return None
|
466
|
|
467
|
return {
|
468
|
ID: c.certificate_id,
|
469
|
COMMON_NAME: c.common_name,
|
470
|
NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
|
471
|
NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
|
472
|
USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
|
473
|
ISSUER: {
|
474
|
ID: c_issuer.certificate_id,
|
475
|
COMMON_NAME: c_issuer.common_name
|
476
|
}
|
477
|
}
|
478
|
|
479
|
def cert_to_dict_full(self, c):
|
480
|
"""
|
481
|
Dictionarizes a certificate directly fetched from the database, but adds subject info.
|
482
|
Contains full information.
|
483
|
:param c: target cert
|
484
|
:return: certificate dict (compliant with some parts of the REST API)
|
485
|
"""
|
486
|
|
487
|
Logger.info(f"Function launched.")
|
488
|
|
489
|
subj = self.certificate_service.get_subject_from_certificate(c)
|
490
|
c_issuer = self.certificate_service.get_certificate(c.parent_id)
|
491
|
if c_issuer is None:
|
492
|
return None
|
493
|
|
494
|
return {
|
495
|
SUBJECT: subj.to_dict(),
|
496
|
NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
|
497
|
NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
|
498
|
USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
|
499
|
CA: c_issuer.certificate_id
|
500
|
}
|
501
|
|
502
|
def get_private_key_of_a_certificate(self, id):
|
503
|
"""
|
504
|
Get a private key used to sign a certificate in PEM format specified by certificate's ID
|
505
|
|
506
|
:param id: ID of a certificate whose private key is to be queried
|
507
|
:type id: dict | bytes
|
508
|
|
509
|
:rtype: PemResponse
|
510
|
"""
|
511
|
|
512
|
Logger.info(f"\n\t{request.referrer}"
|
513
|
f"\n\t{request.method} {request.path} {request.scheme}"
|
514
|
f"\n\tCertificate ID = {id}")
|
515
|
|
516
|
# try to parse the supplied ID
|
517
|
try:
|
518
|
v = int(id)
|
519
|
except ValueError:
|
520
|
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
|
521
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
522
|
|
523
|
# find a certificate using the given ID
|
524
|
cert = self.certificate_service.get_certificate(v)
|
525
|
|
526
|
if cert is None:
|
527
|
Logger.error(f"No such certificate found 'ID = {v}'.")
|
528
|
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
|
529
|
else:
|
530
|
# certificate exists, fetch it's private key
|
531
|
private_key = self.key_service.get_key(cert.private_key_id)
|
532
|
if cert is None:
|
533
|
Logger.error(f"Internal server error (certificate's private key cannot be found).")
|
534
|
return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
|
535
|
else:
|
536
|
return {"success": True, "data": private_key.private_key}, C_SUCCESS
|
537
|
|
538
|
def get_public_key_of_a_certificate(self, id):
|
539
|
"""
|
540
|
Get a public key of a certificate in PEM format specified by certificate's ID
|
541
|
|
542
|
:param id: ID of a certificate whose public key is to be queried
|
543
|
:type id: dict | bytes
|
544
|
|
545
|
:rtype: PemResponse
|
546
|
"""
|
547
|
|
548
|
Logger.info(f"\n\t{request.referrer}"
|
549
|
f"\n\t{request.method} {request.path} {request.scheme}"
|
550
|
f"\n\tCertificate ID = {id}")
|
551
|
|
552
|
# try to parse the supplied ID
|
553
|
try:
|
554
|
v = int(id)
|
555
|
except ValueError:
|
556
|
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
|
557
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
558
|
|
559
|
# find a certificate using the given ID
|
560
|
cert = self.certificate_service.get_certificate(v)
|
561
|
|
562
|
if cert is None:
|
563
|
Logger.error(f"No such certificate found 'ID = {v}'.")
|
564
|
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
|
565
|
else:
|
566
|
return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
|
567
|
|
568
|
def delete_certificate(self, id):
|
569
|
"""
|
570
|
Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
|
571
|
:param id: target certificate ID
|
572
|
:rtype: DeleteResponse
|
573
|
"""
|
574
|
|
575
|
Logger.info(f"\n\t{request.referrer}"
|
576
|
f"\n\t{request.method} {request.path} {request.scheme}"
|
577
|
f"\n\tCertificate ID = {id}")
|
578
|
|
579
|
try:
|
580
|
v = int(id)
|
581
|
except ValueError:
|
582
|
Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
|
583
|
return E_WRONG_PARAMETERS, C_BAD_REQUEST
|
584
|
|
585
|
try:
|
586
|
self.certificate_service.delete_certificate(v)
|
587
|
except CertificateNotFoundException:
|
588
|
Logger.error(f"No such certificate found 'ID = {v}'.")
|
589
|
return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
|
590
|
except DatabaseException:
|
591
|
Logger.error(f"Internal server error (corrupted database).")
|
592
|
return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
|
593
|
except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
|
594
|
Logger.error(f"Internal server error (unknown origin).")
|
595
|
return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
|
596
|
|
597
|
return {"success": True, "data": "The certificate and its descendants have been successfully deleted."}
|