Projekt

Obecné

Profil

Stáhnout (14.5 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, days=30):
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
        :param days: number of days for which the certificate will be valid
105

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

    
111
        subj = self.__subject_to_param_format(subject)
112

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

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

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

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

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

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

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

    
141
        subj_param = self.__subject_to_param_format(subject)
142

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

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

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

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

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

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

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

    
172
        # TODO delete created -.srl file
173

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

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

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

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

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

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

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

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

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

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

    
234
    def extract_public_key(self, private_key_pem: str, passphrase=None) -> str:
235
        """
236
        Extracts a public key from the given private key passed in PEM format
237
        :param private_key_pem: PEM data representing the private key from which a public key should be extracted
238
        :param passphrase: passphrase to be provided when the supplied private key is encrypted
239
        :return: a string containing the extracted public key in PEM format
240
        """
241
        args = ["rsa", "-in", "-", "-pubout"]
242
        if passphrase is not None:
243
            args.extend(["-passin", f"pass:{passphrase}"])
244
        return self.__run_for_output(args, proc_input=bytes(private_key_pem, encoding="utf-8")).decode()
245

    
246
    def parse_cert_pem(self, cert_pem):
247
        """
248
        Parses the given certificate in PEM format and returns the subject of the certificate and it's NOT_BEFORE
249
        and NOT_AFTER field
250
        :param cert_pem: a certificated in a PEM format to be parsed
251
        :return: a tuple containing a subject, NOT_BEFORE and NOT_AFTER dates
252
        """
253
        # run openssl x509 to view certificate content
254
        args = ["x509", "-noout", "-subject", "-startdate", "-enddate", "-in", "-"]
255

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

    
258
        # split lines
259
        results = re.split("\n", cert_info_raw)
260
        subj_line = results[0]
261
        not_before_line = results[1]
262
        not_after_line = results[2]
263

    
264
        # attempt to extract subject via regex
265
        match = re.search(r"subject=(.*)", subj_line)
266
        if match is None:
267
            # TODO use logger
268
            print(f"Could not find subject to parse: {subj_line}")
269
            return None
270
        else:
271
            # find all attributes (key = value)
272
            found = re.findall(r"\s?([^c=\s]+)\s?=\s?([^,\n]+)", match.group(1))
273
            subj = Subject()
274
            for key, value in found:
275
                if key == "C":
276
                    subj.country = value
277
                elif key == "ST":
278
                    subj.state = value
279
                elif key == "L":
280
                    subj.locality = value
281
                elif key == "O":
282
                    subj.organization = value
283
                elif key == "OU":
284
                    subj.organization_unit = value
285
                elif key == "CN":
286
                    subj.common_name = value
287
                elif key == "emailAddress":
288
                    subj.email_address = value
289

    
290
        # extract notBefore and notAfter date fields
291
        not_before = re.search(r"notBefore=(.*)", not_before_line)
292
        not_after = re.search(r"notAfter=(.*)", not_after_line)
293

    
294
        # if date fields are found parse them into date objects
295
        if not_before is not None:
296
            not_before = time.strptime(not_before.group(1).strip(), NOT_AFTER_BEFORE_DATE_FORMAT)
297
        if not_after is not None:
298
            not_after = time.strptime(not_after.group(1).strip(), NOT_AFTER_BEFORE_DATE_FORMAT)
299

    
300
        # TODO wrapper class?
301
        # return it as a tuple
302
        return subj, not_before, not_after
303

    
304
    def get_openssl_version(self) -> str:
305
        """
306
        Get version of the OpenSSL installed on the system
307
        :return: version of the OpenSSL as returned from the process
308
        """
309
        return self.__run_for_output(["version"]).decode("utf-8")
310

    
311

    
312
class CryptographyException(Exception):
313

    
314
    def __init__(self, executable, args, message):
315
        self.executable = executable
316
        self.args = args
317
        self.message = message
318

    
319
    def __str__(self):
320
        return f"""
321
        EXECUTABLE: {self.executable}
322
        ARGS: {self.args}
323
        MESSAGE: {self.message}
324
        """
(3-3/4)