Projekt

Obecné

Profil

Stáhnout (16.2 KB) Statistiky
| Větev: | Tag: | Revize:
1
from typing import List
2

    
3
from injector import inject
4

    
5
from src.config.configuration import Configuration
6
from src.constants import ROOT_CA_ID, INTERMEDIATE_CA_ID, CA_ID, CERTIFICATE_ID, CERTIFICATE_STATES, \
7
    CERTIFICATE_REVOCATION_REASONS
8
from src.dao.certificate_repository import CertificateRepository
9
from src.model.certificate import Certificate
10
from src.model.private_key import PrivateKey
11
from src.model.subject import Subject
12
from src.services.cryptography import CryptographyService
13

    
14
import time
15

    
16
DATE_FORMAT = "%d.%m.%Y %H:%M:%S"
17
CA_EXTENSIONS = "basicConstraints=critical,CA:TRUE"
18
CRL_EXTENSION = "crlDistributionPoints=URI:"
19
OCSP_EXTENSION = "authorityInfoAccess=OCSP;URI:"
20
STATUS_REVOKED = "revoked"
21
STATUS_VALID = "valid"
22

    
23

    
24
class CertificateService:
25

    
26
    @inject
27
    def __init__(self, cryptography_service: CryptographyService,
28
                 certificate_repository: CertificateRepository,
29
                 configuration: Configuration):
30
        self.cryptography_service = cryptography_service
31
        self.certificate_repository = certificate_repository
32
        self.configuration = configuration
33

    
34
    # TODO usages present in method parameters but not in class diagram
35
    def create_root_ca(self, key: PrivateKey, subject: Subject, extensions: str = "", config: str = "",
36
                       usages=None, days=30):
37
        """
38
        Creates a root CA certificate based on the given parameters.
39
        :param key: Private key to be used when generating the certificate
40
        :param subject: Subject to be used put into the certificate
41
        :param config: String containing the configuration to be used
42
        :param extensions: Name of the section in the configuration representing extensions
43
        :param usages: A dictionary containing usages of the certificate to be generated (see constants.py)
44
        :param days: Number of days for which the generated cert. will be considered valid
45
        :return: An instance of Certificate class representing the generated root CA cert
46
        """
47
        if usages is None:
48
            usages = {}
49

    
50
        cert_id = self.certificate_repository.get_next_id()
51
        extensions = extensions + "\n" + CRL_EXTENSION + " " + self.__get_crl_endpoint(cert_id)
52
        extensions = extensions + "\n" + OCSP_EXTENSION + " " + self.__get_ocsp_endpoint(cert_id)
53

    
54
        # create a new self signed  certificate
55
        cert_pem = self.cryptography_service.create_sscrt(subject, key.private_key, key_pass=key.password,
56
                                                          extensions=extensions, config=config, days=days)
57
        # specify CA usage
58
        usages[CA_ID] = True
59

    
60
        # wrap into Certificate class
61
        certificate = self.__create_wrapper(cert_pem, key.private_key_id, usages, 0,
62
                                            ROOT_CA_ID)
63

    
64
        # store the wrapper into the repository
65
        created_id = self.certificate_repository.create(certificate)
66

    
67
        # assign the generated ID to the inserted certificate
68
        certificate.certificate_id = created_id
69

    
70
        return certificate
71

    
72
    def __create_wrapper(self, cert_pem, private_key_id, usages, parent_id, cert_type):
73
        """
74
        Wraps the given parameters using the Certificate class. Uses CryptographyService to find out the notBefore and
75
        notAfter fields.
76
        :param cert_pem: PEM of the cert. to be wrapped
77
        :param private_key_id: ID of the private key used to create the given certificate
78
        :param usages: A dictionary containing usages of the generated certificate generated (see constants.py)
79
        :param parent_id: ID of the CA that issued this certificate
80
        :param cert_type: Type of this certificate (see constants.py)
81
        :return: An instance of the Certificate class wrapping the values passed  via method parameters
82
        """
