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