Add template source package to support code signing

This commit is contained in:
Ben Hutchings 2018-04-05 23:13:20 +02:00
parent 1d4211ef97
commit be394a26da
13 changed files with 461 additions and 7 deletions

View File

@ -177,6 +177,8 @@ class Gencontrol(Base):
makeflags['ABINAME'] = vars['abiname'] = \
self.abiname_version + abiname_part
build_signed = self.config.merge('build', arch).get('signed-code', False)
# Some userland architectures require kernels from another
# (Debian) architecture, e.g. x32/amd64.
# And some derivatives don't need the headers-all packages
@ -226,11 +228,6 @@ class Gencontrol(Base):
installer_def_dir = 'debian/installer'
installer_arch_dir = os.path.join(installer_def_dir, arch)
if os.path.isdir(installer_arch_dir):
# If we're going to build signed udebs later, don't actually
# generate udebs. Just test that we *can* build, so we find
# configuration errors before building linux-signed.
test_build = self.config.merge('build', arch).get('signed-code', False)
kw_env = os.environ.copy()
kw_env['KW_DEFCONFIG_DIR'] = installer_def_dir
kw_env['KW_CONFIG_DIR'] = installer_arch_dir
@ -251,7 +248,11 @@ class Gencontrol(Base):
for package in udeb_packages:
package['Build-Profiles'] = '<!stage1>'
if not test_build:
# If we're going to build signed udebs later, don't actually
# generate udebs. Just test that we *can* build, so we find
# configuration errors before building linux-signed.
if not build_signed:
merge_packages(packages, udeb_packages, arch)
# These packages must be built after the per-flavour/
@ -264,7 +265,19 @@ class Gencontrol(Base):
"PACKAGE_NAMES='%s' UDEB_UNSIGNED_TEST_BUILD=%s" %
(arch, makeflags,
' '.join(p['Package'] for p in udeb_packages),
test_build)])
build_signed)])
# This also needs to be built after the per-flavour/per-featureset
# packages.
if build_signed:
merge_packages(packages,
self.process_packages(
self.templates['control.signed-template'], vars),
arch)
makefile.add(
'binary-arch_%s' % arch,
cmds=["$(MAKE) -f debian/rules.real install-signed-template_%s %s" %
(arch, makeflags)])
def do_featureset_setup(self, vars, makeflags, arch, featureset, extra):
config_base = self.config.merge('base', arch, featureset)

232
debian/bin/gencontrol_signed.py vendored Executable file
View File

