Projekt

Obecné

Profil

Stáhnout (34.1 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
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
PASSWORD = "password"
51

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

    
68

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

    
75

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

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

    
84
        Create a new certificate based on given information
85

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

    
89
        :rtype: CreatedResponse
90
        """
91

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

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

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

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

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

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

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

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

    
117
            usages_dict = {}
118

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

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

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

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

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

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

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

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

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

    
196
            # if extensions are specified and CryptoException occurs, the problem is probably in the
197
            # extensions format - otherwise error 500 is expected
198
            except CryptographyException as e:
199
                if len(extensions) > 0:
200
                    return E_INVALID_EXTENSIONS, C_BAD_REQUEST
201
                else:
202
                    raise CryptographyException(e.executable, e.args, e.message)
203

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

    
218
    def get_certificate_by_id(self, id):
219
        """get certificate by ID
220

    
221
        Get certificate in PEM format by ID
222

    
223
        :param id: ID of a certificate to be queried
224
        :type id: dict | bytes
225

    
226
        :rtype: PemResponse
227
        """
228

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

    
238
        cert = self.certificate_service.get_certificate(v)
239

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

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

    
249
        Get certificate details by ID
250

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

    
254
        :rtype: CertificateResponse
255
        """
256

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

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

    
267
        cert = self.certificate_service.get_certificate(v)
268

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

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

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

    
283
        return {"success": True, "data": data}, C_SUCCESS
284

    
285
    def get_certificate_list(self):
286
        """get list of certificates
287

    
288
        Lists certificates based on provided filtering options
289

    
290
        :param filtering: Filter certificate type to be queried
291
        :type filtering: dict | bytes
292

    
293
        :rtype: CertificateListResponse
294
        """
295

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

    
299

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

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

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

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

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

    
330
        target_types = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}
331
        target_usages = {v for v in CertController.INVERSE_USAGE_KEY_MAP.keys()}
332
        target_cn_substring = None
333
        issuer_id = -1
334

    
335
        unfiltered = True
336

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

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

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

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

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

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

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

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

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

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

    
437
        Get certificate's root of trust chain in PEM format by ID
438

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

    
442
        :rtype: PemResponse
443
        """
444

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

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

    
455
        cert = self.certificate_service.get_certificate(v)
456

    
457
        if cert is None:
458
            Logger.error(f"No such certificate found 'ID = {v}'.")
459
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
460

    
461
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
462
        if trust_chain is None or len(trust_chain) == 0:
463
            Logger.error(f"No such certificate found (empty list).")
464
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
465

    
466
        return {"success": True, "data": trust_chain[-1].pem_data}, C_SUCCESS
467

    
468
    def get_certificate_trust_chain_by_id(self, id):
469
        """get certificate's trust chain by ID (including root certificate)
470

    
471
        Get certificate trust chain in PEM format by ID
472

    
473
        :param id: ID of a child certificate whose chain is to be queried
474
        :type id: dict | bytes
475

    
476
        :rtype: PemResponse
477
        """
478

    
479
        Logger.info(f"\n\t{request.referrer}"
480
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
481
                    f"\n\tCertificate ID = {id}")
482

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

    
489
        cert = self.certificate_service.get_certificate(v)
490

    
491
        if cert is None:
492
            Logger.error(f"No such certificate found 'ID = {v}'.")
493
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
494

    
495
        if cert.parent_id is None:
496
            Logger.error(f"Parent ID is empty in certificate 'ID = {v}'.")
497
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
498

    
499
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
500

    
501
        ret = []
502
        for intermediate in trust_chain:
503
            ret.append(intermediate.pem_data)
504

    
505
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
506

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

    
516
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
517
        """
518

    
519
        Logger.info(f"\n\t{request.referrer}"
520
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
521
                    f"\n\tCertificate ID = {id}")
522

    
523
        required_keys = {STATUS}  # required keys
524

    
525
        # check if the request contains a JSON body
526
        if request.is_json:
527
            request_body = request.get_json()
528

    
529
            Logger.info(f"\n\tRequest body:"
530
                        f"\n{dict_to_string(request_body)}")
531

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

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

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

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

    
576
        # TODO check log
577
        Logger.debug(f"Function launched.")
578

    
579
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
580
        if c_issuer is None:
581
            return None
582

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

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

    
603
        Logger.info(f"Function launched.")
604

    
605
        subj = self.certificate_service.get_subject_from_certificate(c)
606
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
607
        if c_issuer is None:
608
            return None
609

    
610
        return {
611
            SUBJECT: subj.to_dict(),
612
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
613
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
614
            USAGE: {CertController.INVERSE_USAGE_KEY_MAP[k]: v for k, v in c.usages.items()},
615
            CA: c_issuer.certificate_id
616
        }
617

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

    
622
        :param id: ID of a certificate whose private key is to be queried
623
        :type id: dict | bytes
624

    
625
        :rtype: PemResponse
626
        """
627

    
628
        Logger.info(f"\n\t{request.referrer}"
629
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
630
                    f"\n\tCertificate ID = {id}")
631

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

    
639
        # find a certificate using the given ID
640
        cert = self.certificate_service.get_certificate(v)
641

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

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

    
658
        :param id: ID of a certificate whose public key is to be queried
659
        :type id: dict | bytes
660

    
661
        :rtype: PemResponse
662
        """
663

    
664
        Logger.info(f"\n\t{request.referrer}"
665
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
666
                    f"\n\tCertificate ID = {id}")
667

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

    
675
        # find a certificate using the given ID
676
        cert = self.certificate_service.get_certificate(v)
677

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

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

    
691
        Logger.info(f"\n\t{request.referrer}"
692
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
693
                    f"\n\tCertificate ID = {id}")
694

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

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

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

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

    
720
        :param id: ID of a certificate whose PKCS12 identity should be generated
721
        :type id: int
722

    
723
        :rtype: Response
724
        """
725

    
726
        Logger.info(f"\n\t{request.referrer}"
727
                    f"\n\t{request.method}   {request.path}   {request.scheme}"
728
                    f"\n\tCertificate ID = {id}")
729

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

    
737
        # find a certificate using the given ID
738
        cert = self.certificate_service.get_certificate(v)
739

    
740
        if request.is_json:                                                         # accept JSON only
741
            body = request.get_json()
742

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

    
747
            if PASSWORD not in body.keys():
748
                return E_IDENTITY_PASSWORD_NOT_SPECIFIED, C_BAD_REQUEST
749

    
750
            # parse required fields from the request
751
            identity_name = body[NAME]
752
            identity_password = body[PASSWORD]
753

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