83
        # parse the generated pem for subject and notBefore/notAfter fields
84
        # TODO this could be improved in the future in such way that calling openssl is not required to parse the dates
85
        subj, not_before, not_after = self.cryptography_service.parse_cert_pem(cert_pem)
86
        # format the parsed date
87
        not_before_formatted = time.strftime(DATE_FORMAT, not_before)
88
        not_after_formatted = time.strftime(DATE_FORMAT, not_after)
89

    
90
        # create a certificate wrapper
91
        certificate = Certificate(-1, subj.common_name, not_before_formatted, not_after_formatted, cert_pem,
92
                                  private_key_id, cert_type, parent_id, usages)
93

    
94
        return certificate
95

    
96
    # TODO config parameter present in class diagram but not here (unused)
97
    def create_ca(self, subject_key: PrivateKey, subject: Subject, issuer_cert: Certificate, issuer_key: PrivateKey,
98
                  extensions: str = "", days: int = 30, usages=None):
99
        """
100
        Creates an intermediate CA certificate issued by the given parent CA.
101
        :param subject_key: Private key to be used when generating the certificate
102
        :param subject: Subject to be used put into the certificate
103
        :param issuer_cert: Issuer certificate that will sign the CSR required to create an intermediate CA
104
        :param issuer_key: PK used to generate the issuer certificate
105
        :param extensions: Extensions to be used when generating the certificate
106
        :param usages: A dictionary containing usages of the certificate to be generated (see constants.py)
107
        :param days: Number of days for which the generated cert. will be considered valid
108
        :return: An instance of Certificate class representing the generated intermediate CA cert
109
        """
110
        if usages is None:
111
            usages = {}
112

    
113
        extensions = extensions + "\n" + CA_EXTENSIONS
114
        # Add CRL and OCSP distribution point to certificate extensions
115
        cert_id = self.certificate_repository.get_next_id()
116
        extensions = extensions + "\n" + CRL_EXTENSION + " " + self.__get_crl_endpoint(cert_id)
117
        extensions = extensions + "\n" + OCSP_EXTENSION + " " + self.__get_ocsp_endpoint(cert_id)
118

    
119
        # TODO implement AIA URI via extensions
120
        cert_pem = self.cryptography_service.create_crt(subject, subject_key.private_key, issuer_cert.pem_data,
121
                                                        issuer_key.private_key,
122
                                                        subject_key_pass=subject_key.password,
123
                                                        issuer_key_pass=issuer_key.password, extensions=extensions,
124
                                                        days=days)
125

    
126
        # specify CA usage
127
        usages[CA_ID] = True
128

    
129
        # wrap into Certificate class
130
        self.__create_wrapper(cert_pem, subject_key.private_key_id, usages,
131
                              issuer_cert.certificate_id, INTERMEDIATE_CA_ID)
132

    
133
        # parse the generated pem for subject and notBefore/notAfter fields
134
        subj, not_before, not_after = self.cryptography_service.parse_cert_pem(cert_pem)
135

    
136
        # format the parsed date
137
        not_before_formatted = time.strftime(DATE_FORMAT, not_before)
138
        not_after_formatted = time.strftime(DATE_FORMAT, not_after)
139

    
140
        # specify CA usage
141
        usages[CA_ID] = True
142

    
143
        # create a certificate wrapper
144
        certificate = Certificate(-1, subject.common_name, not_before_formatted, not_after_formatted, cert_pem,
145
                                  subject_key.private_key_id, INTERMEDIATE_CA_ID, issuer_cert.certificate_id, usages)
146

    
147
        # store the wrapper into the repository
148
        created_id = self.certificate_repository.create(certificate)
149

    
150
        # assign the generated ID to the inserted certificate
151
        certificate.certificate_id = created_id
152

    
153
        return certificate
154

    
155
    def create_end_cert(self, subject_key: PrivateKey, subject: Subject, issuer_cert: Certificate,
156
                        issuer_key: PrivateKey,
157
                        extensions: str = "", days: int = 30, usages=None):