@ -0,0 +1,232 @@
#!/usr/bin/python3
import sys
sys.path.append("debian/lib/python")
from debian_linux.config import ConfigCoreDump
from debian_linux.debian import Changelog, PackageDescription, VersionLinux, \
Package, PackageRelationGroup
from debian_linux.gencontrol import Gencontrol as Base, merge_packages
from debian_linux.utils import Templates, read_control
import os.path, re, codecs, io, json, subprocess, time
class Gencontrol(Base):
def __init__(self, arch):
super(Gencontrol, self).__init__(
ConfigCoreDump(fp = open('debian/config.defines.dump', 'rb')),
Templates(['debian/signing_templates', 'debian/templates']))
image_binary_version = self.changelog[0].version.complete
config_entry = self.config['version',]
self.version = VersionLinux(config_entry['source'])
# Check config version matches changelog version
assert self.version.complete == re.sub(r'\+b\d+$', r'',
image_binary_version)
self.abiname = config_entry['abiname']
self.signed_version = re.sub(r'\+b(\d+)$', r'.b\1', image_binary_version)
self.vars = {
'upstreamversion': self.version.linux_upstream,
'version': self.version.linux_version,
'source_upstream': self.version.upstream,
'abiname': self.abiname,
'imagebinaryversion': image_binary_version,
'imagesourceversion': self.version.complete,
'signedversion': self.signed_version,
'arch': arch,
}
self.template_top_dir = ('debian/linux-image-%(arch)s-signed-template/usr/share/code-signing/linux-image-%(arch)s-signed-template' %
self.vars)
self.template_debian_dir = self.template_top_dir + '/source-template/debian'
os.makedirs(self.template_debian_dir, exist_ok=True)
self.image_packages = []
def _substitute_file(self, template, vars, target, append=False):
with codecs.open(target, 'a' if append else 'w', 'utf-8') as f:
f.write(self.substitute(self.templates[template], vars))
def do_main_setup(self, vars, makeflags, extra):
makeflags['VERSION'] = self.version.linux_version
makeflags['GENCONTROL_ARGS'] = (
'-DBuilt-Using="linux (= %(imagesourceversion)s)"' % vars)
makeflags['PACKAGE_VERSION'] = self.signed_version
def do_main_packages(self, packages, vars, makeflags, extra):
# Assume that arch:all packages do not get binNMU'd
packages['source']['Build-Depends'].append(
'linux-support-%(abiname)s (= %(imagesourceversion)s)' % vars)
def do_main_recurse(self, packages, makefile, vars, makeflags, extra):
# Each signed source package only covers a single architecture
self.do_arch(packages, makefile, self.vars['arch'], vars.copy(), makeflags.copy(), extra)
def do_extra(self, packages, makefile):
pass
def do_arch_setup(self, vars, makeflags, arch, extra):
super(Gencontrol, self).do_main_setup(vars, makeflags, extra)
if self.version.linux_modifier is None:
abiname_part = '-%s' % self.config.merge('abi', arch)['abiname']
else:
abiname_part = ''
makeflags['ABINAME'] = vars['abiname'] = \
self.config['version', ]['abiname_base'] + abiname_part
def do_arch_packages(self, packages, makefile, arch, vars, makeflags, extra):
if os.getenv('DEBIAN_KERNEL_DISABLE_INSTALLER'):
if self.changelog[0].distribution == 'UNRELEASED':
import warnings
warnings.warn('Disable installer modules on request (DEBIAN_KERNEL_DISABLE_INSTALLER set)')
else:
raise RuntimeError('Unable to disable installer modules in release build (DEBIAN_KERNEL_DISABLE_INSTALLER set)')
elif (self.config.merge('packages').get('installer', True) and
self.config.merge('build', arch).get('signed-code', False)):
# Add udebs using kernel-wedge
installer_def_dir = 'debian/installer'
installer_arch_dir = os.path.join(installer_def_dir, arch)
if os.path.isdir(installer_arch_dir):
kw_env = os.environ.copy()
kw_env['KW_DEFCONFIG_DIR'] = installer_def_dir
kw_env['KW_CONFIG_DIR'] = installer_arch_dir
kw_proc = subprocess.Popen(
['kernel-wedge', 'gen-control', vars['abiname']],
stdout=subprocess.PIPE,
env=kw_env)
if not isinstance(kw_proc.stdout, io.IOBase):
udeb_packages = read_control(io.open(kw_proc.stdout.fileno(), closefd=False))
else:
udeb_packages = read_control(io.TextIOWrapper(kw_proc.stdout))
kw_proc.wait()
if kw_proc.returncode != 0:
raise RuntimeError('kernel-wedge exited with code %d' %
kw_proc.returncode)
merge_packages(packages, udeb_packages, arch)
# These packages must be built after the per-flavour/
# per-featureset packages. Also, this won't work
# correctly with an empty package list.
if udeb_packages:
makefile.add(
'binary-arch_%s' % arch,
cmds=["$(MAKE) -f debian/rules.real install-udeb_%s %s "
"PACKAGE_NAMES='%s'" %
(arch, makeflags,
' '.join(p['Package'] for p in udeb_packages))])
def do_flavour_setup(self, vars, makeflags, arch, featureset, flavour, extra):
super(Gencontrol, self).do_flavour_setup(vars, makeflags, arch, featureset, flavour, extra)
config_image = self.config.merge('image', arch, featureset, flavour)
makeflags['IMAGE_INSTALL_STEM'] = vars['image-stem'] = config_image.get('install-stem')
def do_flavour_packages(self, packages, makefile, arch, featureset, flavour, vars, makeflags, extra):
if not (self.config.merge('build', arch, featureset, flavour)
.get('signed-code', False)):
return
image_suffix = '%(abiname)s%(localversion)s' % vars
image_package_name = 'linux-image-%s-unsigned' % image_suffix
self.image_packages.append((image_suffix, image_package_name))
# Verify that this flavour is configured to support Secure Boot
with open('debian/%s/boot/config-%s' %
(image_package_name, image_suffix)) as f:
kconfig = f.readlines()
assert 'CONFIG_EFI_STUB=y\n' in kconfig
assert 'CONFIG_LOCK_DOWN_IN_EFI_SECURE_BOOT=y\n' in kconfig
packages['source']['Build-Depends'].append(
image_package_name +
' (= %(imagebinaryversion)s) [%(arch)s]' % vars)
packages_signed = self.process_packages(
self.templates['control.image'], vars)
for package in packages_signed:
name = package['Package']
if name in packages:
package = packages.get(name)
package['Architecture'].add(arch)
else:
package['Architecture'] = arch
packages.append(package)
cmds_binary_arch = []
for i in packages_signed:
cmds_binary_arch += ["$(MAKE) -f debian/rules.real install-signed PACKAGE_NAME='%s' %s" % (i['Package'], makeflags)]
makefile.add('binary-arch_%s_%s_%s_real' % (arch, featureset, flavour), cmds = cmds_binary_arch)
for name in ['postinst', 'postrm', 'preinst', 'prerm']:
self._substitute_file('image.%s' % name, vars,
self.template_debian_dir +
'/linux-image-%s%s.%s' %
(vars['abiname'], vars['localversion'], name))
def write(self, packages, makefile):
self.write_changelog()
self.write_control(packages.values(),
name=(self.template_debian_dir + '/control'))
self.write_makefile(makefile,
name=(self.template_debian_dir + '/rules.gen'))
self.write_files_json()
def write_changelog(self):
changelog_text = self.substitute(self.templates['changelog.in'],
self.vars)
# We probably need to insert a new version entry
changelog = Changelog(file=io.StringIO(changelog_text))
if changelog[0].version.complete != self.signed_version:
vars = self.vars.copy()
vars['distribution'] = self.changelog[0].distribution
vars['urgency'] = self.changelog[0].urgency
vars['date'] = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.gmtime())
changelog_text = (self.substitute('''\
linux-signed-@arch@ (@signedversion@) @distribution@; urgency=@urgency@
* Update to linux @imagebinaryversion@
-- Debian signing service <ftpmaster@debian.org> @date@
''',
vars) +
changelog_text)
with codecs.open(self.template_debian_dir + '/changelog', 'w', 'utf-8') as f:
f.write(changelog_text)
def write_files_json(self):
# Can't raise from a lambda function :-(
def raise_func(e):
raise e
all_files = {}
for image_suffix, image_package_name in self.image_packages:
package_dir = 'debian/%s' % image_package_name
package_files = []
package_files.append({'sig_type': 'efi',
'file': 'boot/vmlinuz-%s' % image_suffix})
for root, dirs, files in os.walk('%s/lib/modules' % package_dir,
onerror=raise_func):
for name in files:
if name.endswith('.ko'):
package_files.append(
{'sig_type': 'linux-module',
'file': '%s/%s' %
(root[len(package_dir) + 1 :], name)})
all_files[image_package_name] = {'files': package_files}
with codecs.open(self.template_top_dir + '/files.json', 'w') as f:
json.dump(all_files, f)
if __name__ == '__main__':
Gencontrol(sys.argv[1])()

