/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 bzrlib/gpg.py

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 
22
22
import os
23
23
import sys
 
24
from StringIO import StringIO
24
25
 
25
 
from breezy.lazy_import import lazy_import
 
26
from bzrlib.lazy_import import lazy_import
26
27
lazy_import(globals(), """
27
28
import errno
28
29
import subprocess
29
30
 
30
 
from breezy import (
 
31
from bzrlib import (
31
32
    config,
 
33
    errors,
32
34
    trace,
33
35
    ui,
34
36
    )
35
 
from breezy.i18n import (
36
 
    gettext,
 
37
from bzrlib.i18n import (
 
38
    gettext, 
37
39
    ngettext,
38
40
    )
39
41
""")
40
42
 
41
 
from . import (
42
 
    errors,
43
 
    )
44
 
from .sixish import (
45
 
    BytesIO,
 
43
from bzrlib.symbol_versioning import (
 
44
    deprecated_in,
 
45
    deprecated_method,
46
46
    )
47
47
 
48
48
#verification results
52
52
SIGNATURE_NOT_SIGNED = 3
53
53
SIGNATURE_EXPIRED = 4
54
54
 
55
 
MODE_NORMAL = 0
56
 
MODE_DETACH = 1
57
 
MODE_CLEAR = 2
58
 
 
59
 
 
60
 
class GpgNotInstalled(errors.DependencyNotPresent):
61
 
 
62
 
    _fmt = 'python-gpg is not installed, it is needed to verify signatures'
63
 
 
64
 
    def __init__(self, error):
65
 
        errors.DependencyNotPresent.__init__(self, 'gpg', error)
66
 
 
67
 
 
68
 
class SigningFailed(errors.BzrError):
69
 
 
70
 
    _fmt = 'Failed to GPG sign data: "%(error)s"'
71
 
 
72
 
    def __init__(self, error):
73
 
        errors.BzrError.__init__(self, error=error)
74
 
 
75
 
 
76
 
class SignatureVerificationFailed(errors.BzrError):
77
 
 
78
 
    _fmt = 'Failed to verify GPG signature data with error "%(error)s"'
79
 
 
80
 
    def __init__(self, error):
81
 
        errors.BzrError.__init__(self, error=error)
82
 
 
83
55
 
84
56
def bulk_verify_signatures(repository, revids, strategy,
85
57
        process_events_callback=None):
103
75
    result = []
104
76
    all_verifiable = True
105
77
    total = len(revids)
106
 
    with ui.ui_factory.nested_progress_bar() as pb:
 
78
    pb = ui.ui_factory.nested_progress_bar()
 
79
    try:
107
80
        for i, (rev_id, verification_result, uid) in enumerate(
108
81
                repository.verify_revision_signatures(
109
82
                    revids, strategy)):
114
87
                all_verifiable = False
115
88
            if process_events_callback is not None:
116
89
                process_events_callback()
 
90
    finally:
 
91
        pb.finished()
117
92
    return (count, result, all_verifiable)
118
93
 
119
94
 
127
102
    def __init__(self, ignored):
128
103
        """Real strategies take a configuration."""
129
104
 
130
 
    def sign(self, content, mode):
131
 
        raise SigningFailed('Signing is disabled.')
 
105
    def sign(self, content):
 
106
        raise errors.SigningFailed('Signing is disabled.')
132
107
 
133
 
    def verify(self, signed_data, signature=None):
134
 
        raise SignatureVerificationFailed('Signature verification is \
 
108
    def verify(self, content, testament):
 
109
        raise errors.SignatureVerificationFailed('Signature verification is \
135
110
disabled.')
136
111
 
137
112
    def set_acceptable_keys(self, command_line_input):
150
125
    def __init__(self, ignored):
151
126
        """Real strategies take a configuration."""
152
127
 
153
 
    def sign(self, content, mode):
 
128
    def sign(self, content):
154
129
        return ("-----BEGIN PSEUDO-SIGNED CONTENT-----\n" + content +
155
130
                "-----END PSEUDO-SIGNED CONTENT-----\n")
156
131
 
157
 
    def verify(self, signed_data, signature=None):
158
 
        plain_text = signed_data.replace("-----BEGIN PSEUDO-SIGNED CONTENT-----\n", "")
159
 
        plain_text = plain_text.replace("-----END PSEUDO-SIGNED CONTENT-----\n", "")
160
 
        return SIGNATURE_VALID, None, plain_text
 
132
    def verify(self, content, testament):
 
133
        return SIGNATURE_VALID, None
161
134
 
162
135
    def set_acceptable_keys(self, command_line_input):
163
136
        if command_line_input is not None:
169
142
                else:
170
143
                    self.acceptable_keys.append(pattern)
171
144
 
 
145
    @deprecated_method(deprecated_in((2, 6, 0)))
 
146
    def do_verifications(self, revisions, repository):
 
147
        return bulk_verify_signatures(repository, revisions, self)
 
148
 
 
149
    @deprecated_method(deprecated_in((2, 6, 0)))
 
150
    def valid_commits_message(self, count):
 
151
        return valid_commits_message(count)
 
152
 
 
153
    @deprecated_method(deprecated_in((2, 6, 0)))
 
154
    def unknown_key_message(self, count):
 
155
        return unknown_key_message(count)
 
156
 
 
157
    @deprecated_method(deprecated_in((2, 6, 0)))
 
158
    def commit_not_valid_message(self, count):
 
159
        return commit_not_valid_message(count)
 
160
 
 
161
    @deprecated_method(deprecated_in((2, 6, 0)))
 
162
    def commit_not_signed_message(self, count):
 
163
        return commit_not_signed_message(count)
 
164
 
 
165
    @deprecated_method(deprecated_in((2, 6, 0)))
 
166
    def expired_commit_message(self, count):
 
167
        return expired_commit_message(count)
 
168
 
172
169
 
173
170
def _set_gpg_tty():
174
171
    tty = os.environ.get('TTY')
178
175
    else:
179
176
        # This is not quite worthy of a warning, because some people
180
177
        # don't need GPG_TTY to be set. But it is worthy of a big mark
181
 
        # in ~/.brz.log, so that people can debug it if it happens to them
 
178
        # in ~/.bzr.log, so that people can debug it if it happens to them
182
179
        trace.mutter('** Env var TTY empty, cannot set GPG_TTY.'
183
180
                     '  Is TTY exported?')
184
181
 
191
188
    def __init__(self, config_stack):
192
189
        self._config_stack = config_stack
193
190
        try:
194
 
            import gpg
195
 
            self.context = gpg.Context()
196
 
            self.context.armor = True
197
 
            self.context.signers = self._get_signing_keys()
198
 
        except ImportError as error:
 
191
            import gpgme
 
192
            self.context = gpgme.Context()
 
193
        except ImportError, error:
199
194
            pass # can't use verify()
200
195
 
201
 
    def _get_signing_keys(self):
202
 
        import gpg
203
 
        keyname = self._config_stack.get('gpg_signing_key')
204
 
        if keyname:
205
 
            try:
206
 
                return [self.context.get_key(keyname)]
207
 
            except gpg.errors.KeyNotFound:
208
 
                pass
209
 
 
210
 
        if keyname is None or keyname == 'default':
211
 
            # 'default' or not setting gpg_signing_key at all means we should
212
 
            # use the user email address
213
 
            keyname = config.extract_email_address(self._config_stack.get('email'))
214
 
        possible_keys = self.context.keylist(keyname, secret=True)
215
 
        try:
216
 
            return [possible_keys.next()]
217
 
        except StopIteration:
218
 
            return []
219
 
 
220
196
    @staticmethod
221
197
    def verify_signatures_available():
222
198
        """
225
201
        :return: boolean if this strategy can verify signatures
226
202
        """
227
203
        try:
228
 
            import gpg
 
204
            import gpgme
229
205
            return True
230
 
        except ImportError as error:
 
206
        except ImportError, error:
231
207
            return False
232
208
 
233
 
    def sign(self, content, mode):
234
 
        import gpg
 
209
    def _command_line(self):
 
210
        key = self._config_stack.get('gpg_signing_key')
 
211
        if key is None or key == 'default':
 
212
            # 'default' or not setting gpg_signing_key at all means we should
 
213
            # use the user email address
 
214
            key = config.extract_email_address(self._config_stack.get('email'))
 
215
        return [self._config_stack.get('gpg_signing_command'), '--clearsign',
 
216
                '-u', key]
 
217
 
 
218
    def sign(self, content):
235
219
        if isinstance(content, unicode):
236
220
            raise errors.BzrBadParameterUnicode('content')
 
221
        ui.ui_factory.clear_term()
237
222
 
238
 
        plain_text = gpg.Data(content)
 
223
        preexec_fn = _set_gpg_tty
 
224
        if sys.platform == 'win32':
 
225
            # Win32 doesn't support preexec_fn, but wouldn't support TTY anyway.
 
226
            preexec_fn = None
239
227
        try:
240
 
            output, result = self.context.sign(
241
 
                plain_text, mode={
242
 
                    MODE_DETACH: gpg.constants.sig.mode.DETACH,
243
 
                    MODE_CLEAR: gpg.constants.sig.mode.CLEAR,
244
 
                    MODE_NORMAL: gpg.constants.sig.mode.NORMAL,
245
 
                    }[mode])
246
 
        except gpg.errors.GPGMEError as error:
247
 
            raise SigningFailed(str(error))
248
 
 
249
 
        return output
250
 
 
251
 
    def verify(self, signed_data, signature=None):
 
228
            process = subprocess.Popen(self._command_line(),
 
229
                                       stdin=subprocess.PIPE,
 
230
                                       stdout=subprocess.PIPE,
 
231
                                       preexec_fn=preexec_fn)
 
232
            try:
 
233
                result = process.communicate(content)[0]
 
234
                if process.returncode is None:
 
235
                    process.wait()
 
236
                if process.returncode != 0:
 
237
                    raise errors.SigningFailed(self._command_line())
 
238
                return result
 
239
            except OSError, e:
 
240
                if e.errno == errno.EPIPE:
 
241
                    raise errors.SigningFailed(self._command_line())
 
242
                else:
 
243
                    raise
 
244
        except ValueError:
 
245
            # bad subprocess parameters, should never happen.
 
246
            raise
 
247
        except OSError, e:
 
248
            if e.errno == errno.ENOENT:
 
249
                # gpg is not installed
 
250
                raise errors.SigningFailed(self._command_line())
 
251
            else:
 
252
                raise
 
253
 
 
254
    def verify(self, content, testament):
252
255
        """Check content has a valid signature.
253
256
 
254
 
        :param signed_data; Signed data
255
 
        :param signature: optional signature (if detached)
 
257
        :param content: the commit signature
 
258
        :param testament: the valid testament string for the commit
256
259
 
257
 
        :return: SIGNATURE_VALID or a failed SIGNATURE_ value, key uid if valid, plain text
 
260
        :return: SIGNATURE_VALID or a failed SIGNATURE_ value, key uid if valid
258
261
        """
259
262
        try:
260
 
            import gpg
261
 
        except ImportError as error:
262
 
            raise errors.GpgNotInstalled(error)
 
263
            import gpgme
 
264
        except ImportError, error:
 
265
            raise errors.GpgmeNotInstalled(error)
263
266
 
264
 
        signed_data = gpg.Data(signed_data)
265
 
        if signature:
266
 
            signature = gpg.Data(signature)
 
267
        signature = StringIO(content)
 
268
        plain_output = StringIO()
267
269
        try:
268
 
            plain_output, result = self.context.verify(signed_data, signature)
269
 
        except gpg.errors.BadSignatures as error:
270
 
            fingerprint = error.result.signatures[0].fpr
271
 
            if error.result.signatures[0].summary & gpg.constants.SIGSUM_KEY_EXPIRED:
272
 
                expires = self.context.get_key(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
277
 
                else:
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 & gpg.constants.SIGSUM_KEY_MISSING:
285
 
                return SIGNATURE_KEY_MISSING, fingerprint[-8:], None
286
 
 
287
 
            return SIGNATURE_NOT_VALID, None, None
288
 
        except gpg.errors.GPGMEError as error:
289
 
            raise SignatureVerificationFailed(error)
 
270
            result = self.context.verify(signature, None, plain_output)
 
271
        except gpgme.GpgmeError,error:
 
272
            raise errors.SignatureVerificationFailed(error[2])
290
273
 
291
274
        # No result if input is invalid.
292
275
        # test_verify_invalid()
293
 
        if len(result.signatures) == 0:
294
 
            return SIGNATURE_NOT_VALID, None, plain_output
295
 
 
 
276
        if len(result) == 0:
 
277
            return SIGNATURE_NOT_VALID, None
296
278
        # User has specified a list of acceptable keys, check our result is in
297
279
        # it.  test_verify_unacceptable_key()
298
 
        fingerprint = result.signatures[0].fpr
 
280
        fingerprint = result[0].fpr
299
281
        if self.acceptable_keys is not None:
300
282
            if not fingerprint in self.acceptable_keys:
301
 
                return SIGNATURE_KEY_MISSING, fingerprint[-8:], plain_output
302
 
        # Yay gpg set the valid bit.
 
283
                return SIGNATURE_KEY_MISSING, fingerprint[-8:]
 
284
        # Check the signature actually matches the testament.
 
285
        # test_verify_bad_testament()
 
286
        if testament != plain_output.getvalue():
 
287
            return SIGNATURE_NOT_VALID, None
 
288
        # Yay gpgme set the valid bit.
303
289
        # Can't write a test for this one as you can't set a key to be
304
 
        # trusted using gpg.
305
 
        if result.signatures[0].summary & gpg.constants.SIGSUM_VALID:
 
290
        # trusted using gpgme.
 
291
        if result[0].summary & gpgme.SIGSUM_VALID:
306
292
            key = self.context.get_key(fingerprint)
307
293
            name = key.uids[0].name
308
294
            email = key.uids[0].email
309
 
            return SIGNATURE_VALID, name.decode('utf-8') + u" <" + email.decode('utf-8') + u">", plain_output
 
295
            return SIGNATURE_VALID, name + " <" + email + ">"
310
296
        # Sigsum_red indicates a problem, unfortunatly I have not been able
311
297
        # to write any tests which actually set this.
312
 
        if result.signatures[0].summary & gpg.constants.SIGSUM_RED:
313
 
            return SIGNATURE_NOT_VALID, None, plain_output
 
298
        if result[0].summary & gpgme.SIGSUM_RED:
 
299
            return SIGNATURE_NOT_VALID, None
 
300
        # GPG does not know this key.
 
301
        # test_verify_unknown_key()
 
302
        if result[0].summary & gpgme.SIGSUM_KEY_MISSING:
 
303
            return SIGNATURE_KEY_MISSING, fingerprint[-8:]
314
304
        # Summary isn't set if sig is valid but key is untrusted but if user
315
305
        # has explicity set the key as acceptable we can validate it.
316
 
        if result.signatures[0].summary == 0 and self.acceptable_keys is not None:
 
306
        if result[0].summary == 0 and self.acceptable_keys is not None:
317
307
            if fingerprint in self.acceptable_keys:
318
308
                # test_verify_untrusted_but_accepted()
319
 
                return SIGNATURE_VALID, None, plain_output
 
309
                return SIGNATURE_VALID, None
320
310
        # test_verify_valid_but_untrusted()
321
 
        if result.signatures[0].summary == 0 and self.acceptable_keys is None:
322
 
            return SIGNATURE_NOT_VALID, None, plain_output
 
311
        if result[0].summary == 0 and self.acceptable_keys is None:
 
312
            return SIGNATURE_NOT_VALID, None
 
313
        if result[0].summary & gpgme.SIGSUM_KEY_EXPIRED:
 
314
            expires = self.context.get_key(result[0].fpr).subkeys[0].expires
 
315
            if expires > result[0].timestamp:
 
316
                # The expired key was not expired at time of signing.
 
317
                # test_verify_expired_but_valid()
 
318
                return SIGNATURE_EXPIRED, fingerprint[-8:]
 
319
            else:
 
320
                # I can't work out how to create a test where the signature
 
321
                # was expired at the time of signing.
 
322
                return SIGNATURE_NOT_VALID, None
 
323
        # A signature from a revoked key gets this.
 
324
        # test_verify_revoked_signature()
 
325
        if ((result[0].summary & gpgme.SIGSUM_SYS_ERROR
 
326
             or result[0].status.strerror == 'Certificate revoked')):
 
327
            return SIGNATURE_NOT_VALID, None
323
328
        # Other error types such as revoked keys should (I think) be caught by
324
329
        # SIGSUM_RED so anything else means something is buggy.
325
 
        raise SignatureVerificationFailed(
 
330
        raise errors.SignatureVerificationFailed(
326
331
            "Unknown GnuPG key verification result")
327
332
 
328
333
    def set_acceptable_keys(self, command_line_input):
353
358
                            "No GnuPG key results for pattern: {0}"
354
359
                                ).format(pattern))
355
360
 
 
361
    @deprecated_method(deprecated_in((2, 6, 0)))
 
362
    def do_verifications(self, revisions, repository,
 
363
                            process_events_callback=None):
 
364
        """do verifications on a set of revisions
 
365
 
 
366
        :param revisions: list of revision ids to verify
 
367
        :param repository: repository object
 
368
        :param process_events_callback: method to call for GUI frontends that
 
369
            want to keep their UI refreshed
 
370
 
 
371
        :return: count dictionary of results of each type,
 
372
                 result list for each revision,
 
373
                 boolean True if all results are verified successfully
 
374
        """
 
375
        return bulk_verify_signatures(repository, revisions, self,
 
376
            process_events_callback)
 
377
 
 
378
    @deprecated_method(deprecated_in((2, 6, 0)))
 
379
    def verbose_valid_message(self, result):
 
380
        """takes a verify result and returns list of signed commits strings"""
 
381
        return verbose_valid_message(result)
 
382
 
 
383
    @deprecated_method(deprecated_in((2, 6, 0)))
 
384
    def verbose_not_valid_message(self, result, repo):
 
385
        """takes a verify result and returns list of not valid commit info"""
 
386
        return verbose_not_valid_message(result, repo)
 
387
 
 
388
    @deprecated_method(deprecated_in((2, 6, 0)))
 
389
    def verbose_not_signed_message(self, result, repo):
 
390
        """takes a verify result and returns list of not signed commit info"""
 
391
        return verbose_not_valid_message(result, repo)
 
392
 
 
393
    @deprecated_method(deprecated_in((2, 6, 0)))
 
394
    def verbose_missing_key_message(self, result):
 
395
        """takes a verify result and returns list of missing key info"""
 
396
        return verbose_missing_key_message(result)
 
397
 
 
398
    @deprecated_method(deprecated_in((2, 6, 0)))
 
399
    def verbose_expired_key_message(self, result, repo):
 
400
        """takes a verify result and returns list of expired key info"""
 
401
        return verbose_expired_key_message(result, repo)
 
402
 
 
403
    @deprecated_method(deprecated_in((2, 6, 0)))
 
404
    def valid_commits_message(self, count):
 
405
        """returns message for number of commits"""
 
406
        return valid_commits_message(count)
 
407
 
 
408
    @deprecated_method(deprecated_in((2, 6, 0)))
 
409
    def unknown_key_message(self, count):
 
410
        """returns message for number of commits"""
 
411
        return unknown_key_message(count)
 
412
 
 
413
    @deprecated_method(deprecated_in((2, 6, 0)))
 
414
    def commit_not_valid_message(self, count):
 
415
        """returns message for number of commits"""
 
416
        return commit_not_valid_message(count)
 
417
 
 
418
    @deprecated_method(deprecated_in((2, 6, 0)))
 
419
    def commit_not_signed_message(self, count):
 
420
        """returns message for number of commits"""
 
421
        return commit_not_signed_message(count)
 
422
 
 
423
    @deprecated_method(deprecated_in((2, 6, 0)))
 
424
    def expired_commit_message(self, count):
 
425
        """returns message for number of commits"""
 
426
        return expired_commit_message(count)
 
427
 
356
428
 
357
429
def valid_commits_message(count):
358
430
    """returns message for number of commits"""
470
542
            signers.setdefault(fingerprint, 0)
471
543
            signers[fingerprint] += 1
472
544
    result = []
473
 
    for fingerprint, number in list(signers.items()):
 
545
    for fingerprint, number in signers.items():
474
546
        result.append(ngettext(u"Unknown key {0} signed {1} commit",
475
547
                               u"Unknown key {0} signed {1} commits",
476
548
                               number).format(fingerprint, number))