~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/gpg.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-16 19:18:39 UTC
  • mto: This revision was merged to the branch mainline in revision 6391.
  • Revision ID: jelmer@samba.org-20111216191839-eg681lxqibi1qxu1
Fix remaining tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005, 2011 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
19
19
 
20
20
import os
21
21
import sys
 
22
from StringIO import StringIO
22
23
 
23
24
from bzrlib.lazy_import import lazy_import
24
25
lazy_import(globals(), """
26
27
import subprocess
27
28
 
28
29
from bzrlib import (
 
30
    config,
29
31
    errors,
30
32
    trace,
31
33
    ui,
32
34
    )
 
35
from bzrlib.i18n import (
 
36
    gettext, 
 
37
    ngettext,
 
38
    )
33
39
""")
34
40
 
 
41
#verification results
 
42
SIGNATURE_VALID = 0
 
43
SIGNATURE_KEY_MISSING = 1
 
44
SIGNATURE_NOT_VALID = 2
 
45
SIGNATURE_NOT_SIGNED = 3
 
46
SIGNATURE_EXPIRED = 4
 
47
 
35
48
 
36
49
class DisabledGPGStrategy(object):
37
50
    """A GPG Strategy that makes everything fail."""
38
51
 
 
52
    @staticmethod
 
53
    def verify_signatures_available():
 
54
        return True
 
55
 
39
56
    def __init__(self, ignored):
40
57
        """Real strategies take a configuration."""
41
58
 
42
59
    def sign(self, content):
43
60
        raise errors.SigningFailed('Signing is disabled.')
44
61
 
 
62
    def verify(self, content, testament):
 
