Projekt

Obecné

Profil

Stáhnout (13.4 KB) Statistiky
| Větev: | Tag: | Revize:
1
import re
2
import subprocess
3
import time
4

    
5
from src.model.subject import Subject
6
from src.utils.temporary_file import TemporaryFile
7

    
8
# encryption method to be used when generating private keys
9
PRIVATE_KEY_ENCRYPTION_METHOD = "-aes256"
10

    
11
# openssl executable name
12
OPENSSL_EXECUTABLE = "openssl"
13

    
14
# format of NOT_BEFORE NOT_AFTER date fields
15
NOT_AFTER_BEFORE_DATE_FORMAT = "%b %d %H:%M:%S %Y %Z"
16

    
17

    
18
class CryptographyService:
19

    
20
    @staticmethod
21
    def __subject_to_param_format(subject):
22
        """
23
        Converts the given subject to a dictionary containing openssl field names mapped to subject's fields
24
        :param subject: subject to be converted
25
        :return: a dictionary containing openssl field names mapped to subject's fields
26
        """
27
        subj_dict = {}
28
        if subject.common_name is not None:
29
            subj_dict["CN"] = subject.common_name
30
        if subject.country is not None:
31
            subj_dict["C"] = subject.country
32
        if subject.locality is not None:
33
            subj_dict["L"] = subject.locality
34
        if subject.state is not None:
35
            subj_dict["ST"] = subject.state
36
        if subject.organization is not None:
37
            subj_dict["O"] = subject.organization
38
        if subject.organization_unit is not None:
39
            subj_dict["OU"] = subject.organization_unit
40
        if subject.email_address is not None:
41
            subj_dict["emailAddress"] = subject.email_address
42

    
43
        # merge the subject into a "subj" parameter format
44
        return "".join([f"/{key}={value}" for key, value in subj_dict.items()])
45

    
46
    @staticmethod
47
    def __run_for_output(args=None, proc_input=None, executable=OPENSSL_EXECUTABLE):
48
        """
49
        Launches a new process in which the given executable is run. STDIN and process arguments can be set.
50
        If the process ends with a non-zero then <CryptographyException> is raised.
51

    
52
        :param args: Arguments to be passed to the program.
53
        :param proc_input: String input to be passed to the stdin of the created process.
54
        :param executable: Executable to be run (defaults to openssl)
55
        :return: If the process ends with a zero return code then the STDOUT of the process is returned as a byte array.
56
        """
57
        if args is None:
58
            args = []
59
        try:
60
            # prepend the name of the executable
61
            args.insert(0, executable)
62

    
63
            # create a new process
64
            proc = subprocess.Popen(args, stdin=subprocess.PIPE if proc_input is not None else None,
65
                                    stdout=subprocess.PIPE,
66
                                    stderr=subprocess.PIPE)
67

    
68
            out, err = proc.communicate(proc_input)
69

    
70
            if proc.returncode != 0:
71
                # if the process did not result in zero result code, then raise an exception
72
                if err is not None and len(err) > 0:
73
                    raise CryptographyException(executable, args, err.decode())
74
                else:
75
                    raise CryptographyException(executable, args,
76
                                                f""""Execution resulted in non-zero argument""")
77

    
78
            return out
79
        except FileNotFoundError:
80
            raise CryptographyException(executable, args, f""""{executable}" not found in the current PATH.""")
81

    
82
    def create_private_key(self, passphrase=None):
83
        """
84
        Creates a private key with the option to encrypt it using a passphrase.
85
        :param passphrase: A passphrase to be used when encrypting the key (if none is passed then the key is not
86
        encrypted at all). Empty passphrase ("") also results in a key that is not encrypted.
87
        :return: string containing the generated private key in PEM format
88
        """
89
        if passphrase is None or len(passphrase) == 0:
90
            return self.__run_for_output(["genrsa", "2048"]).decode()
91
        else:
92
            return self.__run_for_output(
93
                ["genrsa", PRIVATE_KEY_ENCRYPTION_METHOD, "-passout", f"pass:{passphrase}", "2048"]).decode()
94

    
95
    def create_sscrt(self, subject, key, config="", extensions="", key_pass=None):
96
        """
97
        Creates a root CA
98

    
99
        :param subject: an instance of <Subject> representing the subject to be added to the certificate
100
        :param key: private key of the CA to be used
101
        :param config: string containing the configuration to be used
102
        :param extensions: name of the section in the configuration representing extensions
103
        :param key_pass: passphrase of the private key
104

    
105
        :return: string containing the generated certificate in PEM format
106
        """
