Projekt

Obecné

Profil

Stáhnout (34 KB) Statistiky
| Větev: | Tag: | Revize:
1
import json
2
from datetime import datetime
3
from itertools import chain
4
from json import JSONDecodeError
5

    
6
from flask import request, Response
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, InvalidSubjectAttribute, InvalidRootCA
19
#  responsibility.
20
from src.services.cryptography import CryptographyException
21
from src.services.key_service import KeyService
22
from src.utils.logger import Logger
23
from src.utils.util import dict_to_string
24

    
25
EXTENSIONS = "extensions"
26

    
27
TREE_NODE_TYPE_COUNT = 3
28
KEY_PEM = "key_pem"
29
PASSWORD = "password"
30
KEY = "key"
31
FILTERING = "filtering"
32
PAGE = "page"
33
PER_PAGE = "per_page"
34
ISSUER = "issuer"
35
US = "usage"
36
NOT_AFTER = "notAfter"
37
NOT_BEFORE = "notBefore"
38
COMMON_NAME = "CN"
39
ID = "id"
40
CA = "CA"
41
USAGE = "usage"
42
SUBJECT = "subject"
43
VALIDITY_DAYS = "validityDays"
44
TYPE = "type"
45
ISSUED_BY = "issuedby"
46
STATUS = "status"
47
REASON = "reason"
48
REASON_UNDEFINED = "unspecified"
49
NAME = "name"
50

    
51
E_NO_ISSUER_FOUND = {"success": False, "data": "No certificate authority with such unique ID exists."}
52
E_NO_CERTIFICATES_FOUND = {"success": False, "data": "No such certificate found."}
53
E_NO_CERTIFICATE_ALREADY_REVOKED = {"success": False, "data": "Certificate is already revoked."}
54
E_NO_CERT_PRIVATE_KEY_FOUND = {"success": False,
55
                               "data": "Internal server error (certificate's private key cannot be found)."}
56
E_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."}
57
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."}
58
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."}
59
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."}
60
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."}
61
E_WRONG_PASSWORD = {"success": False, "data": "The provided passphrase does not match the provided key."}
62
E_IDENTITY_NAME_NOT_SPECIFIED = {"success": False, "data": "Invalid request, missing identity name."}
63
E_IDENTITY_PASSWORD_NOT_SPECIFIED = {"success": False, "data": "Invalid request, missing identity password."}
64
E_INVALID_EXTENSIONS = {"success": False, "data": "Error occurred while creating a certificate. "
65
                                                  "It may be caused by wrong format of extensions."}
66

    
67

    
68
class CertController:
69
    USAGE_KEY_MAP = {'CA': CA_ID, 'SSL': SSL_ID, 'digitalSignature': SIGNATURE_ID, 'authentication': AUTHENTICATION_ID}
70
    INVERSE_USAGE_KEY_MAP = {k: v for v, k in USAGE_KEY_MAP.items()}
71
    FILTERING_TYPE_KEY_MAP = {'root': ROOT_CA_ID, 'inter': INTERMEDIATE_CA_ID, 'end': CERTIFICATE_ID}
72
    # INVERSE_FILTERING_TYPE_KEY_MAP = {k: v for v, k in FILTERING_TYPE_KEY_MAP.items()}
73

    
74

    
75
    @inject
76
    def __init__(self, certificate_service: CertificateService, key_service: KeyService):
77
        self.certificate_service = certificate_service
78
        self.key_service = key_service
79

    
80
    def create_certificate(self):
81
        """create new certificate
82

    
83
        Create a new certificate based on given information
84

    
85
        :param body: Certificate data to be created
86
        :type body: dict | bytes
87

    
88
        :rtype: CreatedResponse
89
        """
