summaryrefslogtreecommitdiff
path: root/src/leap/soledad/util.py
blob: 90797501e1016bf261e4a4dc6b7cbe201e3a1a62 (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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# -*- coding: utf-8 -*-
# util.py
# Copyright (C) 2013 LEAP
#
# 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/>.


"""
Utilities for Soledad.
"""

import os
import gnupg
import re
from gnupg import (
    logger,
    _is_sequence,
    _make_binary_stream,
)


class ListPackets():
    """
    Handle status messages for --list-packets.
    """

    def __init__(self, gpg):
        """
        Initialize the packet listing handling class.

        @param gpg: GPG object instance.
        @type gpg: gnupg.GPG
        """
        self.gpg = gpg
        self.nodata = None
        self.key = None
        self.need_passphrase = None
        self.need_passphrase_sym = None
        self.userid_hint = None

    def handle_status(self, key, value):
        """
        Handle one line of the --list-packets status message.

        @param key: The status message key.
        @type key: str
        @param value: The status message value.
        @type value: str
        """
        # TODO: write tests for handle_status
        if key == 'NODATA':
            self.nodata = True
        if key == 'ENC_TO':
            # This will only capture keys in our keyring. In the future we
            # may want to include multiple unknown keys in this list.
            self.key, _, _ = value.split()
        if key == 'NEED_PASSPHRASE':
            self.need_passphrase = True
        if key == 'NEED_PASSPHRASE_SYM':
            self.need_passphrase_sym = True
        if key == 'USERID_HINT':
            self.userid_hint = value.strip().split()


class GPGWrapper(gnupg.GPG):
    """
    This is a temporary class for handling GPG requests, and should be
    replaced by a more general class used throughout the project.
    """

    GNUPG_HOME = os.environ['HOME'] + "/.config/leap/gnupg"
    GNUPG_BINARY = "/usr/bin/gpg"  # this has to be changed based on OS

    def __init__(self, gpgbinary=GNUPG_BINARY, gnupghome=GNUPG_HOME,
                 verbose=False, use_agent=False, keyring=None, options=None):
        """
        Initialize a GnuPG process wrapper.

        @param gpgbinary: Name for GnuPG binary executable.
        @type gpgbinary: C{str}
        @param gpghome: Full pathname to directory containing the public and
            private keyrings.
        @type gpghome: C{str}
        @param keyring: Name of alternative keyring file to use. If specified,
            the default keyring is not used.
        @param verbose: Should some verbose info be output?
        @type verbose: bool
        @param use_agent: Should pass `--use-agent` to GPG binary?
        @type use_agent: bool
        @param keyring: Path for the keyring to use.
        @type keyring: str
        @options: A list of additional options to pass to the GPG binary.
        @type options: list

        @raise: RuntimeError with explanation message if there is a problem
            invoking gpg.
        """
        gnupg.GPG.__init__(self, gnupghome=gnupghome, gpgbinary=gpgbinary,
                           verbose=verbose, use_agent=use_agent,
                           keyring=keyring, options=options)
        self.result_map['list-packets'] = ListPackets

    def find_key_by_email(self, email, secret=False):
        """
        Find user's key based on their email.

        @param email: Email address of key being searched for.
        @type email: str
        @param secret: Should we search for a secret key?
        @type secret: bool

        @return: The fingerprint of the found key.
        @rtype: str
        """
        for key in self.list_keys(secret=secret):
            for uid in key['uids']:
                if re.search(email, uid):
                    return key
        raise LookupError("GnuPG public key for email %s not found!" % email)

    def find_key_by_subkey(self, subkey, secret=False):
        """
        Find user's key based on a subkey fingerprint.

        @param email: Subkey fingerprint of the key being searched for.
        @type email: str
        @param secret: Should we search for a secret key?
        @type secret: bool

        @return: The fingerprint of the found key.
        @rtype: str
        """
        for key in self.list_keys(secret=secret):
            for sub in key['subkeys']:
                if sub[0] == subkey:
                    return key
        raise LookupError(
            "GnuPG public key for subkey %s not found!" % subkey)

    def find_key_by_keyid(self, keyid, secret=False):
        """
        Find user's key based on the key ID.

        @param email: The key ID of the key being searched for.
        @type email: str
        @param secret: Should we search for a secret key?
        @type secret: bool

        @return: The fingerprint of the found key.
        @rtype: str
        """
        for key in self.list_keys(secret=secret):
            if keyid == key['keyid']:
                return key
        raise LookupError(
            "GnuPG public key for keyid %s not found!" % keyid)

    def find_key_by_fingerprint(self, fingerprint, secret=False):
        """
        Find user's key based on the key fingerprint.

        @param email: The fingerprint of the key being searched for.
        @type email: str
        @param secret: Should we search for a secret key?
        @type secret: bool

        @return: The fingerprint of the found key.
        @rtype: str
        """
        for key in self.list_keys(secret=secret):
            if fingerprint == key['fingerprint']:
                return key
        raise LookupError(
            "GnuPG public key for fingerprint %s not found!" % fingerprint)

    def encrypt(self, data, recipient, sign=None, always_trust=True,
                passphrase=None, symmetric=False):
        """
        Encrypt data using GPG.

        @param data: The data to be encrypted.
        @type data: str
        @param recipient: The address of the public key to be used.
        @type recipient: str
        @param sign: Should the encrypted content be signed?
        @type sign: bool
        @param always_trust: Skip key validation and assume that used keys
            are always fully trusted?
        @type always_trust: bool
        @param passphrase: The passphrase to be used if symmetric encryption
            is desired.
        @type passphrase: str
        @param symmetric: Should we encrypt to a password?
        @type symmetric: bool

        @return: An object with encrypted result in the `data` field.
        @rtype: gnupg.Crypt
        """
        # TODO: devise a way so we don't need to "always trust".
        return gnupg.GPG.encrypt(self, data, recipient, sign=sign,
                                 always_trust=always_trust,
                                 passphrase=passphrase,
                                 symmetric=symmetric,
                                 cipher_algo='AES256')

    def decrypt(self, data, always_trust=True, passphrase=None):
        """
        Decrypt data using GPG.

        @param data: The data to be decrypted.
        @type data: str
        @param always_trust: Skip key validation and assume that used keys
            are always fully trusted?
        @type always_trust: bool
        @param passphrase: The passphrase to be used if symmetric encryption
            is desired.
        @type passphrase: str

        @return: An object with decrypted result in the `data` field.
        @rtype: gnupg.Crypt
        """
        # TODO: devise a way so we don't need to "always trust".
        return gnupg.GPG.decrypt(self, data, always_trust=always_trust,
                                 passphrase=passphrase)

    def send_keys(self, keyserver, *keyids):
        """
        Send keys to a keyserver

        @param keyserver: The keyserver to send the keys to.
        @type keyserver: str
        @param keyids: The key ids to send.
        @type keyids: list

        @return: A list of keys sent to server.
        @rtype: gnupg.ListKeys
        """
        # TODO: write tests for this.
        # TODO: write a SendKeys class to handle status for this.
        result = self.result_map['list'](self)
        gnupg.logger.debug('send_keys: %r', keyids)
        data = gnupg._make_binary_stream("", self.encoding)
        args = ['--keyserver', keyserver, '--send-keys']
        args.extend(keyids)
        self._handle_io(args, data, result, binary=True)
        gnupg.logger.debug('send_keys result: %r', result.__dict__)
        data.close()
        return result

    def encrypt_file(self, file, recipients, sign=None,
                     always_trust=False, passphrase=None,
                     armor=True, output=None, symmetric=False,
                     cipher_algo=None):
        """
        Encrypt the message read from the file-like object 'file'.

        @param file: The file to be encrypted.
        @type data: file
        @param recipient: The address of the public key to be used.
        @type recipient: str
        @param sign: Should the encrypted content be signed?
        @type sign: bool
        @param always_trust: Skip key validation and assume that used keys
            are always fully trusted?
        @type always_trust: bool
        @param passphrase: The passphrase to be used if symmetric encryption
            is desired.
        @type passphrase: str
        @param armor: Create ASCII armored output?
        @type armor: bool
        @param output: Path of file to write results in.
        @type output: str
        @param symmetric: Should we encrypt to a password?
        @type symmetric: bool
        @param cipher_algo: Algorithm to use.
        @type cipher_algo: str

        @return: An object with encrypted result in the `data` field.
        @rtype: gnupg.Crypt
        """
        args = ['--encrypt']
        if symmetric:
            args = ['--symmetric']
            if cipher_algo:
                args.append('--cipher-algo %s' % cipher_algo)
        else:
            args = ['--encrypt']
            if not _is_sequence(recipients):
                recipients = (recipients,)
            for recipient in recipients:
                args.append('--recipient "%s"' % recipient)
        if armor:  # create ascii-armored output - set to False for binary
            args.append('--armor')
        if output:  # write the output to a file with the specified name
            if os.path.exists(output):
                os.remove(output)  # to avoid overwrite confirmation message
            args.append('--output "%s"' % output)
        if sign:
            args.append('--sign --default-key "%s"' % sign)
        if always_trust:
            args.append("--always-trust")
        result = self.result_map['crypt'](self)
        self._handle_io(args, file, result, passphrase=passphrase, binary=True)
        logger.debug('encrypt result: %r', result.data)
        return result

    def list_packets(self, data):
        """
        List the sequence of packets.

        @param data: The data to extract packets from.
        @type data: str

        @return: An object with packet info.
        @rtype ListPackets
        """
        args = ["--list-packets"]
        result = self.result_map['list-packets'](self)
        self._handle_io(
            args,
            _make_binary_stream(data, self.encoding),
            result,
        )
        return result

    def encrypted_to(self, data):
        """
        Return the key to which data is encrypted to.

        @param data: The data to be examined.
        @type data: str

        @return: The fingerprint of the key to which data is encrypted to.
        @rtype: str
        """
        # TODO: make this support multiple keys.
        result = self.list_packets(data)
        if not result.key:
            raise LookupError(
                "Content is not encrypted to a GnuPG key!")
        try:
            return self.find_key_by_keyid(result.key)
        except:
            return self.find_key_by_subkey(result.key)

    def is_encrypted_sym(self, data):
        """
        Say whether some chunk of data is encrypted to a symmetric key.

        @param data: The data to be examined.
        @type data: str

        @return: Whether data is encrypted to a symmetric key.
        @rtype: bool
        """
        result = self.list_packets(data)
        return bool(result.need_passphrase_sym)

    def is_encrypted_asym(self, data):
        """
        Say whether some chunk of data is encrypted to a private key.

        @param data: The data to be examined.
        @type data: str

        @return: Whether data is encrypted to a private key.
        @rtype: bool
        """
        result = self.list_packets(data)
        return bool(result.key)

    def is_encrypted(self, data):
        """
        Say whether some chunk of data is encrypted to a key.

        @param data: The data to be examined.
        @type data: str

        @return: Whether data is encrypted to a key.
        @rtype: bool
        """
        self.is_encrypted_asym() or self.is_encrypted_sym()