63
        raise errors.SignatureVerificationFailed('Signature verification is \
 
64
disabled.')
 
65
 
 
66
    def set_acceptable_keys(self, command_line_input):
 
67
        pass
 
68
 
45
69
 
46
70
class LoopbackGPGStrategy(object):
47
 
    """A GPG Strategy that acts like 'cat' - data is just passed through."""
 
71
    """A GPG Strategy that acts like 'cat' - data is just passed through.
 
72
    Used in tests.
 
73
    """
 
74
 
 
75
    @staticmethod
 
76
    def verify_signatures_available():
 
77
        return True
48
78
 
49
79
    def __init__(self, ignored):
50
80
        """Real strategies take a configuration."""
53
83
        return ("-----BEGIN PSEUDO-SIGNED CONTENT-----\n" + content +
54
84
                "-----END PSEUDO-SIGNED CONTENT-----\n")
55
85
 
 
86
    def verify(self, content, testament):
 
87
        return SIGNATURE_VALID, None
 
88
 
 
89
    def set_acceptable_keys(self, command_line_input):
 
90
        if command_line_input is not None:
 
91
            patterns = command_line_input.split(",")
 
92
            self.acceptable_keys = []
 
93
            for pattern in patterns:
 
94
                if pattern == "unknown":
 
95
                    pass
 
96
                else:
 
97
                    self.acceptable_keys.append(pattern)
 
98
 
 
99
    def do_verifications(self, revisions, repository):
 
100
        count = {SIGNATURE_VALID: 0,
 
101
                 SIGNATURE_KEY_MISSING: 0,
 
102
                 SIGNATURE_NOT_VALID: 0,
 
103
                 SIGNATURE_NOT_SIGNED: 0,
 
104
                 SIGNATURE_EXPIRED: 0}
 
105
        result = []
 
106
        all_verifiable = True
 
107
        for rev_id in revisions:
 
108
            verification_result, uid =\
 
109
                repository.verify_revision_signature(rev_id,self)
 
110
            result.append([rev_id, verification_result, uid])
 
111
            count[verification_result] += 1
 
112
            if verification_result != SIGNATURE_VALID:
 
113
                all_verifiable = False
 
114
        return (count, result, all_verifiable)
 
115
 
 
116
    def valid_commits_message(self, count):
 
117
        return gettext(u"{0} commits with valid signatures").format(
 
118
                                        count[SIGNATURE_VALID])
 
119
 
 
120
    def unknown_key_message(self, count):
 
121
        return ngettext(u"{0} commit with unknown key",
 
122
                             u"{0} commits with unknown keys",
 
123
                             count[SIGNATURE_KEY_MISSING]).format(
 
124
                                        count[SIGNATURE_KEY_MISSING])
 
125
 
 
126
    def commit_not_valid_message(self, count):
 
127
        return ngettext(u"{0} commit not valid",
 
128
                             u"{0} commits not valid",
 
129
                             count[SIGNATURE_NOT_VALID]).format(
 
130
                                            count[SIGNATURE_NOT_VALID])
 
131
 
 
132
    def commit_not_signed_message(self, count):
 
133
        return ngettext(u"{0} commit not signed",
 
134
                             u"{0} commits not signed",
 
135
                             count[SIGNATURE_NOT_SIGNED]).format(
 
136
                                        count[SIGNATURE_NOT_SIGNED])
 
137
 
 
138
    def expired_commit_message(self, count):
 
139
        return ngettext(u"{0} commit with key now expired",
 
140
                        u"{0} commits with key now expired",
 
141
                        count[SIGNATURE_EXPIRED]).format(
 
142
                                        count[SIGNATURE_EXPIRED])
 
143
 
56
144
 
57
145
def _set_gpg_tty():
58
146
    tty = os.environ.get('TTY')
70
158
class GPGStrategy(object):
71
159
    """GPG Signing and checking facilities."""
72
160
 
 
161
    acceptable_keys = None
 
162
 
 
163
    def __init__(self, config_stack):
 
164
        self._config_stack = config_stack
 
165
        try:
 
166
            import gpgme
 
167
            self.context = gpgme.Context()
 
168
        except ImportError, error:
 
169
            pass # can't use verify()
 
170
 
 
171
    @staticmethod
 
172
    def verify_signatures_available():
 
173
        """
 
174
        check if this strategy can verify signatures
 
175
 
 
176
        :return: boolean if this strategy can verify signatures
 
177
        """
 
178
        try:
 
179
            import gpgme
 
180
            return True
 
181
        except ImportError, error:
 
182
            return False
 
183
 
73
184
    def _command_line(self):
74
 
        return [self._config.gpg_signing_command(), '--clearsign']
75
 
 
76
 
    def __init__(self, config):
77
 
        self._config = config
 
185
        key = self._config_stack.get('gpg_signing_key')
 
186
        if key is None or key == 'default':
 
187
            # 'default' or not setting gpg_signing_key at all means we should
 
188
            # use the user email address
 
189
            key = config.extract_email_address(self._config_stack.get('email'))
 
190
        return [self._config_stack.get('gpg_signing_command'), '--clearsign',
 
191
                '-u', key]
78
192
 
79
193
    def sign(self, content):
80
194
        if isinstance(content, unicode):
111
225
                raise errors.SigningFailed(self._command_line())
112
226
            else:
113
227
                raise
 
228
 
 
229
    def verify(self, content, testament):
 
230
        """Check content has a valid signature.
 
231
        
 
232
        :param content: the commit signature
 
233
        :param testament: the valid testament string for the commit
 
234
        
 
235
        :return: SIGNATURE_VALID or a failed SIGNATURE_ value, key uid if valid
 
236
        """
 
237
        try:
 
238
            import gpgme
 
239
        except ImportError, error:
 
240
            raise errors.GpgmeNotInstalled(error)
 
241
 
 
242
        signature = StringIO(content)
 
243
        plain_output = StringIO()
 
244
        try:
 
245
            result = self.context.verify(signature, None, plain_output)
 
246
        except gpgme.GpgmeError,error:
 
247
            raise errors.SignatureVerificationFailed(error[2])
 
248
 
 
249
        # No result if input is invalid.
 
250
        # test_verify_invalid()
 
251
        if len(result) == 0:
 
252
            return SIGNATURE_NOT_VALID, None
 
253
        # User has specified a list of acceptable keys, check our result is in
 
254
        # it.  test_verify_unacceptable_key()
 
255
        fingerprint = result[0].fpr
 
256
        if self.acceptable_keys is not None:
 
257
            if not fingerprint in self.acceptable_keys:
 
258
                return SIGNATURE_KEY_MISSING, fingerprint[-8:]
 
259
        # Check the signature actually matches the testament.
 
260
        # test_verify_bad_testament()
 
261
        if testament != plain_output.getvalue():
 
262
            return SIGNATURE_NOT_VALID, None
 
263
        # Yay gpgme set the valid bit.
 
264
        # Can't write a test for this one as you can't set a key to be
 
265
        # trusted using gpgme.
 
266
        if result[0].summary & gpgme.SIGSUM_VALID:
 
267
            key = self.context.get_key(fingerprint)
 
268
            name = key.uids[0].name
 
269
            email = key.uids[0].email
 
270
            return SIGNATURE_VALID, name + " <" + email + ">"
 
271
        # Sigsum_red indicates a problem, unfortunatly I have not been able
 
272
        # to write any tests which actually set this.
 
273
        if result[0].summary & gpgme.SIGSUM_RED:
 
274
            return SIGNATURE_NOT_VALID, None
 
275
        # GPG does not know this key.
 
276
        # test_verify_unknown_key()
 
277
        if result[0].summary & gpgme.SIGSUM_KEY_MISSING:
 
278
            return SIGNATURE_KEY_MISSING, fingerprint[-8:]
 
279
        # Summary isn't set if sig is valid but key is untrusted but if user
 
280
        # has explicity set the key as acceptable we can validate it.
 
281
        if result[0].summary == 0 and self.acceptable_keys is not None:
 
282
            if fingerprint in self.acceptable_keys:
 
283
                # test_verify_untrusted_but_accepted()
 
284
                return SIGNATURE_VALID, None
 
285
        # test_verify_valid_but_untrusted()
 
286
        if result[0].summary == 0 and self.acceptable_keys is None:
 
287
            return SIGNATURE_NOT_VALID, None
 
288
        if result[0].summary & gpgme.SIGSUM_KEY_EXPIRED:
 
289
            expires = self.context.get_key(result[0].fpr).subkeys[0].expires
 
290
            if expires > result[0].timestamp:
 
291
                # The expired key was not expired at time of signing.
 
292
                # test_verify_expired_but_valid()
 
293
                return SIGNATURE_EXPIRED, fingerprint[-8:]
 
294
            else:
 
295
                # I can't work out how to create a test where the signature
 
296
                # was expired at the time of signing.
 
297
                return SIGNATURE_NOT_VALID, None
 
298
        # A signature from a revoked key gets this.
 
299
        # test_verify_revoked_signature()
 
300
        if result[0].summary & gpgme.SIGSUM_SYS_ERROR:
 
301
            return SIGNATURE_NOT_VALID, None
 
302
        # Other error types such as revoked keys should (I think) be caught by
 
303
        # SIGSUM_RED so anything else means something is buggy.
 
304
        raise errors.SignatureVerificationFailed("Unknown GnuPG key "\
 
305
                                                 "verification result")
 
306
 
 
307
    def set_acceptable_keys(self, command_line_input):
 
308
        """Set the acceptable keys for verifying with this GPGStrategy.
 
309
        
 
310
        :param command_line_input: comma separated list of patterns from
 
311
                                command line
 
312
        :return: nothing
 
313
        """
 
314
        key_patterns = None
 
315
        acceptable_keys_config = self._config_stack.get('acceptable_keys')
 
316
        try:
 
317
            if isinstance(acceptable_keys_config, unicode):
 
318
                acceptable_keys_config = str(acceptable_keys_config)
 
319
        except UnicodeEncodeError:
 
320
            # gpg Context.keylist(pattern) does not like unicode
 
321
            raise errors.BzrCommandError(
 
322
                gettext('Only ASCII permitted in option names'))
 
323
 
 
324
        if acceptable_keys_config is not None:
 
325
            key_patterns = acceptable_keys_config
 
326
        if command_line_input is not None: # command line overrides config
 
327
            key_patterns = command_line_input
 
328
        if key_patterns is not None:
 
329
            patterns = key_patterns.split(",")
 
330
 
 
331
            self.acceptable_keys = []
 
332
            for pattern in patterns:
 
333
                result = self.context.keylist(pattern)
 
334
                found_key = False
 
335
                for key in result:
 
336
                    found_key = True
 
337
                    self.acceptable_keys.append(key.subkeys[0].fpr)
 
338
                    trace.mutter("Added acceptable key: " + key.subkeys[0].fpr)
 
339
                if not found_key:
 
340
                    trace.note(gettext(
 
341
                            "No GnuPG key results for pattern: {0}"
 
342
                                ).format(pattern))
 
343
 
 
344
    def do_verifications(self, revisions, repository,
 
345
                            process_events_callback=None):
 
346
        """do verifications on a set of revisions
 
347
        
 
348
        :param revisions: list of revision ids to verify
 
349
        :param repository: repository object
 
350
        :param process_events_callback: method to call for GUI frontends that
 
351
                                                want to keep their UI refreshed
 
352
        
 
353
        :return: count dictionary of results of each type,
 
354
                 result list for each revision,
 
355
                 boolean True if all results are verified successfully
 
356
        """
 
357
        count = {SIGNATURE_VALID: 0,
 
358
                 SIGNATURE_KEY_MISSING: 0,
 
359
                 SIGNATURE_NOT_VALID: 0,
 
360
                 SIGNATURE_NOT_SIGNED: 0,
 
361
                 SIGNATURE_EXPIRED: 0}
 
362
        result = []
 
363
        all_verifiable = True
 
364
        for rev_id in revisions:
 
365
            verification_result, uid =\
 
366
                repository.verify_revision_signature(rev_id, self)
 
367
            result.append([rev_id, verification_result, uid])
 
368
            count[verification_result] += 1
 
369
            if verification_result != SIGNATURE_VALID:
 
370
                all_verifiable = False
 
371
            if process_events_callback is not None:
 
372
                process_events_callback()
 
373
        return (count, result, all_verifiable)
 
374
 
 
375
    def verbose_valid_message(self, result):
 
376
        """takes a verify result and returns list of signed commits strings"""
 
377
        signers = {}
 
378
        for rev_id, validity, uid in result:
 
379
            if validity == SIGNATURE_VALID:
 
380
                signers.setdefault(uid, 0)
 
381
                signers[uid] += 1
 
382
        result = []
 
383
        for uid, number in signers.items():
 
384
             result.append( ngettext(u"{0} signed {1} commit",
 
385
                             u"{0} signed {1} commits",
 
386
                             number).format(uid, number) )
 
387
        return result
 
388
 
 
389
 
 
390
    def verbose_not_valid_message(self, result, repo):
 
391
        """takes a verify result and returns list of not valid commit info"""
 
392
        signers = {}
 
393
        for rev_id, validity, empty in result:
 
394
            if validity == SIGNATURE_NOT_VALID:
 
395
                revision = repo.get_revision(rev_id)
 
396
                authors = ', '.join(revision.get_apparent_authors())
 
397
                signers.setdefault(authors, 0)
 
398
                signers[authors] += 1
 
399
        result = []
 
400
        for authors, number in signers.items():
 
401
            result.append( ngettext(u"{0} commit by author {1}",
 
402
                                 u"{0} commits by author {1}",
 
403
                                 number).format(number, authors) )
 
404
        return result
 
405
 
 
406
    def verbose_not_signed_message(self, result, repo):
 
407
        """takes a verify result and returns list of not signed commit info"""
 
408
        signers = {}
 
409
        for rev_id, validity, empty in result:
 
410
            if validity == SIGNATURE_NOT_SIGNED:
 
411
                revision = repo.get_revision(rev_id)
 
412
                authors = ', '.join(revision.get_apparent_authors())
 
413
                signers.setdefault(authors, 0)
 
414
                signers[authors] += 1
 
415
        result = []
 
416
        for authors, number in signers.items():
 
417
            result.append( ngettext(u"{0} commit by author {1}",
 
418
                                 u"{0} commits by author {1}",
 
419
                                 number).format(number, authors) )
 
420
        return result
 
421
 
 
422
    def verbose_missing_key_message(self, result):
 
423
        """takes a verify result and returns list of missing key info"""
 
424
        signers = {}
 
425
        for rev_id, validity, fingerprint in result:
 
426
            if validity == SIGNATURE_KEY_MISSING:
 
427
                signers.setdefault(fingerprint, 0)
 
428
                signers[fingerprint] += 1
 
429
        result = []
 
430
        for fingerprint, number in signers.items():
 
431
            result.append( ngettext(u"Unknown key {0} signed {1} commit",
 
432
                                 u"Unknown key {0} signed {1} commits",
 
433
                                 number).format(fingerprint, number) )
 
434
        return result
 
435
 
 
436
    def verbose_expired_key_message(self, result, repo):
 
437
        """takes a verify result and returns list of expired key info"""
 
438
        signers = {}
 
439
        fingerprint_to_authors = {}
 
440
        for rev_id, validity, fingerprint in result:
 
441
            if validity == SIGNATURE_EXPIRED:
 
442
                revision = repo.get_revision(rev_id)
 
443
                authors = ', '.join(revision.get_apparent_authors())
 
444
                signers.setdefault(fingerprint, 0)
 
445
                signers[fingerprint] += 1
 
446
                fingerprint_to_authors[fingerprint] = authors
 
447
        result = []
 
448
        for fingerprint, number in signers.items():
 
449
            result.append(
 
450
                ngettext(u"{0} commit by author {1} with key {2} now expired",
 
451
                         u"{0} commits by author {1} with key {2} now expired",
 
452
                         number).format(
 
453
                    number, fingerprint_to_authors[fingerprint], fingerprint) )
 
454
        return result
 
455
 
 
456
    def valid_commits_message(self, count):
 
457
        """returns message for number of commits"""
 
458
        return gettext(u"{0} commits with valid signatures").format(
 
459
                                        count[SIGNATURE_VALID])
 
460
 
 
461
    def unknown_key_message(self, count):
 
462
        """returns message for number of commits"""
 
463
        return ngettext(u"{0} commit with unknown key",
 
464
                        u"{0} commits with unknown keys",
 
465
                        count[SIGNATURE_KEY_MISSING]).format(
 
466
                                        count[SIGNATURE_KEY_MISSING])
 
467
 
 
468
    def commit_not_valid_message(self, count):
 
469
        """returns message for number of commits"""
 
470
        return ngettext(u"{0} commit not valid",
 
471
                        u"{0} commits not valid",
 
472
                        count[SIGNATURE_NOT_VALID]).format(
 
473
                                            count[SIGNATURE_NOT_VALID])
 
474
 
 
475
    def commit_not_signed_message(self, count):
 
476
        """returns message for number of commits"""
 
477
        return ngettext(u"{0} commit not signed",
 
478
                        u"{0} commits not signed",
 
479
                        count[SIGNATURE_NOT_SIGNED]).format(
 
480
                                        count[SIGNATURE_NOT_SIGNED])
 
481
 
 
482
    def expired_commit_message(self, count):
 
483
        """returns message for number of commits"""
 
484
        return ngettext(u"{0} commit with key now expired",
 
485
                        u"{0} commits with key now expired",
 
486
                        count[SIGNATURE_EXPIRED]).format(
 
487
                                    count[SIGNATURE_EXPIRED])