107
        assert key is not None
108
        assert subject is not None
109

    
110
        subj = self.__subject_to_param_format(subject)
111

    
112
        with TemporaryFile("openssl.conf", config) as conf_path:
113
            args = ["req", "-x509", "-new", "-subj", subj,
114
                    "-key", "-"]
115
            if len(config) > 0:
116
                args.extend(["-config", conf_path])
117

    
118
            if len(extensions) > 0:
119
                args.extend(["-extensions", extensions])
120

    
121
            # it would be best to not send the pass phrase at all, but for some reason pytest then prompts for
122
            # the pass phrase (this does not happen when run from pycharm)
123

    
124
            #  add the passphrase even when None is passed. Otherwise when running tests with pytest some tests freeze
125
            # waiting for the passphrase to be typed in
126
            args.extend(["-passin", f"pass:{key_pass}"])
127

    
128
            return self.__run_for_output(args, proc_input=bytes(key, encoding="utf-8")).decode()
129

    
130
    def __create_csr(self, subject, key, key_pass=""):
131
        """
132
        Creates a CSR (Certificate Signing Request)
133

    
134
        :param subject: an instance of <Subject> representing the subject to be added to the CSR
135
        :param key: the private key of the subject to be used to generate the CSR
136
        :param key_pass: passphrase of the subject's private key
137
        :return: string containing the generated certificate signing request in PEM format
138
        """
139

    
140
        subj_param = self.__subject_to_param_format(subject)
141

    
142
        args = ["req", "-new", "-subj", subj_param, "-key", "-"]
143

    
144
        # add the passphrase even when None is passed. Otherwise when running tests with pytest some tests freeze
145
        # waiting for the passphrase to be typed in
146
        args.extend(["-passin", f"pass:{key_pass}"])
147

    
148
        return self.__run_for_output(args, proc_input=bytes(key, encoding="utf-8")).decode()
149

    
150
    def __sign_csr(self, csr, issuer_pem, issuer_key, issuer_key_pass=None, extensions="", days=30):
151
        """
152
        Signs the given CSR by the given issuer CA
153

    
154
        :param csr: a string containing the CSR to be signed
155
        :param issuer_pem: string containing the certificate of the issuer that will sign this CSR in PEM format
156
        :param issuer_key: string containing the private key of the issuer's certificate in PEM format
157
        :param issuer_key_pass: string containing the passphrase of the private key of the issuer's certificate in PEM
158
        format
159
        :param extensions: extensions to be applied when signing the CSR
160
        :param days: number of days for which the certificate will be valid
161
        :return: string containing the generated and signed certificate in PEM format
162
        """
163

    
164
        # concatenate CSR, issuer certificate and issuer's key (will be used in the openssl call)
165
        proc_input = csr + issuer_pem + issuer_key
166

    
167
        # prepare openssl parameters...
168
        # CSR, CA and CA's private key will be passed via stdin (that's the meaning of the '-' symbol)
169
        params = ["x509", "-req", "-in", "-", "-CA", "-", "-CAkey", "-", "-CAcreateserial", "-days", str(days)]
170

    
171
        # TODO delete created -.srl file
172

    
173
        with TemporaryFile("extensions.conf", extensions) as ext_path:
174
            # add the passphrase even when None is passed. Otherwise when running tests with pytest some tests freeze
175
            # waiting for the passphrase to be typed in
176
            params.extend(["-passin", f"pass:{issuer_key_pass}"])
177

    
178
            if len(extensions) > 0:
179
                params.extend(["-extfile", ext_path])
180

    
181
            return self.__run_for_output(params, proc_input=(bytes(proc_input, encoding="utf-8"))).decode()
182

    
183
    def create_crt(self, subject, subject_key, issuer_pem, issuer_key, subject_key_pass=None, issuer_key_pass=None,
184
                   extensions="",
185
                   days=30):
186
        """
187
        Creates a certificate by using the given subject, subject's key, issuer and its key.
188

    
189
        :param subject: subject to be added to the created certificate
190
        :param subject_key: string containing the private key to be used when creating the certificate in PEM format
191
        :param issuer_key: string containing the private key of the issuer's certificate in PEM format
192
        :param issuer_pem: string containing the certificate of the issuer that will sign this CSR in PEM format
193
        :param subject_key_pass: string containing the passphrase of the private key used when creating the certificate
194
        in PEM format
195
        :param issuer_key_pass: string containing the passphrase of the private key of the issuer's certificate in PEM
196
        format
197
        :param extensions: extensions to be applied when creating the certificate
198
        :param days: number of days for which the certificate will be valid
199
        :return: string containing the generated certificate in PEM format
200
        """