1
debian/changelog vendored
View File

@ -50,6 +50,7 @@ linux (4.16-1~exp1) UNRELEASED; urgency=medium
* debian/lib/python/debian_linux/debian.py: Allow parsing any file as
changelog
* debian/rules.d/tools/lib/lockdep/Makefile: Fix repeated 'make install'
* Add template source package to support code signing
-- Roger Shimizu <rogershimizu@gmail.com> Fri, 23 Mar 2018 21:10:34 +0900

22
debian/rules.real vendored
View File

@ -493,6 +493,28 @@ endif
ln -s ../../../boot/vmlinux-$(REAL_VERSION) $(DEBUG_DIR)/lib/modules/$(REAL_VERSION)/vmlinux
+$(MAKE_SELF) install-base
install-signed-template_$(ARCH): PACKAGE_NAME = linux-image-$(ARCH)-signed-template
install-signed-template_$(ARCH): DH_OPTIONS = -p$(PACKAGE_NAME)
install-signed-template_$(ARCH): PACKAGE_DIR = debian/$(PACKAGE_NAME)
install-signed-template_$(ARCH): CODE_SIGNING_DIR = $(PACKAGE_DIR)/usr/share/code-signing/$(PACKAGE_NAME)
install-signed-template_$(ARCH):
dh_testdir
dh_testroot
dh_prep
rm -rf $(CODE_SIGNING_DIR)
mkdir -p $(CODE_SIGNING_DIR)
PYTHONHASHSEED=0 debian/bin/gencontrol_signed.py $(ARCH)
cp -R debian/compat \
debian/signing_templates/copyright \
debian/signing_templates/README.source \
debian/signing_templates/rules \
debian/signing_templates/rules.real \
debian/signing_templates/source \
$(CODE_SIGNING_DIR)/source-template/debian/
dh_fixperms
dh_gencontrol
dh_builddeb
install-udeb_$(ARCH): export KW_DEFCONFIG_DIR=debian/installer
install-udeb_$(ARCH): export KW_CONFIG_DIR=debian/installer/$(ARCH)
install-udeb_$(ARCH): DH_OPTIONS=$(PACKAGE_NAMES:%=-p%)

