Projekt

Obecné

Profil

Stáhnout (16.1 KB) Statistiky
| Větev: | Tag: | Revize:
1
from datetime import datetime
2
from itertools import chain
3
from flask import request
4
from src.dao.private_key_repository import PrivateKeyRepository
5
from src.model.subject import Subject
6
from src.services.certificate_service import CertificateService
7
from src.dao.certificate_repository import CertificateRepository        # TODO not the Controller's responsibility.
8
from src.services.cryptography import CryptographyService               # TODO not the Controller's responsibility.
9
from sqlite3 import Connection                                          # TODO not the Controller's responsibility.
10
from src.constants import CA_ID, \
11
    DATABASE_FILE_LOCATION, SSL_ID, SIGNATURE_ID, AUTHENTICATION_ID, \
12
    DATETIME_FORMAT, ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID     # TODO DATABASE_FILE - not the Controller's
13
                                                                        #  responsibility.
14
from src.services.key_service import KeyService
15

    
16
TREE_NODE_TYPE_COUNT = 3
17

    
18
FILTERING = "filtering"
19
ISSUER = "issuer"
20
US = "usage"
21
NOT_AFTER = "notAfter"
22
NOT_BEFORE = "notBefore"
23
COMMON_NAME = "CN"
24
ID = "id"
25
USAGE = "usage"
26
SUBJECT = "subject"
27
VALIDITY_DAYS = "validityDays"
28
CA = "CA"
29

    
30
E_NO_ISSUER_FOUND = {"success": False, "data": "No certificate authority with such unique ID exists."}
31
E_NO_CERTIFICATES_FOUND = {"success": False, "data": "No such certificate found."}
32
E_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."}
33
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."}
34
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."}
35
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."}
36
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."}
37

    
38
C_CREATED_SUCCESSFULLY = 201
39
C_BAD_REQUEST = 400
40
C_NO_DATA = 205                                                         # TODO related to 204 issue
41
C_INTERNAL_SERVER_ERROR = 500
42
C_SUCCESS = 200
43

    
44
__ = CryptographyService()                                              # TODO not the Controller's responsibility.
45
CERTIFICATE_SERVICE = CertificateService(__, CertificateRepository(None, None))
46
KEY_SERVICE = KeyService(__, PrivateKeyRepository(None, None))          # TODO not the Controller's responsibility.
47

    
48

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

    
53
    @staticmethod
54
    def setup():
55
        """
56
        SQLite3 thread issue hack.
57
        :return:
58
        """
59
        _ = Connection(DATABASE_FILE_LOCATION.shortest_relative_path())
60
        CERTIFICATE_SERVICE.certificate_repository.connection = _
61
        CERTIFICATE_SERVICE.certificate_repository.cursor = _.cursor()
62
        KEY_SERVICE.private_key_repository.connection = _
63
        KEY_SERVICE.private_key_repository.cursor = _.cursor()
64

    
65
    @staticmethod
66
    def create_certificate():
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
        CertController.setup()                                                      # TODO remove after issue fixed
77

    
78
        required_keys = {SUBJECT, USAGE, VALIDITY_DAYS}                             # required fields of the POST req
79

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

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

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

    
90
            if subject is None:                                                     # if the format is incorrect
91
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
92

    
93
            usages_dict = {}
94

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

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

    
103
            key = KEY_SERVICE.create_new_key()                                      # TODO pass key
104

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

    
115
                if issuer is None:                                                  # if such issuer does not exist
116
                    KEY_SERVICE.delete_key(key.private_key_id)                      # free
117
                    return E_NO_ISSUER_FOUND, C_BAD_REQUEST                         # and throw
118

    
119
                issuer_key = KEY_SERVICE.get_key(issuer.private_key_id)             # get issuer's key, which must exist
120

    
121
                if issuer_key is None:                                              # if it does not
122
                    KEY_SERVICE.delete_key(key.private_key_id)                      # free
123
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR            # and throw
124

    
125
                f = CERTIFICATE_SERVICE.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
126
                    CERTIFICATE_SERVICE.create_end_cert
127

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

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

    
150
    @staticmethod
151
    def get_certificate_by_id(id):
152
        """get certificate by ID
153

    
154
        Get certificate in PEM format by ID
155

    
156
        :param id: ID of a certificate to be queried
157
        :type id: dict | bytes
158

    
159
        :rtype: PemResponse
160
        """
161
        CertController.setup()                                                      # TODO remove after issue fixed
162

    
163
        try:
164
            v = int(id)
165
        except ValueError:
