Projekt

Obecné

Profil

Stáhnout (16.1 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.model.subject import Subject
13
from src.services.certificate_service import CertificateService
14
#  responsibility.
15
from src.services.key_service import KeyService
16

    
17
TREE_NODE_TYPE_COUNT = 3
18

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

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

    
41
C_CREATED_SUCCESSFULLY = 201
42
C_BAD_REQUEST = 400
43
C_NOT_FOUND = 404
44
C_NO_DATA = 205  # TODO related to 204 issue
45
C_INTERNAL_SERVER_ERROR = 500
46
C_SUCCESS = 200
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
    @inject
54
    def __init__(self, certificate_service: CertificateService, key_service: KeyService):
55
        self.certificate_service = certificate_service
56
        self.key_service = key_service
57

    
58
    def create_certificate(self):
59
        """create new certificate
60

    
61
        Create a new certificate based on given information
62

    
63
        :param body: Certificate data to be created
64
        :type body: dict | bytes
65

    
66
        :rtype: CreatedResponse
67
        """
68
        required_keys = {SUBJECT, USAGE, VALIDITY_DAYS}                             # required fields of the POST req
69

    
70
        if request.is_json:                                                         # accept JSON only
71
            body = request.get_json()
72
            if not all(k in body for k in required_keys):                           # verify that all keys are present
73
                return E_MISSING_PARAMETERS, C_BAD_REQUEST
74

    
75
            if not isinstance(body[VALIDITY_DAYS], int):                            # type checking
76
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
77

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

    
80
            if subject is None:                                                     # if the format is incorrect
81
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
82

    
83
            usages_dict = {}
84

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

    
88
            for k, v in body[USAGE].items():                                        # for each usage
89
                if k not in CertController.KEY_MAP:                                 # check that it is a valid usage
90
                    return E_WRONG_PARAMETERS, C_BAD_REQUEST                        # and throw if it is not
91
                usages_dict[CertController.KEY_MAP[k]] = v                          # otherwise translate key and set
92

    
93
            key = self.key_service.create_new_key()                                      # TODO pass key
94

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

    
105
                if issuer is None:                                                  # if such issuer does not exist
106
                    self.key_service.delete_key(key.private_key_id)                      # free
107
                    return E_NO_ISSUER_FOUND, C_BAD_REQUEST                         # and throw
108

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

    
111
                if issuer_key is None:                                              # if it does not
112
                    self.key_service.delete_key(key.private_key_id)                      # free
113
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR            # and throw
114

    
115
                f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
116
                    self.certificate_service.create_end_cert
117

    
118
                # noinspection PyTypeChecker
119
                cert = f(                                                           # create inter CA or end cert
120
                    key,                                                            # according to whether 'CA' is among
121
                    subject,                                                        # the usages' fields
122
                    issuer,
123
                    issuer_key,
124
                    usages=usages_dict,
125
                    days=body[VALIDITY_DAYS]
126
                )
127

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

    
140
    def get_certificate_by_id(self, id):
141
        """get certificate by ID
142

    
143
        Get certificate in PEM format by ID
144

    
145
        :param id: ID of a certificate to be queried
146
        :type id: dict | bytes
147

    
148
        :rtype: PemResponse
149
        """
150
        try:
151
            v = int(id)
152
        except ValueError:
153
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
154

    
155
        cert = self.certificate_service.get_certificate(v)
156

    
157
        if cert is None:
158
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA                               
159
        else:
160
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
161

    
162
    def get_certificate_details_by_id(self, id):
163
        """get certificate's details by ID
164

    
165
        Get certificate details by ID
166

    
167
        :param id: ID of a certificate whose details are to be queried
168
        :type id: dict | bytes
169

    
170
        :rtype: CertificateResponse
171
        """
172
        try:
173
            v = int(id)
174
        except ValueError:
175
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
176

    
177
        cert = self.certificate_service.get_certificate(v)
178

    
179
        if cert is None:
180
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA                               
181
        else:
182
            data = self.cert_to_dict_full(cert)
183
            if data is None:
184
                return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
185
            return {"success": True, "data": data}, C_SUCCESS
186

    
187
    def get_certificate_list(self):
188
        """get list of certificates
189

    
190
        Lists certificates based on provided filtering options
191

    
192
        :param filtering: Filter certificate type to be queried
193
        :type filtering: dict | bytes
194

    
195
        :rtype: CertificateListResponse
196
        """
197
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
198

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

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

    
223
        if len(targets) == TREE_NODE_TYPE_COUNT:                                    # = 3 -> root node,
224
                                                                                    # intermediate node,
225
                                                                                    # or leaf node
226

    
227
                                                                                    # if filtering did not change the
228
                                                                                    # targets,
229
            certs = self.certificate_service.get_certificates()                          # fetch everything
230
        else:                                                                       # otherwise fetch targets only
231
            certs = list(chain(*(self.certificate_service.get_certificates(target) for target in targets)))
232

    
233
        if certs is None:
234
            return E_GENERAL_ERROR, C_INTERNAL_SERVER_ERROR
235
        elif len(certs) == 0:
236
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA                               
237
        else:
238
            ret = []
239
            for c in certs:
240
                data = self.cert_to_dict_partial(c)
241
                if data is None:
242
                    return E_CORRUPTED_DATABASE, C_INTERNAL_SERVER_ERROR
243
                ret.append(
244
                    data
245
                )
246
            return {"success": True, "data": ret}, C_SUCCESS
247

    
248
    def get_certificate_root_by_id(self, id):
249
        """get certificate's root of trust chain by ID
250

    
251
        Get certificate's root of trust chain in PEM format by ID
252

    
253
        :param id: ID of a child certificate whose root is to be queried
254
        :type id: dict | bytes
255

    
256
        :rtype: PemResponse
257
        """
258
        try:
259
            v = int(id)
260
        except ValueError:
261
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
262

    
263
        cert = self.certificate_service.get_certificate(v)
264

    
265
        if cert is None:
266
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
267

    
268
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id, exclude_root=False)
269
        if trust_chain is None or len(trust_chain) == 0:
