gpg_sign.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #
  2. # Copyright OpenEmbedded Contributors
  3. #
  4. # SPDX-License-Identifier: GPL-2.0-only
  5. #
  6. """Helper module for GPG signing"""
  7. import bb
  8. import os
  9. import shlex
  10. import subprocess
  11. import tempfile
  12. class LocalSigner(object):
  13. """Class for handling local (on the build host) signing"""
  14. def __init__(self, d):
  15. self.gpg_bin = d.getVar('GPG_BIN') or \
  16. bb.utils.which(os.getenv('PATH'), 'gpg')
  17. self.gpg_cmd = [self.gpg_bin]
  18. self.gpg_agent_bin = bb.utils.which(os.getenv('PATH'), "gpg-agent")
  19. # Without this we see "Cannot allocate memory" errors when running processes in parallel
  20. # It needs to be set for any gpg command since any agent launched can stick around in memory
  21. # and this parameter must be set.
  22. if self.gpg_agent_bin:
  23. self.gpg_cmd += ["--agent-program=%s|--auto-expand-secmem" % (self.gpg_agent_bin)]
  24. self.gpg_path = d.getVar('GPG_PATH')
  25. self.rpm_bin = bb.utils.which(os.getenv('PATH'), "rpmsign")
  26. self.gpg_version = self.get_gpg_version()
  27. def export_pubkey(self, output_file, keyid, armor=True):
  28. """Export GPG public key to a file"""
  29. cmd = self.gpg_cmd + ["--no-permission-warning", "--batch", "--yes", "--export", "-o", output_file]
  30. if self.gpg_path:
  31. cmd += ["--homedir", self.gpg_path]
  32. if armor:
  33. cmd += ["--armor"]
  34. cmd += [keyid]
  35. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  36. def sign_rpms(self, files, keyid, passphrase, digest, sign_chunk, fsk=None, fsk_password=None):
  37. """Sign RPM files"""
  38. cmd = self.rpm_bin + " --addsign --define '_gpg_name %s' " % keyid
  39. gpg_args = '--no-permission-warning --batch --passphrase=%s --agent-program=%s|--auto-expand-secmem' % (passphrase, self.gpg_agent_bin)
  40. if self.gpg_version > (2,1,):
  41. gpg_args += ' --pinentry-mode=loopback'
  42. cmd += "--define '_gpg_sign_cmd_extra_args %s' " % gpg_args
  43. cmd += "--define '_binary_filedigest_algorithm %s' " % digest
  44. if self.gpg_bin:
  45. cmd += "--define '__gpg %s' " % self.gpg_bin
  46. if self.gpg_path:
  47. cmd += "--define '_gpg_path %s' " % self.gpg_path
  48. if fsk:
  49. cmd += "--signfiles --fskpath %s " % fsk
  50. if fsk_password:
  51. cmd += "--define '_file_signing_key_password %s' " % fsk_password
  52. # Sign in chunks
  53. for i in range(0, len(files), sign_chunk):
  54. subprocess.check_output(shlex.split(cmd + ' '.join(files[i:i+sign_chunk])), stderr=subprocess.STDOUT)
  55. def detach_sign(self, input_file, keyid, passphrase_file, passphrase=None, armor=True, output_suffix=None, use_sha256=False):
  56. """Create a detached signature of a file"""
  57. if passphrase_file and passphrase:
  58. raise Exception("You should use either passphrase_file of passphrase, not both")
  59. cmd = self.gpg_cmd + ['--detach-sign', '--no-permission-warning', '--batch',
  60. '--no-tty', '--yes', '--passphrase-fd', '0', '-u', keyid]
  61. if self.gpg_path:
  62. cmd += ['--homedir', self.gpg_path]
  63. if armor:
  64. cmd += ['--armor']
  65. if use_sha256:
  66. cmd += ['--digest-algo', "SHA256"]
  67. #gpg > 2.1 supports password pipes only through the loopback interface
  68. #gpg < 2.1 errors out if given unknown parameters
  69. if self.gpg_version > (2,1,):
  70. cmd += ['--pinentry-mode', 'loopback']
  71. try:
  72. if passphrase_file:
  73. with open(passphrase_file) as fobj:
  74. passphrase = fobj.readline();
  75. if not output_suffix:
  76. output_suffix = 'asc' if armor else 'sig'
  77. output_file = input_file + "." + output_suffix
  78. with tempfile.TemporaryDirectory(dir=os.path.dirname(output_file)) as tmp_dir:
  79. tmp_file = os.path.join(tmp_dir, os.path.basename(output_file))
  80. cmd += ['-o', tmp_file]
  81. cmd += [input_file]
  82. job = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
  83. (_, stderr) = job.communicate(passphrase.encode("utf-8"))
  84. if job.returncode:
  85. bb.fatal("GPG exited with code %d: %s" % (job.returncode, stderr.decode("utf-8")))
  86. os.rename(tmp_file, output_file)
  87. except IOError as e:
  88. bb.error("IO error (%s): %s" % (e.errno, e.strerror))
  89. raise Exception("Failed to sign '%s'" % input_file)
  90. except OSError as e:
  91. bb.error("OS error (%s): %s" % (e.errno, e.strerror))
  92. raise Exception("Failed to sign '%s" % input_file)
  93. def get_gpg_version(self):
  94. """Return the gpg version as a tuple of ints"""
  95. try:
  96. cmd = self.gpg_cmd + ["--version", "--no-permission-warning"]
  97. ver_str = subprocess.check_output(cmd).split()[2].decode("utf-8")
  98. return tuple([int(i) for i in ver_str.split("-")[0].split('.')])
  99. except subprocess.CalledProcessError as e:
  100. bb.fatal("Could not get gpg version: %s" % e)
  101. def verify(self, sig_file, valid_sigs = ''):
  102. """Verify signature"""
  103. cmd = self.gpg_cmd + ["--verify", "--no-permission-warning", "--status-fd", "1"]
  104. if self.gpg_path:
  105. cmd += ["--homedir", self.gpg_path]
  106. cmd += [sig_file]
  107. status = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  108. # Valid if any key matches if unspecified
  109. if not valid_sigs:
  110. ret = False if status.returncode else True
  111. return ret
  112. import re
  113. goodsigs = []
  114. sigre = re.compile(r'^\[GNUPG:\] GOODSIG (\S+)\s(.*)$')
  115. for l in status.stdout.decode("utf-8").splitlines():
  116. s = sigre.match(l)
  117. if s:
  118. goodsigs += [s.group(1)]
  119. for sig in valid_sigs.split():
  120. if sig in goodsigs:
  121. return True
  122. if len(goodsigs):
  123. bb.warn('No accepted signatures found. Good signatures found: %s.' % ' '.join(goodsigs))
  124. return False
  125. def get_signer(d, backend):
  126. """Get signer object for the specified backend"""
  127. # Use local signing by default
  128. if backend == 'local':
  129. return LocalSigner(d)
  130. else:
  131. bb.fatal("Unsupported signing backend '%s'" % backend)