1c342db35SBrad Bishop# 292b42cb3SPatrick Williams# Copyright OpenEmbedded Contributors 392b42cb3SPatrick Williams# 4c342db35SBrad Bishop# SPDX-License-Identifier: GPL-2.0-only 5c342db35SBrad Bishop# 6c342db35SBrad Bishop 7eb8dc403SDave Cobbley"""Helper module for GPG signing""" 8eb8dc403SDave Cobbley 9eb8dc403SDave Cobbleyimport bb 10*8e7b46e2SPatrick Williamsimport os 111a4b7ee2SBrad Bishopimport shlex 12*8e7b46e2SPatrick Williamsimport subprocess 13*8e7b46e2SPatrick Williamsimport tempfile 14eb8dc403SDave Cobbley 15eb8dc403SDave Cobbleyclass LocalSigner(object): 16eb8dc403SDave Cobbley """Class for handling local (on the build host) signing""" 17eb8dc403SDave Cobbley def __init__(self, d): 18eb8dc403SDave Cobbley self.gpg_bin = d.getVar('GPG_BIN') or \ 19eb8dc403SDave Cobbley bb.utils.which(os.getenv('PATH'), 'gpg') 2015ae2509SBrad Bishop self.gpg_cmd = [self.gpg_bin] 21eb8dc403SDave Cobbley self.gpg_agent_bin = bb.utils.which(os.getenv('PATH'), "gpg-agent") 2215ae2509SBrad Bishop # Without this we see "Cannot allocate memory" errors when running processes in parallel 2315ae2509SBrad Bishop # It needs to be set for any gpg command since any agent launched can stick around in memory 2415ae2509SBrad Bishop # and this parameter must be set. 2515ae2509SBrad Bishop if self.gpg_agent_bin: 2615ae2509SBrad Bishop self.gpg_cmd += ["--agent-program=%s|--auto-expand-secmem" % (self.gpg_agent_bin)] 2715ae2509SBrad Bishop self.gpg_path = d.getVar('GPG_PATH') 2815ae2509SBrad Bishop self.rpm_bin = bb.utils.which(os.getenv('PATH'), "rpmsign") 2915ae2509SBrad Bishop self.gpg_version = self.get_gpg_version() 3015ae2509SBrad Bishop 31eb8dc403SDave Cobbley 32eb8dc403SDave Cobbley def export_pubkey(self, output_file, keyid, armor=True): 33eb8dc403SDave Cobbley """Export GPG public key to a file""" 3415ae2509SBrad Bishop cmd = self.gpg_cmd + ["--no-permission-warning", "--batch", "--yes", "--export", "-o", output_file] 35eb8dc403SDave Cobbley if self.gpg_path: 3615ae2509SBrad Bishop cmd += ["--homedir", self.gpg_path] 37eb8dc403SDave Cobbley if armor: 3815ae2509SBrad Bishop cmd += ["--armor"] 3915ae2509SBrad Bishop cmd += [keyid] 4015ae2509SBrad Bishop subprocess.check_output(cmd, stderr=subprocess.STDOUT) 41eb8dc403SDave Cobbley 42eb8dc403SDave Cobbley def sign_rpms(self, files, keyid, passphrase, digest, sign_chunk, fsk=None, fsk_password=None): 43eb8dc403SDave Cobbley """Sign RPM files""" 44eb8dc403SDave Cobbley 45eb8dc403SDave Cobbley cmd = self.rpm_bin + " --addsign --define '_gpg_name %s' " % keyid 46eb8dc403SDave Cobbley gpg_args = '--no-permission-warning --batch --passphrase=%s --agent-program=%s|--auto-expand-secmem' % (passphrase, self.gpg_agent_bin) 47eb8dc403SDave Cobbley if self.gpg_version > (2,1,): 48eb8dc403SDave Cobbley gpg_args += ' --pinentry-mode=loopback' 49eb8dc403SDave Cobbley cmd += "--define '_gpg_sign_cmd_extra_args %s' " % gpg_args 50eb8dc403SDave Cobbley cmd += "--define '_binary_filedigest_algorithm %s' " % digest 51eb8dc403SDave Cobbley if self.gpg_bin: 52eb8dc403SDave Cobbley cmd += "--define '__gpg %s' " % self.gpg_bin 53eb8dc403SDave Cobbley if self.gpg_path: 54eb8dc403SDave Cobbley cmd += "--define '_gpg_path %s' " % self.gpg_path 55eb8dc403SDave Cobbley if fsk: 56eb8dc403SDave Cobbley cmd += "--signfiles --fskpath %s " % fsk 57eb8dc403SDave Cobbley if fsk_password: 58eb8dc403SDave Cobbley cmd += "--define '_file_signing_key_password %s' " % fsk_password 59eb8dc403SDave Cobbley 60eb8dc403SDave Cobbley # Sign in chunks 61eb8dc403SDave Cobbley for i in range(0, len(files), sign_chunk): 621a4b7ee2SBrad Bishop subprocess.check_output(shlex.split(cmd + ' '.join(files[i:i+sign_chunk])), stderr=subprocess.STDOUT) 63eb8dc403SDave Cobbley 64de0582f0SPatrick Williams def detach_sign(self, input_file, keyid, passphrase_file, passphrase=None, armor=True, output_suffix=None, use_sha256=False): 65eb8dc403SDave Cobbley """Create a detached signature of a file""" 66eb8dc403SDave Cobbley 67eb8dc403SDave Cobbley if passphrase_file and passphrase: 68eb8dc403SDave Cobbley raise Exception("You should use either passphrase_file of passphrase, not both") 69eb8dc403SDave Cobbley 7015ae2509SBrad Bishop cmd = self.gpg_cmd + ['--detach-sign', '--no-permission-warning', '--batch', 71eb8dc403SDave Cobbley '--no-tty', '--yes', '--passphrase-fd', '0', '-u', keyid] 72eb8dc403SDave Cobbley 73eb8dc403SDave Cobbley if self.gpg_path: 74eb8dc403SDave Cobbley cmd += ['--homedir', self.gpg_path] 75eb8dc403SDave Cobbley if armor: 76eb8dc403SDave Cobbley cmd += ['--armor'] 77de0582f0SPatrick Williams if use_sha256: 78de0582f0SPatrick Williams cmd += ['--digest-algo', "SHA256"] 79eb8dc403SDave Cobbley 80eb8dc403SDave Cobbley #gpg > 2.1 supports password pipes only through the loopback interface 81eb8dc403SDave Cobbley #gpg < 2.1 errors out if given unknown parameters 82eb8dc403SDave Cobbley if self.gpg_version > (2,1,): 83eb8dc403SDave Cobbley cmd += ['--pinentry-mode', 'loopback'] 84eb8dc403SDave Cobbley 85eb8dc403SDave Cobbley try: 86eb8dc403SDave Cobbley if passphrase_file: 87eb8dc403SDave Cobbley with open(passphrase_file) as fobj: 88eb8dc403SDave Cobbley passphrase = fobj.readline(); 89eb8dc403SDave Cobbley 90*8e7b46e2SPatrick Williams if not output_suffix: 91*8e7b46e2SPatrick Williams output_suffix = 'asc' if armor else 'sig' 92*8e7b46e2SPatrick Williams output_file = input_file + "." + output_suffix 93*8e7b46e2SPatrick Williams with tempfile.TemporaryDirectory(dir=os.path.dirname(output_file)) as tmp_dir: 94*8e7b46e2SPatrick Williams tmp_file = os.path.join(tmp_dir, os.path.basename(output_file)) 95*8e7b46e2SPatrick Williams cmd += ['-o', tmp_file] 96*8e7b46e2SPatrick Williams 97*8e7b46e2SPatrick Williams cmd += [input_file] 98*8e7b46e2SPatrick Williams 99eb8dc403SDave Cobbley job = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE) 100eb8dc403SDave Cobbley (_, stderr) = job.communicate(passphrase.encode("utf-8")) 101eb8dc403SDave Cobbley 102eb8dc403SDave Cobbley if job.returncode: 10308902b01SBrad Bishop bb.fatal("GPG exited with code %d: %s" % (job.returncode, stderr.decode("utf-8"))) 104eb8dc403SDave Cobbley 105*8e7b46e2SPatrick Williams os.rename(tmp_file, output_file) 106eb8dc403SDave Cobbley except IOError as e: 107eb8dc403SDave Cobbley bb.error("IO error (%s): %s" % (e.errno, e.strerror)) 108eb8dc403SDave Cobbley raise Exception("Failed to sign '%s'" % input_file) 109eb8dc403SDave Cobbley 110eb8dc403SDave Cobbley except OSError as e: 111eb8dc403SDave Cobbley bb.error("OS error (%s): %s" % (e.errno, e.strerror)) 112eb8dc403SDave Cobbley raise Exception("Failed to sign '%s" % input_file) 113eb8dc403SDave Cobbley 114eb8dc403SDave Cobbley 115eb8dc403SDave Cobbley def get_gpg_version(self): 116eb8dc403SDave Cobbley """Return the gpg version as a tuple of ints""" 117eb8dc403SDave Cobbley try: 11815ae2509SBrad Bishop cmd = self.gpg_cmd + ["--version", "--no-permission-warning"] 11915ae2509SBrad Bishop ver_str = subprocess.check_output(cmd).split()[2].decode("utf-8") 120eb8dc403SDave Cobbley return tuple([int(i) for i in ver_str.split("-")[0].split('.')]) 121eb8dc403SDave Cobbley except subprocess.CalledProcessError as e: 12208902b01SBrad Bishop bb.fatal("Could not get gpg version: %s" % e) 123eb8dc403SDave Cobbley 124eb8dc403SDave Cobbley 125eff27476SAndrew Geissler def verify(self, sig_file, valid_sigs = ''): 126eb8dc403SDave Cobbley """Verify signature""" 127eff27476SAndrew Geissler cmd = self.gpg_cmd + ["--verify", "--no-permission-warning", "--status-fd", "1"] 128eb8dc403SDave Cobbley if self.gpg_path: 12915ae2509SBrad Bishop cmd += ["--homedir", self.gpg_path] 13015ae2509SBrad Bishop 13115ae2509SBrad Bishop cmd += [sig_file] 132eff27476SAndrew Geissler status = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 133eff27476SAndrew Geissler # Valid if any key matches if unspecified 134eff27476SAndrew Geissler if not valid_sigs: 135eff27476SAndrew Geissler ret = False if status.returncode else True 136eb8dc403SDave Cobbley return ret 137eb8dc403SDave Cobbley 138eff27476SAndrew Geissler import re 139eff27476SAndrew Geissler goodsigs = [] 140eff27476SAndrew Geissler sigre = re.compile(r'^\[GNUPG:\] GOODSIG (\S+)\s(.*)$') 141eff27476SAndrew Geissler for l in status.stdout.decode("utf-8").splitlines(): 142eff27476SAndrew Geissler s = sigre.match(l) 143eff27476SAndrew Geissler if s: 144eff27476SAndrew Geissler goodsigs += [s.group(1)] 145eff27476SAndrew Geissler 146eff27476SAndrew Geissler for sig in valid_sigs.split(): 147eff27476SAndrew Geissler if sig in goodsigs: 148eff27476SAndrew Geissler return True 149eff27476SAndrew Geissler if len(goodsigs): 150eff27476SAndrew Geissler bb.warn('No accepted signatures found. Good signatures found: %s.' % ' '.join(goodsigs)) 151eff27476SAndrew Geissler return False 152eff27476SAndrew Geissler 153eb8dc403SDave Cobbley 154eb8dc403SDave Cobbleydef get_signer(d, backend): 155eb8dc403SDave Cobbley """Get signer object for the specified backend""" 156eb8dc403SDave Cobbley # Use local signing by default 157eb8dc403SDave Cobbley if backend == 'local': 158eb8dc403SDave Cobbley return LocalSigner(d) 159eb8dc403SDave Cobbley else: 160eb8dc403SDave Cobbley bb.fatal("Unsupported signing backend '%s'" % backend) 161