/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/gpg.py

  • Committer: Jelmer Vernooij
  • Date: 2018-11-21 03:39:28 UTC
  • mto: This revision was merged to the branch mainline in revision 7206.
  • Revision ID: jelmer@jelmer.uk-20181121033928-ck4sb5zfdwosw35b
Fix test.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2009, 2011, 2012, 2013, 2016 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
17
17
 
18
18
"""GPG signing and checking logic."""
19
19
 
 
20
from __future__ import absolute_import
 
21
 
20
22
import os
21
 
import sys
22
23
 
23
 
from bzrlib.lazy_import import lazy_import
 
24
from breezy.lazy_import import lazy_import
24
25
lazy_import(globals(), """
25
 
import errno
26
 
import subprocess
27
 
 
28
 
from bzrlib import (
29
 
    errors,
 
26
from breezy import (
 
27
    config,
30
28
    trace,
31
29
    ui,
32
30
    )
 
31
from breezy.i18n import (
 
32
    gettext,
 
33
    ngettext,
 
34
    )
33
35
""")
34
36
 
 
37
from . import (
 
38
    errors,
 
39
    )
 
40
from .sixish import (
 
41
    text_type,
 
42
    )
 
43
 
 
44
# verification results
 
45
SIGNATURE_VALID = 0
 
46
SIGNATURE_KEY_MISSING = 1
 
47
SIGNATURE_NOT_VALID = 2
 
48
SIGNATURE_NOT_SIGNED = 3
 
49
SIGNATURE_EXPIRED = 4
 
50
 
 
51
MODE_NORMAL = 0
 
52
MODE_DETACH = 1
 
53
MODE_CLEAR = 2
 
54
 
 
55
 
 
56
class GpgNotInstalled(errors.DependencyNotPresent):
 
57
 
 
58
    _fmt = 'python-gpg is not installed, it is needed to verify signatures'
 
59
 
 
60
    def __init__(self, error):
 
61
        errors.DependencyNotPresent.__init__(self, 'gpg', error)
 
62
 
 
63
 
 
64
class SigningFailed(errors.BzrError):
 
65
 
 
66
    _fmt = 'Failed to GPG sign data: "%(error)s"'
 
67
 
 
68
    def __init__(self, error):
 
69
        errors.BzrError.__init__(self, error=error)
 
70
 
 
71
 
 
72
class SignatureVerificationFailed(errors.BzrError):
 
73
 
 
74
    _fmt = 'Failed to verify GPG signature data with error "%(error)s"'
 
75
 
 
76
    def __init__(self, error):
 
77
        errors.BzrError.__init__(self, error=error)
 
78
 
 
79
 
 
80
def bulk_verify_signatures(repository, revids, strategy,
 
81
                           process_events_callback=None):
 
82
    """Do verifications on a set of revisions
 
83
 
 
84
    :param repository: repository object
 
85
    :param revids: list of revision ids to verify
 
86
    :param strategy: GPG strategy to use
 
87
    :param process_events_callback: method to call for GUI frontends that
 
88
        want to keep their UI refreshed
 
89
 
 
90
    :return: count dictionary of results of each type,
 
91
             result list for each revision,
 
92
             boolean True if all results are verified successfully
 
93
    """
 
94
    count = {SIGNATURE_VALID: 0,
 
95
             SIGNATURE_KEY_MISSING: 0,
 
96
             SIGNATURE_NOT_VALID: 0,
 
97
             SIGNATURE_NOT_SIGNED: 0,
 
98
             SIGNATURE_EXPIRED: 0}
 
99
    result = []
 
100
    all_verifiable = True
 
101
    total = len(revids)
 
102
    with ui.ui_factory.nested_progress_bar() as pb:
 
103
        for i, (rev_id, verification_result, uid) in enumerate(
 
104
                repository.verify_revision_signatures(
 
105
                    revids, strategy)):
 
106
            pb.update("verifying signatures", i, total)
 
107
            result.append([rev_id, verification_result, uid])
 
108
            count[verification_result] += 1
 
109
            if verification_result != SIGNATURE_VALID:
 
110
                all_verifiable = False
 
111
            if process_events_callback is not None:
 
112
                process_events_callback()
 
113
    return (count, result, all_verifiable)
 
114
 
35
115
 
36
116
class DisabledGPGStrategy(object):
37
117
    """A GPG Strategy that makes everything fail."""
38
118
 
 
119
    @staticmethod
 
120
    def verify_signatures_available():
 
121
        return True
 
122
 
