Projekt

Obecné

Profil

Stáhnout (21 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
7
from injector import inject
8

    
9
from src.constants import CA_ID, \
10
    SSL_ID, SIGNATURE_ID, AUTHENTICATION_ID, \
11
    DATETIME_FORMAT, ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID  # TODO DATABASE_FILE - not the Controller's
12
from src.controllers.return_codes import *
13
from src.exceptions.database_exception import DatabaseException
14
from src.exceptions.unknown_exception import UnknownException
15
from src.model.subject import Subject
16
from src.services.certificate_service import CertificateService, RevocationReasonInvalidException, \
17
    CertificateStatusInvalidException, CertificateNotFoundException, CertificateAlreadyRevokedException, \
18
    CertificateCannotBeSetToValid
19
#  responsibility.
20
from src.services.key_service import KeyService
21

    
22
TREE_NODE_TYPE_COUNT = 3
23

    
24
FILTERING = "filtering"
25
ISSUER = "issuer"
26
US = "usage"
27
NOT_AFTER = "notAfter"
28
NOT_BEFORE = "notBefore"
29
COMMON_NAME = "CN"
30
ID = "id"
31
USAGE = "usage"
32
SUBJECT = "subject"
33
VALIDITY_DAYS = "validityDays"
34
CA = "CA"
35
ISSUED_BY = "issuedby"
36
STATUS = "status"
37
REASON = "reason"
38
REASON_UNDEFINED = "unspecified"
39

    
40
E_NO_ISSUER_FOUND = {"success": False, "data": "No certificate authority with such unique ID exists."}
41
E_NO_CERTIFICATES_FOUND = {"success": False, "data": "No such certificate found."}
42
E_NO_CERTIFICATE_ALREADY_REVOKED = {"success": False, "data": "Certificate is already revoked."}
43
E_NO_CERT_PRIVATE_KEY_FOUND = {"success": False,
44
                               "data": "Internal server error (certificate's private key cannot be found)."}
45
E_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."}
46
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."}
47
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."}
48
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."}
49
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."}
50

    
51

    
52
class CertController:
53
    KEY_MAP = {'CA': CA_ID, 'SSL': SSL_ID, 'digitalSignature': SIGNATURE_ID, 'authentication': AUTHENTICATION_ID}
54
    INVERSE_KEY_MAP = {k: v for v, k in KEY_MAP.items()}
55

    
56
    @inject
57
    def __init__(self, certificate_service: CertificateService, key_service: KeyService):
58
        self.certificate_service = certificate_service
59
        self.key_service = key_service
60

    
61
    def create_certificate(self):
62
        """create new certificate
63

    
64
        Create a new certificate based on given information
65

    
66
        :param body: Certificate data to be created
67
        :type body: dict | bytes
68

    
69
        :rtype: CreatedResponse
70
        """
71
        required_keys = {SUBJECT, USAGE, VALIDITY_DAYS}                             # required fields of the POST req
72

    
73
        if request.is_json:                                                         # accept JSON only
74
            body = request.get_json()
75
            if not all(k in body for k in required_keys):                           # verify that all keys are present
76
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
77

    
78
            if not isinstance(body[VALIDITY_DAYS], int):                            # type checking
79
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
80

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

    
83
            if subject is None:                                                     # if the format is incorrect
84
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
85

    
86
            usages_dict = {}
87

    
88
            if not isinstance(body[USAGE], dict):                                   # type checking
89
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
90

    
91
            for k, v in body[USAGE].items():                                        # for each usage
92
                if k not in CertController.KEY_MAP:                                 # check that it is a valid usage
93
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST                        # and throw if it is not
94
                usages_dict[CertController.KEY_MAP[k]] = v                          # otherwise translate key and set
95

    
96
            key = self.key_service.create_new_key()                                      # TODO pass key
97

    
98
            if CA not in body or body[CA] is None:                                  # if issuer omitted (legal) or none
99
                cert = self.certificate_service.create_root_ca(                          # create a root CA
100
                    key,
101
                    subject,
102
                    usages=usages_dict,                                             # TODO ignoring usages -> discussion
103
                    days=body[VALIDITY_DAYS]
104
                )
105
            else:
106
                issuer = self.certificate_service.get_certificate(body[CA])              # get base issuer info
107

    
108
                if issuer is None:                                                  # if such issuer does not exist
109
                    self.key_service.delete_key(key.private_key_id)                      # free
110
                    return E_NO_ISSUER_FOUND, C_BAD_REQUEST                         # and throw
111

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

    
114
                if issuer_key is None:                                              # if it does not
115
                    self.key_service.delete_key(key.private_key_id)                      # free
116
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR            # and throw
117

    
118
                f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
119
                    self.certificate_service.create_end_cert
120

    
121
                # noinspection PyTypeChecker
122
                cert = f(                                                           # create inter CA or end cert
123
                    key,                                                            # according to whether 'CA' is among
124
                    subject,                                                        # the usages' fields
125
                    issuer,
126
                    issuer_key,
127
                    usages=usages_dict,
128
                    days=body[VALIDITY_DAYS]
129
                )
130

    
131
            if cert is not None:
132
                return {"success": True,
133
                        "data": cert.certificate_id}, C_CREATED_SUCCESSFULLY
134
            else:                                                                   # if this fails, then
135
                self.key_service.delete_key(key.private_key_id)                          # free
136
                return {"success": False,                                           # and wonder what the cause is,
137
                        "data": "Internal error: The certificate could not have been created."}, C_BAD_REQUEST
138
                                                                                    # as obj/None carries only one bit
139
                                                                                    # of error information
140
        else:
141
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST                                 # throw in case of non-JSON format
142

    
143
    def get_certificate_by_id(self, id):
144
        """get certificate by ID
145

    
146
        Get certificate in PEM format by ID
147

    
148
        :param id: ID of a certificate to be queried
149
        :type id: dict | bytes
150

    
151
        :rtype: PemResponse
152
        """
153
        try:
154
            v = int(id)
155
        except ValueError:
156
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
157

    
158
        cert = self.certificate_service.get_certificate(v)
159

    
160
        if cert is None:
161
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
162
        else:
163
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
164

    
165
    def get_certificate_details_by_id(self, id):
166
        """get certificate's details by ID
167

    
168
        Get certificate details by ID
169

    
170
        :param id: ID of a certificate whose details are to be queried
171
        :type id: dict | bytes
172

    
173
        :rtype: CertificateResponse
174
        """
175
        try:
176
            v = int(id)
177
        except ValueError:
178
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
179

    
180
        cert = self.certificate_service.get_certificate(v)
181

    
182
        if cert is None:
183
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
184
        else:
185
            data = self.cert_to_dict_full(cert)
186
            if data is None:
187
                return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
188
            return {"success": True, "data": data}, C_SUCCESS
189

    
190
    def get_certificate_list(self):
191
        """get list of certificates
192

    
193
        Lists certificates based on provided filtering options
194

    
195
        :param filtering: Filter certificate type to be queried
196
        :type filtering: dict | bytes
197

    
198
        :rtype: CertificateListResponse
199
        """
200
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
201
        issuer_id = -1
202

    
203
        # the filtering parameter can be read as URL argument or as a request body
204
        if request.is_json or FILTERING in request.args.keys():                     # if the request carries JSON data
205
            if request.is_json:
206
                data = request.get_json()                                           # get it
207
            else:
208
                try:
209
                    data = {FILTERING: json.loads(request.args[FILTERING])}
210
                except JSONDecodeError:
211
                    return E_NOT_JSON_FORMAT, C_BAD_REQUEST
212

    
213
            if FILTERING in data:                                                   # if the 'filtering' field exists
214
                if isinstance(data[FILTERING], dict):                               # and it is also a 'dict'
215
                    if CA in data[FILTERING]:                                       # containing 'CA'
216
                        if isinstance(data[FILTERING][CA], bool):                   # which is a 'bool',
217
                            if data[FILTERING][CA]:                                 # then filter according to 'CA'.
218
                                targets.remove(CERTIFICATE_ID)
219
                            else:
220
                                targets.remove(ROOT_CA_ID)
221
                                targets.remove(INTERMEDIATE_CA_ID)
222
                        else:
223
                            return E_WRONG_PARAMETERS, C_BAD_REQUEST
224
                    if ISSUED_BY in data[FILTERING]:                                # containing 'issuedby'
225
                        if isinstance(data[FILTERING][ISSUED_BY], int):             # which is an 'int'
226
                            issuer_id = data[FILTERING][ISSUED_BY]                  # then get its children only
227
                else:
228
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST
229
            if issuer_id >= 0:                                                      # if filtering by an issuer
230
                try:
231
                    children = self.certificate_service.get_certificates_issued_by(issuer_id)  # get his children
232
                except CertificateNotFoundException:                                # if id does not exist
233
                    return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND                     # throw
234

    
235
                certs = [child for child in children if child.type_id in targets]
236

    
237
            elif len(targets) == TREE_NODE_TYPE_COUNT:                              # = 3 -> root node,
238
                                                                                    # intermediate node,
239
                                                                                    # or leaf node
240

    
241
                                                                                    # if filtering did not change the
242
                                                                                    # targets,
243
                certs = self.certificate_service.get_certificates()                 # fetch everything
244
            else:                                                                   # otherwise fetch targets only
245
                certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
246
        else:
247
            certs = self.certificate_service.get_certificates()                     # if no params, fetch everything
248

    
249
        if certs is None:
250
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
251
        elif len(certs) == 0:
252
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
253
        else:
254
            ret = []
255
            for c in certs:
256
                data = self.cert_to_dict_partial(c)
257
                if data is None:
258
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
259
                ret.append(
260
                    data
261
                )
262
            return {"success": True, "data": ret}, C_SUCCESS
263

    
264
    def get_certificate_root_by_id(self, id):
265
        """get certificate's root of trust chain by ID
266

    
267
        Get certificate's root of trust chain in PEM format by ID
268

    
269
        :param id: ID of a child certificate whose root is to be queried
270
        :type id: dict | bytes
271

    
272
        :rtype: PemResponse
273
        """
274
        try:
275
            v = int(id)
276
        except ValueError:
277
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
278

    
279
        cert = self.certificate_service.get_certificate(v)
280

    
281
        if cert is None:
282
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
283

    
284
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
285
        if trust_chain is None or len(trust_chain) == 0:
286
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
287

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

    
290
    def get_certificate_trust_chain_by_id(self, id):
291
        """get certificate's trust chain by ID (including root certificate)
292

    
293
        Get certificate trust chain in PEM format by ID
294

    
295
        :param id: ID of a child certificate whose chain is to be queried
296
        :type id: dict | bytes
297

    
298
        :rtype: PemResponse
299
        """
300

    
301
        try:
302
            v = int(id)
303
        except ValueError:
304
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
305

    
306
        cert = self.certificate_service.get_certificate(v)
307

    
308
        if cert is None:
309
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
310

    
311
        if cert.parent_id is None:
312
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
313

    
314
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
315

    
316
        ret = []
317
        for intermediate in trust_chain:
318
            ret.append(intermediate.pem_data)
319

    
320
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
321

    
322
    def set_certificate_status(self, id):
323
        """
324
        Revoke a certificate given by ID
325
            - revocation request may contain revocation reason
326
            - revocation reason is verified based on the possible predefined values
327
            - if revocation reason is not specified 'undefined' value is used
328
        :param id: Identifier of the certificate to be revoked
329
        :type id: int
330

    
331
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
332
        """
333
        required_keys = {STATUS}  # required keys
334

    
335
        # try to parse certificate identifier -> if it is not int return error 400
336
        try:
337
            identifier = int(id)
338
        except ValueError:
339
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
340

    
341
        # check if the request contains a JSON body
342
        if request.is_json:
343
            request_body = request.get_json()
344
            # verify that all required keys are present
345
            if not all(k in request_body for k in required_keys):
346
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
347

    
348
            # get status and reason from the request
349
            status = request_body[STATUS]
350
            reason = request_body.get(REASON, REASON_UNDEFINED)
351
            try:
352
                # set certificate status using certificate_service
353
                self.certificate_service.set_certificate_revocation_status(identifier, status, reason)
354
            except (RevocationReasonInvalidException, CertificateStatusInvalidException):
355
                # these exceptions are thrown in case invalid status or revocation reason is passed to the controller
356
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
357
            except CertificateAlreadyRevokedException:
358
                return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST
359
            except CertificateNotFoundException:
360
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
361
            except CertificateCannotBeSetToValid as e:
362
                return {"success": False, "data": str(e)}, C_BAD_REQUEST
363
            return {"success": True,
364
                    "data": "Certificate status updated successfully."}, C_SUCCESS
365
        # throw an error in case the request does not contain a json body
366
        else:
367
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST
368

    
369
    def cert_to_dict_partial(self, c):
370
        """
371
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
372
        :param c: target cert
373
        :return: certificate dict (compliant with some parts of the REST API)
374
        """
375
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
376
        if c_issuer is None:
377
            return None
378

    
379
        return {
380
            ID: c.certificate_id,
381
            COMMON_NAME: c.common_name,
382
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
383
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
384
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
385
            ISSUER: {
386
                ID: c_issuer.certificate_id,
387
                COMMON_NAME: c_issuer.common_name
388
            }
389
        }
390

    
391
    def cert_to_dict_full(self, c):
392
        """
393
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
394
        Contains full information.
395
        :param c: target cert
396
        :return: certificate dict (compliant with some parts of the REST API)
397
        """
398
        subj = self.certificate_service.get_subject_from_certificate(c)
399
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
400
        if c_issuer is None:
401
            return None
402

    
403
        return {
404
            SUBJECT: subj.to_dict(),
405
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
406
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
407
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
408
            CA: c_issuer.certificate_id
409
        }
410

    
411
    def get_private_key_of_a_certificate(self, id):
412
        """
413
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
414

    
415
        :param id: ID of a certificate whose private key is to be queried
416
        :type id: dict | bytes
417

    
418
        :rtype: PemResponse
419
        """
420

    
421
        # try to parse the supplied ID
422
        try:
423
            v = int(id)
424
        except ValueError:
425
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
426

    
427
        # find a certificate using the given ID
428
        cert = self.certificate_service.get_certificate(v)
429

    
430
        if cert is None:
431
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
432
        else:
433
            # certificate exists, fetch it's private key
434
            private_key = self.key_service.get_key(cert.private_key_id)
435
            if cert is None:
436
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
437
            else:
438
                return {"success": True, "data": private_key.private_key}, C_SUCCESS
439

    
440
    def get_public_key_of_a_certificate(self, id):
441
        """
442
        Get a public key of a certificate in PEM format specified by certificate's ID
443

    
444
        :param id: ID of a certificate whose public key is to be queried
445
        :type id: dict | bytes
446

    
447
        :rtype: PemResponse
448
        """
449

    
450
        # try to parse the supplied ID
451
        try:
452
            v = int(id)
453
        except ValueError:
454
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
455

    
456
        # find a certificate using the given ID
457
        cert = self.certificate_service.get_certificate(v)
458

    
459
        if cert is None:
460
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
461
        else:
462
            return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
463

    
464
    def delete_certificate(self, id):
465
        """
466
        Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
467
        :param id: target certificate ID
468
        :rtype: DeleteResponse
469
        """
470
        try:
471
            v = int(id)
472
        except ValueError:
473
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
474

    
475
        try:
476
            self.certificate_service.delete_certificate(v)
477
        except CertificateNotFoundException:
478
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
479
        except DatabaseException:
480
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
481
        except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
482
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
483

    
484
        return {"success": True, "data": "The certificate and its descendants have been successfully deleted."}
(2-2/4)