Projekt

Obecné

Profil

Stáhnout (19.2 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.model.subject import Subject
14
from src.services.certificate_service import CertificateService, RevocationReasonInvalidException, \
15
    CertificateStatusInvalidException, CertificateNotFoundException, CertificateAlreadyRevokedException
16
#  responsibility.
17
from src.services.key_service import KeyService
18

    
19
TREE_NODE_TYPE_COUNT = 3
20

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

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

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

    
54

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

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

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

    
67
        Create a new certificate based on given information
68

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

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

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

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

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

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

    
89
            usages_dict = {}
90

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

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

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

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

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

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

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

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

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

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

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

    
149
        Get certificate in PEM format by ID
150

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

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

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

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

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

    
171
        Get certificate details by ID
172

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

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

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

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

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

    
196
        Lists certificates based on provided filtering options
197

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
283
        Get certificate trust chain in PEM format by ID
284

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

    
288
        :rtype: PemResponse
289
        """
290

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
406
        :rtype: PemResponse
407
        """
408

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

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

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

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

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

    
435
        :rtype: PemResponse
436
        """
437

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

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

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