158
        """
159
        Creates an end certificate issued by the given parent CA.
160
        :param subject_key: Private key to be used when generating the certificate
161
        :param subject: Subject to be used put into the certificate
162
        :param issuer_cert: Issuer certificate that will sign the CSR required to create an intermediate CA
163
        :param issuer_key: PK used to generate the issuer certificate
164
        :param extensions: Extensions to be used when generating the certificate
165
        :param usages: A dictionary containing usages of the certificate to be generated (see constants.py)
166
        :param days: Number of days for which the generated cert. will be considered valid
167
        :return: An instance of Certificate class representing the generated cert
168
        """
169
        if usages is None:
170
            usages = {}
171

    
172
        # generate a new certificate
173
        cert_pem = self.cryptography_service.create_crt(subject, subject_key.private_key, issuer_cert.pem_data,
174
                                                        issuer_key.private_key,
175
                                                        subject_key_pass=subject_key.password,
176
                                                        issuer_key_pass=issuer_key.password, extensions=extensions,
177
                                                        days=days)
178

    
179
        # wrap the generated certificate using Certificate class
180
        certificate = self.__create_wrapper(cert_pem, subject_key.private_key_id, usages,
181
                                            issuer_cert.certificate_id, CERTIFICATE_ID)
182

    
183
        created_id = self.certificate_repository.create(certificate)
184

    
185
        certificate.certificate_id = created_id
186

    
187
        return certificate
188

    
189
    def get_certificate(self, unique_id: int) -> Certificate:
190
        """
191
        Tries to fetch a certificate from the certificate repository using a given id.
192
        :param unique_id: ID of the certificate to be fetched
193
        :return: Instance of the Certificate class containing a certificate with the given id or `None` if such
194
        certificate is not found
195
        """
196
        return self.certificate_repository.read(unique_id)
197

    
198
    def get_certificates(self, cert_type=None) -> List[Certificate]:
199
        """
200
        Tries to fetch a list of all certificates from the certificate repository. Using the `cert_type` parameter only
201
        certificates of the given type can be returned.
202
        :param cert_type: Type of certificates to be returned
203
        :return: List of instances of the Certificate class representing all certificates present in the certificate
204
        repository. An empty list is returned when no certificates are found.
205
        """
206
        return self.certificate_repository.read_all(cert_type)
207

    
208
    def get_chain_of_trust(self, from_id: int, to_id: int = -1, exclude_root=True) -> List[Certificate]:
209
        """
210
        Traverses the certificate hierarchy tree upwards till a certificate with the `to_id` ID is found or till a
211
        root CA certificate is found. Root certificates are excluded from the chain by default.
212
        :param from_id: ID of the first certificate to be included in the chain of trust
213
        :param to_id: ID of the last certificate to be included in the chain of trust
214
        :param exclude_root: a flag indicating whether root CA certificate should be excluded
215
        :return: a list of certificates representing the chain of trust starting with the certificate given by `from_id`
216
        ID
217
        """
218
        # read the first certificate of the chain
219
        start_cert = self.certificate_repository.read(from_id)
220

    
221
        # if no cert is found or the current cert is root CA and root CAs should be excluded, then return an empty list
222
        if start_cert is None or (start_cert.type_id == ROOT_CA_ID and exclude_root):
223
            return []
224

    
225
        current_cert = start_cert
226
        chain_of_trust = [current_cert]
227

    
228
        # TODO could possibly be simplified
229
        if start_cert.type_id == ROOT_CA_ID:
230
            # the first cert found is a root ca
231
            return chain_of_trust
232

    
233
        while True:
234
            parent_cert = self.certificate_repository.read(current_cert.parent_id)
235

    
236
            # check whether parent certificate exists
237
            if parent_cert is None:
238
                break
239

    
240
            # check whether the found certificate is a root certificate
241
            if parent_cert.type_id == ROOT_CA_ID:
242
                if not exclude_root:
243
                    # append the found root cert only if root certificates should not be excluded from the CoT