90

    
91
        Logger.info(f"\n\t{request.referrer}"
92
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
93

    
94
        required_keys = {SUBJECT, USAGE, VALIDITY_DAYS}                             # required fields of the POST req
95

    
96
        if request.is_json:                                                         # accept JSON only
97
            body = request.get_json()
98

    
99
            Logger.info(f"\n\tRequest body:"
100
                        f"\n{dict_to_string(body)}")
101

    
102
            if not all(k in body for k in required_keys):                           # verify that all keys are present
103
                Logger.error(f"Invalid request, missing parameters")
104
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
105

    
106
            if not isinstance(body[VALIDITY_DAYS], int):                            # type checking
107
                Logger.error(f"Invalid request, wrong parameter '{VALIDITY_DAYS}'.")
108
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
109

    
110
            subject = Subject.from_dict(body[SUBJECT])                              # generate Subject from passed dict
111

    
112
            if subject is None:                                                     # if the format is incorrect
113
                Logger.error(f"Invalid request, wrong parameter '{SUBJECT}'.")
114
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
115

    
116
            usages_dict = {}
117

    
118
            if USAGE not in body or not isinstance(body[USAGE], list):              # type checking
119
                Logger.error(f"Invalid request, wrong parameter '{USAGE}'.")
120
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
121

    
122
            for v in body[USAGE]:                                                   # for each usage
123
                if v not in CertController.USAGE_KEY_MAP:                                 # check that it is a valid usage
124
                    Logger.error(f"Invalid request, wrong parameter '{USAGE}'[{v}].")
125
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST                        # and throw if it is not
126
                usages_dict[CertController.USAGE_KEY_MAP[v]] = True                 # otherwise translate key and set
127

    
128
            if KEY in body:
129
                if isinstance(body[KEY], dict):
130
                    if PASSWORD in body[KEY]:
131
                        passphrase = body[KEY][PASSWORD]
132
                        if KEY_PEM in body[KEY]:
133
                            key_pem = body[KEY][KEY_PEM]
134
                            if not self.key_service.verify_key(key_pem, passphrase=passphrase):
135
                                Logger.error(f"Passphrase specified but invalid.")
136
                                return E_WRONG_PASSWORD, C_BAD_REQUEST
137
                            key = self.key_service.wrap_custom_key(key_pem, passphrase=passphrase)
138
                        else:
139
                            key = self.key_service.create_new_key(passphrase)
140
                    else:
141
                        if KEY_PEM in body[KEY]:
142
                            key_pem = body[KEY][KEY_PEM]
143
                            if not self.key_service.verify_key(key_pem, passphrase=None):
144
                                Logger.error("Passphrase ommited but required.")
145
                                return E_WRONG_PASSWORD, C_BAD_REQUEST
146
                            key = self.key_service.wrap_custom_key(key_pem, passphrase=None)
147
                        else:
148
                            return E_WRONG_PARAMETERS, C_BAD_REQUEST                # if "key" exists but is empty
149
                else:
150
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST
151
            else:
152
                key = self.key_service.create_new_key()                             # if "key" does not exist
153

    
154
            extensions = ""
155
            if EXTENSIONS in body:
156
                extensions = body[EXTENSIONS]
157
            try:
158
                if CA not in body or body[CA] is None:                                  # if issuer omitted (legal) or none
159
                    cert = self.certificate_service.create_root_ca(                     # create a root CA
160
                        key,
161
                        subject,
162
                        usages=usages_dict,                                             # TODO ignoring usages -> discussion
163
                        days=body[VALIDITY_DAYS],
164
                        extensions=extensions
165
                    )
166
                else:
167
                    issuer = self.certificate_service.get_certificate(body[CA])         # get base issuer info
168

    
169
                    if issuer is None:                                              # if such issuer does not exist
170
                        Logger.error(f"No certificate authority with such unique ID exists 'ID = {key.private_key_id}'.")
171
                        self.key_service.delete_key(key.private_key_id)             # free
172
                        return E_NO_ISSUER_FOUND, C_BAD_REQUEST                     # and throw
173

    
174
                    issuer_key = self.key_service.get_key(issuer.private_key_id)    # get issuer's key, which must exist
175

    
176
                    if issuer_key is None:                                          # if it does not
177
                        Logger.error(f"Internal server error (corrupted database).")
178
                        self.key_service.delete_key(key.private_key_id)             # free
179
                        return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR        # and throw
180

    
181
                    f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
182
                        self.certificate_service.create_end_cert
183

    
184
                    # noinspection PyArgumentList
185
                    cert = f(                                                       # create inter CA or end cert
186
                        key,                                                        # according to whether 'CA' is among
187
                        subject,                                                    # the usages' fields
188
                        issuer,
189
                        issuer_key,
190
                        usages=usages_dict,
191
                        days=body[VALIDITY_DAYS],
192
                        extensions=extensions
193
                    )
194

    
195
            # if extensions are specified and CryptoException occurs, the problem is probably in the
196
            # extensions format - otherwise error 500 is expected
197
            except CryptographyException as e:
198
                if len(extensions) > 0:
199
                    return E_INVALID_EXTENSIONS, C_BAD_REQUEST
200
                else:
201
                    raise CryptographyException(e.executable, e.args, e.message)
202
            except InvalidSubjectAttribute as e:
203
                Logger.warning(str(e))
204
                return {"success": False, "data": str(e)}, C_BAD_REQUEST
205

    
206
            if cert is not None:
207
                return {"success": True,
208
                        "data": cert.certificate_id}, C_CREATED_SUCCESSFULLY
209
            else:                                                                   # if this fails, then
210
                Logger.error(f"Internal error: The certificate could not have been created.")
211
                self.key_service.delete_key(key.private_key_id)                     # free
212
                return {"success": False,                                           # and wonder what the cause is,
213
                        "data": "Internal error: The certificate could not have been created."}, C_BAD_REQUEST
214
                                                                                    # as obj/None carries only one bit
215
                                                                                    # of error information
216
        else:
217
            Logger.error(f"The request must be JSON-formatted.")
218
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST                                 # throw in case of non-JSON format
219

    
220
    def get_certificate_by_id(self, id):
221
        """get certificate by ID
222

    
223
        Get certificate in PEM format by ID
224

    
225
        :param id: ID of a certificate to be queried
226
        :type id: dict | bytes
227

    
228
        :rtype: PemResponse
229
        """
230

    
231
        Logger.info(f"\n\t{request.referrer}"
232
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
233
                    f"\n\tCertificate ID = {id}")
234
        try:
235
            v = int(id)
236
        except ValueError:
237
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
238
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
239

    
240
        cert = self.certificate_service.get_certificate(v)
241

    
242
        if cert is None:
243
            Logger.error(f"No such certificate found 'ID = {v}'.")
244
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
245
        else:
246
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
247

    
248
    def get_certificate_details_by_id(self, id):
249
        """get certificate's details by ID
250

    
251
        Get certificate details by ID
252

    
253
        :param id: ID of a certificate whose details are to be queried
254
        :type id: dict | bytes
255

    
256
        :rtype: CertificateResponse
257
        """
258

    
259
        Logger.info(f"\n\t{request.referrer}"
260
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
261
                    f"\n\tCertificate ID = {id}")
262

    
263
        try:
264
            v = int(id)
265
        except ValueError:
266
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
267
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
268

    
269
        cert = self.certificate_service.get_certificate(v)
270

    
271
        if cert is None:
272
            Logger.error(f"No such certificate found 'ID = {v}'.")
273
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
274

    
275
        data = self.cert_to_dict_full(cert)
276
        if data is None:
277
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
278

    
279
        try:
280
            state = self.certificate_service.get_certificate_state(v)
281
            data["status"] = state
282
        except CertificateNotFoundException:
283
            Logger.error(f"No such certificate found 'ID = {id}'.")
284

    
285
        return {"success": True, "data": data}, C_SUCCESS
286

    
287
    def get_certificate_list(self):
288
        """get list of certificates
289

    
290
        Lists certificates based on provided filtering options
291

    
292
        :param filtering: Filter certificate type to be queried
293
        :type filtering: dict | bytes
294

    
295
        :rtype: CertificateListResponse
296
        """
297

    
298
        Logger.info(f"\n\t{request.referrer}"
299
                    f"\n\t{request.method}   {request.path}   {request.scheme}")
300

    
301

    
302
        # the filtering parameter can be read as URL argument or as a request body
303
        if request.is_json:
304
            data = request.get_json()
305
        else:
306
            data = {}
307

    
308
        if FILTERING in request.args.keys():
309
            try:
310
                data[FILTERING] = json.loads(request.args[FILTERING])
311
            except JSONDecodeError:
312
                Logger.error(f"The request must be JSON-formatted.")
313
                return E_NOT_JSON_FORMAT, C_BAD_REQUEST
314

    
315
        if PAGE in request.args.keys():
316
            try:
317
                data[PAGE] = json.loads(request.args[PAGE])
318
            except JSONDecodeError:
319
                Logger.error(f"The request must be JSON-formatted.")
320
                return E_NOT_JSON_FORMAT, C_BAD_REQUEST
321

    
322
        if PER_PAGE in request.args.keys():
323
            try:
324
                data[PER_PAGE] = json.loads(request.args[PER_PAGE])
325
            except JSONDecodeError:
326
                Logger.error(f"The request must be JSON-formatted.")
327
                return E_NOT_JSON_FORMAT, C_BAD_REQUEST
328

    
329
        Logger.info(f"\n\tRequest body:"
330
                    f"\n{dict_to_string(data)}")
331

    
332
        target_types = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}
