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.exceptions.database_exception import DatabaseException
13
from src.exceptions.unknown_exception import UnknownException
14
from src.model.subject import Subject
15
from src.services.certificate_service import CertificateService, RevocationReasonInvalidException, \
16
    CertificateStatusInvalidException, CertificateNotFoundException, CertificateAlreadyRevokedException
17
#  responsibility.
18
from src.services.key_service import KeyService
19

    
20
TREE_NODE_TYPE_COUNT = 3
21

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

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

    
49
C_CREATED_SUCCESSFULLY = 201
50
C_BAD_REQUEST = 400
51
C_NOT_FOUND = 404
52
C_NO_DATA = 205  # TODO related to 204 issue                                               # TODO related to 204 issue
53
C_INTERNAL_SERVER_ERROR = 500
54
C_SUCCESS = 200
55

    
56

    
57
class CertController:
58
    KEY_MAP = {'CA': CA_ID, 'SSL': SSL_ID, 'digitalSignature': SIGNATURE_ID, 'authentication': AUTHENTICATION_ID}
59
    INVERSE_KEY_MAP = {k: v for v, k in KEY_MAP.items()}
60

    
61
    @inject
62
    def __init__(self, certificate_service: CertificateService, key_service: KeyService):
63
        self.certificate_service = certificate_service
64
        self.key_service = key_service
65

    
66
    def create_certificate(self):
67
        """create new certificate
68

    
69
        Create a new certificate based on given information
70

    
71
        :param body: Certificate data to be created
72
        :type body: dict | bytes
73

    
74
        :rtype: CreatedResponse
75
        """
76
        required_keys = {SUBJECT, USAGE, VALIDITY_DAYS}                             # required fields of the POST req
77

    
78
        if request.is_json:                                                         # accept JSON only
79
            body = request.get_json()
80
            if not all(k in body for k in required_keys):                           # verify that all keys are present
81
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
82

    
83
            if not isinstance(body[VALIDITY_DAYS], int):                            # type checking
84
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
85

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

    
88
            if subject is None:                                                     # if the format is incorrect
89
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
90

    
91
            usages_dict = {}
92

    
93
            if not isinstance(body[USAGE], dict):                                   # type checking
94
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
95

    
96
            for k, v in body[USAGE].items():                                        # for each usage
97
                if k not in CertController.KEY_MAP:                                 # check that it is a valid usage
98
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST                        # and throw if it is not
99
                usages_dict[CertController.KEY_MAP[k]] = v                          # otherwise translate key and set
100

    
101
            key = self.key_service.create_new_key()                                      # TODO pass key
102

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

    
113
                if issuer is None:                                                  # if such issuer does not exist
114
                    self.key_service.delete_key(key.private_key_id)                      # free
115
                    return E_NO_ISSUER_FOUND, C_BAD_REQUEST                         # and throw
116

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

    
119
                if issuer_key is None:                                              # if it does not
120
                    self.key_service.delete_key(key.private_key_id)                      # free
121
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR            # and throw
122

    
123
                f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
124
                    self.certificate_service.create_end_cert
125

    
126
                # noinspection PyTypeChecker
127
                cert = f(                                                           # create inter CA or end cert
128
                    key,                                                            # according to whether 'CA' is among
129
                    subject,                                                        # the usages' fields
130
                    issuer,
131
                    issuer_key,
132
                    usages=usages_dict,
133
                    days=body[VALIDITY_DAYS]
134
                )
135

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

    
148
    def get_certificate_by_id(self, id):
149
        """get certificate by ID
150

    
151
        Get certificate in PEM format by ID
152

    
153
        :param id: ID of a certificate to be queried
154
        :type id: dict | bytes
155

    
156
        :rtype: PemResponse
157
        """
158
        try:
159
            v = int(id)
160
        except ValueError:
161
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
162

    
163
        cert = self.certificate_service.get_certificate(v)
164

    
165
        if cert is None:
166
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
167
        else:
168
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
169

    
170
    def get_certificate_details_by_id(self, id):
