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