201
        csr = self.__create_csr(subject, subject_key, key_pass=subject_key_pass)
202
        return self.__sign_csr(csr, issuer_pem, issuer_key, issuer_key_pass=issuer_key_pass, extensions=extensions,
203
                               days=days)
204

    
205
    @staticmethod
206
    def verify_cert(certificate):
207
        """
208
        Verifies whether the given certificate is not expired.
209

    
210
        :param certificate: certificate to be verified in PEM format
211
        :return: Returns `true` if the certificate is not expired, `false` when expired.
212
        """
213
        # call openssl to check whether the certificate is valid to this date
214
        args = [OPENSSL_EXECUTABLE, "x509", "-checkend", "0", "-noout", "-text", "-in", "-"]
215

    
216
        # create a new process
217
        proc = subprocess.Popen(args, stdin=subprocess.PIPE,
218
                                stdout=subprocess.PIPE,
219
                                stderr=subprocess.PIPE)
220

    
221
        out, err = proc.communicate(bytes(certificate, encoding="utf-8"))
222

    
223
        # zero return code means that the certificate is valid
224
        if proc.returncode == 0:
225
            return True
226
        elif proc.returncode == 1 and "Certificate will expire" in out.decode():
227
            # 1 return code means that the certificate is invalid but such message has to be present in the proc output
228
            return False
229
        else:
230
            # the process failed because of some other reason (incorrect cert format)
231
            raise CryptographyException(OPENSSL_EXECUTABLE, args, err.decode())
232

    
233
    def parse_cert_pem(self, cert_pem):
234
        """
235
        Parses the given certificate in PEM format and returns the subject of the certificate and it's NOT_BEFORE
236
        and NOT_AFTER field
237
        :param cert_pem: a certificated in a PEM format to be parsed
238
        :return: a tuple containing a subject, NOT_BEFORE and NOT_AFTER dates
239
        """
240
        # run openssl x509 to view certificate content
241
        args = ["x509", "-noout", "-subject", "-startdate", "-enddate", "-in", "-"]
242

    
243
        cert_info_raw = self.__run_for_output(args, proc_input=bytes(cert_pem, encoding="utf-8")).decode()
244

    
245
        # split lines
246
        results = re.split("\n", cert_info_raw)
247
        subj_line = results[0]
248
        not_before_line = results[1]
249
        not_after_line = results[2]
250

    
251
        # attempt to extract subject via regex
252
        match = re.search(r"subject=(.*)", subj_line)
253
        if match is None:
254
            # TODO use logger
255
            print(f"Could not find subject to parse: {subj_line}")
256
            return None
257
        else:
258
            # find all attributes (key = value)
259
            found = re.findall(r"\s?([^c=\s]+)\s?=\s?([^,\n]+)", match.group(1))
260
            subj = Subject()
261
            for key, value in found:
262
                if key == "C":
263
                    subj.country = value
264
                elif key == "ST":
265
                    subj.state = value
266
                elif key == "L":
267
                    subj.locality = value
268
                elif key == "O":
269
                    subj.organization = value
270
                elif key == "OU":
271
                    subj.organization_unit = value
272
                elif key == "CN":
273
                    subj.common_name = value
274
                elif key == "emailAddress":
275
                    subj.email_address = value
276

    
277
        # extract notBefore and notAfter date fields
278
        not_before = re.search(r"notBefore=(.*)", not_before_line)
279
        not_after = re.search(r"notAfter=(.*)", not_after_line)
280

    
281
        # if date fields are found parse them into date objects
282
        if not_before is not None:
283
            not_before = time.strptime(not_before.group(1), NOT_AFTER_BEFORE_DATE_FORMAT)
284
        if not_after is not None:
285
            not_after = time.strptime(not_after.group(1), NOT_AFTER_BEFORE_DATE_FORMAT)
286

    
287
        # TODO wrapper class?
288
        # return it as a tuple
289
        return subj, not_before, not_after
290

    
291

    
292
class CryptographyException(Exception):
293

    
294
    def __init__(self, executable, args, message):
295
        self.executable = executable
296
        self.args = args
297
        self.message = message
298

    
299
    def __str__(self):
300
        return f"""
301
        EXECUTABLE: {self.executable}
302
        ARGS: {self.args}
303
        MESSAGE: {self.message}
304
        """
(3-3/4)