333
        target_usages = None
334
        target_cn_substring = None
335
        issuer_id = -1
336

    
337
        unfiltered = True
338

    
339
        if PER_PAGE in data:
340
            unfiltered = False
341
            page = data.get(PAGE, 0)
342
            per_page = data[PER_PAGE]
343
        else:
344
            page = None
345
            per_page = None
346

    
347
        if FILTERING in data:                                                   # if the 'filtering' field exists
348
            unfiltered = False
349
            if isinstance(data[FILTERING], dict):                               # and it is also a 'dict'
350

    
351
                # noinspection DuplicatedCode
352
                if TYPE in data[FILTERING]:                                     # containing 'type'
353
                    if isinstance(data[FILTERING][TYPE], list):                 # which is a 'list',
354
                                                                                # map every field to id
355
                        try:
356
                            target_types = {CertController.FILTERING_TYPE_KEY_MAP[v] for v in data[FILTERING][TYPE]}
357
                        except KeyError as e:
358
                            Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{TYPE}' - '{e}'.")
359
                            return E_WRONG_PARAMETERS, C_BAD_REQUEST
360
                    else:
361
                        Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{TYPE}'.")
362
                        return E_WRONG_PARAMETERS, C_BAD_REQUEST
363

    
364
                # noinspection DuplicatedCode