244
                    chain_of_trust.append(parent_cert)
245
                break
246

    
247
            # append the certificate
248
            chain_of_trust.append(parent_cert)
249

    
250
            # stop iterating over certificates if the id of the found certificate matches `to_id` method parameter
251
            if parent_cert.certificate_id == to_id:
252
                break
253

    
254
            current_cert = parent_cert
255

    
256
        return chain_of_trust
257

    
258
    def delete_certificate(self, unique_id) -> bool:
259
        """
260
        Deletes a certificate
261

    
262
        :param unique_id: ID of specific certificate
263

    
264
        :return: `True` when the deletion was successful. `False` in other case
265
        """
266
        # TODO delete children?
267
        return self.certificate_repository.delete(unique_id)
268

    
269
    def set_certificate_revocation_status(self, id, status, reason="unspecified"):
270
        """
271
        Set certificate status to 'valid' or 'revoked'.
272
        If the new status is revoked a reason can be provided -> default is unspecified
273
        :param reason: reason for revocation
274
        :param id: identifier of the certificate whose status is to be changed
275
        :param status: new status of the certificate
276
        """
277
        if status not in CERTIFICATE_STATES:
278
            raise CertificateStatusInvalidException(status)
279
        if reason not in CERTIFICATE_REVOCATION_REASONS:
280
            raise RevocationReasonInvalidException(reason)
281

    
282
        if status == STATUS_VALID:
283
            self.certificate_repository.clear_certificate_revocation(id)
284
        elif status == STATUS_REVOKED:
285
            revocation_timestamp = int(time.time())
286
            self.certificate_repository.set_certificate_revoked(id, str(revocation_timestamp), reason)
287

    
288
    def get_subject_from_certificate(self, certificate: Certificate) -> Subject:
289
        """
290
        Get Subject distinguished name from a Certificate
291
        :param certificate: certificate instance whose Subject shall be parsed
292
        :return: instance of Subject class containing resulting distinguished name
293
        """
294
        (subject, _, _) = self.cryptography_service.parse_cert_pem(certificate.pem_data)
295
        return subject
296

    
297
    def get_public_key_from_certificate(self, certificate: Certificate):
298
        """
299
        Extracts a public key from the given certificate
300
        :param certificate: an instance of the Certificate class containing the certificate from which a public key
301
        should be extracted.
302
        :return: a string containing the extracted public key in PEM format
303
        """
304
        return self.cryptography_service.extract_public_key_from_certificate(certificate.pem_data)
305

    
306
    def __get_crl_endpoint(self, ca_identifier: int) -> str:
307
        """
308
        Get URL address of CRL distribution endpoint based on
309
        issuer's ID
310

    
311
        :param ca_identifier: ID of issuing authority
312
        :return: CRL endpoint for the given CA
313
        """
314
        return self.configuration.base_server_url + "/api/crl/" + str(ca_identifier)
315

    
316
    def __get_ocsp_endpoint(self, ca_identifier: int) -> str:
317
        """
318
        Get URL address of OCSP distribution endpoint based on
319
        issuer's ID
320

    
321
        :param ca_identifier: ID of issuing authority
322
        :return: OCSP endpoint for the given CA
323
        """
324
        return self.configuration.base_server_url + "/api/ocsp/" + str(ca_identifier)
325

    
326

    
327
class RevocationReasonInvalidException(Exception):
328
    """
329
    Exception that denotes that the caller was trying to revoke
330
    a certificate using an invalid revocation reason
331
    """
332

    
333
    def __init__(self, reason):
334
        self.reason = reason
335

    
336
    def __str__(self):
337
        return f"Revocation reason '{self.reason}' is not valid."
338

    
339

    
340
class CertificateStatusInvalidException(Exception):
341
    """
342
    Exception that denotes that the caller was trying to set
343
    a certificate to an invalid state
344
    """
345

    
346
    def __init__(self, status):
347
        self.status = status
348

    
349
    def __str__(self):
350
        return f"Certificate status '{self.status}' is not valid."
(2-2/4)