Projekt

Obecné

Profil

Stáhnout (20 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
STATUS = "status"
34
REASON = "reason"
35
REASON_UNDEFINED = "unspecified"
36

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

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

    
55

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

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

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

    
68
        Create a new certificate based on given information
69

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

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

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

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

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

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

    
90
            usages_dict = {}
91

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

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

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

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

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

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

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

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

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

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

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

    
150
        Get certificate in PEM format by ID
151

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

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

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

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

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

    
172
        Get certificate details by ID
173

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

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

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

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

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

    
197
        Lists certificates based on provided filtering options
198

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

    
202
        :rtype: CertificateListResponse
203
        """
204
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
205

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

    
216
            if FILTERING in data:                                                   # if the 'filtering' field exists
217
                if isinstance(data[FILTERING], dict):                               # and it is also a 'dict'
218
                    if CA in data[FILTERING]:                                       # containing 'CA'
219
                        if isinstance(data[FILTERING][CA], bool):                   # which is a 'bool',
220
                            if data[FILTERING][CA]:                                 # then filter according to 'CA'.
221
                                targets.remove(CERTIFICATE_ID)
222
                            else:
223
                                targets.remove(ROOT_CA_ID)
224
                                targets.remove(INTERMEDIATE_CA_ID)
225
                        else:
226
                            return E_WRONG_PARAMETERS, C_BAD_REQUEST
227
                else:
228
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST
229

    
230
        if len(targets) == TREE_NODE_TYPE_COUNT:                                    # = 3 -> root node,
231
                                                                                    # intermediate node,
232
                                                                                    # or leaf node
233

    
234
                                                                                    # if filtering did not change the
235
                                                                                    # targets,
236
            certs = self.certificate_service.get_certificates()                          # fetch everything
237
        else:                                                                       # otherwise fetch targets only
238
            certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
239

    
240
        if certs is None:
241
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
242
        elif len(certs) == 0:
243
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
244
        else:
245
            ret = []
246
            for c in certs:
247
                data = self.cert_to_dict_partial(c)
248
                if data is None:
249
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
250
                ret.append(
251
                    data
252
                )
253
            return {"success": True, "data": ret}, C_SUCCESS
254

    
255
    def get_certificate_root_by_id(self, id):
256
        """get certificate's root of trust chain by ID
257

    
258
        Get certificate's root of trust chain in PEM format by ID
259

    
260
        :param id: ID of a child certificate whose root is to be queried
261
        :type id: dict | bytes
262

    
263
        :rtype: PemResponse
264
        """
265
        try:
266
            v = int(id)
267
        except ValueError:
268
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
269

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

    
272
        if cert is None:
273
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
274

    
275
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
276
        if trust_chain is None or len(trust_chain) == 0:
277
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
278

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

    
281
    def get_certificate_trust_chain_by_id(self, id):
282
        """get certificate's trust chain by ID
283

    
284
        Get certificate trust chain in PEM format by ID
285

    
286
        :param id: ID of a child certificate whose chain is to be queried
287
        :type id: dict | bytes
288

    
289
        :rtype: PemResponse
290
        """
291

    
292
        try:
293
            v = int(id)
294
        except ValueError:
295
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
296

    
297
        cert = self.certificate_service.get_certificate(v)
298

    
299
        if cert is None:
300
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
301

    
302
        if cert.parent_id is None:
303
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
304

    
305
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id)
306

    
307
        ret = []
308
        for intermediate in trust_chain:
309
            ret.append(intermediate.pem_data)
310

    
311
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
312

    
313
    def set_certificate_status(self, id):
314
        """
315
        Revoke a certificate given by ID
316
            - revocation request may contain revocation reason
317
            - revocation reason is verified based on the possible predefined values
318
            - if revocation reason is not specified 'undefined' value is used
319
        :param id: Identifier of the certificate to be revoked
320
        :type id: int
321

    
322
        :rtype: SuccessResponse | ErrorResponse (see OpenAPI definition)
323
        """
324
        required_keys = {STATUS}  # required keys
325

    
326
        # try to parse certificate identifier -> if it is not int return error 400
327
        try:
328
            identifier = int(id)
329
        except ValueError:
330
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
331

    
332
        # check if the request contains a JSON body
333
        if request.is_json:
334
            request_body = request.get_json()
335
            # verify that all required keys are present
336
            if not all(k in request_body for k in required_keys):
337
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
338

    
339
            # get status and reason from the request
340
            status = request_body[STATUS]
341
            reason = request_body.get(REASON, REASON_UNDEFINED)
342
            try:
343
                # set certificate status using certificate_service
344
                self.certificate_service.set_certificate_revocation_status(identifier, status, reason)
345
            except (RevocationReasonInvalidException, CertificateStatusInvalidException):
346
                # these exceptions are thrown in case invalid status or revocation reason is passed to the controller
347
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
348
            except CertificateAlreadyRevokedException:
349
                return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST
350
            except CertificateNotFoundException:
351
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
352
            return {"success": True,
353
                    "data": "Certificate status updated successfully."}, C_SUCCESS
354
        # throw an error in case the request does not contain a json body
355
        else:
356
            return E_NOT_JSON_FORMAT, C_BAD_REQUEST
357

    
358
    def cert_to_dict_partial(self, c):
359
        """
360
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
361
        :param c: target cert
362
        :return: certificate dict (compliant with some parts of the REST API)
363
        """
364
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
365
        if c_issuer is None:
366
            return None
367

    
368
        return {
369
            ID: c.certificate_id,
370
            COMMON_NAME: c.common_name,
371
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
372
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
373
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
374
            ISSUER: {
375
                ID: c_issuer.certificate_id,
376
                COMMON_NAME: c_issuer.common_name
377
            }
378
        }
379

    
380
    def cert_to_dict_full(self, c):
381
        """
382
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
383
        Contains full information.
384
        :param c: target cert
385
        :return: certificate dict (compliant with some parts of the REST API)
386
        """
387
        subj = self.certificate_service.get_subject_from_certificate(c)
388
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
389
        if c_issuer is None:
390
            return None
391

    
392
        return {
393
            SUBJECT: subj.to_dict(),
394
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
395
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
396
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
397
            CA: c_issuer.certificate_id
398
        }
399

    
400
    def get_private_key_of_a_certificate(self, id):
401
        """
402
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
403

    
404
        :param id: ID of a certificate whose private key is to be queried
405
        :type id: dict | bytes
406

    
407
        :rtype: PemResponse
408
        """
409

    
410
        # try to parse the supplied ID
411
        try:
412
            v = int(id)
413
        except ValueError:
414
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
415

    
416
        # find a certificate using the given ID
417
        cert = self.certificate_service.get_certificate(v)
418

    
419
        if cert is None:
420
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
421
        else:
422
            # certificate exists, fetch it's private key
423
            private_key = self.key_service.get_key(cert.private_key_id)
424
            if cert is None:
425
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
426
            else:
427
                return {"success": True, "data": private_key.private_key}, C_SUCCESS
428

    
429
    def get_public_key_of_a_certificate(self, id):
430
        """
431
        Get a public key of a certificate in PEM format specified by certificate's ID
432

    
433
        :param id: ID of a certificate whose public key is to be queried
434
        :type id: dict | bytes
435

    
436
        :rtype: PemResponse
437
        """
438

    
439
        # try to parse the supplied ID
440
        try:
441
            v = int(id)
442
        except ValueError:
443
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
444

    
445
        # find a certificate using the given ID
446
        cert = self.certificate_service.get_certificate(v)
447

    
448
        if cert is None:
449
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
450
        else:
451
            return {"success": True, "data": self.certificate_service.get_public_key_from_certificate(cert)}, C_SUCCESS
452

    
453
    def delete_certificate(self, id):
454
        """
455
        Deletes a certificate identified by ID, including its corresponding subtree (all descendants).
456
        :param id: target certificate ID
457
        :rtype: DeleteResponse
458
        """
459
        try:
460
            v = int(id)
461
        except ValueError:
462
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
463

    
464
        try:
465
            self.certificate_service.delete_certificate(v)
466
        except CertificateNotFoundException:
467
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
468
        except DatabaseException:
469
            return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
470
        except CertificateStatusInvalidException or RevocationReasonInvalidException or UnknownException:
471
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
472

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