View File

@ -0,0 +1,4 @@
This source package is generated by the Debian signing service from a
template built by the linux package. It should never be updated directly.
-- Ben Hutchings <ben@decadent.org.uk> Fri, 06 Apr 2018 10:23:29 +0100

6
debian/signing_templates/changelog.in vendored Normal file
View File

@ -0,0 +1,6 @@
linux-signed-@arch@ (4.15.11-2) unstable; urgency=medium
* Add template source package for signing
-- Ben Hutchings <ben@decadent.org.uk> Fri, 06 Apr 2018 10:36:20 +0100

View File

@ -0,0 +1,11 @@
Package: linux-image-@abiname@@localversion@
Depends: ${unsigned:Depends}
Recommends: ${unsigned:Recommends}
Suggests: ${unsigned:Suggests}
Breaks: ${unsigned:Breaks}
Conflicts: linux-image-@abiname@@localversion@-unsigned
Replaces: linux-image-@abiname@@localversion@-unsigned
Description: ${unsigned:DescriptionShort} (signed)
${unsigned:DescriptionLong}
.
${signed:Description}

View File

@ -0,0 +1,11 @@
Source: linux-signed-@arch@
Section: kernel
Priority: optional
Maintainer: Debian Kernel Team <debian-kernel@lists.debian.org>
Uploaders: Ben Hutchings <ben@decadent.org.uk>
Standards-Version: 4.1.1
Build-Depends: debhelper (>= 10.1~), rsync, sbsigntool [amd64 arm64 i386], kernel-wedge (>= 2.93~), linux-kbuild-@version@
Rules-Requires-Root: no
Vcs-Git: https://salsa.debian.org/kernel-team/linux.git
Vcs-Browser: https://salsa.debian.org/kernel-team/linux
Homepage: https://www.kernel.org/