171
        """get certificate's details by ID
172

    
173
        Get certificate details by ID
174

    
175
        :param id: ID of a certificate whose details are to be queried
176
        :type id: dict | bytes
177

    
178
        :rtype: CertificateResponse
179
        """
180
        try:
181
            v = int(id)
182
        except ValueError:
183
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
184

    
185
        cert = self.certificate_service.get_certificate(v)
186

    
187
        if cert is None:
188
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
189
        else:
190
            data = self.cert_to_dict_full(cert)
191
            if data is None:
192
                return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
193
            return {"success": True, "data": data}, C_SUCCESS
194

    
195
    def get_certificate_list(self):
196
        """get list of certificates
197

    
198
        Lists certificates based on provided filtering options
199

    
200
        :param filtering: Filter certificate type to be queried
201
        :type filtering: dict | bytes
202

    
203
        :rtype: CertificateListResponse
204
        """
205
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
206
        issuer_id = -1
207

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

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

    
240
                certs = [child for child in children if child.type_id in targets]
241

    
242
            elif len(targets) == TREE_NODE_TYPE_COUNT:                              # = 3 -> root node,
243
                                                                                    # intermediate node,
244
                                                                                    # or leaf node
245

    
246
                                                                                    # if filtering did not change the
247
                                                                                    # targets,
248
                certs = self.certificate_service.get_certificates()                 # fetch everything
249
            else:                                                                   # otherwise fetch targets only
250
                certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
251
        else:
252
            certs = self.certificate_service.get_certificates()                     # if no params, fetch everything
253

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

    
269
    def get_certificate_root_by_id(self, id):
270
        """get certificate's root of trust chain by ID
271

    
272
        Get certificate's root of trust chain in PEM format by ID
273

    
274
        :param id: ID of a child certificate whose root is to be queried
275
        :type id: dict | bytes
276

    
277
        :rtype: PemResponse
278
        """
279
        try:
280
            v = int(id)
281
        except ValueError:
282
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
283

    
284
        cert = self.certificate_service.get_certificate(v)
285

    
286
        if cert is None:
287
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
288

    
289
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
290
        if trust_chain is None or len(trust_chain) == 0:
291
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
292

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

    
295
    def get_certificate_trust_chain_by_id(self, id):
296
        """get certificate's trust chain by ID
297

    
298
        Get certificate trust chain in PEM format by ID
299

    
300
        :param id: ID of a child certificate whose chain is to be queried
301
        :type id: dict | bytes
302

    
303
        :rtype: PemResponse
304
        """
305

    
306
        try:
307
            v = int(id)
308
        except ValueError:
309
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
310

    
311
        cert = self.certificate_service.get_certificate(v)
312

    
313
        if cert is None:
314
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
315

    
316
        if cert.parent_id is None:
317
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
318

    
319
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id)
320

    
321
        ret = []
322
        for intermediate in trust_chain:
323
            ret.append(intermediate.pem_data)
324

    
325
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
326

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

    
336
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
337
        """
338
        required_keys = {STATUS}  # required keys
339

    
340
        # try to parse certificate identifier -> if it is not int return error 400
341
        try:
342
            identifier = int(id)
343
        except ValueError:
344
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
345

    
346
        # check if the request contains a JSON body
347
        if request.is_json:
348
            request_body = request.get_json()
349
            # verify that all required keys are present
350
            if not all(k in request_body for k in required_keys):
351
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
352

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

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

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

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

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

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

    
418
        :param id: ID of a certificate whose private key is to be queried
419
        :type id: dict | bytes
420

    
421
        :rtype: PemResponse
422
        """
423

    
424
        # try to parse the supplied ID
425
        try:
426
            v = int(id)
427
        except ValueError:
428
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
429

    
430
        # find a certificate using the given ID
431
        cert = self.certificate_service.get_certificate(v)
432

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

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

    
447
        :param id: ID of a certificate whose public key is to be queried
448
        :type id: dict | bytes
449

    
450
        :rtype: PemResponse
451
        """
452

    
453
        # try to parse the supplied ID
454
        try:
455
            v = int(id)
456
        except ValueError:
457
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
458

    
459
        # find a certificate using the given ID
460
        cert = self.certificate_service.get_certificate(v)
461

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

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

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

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