/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-06-08 23:30:31 UTC
  • mto: This revision was merged to the branch mainline in revision 6690.
  • Revision ID: jelmer@jelmer.uk-20170608233031-3qavls2o7a1pqllj
Update imports.

Show diffs side-by-side

added added

removed removed

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