blob: 2fd8c3b1ac3dcc9370ba73a0d161f6324de573dc [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
9import oe.utils
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080010import subprocess
11import shlex
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050012
13class LocalSigner(object):
14 """Class for handling local (on the build host) signing"""
15 def __init__(self, d):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050016 self.gpg_bin = d.getVar('GPG_BIN') or \
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050017 bb.utils.which(os.getenv('PATH'), 'gpg')
Brad Bishop15ae2502019-06-18 21:44:24 -040018 self.gpg_cmd = [self.gpg_bin]
Brad Bishop316dfdd2018-06-25 12:45:53 -040019 self.gpg_agent_bin = bb.utils.which(os.getenv('PATH'), "gpg-agent")
Brad Bishop15ae2502019-06-18 21:44:24 -040020 # 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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050029
30 def export_pubkey(self, output_file, keyid, armor=True):
31 """Export GPG public key to a file"""
Brad Bishop15ae2502019-06-18 21:44:24 -040032 cmd = self.gpg_cmd + ["--no-permission-warning", "--batch", "--yes", "--export", "-o", output_file]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050033 if self.gpg_path:
Brad Bishop15ae2502019-06-18 21:44:24 -040034 cmd += ["--homedir", self.gpg_path]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050035 if armor:
Brad Bishop15ae2502019-06-18 21:44:24 -040036 cmd += ["--armor"]
37 cmd += [keyid]
38 subprocess.check_output(cmd, stderr=subprocess.STDOUT)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050039
Brad Bishopd7bf8c12018-02-25 22:55:05 -050040 def sign_rpms(self, files, keyid, passphrase, digest, sign_chunk, fsk=None, fsk_password=None):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050041 """Sign RPM files"""
42
43 cmd = self.rpm_bin + " --addsign --define '_gpg_name %s' " % keyid
Brad Bishop316dfdd2018-06-25 12:45:53 -040044 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 -050045 if self.gpg_version > (2,1,):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050046 gpg_args += ' --pinentry-mode=loopback'
47 cmd += "--define '_gpg_sign_cmd_extra_args %s' " % gpg_args
Brad Bishopd7bf8c12018-02-25 22:55:05 -050048 cmd += "--define '_binary_filedigest_algorithm %s' " % digest
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050049 if self.gpg_bin:
Brad Bishopd7bf8c12018-02-25 22:55:05 -050050 cmd += "--define '__gpg %s' " % self.gpg_bin
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050051 if self.gpg_path:
52 cmd += "--define '_gpg_path %s' " % self.gpg_path
Brad Bishopd7bf8c12018-02-25 22:55:05 -050053 if fsk:
54 cmd += "--signfiles --fskpath %s " % fsk
55 if fsk_password:
56 cmd += "--define '_file_signing_key_password %s' " % fsk_password
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050057
Brad Bishopd7bf8c12018-02-25 22:55:05 -050058 # Sign in chunks
59 for i in range(0, len(files), sign_chunk):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080060 subprocess.check_output(shlex.split(cmd + ' '.join(files[i:i+sign_chunk])), stderr=subprocess.STDOUT)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050061
62 def detach_sign(self, input_file, keyid, passphrase_file, passphrase=None, armor=True):
63 """Create a detached signature of a file"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050064
65 if passphrase_file and passphrase:
66 raise Exception("You should use either passphrase_file of passphrase, not both")
67
Brad Bishop15ae2502019-06-18 21:44:24 -040068 cmd = self.gpg_cmd + ['--detach-sign', '--no-permission-warning', '--batch',
Brad Bishopd7bf8c12018-02-25 22:55:05 -050069 '--no-tty', '--yes', '--passphrase-fd', '0', '-u', keyid]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050070
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
Brad Bishop37a0e4d2017-12-04 01:01:44 -050078 if self.gpg_version > (2,1,):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050079 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)
Patrick Williamsc0f7c042017-02-23 20:41:17 -060089 (_, stderr) = job.communicate(passphrase.encode("utf-8"))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050090
91 if job.returncode:
92 raise bb.build.FuncFailed("GPG exited with code %d: %s" %
Patrick Williamsc0f7c042017-02-23 20:41:17 -060093 (job.returncode, stderr.decode("utf-8")))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050094
95 except IOError as e:
96 bb.error("IO error (%s): %s" % (e.errno, e.strerror))
97 raise Exception("Failed to sign '%s'" % input_file)
98
99 except OSError as e:
100 bb.error("OS error (%s): %s" % (e.errno, e.strerror))
101 raise Exception("Failed to sign '%s" % input_file)
102
103
104 def get_gpg_version(self):
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500105 """Return the gpg version as a tuple of ints"""
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500106 try:
Brad Bishop15ae2502019-06-18 21:44:24 -0400107 cmd = self.gpg_cmd + ["--version", "--no-permission-warning"]
108 ver_str = subprocess.check_output(cmd).split()[2].decode("utf-8")
Brad Bishop316dfdd2018-06-25 12:45:53 -0400109 return tuple([int(i) for i in ver_str.split("-")[0].split('.')])
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500110 except subprocess.CalledProcessError as e:
111 raise bb.build.FuncFailed("Could not get gpg version: %s" % e)
112
113
114 def verify(self, sig_file):
115 """Verify signature"""
Brad Bishop15ae2502019-06-18 21:44:24 -0400116 cmd = self.gpg_cmd + [" --verify", "--no-permission-warning"]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500117 if self.gpg_path:
Brad Bishop15ae2502019-06-18 21:44:24 -0400118 cmd += ["--homedir", self.gpg_path]
119
120 cmd += [sig_file]
121 status = subprocess.call(cmd)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500122 ret = False if status else True
123 return ret
124
125
126def get_signer(d, backend):
127 """Get signer object for the specified backend"""
128 # Use local signing by default
129 if backend == 'local':
130 return LocalSigner(d)
131 else:
132 bb.fatal("Unsupported signing backend '%s'" % backend)