/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: 2017-08-26 18:51:21 UTC
  • mto: This revision was merged to the branch mainline in revision 6773.
  • Revision ID: jelmer@jelmer.uk-20170826185121-v6f5y9t77l4eghqo
Remove saved_state.

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