365
                if USAGE in data[FILTERING]:                                    # containing 'usage'
366
                    if isinstance(data[FILTERING][USAGE], list):                # which is a 'list',
367
                                                                                # map every field to id
368
                        try:
369
                            target_usages = {CertController.USAGE_KEY_MAP[v] for v in data[FILTERING][USAGE]}
370
                        except KeyError as e:
371
                            Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{USAGE}' - '{e}'.")
372
                            return E_WRONG_PARAMETERS, C_BAD_REQUEST
373
                    else:
374
                        Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{USAGE}'.")
375
                        return E_WRONG_PARAMETERS, C_BAD_REQUEST
376

    
377
                if COMMON_NAME in data[FILTERING]:                              # containing 'CN'
378
                    if isinstance(data[FILTERING][COMMON_NAME], str):           # which is a 'str'
379
                        target_cn_substring = data[FILTERING][COMMON_NAME]
380
                    else:
381
                        Logger.error(f"Invalid request, wrong parameters '{FILTERING}.{COMMON_NAME}'.")
382
                        return E_WRONG_PARAMETERS, C_BAD_REQUEST
383

    
384
                if ISSUED_BY in data[FILTERING]:                                # containing 'issuedby'
385
                    if isinstance(data[FILTERING][ISSUED_BY], int):             # which is an 'int'
386
                        issuer_id = data[FILTERING][ISSUED_BY]                  # then get its children only
387

    
388
            else:
389
                Logger.error(f"Invalid request, wrong parameters '{FILTERING}'.")
390
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
391

    
392
        if unfiltered:                                                      # if not filtering
393
            certs = self.certificate_service.get_certificates()
394
        elif issuer_id >= 0:                                                # if filtering by an issuer
395
            try:
396
                                                                            # get his children, filtered
