gpg_sign.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. """Helper module for GPG signing"""
  5. import os
  6. import bb
  7. import oe.utils
  8. import subprocess
  9. import shlex
  10. class LocalSigner(object):
  11. """Class for handling local (on the build host) signing"""
  12. def __init__(self, d):
  13. self.gpg_bin = d.getVar('GPG_BIN') or \
  14. bb.utils.which(os.getenv('PATH'), 'gpg')
  15. self.gpg_path = d.getVar('GPG_PATH')
  16. self.gpg_version = self.get_gpg_version()
  17. self.rpm_bin = bb.utils.which(os.getenv('PATH'), "rpmsign")
  18. self.gpg_agent_bin = bb.utils.which(os.getenv('PATH'), "gpg-agent")
  19. def export_pubkey(self, output_file, keyid, armor=True):
  20. """Export GPG public key to a file"""
  21. cmd = '%s --no-permission-warning --batch --yes --export -o %s ' % \
  22. (self.gpg_bin, output_file)
  23. if self.gpg_path:
  24. cmd += "--homedir %s " % self.gpg_path
  25. if armor:
  26. cmd += "--armor "
  27. cmd += keyid
  28. subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT)
  29. def sign_rpms(self, files, keyid, passphrase, digest, sign_chunk, fsk=None, fsk_password=None):
  30. """Sign RPM files"""
  31. cmd = self.rpm_bin + " --addsign --define '_gpg_name %s' " % keyid
  32. gpg_args = '--no-permission-warning --batch --passphrase=%s --agent-program=%s|--auto-expand-secmem' % (passphrase, self.gpg_agent_bin)
  33. if self.gpg_version > (2,1,):
  34. gpg_args += ' --pinentry-mode=loopback'
  35. cmd += "--define '_gpg_sign_cmd_extra_args %s' " % gpg_args
  36. cmd += "--define '_binary_filedigest_algorithm %s' " % digest
  37. if self.gpg_bin:
  38. cmd += "--define '__gpg %s' " % self.gpg_bin
  39. if self.gpg_path:
  40. cmd += "--define '_gpg_path %s' " % self.gpg_path
  41. if fsk:
  42. cmd += "--signfiles --fskpath %s " % fsk
  43. if fsk_password:
  44. cmd += "--define '_file_signing_key_password %s' " % fsk_password
  45. # Sign in chunks
  46. for i in range(0, len(files), sign_chunk):
  47. subprocess.check_output(shlex.split(cmd + ' '.join(files[i:i+sign_chunk])), stderr=subprocess.STDOUT)
  48. def detach_sign(self, input_file, keyid, passphrase_file, passphrase=None, armor=True):
  49. """Create a detached signature of a file"""
  50. if passphrase_file and passphrase:
  51. raise Exception("You should use either passphrase_file of passphrase, not both")
  52. cmd = [self.gpg_bin, '--detach-sign', '--no-permission-warning', '--batch',
  53. '--no-tty', '--yes', '--passphrase-fd', '0', '-u', keyid]
  54. if self.gpg_path:
  55. cmd += ['--homedir', self.gpg_path]
  56. if armor:
  57. cmd += ['--armor']
  58. #gpg > 2.1 supports password pipes only through the loopback interface
  59. #gpg < 2.1 errors out if given unknown parameters
  60. if self.gpg_version > (2,1,):
  61. cmd += ['--pinentry-mode', 'loopback']
  62. if self.gpg_agent_bin:
  63. cmd += ["--agent-program=%s|--auto-expand-secmem" % (self.gpg_agent_bin)]
  64. cmd += [input_file]
  65. try:
  66. if passphrase_file:
  67. with open(passphrase_file) as fobj:
  68. passphrase = fobj.readline();
  69. job = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
  70. (_, stderr) = job.communicate(passphrase.encode("utf-8"))
  71. if job.returncode:
  72. raise bb.build.FuncFailed("GPG exited with code %d: %s" %
  73. (job.returncode, stderr.decode("utf-8")))
  74. except IOError as e:
  75. bb.error("IO error (%s): %s" % (e.errno, e.strerror))
  76. raise Exception("Failed to sign '%s'" % input_file)
  77. except OSError as e:
  78. bb.error("OS error (%s): %s" % (e.errno, e.strerror))
  79. raise Exception("Failed to sign '%s" % input_file)
  80. def get_gpg_version(self):
  81. """Return the gpg version as a tuple of ints"""
  82. try:
  83. ver_str = subprocess.check_output((self.gpg_bin, "--version", "--no-permission-warning")).split()[2].decode("utf-8")
  84. return tuple([int(i) for i in ver_str.split("-")[0].split('.')])
  85. except subprocess.CalledProcessError as e:
  86. raise bb.build.FuncFailed("Could not get gpg version: %s" % e)
  87. def verify(self, sig_file):
  88. """Verify signature"""
  89. cmd = self.gpg_bin + " --verify --no-permission-warning "
  90. if self.gpg_path:
  91. cmd += "--homedir %s " % self.gpg_path
  92. cmd += sig_file
  93. status = subprocess.call(shlex.split(cmd))
  94. ret = False if status else True
  95. return ret
  96. def get_signer(d, backend):
  97. """Get signer object for the specified backend"""
  98. # Use local signing by default
  99. if backend == 'local':
  100. return LocalSigner(d)
  101. else:
  102. bb.fatal("Unsupported signing backend '%s'" % backend)