53
debian/signing_templates/copyright vendored Normal file
View File

@ -0,0 +1,53 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Comment:
This file describes only the linux-signed source package. Its binary
packages are built largely from source in the linux source package,
which is described by the file 'copyright.linux'.
Files: debian/signatures/*
License: public-domain
Digital signatures and certificates are presumed not to be
copyrightable works, and no copyright is claimed for them.
Comment:
The signatures and certificates in this package cannot be regenerated
as-is without the associated private key material, but they can be
replaced using alternate private keys.
Files: debian/rules
Copyright: 2016,2018 Debian kernel team
License: GPL-2
This package is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License
along with this package; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
.
On Debian systems, the complete text of the GNU General Public
License version 2 can be found in `/usr/share/common-licenses/GPL-2'.
Files: debian/*
Copyright: 2016,2018 Debian kernel team
License: GPL-2+
This package is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License
along with this package; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
.
On Debian systems, the complete text of the GNU General Public
License version 2 can be found in `/usr/share/common-licenses/GPL-2'.

20
debian/signing_templates/rules vendored Executable file
View File

@ -0,0 +1,20 @@
#!/usr/bin/make -f
SHELL := sh -e
DEB_HOST_ARCH := $(shell dpkg-architecture -qDEB_HOST_ARCH)
build: build-arch build-indep
build-arch:
build-indep:
clean:
dh_testdir
dh_clean
binary: binary-arch binary-indep
binary-arch: debian/control
dh_testdir
$(MAKE) -f debian/rules.gen binary-arch_$(DEB_HOST_ARCH)
binary-indep:
.PHONY: build build-arch build-indep clean binary binary-arch binary-indep

75
debian/signing_templates/rules.real vendored Normal file
View File

@ -0,0 +1,75 @@
SHELL := bash -e
export DH_OPTIONS
build-indep:
install-signed: DH_OPTIONS = -p$(PACKAGE_NAME)
install-signed: KERNEL_VERSION = $(ABINAME)$(LOCALVERSION)
install-signed: IMAGE_PACKAGE_NAME = linux-image-$(KERNEL_VERSION)-unsigned
install-signed: PACKAGE_DIR = debian/$(PACKAGE_NAME)
install-signed: SIGNATURE_DIR = debian/signatures/$(IMAGE_PACKAGE_NAME)
install-signed:
mkdir -p $(PACKAGE_DIR)/boot
rsync -a $(patsubst %,/boot/%-$(KERNEL_VERSION),config System.map $(IMAGE_INSTALL_STEM)) \
$(PACKAGE_DIR)/boot/
if [ -f $(SIGNATURE_DIR)/boot/vmlinuz-$(KERNEL_VERSION).sig ]; then \
sbattach --attach $(SIGNATURE_DIR)/boot/vmlinuz-$(KERNEL_VERSION).sig \
$(PACKAGE_DIR)/boot/vmlinuz-$(KERNEL_VERSION); \
echo >> debian/$(PACKAGE_NAME).substvars 'signed:Description=The kernel image and modules are signed for use with Secure Boot.'; \
else \
echo >> debian/$(PACKAGE_NAME).substvars 'signed:Description=The modules are signed.'; \
fi
mkdir -p $(PACKAGE_DIR)/lib/modules/$(KERNEL_VERSION)
rsync -a $(addprefix /lib/modules/$(KERNEL_VERSION)/,kernel modules.builtin modules.order) \
$(PACKAGE_DIR)/lib/modules/$(KERNEL_VERSION)/
while read path; do \
/usr/lib/linux-kbuild-$(VERSION)/scripts/sign-file -s \
$(SIGNATURE_DIR)/lib/modules/$(KERNEL_VERSION)/$$path \
sha256 dummy \
$(PACKAGE_DIR)/lib/modules/$(KERNEL_VERSION)/$${path%.sig}; \
done < <(find $(SIGNATURE_DIR)/lib/modules/$(KERNEL_VERSION) -name '*.sig' -printf '%P\n')
# Copy any device tree files
if [ -d /usr/lib/linux-image-$(KERNEL_VERSION) ]; then \
mkdir -p $(PACKAGE_DIR)/usr/lib/linux-image-$(KERNEL_VERSION); \
rsync -a /usr/lib/linux-image-$(KERNEL_VERSION)/ \
$(PACKAGE_DIR)/usr/lib/linux-image-$(KERNEL_VERSION)/; \
fi
# Copy bug scripts but change the info file to refer to the right package
mkdir -p $(PACKAGE_DIR)/usr/share/bug/$(PACKAGE_NAME)
rsync -a /usr/share/bug/$(IMAGE_PACKAGE_NAME)/ \
$(PACKAGE_DIR)/usr/share/bug/$(PACKAGE_NAME)/
sed -i -e 's/^PACKAGE_NAME=.*/PACKAGE_NAME=$(PACKAGE_NAME)/' \
-e 's/^PACKAGE_VERSION=.*/PACKAGE_VERSION=$(PACKAGE_VERSION)/' \
$(PACKAGE_DIR)/usr/share/bug/$(PACKAGE_NAME)/info
dh_install
dh_installchangelogs
cp /usr/share/doc/$(IMAGE_PACKAGE_NAME)/changelog.Debian.gz \
$(PACKAGE_DIR)/usr/share/doc/$(PACKAGE_NAME)/changelog.linux.gz
dh_installdocs
cp /usr/share/doc/$(IMAGE_PACKAGE_NAME)/copyright \
$(PACKAGE_DIR)/usr/share/doc/$(PACKAGE_NAME)/copyright.linux
dh_compress -Xcopyright.linux
dh_fixperms
dh_installdeb
# Copy most package relations and description from unsigned package
for field in Depends Suggests Recommends Breaks; do \
echo >> debian/$(PACKAGE_NAME).substvars "unsigned:$$field=$$(dpkg-query -f '$${'$$field'}' -W $(IMAGE_PACKAGE_NAME))"; \
done
echo >> debian/$(PACKAGE_NAME).substvars "unsigned:DescriptionShort=$$(dpkg-query -f '$${Description}' -W $(IMAGE_PACKAGE_NAME) | head -n 1)"
echo >> debian/$(PACKAGE_NAME).substvars "unsigned:DescriptionLong=$$(dpkg-query -f '$${Description}' -W $(IMAGE_PACKAGE_NAME) | tail -n +2 | sed -rz 's/\$$/$${}/g; s/^ //; s/\n \.?/$${Newline}/g')"
dh_gencontrol -- $(GENCONTROL_ARGS)
dh_md5sums
dh_builddeb
install-udeb_$(ARCH): export KW_DEFCONFIG_DIR=/usr/share/linux-support-$(ABINAME)/installer
install-udeb_$(ARCH): export KW_CONFIG_DIR=/usr/share/linux-support-$(ABINAME)/installer/$(ARCH)
install-udeb_$(ARCH): DH_OPTIONS=$(PACKAGE_NAMES:%=-p%)
install-udeb_$(ARCH):
dh_testdir
dh_prep
kernel-wedge install-files $(ABINAME)
kernel-wedge check $(PACKAGE_NAMES)
dh_fixperms
dh_gencontrol -- $(GENCONTROL_ARGS)
dh_builddeb

View File

@ -0,0 +1 @@
3.0 (native)

View File

@ -0,0 +1,5 @@
Package: linux-image-@arch@-signed-template
Build-Profiles: <!stage1>
Description: Template for signed linux-image packages for @arch@
This package is used to control code signing by the Debian signing
service.