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