blob: 1bce6cb79240da668a5ac0afb036c4c2b132f59c [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05005"""Helper module for GPG signing"""
6import os
7
8import bb
Brad Bishop1a4b7ee2018-12-16 17:11:34 -08009import subprocess
10import shlex
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050011
12class LocalSigner(object):
13 """Class for handling local (on the build host) signing"""
14 def __init__(self, d):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050015 self.gpg_bin = d.getVar('GPG_BIN') or \
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050016 bb.utils.which(os.getenv('PATH'), 'gpg')
Brad Bishop15ae2502019-06-18 21:44:24 -040017 self.gpg_cmd = [self.gpg_bin]
Brad Bishop316dfdd2018-06-25 12:45:53 -040018 self.gpg_agent_bin = bb.utils.which(os.getenv('PATH'), "gpg-agent")
Brad Bishop15ae2502019-06-18 21:44:24 -040019 # 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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050028
29 def export_pubkey(self, output_file, keyid, armor=True):
30 """Export GPG public key to a file"""
Brad Bishop15ae2502019-06-18 21:44:24 -040031 cmd = self.gpg_cmd + ["--no-permission-warning", "--batch", "--yes", "--export", "-o", output_file]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050032 if self.gpg_path:
Brad Bishop15ae2502019-06-18 21:44:24 -040033 cmd += ["--homedir", self.gpg_path]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050034 if armor:
Brad Bishop15ae2502019-06-18 21:44:24 -040035 cmd += ["--armor"]
36 cmd += [keyid]
37 subprocess.check_output(cmd, stderr=subprocess.STDOUT)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050038
Brad Bishopd7bf8c12018-02-25 22:55:05 -050039 def sign_rpms(self, files, keyid, passphrase, digest, sign_chunk, fsk=None, fsk_password=None):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050040 """Sign RPM files"""
41
42 cmd = self.rpm_bin + " --addsign --define '_gpg_name %s' " % keyid
Brad Bishop316dfdd2018-06-25 12:45:53 -040043 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 -050044 if self.gpg_version > (2,1,):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050045 gpg_args += ' --pinentry-mode=loopback'
46 cmd += "--define '_gpg_sign_cmd_extra_args %s' " % gpg_args
Brad Bishopd7bf8c12018-02-25 22:55:05 -050047 cmd += "--define '_binary_filedigest_algorithm %s' " % digest
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050048 if self.gpg_bin:
Brad Bishopd7bf8c12018-02-25 22:55:05 -050049 cmd += "--define '__gpg %s' " % self.gpg_bin
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050050 if self.gpg_path:
51 cmd += "--define '_gpg_path %s' " % self.gpg_path
Brad Bishopd7bf8c12018-02-25 22:55:05 -050052 if fsk:
53 cmd += "--signfiles --fskpath %s " % fsk
54 if fsk_password:
55 cmd += "--define '_file_signing_key_password %s' " % fsk_password
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050056
Brad Bishopd7bf8c12018-02-25 22:55:05 -050057 # Sign in chunks
58 for i in range(0, len(files), sign_chunk):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080059 subprocess.check_output(shlex.split(cmd + ' '.join(files[i:i+sign_chunk])), stderr=subprocess.STDOUT)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050060
61 def detach_sign(self, input_file, keyid, passphrase_file, passphrase=None, armor=True):
62 """Create a detached signature of a file"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050063
64 if passphrase_file and passphrase:
65 raise Exception("You should use either passphrase_file of passphrase, not both")
66
Brad Bishop15ae2502019-06-18 21:44:24 -040067 cmd = self.gpg_cmd + ['--detach-sign', '--no-permission-warning', '--batch',
Brad Bishopd7bf8c12018-02-25 22:55:05 -050068 '--no-tty', '--yes', '--passphrase-fd', '0', '-u', keyid]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050069
70 if self.gpg_path:
71 cmd += ['--homedir', self.gpg_path]
72 if armor:
73 cmd += ['--armor']
74
75 #gpg > 2.1 supports password pipes only through the loopback interface
76 #gpg < 2.1 errors out if given unknown parameters
Brad Bishop37a0e4d2017-12-04 01:01:44 -050077 if self.gpg_version > (2,1,):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050078 cmd += ['--pinentry-mode', 'loopback']
79
80 cmd += [input_file]
81
82 try:
83 if passphrase_file:
84 with open(passphrase_file) as fobj:
85 passphrase = fobj.readline();
86
87 job = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060088 (_, stderr) = job.communicate(passphrase.encode("utf-8"))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050089
90 if job.returncode:
Brad Bishop08902b02019-08-20 09:16:51 -040091 bb.fatal("GPG exited with code %d: %s" % (job.returncode, stderr.decode("utf-8")))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050092
93 except IOError as e:
94 bb.error("IO error (%s): %s" % (e.errno, e.strerror))
95 raise Exception("Failed to sign '%s'" % input_file)
96
97 except OSError as e:
98 bb.error("OS error (%s): %s" % (e.errno, e.strerror))
99 raise Exception("Failed to sign '%s" % input_file)
100
101
102 def get_gpg_version(self):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500103 """Return the gpg version as a tuple of ints"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500104 try:
Brad Bishop15ae2502019-06-18 21:44:24 -0400105 cmd = self.gpg_cmd + ["--version", "--no-permission-warning"]
106 ver_str = subprocess.check_output(cmd).split()[2].decode("utf-8")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400107 return tuple([int(i) for i in ver_str.split("-")[0].split('.')])
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500108 except subprocess.CalledProcessError as e:
Brad Bishop08902b02019-08-20 09:16:51 -0400109 bb.fatal("Could not get gpg version: %s" % e)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500110
111
Andrew Geisslereff27472021-10-29 15:35:00 -0500112 def verify(self, sig_file, valid_sigs = ''):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500113 """Verify signature"""
Andrew Geisslereff27472021-10-29 15:35:00 -0500114 cmd = self.gpg_cmd + ["--verify", "--no-permission-warning", "--status-fd", "1"]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500115 if self.gpg_path:
Brad Bishop15ae2502019-06-18 21:44:24 -0400116 cmd += ["--homedir", self.gpg_path]
117
118 cmd += [sig_file]
Andrew Geisslereff27472021-10-29 15:35:00 -0500119 status = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
120 # Valid if any key matches if unspecified
121 if not valid_sigs:
122 ret = False if status.returncode else True
123 return ret
124
125 import re
126 goodsigs = []
127 sigre = re.compile(r'^\[GNUPG:\] GOODSIG (\S+)\s(.*)$')
128 for l in status.stdout.decode("utf-8").splitlines():
129 s = sigre.match(l)
130 if s:
131 goodsigs += [s.group(1)]
132
133 for sig in valid_sigs.split():
134 if sig in goodsigs:
135 return True
136 if len(goodsigs):
137 bb.warn('No accepted signatures found. Good signatures found: %s.' % ' '.join(goodsigs))
138 return False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500139
140
141def get_signer(d, backend):
142 """Get signer object for the specified backend"""
143 # Use local signing by default
144 if backend == 'local':
145 return LocalSigner(d)
146 else:
147 bb.fatal("Unsupported signing backend '%s'" % backend)