18
18
"""GPG signing and checking logic."""
20
from __future__ import absolute_import
23
from bzrlib.lazy_import import lazy_import
24
from breezy.lazy_import import lazy_import
24
25
lazy_import(globals(), """
31
from breezy.i18n import (
46
SIGNATURE_KEY_MISSING = 1
47
SIGNATURE_NOT_VALID = 2
48
SIGNATURE_NOT_SIGNED = 3
56
class GpgNotInstalled(errors.DependencyNotPresent):
58
_fmt = 'python-gpg is not installed, it is needed to verify signatures'
60
def __init__(self, error):
61
errors.DependencyNotPresent.__init__(self, 'gpg', error)
64
class SigningFailed(errors.BzrError):
66
_fmt = 'Failed to GPG sign data: "%(error)s"'
68
def __init__(self, error):
69
errors.BzrError.__init__(self, error=error)
72
class SignatureVerificationFailed(errors.BzrError):
74
_fmt = 'Failed to verify GPG signature data with error "%(error)s"'
76
def __init__(self, error):
77
errors.BzrError.__init__(self, error=error)
80
def bulk_verify_signatures(repository, revids, strategy,
81
process_events_callback=None):
82
"""Do verifications on a set of revisions
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
90
:return: count dictionary of results of each type,
91
result list for each revision,
92
boolean True if all results are verified successfully
94
count = {SIGNATURE_VALID: 0,
95
SIGNATURE_KEY_MISSING: 0,
96
SIGNATURE_NOT_VALID: 0,
97
SIGNATURE_NOT_SIGNED: 0,
100
all_verifiable = True
102
with ui.ui_factory.nested_progress_bar() as pb:
103
for i, (rev_id, verification_result, uid) in enumerate(
104
repository.verify_revision_signatures(
106
pb.update("verifying signatures", i, total)
107
result.append([rev_id, verification_result, uid])
108
count[verification_result] += 1
109
if verification_result != SIGNATURE_VALID:
110
all_verifiable = False
111
if process_events_callback is not None:
112
process_events_callback()
113
return (count, result, all_verifiable)
36
116
class DisabledGPGStrategy(object):
37
117
"""A GPG Strategy that makes everything fail."""
120
def verify_signatures_available():
39
123
def __init__(self, ignored):
40
124
"""Real strategies take a configuration."""
42
def sign(self, content):
43
raise errors.SigningFailed('Signing is disabled.')
126
def sign(self, content, mode):
127
raise SigningFailed('Signing is disabled.')
129
def verify(self, signed_data, signature=None):
130
raise SignatureVerificationFailed('Signature verification is \
133
def set_acceptable_keys(self, command_line_input):
46
137
class LoopbackGPGStrategy(object):
47
"""A GPG Strategy that acts like 'cat' - data is just passed through."""
138
"""A GPG Strategy that acts like 'cat' - data is just passed through.
143
def verify_signatures_available():
49
146
def __init__(self, ignored):
50
147
"""Real strategies take a configuration."""
52
def sign(self, content):
53
return ("-----BEGIN PSEUDO-SIGNED CONTENT-----\n" + content +
54
"-----END PSEUDO-SIGNED CONTENT-----\n")
149
def sign(self, content, mode):
150
return (b"-----BEGIN PSEUDO-SIGNED CONTENT-----\n" + content +
151
b"-----END PSEUDO-SIGNED CONTENT-----\n")
153
def verify(self, signed_data, signature=None):
154
plain_text = signed_data.replace(b"-----BEGIN PSEUDO-SIGNED CONTENT-----\n", b"")
155
plain_text = plain_text.replace(b"-----END PSEUDO-SIGNED CONTENT-----\n", b"")
156
return SIGNATURE_VALID, None, plain_text
158
def set_acceptable_keys(self, command_line_input):
159
if command_line_input is not None:
160
patterns = command_line_input.split(",")
161
self.acceptable_keys = []
162
for pattern in patterns:
163
if pattern == "unknown":
166
self.acceptable_keys.append(pattern)
57
169
def _set_gpg_tty():
70
182
class GPGStrategy(object):
71
183
"""GPG Signing and checking facilities."""
73
def _command_line(self):
74
return [self._config.gpg_signing_command(), '--clearsign']
76
def __init__(self, config):
79
def sign(self, content):
80
if isinstance(content, unicode):
185
acceptable_keys = None
187
def __init__(self, config_stack):
188
self._config_stack = config_stack
191
self.context = gpg.Context()
192
self.context.armor = True
193
self.context.signers = self._get_signing_keys()
194
except ImportError as error:
195
pass # can't use verify()
197
def _get_signing_keys(self):
199
keyname = self._config_stack.get('gpg_signing_key')
202
return [self.context.get_key(keyname)]
203
except gpg.errors.KeyNotFound:
206
if keyname is None or keyname == 'default':
207
# 'default' or not setting gpg_signing_key at all means we should
208
# use the user email address
209
keyname = config.extract_email_address(self._config_stack.get('email'))
210
possible_keys = self.context.keylist(keyname, secret=True)
212
return [next(possible_keys)]
213
except StopIteration:
217
def verify_signatures_available():
219
check if this strategy can verify signatures
221
:return: boolean if this strategy can verify signatures
224
import gpg # noqa: F401
226
except ImportError as error:
229
def sign(self, content, mode):
231
if isinstance(content, text_type):
81
232
raise errors.BzrBadParameterUnicode('content')
82
ui.ui_factory.clear_term()
84
preexec_fn = _set_gpg_tty
85
if sys.platform == 'win32':
86
# Win32 doesn't support preexec_fn, but wouldn't support TTY anyway.
89
process = subprocess.Popen(self._command_line(),
90
stdin=subprocess.PIPE,
91
stdout=subprocess.PIPE,
92
preexec_fn=preexec_fn)
94
result = process.communicate(content)[0]
95
if process.returncode is None:
97
if process.returncode != 0:
98
raise errors.SigningFailed(self._command_line())
101
if e.errno == errno.EPIPE:
102
raise errors.SigningFailed(self._command_line())
234
plain_text = gpg.Data(content)
236
output, result = self.context.sign(
238
MODE_DETACH: gpg.constants.sig.mode.DETACH,
239
MODE_CLEAR: gpg.constants.sig.mode.CLEAR,
240
MODE_NORMAL: gpg.constants.sig.mode.NORMAL,
242
except gpg.errors.GPGMEError as error:
243
raise SigningFailed(str(error))
247
def verify(self, signed_data, signature=None):
248
"""Check content has a valid signature.
250
:param signed_data; Signed data
251
:param signature: optional signature (if detached)
253
:return: SIGNATURE_VALID or a failed SIGNATURE_ value, key uid if valid, plain text
257
except ImportError as error:
258
raise errors.GpgNotInstalled(error)
260
signed_data = gpg.Data(signed_data)
262
signature = gpg.Data(signature)
264
plain_output, result = self.context.verify(signed_data, signature)
265
except gpg.errors.BadSignatures as error:
266
fingerprint = error.result.signatures[0].fpr
267
if error.result.signatures[0].summary & gpg.constants.SIGSUM_KEY_EXPIRED:
268
expires = self.context.get_key(error.result.signatures[0].fpr).subkeys[0].expires
269
if expires > error.result.signatures[0].timestamp:
270
# The expired key was not expired at time of signing.
271
# test_verify_expired_but_valid()
272
return SIGNATURE_EXPIRED, fingerprint[-8:], None
106
# bad subprocess parameters, should never happen.
109
if e.errno == errno.ENOENT:
110
# gpg is not installed
111
raise errors.SigningFailed(self._command_line())
274
# I can't work out how to create a test where the signature
275
# was expired at the time of signing.
276
return SIGNATURE_NOT_VALID, None, None
278
# GPG does not know this key.
279
# test_verify_unknown_key()
280
if error.result.signatures[0].summary & gpg.constants.SIGSUM_KEY_MISSING:
281
return SIGNATURE_KEY_MISSING, fingerprint[-8:], None
283
return SIGNATURE_NOT_VALID, None, None
284
except gpg.errors.GPGMEError as error:
285
raise SignatureVerificationFailed(error)
287
# No result if input is invalid.
288
# test_verify_invalid()
289
if len(result.signatures) == 0:
290
return SIGNATURE_NOT_VALID, None, plain_output
292
# User has specified a list of acceptable keys, check our result is in
293
# it. test_verify_unacceptable_key()
294
fingerprint = result.signatures[0].fpr
295
if self.acceptable_keys is not None:
296
if not fingerprint in self.acceptable_keys:
297
return SIGNATURE_KEY_MISSING, fingerprint[-8:], plain_output
298
# Yay gpg set the valid bit.
299
# Can't write a test for this one as you can't set a key to be
301
if result.signatures[0].summary & gpg.constants.SIGSUM_VALID:
302
key = self.context.get_key(fingerprint)
303
name = key.uids[0].name
304
email = key.uids[0].email
305
return SIGNATURE_VALID, name.decode('utf-8') + u" <" + email.decode('utf-8') + u">", plain_output
306
# Sigsum_red indicates a problem, unfortunatly I have not been able
307
# to write any tests which actually set this.
308
if result.signatures[0].summary & gpg.constants.SIGSUM_RED:
309
return SIGNATURE_NOT_VALID, None, plain_output
310
# Summary isn't set if sig is valid but key is untrusted but if user
311
# has explicity set the key as acceptable we can validate it.
312
if result.signatures[0].summary == 0 and self.acceptable_keys is not None:
313
if fingerprint in self.acceptable_keys:
314
# test_verify_untrusted_but_accepted()
315
return SIGNATURE_VALID, None, plain_output
316
# test_verify_valid_but_untrusted()
317
if result.signatures[0].summary == 0 and self.acceptable_keys is None:
318
return SIGNATURE_NOT_VALID, None, plain_output
319
# Other error types such as revoked keys should (I think) be caught by
320
# SIGSUM_RED so anything else means something is buggy.
321
raise SignatureVerificationFailed(
322
"Unknown GnuPG key verification result")
324
def set_acceptable_keys(self, command_line_input):
325
"""Set the acceptable keys for verifying with this GPGStrategy.
327
:param command_line_input: comma separated list of patterns from
332
acceptable_keys_config = self._config_stack.get('acceptable_keys')
333
if acceptable_keys_config is not None:
334
patterns = acceptable_keys_config
335
if command_line_input is not None: # command line overrides config
336
patterns = command_line_input.split(',')
339
self.acceptable_keys = []
340
for pattern in patterns:
341
result = self.context.keylist(pattern)
345
self.acceptable_keys.append(key.subkeys[0].fpr)
346
trace.mutter("Added acceptable key: " + key.subkeys[0].fpr)
349
"No GnuPG key results for pattern: {0}"
353
def valid_commits_message(count):
354
"""returns message for number of commits"""
355
return gettext(u"{0} commits with valid signatures").format(
356
count[SIGNATURE_VALID])
359
def unknown_key_message(count):
360
"""returns message for number of commits"""
361
return ngettext(u"{0} commit with unknown key",
362
u"{0} commits with unknown keys",
363
count[SIGNATURE_KEY_MISSING]).format(
364
count[SIGNATURE_KEY_MISSING])
367
def commit_not_valid_message(count):
368
"""returns message for number of commits"""
369
return ngettext(u"{0} commit not valid",
370
u"{0} commits not valid",
371
count[SIGNATURE_NOT_VALID]).format(
372
count[SIGNATURE_NOT_VALID])
375
def commit_not_signed_message(count):
376
"""returns message for number of commits"""
377
return ngettext(u"{0} commit not signed",
378
u"{0} commits not signed",
379
count[SIGNATURE_NOT_SIGNED]).format(
380
count[SIGNATURE_NOT_SIGNED])
383
def expired_commit_message(count):
384
"""returns message for number of commits"""
385
return ngettext(u"{0} commit with key now expired",
386
u"{0} commits with key now expired",
387
count[SIGNATURE_EXPIRED]).format(
388
count[SIGNATURE_EXPIRED])
391
def verbose_expired_key_message(result, repo):
392
"""takes a verify result and returns list of expired key info"""
394
fingerprint_to_authors = {}
395
for rev_id, validity, fingerprint in result:
396
if validity == SIGNATURE_EXPIRED:
397
revision = repo.get_revision(rev_id)
398
authors = ', '.join(revision.get_apparent_authors())
399
signers.setdefault(fingerprint, 0)
400
signers[fingerprint] += 1
401
fingerprint_to_authors[fingerprint] = authors
403
for fingerprint, number in signers.items():
405
ngettext(u"{0} commit by author {1} with key {2} now expired",
406
u"{0} commits by author {1} with key {2} now expired",
408
number, fingerprint_to_authors[fingerprint], fingerprint))
412
def verbose_valid_message(result):
413
"""takes a verify result and returns list of signed commits strings"""
415
for rev_id, validity, uid in result:
416
if validity == SIGNATURE_VALID:
417
signers.setdefault(uid, 0)
420
for uid, number in signers.items():
421
result.append(ngettext(u"{0} signed {1} commit",
422
u"{0} signed {1} commits",
423
number).format(uid, number))
427
def verbose_not_valid_message(result, repo):
428
"""takes a verify result and returns list of not valid commit info"""
430
for rev_id, validity, empty in result:
431
if validity == SIGNATURE_NOT_VALID:
432
revision = repo.get_revision(rev_id)
433
authors = ', '.join(revision.get_apparent_authors())
434
signers.setdefault(authors, 0)
435
signers[authors] += 1
437
for authors, number in signers.items():
438
result.append(ngettext(u"{0} commit by author {1}",
439
u"{0} commits by author {1}",
440
number).format(number, authors))
444
def verbose_not_signed_message(result, repo):
445
"""takes a verify result and returns list of not signed commit info"""
447
for rev_id, validity, empty in result:
448
if validity == SIGNATURE_NOT_SIGNED:
449
revision = repo.get_revision(rev_id)
450
authors = ', '.join(revision.get_apparent_authors())
451
signers.setdefault(authors, 0)
452
signers[authors] += 1
454
for authors, number in signers.items():
455
result.append(ngettext(u"{0} commit by author {1}",
456
u"{0} commits by author {1}",
457
number).format(number, authors))
461
def verbose_missing_key_message(result):
462
"""takes a verify result and returns list of missing key info"""
464
for rev_id, validity, fingerprint in result:
465
if validity == SIGNATURE_KEY_MISSING:
466
signers.setdefault(fingerprint, 0)
467
signers[fingerprint] += 1
469
for fingerprint, number in list(signers.items()):
470
result.append(ngettext(u"Unknown key {0} signed {1} commit",
471
u"Unknown key {0} signed {1} commits",
472
number).format(fingerprint, number))