397
                certs = self.certificate_service.get_certificates_issued_by_filter(
398
                    issuer_id=issuer_id,
399
                    target_types=target_types,
400
                    target_usages=target_usages,
401
                    target_cn_substring=target_cn_substring,
402
                    page=page,
403
                    per_page=per_page
404
                )
405
            except CertificateNotFoundException:                            # if id does not exist
406
                Logger.error(f"No such certificate found 'ID = {issuer_id}'.")
407
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND                 # throw
408
        else:
409
            certs = self.certificate_service.get_certificates_filter(
410
                target_types=target_types,
411
                target_usages=target_usages,
412
                target_cn_substring=target_cn_substring,
413
                page=page,
414
                per_page=per_page
415
            )
416

    
417
        if certs is None:
418
            Logger.error(f"Internal server error (unknown origin).")
419
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
420
        elif len(certs) == 0:
421
            # TODO check log level
422
            Logger.warning(f"No such certificate found (empty list).")
423
            return {"success": True, "data": []}, C_SUCCESS
424
        else:
425
            ret = []
426
            for c in certs:
427
                data = self.cert_to_dict_partial(c)
428
                if data is None:
429
                    Logger.error(f"Internal server error (corrupted database).")
430
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
431
                ret.append(
432
                    data
433
                )
434
            return {"success": True, "data": ret}, C_SUCCESS
435

    
436
    def get_certificate_root_by_id(self, id):
437
        """get certificate's root of trust chain by ID
438

    
439
        Get certificate's root of trust chain in PEM format by ID
440

    
441
        :param id: ID of a child certificate whose root is to be queried
442
        :type id: dict | bytes
443

    
444
        :rtype: PemResponse
445
        """
446

    
447
        Logger.info(f"\n\t{request.referrer}"
448
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
449
                    f"\n\tCertificate ID = {id}")
450

    
451
        try:
452
            v = int(id)
453
        except ValueError:
454
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
455
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
456

    
457
        try:
458
            root = self.certificate_service.get_root(v)
459
            return {"success": True, "data": root.pem_data}, C_SUCCESS
460
        except CertificateNotFoundException:
461
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
462
        except InvalidRootCA:
463
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
464

    
465
    def get_certificate_trust_chain_by_id(self, id):
466
        """get certificate's trust chain by ID (including root certificate)
467

    
468
        Get certificate trust chain in PEM format by ID
469

    
470
        :param id: ID of a child certificate whose chain is to be queried
471
        :type id: dict | bytes
472

    
473
        :rtype: PemResponse
474
        """
475

    
476
        Logger.info(f"\n\t{request.referrer}"
477
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
478
                    f"\n\tCertificate ID = {id}")
479

    
480
        try:
481
            v = int(id)
482
        except ValueError:
483
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
484
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
485

    
486
        cert = self.certificate_service.get_certificate(v)
487

    
488
        if cert is None:
489
            Logger.error(f"No such certificate found 'ID = {v}'.")
490
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
491

    
492
        if cert.parent_id is None:
493
            Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.")
494
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
495

    
496
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
497

    
498
        ret = []
499
        for intermediate in trust_chain:
500
            ret.append(intermediate.pem_data)
501

    
502
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
503

    
504
    def set_certificate_status(self, id):
505
        """
506
        Revoke a certificate given by ID
507
            - revocation request may contain revocation reason
508
            - revocation reason is verified based on the possible predefined values
509
            - if revocation reason is not specified 'undefined' value is used
510
        :param id: Identifier of the certificate to be revoked
511
        :type id: int
512

    
513
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
514
        """
515

    
516
        Logger.info(f"\n\t{request.referrer}"
517
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
518
                    f"\n\tCertificate ID = {id}")
519

    
520
        required_keys = {STATUS}  # required keys
521

    
522
        # check if the request contains a JSON body
523
        if request.is_json:
524
            request_body = request.get_json()
525

    
526
            Logger.info(f"\n\tRequest body:"
527
                        f"\n{dict_to_string(request_body)}")
528

    
529
            # try to parse certificate identifier -> if it is not int return error 400
530
            try:
531
                identifier = int(id)
532
            except ValueError:
533
                Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
534
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
535

    
536
            # verify that all required keys are present
537
            if not all(k in request_body for k in required_keys):
