Projekt

Obecné

Profil

Stáhnout (14.8 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_NOT_JSON_FORMAT = {"success": False, "data": "The request must be JSON-formatted."}
34
E_CORRUPTED_DATABASE = {"success": False, "data": "Internal server error (corrupted database)."}
35
E_GENERAL_ERROR = {"success": False, "data": "Internal server error (unknown origin)."}
36
E_MISSING_PARAMETERS = {"success": False, "data": "Invalid request, missing parameters."}
37
E_WRONG_PARAMETERS = {"success": False, "data": "Invalid request, wrong parameters."}
38

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

    
45

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

    
50
    @inject
51
    def __init__(self, certificate_service: CertificateService, key_service: KeyService):
52
        self.certificate_service = certificate_service
53
        self.key_service = key_service
54

    
55
    def create_certificate(self):
56
        """create new certificate
57

    
58
        Create a new certificate based on given information
59

    
60
        :param body: Certificate data to be created
61
        :type body: dict | bytes
62

    
63
        :rtype: CreatedResponse
64
        """
65
        required_keys = {SUBJECT, USAGE, VALIDITY_DAYS}                             # required fields of the POST req
66

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

    
72
            if not isinstance(body[VALIDITY_DAYS], int):                            # type checking
73
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
74

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

    
77
            if subject is None:                                                     # if the format is incorrect
78
                return E_WRONG_PARAMETERS, C_BAD_REQUEST
79

    
80
            usages_dict = {}
81

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

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

    
90
            key = self.key_service.create_new_key()                                      # TODO pass key
91

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

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

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

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

    
112
                f = self.certificate_service.create_ca if CA_ID in usages_dict and usages_dict[CA_ID] else \
113
                    self.certificate_service.create_end_cert
114

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

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

    
137
    def get_certificate_by_id(self, id):
138
        """get certificate by ID
139

    
140
        Get certificate in PEM format by ID
141

    
142
        :param id: ID of a certificate to be queried
143
        :type id: dict | bytes
144

    
145
        :rtype: PemResponse
146
        """
147
        try:
148
            v = int(id)
149
        except ValueError:
150
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
151

    
152
        cert = self.certificate_service.get_certificate(v)
153

    
154
        if cert is None:
155
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA                               
156
        else:
157
            return {"success": True, "data": cert.pem_data}, C_SUCCESS
158

    
159
    def get_certificate_details_by_id(self, id):
160
        """get certificate's details by ID
161

    
162
        Get certificate details by ID
163

    
164
        :param id: ID of a certificate whose details are to be queried
165
        :type id: dict | bytes
166

    
167
        :rtype: CertificateResponse
168
        """
169
        try:
170
            v = int(id)
171
        except ValueError:
172
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
173

    
174
        cert = self.certificate_service.get_certificate(v)
175

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

    
184
    def get_certificate_list(self):
185
        """get list of certificates
186

    
187
        Lists certificates based on provided filtering options
188

    
189
        :param filtering: Filter certificate type to be queried
190
        :type filtering: dict | bytes
191

    
192
        :rtype: CertificateListResponse
193
        """
194
        targets = {ROOT_CA_ID, INTERMEDIATE_CA_ID, CERTIFICATE_ID}                  # all targets
195

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

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

    
220
        if len(targets) == TREE_NODE_TYPE_COUNT:                                    # = 3 -> root node,
221
                                                                                    # intermediate node,
222
                                                                                    # or leaf node
223

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

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

    
245
    def get_certificate_root_by_id(self, id):
246
        """get certificate's root of trust chain by ID
247

    
248
        Get certificate's root of trust chain in PEM format by ID
249

    
250
        :param id: ID of a child certificate whose root is to be queried
251
        :type id: dict | bytes
252

    
253
        :rtype: PemResponse
254
        """
255
        try:
256
            v = int(id)
257
        except ValueError:
258
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
259

    
260
        cert = self.certificate_service.get_certificate(v)
261

    
262
        if cert is None:
263
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA
264

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

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

    
271
    def get_certificate_trust_chain_by_id(self, id):
272
        """get certificate's trust chain by ID
273

    
274
        Get certificate trust chain in PEM format by ID
275

    
276
        :param id: ID of a child certificate whose chain is to be queried
277
        :type id: dict | bytes
278

    
279
        :rtype: PemResponse
280
        """
281

    
282
        try:
283
            v = int(id)
284
        except ValueError:
285
            return E_WRONG_PARAMETERS, C_BAD_REQUEST
286

    
287
        cert = self.certificate_service.get_certificate(v)
288

    
289
        if cert is None:
290
            return E_NO_CERTIFICATES_FOUND, C_NO_DATA                               
291

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

    
295
        trust_chain = self.certificate_service.get_chain_of_trust(cert.parent_id)
296

    
297
        ret = []
298
        for intermediate in trust_chain:
299
            ret.append(intermediate.pem_data)
300

    
301
        return {"success": True, "data": "".join(ret)}, C_SUCCESS
302

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

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

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

    
337
        return {
338
            SUBJECT: subj.to_dict(),
339
            NOT_BEFORE: datetime.strptime(c.valid_from, DATETIME_FORMAT).date(),
340
            NOT_AFTER: datetime.strptime(c.valid_to, DATETIME_FORMAT).date(),
341
            USAGE: {CertController.INVERSE_KEY_MAP[k]: v for k, v in c.usages.items()},
342
            CA: c_issuer.certificate_id
343
        }
(2-2/2)