39
123
    def __init__(self, ignored):
40
124
        """Real strategies take a configuration."""
41
125
 
42
 
    def sign(self, content):
43
 
        raise errors.SigningFailed('Signing is disabled.')
 
126
    def sign(self, content, mode):
 
127
        raise SigningFailed('Signing is disabled.')
 
128
 
 
129
    def verify(self, signed_data, signature=None):
 
130
        raise SignatureVerificationFailed('Signature verification is \
 
131
disabled.')
 
132
 
 
133
    def set_acceptable_keys(self, command_line_input):
 
134
        pass
44
135
 
45
136
 
46
137
class LoopbackGPGStrategy(object):
47
 
    """A GPG Strategy that acts like 'cat' - data is just passed through."""
 
138
    """A GPG Strategy that acts like 'cat' - data is just passed through.
 
139
    Used in tests.
 
140
    """
 
141
 
 
142
    @staticmethod
 
143
    def verify_signatures_available():
 
144
        return True
48
145
 
49
146
    def __init__(self, ignored):
50
147
        """Real strategies take a configuration."""
51
148
 
52
 
    def sign(self, content):
53
 
        return ("-----BEGIN PSEUDO-SIGNED CONTENT-----\n" + content +
54
 
                "-----END PSEUDO-SIGNED CONTENT-----\n")
 
149
    def sign(self, content, mode):
 
150
        return (b"-----BEGIN PSEUDO-SIGNED CONTENT-----\n" + content
 
151
                + b"-----END PSEUDO-SIGNED CONTENT-----\n")
 
152
 
 
153
    def verify(self, signed_data, signature=None):
 
154
        plain_text = signed_data.replace(
 
155
            b"-----BEGIN PSEUDO-SIGNED CONTENT-----\n", b"")
 
156
        plain_text = plain_text.replace(
 
157
            b"-----END PSEUDO-SIGNED CONTENT-----\n", b"")
 
158
        return SIGNATURE_VALID, None, plain_text
 
159
 
 
160
    def set_acceptable_keys(self, command_line_input):
 
161
        if command_line_input is not None:
 
162
            patterns = command_line_input.split(",")
 
163
            self.acceptable_keys = []
 
164
            for pattern in patterns:
 
165
                if pattern == "unknown":
 
166
                    pass
 
167
                else:
 
168
                    self.acceptable_keys.append(pattern)
55
169
 
56
170
 
57
171
def _set_gpg_tty():
62
176
    else:
63
177
        # This is not quite worthy of a warning, because some people
64
178
        # don't need GPG_TTY to be set. But it is worthy of a big mark
65
 
        # in ~/.bzr.log, so that people can debug it if it happens to them
 
179
        # in ~/.brz.log, so that people can debug it if it happens to them
66
180
        trace.mutter('** Env var TTY empty, cannot set GPG_TTY.'
67
181
                     '  Is TTY exported?')
68
182
 
70
184
class GPGStrategy(object):
71
185
    """GPG Signing and checking facilities."""
72
186
 
73
 
    def _command_line(self):
74
 
        return [self._config.gpg_signing_command(), '--clearsign']
75
 
 
76
 
    def __init__(self, config):
77
 
        self._config = config
78
 
 
79
 
    def sign(self, content):
80
 
        if isinstance(content, unicode):
 
187
    acceptable_keys = None
 
188
 
 
189
    def __init__(self, config_stack):
 
190
        self._config_stack = config_stack
 
191
        try:
 
192
            import gpg
 
193
            self.context = gpg.Context()
 
194
            self.context.armor = True
 
195
            self.context.signers = self._get_signing_keys()
 
196
        except ImportError:
 
197
            pass  # can't use verify()
 
198
 
 
199
    def _get_signing_keys(self):
 
200
        import gpg
 
201
        keyname = self._config_stack.get('gpg_signing_key')
 
202
        if keyname:
 
203
            try:
 
204
                return [self.context.get_key(keyname)]
 
205
            except gpg.errors.KeyNotFound:
 
206
                pass
 
207
 
 
208
        if keyname is None or keyname == 'default':
 
209
            # 'default' or not setting gpg_signing_key at all means we should
 
210
            # use the user email address
 
211
            keyname = config.extract_email_address(
 
212
                self._config_stack.get('email'))
 
213
        possible_keys = self.context.keylist(keyname, secret=True)
 
214
        try:
 
215
            return [next(possible_keys)]
 
216
        except StopIteration:
 
217
            return []
 
218
 
 
219
    @staticmethod
 
220
    def verify_signatures_available():
 
221
        """
 
222
        check if this strategy can verify signatures
 
223
 
 
224
        :return: boolean if this strategy can verify signatures
 
225
        """
 
226
        try:
 
227
            import gpg  # noqa: F401
 
228
            return True
 
229
        except ImportError:
 
230
            return False
 
231
 
 
232
    def sign(self, content, mode):
 
233
        import gpg
 
234
        if isinstance(content, text_type):
81
235
            raise errors.BzrBadParameterUnicode('content')
82
 
        ui.ui_factory.clear_term()
83
 
 
84
 
        preexec_fn = _set_gpg_tty
85
 
        if sys.platform == 'win32':
86
 
            # Win32 doesn't support preexec_fn, but wouldn't support TTY anyway.
87
 
            preexec_fn = None
88
 
        try:
89
 
            process = subprocess.Popen(self._command_line(),
90
 
                                       stdin=subprocess.PIPE,
91
 
                                       stdout=subprocess.PIPE,
92
 
                                       preexec_fn=preexec_fn)
93
 
            try:
94
 
                result = process.communicate(content)[0]
95
 
                if process.returncode is None:
96
 
                    process.wait()
97
 
                if process.returncode != 0:
98
 
                    raise errors.SigningFailed(self._command_line())
99
 
                return result
100
 
            except OSError, e:
101
 
                if e.errno == errno.EPIPE:
102
 
                    raise errors.SigningFailed(self._command_line())
 
236
 
 
237
        plain_text = gpg.Data(content)
 
238
        try:
 
239
            output, result = self.context.sign(
 
240
                plain_text, mode={
 
241
                    MODE_DETACH: gpg.constants.sig.mode.DETACH,
 
242
                    MODE_CLEAR: gpg.constants.sig.mode.CLEAR,
 
243
                    MODE_NORMAL: gpg.constants.sig.mode.NORMAL,
 
244
                    }[mode])
 
245
        except gpg.errors.GPGMEError as error:
 
246
            raise SigningFailed(str(error))
 
247
 
 
248
        return output
 
249
 
 
250
    def verify(self, signed_data, signature=None):
 
251
        """Check content has a valid signature.
 
252
 
 
253
        :param signed_data; Signed data
 
254
        :param signature: optional signature (if detached)
 
255
 
 
256
        :return: SIGNATURE_VALID or a failed SIGNATURE_ value, key uid if valid, plain text
 
257
        """
 
258
        try:
 
259
            import gpg
 
260
        except ImportError as error:
 
261
            raise errors.GpgNotInstalled(error)
 
262
 
 
263
        signed_data = gpg.Data(signed_data)
 
264
        if signature:
 
265
            signature = gpg.Data(signature)
 
266
        try:
 
267
            plain_output, result = self.context.verify(signed_data, signature)
 
268
        except gpg.errors.BadSignatures as error:
 
269
            fingerprint = error.result.signatures[0].fpr
 
270
            if error.result.signatures[0].summary & gpg.constants.SIGSUM_KEY_EXPIRED:
 
271
                expires = self.context.get_key(
 
272
                    error.result.signatures[0].fpr).subkeys[0].expires
 
273
                if expires > error.result.signatures[0].timestamp:
 
274
                    # The expired key was not expired at time of signing.
 
275
                    # test_verify_expired_but_valid()
 
276
                    return SIGNATURE_EXPIRED, fingerprint[-8:], None
103
277
                else:
104
 
                    raise
105
 
        except ValueError:
106
 
            # bad subprocess parameters, should never happen.
107
 
            raise
108
 
        except OSError, e:
109
 
            if e.errno == errno.ENOENT:
110
 
                # gpg is not installed
111
 
                raise errors.SigningFailed(self._command_line())
112
 
            else:
113
 
                raise
 
278
                    # I can't work out how to create a test where the signature
 
279
                    # was expired at the time of signing.
 
280
                    return SIGNATURE_NOT_VALID, None, None
 
281
 
 
282
            # GPG does not know this key.
 
283
            # test_verify_unknown_key()
 
284
            if (error.result.signatures[0].summary &
 
285
                    gpg.constants.SIGSUM_KEY_MISSING):
 
286
                return SIGNATURE_KEY_MISSING, fingerprint[-8:], None
 
287
 
 
288
            return SIGNATURE_NOT_VALID, None, None
 
289
        except gpg.errors.GPGMEError as error:
 
290
            raise SignatureVerificationFailed(error)
 
291
 
 
292
        # No result if input is invalid.
 
293
        # test_verify_invalid()
 
294
        if len(result.signatures) == 0:
 
295
            return SIGNATURE_NOT_VALID, None, plain_output
 
296
 
 
297
        # User has specified a list of acceptable keys, check our result is in
 
298
        # it.  test_verify_unacceptable_key()
 
299
        fingerprint = result.signatures[0].fpr
 
300
        if self.acceptable_keys is not None:
 
301
            if fingerprint not in self.acceptable_keys:
 
302
                return SIGNATURE_KEY_MISSING, fingerprint[-8:], plain_output
 
303
        # Yay gpg set the valid bit.
 
304
        # Can't write a test for this one as you can't set a key to be
 
305
        # trusted using gpg.
 
306
        if result.signatures[0].summary & gpg.constants.SIGSUM_VALID:
 
307
            key = self.context.get_key(fingerprint)
 
308
            name = key.uids[0].name
 
309
            email = key.uids[0].email
 
310
            return (
 
311
                SIGNATURE_VALID,
 
312
                name.decode('utf-8') + u" <" + email.decode('utf-8') + u">",
 
313
                plain_output)
 
314
        # Sigsum_red indicates a problem, unfortunatly I have not been able
 
315
        # to write any tests which actually set this.
 
316
        if result.signatures[0].summary & gpg.constants.SIGSUM_RED:
 
317
            return SIGNATURE_NOT_VALID, None, plain_output
 
318
        # Summary isn't set if sig is valid but key is untrusted but if user
 
319
        # has explicity set the key as acceptable we can validate it.
 
320
        if (result.signatures[0].summary == 0 and
 
321
                self.acceptable_keys is not None):
 
322
            if fingerprint in self.acceptable_keys:
 
323
                # test_verify_untrusted_but_accepted()
 
324
                return SIGNATURE_VALID, None, plain_output
 
325
        # test_verify_valid_but_untrusted()
 
326
        if result.signatures[0].summary == 0 and self.acceptable_keys is None:
 
327
            return SIGNATURE_NOT_VALID, None, plain_output
 
328
        # Other error types such as revoked keys should (I think) be caught by
 
329
        # SIGSUM_RED so anything else means something is buggy.
 
330
        raise SignatureVerificationFailed(
 
331
            "Unknown GnuPG key verification result")
 
332
 
 
333
    def set_acceptable_keys(self, command_line_input):
 
334
        """Set the acceptable keys for verifying with this GPGStrategy.
 
335
 
 
336
        :param command_line_input: comma separated list of patterns from
 
337
                                command line
 
338
        :return: nothing
 
339
        """
 
340
        patterns = None
 
341
        acceptable_keys_config = self._config_stack.get('acceptable_keys')
 
342
        if acceptable_keys_config is not None:
 
343
            patterns = acceptable_keys_config
 
344
        if command_line_input is not None:  # command line overrides config
 
345
            patterns = command_line_input.split(',')
 
346
 
 
347
        if patterns:
 
348
            self.acceptable_keys = []
 
349
            for pattern in patterns:
 
350
                result = self.context.keylist(pattern)
 
351
                found_key = False
 
352
                for key in result:
 
353
                    found_key = True
 
354
                    self.acceptable_keys.append(key.subkeys[0].fpr)
 
355
                    trace.mutter("Added acceptable key: " + key.subkeys[0].fpr)
 
356
                if not found_key:
 
357
                    trace.note(gettext(
 
358
                        "No GnuPG key results for pattern: {0}"
 
359
                        ).format(pattern))
 
360
 
 
361
 
 
362
def valid_commits_message(count):
 
363
    """returns message for number of commits"""
 
364
    return gettext(u"{0} commits with valid signatures").format(
 
365
        count[SIGNATURE_VALID])
 
366
 
 
367
 
 
368
def unknown_key_message(count):
 
369
    """returns message for number of commits"""
 
370
    return ngettext(u"{0} commit with unknown key",
 
371
                    u"{0} commits with unknown keys",
 
372
                    count[SIGNATURE_KEY_MISSING]).format(
 
373
        count[SIGNATURE_KEY_MISSING])
 
374
 
 
375
 
 
376
def commit_not_valid_message(count):
 
377
    """returns message for number of commits"""
 
378
    return ngettext(u"{0} commit not valid",
 
379
                    u"{0} commits not valid",
 
380
                    count[SIGNATURE_NOT_VALID]).format(
 
381
        count[SIGNATURE_NOT_VALID])
 
382
 
 
383
 
 
384
def commit_not_signed_message(count):
 
385
    """returns message for number of commits"""
 
386
    return ngettext(u"{0} commit not signed",
 
387
                    u"{0} commits not signed",
 
388
                    count[SIGNATURE_NOT_SIGNED]).format(
 
389
        count[SIGNATURE_NOT_SIGNED])
 
390
 
 
391
 
 
392
def expired_commit_message(count):
 
393
    """returns message for number of commits"""
 
394
    return ngettext(u"{0} commit with key now expired",
 
395
                    u"{0} commits with key now expired",
 
396
                    count[SIGNATURE_EXPIRED]).format(
 
397
        count[SIGNATURE_EXPIRED])
 
398
 
 
399
 
 
400
def verbose_expired_key_message(result, repo):
 
401
    """takes a verify result and returns list of expired key info"""
 
402
    signers = {}
 
403
    fingerprint_to_authors = {}
 
404
    for rev_id, validity, fingerprint in result:
 
405
        if validity == SIGNATURE_EXPIRED:
 
406
            revision = repo.get_revision(rev_id)
 
407
            authors = ', '.join(revision.get_apparent_authors())
 
408
            signers.setdefault(fingerprint, 0)
 
409
            signers[fingerprint] += 1
 
410
            fingerprint_to_authors[fingerprint] = authors
 
411
    result = []
 
412
    for fingerprint, number in signers.items():
 
413
        result.append(
 
414
            ngettext(u"{0} commit by author {1} with key {2} now expired",
 
415
                     u"{0} commits by author {1} with key {2} now expired",
 
416
                     number).format(
 
417
                number, fingerprint_to_authors[fingerprint], fingerprint))
 
418
    return result
 
419
 
 
420
 
 
421
def verbose_valid_message(result):
 
422
    """takes a verify result and returns list of signed commits strings"""
 
423
    signers = {}
 
424
    for rev_id, validity, uid in result:
 
425
        if validity == SIGNATURE_VALID:
 
426
            signers.setdefault(uid, 0)
 
427
            signers[uid] += 1
 
428
    result = []
 
429
    for uid, number in signers.items():
 
430
        result.append(ngettext(u"{0} signed {1} commit",
 
431
                               u"{0} signed {1} commits",
 
432
                               number).format(uid, number))
 
433
    return result
 
434
 
 
435
 
 
436
def verbose_not_valid_message(result, repo):
 
437
    """takes a verify result and returns list of not valid commit info"""
 
438
    signers = {}
 
439
    for rev_id, validity, empty in result:
 
440
        if validity == SIGNATURE_NOT_VALID:
 
441
            revision = repo.get_revision(rev_id)
 
442
            authors = ', '.join(revision.get_apparent_authors())
 
443
            signers.setdefault(authors, 0)
 
444
            signers[authors] += 1
 
445
    result = []
 
446
    for authors, number in signers.items():
 
447
        result.append(ngettext(u"{0} commit by author {1}",
 
448
                               u"{0} commits by author {1}",
 
449
                               number).format(number, authors))
 
450
    return result
 
451
 
 
452
 
 
453
def verbose_not_signed_message(result, repo):
 
454
    """takes a verify result and returns list of not signed commit info"""
 
455
    signers = {}
 
456
    for rev_id, validity, empty in result:
 
457
        if validity == SIGNATURE_NOT_SIGNED:
 
458
            revision = repo.get_revision(rev_id)
 
459
            authors = ', '.join(revision.get_apparent_authors())
 
460
            signers.setdefault(authors, 0)
 
461
            signers[authors] += 1
 
462
    result = []
 
463
    for authors, number in signers.items():
 
464
        result.append(ngettext(u"{0} commit by author {1}",
 
465
                               u"{0} commits by author {1}",
 
466
                               number).format(number, authors))
 
467
    return result
 
468
 
 
469
 
 
470
def verbose_missing_key_message(result):
 
471
    """takes a verify result and returns list of missing key info"""
 
472
    signers = {}
 
473
    for rev_id, validity, fingerprint in result:
 
474
        if validity == SIGNATURE_KEY_MISSING:
 
475
            signers.setdefault(fingerprint, 0)
 
476
            signers[fingerprint] += 1
 
477
    result = []
 
478
    for fingerprint, number in list(signers.items()):
 
479
        result.append(ngettext(u"Unknown key {0} signed {1} commit",
 
480
                               u"Unknown key {0} signed {1} commits",
 
481
                               number).format(fingerprint, number))
 
482
    return result