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.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
ISSUED_BY = "issuedby"
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
        issuer_id = -1
206

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

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

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

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

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

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

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

    
269
        Get certificate's root of trust chain in PEM format by ID
270

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

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

    
281
        cert = self.certificate_service.get_certificate(v)
282

    
283
        if cert is None:
284
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
285

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

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

    
292
    def get_certificate_trust_chain_by_id(self, id):
293
        """get certificate's trust chain by ID
294

    
295
        Get certificate trust chain in PEM format by ID
296

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

    
300
        :rtype: PemResponse
301
        """
302

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

    
308
        cert = self.certificate_service.get_certificate(v)
309

    
310
        if cert is None:
311
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
312

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

    
316
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id)
317

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

    
322
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
323

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

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

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

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

    
350
            # get status and reason from the request
351
            status = request_body[STATUS]
352
            reason = request_body.get(REASON, REASON_UNDEFINED)
353
            try:
354
                # set certificate status using certificate_service
355
                self.certificate_service.set_certificate_revocation_status(identifier, status, reason)
356
            except (RevocationReasonInvalidException, CertificateStatusInvalidException):
357
                # these exceptions are thrown in case invalid status or revocation reason is passed to the controller
358
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
359
            except CertificateAlreadyRevokedException:
360
                return E_NO_CERTIFICATE_ALREADY_REVOKED, C_BAD_REQUEST
361
            except CertificateNotFoundException:
362
                return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
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
(2-2/2)