538
                Logger.error(f"Invalid request, missing parameters.")
539
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
540

    
541
            # get status and reason from the request
542
            status = request_body[STATUS]
543
            reason = request_body.get(REASON, REASON_UNDEFINED)
544
            try:
545
                # set certificate status using certificate_service
546
                self.certificate_service.set_certificate_revocation_status(identifier, status, reason)
547
            except (RevocationReasonInvalidException, CertificateStatusInvalidException):
548
                # these exceptions are thrown in case invalid status or revocation reason is passed to the controller
549
                Logger.error(f"Invalid request, wrong parameters.")
550
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
551
            except CertificateAlreadyRevokedException:
552
                Logger.error(f"Certificate is already revoked 'ID = {identifier}'.")
553
                return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST
554
            except CertificateNotFoundException:
555
                Logger.error(f"No such certificate found 'ID = {identifier}'.")
556
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
557
            except CertificateCannotBeSetToValid as e:
558
                return {"success": False, "data": str(e)}, C_BAD_REQUEST
559
            return {"success": True,
560
                    "data": "Certificate status updated successfully."}, C_SUCCESS
561
        # throw an error in case the request does not contain a json body
562
        else:
563
            Logger.error(f"The request must be JSON-formatted.")
564
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST
565

    
566
    def cert_to_dict_partial(self, c):
567
        """
568
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
569
        :param c: target cert
570
        :return: certificate dict (compliant with some parts of the REST API)
571
        """
572

    
573
        # TODO check log
574
        Logger.debug(f"Function launched.")
575

    
576
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
577
        if c_issuer is None:
578
            return None
579

    
580
        return {
581
            ID: c.certificate_id,
582
            COMMON_NAME: c.common_name,
583
            NOT_BEFORE: datetime.utcfromtimestamp(c.valid_from).strftime(DATETIME_FORMAT),
584
            NOT_AFTER: datetime.utcfromtimestamp(c.valid_to).strftime(DATETIME_FORMAT),
585
            USAGE: {CertController.INVERSE_USAGE_KEY_MAP[k]: v for k, v in c.usages.items()},
586
            ISSUER: {
587
                ID: c_issuer.certificate_id,
588
                COMMON_NAME: c_issuer.common_name
589
            }
590
        }
591

    
592
    def cert_to_dict_full(self, c):
593
        """
594
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
595
        Contains full information.
596
        :param c: target cert
597
        :return: certificate dict (compliant with some parts of the REST API)
598
        """
599

    
600
        Logger.info(f"Function launched.")
601

    
602
        subj = self.certificate_service.get_subject_from_certificate(c)
603
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
604
        if c_issuer is None:
605
            return None
606

    
607
        return {
608
            SUBJECT: subj.to_dict(),
609
            NOT_BEFORE: datetime.utcfromtimestamp(c.valid_from).strftime(DATETIME_FORMAT),
610
            NOT_AFTER: datetime.utcfromtimestamp(c.valid_to).strftime(DATETIME_FORMAT),
611
            USAGE: {CertController.INVERSE_USAGE_KEY_MAP[k]: v for k, v in c.usages.items()},
612
            CA: c_issuer.certificate_id
613
        }
614

    
615
    def get_private_key_of_a_certificate(self, id):
616
        """
617
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
618

    
619
        :param id: ID of a certificate whose private key is to be queried
620
        :type id: dict | bytes
621

    
622
        :rtype: PemResponse
623
        """
624

    
625
        Logger.info(f"\n\t{request.referrer}"
626
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
627
                    f"\n\tCertificate ID = {id}")
628

    
629
        # try to parse the supplied ID
630
        try:
631
            v = int(id)
632
        except ValueError:
633
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
634
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
635

    
636
        # find a certificate using the given ID
637
        cert = self.certificate_service.get_certificate(v)
638

    
639
        if cert is None:
640
            Logger.error(f"No such certificate found 'ID = {v}'.")
641
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
642
        else:
643
            # certificate exists, fetch it's private key
644
            private_key = self.key_service.get_key(cert.private_key_id)
645
            if cert is None:
646
                Logger.error(f"Internal server error (certificate's private key cannot be found).")
647
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
648
            else:
