/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

Convert more stuff to use config stacks.

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