blob: ede6186c84f3e982e35c65980ecf81ac041954a1 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Patrick Williams92b42cb2022-09-03 06:53:57 -05002# Copyright OpenEmbedded Contributors
3#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: GPL-2.0-only
5#
6
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05007"""Helper module for GPG signing"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05008
9import bb
Patrick Williams8e7b46e2023-05-01 14:19:06 -050010import os
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080011import shlex
Patrick Williams8e7b46e2023-05-01 14:19:06 -050012import subprocess
13import tempfile
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050014
15class LocalSigner(object):
16 """Class for handling local (on the build host) signing"""
17 def __init__(self, d):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050018 self.gpg_bin = d.getVar('GPG_BIN') or \
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050019 bb.utils.which(os.getenv('PATH'), 'gpg')
Brad Bishop15ae2502019-06-18 21:44:24 -040020 self.gpg_cmd = [self.gpg_bin]
Brad Bishop316dfdd2018-06-25 12:45:53 -040021 self.gpg_agent_bin = bb.utils.which(os.getenv('PATH'), "gpg-agent")
Brad Bishop15ae2502019-06-18 21:44:24 -040022 # Without this we see "Cannot allocate memory" errors when running processes in parallel
23 # It needs to be set for any gpg command since any agent launched can stick around in memory
24 # and this parameter must be set.
25 if self.gpg_agent_bin:
26 self.gpg_cmd += ["--agent-program=%s|--auto-expand-secmem" % (self.gpg_agent_bin)]
27 self.gpg_path = d.getVar('GPG_PATH')
28 self.rpm_bin = bb.utils.which(os.getenv('PATH'), "rpmsign")
29 self.gpg_version = self.get_gpg_version()
30
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050031
32 def export_pubkey(self, output_file, keyid, armor=True):
33 """Export GPG public key to a file"""
Brad Bishop15ae2502019-06-18 21:44:24 -040034 cmd = self.gpg_cmd + ["--no-permission-warning", "--batch", "--yes", "--export", "-o", output_file]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050035 if self.gpg_path:
Brad Bishop15ae2502019-06-18 21:44:24 -040036 cmd += ["--homedir", self.gpg_path]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050037 if armor:
Brad Bishop15ae2502019-06-18 21:44:24 -040038 cmd += ["--armor"]
39 cmd += [keyid]
40 subprocess.check_output(cmd, stderr=subprocess.STDOUT)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050041
Brad Bishopd7bf8c12018-02-25 22:55:05 -050042 def sign_rpms(self, files, keyid, passphrase, digest, sign_chunk, fsk=None, fsk_password=None):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050043 """Sign RPM files"""
44
45 cmd = self.rpm_bin + " --addsign --define '_gpg_name %s' " % keyid
Brad Bishop316dfdd2018-06-25 12:45:53 -040046 gpg_args = '--no-permission-warning --batch --passphrase=%s --agent-program=%s|--auto-expand-secmem' % (passphrase, self.gpg_agent_bin)
Brad Bishop37a0e4d2017-12-04 01:01:44 -050047 if self.gpg_version > (2,1,):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050048 gpg_args += ' --pinentry-mode=loopback'
49 cmd += "--define '_gpg_sign_cmd_extra_args %s' " % gpg_args
Brad Bishopd7bf8c12018-02-25 22:55:05 -050050 cmd += "--define '_binary_filedigest_algorithm %s' " % digest
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050051 if self.gpg_bin:
Brad Bishopd7bf8c12018-02-25 22:55:05 -050052 cmd += "--define '__gpg %s' " % self.gpg_bin
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050053 if self.gpg_path:
54 cmd += "--define '_gpg_path %s' " % self.gpg_path
Brad Bishopd7bf8c12018-02-25 22:55:05 -050055 if fsk:
56 cmd += "--signfiles --fskpath %s " % fsk
57 if fsk_password:
58 cmd += "--define '_file_signing_key_password %s' " % fsk_password
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050059
Brad Bishopd7bf8c12018-02-25 22:55:05 -050060 # Sign in chunks
61 for i in range(0, len(files), sign_chunk):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080062 subprocess.check_output(shlex.split(cmd + ' '.join(files[i:i+sign_chunk])), stderr=subprocess.STDOUT)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050063
Patrick Williamsde0582f2022-04-08 10:23:27 -050064 def detach_sign(self, input_file, keyid, passphrase_file, passphrase=None, armor=True, output_suffix=None, use_sha256=False):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050065 """Create a detached signature of a file"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050066
67 if passphrase_file and passphrase:
68 raise Exception("You should use either passphrase_file of passphrase, not both")
69
Brad Bishop15ae2502019-06-18 21:44:24 -040070 cmd = self.gpg_cmd + ['--detach-sign', '--no-permission-warning', '--batch',
Brad Bishopd7bf8c12018-02-25 22:55:05 -050071 '--no-tty', '--yes', '--passphrase-fd', '0', '-u', keyid]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050072
73 if self.gpg_path:
74 cmd += ['--homedir', self.gpg_path]
75 if armor:
76 cmd += ['--armor']
Patrick Williamsde0582f2022-04-08 10:23:27 -050077 if use_sha256:
78 cmd += ['--digest-algo', "SHA256"]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050079
80 #gpg > 2.1 supports password pipes only through the loopback interface
81 #gpg < 2.1 errors out if given unknown parameters
Brad Bishop37a0e4d2017-12-04 01:01:44 -050082 if self.gpg_version > (2,1,):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050083 cmd += ['--pinentry-mode', 'loopback']
84
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050085 try:
86 if passphrase_file:
87 with open(passphrase_file) as fobj:
88 passphrase = fobj.readline();
89
Patrick Williams8e7b46e2023-05-01 14:19:06 -050090 if not output_suffix:
91 output_suffix = 'asc' if armor else 'sig'
92 output_file = input_file + "." + output_suffix
93 with tempfile.TemporaryDirectory(dir=os.path.dirname(output_file)) as tmp_dir:
94 tmp_file = os.path.join(tmp_dir, os.path.basename(output_file))
95 cmd += ['-o', tmp_file]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050096
Patrick Williams8e7b46e2023-05-01 14:19:06 -050097 cmd += [input_file]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050098
Patrick Williams8e7b46e2023-05-01 14:19:06 -050099 job = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
100 (_, stderr) = job.communicate(passphrase.encode("utf-8"))
101
102 if job.returncode:
103 bb.fatal("GPG exited with code %d: %s" % (job.returncode, stderr.decode("utf-8")))
104
105 os.rename(tmp_file, output_file)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500106 except IOError as e:
107 bb.error("IO error (%s): %s" % (e.errno, e.strerror))
108 raise Exception("Failed to sign '%s'" % input_file)
109
110 except OSError as e:
111 bb.error("OS error (%s): %s" % (e.errno, e.strerror))
112 raise Exception("Failed to sign '%s" % input_file)
113
114
115 def get_gpg_version(self):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500116 """Return the gpg version as a tuple of ints"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500117 try:
Brad Bishop15ae2502019-06-18 21:44:24 -0400118 cmd = self.gpg_cmd + ["--version", "--no-permission-warning"]
119 ver_str = subprocess.check_output(cmd).split()[2].decode("utf-8")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400120 return tuple([int(i) for i in ver_str.split("-")[0].split('.')])
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500121 except subprocess.CalledProcessError as e:
Brad Bishop08902b02019-08-20 09:16:51 -0400122 bb.fatal("Could not get gpg version: %s" % e)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500123
124
Andrew Geisslereff27472021-10-29 15:35:00 -0500125 def verify(self, sig_file, valid_sigs = ''):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500126 """Verify signature"""
Andrew Geisslereff27472021-10-29 15:35:00 -0500127 cmd = self.gpg_cmd + ["--verify", "--no-permission-warning", "--status-fd", "1"]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500128 if self.gpg_path:
Brad Bishop15ae2502019-06-18 21:44:24 -0400129 cmd += ["--homedir", self.gpg_path]
130
131 cmd += [sig_file]
Andrew Geisslereff27472021-10-29 15:35:00 -0500132 status = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
133 # Valid if any key matches if unspecified
134 if not valid_sigs:
135 ret = False if status.returncode else True
136 return ret
137
138 import re
139 goodsigs = []
140 sigre = re.compile(r'^\[GNUPG:\] GOODSIG (\S+)\s(.*)$')
141 for l in status.stdout.decode("utf-8").splitlines():
142 s = sigre.match(l)
143 if s:
144 goodsigs += [s.group(1)]
145
146 for sig in valid_sigs.split():
147 if sig in goodsigs:
148 return True
149 if len(goodsigs):
150 bb.warn('No accepted signatures found. Good signatures found: %s.' % ' '.join(goodsigs))
151 return False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500152
153
154def get_signer(d, backend):
155 """Get signer object for the specified backend"""
156 # Use local signing by default
157 if backend == 'local':
158 return LocalSigner(d)
159 else:
160 bb.fatal("Unsupported signing backend '%s'" % backend)