649
                return {"success": True, "data": private_key.private_key}, C_SUCCESS
650

    
651
    def get_public_key_of_a_certificate(self, id):
652
        """
653
        Get a public key of a certificate in PEM format specified by certificate's ID
654

    
655
        :param id: ID of a certificate whose public key is to be queried
656
        :type id: dict | bytes
657

    
658
        :rtype: PemResponse
659
        """
660

    
661
        Logger.info(f"\n\t{request.referrer}"
662
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
663
                    f"\n\tCertificate ID = {id}")
664

    
665
        # try to parse the supplied ID
666
        try:
667
            v = int(id)
668
        except ValueError:
669
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
670
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
671

    
672
        # find a certificate using the given ID
673
        cert = self.certificate_service.get_certificate(v)
674

    
675
        if cert is None:
676
            Logger.error(f"No such certificate found 'ID = {v}'.")
677
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
678
        else:
679
            return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
680

    
681
    def delete_certificate(self, id):
682
        """
683
        Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
684
        :param id: target certificate ID
685
        :rtype: DeleteResponse
686
        """
687

    
688
        Logger.info(f"\n\t{request.referrer}"
689
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
690
                    f"\n\tCertificate ID = {id}")
691

    
692
        try:
693
            v = int(id)
694
        except ValueError:
695
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}].")
696
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
697

    
698
        try:
699
            self.certificate_service.delete_certificate(v)
700
        except CertificateNotFoundException:
701
            Logger.error(f"No such certificate found 'ID = {v}'.")
702
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
703
        except DatabaseException:
704
            Logger.error(f"Internal server error (corrupted database).")
705
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
706
        except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
707
            Logger.error(f"Internal server error (unknown origin).")
708
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
709

    
710
        return {"success": True, "data": "The certificate and its descendants have been successfully deleted."}
711

    
712
    def generate_certificate_pkcs_identity(self, id):
713
        """
714
        Generates a PKCS12 identity (including the chain of trust) of the certificate given by the specified ID.
715
        Response is of application/x-pkcs12 type.
716

    
717
        :param id: ID of a certificate whose PKCS12 identity should be generated
718
        :type id: int
719

    
720
        :rtype: Response
721
        """
722

    
723
        Logger.info(f"\n\t{request.referrer}"
724
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
725
                    f"\n\tCertificate ID = {id}")
726

    
727
        # try to parse the supplied ID
728
        try:
729
            v = int(id)
730
        except ValueError:
731
            Logger.error(f"Invalid request, wrong parameters 'id'[{id}] (expected integer).")
732
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
733

    
734
        # find a certificate using the given ID
735
        cert = self.certificate_service.get_certificate(v)
736

    
737
        if request.is_json:                                                         # accept JSON only
738
            body = request.get_json()
739

    
740
            # check whether the request is well formed meaning that it contains all required fields
741
            if NAME not in body.keys():
742
                return E_IDENTITY_NAME_NOT_SPECIFIED, C_BAD_REQUEST
743

    
744
            if PASSWORD not in body.keys():
745
                return E_IDENTITY_PASSWORD_NOT_SPECIFIED, C_BAD_REQUEST
746

    
747
            # parse required fields from the request
748
            identity_name = body[NAME]
749
            identity_password = body[PASSWORD]
750

    
751
            # check whether a certificated specified by the given ID exists
752
            if cert is None:
753
                Logger.error(f"No such certificate found 'ID = {v}'.")
754
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
755
            else:
756
                # try to load it's private key
757
                key = self.key_service.get_key(cert.private_key_id)
758
                if key is None:
759
                    Logger.error(
760
                        f"The private key 'ID = {cert.private_key_id}'of the certificate 'ID = {cert.certificate_id}' does not exist.")
761
                    return E_NO_CERTIFICATES_FOUND, C_INTERNAL_SERVER_ERROR
762
                else:
763
                    # generate PKCS12 identity
764
                    identity_byte_array = self.certificate_service.generate_pkcs_identity(cert, key,
765
                                                                                          identity_name,
766
                                                                                          identity_password)
767
                    return Response(identity_byte_array, mimetype='application/x-pkcs12')
(2-2/5)