166
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
167

    
168
        cert = CERTIFICATE_SERVICE.get_certificate(v)
169

    
170
        if cert is None:
171
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA                               
172
        else:
173
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
174

    
175
    @staticmethod
176
    def get_certificate_details_by_id(id):
177
        """get certificate's details by ID
178

    
179
        Get certificate details by ID
180

    
181
        :param id: ID of a certificate whose details are to be queried
182
        :type id: dict | bytes
183

    
184
        :rtype: CertificateResponse
185
        """
186
        CertController.setup()                                                      # TODO remove after issue fixed
187

    
188
        try:
189
            v = int(id)
190
        except ValueError:
191
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
192

    
193
        cert = CERTIFICATE_SERVICE.get_certificate(v)
194

    
195
        if cert is None:
196
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA                               
197
        else:
198
            data = CertController.cert_to_dict_full(cert)
199
            if data is None:
200
                return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
201
            return {"success": True, "data": data}, C_SUCCESS
202

    
203
    @staticmethod
204
    def get_certificate_list():
205
        """get list of certificates
206

    
207
        Lists certificates based on provided filtering options
208

    
209
        :param filtering: Filter certificate type to be queried
210
        :type filtering: dict | bytes
211

    
212
        :rtype: CertificateListResponse
213
        """
214
        CertController.setup()                                                      # TODO remove after issue fixed
215

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

    
233
        if len(targets) == TREE_NODE_TYPE_COUNT:                                    # = 3 -> root node,
234
                                                                                    # intermediate node,
235
                                                                                    # or leaf node
236

    
237
                                                                                    # if filtering did not change the
238
                                                                                    # targets,
239
            certs = CERTIFICATE_SERVICE.get_certificates()                          # fetch everything
240
        else:                                                                       # otherwise fetch targets only
241
            certs = list(chain(*(CERTIFICATE_SERVICE.get_certificates(target) for target in targets)))
242

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

    
258
    @staticmethod
259
    def get_certificate_root_by_id(id):
260
        """get certificate's root of trust chain by ID
261

    
262
        Get certificate's root of trust chain in PEM format by ID
263

    
264
        :param id: ID of a child certificate whose root is to be queried
265
        :type id: dict | bytes
266

    
267
        :rtype: PemResponse
268
        """
269
        CertController.setup()                                                      # TODO remove after issue fixed
270

    
271
        try:
272
            v = int(id)
273
        except ValueError:
274
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
275

    
276
        cert = CERTIFICATE_SERVICE.get_certificate(v)
277

    
278
        if cert is None:
279
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
280

    
281
        trust_chain = CERTIFICATE_SERVICE.get_chain_of_trust(cert.parent_id, exclude_root=False)
282
        if trust_chain is None or len(trust_chain) is 0:
283
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
284

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

    
287
    @staticmethod
288
    def get_certificate_trust_chain_by_id(id):
289
        """get certificate's trust chain by ID
290

    
291
        Get certificate trust chain in PEM format by ID
292

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

    
296
        :rtype: PemResponse
297
        """
298
        CertController.setup()                                                      # TODO remove after issue fixed
299

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

    
305
        cert = CERTIFICATE_SERVICE.get_certificate(v)
306

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

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

    
313
        trust_chain = CERTIFICATE_SERVICE.get_chain_of_trust(cert.parent_id)
314

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

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

    
321
    @staticmethod
322
    def cert_to_dict_partial(c):
323
        """
324
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
325
        :param c: target cert
326
        :return: certificate dict (compliant with some parts of the REST API)
327
        """
328
        c_issuer = CERTIFICATE_SERVICE.get_certificate(c.parent_id)
329
        if c_issuer is None:
330
            return None
331

    
332
        return {
333
            ID: c.certificate_id,
334
            COMMON_NAME: c.common_name,
335
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
336
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
337
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
338
            ISSUER: {
339
                ID: c_issuer.certificate_id,
340
                COMMON_NAME: c_issuer.common_name
341
            }
342
        }
343

    
344
    @staticmethod
345
    def cert_to_dict_full(c):
346
        """
347
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
348
        Contains full information.
349
        :param c: target cert
350
        :return: certificate dict (compliant with some parts of the REST API)
351
        """
352
        subj = CERTIFICATE_SERVICE.get_subject_from_certificate(c)
353
        c_issuer = CERTIFICATE_SERVICE.get_certificate(c.parent_id)
354
        if c_issuer is None:
355
            return None
356

    
357
        return {
358
            SUBJECT: subj.to_dict(),
359
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
360
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
361
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
362
            CA: c_issuer.certificate_id
363
        }
(2-2/2)