Projekt

Obecné

Profil

Stáhnout (7.94 KB) Statistiky
| Větev: | Tag: | Revize:
1
import subprocess
2

    
3
# encryption method to be used when generating private keys
4
from proj.utils.temporary_file import TemporaryFile
5

    
6
PRIVATE_KEY_ENCRYPTION_METHOD = "-aes256"
7

    
8
# openssl executable name
9
OPENSSL_EXECUTABLE = "openssl"
10

    
11

    
12
class CryptographyService:
13

    
14
    @staticmethod
15
    def subject_to_param_format(subject):
16
        subj_dict = {}
17
        if subject.common_name is not None:
18
            subj_dict["CN"] = subject.common_name
19
        if subject.country is not None:
20
            subj_dict["C"] = subject.country
21
        if subject.locality is not None:
22
            subj_dict["L"] = subject.locality
23
        if subject.state is not None:
24
            subj_dict["ST"] = subject.state
25
        if subject.organization is not None:
26
            subj_dict["O"] = subject.organization
27
        if subject.organization_unit is not None:
28
            subj_dict["OU"] = subject.organization_unit
29
        if subject.email_address is not None:
30
            subj_dict["emailAddress"] = subject.email_address
31

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

    
35
    @staticmethod
36
    def _run_for_output(args=None, proc_input=None, executable=OPENSSL_EXECUTABLE):
37
        """
38
        Launches a new process in which the given executable is run. STDIN and process arguments can be set.
39
        If the process ends with a non-zero then <CryptographyException> is raised.
40
        :param args: Arguments to be passed to the program.
41
        :param proc_input: String input to be passed to the stdin of the created process.
42
        :param executable: Executable to be run (defaults to openssl)
43
        :return: If the process ends with a zero return code then the STDOUT of the process is returned as a byte array.
44
        """
45
        if args is None:
46
            args = []
47
        try:
48
            # prepend the name of the executable
49
            args.insert(0, executable)
50

    
51
            # create a new process
52
            proc = subprocess.Popen(args, stdin=subprocess.PIPE if proc_input is not None else None,
53
                                    stdout=subprocess.PIPE,
54
                                    stderr=subprocess.PIPE)
55

    
56
            out, err = proc.communicate(proc_input)
57

    
58
            if proc.returncode != 0:
59
                # if the process did not result in zero result code, then raise an exception
60
                if err is not None:
61
                    raise CryptographyException(executable, args, err.decode())
62
                else:
63
                    raise CryptographyException(executable, args,
64
                                                f""""Execution resulted in non-zero argument""")
65

    
66
            return out
67
        except FileNotFoundError:
68
            raise CryptographyException(executable, args, f""""{executable}" not found in the current PATH.""")
69

    
70
    def create_private_key(self, passphrase=None):
71
        """
72
        Creates a private key with the option to encrypt it using a passphrase.
73
        :param passphrase: A passphrase to be used when encrypting the key (if none is passed then the key is not
74
        encrypted at all). Empty passphrase ("") also results in a key that is not encrypted.
75
        :return: A text representation of the generated private key.
76
        """
77
        if passphrase is None or len(passphrase) == 0:
78
            return self._run_for_output(["genrsa", "2048"]).decode()
79
        else:
80
            return self._run_for_output(
81
                ["genrsa", PRIVATE_KEY_ENCRYPTION_METHOD, "-passout", f"pass:{passphrase}", "2048"]).decode()
82

    
83
    def create_sscrt(self, key, subject, config="", extensions="", key_passphrase=None):
84
        """
85
        Creates a root CA
86

    
87
        :param key: private key of the CA to be used
88
        :param subject: an instance of <Subject> representing the subject to be added to the certificate
89
        :param config: string containing the configuration to be used
90
        :param extensions: name of the section in the configuration representing extensions
91
        :param key_passphrase: passphrase of the private key
92

    
93
        :return: byte array containing the generated certificate
94
        """
95
        assert key is not None
96
        assert subject is not None
97

    
98
        subj = self.subject_to_param_format(subject)
99

    
100
        with TemporaryFile("openssl.conf", config) as conf_path:
101
            args = ["req", "-x509", "-new", "-subj", subj,
102
                    "-key", "-"]
103
            if len(config) > 0:
104
                args.extend(["-config", conf_path])
105

    
106
            if len(extensions) > 0:
107
                args.extend(["-extensions", extensions])
108

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

    
112
            #  add the passphrase even when None is passed. Otherwise when running tests with pytest some tests freeze
113
            # waiting for the passphrase to be typed in
114
            args.extend(["-passin", f"pass:{key_passphrase}"])
115

    
116
            return self._run_for_output(args, proc_input=bytes(key, encoding="utf-8")).decode()
117

    
118
    def make_csr(self, subject, subject_key, subject_key_pass=""):
119
        """
120
        Makes a CSR (Certificate Signing Request)
121

    
122
        :param subject: an instance of <Subject> representing the subject to be added to the CSR
123
        :param subject_key: the private key of the subject to be used to generate the CSR
124
        :param subject_key_pass: passphrase of the subject's private key
125
        :return: byte array containing the generated certificate signing request
126
        """
127

    
128
        subj_param = self.subject_to_param_format(subject)
129

    
130
        args = ["req", "-new", "-subj", subj_param, "-key", "-"]
131

    
132
        # add the passphrase even when None is passed. Otherwise when running tests with pytest some tests freeze
133
        # waiting for the passphrase to be typed in
134
        args.extend(["-passin", f"pass:{subject_key_pass}"])
135

    
136
        return self._run_for_output(args, proc_input=bytes(subject_key, encoding="utf-8")).decode()
137

    
138
    def sign_csr(self, csr, issuer_pem, issuer_key, issuer_key_pass=None, config="", extensions=""):
139
        """
140
        Signs the given CSR by the given issuer CA
141
        :param csr: a string containing the CSR to be signed
142
        :param issuer_pem: string containing the certificate of the issuer that will sign this CSR in PEM format
143
        :param issuer_key: string containing the private key of the issuer's certificate in PEM format
144
        :param issuer_key_pass: string containing the private key of the issuer's certificate in PEM format
145
        :param config: TODO NOT USED
146
        :param extensions: extensions to be applied when signing the CSR
147
        :return: string containing the generated and signed certificate in PEM format
148
        """
149

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

    
153
        # prepare openssl parameters...
154
        # CSR, CA and CA's private key will be passed via stdin (that's the meaning of the '-' symbol)
155
        params = ["x509", "-req", "-in", "-", "-CA", "-", "-CAkey", "-", "-CAcreateserial"]
156

    
157
        # TODO delete created -.srl file
158

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

    
164
            if len(extensions) > 0:
165
                params.extend(["-extfile", ext_path])
166

    
167
            return self._run_for_output(params, proc_input=(bytes(proc_input, encoding="utf-8"))).decode()
168

    
169

    
170
class CryptographyException(Exception):
171

    
172
    def __init__(self, executable, args, message):
173
        self.executable = executable
174
        self.args = args
175
        self.message = message
176

    
177
    def __str__(self):
178
        return f"""
179
        EXECUTABLE: {self.executable}
180
        ARGS: {self.args}
181
        MESSAGE: {self.message}
182
        """
(2-2/2)