aboutsummaryrefslogtreecommitdiff
path: root/src/mailman_pgp/pgp/inline.py
blob: bb0971dfc3988f248124dd75c901e5fedfc87b66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# Copyright (C) 2017 Jan Jancar
#
# This file is a part of the Mailman PGP plugin.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.

"""Strict inline PGP message wrapper."""
import copy
from email.iterators import walk

from pgpy import PGPMessage
from pgpy.constants import SymmetricKeyAlgorithm
from public import public

from mailman_pgp.utils.pgp import key_from_blob


@public
class InlineWrapper:
    """Inline PGP wrapper."""

    def __init__(self, msg):
        """
        Wrap the given message.

        :param msg: The message to wrap.
        :type msg: mailman.email.message.Message
        """
        self.msg = msg

    def get_payload(self):
        for part in walk(self.msg):
            if not part.is_multipart():
                yield part.get_payload()

    def _walk(self, walk_fn, *args, **kwargs):
        for part in walk(self.msg):
            if not part.is_multipart():
                yield walk_fn(part, *args, **kwargs)

    def _is_signed(self, part):
        try:
            msg = PGPMessage.from_blob(part.get_payload())
            return msg.is_signed
        except:
            pass
        return False

    def is_signed(self):
        """
        Whether the message is inline signed.

        :return: If the message is inline signed.
        :rtype: bool
        """
        return all(self._walk(self._is_signed))

    def has_signature(self):
        """
        Whether some parts of the message are inline signed.

        :return: If some parts of the message are inline signed.
        :rtype: bool
        """
        return any(self._walk(self._is_signed))

    def get_signed(self):
        """

        :return:
        """
        for part in walk(self.msg):
            if not part.is_multipart() and self._is_signed(part):
                try:
                    msg = PGPMessage.from_blob(part.get_payload()).message
                except:
                    continue
                yield msg

    def get_signature(self):
        """

        :return:
        :rtype: typing.Generator[pgpy.PGPMessage]
        """
        for part in walk(self.msg):
            if not part.is_multipart() and self._is_signed(part):
                try:
                    msg = PGPMessage.from_blob(part.get_payload())
                except:
                    continue
                yield msg

    def _is_encrypted(self, part):
        try:
            msg = PGPMessage.from_blob(part.get_payload())
            return msg.is_encrypted
        except:
            pass
        return False

    def is_encrypted(self):
        """
        Whether the message is inline encrypted.

        :return: If the message is inline encrypted.
        :rtype: bool
        """
        return all(self._walk(self._is_encrypted))

    def has_encryption(self):
        """
        Whether some parts of the message are inline encrypted.

        :return: If some parts of the message are inline encrypted.
        :rtype: bool
        """
        return any(self._walk(self._is_encrypted))

    def get_encrypted(self):
        """

        :return:
        :rtype: typing.Generator[pgpy.PGPMessage]
        """
        for part in walk(self.msg):
            if not part.is_multipart() and self._is_encrypted(part):
                try:
                    msg = PGPMessage.from_blob(part.get_payload())
                except:
                    continue
                yield msg

    def _has_keys(self, part):
        try:
            key_from_blob(part.get_payload())
            return True
        except:
            pass
        return False

    def is_keys(self):
        """
        Whether the message is all keys (all parts).

        :return: If the message is keys.
        :rtype: bool
        """
        return all(self._walk(self._has_keys))

    def has_keys(self):
        """
        Whether the message contains public or private keys.

        :return: If the message contains keys.
        :rtype: bool
        """
        return any(self._walk(self._has_keys))

    def keys(self):
        """
        Get the collection of keys in this message.

        :return: A collection of keys.
        :rtype: Generator[pgpy.PGPKey]
        """
        for part in walk(self.msg):
            if not part.is_multipart() and self._has_keys(part):
                try:
                    key = key_from_blob(part.get_payload())
                except:
                    continue
                yield key

    def verify(self, key):
        """
        Verify the signatures of this message with key.

        :param key: The key to verify with.
        :type key: pgpy.PGPKey
        :return: The verified signatures.
        :rtype: Generator[pgpy.types.SignatureVerification]
        """
        yield from map(key.verify, self.get_signature())

    def _sign(self, pmsg, key, hash):
        smsg = copy.copy(pmsg)
        smsg |= key.sign(smsg, hash=hash)
        return smsg

    def sign(self, key, hash=None):
        """
        Sign a message with key.

        :param key: The key to sign with.
        :type key: pgpy.PGPKey
        :param hash: The hash algorithm to use.
        :type hash: pgpy.constants.HashAlgorithm
        :return: The signed message.
        :rtype: mailman.email.message.Message
        """
        out = copy.deepcopy(self.msg)
        for part in walk(out):
            if not part.is_multipart():
                if self._is_signed(part):
                    pmsg = PGPMessage.from_blob(part.get_payload())
                else:
                    payload = str(part.get_payload())
                    pmsg = PGPMessage.new(payload, cleartext=True)
                smsg = self._sign(pmsg, key, hash)
                part.set_payload(str(smsg))
        return out

    def _decrypt(self, part, key):
        message = PGPMessage.from_blob(part.get_payload())
        # TODO: exception safe this.
        decrypted = key.decrypt(message)
        if decrypted.is_signed:
            part.set_payload(str(decrypted))
        else:
            part.set_payload(decrypted.message)

    def decrypt(self, key):
        """
        Decrypt this message with key.

        :param key: The key to decrypt with.
        :type key: pgpy.PGPKey
        :return: The decrypted message.
        :rtype: mailman.email.message.Message
        """
        out = copy.deepcopy(self.msg)
        for part in walk(out):
            if not part.is_multipart() and self._is_encrypted(part):
                self._decrypt(part, key)
        return out

    def _encrypt(self, pmsg, *keys, cipher, **kwargs):
        emsg = copy.copy(pmsg)
        if len(keys) == 1:
            emsg = keys[0].encrypt(emsg, cipher=cipher, **kwargs)
        else:
            session_key = cipher.gen_key()
            for key in keys:
                emsg = key.encrypt(emsg, cipher=cipher,
                                   sessionkey=session_key,
                                   **kwargs)
            del session_key
        return emsg

    def encrypt(self, *keys, cipher=SymmetricKeyAlgorithm.AES256,
                **kwargs):
        """
        Encrypt the message with key/s, using cipher.

        :param keys: The key/s to encrypt with.
        :type keys: pgpy.PGPKey
        :param cipher: The symmetric cipher to use.
        :type cipher: SymmetricKeyAlgorithm
        :return: mailman.email.message.Message
        """
        if len(keys) == 0:
            raise ValueError('At least one key necessary.')

        out = copy.deepcopy(self.msg)
        for part in walk(out):
            if not part.is_multipart():
                payload = str(part.get_payload())
                pmsg = PGPMessage.new(payload)
                emsg = self._encrypt(pmsg, *keys, cipher=cipher, **kwargs)
                part.set_payload(str(emsg))
        return out

    def sign_encrypt(self, key, *keys, hash=None,
                     cipher=SymmetricKeyAlgorithm.AES256,
                     **kwargs):
        """
        Sign and encrypt the message, in one go.

        :param key: The key to sign with.
        :type key: pgpy.PGPKey
        :param keys: The key/s to encrypt with.
        :type keys: pgpy.PGPKey
        :param hash:
        :type hash: pgpy.constants.HashAlgorithm
        :param cipher:
        :type cipher: pgpy.constants.SymmetricKeyAlgorithm
        :return: The signed + encrypted message.
        :rtype: mailman.email.message.Message
        """
        if len(keys) == 0:
            raise ValueError('At least one key necessary.')

        out = copy.deepcopy(self.msg)
        for part in walk(out):
            if not part.is_multipart():
                if self._is_signed(part):
                    pmsg = PGPMessage.from_blob(part.get_payload())
                else:
                    payload = str(part.get_payload())
                    pmsg = PGPMessage.new(payload)
                smsg = self._sign(pmsg, key, hash=hash)
                emsg = self._encrypt(smsg, *keys, cipher=cipher, **kwargs)
                part.set_payload(str(emsg))
        return out

    def sign_then_encrypt(self, key, *keys, hash=None,
                          cipher=SymmetricKeyAlgorithm.AES256,
                          **kwargs):
        return self.sign_encrypt(key, *keys, hash=hash, cipher=cipher,
                                 **kwargs)