270
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
271

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

    
274
    def get_certificate_trust_chain_by_id(self, id):
275
        """get certificate's trust chain by ID
276

    
277
        Get certificate trust chain in PEM format by ID
278

    
279
        :param id: ID of a child certificate whose chain is to be queried
280
        :type id: dict | bytes
281

    
282
        :rtype: PemResponse
283
        """
284

    
285
        try:
286
            v = int(id)
287
        except ValueError:
288
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
289

    
290
        cert = self.certificate_service.get_certificate(v)
291

    
292
        if cert is None:
293
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA                               
294

    
295
        if cert.parent_id is None:
296
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
297

    
298
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id)
299

    
300
        ret = []
301
        for intermediate in trust_chain:
302
            ret.append(intermediate.pem_data)
303

    
304
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
305

    
306
    def cert_to_dict_partial(self, c):
307
        """
308
        Dictionarizes a certificate directly fetched from the database. Contains partial information.
309
        :param c: target cert
310
        :return: certificate dict (compliant with some parts of the REST API)
311
        """
312
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
313
        if c_issuer is None:
314
            return None
315

    
316
        return {
317
            ID: c.certificate_id,
318
            COMMON_NAME: c.common_name,
319
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
320
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
321
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
322
            ISSUER: {
323
                ID: c_issuer.certificate_id,
324
                COMMON_NAME: c_issuer.common_name
325
            }
326
        }
327

    
328
    def cert_to_dict_full(self, c):
329
        """
330
        Dictionarizes a certificate directly fetched from the database, but adds subject info.
331
        Contains full information.
332
        :param c: target cert
333
        :return: certificate dict (compliant with some parts of the REST API)
334
        """
335
        subj = self.certificate_service.get_subject_from_certificate(c)
336
        c_issuer = self.certificate_service.get_certificate(c.parent_id)
337
        if c_issuer is None:
338
            return None
339

    
340
        return {
341
            SUBJECT: subj.to_dict(),
342
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
343
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
344
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
345
            CA: c_issuer.certificate_id
346
        }
347

    
348
    def get_public_key_of_a_certificate(self, id):
349
        """
350
        Get a private key used to sign a certificate in PEM format specified by certificate's ID
351

    
352
        :param id: ID of a certificate whose public key is to be queried
353
        :type id: dict | bytes
354

    
355
        :rtype: PemResponse
356
        """
357

    
358
        # try to parse the supplied ID
359
        try:
360
            v = int(id)
361
        except ValueError:
362
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
363

    
364
        # find a certificate with using the given ID
365
        cert = self.certificate_service.get_certificate(v)
366

    
367
        if cert is None:
368
            return E_NO_CERTIFICATES_FOUND, C_NOT_FOUND
369
        else:
370
            # certificate exists, fetch it's private key
371
            private_key = self.key_service.get_key(cert.private_key_id)
372
            if cert is None:
373
                return E_NO_CERT_PRIVATE_KEY_FOUND, C_INTERNAL_SERVER_ERROR
374
            else:
375
                # TODO public key can be extracted from a certificate
376
                # private key fetched, extract a public key from it
377
                public_key = self.key_service.get_public_key(private_key)
378
                return {"success": True, "data": public_key}, C_SUCCESS
(2-2/2)