diff -Nru ubuntu-core-initramfs-46+ppa4/ARCHITECTURE.md ubuntu-core-initramfs-51.5/ARCHITECTURE.md --- ubuntu-core-initramfs-46+ppa4/ARCHITECTURE.md 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/ARCHITECTURE.md 2023-03-23 07:54:39.000000000 +0000 @@ -0,0 +1,70 @@ +# Core-initrd architecture + +In UC20, initrd is migrated from script based implementation (UC16/18) +to **systemd based**. Here we do a high-level description of UC20's +core-initrd architecture. The repository contains a native debian +source package which contains different files and helper scripts that +are used to build an initramfs that is used in Ubuntu Core systems. + +This package is meant to be installed in a classic Ubuntu system +jointly with a kernel so an initrd and a `kernel.efi` binary are +built. On x86, the latter must be included in a kernel snap so it can +be loaded by grub to start a UC system. For other architectures, we +might need only the generated initramfs. + +The generated `kernel.efi` binaries are EFI Unified Kernel Images, as +described under "Type #2" in systemd's [bootloader +specification](https://systemd.io/BOOT_LOADER_SPECIFICATION/) (BLS). + +## Directory structure + +``` +|-bin -> helper scripts to build the initramfs +|-debian -> debian folder to build deb package +|-factory -> some files that will be included verbatim in the initramfs +|-features -> files also part of the initramfs, but optional +|-postinst.d -> script that will run on kernel updates +|-snakeoil -> keys to sign binaries for testing +|-tests -> spread tests +└-vendor -> vendordized systemd +``` + +In more detail, + +- `bin/` contains the `ubuntu-core-initramfs` python script, that is + used to generate the initramfs and the `kernel.efi` file. +- `debian/` is used to build the debian binary package, including the + vendordized systemd +- `factory/` essentially consists of configuration files and some + additional scripts used by some services. These files are copied to + the target initramfs. +- `features/` defines additional files to add to the initramfs, but + selectable when running `ubuntu-core-initramfs` via the `--feature` + argument. This allows some flexibility when creating the + initramfs. Each "feature" matches a subfolder inside + `features/`. Currently we have `server` and `cloudimg-rootfs`. The + former is selected when building x86 images, while the latter is + added when building cloud images. +- `postinst.d/` contains a script that is installed as a kernel hook + when the deb is installed. This scripts rebuilds initramfs and EFI + image on kernel installation. +- `snakeoil/` contains a public/private key pair that is used to sign + the EFI image by default by `ubuntu-core-initramfs`, and a file with + UEFI variables for OVMF (which includes the public key) that is + used by the spread tests. +- `tests/` contains spread tests that are run by CI/CD +- `vendor/` contains a vendordized version of systemd with some + modifications compared to the one in Ubuntu 20.04. The additional + patches are + - `ubuntu-core-initramfs-clock-util-read-timestamp-from-usr-lib-clock-epoch.patch`, + which was taken from upstream + - `ubuntu-core-initramfs-fix-default.target`, that changes the default + target for the initrd + +## Typical boot sequence + +On arm SBC's: +FSBL-->SBL-->Uboot-->Kernel-->**Initrd**-->pivot-root to persistent storage root. + +On amd64 devices: +Bootrom-->UEFI Firmware-->shim-->GRUB-->sd-stub->Kernel-->**Initrd**-->pivot-root to persistent storage root. diff -Nru ubuntu-core-initramfs-46+ppa4/bin/ubuntu-core-initramfs ubuntu-core-initramfs-51.5/bin/ubuntu-core-initramfs --- ubuntu-core-initramfs-46+ppa4/bin/ubuntu-core-initramfs 2021-06-08 14:21:26.000000000 +0000 +++ ubuntu-core-initramfs-51.5/bin/ubuntu-core-initramfs 2023-03-23 07:54:39.000000000 +0000 @@ -34,7 +34,7 @@ for feature in args.features: # Needs https://github.com/snapcore/snapd/pull/10351 to land if feature == "cloudimg-rootfs": - os.unlink(os.path.join(main, "usrlib/systemd/system/sysroot.mount")) + os.unlink(os.path.join(main, "usr/lib/systemd/system/sysroot.mount")) subprocess.check_call(["cp", "-ar", "%s/%s/." % (args.skeleton, feature), main]) # Update epoch pathlib.Path("%s/main/usr/lib/clock-epoch" % d).touch() @@ -78,12 +78,14 @@ for early in glob.iglob("%s/early/*.cpio" % args.skeleton): with open(early, "rb") as f: shutil.copyfileobj(f, output) - subprocess.check_call( - "find . | cpio --create --quiet --format='newc' --owner=0:0 | lz4 -9 -l", - cwd=main, - shell=True, - stdout=output, - ) + output.write( + subprocess.run( + "find . | cpio --create --quiet --format='newc' --owner=0:0 | lz4 -9 -l", + cwd=main, + capture_output=True, + shell=True, + check=True, + ).stdout) def create_efi(parser, args): @@ -91,6 +93,7 @@ parser.error("--stub is required, and one was not automatically detected") if args.root: args.stub = os.path.join(args.root, args.stub) + args.sbat = os.path.join(args.root, args.sbat) args.kernel = os.path.join(args.root, args.kernel) args.initrd = os.path.join(args.root, args.initrd) args.key = os.path.join(args.root, args.key) @@ -100,19 +103,19 @@ args.kernel = "-".join([args.kernel, args.kernelver]) args.initrd = "-".join([args.initrd, args.kernelver]) args.output = "-".join([args.output, args.kernelver]) + + # kernel.efi map + # 0x0000000 stub + # 0x0020000 .osrel + # 0x0030000 .cmdline + # 0x0040000 .splash + # 0x0050000 .sbat + # 0x2000000 .linux + # 0x3000000 .initrd objcopy_cmd = [ "objcopy", - "--add-section", - ".linux=%s" % args.kernel, - "--change-section-vma", - ".linux=0x40000", - "--add-section", - ".initrd=%s" % args.initrd, - "--change-section-vma", - ".initrd=0x3000000", - args.stub, - args.output, ] + # TODO add .osrel if args.cmdline: cmdline = tempfile.NamedTemporaryFile(mode='w') cmdline.write('%s' % args.cmdline) @@ -123,6 +126,27 @@ "--change-section-vma", ".cmdline=0x30000" ] + # TODO add .splash + objcopy_cmd += [ + "--add-section", + ".sbat=%s" % args.sbat, + "--set-section-flags", + ".sbat=contents,alloc,load,readonly,data", + "--change-section-vma", + ".sbat=0x50000", + "--set-section-alignment", + ".sbat=4096", + "--add-section", + ".linux=%s" % args.kernel, + "--change-section-vma", + ".linux=0x2000000", + "--add-section", + ".initrd=%s" % args.initrd, + "--change-section-vma", + ".initrd=0x3000000", + args.stub, + args.output, + ] subprocess.check_call(objcopy_cmd) if not args.unsigned: subprocess.check_call( @@ -153,6 +177,8 @@ ) efi_parser.add_argument("--root", help="path to root") efi_parser.add_argument("--stub", help="path to stub") + efi_parser.add_argument("--sbat", help="path to sbat", + default="/usr/lib/ubuntu-core-initramfs/efi/sbat.txt") if suffix: efi_parser.set_defaults( stub="/usr/lib/ubuntu-core-initramfs/efi/linux%s.efi.stub" % suffix diff -Nru ubuntu-core-initramfs-46+ppa4/debian/changelog ubuntu-core-initramfs-51.5/debian/changelog --- ubuntu-core-initramfs-46+ppa4/debian/changelog 2021-06-08 16:58:08.000000000 +0000 +++ ubuntu-core-initramfs-51.5/debian/changelog 2023-03-23 08:10:58.000000000 +0000 @@ -1,5 +1,47 @@ -ubuntu-core-initramfs (46+ppa4) focal; urgency=medium +ubuntu-core-initramfs (51.5) focal; urgency=medium + + * Pick up snap-bootstrap from snapd 2.59 + + [ Dimitri John Ledkov ] + * vendor/systemd: maintain stable default net-naming-scheme (LP#1945225) + + -- Alfonso Sanchez-Beato Thu, 23 Mar 2023 08:10:58 +0000 + +ubuntu-core-initramfs (51.4) focal; urgency=medium + + * Update systemd to 245.4-4ubuntu3.19 + + -- Valentin David Thu, 08 Dec 2022 09:29:43 +0100 + +ubuntu-core-initramfs (51.3) focal; urgency=medium + + * No change rebuild to pick up snap-bootstrap from snapd 2.57.2 + + -- Alfonso Sanchez-Beato Mon, 05 Sep 2022 11:10:41 +0100 + +ubuntu-core-initramfs (51.2) focal; urgency=medium + + * Update to cloudimg-rootfs feature with ephemeral sysroot.mount and + unmounted ubuntu-seed partition (ESP). + + -- Dimitri John Ledkov Wed, 22 Jun 2022 15:10:11 +0100 + +ubuntu-core-initramfs (51.1) focal; urgency=medium + + * doc: add instructions on how to release the package + * Rebuild to pull snap-bootstrap from snapd deb 2.54.4+20.04 + + [ Philip Meulengracht ] + * spread: add spread and CI testing for core20 version of core-initrd + + [ Valentin David ] + * HACKING.md: Fix a few details + * tests: Properly call ubuntu-core-initramfs to generate the initrd + + -- Alfonso Sanchez-Beato (email Canonical) Thu, 10 Mar 2022 15:17:38 +0100 + +ubuntu-core-initramfs (51) focal; urgency=medium * Initial Release. - -- Dimitri John Ledkov Tue, 08 Jun 2021 17:58:08 +0100 + -- Dimitri John Ledkov Wed, 09 Jun 2021 11:34:39 +0100 diff -Nru ubuntu-core-initramfs-46+ppa4/debian/control ubuntu-core-initramfs-51.5/debian/control --- ubuntu-core-initramfs-46+ppa4/debian/control 2021-06-08 16:58:08.000000000 +0000 +++ ubuntu-core-initramfs-51.5/debian/control 2023-03-23 07:54:39.000000000 +0000 @@ -16,6 +16,7 @@ meson (>= 0.49), gettext, gperf, + git, gnu-efi [amd64 i386 arm64 armhf], libcap-dev (>= 1:2.24-9~), libpam0g-dev, @@ -58,6 +59,7 @@ libgcc-s1, squashfs-tools, snapd (>= 2.50+20.04), + systemd-bootchart, golang-go, indent, libapparmor-dev, libcap-dev, libfuse-dev, libglib2.0-dev, liblzma-dev, liblzo2-dev, libseccomp-dev, libudev-dev, openssh-client, pkg-config, python3, python3-docutils, python3-markdown, squashfs-tools, tzdata, udev, xfslibs-dev Standards-Version: 4.4.1 Homepage: https://launchpad.net/ubuntu-core-initramfs diff -Nru ubuntu-core-initramfs-46+ppa4/debian/install ubuntu-core-initramfs-51.5/debian/install --- ubuntu-core-initramfs-46+ppa4/debian/install 2021-06-07 15:13:19.000000000 +0000 +++ ubuntu-core-initramfs-51.5/debian/install 2023-03-23 07:54:39.000000000 +0000 @@ -3,4 +3,5 @@ snakeoil/* usr/lib/ubuntu-core-initramfs/snakeoil/ debian/tmp/* usr/lib/ubuntu-core-initramfs/main debian/tmp/usr/lib/systemd/boot/efi/linux*.efi.stub usr/lib/ubuntu-core-initramfs/efi/ +debian/sbat.txt usr/lib/ubuntu-core-initramfs/efi/ features/* usr/lib/ubuntu-core-initramfs/ diff -Nru ubuntu-core-initramfs-46+ppa4/debian/rules ubuntu-core-initramfs-51.5/debian/rules --- ubuntu-core-initramfs-46+ppa4/debian/rules 2021-06-08 16:58:08.000000000 +0000 +++ ubuntu-core-initramfs-51.5/debian/rules 2023-03-23 07:54:49.000000000 +0000 @@ -72,6 +72,7 @@ -Dwheel-group=false \ -Ddev-kvm-mode=0660 \ -Dgroup-render-mode=0660 \ + -Ddefault-net-naming-scheme=v245 \ -Ddefault-dnssec=no \ -Dselinux=true \ -Ddefault-kill-user-processes=false \ @@ -125,6 +126,7 @@ cd vendor/systemd; QUILT_PATCHES=debian/patches quilt pop -a || true rm -rf vendor/systemd/.pc +override_dh_auto_install: TEMPLIBDIR := $(shell mktemp -d) override_dh_auto_install: rm -rf debian/tmp mkdir debian/tmp @@ -183,9 +185,18 @@ ln -v -s busybox debian/tmp/usr/bin/$$alias; \ done + # We want the deps from the systemd libs we have compiled, not from the ones + # installed in the system. Copy them around so we can point LD_LIBRARY_PATH + # to them. + for lib in libudev.so libnss_systemd.so libsystemd.so; do \ + cp -a $(CURDIR)/debian/tmp/lib/$(DEB_HOST_MULTIARCH)/$$lib* $(TEMPLIBDIR); \ + done + cp -a $(CURDIR)/debian/tmp/usr/lib/systemd/libsystemd-shared* $(TEMPLIBDIR) + set -e; \ - for f in "/lib/$(DEB_HOST_MULTIARCH)/libnss_files.so.* /lib/$(DEB_HOST_MULTIARCH)/libnss_compat.so.* /lib/$(DEB_HOST_MULTIARCH)/libgcc_s.so.1 /sbin/e2fsck /sbin/fsck.vfat /sbin/fsck /bin/umount /bin/mount /bin/kmod /usr/bin/unsquashfs /sbin/dmsetup /usr/lib/snapd/snap-bootstrap /usr/lib/snapd/info /lib/systemd/system/snapd.recovery-chooser-trigger.service"; do \ - /usr/lib/dracut/dracut-install -D $(CURDIR)/debian/tmp --ldd $$f; \ + for f in "/lib/$(DEB_HOST_MULTIARCH)/libnss_files.so.* /lib/$(DEB_HOST_MULTIARCH)/libnss_compat.so.* /lib/$(DEB_HOST_MULTIARCH)/libgcc_s.so.1 /sbin/e2fsck /sbin/fsck.vfat /sbin/fsck /bin/umount /bin/mount /bin/kmod /usr/bin/unsquashfs /sbin/dmsetup /usr/lib/snapd/snap-bootstrap /usr/lib/snapd/info /lib/systemd/systemd-bootchart /lib/systemd/system/snapd.recovery-chooser-trigger.service"; do \ + LD_PRELOAD= LD_LIBRARY_PATH=$(TEMPLIBDIR) \ + /usr/lib/dracut/dracut-install -D $(CURDIR)/debian/tmp --ldd $$f; \ done dpkg -L dmsetup | grep rules.d | xargs -L1 /usr/lib/dracut/dracut-install -D $(CURDIR)/debian/tmp --ldd ifeq ($(DEB_HOST_ARCH),amd64) @@ -197,17 +208,30 @@ set -e; \ for e in $$(find debian/tmp -type f -executable); do \ - /usr/lib/dracut/dracut-install -D $(CURDIR)/debian/tmp --resolvelazy $$e ; \ + LD_PRELOAD= LD_LIBRARY_PATH=$(TEMPLIBDIR) \ + /usr/lib/dracut/dracut-install -D $(CURDIR)/debian/tmp --resolvelazy $$e ; \ done - ldconfig -r debian/tmp + rm -rf $(TEMPLIBDIR) + # dracut has installed the libraries from TEMPLIBDIR inside the packaging + # folder, remove that artifact too. + rm -rf debian/tmp/tmp/ override_dh_install: dh_install +ifneq ($(CI),true) +ifeq ($(DEB_HOST_ARCH_BITS),64) + # This builds a forked snap-bootstrap ito the "cloudimg-rootfs" feature + # directory. This is *not* used unless "--feature main cloudimg-rootfs" + # is specified . This is only done for the certain cloud kernels during + # the "core-initrd create-initrd" time. + # # Forked snap-bootstrap until https://github.com/snapcore/snapd/pull/10267 lands GOPATH=$(CURDIR)/vendor/gopath/ HOME=$(CURDIR)/debian CGO_ENABLED=1 go build -buildmode=pie -tags nomanagers -o $(CURDIR)/debian/$(DEB_SOURCE)/usr/lib/$(DEB_SOURCE)/cloudimg-rootfs/usr/lib/snapd/snap-bootstrap github.com/snapcore/snapd/cmd/snap-bootstrap # For some reason tests fail when building in chroot GOPATH=$(CURDIR)/vendor/gopath/ HOME=$(CURDIR)/debian CGO_ENABLED=1 go test -buildmode=pie -tags nomanagers github.com/snapcore/snapd/cmd/snap-bootstrap || : +endif +endif rm -rf debian/ubuntu-core-initramfs/usr/lib/ubuntu-core-initramfs/main/usr/lib/systemd/boot ifeq ($(DEB_HOST_ARCH),amd64) mkdir -p debian/ubuntu-core-initramfs/usr/lib/ubuntu-core-initramfs/early/ @@ -215,7 +239,11 @@ endif override_dh_clean: - [ -d vendor/gopath ] || ( mkdir -p vendor/gopath/src/github.com/snapcore/; cd vendor/gopath/src/github.com/snapcore; git clone -b run-cloudimg-rootfs-draft-1 https://github.com/xnox/snapd.git; cd snapd; GOPATH= ./get-deps.sh ) +ifneq ($(CI),true) + # only needed for the "--feature main cloudimg-rootfs", not used for the + # default initrd + [ -d vendor/gopath ] || ( mkdir -p vendor/gopath/src/github.com/snapcore/; cd vendor/gopath/src/github.com/snapcore; git clone -b run-cloudimg-rootfs-draft-1-umount https://github.com/xnox/snapd.git; cd snapd; git checkout d93cbf93837224131b21716d76c14d6cfd784a65; GOPATH= ./get-deps.sh ) +endif dh_clean override_dh_python3: diff -Nru ubuntu-core-initramfs-46+ppa4/debian/sbat.txt ubuntu-core-initramfs-51.5/debian/sbat.txt --- ubuntu-core-initramfs-46+ppa4/debian/sbat.txt 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/debian/sbat.txt 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,3 @@ +sbat,1,SBAT Version,sbat,1,https://github.com/rhboot/shim/blob/main/SBAT.md +systemd,1,The systemd Developers,systemd,245,https://www.freedesktop.org/wiki/Software/systemd +systemd.ubuntu,1,Ubuntu,systemd,245.4-4ubuntu3.6,https://bugs.launchpad.net/ubuntu/ Binary files /tmp/tmp7x14ovzp/BLyL3OAKjZ/ubuntu-core-initramfs-46+ppa4/factory/lib/snapd/snap-bootstrap and /tmp/tmp7x14ovzp/ESRRdmIyl5/ubuntu-core-initramfs-51.5/factory/lib/snapd/snap-bootstrap differ diff -Nru ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/bootchart.conf.d/ubuntu-core.conf ubuntu-core-initramfs-51.5/factory/lib/systemd/bootchart.conf.d/ubuntu-core.conf --- ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/bootchart.conf.d/ubuntu-core.conf 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/lib/systemd/bootchart.conf.d/ubuntu-core.conf 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,8 @@ +[Bootchart] +Samples=36000 +Frequency=20 +Relative=yes +Filter=no +# Memory usage produces a bad overlay in the svg +#PlotMemoryUsage=yes +Cmdline=yes diff -Nru ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/initrd-switch-root.service.d/core-override.conf ubuntu-core-initramfs-51.5/factory/lib/systemd/system/initrd-switch-root.service.d/core-override.conf --- ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/initrd-switch-root.service.d/core-override.conf 2020-11-16 10:50:20.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/lib/systemd/system/initrd-switch-root.service.d/core-override.conf 2023-03-23 07:54:39.000000000 +0000 @@ -1,5 +1,18 @@ [Service] +# This empty "ExecStart" does override the original ExecStat from the +# "real" initrd-switch-root.service that would do a stateful re-exec. ExecStart= -#Ensure that we do not perform stateful reexec (boot fails) -#Ensure that we ignore kernel cmdline init= parameter (dangerous) +# Currently doing a stateful re-exec will fail. The reasons are a bit +# unclear, it seems to be related to the fact that systemd is confused +# by the mount units in the initrd that are not there in the new pivot +# root. So this systemctl call to "/sbin/init" is a workaround to prevent +# systemd from doing a stateful re-exec (there is no other way to +# prevent this). +# +# Using "/sbin/init" here directly also ensures that the kernel commandline +# "init=" parameter is ignored as it would allow to bypass our protections. +# +# XXX: we should fix this eventually (this may involve upstream work) +# because this also prevents "systemd-analyze time" from displaying +# the time spend in the initrd. ExecStart=/bin/systemctl --no-block switch-root /sysroot /sbin/init diff -Nru ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/initrd-switch-root.target.wants/systemd-bootchart-quit.service ubuntu-core-initramfs-51.5/factory/lib/systemd/system/initrd-switch-root.target.wants/systemd-bootchart-quit.service --- ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/initrd-switch-root.target.wants/systemd-bootchart-quit.service 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/lib/systemd/system/initrd-switch-root.target.wants/systemd-bootchart-quit.service 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,9 @@ +[Unit] +Description=Stop Boot Process Profiler +DefaultDependencies=no +Before=initrd-switch-root.service +ConditionKernelCommandLine=core.bootchart + +[Service] +Type=oneshot +ExecStart=-/usr/bin/systemctl stop systemd-bootchart.service diff -Nru ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/sysinit.target.wants/systemd-bootchart.service ubuntu-core-initramfs-51.5/factory/lib/systemd/system/sysinit.target.wants/systemd-bootchart.service --- ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/sysinit.target.wants/systemd-bootchart.service 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/lib/systemd/system/sysinit.target.wants/systemd-bootchart.service 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,10 @@ +[Unit] +Description=Boot Process Profiler +Documentation=man:systemd-bootchart.service(1) man:bootchart.conf(5) +DefaultDependencies=no +ConditionKernelCommandLine=core.bootchart + +[Service] +ExecStartPre=/usr/sbin/mkdir -p /run/log +ExecStart=/lib/systemd/systemd-bootchart -r +KillSignal=SIGHUP diff -Nru ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/systemd-bootchart-quit.service ubuntu-core-initramfs-51.5/factory/lib/systemd/system/systemd-bootchart-quit.service --- ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/systemd-bootchart-quit.service 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/lib/systemd/system/systemd-bootchart-quit.service 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,9 @@ +[Unit] +Description=Stop Boot Process Profiler +DefaultDependencies=no +Before=initrd-switch-root.service +ConditionKernelCommandLine=core.bootchart + +[Service] +Type=oneshot +ExecStart=-/usr/bin/systemctl stop systemd-bootchart.service diff -Nru ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/systemd-bootchart.service ubuntu-core-initramfs-51.5/factory/lib/systemd/system/systemd-bootchart.service --- ubuntu-core-initramfs-46+ppa4/factory/lib/systemd/system/systemd-bootchart.service 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/lib/systemd/system/systemd-bootchart.service 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,10 @@ +[Unit] +Description=Boot Process Profiler +Documentation=man:systemd-bootchart.service(1) man:bootchart.conf(5) +DefaultDependencies=no +ConditionKernelCommandLine=core.bootchart + +[Service] +ExecStartPre=/usr/sbin/mkdir -p /run/log +ExecStart=/lib/systemd/systemd-bootchart -r +KillSignal=SIGHUP Binary files /tmp/tmp7x14ovzp/BLyL3OAKjZ/ubuntu-core-initramfs-46+ppa4/factory/usr/lib/snapd/snap-bootstrap and /tmp/tmp7x14ovzp/ESRRdmIyl5/ubuntu-core-initramfs-51.5/factory/usr/lib/snapd/snap-bootstrap differ diff -Nru ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/bootchart.conf.d/ubuntu-core.conf ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/bootchart.conf.d/ubuntu-core.conf --- ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/bootchart.conf.d/ubuntu-core.conf 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/bootchart.conf.d/ubuntu-core.conf 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,8 @@ +[Bootchart] +Samples=36000 +Frequency=20 +Relative=yes +Filter=no +# Memory usage produces a bad overlay in the svg +#PlotMemoryUsage=yes +Cmdline=yes diff -Nru ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/initrd-switch-root.service.d/core-override.conf ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/initrd-switch-root.service.d/core-override.conf --- ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/initrd-switch-root.service.d/core-override.conf 2020-11-16 10:50:20.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/initrd-switch-root.service.d/core-override.conf 2023-03-23 07:54:39.000000000 +0000 @@ -1,5 +1,18 @@ [Service] +# This empty "ExecStart" does override the original ExecStat from the +# "real" initrd-switch-root.service that would do a stateful re-exec. ExecStart= -#Ensure that we do not perform stateful reexec (boot fails) -#Ensure that we ignore kernel cmdline init= parameter (dangerous) +# Currently doing a stateful re-exec will fail. The reasons are a bit +# unclear, it seems to be related to the fact that systemd is confused +# by the mount units in the initrd that are not there in the new pivot +# root. So this systemctl call to "/sbin/init" is a workaround to prevent +# systemd from doing a stateful re-exec (there is no other way to +# prevent this). +# +# Using "/sbin/init" here directly also ensures that the kernel commandline +# "init=" parameter is ignored as it would allow to bypass our protections. +# +# XXX: we should fix this eventually (this may involve upstream work) +# because this also prevents "systemd-analyze time" from displaying +# the time spend in the initrd. ExecStart=/bin/systemctl --no-block switch-root /sysroot /sbin/init diff -Nru ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/initrd-switch-root.target.wants/systemd-bootchart-quit.service ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/initrd-switch-root.target.wants/systemd-bootchart-quit.service --- ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/initrd-switch-root.target.wants/systemd-bootchart-quit.service 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/initrd-switch-root.target.wants/systemd-bootchart-quit.service 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,9 @@ +[Unit] +Description=Stop Boot Process Profiler +DefaultDependencies=no +Before=initrd-switch-root.service +ConditionKernelCommandLine=core.bootchart + +[Service] +Type=oneshot +ExecStart=-/usr/bin/systemctl stop systemd-bootchart.service diff -Nru ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/sysinit.target.wants/systemd-bootchart.service ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/sysinit.target.wants/systemd-bootchart.service --- ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/sysinit.target.wants/systemd-bootchart.service 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/sysinit.target.wants/systemd-bootchart.service 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,10 @@ +[Unit] +Description=Boot Process Profiler +Documentation=man:systemd-bootchart.service(1) man:bootchart.conf(5) +DefaultDependencies=no +ConditionKernelCommandLine=core.bootchart + +[Service] +ExecStartPre=/usr/sbin/mkdir -p /run/log +ExecStart=/lib/systemd/systemd-bootchart -r +KillSignal=SIGHUP diff -Nru ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/systemd-bootchart-quit.service ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/systemd-bootchart-quit.service --- ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/systemd-bootchart-quit.service 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/systemd-bootchart-quit.service 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,9 @@ +[Unit] +Description=Stop Boot Process Profiler +DefaultDependencies=no +Before=initrd-switch-root.service +ConditionKernelCommandLine=core.bootchart + +[Service] +Type=oneshot +ExecStart=-/usr/bin/systemctl stop systemd-bootchart.service diff -Nru ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/systemd-bootchart.service ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/systemd-bootchart.service --- ubuntu-core-initramfs-46+ppa4/factory/usr/lib/systemd/system/systemd-bootchart.service 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/factory/usr/lib/systemd/system/systemd-bootchart.service 2022-01-05 10:16:01.000000000 +0000 @@ -0,0 +1,10 @@ +[Unit] +Description=Boot Process Profiler +Documentation=man:systemd-bootchart.service(1) man:bootchart.conf(5) +DefaultDependencies=no +ConditionKernelCommandLine=core.bootchart + +[Service] +ExecStartPre=/usr/sbin/mkdir -p /run/log +ExecStart=/lib/systemd/systemd-bootchart -r +KillSignal=SIGHUP diff -Nru ubuntu-core-initramfs-46+ppa4/.github/workflows/lxd-image.yaml ubuntu-core-initramfs-51.5/.github/workflows/lxd-image.yaml --- ubuntu-core-initramfs-46+ppa4/.github/workflows/lxd-image.yaml 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/.github/workflows/lxd-image.yaml 2023-03-23 07:54:39.000000000 +0000 @@ -0,0 +1,30 @@ +name: Build LXD image +on: + workflow_dispatch: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Cleanup job workspace + id: cleanup-job-workspace + run: | + rm -rf "${{ github.workspace }}" + mkdir "${{ github.workspace }}" + - uses: actions/checkout@v2 + - name: Install spread + run: curl -s https://storage.googleapis.com/snapd-spread-tests/spread/spread-amd64.tar.gz | sudo tar xzv -C /usr/bin + - name: Run tests + env: + SPREAD_GOOGLE_KEY: ${{ secrets.SPREAD_GOOGLE_KEY }} + run: | + echo $SPREAD_GOOGLE_KEY > sa.json + spread google-nested:tests/spread/ci + + - name: Discard spread workers + if: always() + run: | + shopt -s nullglob + for r in .spread-reuse.*.yaml; do + spread -discard -reuse-pid="$(echo "$r" | grep -o -E '[0-9]+')" + done diff -Nru ubuntu-core-initramfs-46+ppa4/.github/workflows/tests.yml ubuntu-core-initramfs-51.5/.github/workflows/tests.yml --- ubuntu-core-initramfs-46+ppa4/.github/workflows/tests.yml 2021-06-08 14:12:33.000000000 +0000 +++ ubuntu-core-initramfs-51.5/.github/workflows/tests.yml 2023-03-23 07:54:39.000000000 +0000 @@ -5,23 +5,23 @@ - cron: '0 12 * * 0' push: branches: - - main + - core20 pull_request: branches: - - main + - core20 jobs: build: - runs-on: ubuntu-20.04 + runs-on: self-hosted steps: + - name: Cleanup job workspace + id: cleanup-job-workspace + run: | + rm -rf "${{ github.workspace }}" + mkdir "${{ github.workspace }}" - uses: actions/checkout@v2 - - name: Install spread - run: curl -s https://storage.googleapis.com/snapd-spread-tests/spread/spread-amd64.tar.gz | sudo tar xzv -C /usr/bin - - name: Run tests - env: - SPREAD_GOOGLE_KEY: ${{ secrets.SPREAD_GOOGLE_KEY }} run: | spread google-nested: diff -Nru ubuntu-core-initramfs-46+ppa4/HACKING.md ubuntu-core-initramfs-51.5/HACKING.md --- ubuntu-core-initramfs-46+ppa4/HACKING.md 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/HACKING.md 2023-03-23 07:54:39.000000000 +0000 @@ -0,0 +1,340 @@ +# Hacking the Initrd for Ubuntu Core + +This document explains how to modify & update initrd for Ubuntu Core + +# Purpose + +Sometimes you may need to alter the behaviour of stock initrd or you may want to add a new functionality to it. + +# Target platforms + +Modifying initrd is relatively easy for arm SBC's (Like RPi) or amd64 devices ( Like Intel NUCs ) without secure boot ( No TPM or PTT or similar) + +For devices with secure boot, one need to : + +TODO: Explain how to modify initrd when there is Secure boot / FDE. + +# Prequisities + +- A Linux Computer with various development tools + - Latest Ubuntu Desktop is recommended + - (For a SBC like RPi) you will need UART TTL serial debug cable (Because you will not have SSH in initrd) + - initramfs-tools + - snapcraft + - etc + +# Testing with spread + +## Prerequisites for testing + +You need to have the following software installed before you can test with spread + - Go (https://golang.org/doc/install or ```sudo snap install go```) + - Spread (install from source as per below) + +## Installing spread + +You can install spread by simply using ```snap install spread```, however this does not allow for the lxd-backend to be used. +To use the lxd backend you need to install spread from source, as the LXD profile support has not been upstreamed yet. +This document will be updated with the upstream version when the PR https://github.com/snapcore/spread/pull/136 merges. To install spread from source you need to do the following. + +``` +git clone https://github.com/Meulengracht/spread +cd spread +cd cmd/spread +go build . +go install . +``` + +## QEmu backend + +1. Install the dependencies required for the qemu emulation +``` +sudo apt update && sudo apt install -y qemu-kvm autopkgtest +``` +2. Create a suitable ubuntu test image (focal) in the following directory where spread locates images. Note that the location is different when using spread installed through snap. +``` +mkdir -p ~/.spread/qemu # This location is different if you installed spread from snap +cd ~/.spread/qemu +autopkgtest-buildvm-ubuntu-cloud -r focal +``` +3. Rename the newly built image as the name will not match what spread is expecting +``` +mv autopkgtest-focal-amd64.img ubuntu-20.04-64.img +``` +4. Now you are ready to run spread tests with the qemu backend +``` +cd ~/core-initrd # or wherever you checked out this repository +spread qemu-nested +``` + +## LXD backend +The LXD backend is the preffered way of testing locally as it uses virtualization and thus runs a lot quicker than +the qemu backend. This is because the container can use all the resources of the host, and we can support +qemu-kvm acceleration in the container for the nested instance. + +This backend requires that your host machine supports KVM. + +1. Setup any prerequisites and build the LXD image needed for testing. The following commands will install lxd +and yq (needed for yaml manipulation), download the newest image and import it into LXD. +``` +sudo snap install lxd +sudo snap install yq +curl -o lxd-initrd-img.tar.gz https://storage.googleapis.com/snapd-spread-core/lxd/lxd-spread-initrd-img.tar.gz +lxc image import lxd-initrd-img.tar.gz --alias ucspread +lxc image show ucspread > temp.profile +yq e '.properties.aliases = "ucspread,amd64"' -i ./temp.profile +yq e '.properties.remote = "images"' -i ./temp.profile +cat ./temp.profile | lxc image edit ucspread +rm ./temp.profile ./lxd-initrd-img.tar.gz +``` +2. Import the LXD coreinitrd test profile. Make sure your working directory is the root of this repository. +``` +lxc profile create coreinitrd +cat tests/spread/core-initrd.lxdprofile | lxc profile edit coreinitrd +``` +3. Set environment variable to enable KVM acceleration for the nested qemu instance +``` +export SPREAD_ENABLE_KVM=true +``` +4. Now you can run the spread tests using the LXD backend +``` +spread lxd-nested +``` + +# Debugging + +## Getting a debug shell in initrd + +Getting a debug shell in initrd is very simple: +1. Boot your UC20 image on your RPi +2. Access to it via SSH +3. Edit your kernel commandline: + +First your current kernel commandline is: +``` + ~$ cat /run/mnt/ubuntu-seed/cmdline.txt +dwc_otg.lpm_enable=0 console=serial0,115200 elevator=deadline rng_core.default_quality=700 vt.handoff=2 quiet splash + ~$ +``` +Now you need to add following three arguments to it: +``` +rd.systemd.debug_shell=serial0 dangerous rd.systemd.unit=emergency.service +``` + +So it will look like: +``` + ~$ cat /run/mnt/ubuntu-seed/cmdline.txt +dwc_otg.lpm_enable=0 console=serial0,115200 elevator=deadline rng_core.default_quality=700 vt.handoff=2 quiet splash rd.systemd.debug_shell=serial0 dangerous rd.systemd.unit=emergency.service + ~$ +``` + +**Warning**: Because of a [bug](https://bugs.launchpad.net/ubuntu/+source/flash-kernel/+bug/1933093) in boot.scr, following will not happen, and your RPi will boot to main rootfs again (you can ssh to it). Leaving this warning until this bug is fixed. + +Finally, after a reboot, you will get a shell like this: +``` +PM_RSTS: 0x00001000 +....lot of logs here +Starting start4.elf @ 0xfec00200 partition 0 + +U-Boot 2020.10+dfsg-1ubuntu0~20.04.2 (Jan 08 2021 - 13:03:11 +0000) + +DRAM: 3.9 GiB +....lot of logs +Decompressing kernel... +Uncompressed size: 23843328 = 0x16BD200 +20600685 bytes read in 1504 ms (13.1 MiB/s) +Booting Ubuntu (with booti) from mmc 0:... +## Flattened Device Tree blob at 02600000 + Booting using the fdt blob at 0x2600000 + Using Device Tree in place at 0000000002600000, end 000000000260f07f + +Starting kernel ... +[ 1.224420] spi-bcm2835 fe204000.spi: could not get clk: -517 + +BusyBox v1.30.1 (Ubuntu 1:1.30.1-4ubuntu6.3) built-in shell (ash) +Enter 'help' for a list of built-in commands. +# +``` + +In this state, if you want to pivot-root to main rootfs, just execute: + +``` +# systemctl start basic.target +``` + +# Hacking without re-building + +Sometimes, in order for testing some new feature, rebuilding is not necessary. It is possible to add your fancy nice application to current initrd.img. Depending on the board, we need to do different things, so we will show how to do this for an RPi and for x86 images. + +## Hacking an RPi initrd + +Basically: +- Download current initrd.img from your RPi to your host +- unpack it to a directory +- add your binary / systemd unit into it +- repack initrd.img +- upload to your RPi +- reboot + +``` + ~ $ mkdir uc-initrd + ~ $ cd uc-initrd/ + ~/uc-initrd $ scp pi:/run/mnt/ubuntu-boot/uboot/ubuntu/pi-kernel_292.snap/initrd.img . +initrd.img 100% 20MB 34.8MB/s 00:00 + ~/uc-initrd $ unmkinitramfs initrd.img somedir + ~/uc-initrd $ tree -L 1 somedir/ +somedir/ +├── bin -> usr/bin +├── etc +├── init -> usr/lib/systemd/systemd +├── lib -> usr/lib +├── lib64 -> usr/lib64 +├── sbin -> usr/bin +└── usr + +5 directories, 2 files + ~/uc-initrd $ echo "echo \"Hello world\"" > somedir/usr/bin/hello.sh + ~/uc-initrd $ chmod +x somedir/usr/bin/hello.sh + ~/uc-initrd $ somedir/usr/bin/hello.sh +Hello world + ~/uc-initrd $ + ~/uc-initrd $ cd somedir/ + ~/uc-initrd/somedir $ find ./ | cpio --create --quiet --format=newc --owner=0:0 | lz4 -9 -l > ../initrd.img.new +103890 blocks + ~/uc-initrd/somedir $ cd .. + ~/uc-initrd $ file initrd.img +initrd.img: LZ4 compressed data (v0.1-v0.9) + ~/uc-initrd $ file initrd.img.new +initrd.img.new: LZ4 compressed data (v0.1-v0.9) + ~/uc-initrd $ ll +total 40252 +drwxrwxr-x 3 4096 Haz 21 17:53 ./ +drwxr-x--- 36 4096 Haz 21 17:52 ../ +-rwxr-xr-x 1 20600685 Haz 21 17:43 initrd.img* +-rw-rw-r-- 1 20601051 Haz 21 17:53 initrd.img.new +drwxrwxr-x 4 4096 Haz 21 17:49 somedir/ + ~/uc-initrd $ scp initrd.img.new pi:/tmp/ +initrd.img.new 100% 20MB 41.6MB/s 00:00 + ~/uc-initrd $ ssh pi +Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-1037-raspi aarch64) +...... +Last login: Mon Jun 21 14:40:10 2021 from 192.168.1.247 + ~$ sudo cp /tmp/initrd.img.new /run/mnt/ubuntu-boot/uboot/ubuntu/pi-kernel_292.snap/initrd.img + ~$ sync + ~$ sudo reboot +Connection to 192.168.1.224 closed by remote host. +Connection to 192.168.1.224 closed. + ~/uc-initrd $ +``` + +And then, finally, on your serial console : +``` +Starting kernel ... + +[ 1.223730] spi-bcm2835 fe204000.spi: could not get clk: -517 + + +BusyBox v1.30.1 (Ubuntu 1:1.30.1-4ubuntu6.3) built-in shell (ash) +Enter 'help' for a list of built-in commands. + +# hello.sh +Hello world +# + +``` + +## Hacking generic x86 initrd + +For x86 the process is a bit different as in this case the initrd is a +section in a PE+/COFF binary. We can download the snap and extract the +initrd with: + +``` +$ snap download --channel=20/stable pc-kernel +$ unsquashfs -d pc-kernel pc-kernel_*.snap +$ objcopy -O binary -j .initrd pc-kernel/kernel.efi initrd.img +$ unmkinitramfs initrd.img initrd +``` + +Then, you can change the initrd as described in the RPi section. After +that, to repack everything, run these commands: + + +``` +$ cd initrd +$ find . | cpio --create --quiet --format=newc --owner=0:0 | lz4 -l -7 > ../initrd.img +$ cd - +$ sudo add-apt-repository ppa:snappy-dev/image +$ apt download ubuntu-core-initramfs +$ dpkg --fsys-tarfile ubuntu-core-initramfs_*_amd64.deb | + tar xf - ./usr/lib/ubuntu-core-initramfs/efi/linuxx64.efi.stub +$ objcopy -O binary -j .linux pc-kernel/kernel.efi linux +$ objcopy --add-section .linux=linux --change-section-vma .linux=0x2000000 \ + --add-section .initrd=initrd.img --change-section-vma .initrd=0x3000000 \ + usr/lib/ubuntu-core-initramfs/efi/linuxx64.efi.stub \ + pc-kernel/kernel.efi +$ snap pack pc-kernel +``` + +You can use this new kernel snap while building image, or copy it over +to your device and install. Note that the new `kernel.efi` won't be +signed, so Secure Boot will not be possible anymore. + +# Hacking with rebuilding + +The initrd is part of the kernel snap, so ideally we would prefer to +simply build it by using snapcraft. However, the snapcraft recipe for +the kernel downloads binaries from already built kernel packages, so +we cannot use it easily for local hacking. So we will provide +instructions on how to build the initrd from scratch and insert it in +the kernel snap. + +First, we need to build the debian package, for this you can use +debuild or dpkg-buildpackage from the root folder: + +``` +$ sudo apt build-dep ./ +$ debuild -us -uc +``` + +Then, install the package in the container: + +``` +$ sudo apt install ../ubuntu-core-initramfs_*.deb +``` + +We extract the kernel from the pc-kernel snap: + +``` +$ snap download --channel=20/stable pc-kernel +$ unsquashfs -d pc-kernel pc-kernel_*.snap +``` + +We can now extract the kernel image from kernel.efi: + +``` +$ snap info pc-kernel | grep 20/stable + 20/stable: 5.4.0-87.98.1 2021-09-30 (838) 295MB - +$ kernelver=5.4.0-87-generic +$ objcopy -O binary -j .linux pc-kernel/kernel.efi kernel.img-"${kernelver}" +``` + +We can inject it in the kernel snap as in previous sections. It is +also possible to force the build of `kernel.efi` (or just the initrd), with: + +``` +$ ubuntu-core-initramfs create-initrd --kernelver=$kernelver --kerneldir pc-kernel/modules/${kernelver} --firmwaredir pc-kernel/firmware --output initrd.img +$ ubuntu-core-initramfs create-efi --kernelver=$kernelver --initrd initrd.img --kernel kernel.img --output kernel.efi +``` + +Note that for RPi we need only the initrd image file. + +Now `kernel.efi-5.4.0-87-generic` has been created with the new initramfs. We can put it back into the snap: + +``` +$ cp kernel.efi-$kernelver pc-kernel/kernel.efi +$ snap pack pc-kernel +``` + +# Troubleshooting + diff -Nru ubuntu-core-initramfs-46+ppa4/README.md ubuntu-core-initramfs-51.5/README.md --- ubuntu-core-initramfs-46+ppa4/README.md 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/README.md 2023-03-23 07:54:39.000000000 +0000 @@ -0,0 +1,82 @@ +# Initrd for Ubuntu Core + +This repository contains source code to build initial ramdisk used in Ubuntu Core Embedded Linux OS. + +# Purpose + +See: https://en.wikipedia.org/wiki/Initial_ramdisk + +# Architecture + +In Ubuntu Core, initrd.img file is part of Kernel Snap as a binary. This file is brought to Kernel snap from a PPA. See [integration](#integrating-with-kernel-snap) below. + +In UC20, initrd is migrated from script based implementation (UC16/18) to **systemd based**. +See the [architecture document](ARCHITECTURE.md) for more details. + +# Building initrd for Ubuntu Core + +TODO: Write documentation for how to build initrd locally + +## Prequisities + +## Preparation + +## Building + +# Testing & Debugging + +See [Hacking](HACKING.md) + +# Releasing + +The UC initrd is included in kernel snaps. However, the process to get +it inside the kernel snap is not immediate and consists of a few +steps. First, we need to build the `ubuntu-core-initramfs` +debian package in the [snappy-dev/image +PPA](https://launchpad.net/~snappy-dev/+archive/ubuntu/image) by +following these steps: + +1. Update the changelog with latest changes since last release (use `dch -i` for this) +1. Commit using `debcommit --release -a` which will commit the changelog update & tag the release +1. Propose a PR to the repo with the new changelog, get it reviewed and merged +1. Push the tag to the repository with the new version (GitHub pull requests do not update tags) +1. Build the source package by running (note that the clean command + removes all untracked files, including subtrees with .git folders) + + git clean -ffdx + gbp buildpackage -S -sa -d --git-ignore-branch + +1. Compare with the latest package that was uploaded to the snappy-dev +PPA to make sure that the changes are correct. For this, you can +download the .dsc file and the tarball from the PPA, then run debdiff +to find out the differences: + + dget https://launchpad.net/~snappy-dev/+archive/ubuntu/image/+sourcefiles/ubuntu-core-initramfs//ubuntu-core-initramfs_.dsc + debdiff ubuntu-core-initramfs_.dsc ubuntu-core-initramfs_.dsc > diff.txt + +1. Upload, or request sponsorship, to the snappy-dev PPA + + dput ppa:snappy-dev/image ubuntu-core-initramfs__source.changes + +1. Make sure that the package has been built correctly. If not, make + changes appropriately and repeat these steps, including creating a + new changelog entry. + +Note that `ubuntu-core-initramfs` gets some files from its build +dependencies while being built, including for instance +`snap-bootstrap`, so we need to make sure that the snappy-dev PPA +already contains the desired version of the snapd deb package (or +others) when we upload the package. + +After this, the initrd changes will be included in future kernel snaps +releases automatically, following the usual 3 weeks cadence, as the +snappy-dev PPA is included when these build happen. + +# Bootchart + +It is possible to enable bootcharts by adding `core.bootchart` to the +kernel command line. The sample collector will run until the systemd +switches root, and the chart will be saved in `/run/log`. If +bootcharts are also enabled for the core snap, that file will be +eventually moved to the `ubuntu-save` partition (see Core snap +documentation). diff -Nru ubuntu-core-initramfs-46+ppa4/spread.yaml ubuntu-core-initramfs-51.5/spread.yaml --- ubuntu-core-initramfs-46+ppa4/spread.yaml 2021-06-04 09:36:12.000000000 +0000 +++ ubuntu-core-initramfs-51.5/spread.yaml 2023-03-23 07:54:39.000000000 +0000 @@ -5,7 +5,7 @@ PROJECT_PATH: $SETUPDIR PATH: $PATH:$PROJECT_PATH/tests/bin TESTSLIB: $PROJECT_PATH/tests/lib - TESTSTOOLS: $PROJECT_PATH/tests/lib/tools + SNAP_BRANCH: "edge" # stable/edge/beta # TODO: are these vars needed still? LANG: "C.UTF-8" LANGUAGE: "en" @@ -15,7 +15,7 @@ type: google key: '$(HOST: echo "$SPREAD_GOOGLE_KEY")' location: snapd-spread/us-east1-b - plan: n1-standard-2 + plan: n2-standard-2 halt-timeout: 2h systems: - ubuntu-20.04-64: @@ -33,6 +33,13 @@ username: ubuntu password: ubuntu + lxd-nested: + type: lxd + container-profiles: coreinitrd + systems: + - ubuntu-20.04: + image: ucspread + path: /home/core-initrd exclude: @@ -83,10 +90,14 @@ . "$TESTSLIB/nested.sh" cleanup_nested_core_vm +debug-each: | + . "$TESTSLIB/nested.sh" + print_nested_status + # it takes a while to build everything while preparing the project -warn-timeout: 20m +warn-timeout: 40m # but it shouldn't take _too_ long... -kill-timeout: 30m +kill-timeout: 50m suites: tests/spread/: diff -Nru ubuntu-core-initramfs-46+ppa4/tests/lib/nested.sh ubuntu-core-initramfs-51.5/tests/lib/nested.sh --- ubuntu-core-initramfs-46+ppa4/tests/lib/nested.sh 2020-11-16 10:50:20.000000000 +0000 +++ ubuntu-core-initramfs-51.5/tests/lib/nested.sh 2023-03-23 07:54:39.000000000 +0000 @@ -9,28 +9,17 @@ sshpass -p ubuntu ssh -p "$SSH_PORT" -o ConnectTimeout=10 -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ubuntu@localhost "$*" } -wait_for_service() { - local service_name="$1" - local state="${2:-active}" - for i in $(seq 300); do - if systemctl show -p ActiveState "$service_name" | grep -q "ActiveState=$state"; then - return - fi - # show debug output every 1min - if [ "$i" -gt 0 ] && [ $(( i % 60 )) = 0 ]; then - systemctl status "$service_name" || true; - fi - sleep 1; - done - - echo "service $service_name did not start" - exit 1 -} - wait_for_ssh(){ - retry=400 + local service_name="$1" + retry=800 wait=1 while ! execute_remote true; do + if ! systemctl is-active "$service_name"; then + echo "Service no longer active" + systemctl status "${service_name}" || true + return 1 + fi + retry=$(( retry - 1 )) if [ $retry -le 0 ]; then echo "Timed out waiting for ssh. Aborting!" @@ -40,29 +29,57 @@ done } +nested_wait_for_snap_command(){ + retry=400 + wait=1 + while ! execute_remote command -v snap; do + retry=$(( retry - 1 )) + if [ $retry -le 0 ]; then + echo "Timed out waiting for snap command to be available. Aborting!" + exit 1 + fi + sleep "$wait" + done +} + cleanup_nested_core_vm(){ # stop the VM if it is running systemctl stop nested-vm-* - # remove the swtpm - # TODO: we could just remove/reset the swtpm instead of removing the snap - # wholesale - snap remove swtpm-mvo + if [ "${ENABLE_TPM:-false}" = "true" ]; then + if [ -d "/tmp/qtpm" ]; then + rm -rf /tmp/qtpm + fi + + # remove the swtpm + # TODO: we could just remove/reset the swtpm instead of removing the snap + # wholesale + snap remove --purge swtpm-mvo + fi # delete the image file rm -rf "${IMAGE_FILE}" } +print_nested_status(){ + SVC_NAME="nested-vm-$(systemd-escape "${SPREAD_JOB:-unknown}")" + systemctl status "${SVC_NAME}" || true + journalctl -u "${SVC_NAME}" || true +} + start_nested_core_vm_unit(){ # copy the image file to create a new one to use # TODO: maybe create a snapshot qcow image instead? mkdir -p "${WORK_DIR}" - cp /home/core-initrd/pc.img "${IMAGE_FILE}" + cp "${SETUPDIR}/pc.img" "${IMAGE_FILE}" # use only 2G of RAM for qemu-nested if [ "${SPREAD_BACKEND}" = "google-nested" ]; then PARAM_MEM="-m 4096" PARAM_SMP="-smp 2" + elif [ "${SPREAD_BACKEND}" = "lxd-nested" ]; then + PARAM_MEM="-m 4096" + PARAM_SMP="-smp 2" elif [ "${SPREAD_BACKEND}" = "qemu-nested" ]; then PARAM_MEM="-m 2048" PARAM_SMP="-smp 1" @@ -87,83 +104,72 @@ ATTR_KVM=",accel=kvm" # CPU can be defined just when kvm is enabled PARAM_CPU="-cpu host" - # Increase the number of cpus used once the issue related to kvm and ovmf is fixed - # https://bugs.launchpad.net/ubuntu/+source/kvm/+bug/1872803 - PARAM_SMP="-smp 1" - fi - - # with qemu-nested, we can't use kvm acceleration - if [ "${SPREAD_BACKEND}" = "google-nested" ]; then - PARAM_MACHINE="-machine ubuntu${ATTR_KVM}" - elif [ "${SPREAD_BACKEND}" = "qemu-nested" ]; then - PARAM_MACHINE="" - else - echo "unknown spread backend ${SPREAD_BACKEND}" - exit 1 fi # TODO: enable ms key booting for i.e. nightly edge jobs ? - OVMF_VARS="snakeoil" OVMF_CODE="" - if [ "${ENABLE_SECURE_BOOT}" = "true" ]; then + OVMF_VARS="" + if [ "${ENABLE_SECURE_BOOT:-false}" = "true" ]; then OVMF_CODE=".secboot" fi + if [ "${ENABLE_OVMF_SNAKEOIL:-false}" = "true" ]; then + OVMF_VARS=".snakeoil" + fi mkdir -p "${WORK_DIR}/image/" - cp -f "/usr/share/OVMF/OVMF_VARS.${OVMF_VARS}.fd" "${WORK_DIR}/image/OVMF_VARS.${OVMF_VARS}.fd" - PARAM_BIOS="-drive file=/usr/share/OVMF/OVMF_CODE${OVMF_CODE}.fd,if=pflash,format=raw,unit=0,readonly -drive file=${WORK_DIR}/image/OVMF_VARS.${OVMF_VARS}.fd,if=pflash,format=raw" + cp -f "/usr/share/OVMF/OVMF_VARS${OVMF_VARS}.fd" "${WORK_DIR}/image/OVMF_VARS${OVMF_VARS}.fd" + PARAM_BIOS="-drive file=/usr/share/OVMF/OVMF_CODE${OVMF_CODE}.fd,if=pflash,format=raw,unit=0,readonly -drive file=${WORK_DIR}/image/OVMF_VARS${OVMF_VARS}.fd,if=pflash,format=raw" PARAM_MACHINE="-machine q35${ATTR_KVM} -global ICH9-LPC.disable_s3=1" - if [ "${ENABLE_TPM}" = "true" ]; then - if ! snap list swtpm-mvo > /dev/null; then + # Unfortunately the swtpm-mvo snap does not work correctly in lxd container. It's not possible + # for the socket to come up due to being containerized. + if [ "${ENABLE_TPM:-false}" = "true" ]; then + TPMSOCK_PATH="/var/snap/swtpm-mvo/current/swtpm-sock" + if [ "${SPREAD_BACKEND}" = "lxd-nested" ]; then + mkdir -p /tmp/qtpm + swtpm socket --tpmstate dir=/tmp/qtpm --ctrl type=unixio,path=/tmp/qtpm/sock --tpm2 -d -t + TPMSOCK_PATH="/tmp/qtpm/sock" + elif ! snap list swtpm-mvo > /dev/null; then snap install swtpm-mvo --beta + retry=60 + while ! test -S /var/snap/swtpm-mvo/current/swtpm-sock; do + retry=$(( retry - 1 )) + if [ $retry -le 0 ]; then + echo "Timed out waiting for the swtpm socket. Aborting!" + return 1 + fi + sleep 1 + done fi - PARAM_TPM="-chardev socket,id=chrtpm,path=/var/snap/swtpm-mvo/current/swtpm-sock -tpmdev emulator,id=tpm0,chardev=chrtpm -device tpm-tis,tpmdev=tpm0" + PARAM_TPM="-chardev socket,id=chrtpm,path=${TPMSOCK_PATH} -tpmdev emulator,id=tpm0,chardev=chrtpm -device tpm-tis,tpmdev=tpm0" fi PARAM_IMAGE="-drive file=${IMAGE_FILE},cache=none,format=raw,id=disk1,if=none -device virtio-blk-pci,drive=disk1,bootindex=1" - # Create the systemd unit for running the VM, the qemu parameter order is - # important. We run all of the qemu logic through a script that systemd runs - # for an easier time escaping everything SVC_NAME="nested-vm-$(systemd-escape "${SPREAD_JOB:-unknown}")" - SVC_SCRIPT="/tmp/nested-vm-$RANDOM.sh" - cat << EOF > "${SVC_SCRIPT}" -#!/bin/sh -e -qemu-system-x86_64 \ - ${PARAM_SMP} \ - ${PARAM_CPU} \ - ${PARAM_MEM} \ - ${PARAM_TRACE} \ - ${PARAM_LOG} \ - ${PARAM_MACHINE} \ - ${PARAM_DISPLAY} \ - ${PARAM_NETWORK} \ - ${PARAM_BIOS} \ - ${PARAM_TPM} \ - ${PARAM_RANDOM} \ - ${PARAM_IMAGE} \ - ${PARAM_SERIAL} \ - ${PARAM_MONITOR} -EOF - - chmod +x "${SVC_SCRIPT}" - - printf '[Unit]\nDescription=QEMU Nested VM for UC20 spread job %s\n[Service]\nType=simple\nExecStart=%s\n' \ - "${SPREAD_JOB:-unknown}" \ - "${SVC_SCRIPT}" \ - > "/run/systemd/system/${SVC_NAME}.service" - - systemctl daemon-reload - systemctl start "${SVC_NAME}" - - # wait for the nested-vm service to appear active - if ! wait_for_service "${SVC_NAME}"; then + if ! systemd-run --service-type=simple --unit="${SVC_NAME}" -- \ + qemu-system-x86_64 \ + ${PARAM_SMP} \ + ${PARAM_CPU} \ + ${PARAM_MEM} \ + ${PARAM_TRACE} \ + ${PARAM_LOG} \ + ${PARAM_MACHINE} \ + ${PARAM_DISPLAY} \ + ${PARAM_NETWORK} \ + ${PARAM_BIOS} \ + ${PARAM_TPM} \ + ${PARAM_RANDOM} \ + ${PARAM_IMAGE} \ + ${PARAM_SERIAL} \ + ${PARAM_MONITOR}; then + echo "Failed to start ${SVC_NAME}" 1>&2 + systemctl status "${SVC_NAME}" || true return 1 fi # Wait until ssh is ready - if ! wait_for_ssh; then + if ! wait_for_ssh "${SVC_NAME}"; then return 1 fi } diff -Nru ubuntu-core-initramfs-46+ppa4/tests/lib/prepare-uc20.sh ubuntu-core-initramfs-51.5/tests/lib/prepare-uc20.sh --- ubuntu-core-initramfs-46+ppa4/tests/lib/prepare-uc20.sh 2020-11-16 10:50:20.000000000 +0000 +++ ubuntu-core-initramfs-51.5/tests/lib/prepare-uc20.sh 2023-03-23 07:54:39.000000000 +0000 @@ -13,17 +13,14 @@ # these should already be installed in GCE images with the google-nested # backend, but in qemu local images from qemu-nested, we might not have them -apt install snapd ovmf qemu-system-x86 sshpass whois -yqq +apt install snapd mtools ovmf qemu-system-x86 sshpass whois -yqq # use the snapd snap explicitly # TODO: since ubuntu-image ships it's own version of `snap prepare-image`, # should we instead install beta/edge snapd here and point ubuntu-image to this # version of snapd? snap install snapd - -# install some dependencies -# TODO:UC20: when should we start using candidate / stable ubuntu-image? -snap install ubuntu-image --edge --classic +snap install ubuntu-image --classic # install build-deps for ubuntu-core-initramfs ( @@ -56,20 +53,21 @@ cp ../*.deb "$SETUPDIR" ) -# install ubuntu-core-initramfs here so the repack-kernel.sh uses the version of +# install ubuntu-core-initramfs here so the repack-kernel uses the version of # ubuntu-core-initramfs we built here apt install -yqq "$SETUPDIR"/ubuntu-core-initramfs*.deb # now download snap dependencies # TODO:UC20: when should some of these things start tracking stable ? -snap download pc-kernel --channel=20/edge --basename=upstream-pc-kernel -snap download pc --channel=20/edge --basename=upstream-pc-gadget -snap download core20 --channel=edge --basename=upstream-core20 +snap download pc-kernel --channel=20/$SNAP_BRANCH --basename=upstream-pc-kernel +snap download pc --channel=20/$SNAP_BRANCH --basename=upstream-pc-gadget +snap download core20 --channel=$SNAP_BRANCH --basename=upstream-core20 + # note that we currently use snap-bootstrap from the snapd deb package, but we # could instead copy a potentially more up-to-date version out of the snapd snap # but we don't currently do that as it doesn't represent what # ubuntu-core-initramfs would actually used if that package was built from LP -snap download snapd --channel=edge --basename=upstream-snapd +snap download snapd --channel=$SNAP_BRANCH --basename=upstream-snapd # next repack / modify the snaps we use in the image, we do this for a few # reasons: @@ -182,19 +180,23 @@ # next re-pack the kernel snap with this version of ubuntu-core-initramfs # extract the kernel snap, including extracting the initrd from the kernel.efi -kerneldir=/tmp/kernel-workdir -"$TESTSLIB/repack-kernel.sh" extract upstream-pc-kernel.snap $kerneldir +kerneldir="$(mktemp --tmpdir -d kernel-workdirXXXXXXXXXX)" +trap 'rm -rf "${kerneldir}"' EXIT + +unsquashfs -f -d "${kerneldir}" upstream-pc-kernel.snap +( + cd "${kerneldir}" + config="$(echo config-*)" + kernelver="${config#config-}" + objcopy -O binary -j .linux kernel.efi kernel.img-"${kernelver}" + ubuntu-core-initramfs create-initrd --kerneldir modules/"${kernelver}" --kernelver "${kernelver}" --firmwaredir firmware --output ubuntu-core-initramfs.img + ubuntu-core-initramfs create-efi --initrd ubuntu-core-initramfs.img --kernel kernel.img --output kernel.efi --kernelver "${kernelver}" + mv "kernel.efi-${kernelver}" kernel.efi + rm kernel.img-"${kernelver}" + rm ubuntu-core-initramfs.img-"${kernelver}" +) -# copy the skeleton from our installed ubuntu-core-initramfs into the initrd -# skeleton for the kernel snap -cp -ar /usr/lib/ubuntu-core-initramfs/main/* "$kerneldir/skeleton/main" - -# repack the initrd into the kernel.efi -"$TESTSLIB/repack-kernel.sh" prepare $kerneldir - -# repack the kernel snap itself -"$TESTSLIB/repack-kernel.sh" pack $kerneldir --filename=pc-kernel.snap -rm -rf $kerneldir +snap pack --filename=pc-kernel.snap "${kerneldir}" # penultimately, re-pack the gadget snap with snakeoil signed shim @@ -256,27 +258,10 @@ # add the test user to the systemd-journal group if it isn't already sed -r -i -e 's/^systemd-journal:x:([0-9]+):$/systemd-journal:x:\1:test/' /root/test-etc/group -# mount fresh image and add all our SPREAD_PROJECT data -kpartx -avs pc.img -# losetup --list --noheadings returns: -# /dev/loop1 0 0 1 1 /var/lib/snapd/snaps/ohmygiraffe_3.snap 0 512 -# /dev/loop57 0 0 1 1 /var/lib/snapd/snaps/http_25.snap 0 512 -# /dev/loop19 0 0 1 1 /var/lib/snapd/snaps/test-snapd-netplan-apply_75.snap 0 512 -devloop=$(losetup --list --noheadings | grep pc.img | awk '{print $1}') -dev=$(basename "$devloop") - -# mount it so we can use it now -mkdir -p /mnt -mount "/dev/mapper/${dev}p2" /mnt - -# add the data that snapd.spread-tests-run-mode-tweaks.service reads to the -# mounted partition -tar -c -z \ - -f /mnt/run-mode-overlay-data.tar.gz \ +# tar the runmode tweaks and copy them to the image +tar -c -z -f run-mode-overlay-data.tar.gz \ /root/test-etc /root/test-var/lib/extrausers - -# tear down the mounts -umount /mnt -kpartx -d pc.img +partoffset=$(fdisk -lu pc.img | awk '/EFI System$/ {print $2}') +mcopy -i pc.img@@$(($partoffset * 512)) run-mode-overlay-data.tar.gz ::run-mode-overlay-data.tar.gz # the image is now ready to be booted diff -Nru ubuntu-core-initramfs-46+ppa4/tests/lib/repack-kernel.sh ubuntu-core-initramfs-51.5/tests/lib/repack-kernel.sh --- ubuntu-core-initramfs-46+ppa4/tests/lib/repack-kernel.sh 2021-06-08 14:12:33.000000000 +0000 +++ ubuntu-core-initramfs-51.5/tests/lib/repack-kernel.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,234 +0,0 @@ -#!/bin/bash - -# Author: Maciej Borzecki -# Modified by Ian Johnson - -set -e - -if [[ -n "$D" ]]; then - set -x -fi - -##HELP: Usage: repack-kernel -##HELP: -##HELP: Handle extraction of the kernel snap to a workspace directory, and later -##HELP: repacking it back to a snap. -##HELP: -##HELP: Commands: -##HELP: setup - setup system dependencies -##HELP: extract - extract under workspace tree -##HELP: prepare - prepare initramfs & kernel for repacking -##HELP: pack - pack the kernel -##HELP: cull-firmware - remove unnecessary firmware -##HELP: cull-modules - remove unnecessary mofules -##HELP: - -setup_deps() { - if [[ "$UID" != "0" ]]; then - echo "run as root (only this command)" - exit 1 - fi - - # carries ubuntu-core-initframfs - add-apt-repository ppa:snappy-dev/image -y - apt install ubuntu-core-initramfs -y -} - -get_kver() { - kerneldir="$1" - ( - cd "$kerneldir" - #shellcheck disable=SC2010 - ls "config"-* | grep -Po 'config-\K.*' - ) -} - -extract_kernel() { - local snap_file="$1" - local target="$2" - - if [[ -z "$target" ]] || [[ -z "$snap_file" ]]; then - echo "usage: prepare " - exit 1 - fi - - target=$(realpath "$target") - - mkdir -p "$target" "$target/work" "$target/backup" - - # kernel snap is huge, unpacking to current dir - unsquashfs -d "$target/kernel" "$snap_file" - - kver="$(get_kver "$target/kernel")" - - # repack initrd magic, beware - # assumptions: initrd is compressed with LZ4, cpio block size 512, microcode - # at the beginning of initrd image - ( - cd "$target/kernel" - - # XXX: ideally we should unpack the initrd, replace snap-boostrap and - # repack it using ubuntu-core-initramfs --skeleton= this does not - # work and the rebuilt kernel.efi panics unable to start init, but we - # still need the unpacked initrd to get the right kernel modules - objcopy -j .initrd -O binary kernel.efi "$target/work/initrd" - - # copy out the kernel image for create-efi command - objcopy -j .linux -O binary kernel.efi "$target/work/vmlinuz-$kver" - - cp -a kernel.efi "$target/backup/" - ) - - ( - cd "$target/work" - # this works on 20.04 but not on 18.04 - unmkinitramfs initrd unpacked-initrd - ) - - # copy the unpacked initrd to use as the target skeleton - cp -ar "$target/work/unpacked-initrd" "$target/skeleton" - - echo "prepared workspace at $target" - echo " kernel: $target/kernel ($kver)" - echo " kernel.efi backup: $target/backup/kernel.efi" - echo " temporary artifacts: $target/work" - echo " initramfs skeleton: $target/skeleton" - -} - -prepare_kernel() { - local target="$1" - - if [[ -z "$target" ]]; then - echo "usage: repack " - exit 1 - fi - - target=$(realpath "$target") - kver="$(get_kver "$target/kernel")" - - ( - # all the skeleton edits go to a local copy of distro directory - skeletondir="$target/skeleton" - - cd "$target/work" - # XXX: need to be careful to build an initrd using the right kernel - # modules from the unpacked initrd, rather than the host which may be - # running a different kernel - ( - # accommodate assumptions about tree layout, use the unpacked initrd - # to pick up the right modules - cd unpacked-initrd/main - ubuntu-core-initramfs create-initrd \ - --kernelver "$kver" \ - --skeleton "$skeletondir" \ - --feature main \ - --kerneldir "lib/modules/$kver" \ - --output "$target/work/repacked-initrd" - ) - - # assumes all files are named -$kver - ubuntu-core-initramfs create-efi \ - --kernelver "$kver" \ - --initrd repacked-initrd \ - --kernel vmlinuz \ - --output repacked-kernel.efi - - cp "repacked-kernel.efi-$kver" "$target/kernel/kernel.efi" - - # XXX: needed? - chmod +x "$target/kernel/kernel.efi" - ) -} - -cull_firmware() { - local target="$1" - - if [[ -z "$target" ]]; then - echo "usage: cull-firmware " - exit 1 - fi - ( - # XXX: drop ~450MB+ of firmware which should not be needed in under qemu - # or the cloud system - cd "$target/kernel" - rm -rf firmware/* - ) -} - -cull_modules() { - local target="$1" - - if [[ -z "$target" ]]; then - echo "usage: cull-modules " - exit 1 - fi - - target=$(realpath "$target") - kver="$(get_kver "$target/kernel")" - - ( - cd "$target/kernel" - # drop unnecessary modules - awk '{print $1}' < /proc/modules | sort > "$target/work/current-modules" - #shellcheck disable=SC2044 - for m in $(find modules/ -name '*.ko'); do - noko=$(basename "$m"); noko="${noko%.ko}" - if echo "$noko" | grep -f "$target/work/current-modules" -q ; then - echo "keeping $m - $noko" - else - rm -f "$m" - fi - done - - # depmod assumes that /lib/modules/$kver is under basepath - mkdir -p fake/lib - ln -s "$PWD/modules" fake/lib/modules - depmod -b "$PWD/fake" -A -v "$kver" - rm -rf fake - ) -} - -pack() { - local target="$1" - - if [[ -z "$target" ]]; then - echo "usage: pack " - exit 1 - fi - snap pack "${@:2}" "$target/kernel" -} - -show_help() { - grep '^##HELP:' "$0" | sed -e 's/##HELP: \?//' -} - - -opt="$1" -shift || true - -if [[ -z "$opt" ]] || [[ "$opt" == "--help" ]]; then - show_help - exit 1 -fi - -case "$opt" in - setup) - setup_deps - ;; - extract) - extract_kernel "$@" - ;; - prepare) - prepare_kernel "$@" - ;; - cull-modules) - cull_modules "$@" - ;; - cull-firmware) - cull_firmware "$@" - ;; - pack) - pack "$@" - ;; -esac diff -Nru ubuntu-core-initramfs-46+ppa4/tests/spread/basic/task.yaml ubuntu-core-initramfs-51.5/tests/spread/basic/task.yaml --- ubuntu-core-initramfs-46+ppa4/tests/spread/basic/task.yaml 2020-11-16 10:50:20.000000000 +0000 +++ ubuntu-core-initramfs-51.5/tests/spread/basic/task.yaml 2023-03-23 07:54:39.000000000 +0000 @@ -1,6 +1,6 @@ summary: Ensure that things worked -execute: | +prepare: | # for various utilities . "$TESTSLIB/nested.sh" @@ -10,16 +10,11 @@ # At this point we are able to SSH to the nested VM, so things probably worked # but we should wait for snapd to finish seeding anyways, but first we need to # wait for the snap command to exist - retry=400 - wait=1 - while ! execute_remote command -v snap; do - retry=$(( retry - 1 )) - if [ $retry -le 0 ]; then - echo "Timed out waiting for snap command to be available. Aborting!" - exit 1 - fi - sleep "$wait" - done + nested_wait_for_snap_command + +execute: | + # for various utilities + . "$TESTSLIB/nested.sh" # Now formally wait for seeding execute_remote sudo snap wait system seed.loaded diff -Nru ubuntu-core-initramfs-46+ppa4/tests/spread/ci/task.yaml ubuntu-core-initramfs-51.5/tests/spread/ci/task.yaml --- ubuntu-core-initramfs-46+ppa4/tests/spread/ci/task.yaml 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/tests/spread/ci/task.yaml 2023-03-23 07:54:39.000000000 +0000 @@ -0,0 +1,53 @@ +summary: Build an LXD spread test image with TPM software +manual: true + +execute: | + INSTANCE_NAME=spread-test + IMAGE_NAME=lxd-spread-initrd-img + + # be in project folder + cd $PROJECT_PATH + + # install prerequisites + snap install google-cloud-sdk --classic + snap install lxd --channel=latest/stable + lxd init --auto + + # authenticate with gcloud + gcloud auth activate-service-account --key-file="./sa.json" + + # launch the new lxc instance from an ubuntu 20.04 base + lxc launch ubuntu:20.04 $INSTANCE_NAME + + # wait a few seconds before proceeding, otherwise we are going to have issues + # with the container (systemd) not being ready yet, and then the rest of + # the commands will fail + sleep 5s + lxc exec $INSTANCE_NAME -- bash -c 'systemctl is-system-running --wait' || true + + # we build libtpms and swptm from source and preinstall that in the image for TPM emulation support + lxc exec $INSTANCE_NAME -- bash -c "apt update -yqq" + lxc exec $INSTANCE_NAME -- bash -c "apt install snapd ovmf qemu-system-x86 sshpass whois coreutils net-tools iproute2 automake autoconf libtool gcc build-essential libssl-dev dh-exec pkg-config dh-autoreconf libtasn1-6-dev libjson-glib-dev libgnutls28-dev expect gawk socat libseccomp-dev make -yqq" + lxc exec $INSTANCE_NAME -- bash -c "git clone https://github.com/stefanberger/libtpms" + lxc exec $INSTANCE_NAME -- bash -c "git clone https://github.com/stefanberger/swtpm" + lxc exec $INSTANCE_NAME -- bash -c "cd libtpms && ./autogen.sh --with-openssl --prefix=/usr --with-tpm2 && make -j4 && make check && make install" + lxc exec $INSTANCE_NAME -- bash -c "cd swtpm && ./autogen.sh --with-openssl --prefix=/usr && make -j4 && make -j4 check && make install" + lxc exec $INSTANCE_NAME -- bash -c "rm -rf libtpms" + lxc exec $INSTANCE_NAME -- bash -c "rm -rf swtpm" + + # stop the container as the last step, the container is now ready for publishing + lxc stop $INSTANCE_NAME + + # make a tarball out of the container image and delete the container + lxc publish $INSTANCE_NAME --alias ucspread + lxc image export ucspread ./$IMAGE_NAME + + # upload the image file as https://storage.googleapis.com/snapd-spread-core/lxd/$IMAGE_NAME.tar.gz + gsutil -o GSUtil:parallel_composite_upload_threshold=2000M cp "./$IMAGE_NAME.tar.gz" "gs://snapd-spread-core/lxd/$IMAGE_NAME.tar.gz" + +restore: | + INSTANCE_NAME=spread-test + + # Make sure that we continue even if these commands fail + # to make sure everything is shutdown + lxc delete -f $INSTANCE_NAME || true diff -Nru ubuntu-core-initramfs-46+ppa4/tests/spread/core-initrd.lxdprofile ubuntu-core-initramfs-51.5/tests/spread/core-initrd.lxdprofile --- ubuntu-core-initramfs-46+ppa4/tests/spread/core-initrd.lxdprofile 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/tests/spread/core-initrd.lxdprofile 2022-03-10 14:11:17.000000000 +0000 @@ -0,0 +1,340 @@ +config: + security.privileged: "true" +description: Profile for testing core-initrd with kvm enabled +devices: + eth0: + name: eth0 + network: lxdbr0 + type: nic + kvm: + path: /dev/kvm + type: unix-char + loop-control: + path: /dev/loop-control + type: unix-char + loop0: + major: "7" + minor: "0" + path: /dev/loop0 + type: unix-block + loop1: + major: "7" + minor: "1" + path: /dev/loop1 + type: unix-block + loop2: + major: "7" + minor: "2" + path: /dev/loop2 + type: unix-block + loop3: + major: "7" + minor: "3" + path: /dev/loop3 + type: unix-block + loop4: + major: "7" + minor: "4" + path: /dev/loop4 + type: unix-block + loop5: + major: "7" + minor: "5" + path: /dev/loop5 + type: unix-block + loop6: + major: "7" + minor: "6" + path: /dev/loop6 + type: unix-block + loop7: + major: "7" + minor: "7" + path: /dev/loop7 + type: unix-block + loop8: + major: "7" + minor: "8" + path: /dev/loop8 + type: unix-block + loop9: + major: "7" + minor: "9" + path: /dev/loop9 + type: unix-block + loop10: + major: "7" + minor: "10" + path: /dev/loop10 + type: unix-block + loop11: + major: "7" + minor: "11" + path: /dev/loop11 + type: unix-block + loop12: + major: "7" + minor: "12" + path: /dev/loop12 + type: unix-block + loop13: + major: "7" + minor: "13" + path: /dev/loop13 + type: unix-block + loop14: + major: "7" + minor: "14" + path: /dev/loop14 + type: unix-block + loop15: + major: "7" + minor: "15" + path: /dev/loop15 + type: unix-block + loop16: + major: "7" + minor: "16" + path: /dev/loop16 + type: unix-block + loop17: + major: "7" + minor: "17" + path: /dev/loop17 + type: unix-block + loop18: + major: "7" + minor: "18" + path: /dev/loop18 + type: unix-block + loop19: + major: "7" + minor: "19" + path: /dev/loop19 + type: unix-block + loop20: + major: "7" + minor: "20" + path: /dev/loop20 + type: unix-block + loop21: + major: "7" + minor: "21" + path: /dev/loop21 + type: unix-block + loop22: + major: "7" + minor: "22" + path: /dev/loop22 + type: unix-block + loop23: + major: "7" + minor: "23" + path: /dev/loop23 + type: unix-block + loop24: + major: "7" + minor: "24" + path: /dev/loop24 + type: unix-block + loop25: + major: "7" + minor: "25" + path: /dev/loop25 + type: unix-block + loop26: + major: "7" + minor: "26" + path: /dev/loop26 + type: unix-block + loop27: + major: "7" + minor: "27" + path: /dev/loop27 + type: unix-block + loop28: + major: "7" + minor: "28" + path: /dev/loop28 + type: unix-block + loop29: + major: "7" + minor: "29" + path: /dev/loop29 + type: unix-block + loop30: + major: "7" + minor: "30" + path: /dev/loop30 + type: unix-block + loop31: + major: "7" + minor: "31" + path: /dev/loop31 + type: unix-block + loop32: + major: "7" + minor: "32" + path: /dev/loop32 + type: unix-block + loop33: + major: "7" + minor: "33" + path: /dev/loop33 + type: unix-block + loop34: + major: "7" + minor: "34" + path: /dev/loop34 + type: unix-block + loop35: + major: "7" + minor: "35" + path: /dev/loop35 + type: unix-block + loop36: + major: "7" + minor: "36" + path: /dev/loop36 + type: unix-block + loop37: + major: "7" + minor: "37" + path: /dev/loop37 + type: unix-block + loop38: + major: "7" + minor: "38" + path: /dev/loop38 + type: unix-block + loop39: + major: "7" + minor: "39" + path: /dev/loop39 + type: unix-block + loop40: + major: "7" + minor: "40" + path: /dev/loop40 + type: unix-block + loop41: + major: "7" + minor: "41" + path: /dev/loop41 + type: unix-block + loop42: + major: "7" + minor: "42" + path: /dev/loop42 + type: unix-block + loop43: + major: "7" + minor: "43" + path: /dev/loop43 + type: unix-block + loop44: + major: "7" + minor: "44" + path: /dev/loop44 + type: unix-block + loop45: + major: "7" + minor: "45" + path: /dev/loop45 + type: unix-block + loop46: + major: "7" + minor: "46" + path: /dev/loop46 + type: unix-block + loop47: + major: "7" + minor: "47" + path: /dev/loop47 + type: unix-block + loop48: + major: "7" + minor: "48" + path: /dev/loop48 + type: unix-block + loop49: + major: "7" + minor: "49" + path: /dev/loop49 + type: unix-block + loop50: + major: "7" + minor: "50" + path: /dev/loop50 + type: unix-block + loop51: + major: "7" + minor: "51" + path: /dev/loop51 + type: unix-block + loop52: + major: "7" + minor: "52" + path: /dev/loop52 + type: unix-block + loop53: + major: "7" + minor: "53" + path: /dev/loop53 + type: unix-block + loop54: + major: "7" + minor: "54" + path: /dev/loop54 + type: unix-block + loop55: + major: "7" + minor: "55" + path: /dev/loop55 + type: unix-block + loop56: + major: "7" + minor: "56" + path: /dev/loop56 + type: unix-block + loop57: + major: "7" + minor: "57" + path: /dev/loop57 + type: unix-block + loop58: + major: "7" + minor: "58" + path: /dev/loop58 + type: unix-block + loop59: + major: "7" + minor: "59" + path: /dev/loop59 + type: unix-block + loop60: + major: "7" + minor: "60" + path: /dev/loop60 + type: unix-block + loop61: + major: "7" + minor: "61" + path: /dev/loop61 + type: unix-block + loop62: + major: "7" + minor: "62" + path: /dev/loop62 + type: unix-block + loop63: + major: "7" + minor: "63" + path: /dev/loop63 + type: unix-block + root: + path: / + pool: default + type: disk +name: coreinitrd +used_by: [] diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/account_key_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/account_key_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/account_key_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/account_key_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -831,7 +831,7 @@ untilHeader string until time.Time }{ - {"", time.Time{}}, // zero time default + {"", time.Time{}}, // zero time default {aks.until.Format(time.RFC3339), aks.until}, // in the future {aks.since.Format(time.RFC3339), aks.since}, // same as since } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/crypto.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/crypto.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/crypto.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/crypto.go 2023-03-23 08:10:58.000000000 +0000 @@ -24,8 +24,12 @@ "crypto" "crypto/rand" "crypto/rsa" - _ "crypto/sha256" // be explicit about supporting SHA256 - _ "crypto/sha512" // be explicit about needing SHA512 + + // be explicit about supporting SHA256 + _ "crypto/sha256" + + // be explicit about needing SHA512 + _ "crypto/sha512" "encoding/base64" "fmt" "io" @@ -301,14 +305,14 @@ // externally held key pairs type extPGPPrivateKey struct { - pubKey PublicKey - from string - pgpFingerprint string - bitLen int - doSign func(content []byte) ([]byte, error) + pubKey PublicKey + from string + externalID string + bitLen int + doSign func(content []byte) (*packet.Signature, error) } -func newExtPGPPrivateKey(exportedPubKeyStream io.Reader, from string, sign func(content []byte) ([]byte, error)) (*extPGPPrivateKey, error) { +func newExtPGPPrivateKey(exportedPubKeyStream io.Reader, from string, sign func(content []byte) (*packet.Signature, error)) (*extPGPPrivateKey, error) { var pubKey *packet.PublicKey rd := packet.NewReader(exportedPubKeyStream) @@ -343,18 +347,14 @@ } return &extPGPPrivateKey{ - pubKey: RSAPublicKey(rsaPubKey), - from: from, - pgpFingerprint: fmt.Sprintf("%X", pubKey.Fingerprint), - bitLen: rsaPubKey.N.BitLen(), - doSign: sign, + pubKey: RSAPublicKey(rsaPubKey), + from: from, + externalID: fmt.Sprintf("%X", pubKey.Fingerprint), + bitLen: rsaPubKey.N.BitLen(), + doSign: sign, }, nil } -func (expk *extPGPPrivateKey) fingerprint() string { - return expk.pgpFingerprint -} - func (expk *extPGPPrivateKey) PublicKey() PublicKey { return expk.pubKey } @@ -368,23 +368,13 @@ return nil, fmt.Errorf("signing needs at least a 4096 bits key, got %d", expk.bitLen) } - out, err := expk.doSign(content) + sig, err := expk.doSign(content) if err != nil { return nil, err } badSig := fmt.Sprintf("bad %s produced signature: ", expk.from) - sigpkt, err := packet.Read(bytes.NewBuffer(out)) - if err != nil { - return nil, fmt.Errorf(badSig+"%v", err) - } - - sig, ok := sigpkt.(*packet.Signature) - if !ok { - return nil, fmt.Errorf(badSig+"got %T", sigpkt) - } - if sig.Hash != crypto.SHA512 { return nil, fmt.Errorf(badSig + "expected SHA512 digest") } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/extkeypairmgr.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/extkeypairmgr.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/extkeypairmgr.go 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/extkeypairmgr.go 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,298 @@ +// -*- Mode: Go; indent-tabs-mode: t -*- + +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +package asserts + +import ( + "bytes" + "crypto" + "crypto/rsa" + "crypto/x509" + "encoding/json" + "fmt" + "io" + "os/exec" + + "golang.org/x/crypto/openpgp/packet" + + "github.com/snapcore/snapd/strutil" +) + +type ExternalKeyInfo struct { + Name string + ID string +} + +// ExternalKeypairManager is key pair manager implemented via an external program interface. +// TODO: points to interface docs +type ExternalKeypairManager struct { + keyMgrPath string + nameToID map[string]string + cache map[string]*cachedExtKey +} + +// NewExternalKeypairManager creates a new ExternalKeypairManager using the program at keyMgrPath. +func NewExternalKeypairManager(keyMgrPath string) (*ExternalKeypairManager, error) { + em := &ExternalKeypairManager{ + keyMgrPath: keyMgrPath, + nameToID: make(map[string]string), + cache: make(map[string]*cachedExtKey), + } + if err := em.checkFeatures(); err != nil { + return nil, err + } + return em, nil +} + +func (em *ExternalKeypairManager) keyMgr(op string, args []string, in []byte, out interface{}) error { + args = append([]string{op}, args...) + cmd := exec.Command(em.keyMgrPath, args...) + var outBuf bytes.Buffer + var errBuf bytes.Buffer + + if len(in) != 0 { + cmd.Stdin = bytes.NewBuffer(in) + } + cmd.Stdout = &outBuf + cmd.Stderr = &errBuf + + if err := cmd.Run(); err != nil { + return fmt.Errorf("external keypair manager %q %v failed: %v (%q)", em.keyMgrPath, args, err, errBuf.Bytes()) + + } + switch o := out.(type) { + case *[]byte: + *o = outBuf.Bytes() + default: + if err := json.Unmarshal(outBuf.Bytes(), out); err != nil { + return fmt.Errorf("cannot decode external keypair manager %q %v output: %v", em.keyMgrPath, args, err) + } + } + return nil +} + +func (em *ExternalKeypairManager) checkFeatures() error { + var feats struct { + Signing []string `json:"signing"` + PublicKeys []string `json:"public-keys"` + } + if err := em.keyMgr("features", nil, nil, &feats); err != nil { + return err + } + if !strutil.ListContains(feats.Signing, "RSA-PKCS") { + return fmt.Errorf("external keypair manager %q missing support for RSA-PKCS signing", em.keyMgrPath) + } + if !strutil.ListContains(feats.PublicKeys, "DER") { + return fmt.Errorf("external keypair manager %q missing support for public key DER output format", em.keyMgrPath) + } + return nil +} + +func (em *ExternalKeypairManager) keyNames() ([]string, error) { + var knames struct { + Names []string `json:"key-names"` + } + if err := em.keyMgr("key-names", nil, nil, &knames); err != nil { + return nil, fmt.Errorf("cannot get all external keypair manager key names: %v", err) + } + return knames.Names, nil +} + +func (em *ExternalKeypairManager) findByName(name string) (PublicKey, *rsa.PublicKey, error) { + var k []byte + err := em.keyMgr("get-public-key", []string{"-f", "DER", "-k", name}, nil, &k) + if err != nil { + return nil, nil, fmt.Errorf("cannot find external key: %v", err) + } + pubk, err := x509.ParsePKIXPublicKey(k) + if err != nil { + return nil, nil, fmt.Errorf("cannot decode external key %q: %v", name, err) + } + rsaPub, ok := pubk.(*rsa.PublicKey) + if !ok { + return nil, nil, fmt.Errorf("expected RSA public key, got instead: %T", pubk) + } + pubKey := RSAPublicKey(rsaPub) + return pubKey, rsaPub, nil +} + +func (em *ExternalKeypairManager) Export(keyName string) ([]byte, error) { + pubKey, _, err := em.findByName(keyName) + if err != nil { + return nil, err + } + return EncodePublicKey(pubKey) +} + +func (em *ExternalKeypairManager) loadKey(name string) (*cachedExtKey, error) { + id, ok := em.nameToID[name] + if ok { + return em.cache[id], nil + } + pubKey, rsaPub, err := em.findByName(name) + if err != nil { + return nil, err + } + id = pubKey.ID() + em.nameToID[name] = id + cachedKey := &cachedExtKey{ + pubKey: pubKey, + signer: &extSigner{ + keyName: name, + rsaPub: rsaPub, + // signWith is filled later + }, + } + em.cache[id] = cachedKey + return cachedKey, nil +} + +func (em *ExternalKeypairManager) privateKey(cachedKey *cachedExtKey) PrivateKey { + if cachedKey.privKey == nil { + extSigner := cachedKey.signer + // fill signWith + extSigner.signWith = em.signWith + signer := packet.NewSignerPrivateKey(v1FixedTimestamp, extSigner) + signk := openpgpPrivateKey{privk: signer} + extKey := &extPGPPrivateKey{ + pubKey: cachedKey.pubKey, + from: fmt.Sprintf("external keypair manager %q", em.keyMgrPath), + externalID: extSigner.keyName, + bitLen: extSigner.rsaPub.N.BitLen(), + doSign: signk.sign, + } + cachedKey.privKey = extKey + } + return cachedKey.privKey +} + +func (em *ExternalKeypairManager) GetByName(keyName string) (PrivateKey, error) { + cachedKey, err := em.loadKey(keyName) + if err != nil { + return nil, err + } + return em.privateKey(cachedKey), nil +} + +// ExternalUnsupportedOpError represents the error situation of operations +// that are not supported/mediated via ExternalKeypairManager. +type ExternalUnsupportedOpError struct { + msg string +} + +func (euoe *ExternalUnsupportedOpError) Error() string { + return euoe.msg +} + +func (em *ExternalKeypairManager) Put(privKey PrivateKey) error { + return &ExternalUnsupportedOpError{"cannot import private key into external keypair manager"} +} + +func (em *ExternalKeypairManager) Delete(keyName string) error { + return &ExternalUnsupportedOpError{"no support to delete external keypair manager keys"} +} + +func (em *ExternalKeypairManager) Generate(keyName string) error { + return &ExternalUnsupportedOpError{"no support to mediate generating an external keypair manager key"} +} + +func (em *ExternalKeypairManager) loadAllKeys() ([]string, error) { + names, err := em.keyNames() + if err != nil { + return nil, err + } + for _, name := range names { + if _, err := em.loadKey(name); err != nil { + return nil, err + } + } + return names, nil +} + +func (em *ExternalKeypairManager) Get(keyID string) (PrivateKey, error) { + cachedKey, ok := em.cache[keyID] + if !ok { + // try to load all keys + if _, err := em.loadAllKeys(); err != nil { + return nil, err + } + cachedKey, ok = em.cache[keyID] + if !ok { + return nil, fmt.Errorf("cannot find external key with id %q", keyID) + } + } + return em.privateKey(cachedKey), nil +} + +func (em *ExternalKeypairManager) List() ([]ExternalKeyInfo, error) { + names, err := em.loadAllKeys() + if err != nil { + return nil, err + } + res := make([]ExternalKeyInfo, len(names)) + for i, name := range names { + res[i].Name = name + res[i].ID = em.cache[em.nameToID[name]].pubKey.ID() + } + return res, nil +} + +// see https://datatracker.ietf.org/doc/html/rfc2313 and more recently +// and more precisely about SHA-512: +// https://datatracker.ietf.org/doc/html/rfc3447#section-9.2 Notes 1. +var digestInfoSHA512Prefix = []byte{0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40} + +func (em *ExternalKeypairManager) signWith(keyName string, digest []byte) (signature []byte, err error) { + // wrap the digest into the needed DigestInfo, the RSA-PKCS + // mechanism or equivalent is expected not to do this on its + // own + toSign := &bytes.Buffer{} + toSign.Write(digestInfoSHA512Prefix) + toSign.Write(digest) + + err = em.keyMgr("sign", []string{"-m", "RSA-PKCS", "-k", keyName}, toSign.Bytes(), &signature) + if err != nil { + return nil, err + } + return signature, nil +} + +type cachedExtKey struct { + pubKey PublicKey + signer *extSigner + privKey PrivateKey +} + +type extSigner struct { + keyName string + rsaPub *rsa.PublicKey + signWith func(keyName string, digest []byte) (signature []byte, err error) +} + +func (es *extSigner) Public() crypto.PublicKey { + return es.rsaPub +} + +func (es *extSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) (signature []byte, err error) { + if opts.HashFunc() != crypto.SHA512 { + return nil, fmt.Errorf("unexpected pgp signature digest") + } + + return es.signWith(es.keyName, digest) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/extkeypairmgr_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/extkeypairmgr_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/extkeypairmgr_test.go 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/extkeypairmgr_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,320 @@ +// -*- Mode: Go; indent-tabs-mode: t -*- + +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +package asserts_test + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "fmt" + "io/ioutil" + "os" + "os/exec" + "path/filepath" + "time" + + . "gopkg.in/check.v1" + + "github.com/snapcore/snapd/asserts" + "github.com/snapcore/snapd/asserts/assertstest" + "github.com/snapcore/snapd/testutil" +) + +type extKeypairMgrSuite struct { + pgm *testutil.MockCmd + + defaultPub *rsa.PublicKey + modelsPub *rsa.PublicKey +} + +var _ = Suite(&extKeypairMgrSuite{}) + +func (s *extKeypairMgrSuite) SetUpSuite(c *C) { + tmpdir := c.MkDir() + k1, err := rsa.GenerateKey(rand.Reader, 4096) + c.Assert(err, IsNil) + k2, err := rsa.GenerateKey(rand.Reader, 4096) + c.Assert(err, IsNil) + + derPub1, err := x509.MarshalPKIXPublicKey(&k1.PublicKey) + c.Assert(err, IsNil) + err = ioutil.WriteFile(filepath.Join(tmpdir, "default.pub"), derPub1, 0644) + c.Assert(err, IsNil) + derPub2, err := x509.MarshalPKIXPublicKey(&k2.PublicKey) + c.Assert(err, IsNil) + err = ioutil.WriteFile(filepath.Join(tmpdir, "models.pub"), derPub2, 0644) + c.Assert(err, IsNil) + + err = ioutil.WriteFile(filepath.Join(tmpdir, "default.key"), x509.MarshalPKCS1PrivateKey(k1), 0600) + c.Assert(err, IsNil) + err = ioutil.WriteFile(filepath.Join(tmpdir, "models.key"), x509.MarshalPKCS1PrivateKey(k2), 0600) + c.Assert(err, IsNil) + + s.defaultPub = &k1.PublicKey + s.modelsPub = &k2.PublicKey + + s.pgm = testutil.MockCommand(c, "keymgr", fmt.Sprintf(` +keydir=%q +case $1 in + features) + echo '{"signing":["RSA-PKCS"] , "public-keys":["DER"]}' + ;; + key-names) + echo '{"key-names": ["default", "models"]}' + ;; + get-public-key) + if [ "$5" = missing ]; then + echo not found + exit 1 + fi + cat ${keydir}/"$5".pub + ;; + sign) + openssl rsautl -sign -pkcs -keyform DER -inkey ${keydir}/"$5".key + ;; + *) + exit 1 + ;; +esac +`, tmpdir)) +} + +func (s *extKeypairMgrSuite) TearDownSuite(c *C) { + s.pgm.Restore() +} + +func (s *extKeypairMgrSuite) TestFeaturesErrors(c *C) { + pgm := testutil.MockCommand(c, "keymgr", ` +if [ "$1" != "features" ]; then + exit 2 +fi +if [ "${EXT_KEYMGR_FAIL}" = "exit-1" ]; then + exit 1 +fi +echo "${EXT_KEYMGR_FAIL}" +`) + defer pgm.Restore() + defer os.Unsetenv("EXT_KEYMGR_FAIL") + + tests := []struct { + outcome string + err string + }{ + {"exit-1", `.*exit status 1.*`}, + {`{"signing":["RSA-PKCS"]}`, `external keypair manager "keymgr" missing support for public key DER output format`}, + {"{}", `external keypair manager \"keymgr\" missing support for RSA-PKCS signing`}, + {"{", `cannot decode external keypair manager "keymgr" \[features\] output.*`}, + {"", `cannot decode external keypair manager "keymgr" \[features\] output.*`}, + } + + defer os.Unsetenv("EXT_KEYMGR_FAIL") + for _, t := range tests { + os.Setenv("EXT_KEYMGR_FAIL", t.outcome) + + _, err := asserts.NewExternalKeypairManager("keymgr") + c.Check(err, ErrorMatches, t.err) + c.Check(pgm.Calls(), DeepEquals, [][]string{ + {"keymgr", "features"}, + }) + pgm.ForgetCalls() + } +} + +func (s *extKeypairMgrSuite) TestGetByName(c *C) { + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + s.pgm.ForgetCalls() + + pk, err := kmgr.GetByName("default") + c.Assert(err, IsNil) + + expPK := asserts.RSAPublicKey(s.defaultPub) + + c.Check(pk.PublicKey().ID(), DeepEquals, expPK.ID()) + + c.Check(s.pgm.Calls(), DeepEquals, [][]string{ + {"keymgr", "get-public-key", "-f", "DER", "-k", "default"}, + }) +} + +func (s *extKeypairMgrSuite) TestGetByNameNotFound(c *C) { + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + + _, err = kmgr.GetByName("missing") + c.Check(err, ErrorMatches, `cannot find external key:.*missing.*`) +} + +func (s *extKeypairMgrSuite) TestGet(c *C) { + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + s.pgm.ForgetCalls() + + defaultID := asserts.RSAPublicKey(s.defaultPub).ID() + modelsID := asserts.RSAPublicKey(s.modelsPub).ID() + + pk1, err := kmgr.Get(defaultID) + c.Assert(err, IsNil) + c.Check(pk1.PublicKey().ID(), Equals, defaultID) + + pk2, err := kmgr.Get(modelsID) + c.Assert(err, IsNil) + c.Check(pk2.PublicKey().ID(), Equals, modelsID) + + c.Check(s.pgm.Calls(), DeepEquals, [][]string{ + {"keymgr", "key-names"}, + {"keymgr", "get-public-key", "-f", "DER", "-k", "default"}, + {"keymgr", "get-public-key", "-f", "DER", "-k", "models"}, + }) + + _, err = kmgr.Get("unknown-id") + c.Check(err, ErrorMatches, `cannot find external key with id "unknown-id"`) +} + +func (s *extKeypairMgrSuite) TestSignFlow(c *C) { + // the signing uses openssl + _, err := exec.LookPath("openssl") + if err != nil { + c.Skip("cannot locate openssl on this system to test signing") + } + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + s.pgm.ForgetCalls() + + pk, err := kmgr.GetByName("default") + c.Assert(err, IsNil) + + store := assertstest.NewStoreStack("trusted", nil) + + brandAcct := assertstest.NewAccount(store, "brand", map[string]interface{}{ + "account-id": "brand-id", + }, "") + brandAccKey := assertstest.NewAccountKey(store, brandAcct, nil, pk.PublicKey(), "") + + signDB, err := asserts.OpenDatabase(&asserts.DatabaseConfig{ + KeypairManager: kmgr, + }) + c.Assert(err, IsNil) + + checkDB, err := asserts.OpenDatabase(&asserts.DatabaseConfig{ + Backstore: asserts.NewMemoryBackstore(), + Trusted: store.Trusted, + }) + c.Assert(err, IsNil) + // add store key + err = checkDB.Add(store.StoreAccountKey("")) + c.Assert(err, IsNil) + // enable brand key + err = checkDB.Add(brandAcct) + c.Assert(err, IsNil) + err = checkDB.Add(brandAccKey) + c.Assert(err, IsNil) + + modelHdsrs := map[string]interface{}{ + "authority-id": "brand-id", + "brand-id": "brand-id", + "model": "model", + "series": "16", + "architecture": "amd64", + "base": "core18", + "gadget": "gadget", + "kernel": "pc-kernel", + "timestamp": time.Now().Format(time.RFC3339), + } + a, err := signDB.Sign(asserts.ModelType, modelHdsrs, nil, pk.PublicKey().ID()) + c.Assert(err, IsNil) + + // valid + err = checkDB.Check(a) + c.Assert(err, IsNil) + + c.Check(s.pgm.Calls(), DeepEquals, [][]string{ + {"keymgr", "get-public-key", "-f", "DER", "-k", "default"}, + {"keymgr", "sign", "-m", "RSA-PKCS", "-k", "default"}, + }) +} + +func (s *extKeypairMgrSuite) TestExport(c *C) { + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + + keys := []struct { + name string + pk *rsa.PublicKey + }{ + {name: "default", pk: s.defaultPub}, + {name: "models", pk: s.modelsPub}, + } + + for _, tk := range keys { + exported, err := kmgr.Export(tk.name) + c.Assert(err, IsNil) + + expected, err := asserts.EncodePublicKey(asserts.RSAPublicKey(tk.pk)) + c.Assert(err, IsNil) + c.Check(exported, DeepEquals, expected) + } +} + +func (s *extKeypairMgrSuite) TestList(c *C) { + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + + keys, err := kmgr.List() + c.Assert(err, IsNil) + + defaultID := asserts.RSAPublicKey(s.defaultPub).ID() + modelsID := asserts.RSAPublicKey(s.modelsPub).ID() + + c.Check(keys, DeepEquals, []asserts.ExternalKeyInfo{ + {Name: "default", ID: defaultID}, + {Name: "models", ID: modelsID}, + }) +} + +func (s *extKeypairMgrSuite) TestListError(c *C) { + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + + pgm := testutil.MockCommand(c, "keymgr", `exit 1`) + defer pgm.Restore() + + _, err = kmgr.List() + c.Check(err, ErrorMatches, `cannot get all external keypair manager key names:.*exit status 1.*`) +} + +func (s *extKeypairMgrSuite) TestDeleteUnsupported(c *C) { + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + + err = kmgr.Delete("key") + c.Check(err, ErrorMatches, `no support to delete external keypair manager keys`) + c.Check(err, FitsTypeOf, &asserts.ExternalUnsupportedOpError{}) + +} + +func (s *extKeypairMgrSuite) TestGenerateUnsupported(c *C) { + kmgr, err := asserts.NewExternalKeypairManager("keymgr") + c.Assert(err, IsNil) + + err = kmgr.Generate("key") + c.Check(err, ErrorMatches, `no support to mediate generating an external keypair manager key`) + c.Check(err, FitsTypeOf, &asserts.ExternalUnsupportedOpError{}) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/fetcher_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/fetcher_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/fetcher_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/fetcher_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -25,7 +25,6 @@ "time" "golang.org/x/crypto/sha3" - . "gopkg.in/check.v1" "github.com/snapcore/snapd/asserts" diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/gpgkeypairmgr.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/gpgkeypairmgr.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/gpgkeypairmgr.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/gpgkeypairmgr.go 2023-03-23 08:10:58.000000000 +0000 @@ -1,7 +1,7 @@ // -*- Mode: Go; indent-tabs-mode: t -*- /* - * Copyright (C) 2016 Canonical Ltd + * Copyright (C) 2016-2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -28,6 +28,8 @@ "path/filepath" "strings" + "golang.org/x/crypto/openpgp/packet" + "github.com/snapcore/snapd/osutil" ) @@ -141,13 +143,13 @@ } pubKeyBuf := bytes.NewBuffer(out) - privKey, err := newExtPGPPrivateKey(pubKeyBuf, "GPG", func(content []byte) ([]byte, error) { + privKey, err := newExtPGPPrivateKey(pubKeyBuf, "GPG", func(content []byte) (*packet.Signature, error) { return gkm.sign(fpr, content) }) if err != nil { return nil, fmt.Errorf("cannot load GPG public key with fingerprint %q: %v", fpr, err) } - gotFingerprint := privKey.fingerprint() + gotFingerprint := privKey.externalID if gotFingerprint != fpr { return nil, fmt.Errorf("got wrong public key from GPG, expected fingerprint %q: %s", fpr, gotFingerprint) } @@ -254,12 +256,24 @@ return nil, fmt.Errorf("cannot find key %q in GPG keyring", keyID) } -func (gkm *GPGKeypairManager) sign(fingerprint string, content []byte) ([]byte, error) { +func (gkm *GPGKeypairManager) sign(fingerprint string, content []byte) (*packet.Signature, error) { out, err := gkm.gpg(content, "--personal-digest-preferences", "SHA512", "--default-key", "0x"+fingerprint, "--detach-sign") if err != nil { return nil, fmt.Errorf("cannot sign using GPG: %v", err) } - return out, nil + + badSig := "bad GPG produced signature: " + sigpkt, err := packet.Read(bytes.NewBuffer(out)) + if err != nil { + return nil, fmt.Errorf(badSig+"%v", err) + } + + sig, ok := sigpkt.(*packet.Signature) + if !ok { + return nil, fmt.Errorf(badSig+"got %T", sigpkt) + } + + return sig, nil } type gpgKeypairInfo struct { @@ -351,3 +365,18 @@ } return nil } + +func (gkm *GPGKeypairManager) List() (res []ExternalKeyInfo, err error) { + collect := func(privk PrivateKey, fpr string, uid string) error { + key := ExternalKeyInfo{ + Name: uid, + ID: privk.PublicKey().ID(), + } + res = append(res, key) + return nil + } + if err := gkm.Walk(collect); err != nil { + return nil, err + } + return res, nil +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/gpgkeypairmgr_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/gpgkeypairmgr_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/gpgkeypairmgr_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/gpgkeypairmgr_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -1,7 +1,7 @@ // -*- Mode: Go; indent-tabs-mode: t -*- /* - * Copyright (C) 2016 Canonical Ltd + * Copyright (C) 2016-2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -28,9 +28,8 @@ "os" "time" - . "gopkg.in/check.v1" - "golang.org/x/crypto/openpgp/packet" + . "gopkg.in/check.v1" "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/asserts/assertstest" @@ -329,3 +328,13 @@ c.Check(parameters, Equals, baseParameters+test.extraParameters) } } + +func (gkms *gpgKeypairMgrSuite) TestList(c *C) { + gpgKeypairMgr := gkms.keypairMgr.(*asserts.GPGKeypairManager) + + keys, err := gpgKeypairMgr.List() + c.Assert(err, IsNil) + c.Check(keys, HasLen, 1) + c.Check(keys[0].ID, Equals, assertstest.DevKeyID) + c.Check(keys[0].Name, Not(Equals), "") +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/ifacedecls_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/ifacedecls_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/ifacedecls_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/ifacedecls_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -29,7 +29,6 @@ "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/snap" - "github.com/snapcore/snapd/testutil" ) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/pool.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/pool.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/pool.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/pool.go 2023-03-23 08:10:58.000000000 +0000 @@ -1020,3 +1020,8 @@ p.curPhase = poolPhaseAdd return nil } + +// Backstore returns the memory backstore of this pool. +func (p *Pool) Backstore() Backstore { + return p.bs +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/pool_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/pool_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/pool_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/pool_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -1716,3 +1716,29 @@ }) c.Check(toResolveSeq, HasLen, 0) } + +func (s *poolSuite) TestBackstore(c *C) { + assertstest.AddMany(s.db, s.hub.StoreAccountKey(""), s.dev1Acct) + pool := asserts.NewPool(s.db, 64) + + at1111 := &asserts.AtRevision{ + Ref: asserts.Ref{Type: asserts.TestOnlyRevType, PrimaryKey: []string{"1111"}}, + Revision: asserts.RevisionNotKnown, + } + c.Assert(pool.AddUnresolved(at1111, "for_one"), IsNil) + res, _, err := pool.ToResolve() + c.Assert(err, IsNil) + c.Assert(res, HasLen, 1) + + // resolve (but do not commit) + ok, err := pool.Add(s.rev1_1111, asserts.MakePoolGrouping(0)) + c.Assert(err, IsNil) + c.Assert(ok, Equals, true) + + // the assertion should be available via pool's backstore + bs := pool.Backstore() + c.Assert(bs, NotNil) + a, err := bs.Get(s.rev1_1111.Type(), s.rev1_1111.At().PrimaryKey, s.rev1_1111.Type().MaxSupportedFormat()) + c.Assert(err, IsNil) + c.Assert(a, NotNil) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/snapasserts_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/snapasserts_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/snapasserts_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/snapasserts_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -28,7 +28,6 @@ "time" "golang.org/x/crypto/sha3" - . "gopkg.in/check.v1" "github.com/snapcore/snapd/asserts" diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/validation_sets.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/validation_sets.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/validation_sets.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/validation_sets.go 2023-03-23 08:10:58.000000000 +0000 @@ -359,7 +359,7 @@ } // CheckInstalledSnaps checks installed snaps against the validation sets. -func (v *ValidationSets) CheckInstalledSnaps(snaps []*InstalledSnap) error { +func (v *ValidationSets) CheckInstalledSnaps(snaps []*InstalledSnap, ignoreValidation map[string]bool) error { installed := naming.NewSnapSet(nil) for _, sn := range snaps { installed.Add(sn) @@ -377,6 +377,10 @@ sn := installed.Lookup(rc) isInstalled := sn != nil + if isInstalled && ignoreValidation[rc.Name] { + continue + } + switch { case !isInstalled && (cstrs.presence == asserts.PresenceOptional || cstrs.presence == asserts.PresenceInvalid): // not installed, but optional or not required @@ -401,7 +405,11 @@ sets[rc.validationSetKey] = v.sets[rc.validationSetKey] } default: - // not installed but required + // not installed but required. + // note, not checking ignoreValidation here because it's not a viable scenario (it's not + // possible to have enforced validation set while not having the required snap at all - it + // is only possible to have it with a wrong revision, or installed while invalid, in both + // cases through --ignore-validation flag). if missing[rc.Name] == nil { missing[rc.Name] = make(map[string]bool) } @@ -449,3 +457,97 @@ } return nil } + +// PresenceConstraintError describes an error where presence of the given snap +// has unexpected value, e.g. it's "invalid" while checking for "required". +type PresenceConstraintError struct { + SnapName string + Presence asserts.Presence +} + +func (e *PresenceConstraintError) Error() string { + return fmt.Sprintf("unexpected presence %q for snap %q", e.Presence, e.SnapName) +} + +func (v *ValidationSets) constraintsForSnap(snapRef naming.SnapRef) *snapContraints { + if snapRef.ID() != "" { + return v.snaps[snapRef.ID()] + } + // snapID not available, find by snap name + for _, cstrs := range v.snaps { + if cstrs.name == snapRef.SnapName() { + return cstrs + } + } + return nil +} + +// CheckPresenceRequired returns the list of all validation sets that declare +// presence of the given snap as required and the required revision (or +// snap.R(0) if no specific revision is required). PresenceConstraintError is +// returned if presence of the snap is "invalid". +// The method assumes that validation sets are not in conflict. +func (v *ValidationSets) CheckPresenceRequired(snapRef naming.SnapRef) ([]string, snap.Revision, error) { + cstrs := v.constraintsForSnap(snapRef) + if cstrs == nil { + return nil, unspecifiedRevision, nil + } + if cstrs.presence == asserts.PresenceInvalid { + return nil, unspecifiedRevision, &PresenceConstraintError{snapRef.SnapName(), cstrs.presence} + } + if cstrs.presence != asserts.PresenceRequired { + return nil, unspecifiedRevision, nil + } + + snapRev := unspecifiedRevision + var keys []string + for rev, revCstr := range cstrs.revisions { + for _, rc := range revCstr { + vs := v.sets[rc.validationSetKey] + if vs == nil { + return nil, unspecifiedRevision, fmt.Errorf("internal error: no validation set for %q", rc.validationSetKey) + } + keys = append(keys, strings.Join(vs.Ref().PrimaryKey, "/")) + // there may be constraints without revision; only set snapRev if + // it wasn't already determined. Note that if revisions are set, + // then they are the same, otherwise validation sets would be in + // conflict. + // This is an equivalent of 'if rev != unspecifiedRevision`. + if snapRev == unspecifiedRevision { + snapRev = rev + } + } + } + + sort.Strings(keys) + return keys, snapRev, nil +} + +// CheckPresenceInvalid returns the list of all validation sets that declare +// presence of the given snap as invalid. PresenceConstraintError is returned if +// presence of the snap is "optional" or "required". +// The method assumes that validation sets are not in conflict. +func (v *ValidationSets) CheckPresenceInvalid(snapRef naming.SnapRef) ([]string, error) { + cstrs := v.constraintsForSnap(snapRef) + if cstrs == nil { + return nil, nil + } + if cstrs.presence != asserts.PresenceInvalid { + return nil, &PresenceConstraintError{snapRef.SnapName(), cstrs.presence} + } + var keys []string + for _, revCstr := range cstrs.revisions { + for _, rc := range revCstr { + if rc.Presence == asserts.PresenceInvalid { + vs := v.sets[rc.validationSetKey] + if vs == nil { + return nil, fmt.Errorf("internal error: no validation set for %q", rc.validationSetKey) + } + keys = append(keys, strings.Join(vs.Ref().PrimaryKey, "/")) + } + } + } + + sort.Strings(keys) + return keys, nil +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/validation_sets_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/validation_sets_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/validation_sets_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/snapasserts/validation_sets_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -29,6 +29,7 @@ "github.com/snapcore/snapd/asserts/assertstest" "github.com/snapcore/snapd/asserts/snapasserts" "github.com/snapcore/snapd/snap" + "github.com/snapcore/snapd/snap/naming" ) type validationSetsSuite struct{} @@ -271,7 +272,7 @@ snaps := []*snapasserts.InstalledSnap{ snapasserts.NewInstalledSnap("snap-a", "mysnapaaaaaaaaaaaaaaaaaaaaaaaaaa", snap.R(1)), } - err := valsets.CheckInstalledSnaps(snaps) + err := valsets.CheckInstalledSnaps(snaps, nil) c.Assert(err, IsNil) } @@ -551,7 +552,7 @@ } for i, tc := range tests { - err := valsets.CheckInstalledSnaps(tc.snaps) + err := valsets.CheckInstalledSnaps(tc.snaps, nil) if err == nil { c.Assert(tc.expectedInvalid, IsNil) c.Assert(tc.expectedMissing, IsNil) @@ -567,6 +568,59 @@ } } +func (s *validationSetsSuite) TestCheckInstalledSnapsIgnoreValidation(c *C) { + // require: snapB rev 3, snapC rev 2. + // invalid: snapA + vs := assertstest.FakeAssertion(map[string]interface{}{ + "type": "validation-set", + "authority-id": "acme", + "series": "16", + "account-id": "acme", + "name": "fooname", + "sequence": "1", + "snaps": []interface{}{ + map[string]interface{}{ + "name": "snap-a", + "id": "mysnapaaaaaaaaaaaaaaaaaaaaaaaaaa", + "presence": "invalid", + }, + map[string]interface{}{ + "name": "snap-b", + "id": "mysnapbbbbbbbbbbbbbbbbbbbbbbbbbb", + "revision": "3", + "presence": "required", + }, + map[string]interface{}{ + "name": "snap-c", + "id": "mysnapcccccccccccccccccccccccccc", + "revision": "2", + "presence": "optional", + }, + }, + }).(*asserts.ValidationSet) + + valsets := snapasserts.NewValidationSets() + c.Assert(valsets.Add(vs), IsNil) + + snapA := snapasserts.NewInstalledSnap("snap-a", "mysnapaaaaaaaaaaaaaaaaaaaaaaaaaa", snap.R(1)) + snapB := snapasserts.NewInstalledSnap("snap-b", "mysnapbbbbbbbbbbbbbbbbbbbbbbbbbb", snap.R(3)) + snapBinvRev := snapasserts.NewInstalledSnap("snap-b", "mysnapbbbbbbbbbbbbbbbbbbbbbbbbbb", snap.R(8)) + + // sanity check + c.Check(valsets.CheckInstalledSnaps([]*snapasserts.InstalledSnap{snapA, snapB}, nil), ErrorMatches, "validation sets assertions are not met:\n"+ + "- invalid snaps:\n"+ + " - snap-a \\(invalid for sets acme/fooname\\)") + // snapA is invalid but ignore-validation is set so it's ok + c.Check(valsets.CheckInstalledSnaps([]*snapasserts.InstalledSnap{snapA, snapB}, map[string]bool{"snap-a": true}), IsNil) + + // sanity check + c.Check(valsets.CheckInstalledSnaps([]*snapasserts.InstalledSnap{snapBinvRev}, nil), ErrorMatches, "validation sets assertions are not met:\n"+ + "- snaps at wrong revisions:\n"+ + " - snap-b \\(required at revision 3 by sets acme/fooname\\)") + // snapB is at the wrong revision, but ignore-validation is set so it's ok + c.Check(valsets.CheckInstalledSnaps([]*snapasserts.InstalledSnap{snapBinvRev}, map[string]bool{"snap-b": true}), IsNil) +} + func (s *validationSetsSuite) TestCheckInstalledSnapsErrorFormat(c *C) { vs1 := assertstest.FakeAssertion(map[string]interface{}{ "type": "validation-set", @@ -640,7 +694,7 @@ } for i, tc := range tests { - err := valsets.CheckInstalledSnaps(tc.snaps) + err := valsets.CheckInstalledSnaps(tc.snaps, nil) c.Assert(err, NotNil, Commentf("#%d", i)) c.Assert(err, ErrorMatches, tc.errorMsg, Commentf("#%d: ", i)) } @@ -652,3 +706,193 @@ sort.Sort(snapasserts.ByRevision(revs)) c.Assert(revs, DeepEquals, []snap.Revision{snap.R(-1), snap.R(4), snap.R(5), snap.R(10)}) } + +func (s *validationSetsSuite) TestCheckPresenceRequired(c *C) { + valset1 := assertstest.FakeAssertion(map[string]interface{}{ + "type": "validation-set", + "authority-id": "account-id", + "series": "16", + "account-id": "account-id", + "name": "my-snap-ctl", + "sequence": "1", + "snaps": []interface{}{ + map[string]interface{}{ + "name": "my-snap", + "id": "mysnapididididididididididididid", + "presence": "required", + "revision": "7", + }, + map[string]interface{}{ + "name": "other-snap", + "id": "123456ididididididididididididid", + "presence": "optional", + }, + }, + }).(*asserts.ValidationSet) + + valset2 := assertstest.FakeAssertion(map[string]interface{}{ + "type": "validation-set", + "authority-id": "account-id", + "series": "16", + "account-id": "account-id", + "name": "my-snap-ctl2", + "sequence": "2", + "snaps": []interface{}{ + map[string]interface{}{ + "name": "my-snap", + "id": "mysnapididididididididididididid", + "presence": "required", + "revision": "7", + }, + map[string]interface{}{ + "name": "other-snap", + "id": "123456ididididididididididididid", + "presence": "invalid", + }, + }, + }).(*asserts.ValidationSet) + + // my-snap required but no specific revision set. + valset3 := assertstest.FakeAssertion(map[string]interface{}{ + "type": "validation-set", + "authority-id": "account-id", + "series": "16", + "account-id": "account-id", + "name": "my-snap-ctl3", + "sequence": "1", + "snaps": []interface{}{ + map[string]interface{}{ + "name": "my-snap", + "id": "mysnapididididididididididididid", + "presence": "required", + }, + }, + }).(*asserts.ValidationSet) + + valsets := snapasserts.NewValidationSets() + + // no validation sets + vsKeys, _, err := valsets.CheckPresenceRequired(naming.Snap("my-snap")) + c.Assert(err, IsNil) + c.Check(vsKeys, HasLen, 0) + + c.Assert(valsets.Add(valset1), IsNil) + c.Assert(valsets.Add(valset2), IsNil) + c.Assert(valsets.Add(valset3), IsNil) + + // sanity + c.Assert(valsets.Conflict(), IsNil) + + vsKeys, rev, err := valsets.CheckPresenceRequired(naming.Snap("my-snap")) + c.Assert(err, IsNil) + c.Check(rev, DeepEquals, snap.Revision{N: 7}) + c.Check(vsKeys, DeepEquals, []string{"16/account-id/my-snap-ctl/1", "16/account-id/my-snap-ctl2/2", "16/account-id/my-snap-ctl3/1"}) + + vsKeys, rev, err = valsets.CheckPresenceRequired(naming.NewSnapRef("my-snap", "mysnapididididididididididididid")) + c.Assert(err, IsNil) + c.Check(rev, DeepEquals, snap.Revision{N: 7}) + c.Check(vsKeys, DeepEquals, []string{"16/account-id/my-snap-ctl/1", "16/account-id/my-snap-ctl2/2", "16/account-id/my-snap-ctl3/1"}) + + // other-snap is not required + vsKeys, rev, err = valsets.CheckPresenceRequired(naming.Snap("other-snap")) + c.Assert(err, ErrorMatches, `unexpected presence "invalid" for snap "other-snap"`) + pr, ok := err.(*snapasserts.PresenceConstraintError) + c.Assert(ok, Equals, true) + c.Check(pr.SnapName, Equals, "other-snap") + c.Check(pr.Presence, Equals, asserts.PresenceInvalid) + c.Check(rev, DeepEquals, snap.Revision{N: 0}) + c.Check(vsKeys, HasLen, 0) + + // unknown snap is not required + vsKeys, rev, err = valsets.CheckPresenceRequired(naming.NewSnapRef("unknown-snap", "00000000idididididididididididid")) + c.Assert(err, IsNil) + c.Check(rev, DeepEquals, snap.Revision{N: 0}) + c.Check(vsKeys, HasLen, 0) + + // just one set, required but no revision specified + valsets = snapasserts.NewValidationSets() + c.Assert(valsets.Add(valset3), IsNil) + vsKeys, rev, err = valsets.CheckPresenceRequired(naming.Snap("my-snap")) + c.Assert(err, IsNil) + c.Check(rev, DeepEquals, snap.Revision{N: 0}) + c.Check(vsKeys, DeepEquals, []string{"16/account-id/my-snap-ctl3/1"}) +} + +func (s *validationSetsSuite) TestIsPresenceInvalid(c *C) { + valset1 := assertstest.FakeAssertion(map[string]interface{}{ + "type": "validation-set", + "authority-id": "account-id", + "series": "16", + "account-id": "account-id", + "name": "my-snap-ctl", + "sequence": "1", + "snaps": []interface{}{ + map[string]interface{}{ + "name": "my-snap", + "id": "mysnapididididididididididididid", + "presence": "invalid", + }, + map[string]interface{}{ + "name": "other-snap", + "id": "123456ididididididididididididid", + "presence": "optional", + }, + }, + }).(*asserts.ValidationSet) + + valset2 := assertstest.FakeAssertion(map[string]interface{}{ + "type": "validation-set", + "authority-id": "account-id", + "series": "16", + "account-id": "account-id", + "name": "my-snap-ctl2", + "sequence": "2", + "snaps": []interface{}{ + map[string]interface{}{ + "name": "my-snap", + "id": "mysnapididididididididididididid", + "presence": "invalid", + }, + }, + }).(*asserts.ValidationSet) + + valsets := snapasserts.NewValidationSets() + + // no validation sets + vsKeys, err := valsets.CheckPresenceInvalid(naming.Snap("my-snap")) + c.Assert(err, IsNil) + c.Check(vsKeys, HasLen, 0) + + c.Assert(valsets.Add(valset1), IsNil) + c.Assert(valsets.Add(valset2), IsNil) + + // sanity + c.Assert(valsets.Conflict(), IsNil) + + // invalid in two sets + vsKeys, err = valsets.CheckPresenceInvalid(naming.Snap("my-snap")) + c.Assert(err, IsNil) + c.Check(vsKeys, DeepEquals, []string{"16/account-id/my-snap-ctl/1", "16/account-id/my-snap-ctl2/2"}) + + vsKeys, err = valsets.CheckPresenceInvalid(naming.NewSnapRef("my-snap", "mysnapididididididididididididid")) + c.Assert(err, IsNil) + c.Check(vsKeys, DeepEquals, []string{"16/account-id/my-snap-ctl/1", "16/account-id/my-snap-ctl2/2"}) + + // other-snap isn't invalid + vsKeys, err = valsets.CheckPresenceInvalid(naming.Snap("other-snap")) + c.Assert(err, ErrorMatches, `unexpected presence "optional" for snap "other-snap"`) + pr, ok := err.(*snapasserts.PresenceConstraintError) + c.Assert(ok, Equals, true) + c.Check(pr.SnapName, Equals, "other-snap") + c.Check(pr.Presence, Equals, asserts.PresenceOptional) + c.Check(vsKeys, HasLen, 0) + + vsKeys, err = valsets.CheckPresenceInvalid(naming.NewSnapRef("other-snap", "123456ididididididididididididid")) + c.Assert(err, ErrorMatches, `unexpected presence "optional" for snap "other-snap"`) + c.Check(vsKeys, HasLen, 0) + + // unknown snap isn't invalid + vsKeys, err = valsets.CheckPresenceInvalid(naming.NewSnapRef("unknown-snap", "00000000idididididididididididid")) + c.Assert(err, IsNil) + c.Check(vsKeys, HasLen, 0) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/snap_asserts.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/snap_asserts.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/snap_asserts.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/snap_asserts.go 2023-03-23 08:10:58.000000000 +0000 @@ -25,7 +25,8 @@ "fmt" "time" - _ "golang.org/x/crypto/sha3" // expected for digests + // expected for digests + _ "golang.org/x/crypto/sha3" "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/release" diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/store_asserts_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/store_asserts_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/store_asserts_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/store_asserts_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -24,9 +24,10 @@ "strings" "time" + . "gopkg.in/check.v1" + "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/asserts/assertstest" - . "gopkg.in/check.v1" ) var _ = Suite(&storeSuite{}) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/sysdb/sysdb_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/sysdb/sysdb_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/asserts/sysdb/sysdb_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/asserts/sysdb/sysdb_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -27,11 +27,10 @@ . "gopkg.in/check.v1" - "github.com/snapcore/snapd/dirs" - "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/asserts/assertstest" "github.com/snapcore/snapd/asserts/sysdb" + "github.com/snapcore/snapd/dirs" ) func TestSysDB(t *testing.T) { TestingT(t) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/assets.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/assets.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/assets.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/assets.go 2023-03-23 08:10:58.000000000 +0000 @@ -518,16 +518,16 @@ } switch op { case gadget.ContentUpdate: - return o.observeUpdate(whichBootloader, isRecovery, root, relativeTarget, data) + return o.observeUpdate(whichBootloader, isRecovery, relativeTarget, data) case gadget.ContentRollback: - return o.observeRollback(whichBootloader, isRecovery, root, relativeTarget, data) + return o.observeRollback(whichBootloader, isRecovery, root, relativeTarget) default: // we only care about update and rollback actions return gadget.ChangeApply, nil } } -func (o *TrustedAssetsUpdateObserver) observeUpdate(bl bootloader.Bootloader, recovery bool, root, relativeTarget string, change *gadget.ContentChange) (gadget.ContentChangeAction, error) { +func (o *TrustedAssetsUpdateObserver) observeUpdate(bl bootloader.Bootloader, recovery bool, relativeTarget string, change *gadget.ContentChange) (gadget.ContentChangeAction, error) { modeenvBefore, err := o.modeenv.Copy() if err != nil { return gadget.ChangeAbort, fmt.Errorf("cannot copy modeenv: %v", err) @@ -594,7 +594,7 @@ return gadget.ChangeApply, nil } -func (o *TrustedAssetsUpdateObserver) observeRollback(bl bootloader.Bootloader, recovery bool, root, relativeTarget string, data *gadget.ContentChange) (gadget.ContentChangeAction, error) { +func (o *TrustedAssetsUpdateObserver) observeRollback(bl bootloader.Bootloader, recovery bool, root, relativeTarget string) (gadget.ContentChangeAction, error) { trustedAssets := &o.modeenv.CurrentTrustedBootAssets otherTrustedAssets := o.modeenv.CurrentTrustedRecoveryBootAssets if recovery { @@ -672,7 +672,7 @@ return nil } const expectReseal = true - if err := resealKeyToModeenv(dirs.GlobalRootDir, o.model, o.modeenv, expectReseal); err != nil { + if err := resealKeyToModeenv(dirs.GlobalRootDir, o.modeenv, expectReseal); err != nil { return err } return nil @@ -738,7 +738,7 @@ } const expectReseal = true - if err := resealKeyToModeenv(dirs.GlobalRootDir, o.model, o.modeenv, expectReseal); err != nil { + if err := resealKeyToModeenv(dirs.GlobalRootDir, o.modeenv, expectReseal); err != nil { return fmt.Errorf("while canceling gadget update: %v", err) } return nil diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/assets_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/assets_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/assets_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/assets_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -79,7 +79,7 @@ return obs, uc20Model } -func (s *assetsSuite) bootloaderWithTrustedAssets(c *C, trustedAssets []string) *bootloadertest.MockTrustedAssetsBootloader { +func (s *assetsSuite) bootloaderWithTrustedAssets(trustedAssets []string) *bootloadertest.MockTrustedAssetsBootloader { tab := bootloadertest.Mock("trusted", "").WithTrustedAssets() bootloader.Force(tab) tab.TrustedAssetsList = trustedAssets @@ -253,7 +253,7 @@ c.Assert(nonUC20obs, IsNil) // listing trusted assets fails - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", }) tab.TrustedAssetsErr = fmt.Errorf("fail") @@ -369,7 +369,7 @@ func (s *assetsSuite) TestInstallObserverObserveSystemBootMocked(c *C) { d := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", "nested/other-asset", }) @@ -429,7 +429,7 @@ func (s *assetsSuite) TestInstallObserverObserveSystemBootMockedNoEncryption(c *C) { d := c.MkDir() - s.bootloaderWithTrustedAssets(c, []string{"asset"}) + s.bootloaderWithTrustedAssets([]string{"asset"}) uc20Model := boottest.MakeMockUC20Model() useEncryption := false obs, err := boot.TrustedAssetsInstallObserverForModel(uc20Model, d, useEncryption) @@ -439,7 +439,7 @@ func (s *assetsSuite) TestInstallObserverObserveSystemBootMockedUnencryptedWithManaged(c *C) { d := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) + tab := s.bootloaderWithTrustedAssets([]string{"asset"}) tab.ManagedAssetsList = []string{"managed"} uc20Model := boottest.MakeMockUC20Model() useEncryption := false @@ -505,7 +505,7 @@ func (s *assetsSuite) TestInstallObserverTrustedReuseNameErr(c *C) { d := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", "nested/asset", }) @@ -537,7 +537,7 @@ func (s *assetsSuite) TestInstallObserverObserveExistingRecoveryMocked(c *C) { d := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", "nested/other-asset", "shim", @@ -587,7 +587,7 @@ func (s *assetsSuite) TestInstallObserverObserveExistingRecoveryReuseNameErr(c *C) { d := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", "nested/asset", }) @@ -617,7 +617,7 @@ func (s *assetsSuite) TestInstallObserverObserveExistingRecoveryButMissingErr(c *C) { d := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", }) @@ -634,7 +634,7 @@ } func (s *assetsSuite) TestUpdateObserverNew(c *C) { - tab := s.bootloaderWithTrustedAssets(c, nil) + tab := s.bootloaderWithTrustedAssets(nil) uc20Model := boottest.MakeMockUC20Model() @@ -710,7 +710,7 @@ err = m.WriteTo("") c.Assert(err, IsNil) - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", "nested/other-asset", "shim", @@ -796,7 +796,7 @@ d := c.MkDir() root := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", "shim", }) @@ -902,7 +902,7 @@ d := c.MkDir() root := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", }) @@ -958,7 +958,7 @@ d := c.MkDir() root := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", }) @@ -1135,7 +1135,7 @@ err = m.WriteTo("") c.Assert(err, IsNil) - s.bootloaderWithTrustedAssets(c, []string{ + s.bootloaderWithTrustedAssets([]string{ "asset", }) @@ -1183,7 +1183,7 @@ d := c.MkDir() backups := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", "nested/other-asset", "shim", @@ -1300,7 +1300,7 @@ func (s *assetsSuite) TestUpdateObserverRollbackFileSanity(c *C) { root := c.MkDir() - tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) + tab := s.bootloaderWithTrustedAssets([]string{"asset"}) // we get an observer for UC20 obs, _ := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) @@ -1590,7 +1590,7 @@ c.Assert(err, IsNil) } - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) // we get an observer for UC20 obs, _ := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) @@ -1672,7 +1672,7 @@ d := c.MkDir() root := c.MkDir() - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) data := []byte("foobar") // SHA3-384 @@ -1791,7 +1791,7 @@ c.Assert(err, IsNil) } - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) // we get an observer for UC20 obs, _ := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) @@ -1850,7 +1850,7 @@ err := m.WriteTo("") c.Assert(err, IsNil) - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) // we get an observer for UC20 obs, _ := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) @@ -1904,7 +1904,7 @@ err := m.WriteTo("") c.Assert(err, IsNil) - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) // we get an observer for UC20 obs, _ := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) @@ -1974,7 +1974,7 @@ c.Assert(err, IsNil) } - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) // we get an observer for UC20 obs, _ := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) @@ -2043,7 +2043,7 @@ func (s *assetsSuite) TestObserveSuccessfulBootNoAssetsOnDisk(c *C) { // call to observe successful boot, but assets do not exist on disk - s.bootloaderWithTrustedAssets(c, []string{"asset"}) + s.bootloaderWithTrustedAssets([]string{"asset"}) m := &boot.Modeenv{ Mode: "run", @@ -2066,7 +2066,7 @@ func (s *assetsSuite) TestObserveSuccessfulBootAfterUpdate(c *C) { // call to observe successful boot - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) data := []byte("foobar") // SHA3-384 @@ -2116,7 +2116,7 @@ func (s *assetsSuite) TestObserveSuccessfulBootWithUnexpected(c *C) { // call to observe successful boot, but the asset we booted with is unexpected - s.bootloaderWithTrustedAssets(c, []string{"asset"}) + s.bootloaderWithTrustedAssets([]string{"asset"}) data := []byte("foobar") dataHash := "0fa8abfbdaf924ad307b74dd2ed183b9a4a398891a2f6bac8fd2db7041b77f068580f9c6c66f699b496c2da1cbcc7ed8" @@ -2156,7 +2156,7 @@ func (s *assetsSuite) TestObserveSuccessfulBootSingleEntries(c *C) { // call to observe successful boot - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) data := []byte("foobar") // SHA3-384 @@ -2194,7 +2194,7 @@ // bootloader is used by the ubuntu-boot bootloader, so it cannot be // dropped from cache - s.bootloaderWithTrustedAssets(c, []string{"asset"}) + s.bootloaderWithTrustedAssets([]string{"asset"}) maybeDrop := []byte("maybe-drop") maybeDropHash := "08a99ce3af529ebbfb9a82df690007ac650635b165c3d1b416d471907fa3843270dce9cc001ea26f4afb4e0c5af05209" @@ -2234,7 +2234,7 @@ func (s *assetsSuite) TestObserveSuccessfulBootParallelUpdate(c *C) { // call to observe successful boot - s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) + s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) data := []byte("foobar") // SHA3-384 @@ -2282,7 +2282,7 @@ c.Skip("the test cannot be executed by the root user") } - s.bootloaderWithTrustedAssets(c, []string{"asset"}) + s.bootloaderWithTrustedAssets([]string{"asset"}) data := []byte("foobar") dataHash := "0fa8abfbdaf924ad307b74dd2ed183b9a4a398891a2f6bac8fd2db7041b77f068580f9c6c66f699b496c2da1cbcc7ed8" @@ -2306,7 +2306,7 @@ } func (s *assetsSuite) TestObserveSuccessfulBootDifferentMode(c *C) { - s.bootloaderWithTrustedAssets(c, []string{"asset"}) + s.bootloaderWithTrustedAssets([]string{"asset"}) m := &boot.Modeenv{ Mode: "recover", @@ -2439,6 +2439,14 @@ err = ioutil.WriteFile(filepath.Join(d, "shim"), shim, 0644) c.Assert(err, IsNil) + tab := s.bootloaderWithTrustedAssets([]string{ + "asset", + "shim", + }) + + // we get an observer for UC20 + obs, uc20model := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) + m := boot.Modeenv{ Mode: "run", CurrentTrustedBootAssets: boot.BootAssetsMap{ @@ -2449,18 +2457,15 @@ }, CurrentRecoverySystems: []string{"recovery-system-label"}, CurrentKernels: []string{"pc-kernel_500.snap"}, + + Model: uc20model.Model(), + BrandID: uc20model.BrandID(), + Grade: string(uc20model.Grade()), + ModelSignKeyID: uc20model.SignKeyID(), } err = m.WriteTo("") c.Assert(err, IsNil) - tab := s.bootloaderWithTrustedAssets(c, []string{ - "asset", - "shim", - }) - - // we get an observer for UC20 - obs, uc20model := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) - res, err := obs.Observe(gadget.ContentUpdate, mockRunBootStruct, root, "asset", &gadget.ContentChange{ After: filepath.Join(d, "foobar"), @@ -2493,7 +2498,7 @@ }) restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { - return uc20model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + return uc20model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -2522,7 +2527,7 @@ c.Assert(params.ModelParams, HasLen, 1) mp := params.ModelParams[0] - c.Check(mp.Model, DeepEquals, uc20model) + c.Check(mp.Model.Model(), Equals, uc20model.Model()) for _, ch := range mp.EFILoadChains { printChain(c, ch, "-") } @@ -2566,6 +2571,22 @@ d := c.MkDir() root := c.MkDir() + // mock some files in cache + c.Assert(os.MkdirAll(filepath.Join(dirs.SnapBootAssetsDir, "trusted"), 0755), IsNil) + for _, name := range []string{ + "shim-shimhash", + "asset-assethash", + "asset-recoveryhash", + } { + err := ioutil.WriteFile(filepath.Join(dirs.SnapBootAssetsDir, "trusted", name), nil, 0644) + c.Assert(err, IsNil) + } + + tab := s.bootloaderWithTrustedAssets([]string{"asset", "shim"}) + + // we get an observer for UC20 + obs, uc20model := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) + m := boot.Modeenv{ Mode: "run", CurrentTrustedBootAssets: boot.BootAssetsMap{ @@ -2579,26 +2600,15 @@ CurrentRecoverySystems: []string{"system"}, CurrentKernels: []string{"pc-kernel_1.snap"}, CurrentKernelCommandLines: boot.BootCommandLines{"snapd_recovery_mode=run"}, + + Model: uc20model.Model(), + BrandID: uc20model.BrandID(), + Grade: string(uc20model.Grade()), + ModelSignKeyID: uc20model.SignKeyID(), } err := m.WriteTo("") c.Assert(err, IsNil) - // mock some files in cache - c.Assert(os.MkdirAll(filepath.Join(dirs.SnapBootAssetsDir, "trusted"), 0755), IsNil) - for _, name := range []string{ - "shim-shimhash", - "asset-assethash", - "asset-recoveryhash", - } { - err = ioutil.WriteFile(filepath.Join(dirs.SnapBootAssetsDir, "trusted", name), nil, 0644) - c.Assert(err, IsNil) - } - - tab := s.bootloaderWithTrustedAssets(c, []string{"asset", "shim"}) - - // we get an observer for UC20 - obs, uc20model := s.uc20UpdateObserverEncryptedSystemMockedBootloader(c) - data := []byte("foobar") err = ioutil.WriteFile(filepath.Join(d, "foobar"), data, 0644) c.Assert(err, IsNil) @@ -2626,7 +2636,7 @@ c.Check(res, Equals, gadget.ChangeApply) restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { - return uc20model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + return uc20model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -2650,7 +2660,7 @@ resealCalls++ c.Assert(params.ModelParams, HasLen, 1) mp := params.ModelParams[0] - c.Check(mp.Model, DeepEquals, uc20model) + c.Check(mp.Model.Model(), Equals, uc20model.Model()) for _, ch := range mp.EFILoadChains { printChain(c, ch, "-") } @@ -2713,7 +2723,7 @@ err = m.WriteTo("") c.Assert(err, IsNil) - tab := s.bootloaderWithTrustedAssets(c, []string{ + tab := s.bootloaderWithTrustedAssets([]string{ "asset", }) tab.ManagedAssetsList = []string{ diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/bootchain.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/bootchain.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/bootchain.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/bootchain.go 2023-03-23 08:10:58.000000000 +0000 @@ -47,10 +47,18 @@ KernelRevision string `json:"kernel-revision"` KernelCmdlines []string `json:"kernel-cmdlines"` - model *asserts.Model kernelBootFile bootloader.BootFile } +func (b *bootChain) modelForSealing() *modelForSealing { + return &modelForSealing{ + brandID: b.BrandID, + model: b.Model, + grade: b.Grade, + modelSignKeyID: b.ModelSignKeyID, + } +} + // TODO:UC20 add a doc comment when this is stabilized type bootAsset struct { Role bootloader.Role `json:"role"` diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/bootchain_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/bootchain_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/bootchain_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/bootchain_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -27,8 +27,8 @@ . "gopkg.in/check.v1" + "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/boot" - "github.com/snapcore/snapd/boot/boottest" "github.com/snapcore/snapd/bootloader" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/secboot" @@ -152,8 +152,6 @@ KernelCmdlines: []string{`foo=bar baz=0x123`, `a=1`}, } - uc20model := boottest.MakeMockUC20Model() - bc.SetModelAssertion(uc20model) kernelBootFile := bootloader.NewBootFile("pc-kernel", "/foo", bootloader.RoleRecovery) bc.SetKernelBootFile(kernelBootFile) @@ -174,7 +172,6 @@ KernelCmdlines: []string{`a=1`, `foo=bar baz=0x123`}, } // those can't be set directly, but are copied as well - expectedPredictableBc.SetModelAssertion(uc20model) expectedPredictableBc.SetKernelBootFile(kernelBootFile) predictableBc := boot.ToPredictableBootChain(bc) @@ -197,7 +194,6 @@ KernelRevision: "1234", KernelCmdlines: []string{`foo=bar baz=0x123`, `a=1`}, } - expectedOriginal.SetModelAssertion(uc20model) expectedOriginal.SetKernelBootFile(kernelBootFile) // original structure has not been modified c.Check(bc, DeepEquals, expectedOriginal) @@ -1233,3 +1229,21 @@ c.Check(loaded, IsNil) c.Check(cnt, Equals, 0) } + +func (s *bootchainSuite) TestModelForSealing(c *C) { + bc := boot.BootChain{ + BrandID: "my-brand", + Model: "my-model", + Grade: "signed", + ModelSignKeyID: "my-key-id", + } + + modelForSealing := bc.SecbootModelForSealing() + c.Check(modelForSealing.Model(), Equals, "my-model") + c.Check(modelForSealing.BrandID(), Equals, "my-brand") + c.Check(modelForSealing.Grade(), Equals, asserts.ModelGrade("signed")) + c.Check(modelForSealing.SignKeyID(), Equals, "my-key-id") + c.Check(modelForSealing.Series(), Equals, "16") + c.Check(boot.ModelUniqueID(modelForSealing), Equals, "my-brand/my-model,signed,my-key-id") + +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/boot.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/boot.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/boot.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/boot.go 2023-03-23 08:10:58.000000000 +0000 @@ -344,6 +344,7 @@ trustedAssetsBootState(dev), trustedCommandLineBootState(dev), recoverySystemsBootState(dev), + modelBootState(dev), } { var err error u, err = bs.markSuccessful(u) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/bootstate20.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/bootstate20.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/bootstate20.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/bootstate20.go 2023-03-23 08:10:58.000000000 +0000 @@ -23,7 +23,6 @@ "fmt" "path/filepath" - "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/bootloader" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/logger" @@ -96,9 +95,6 @@ // tasks to run after the modeenv has been written postModeenvTasks []bootCommitTask - - // model set if a reseal might be necessary - resealModel *asserts.Model } func (u20 *bootStateUpdate20) preModeenv(task bootCommitTask) { @@ -109,10 +105,6 @@ u20.postModeenvTasks = append(u20.postModeenvTasks, task) } -func (u20 *bootStateUpdate20) resealForModel(model *asserts.Model) { - u20.resealModel = model -} - func newBootStateUpdate20(m *Modeenv) (*bootStateUpdate20, error) { u20 := &bootStateUpdate20{} if m == nil { @@ -166,15 +158,14 @@ // post-modeenv tasks so if we are rebooted at any point after // the reseal even before the post tasks are completed, we // still boot properly - if u20.resealModel != nil { - // if there is ambiguity whether the boot chains have - // changed because of unasserted kernels, then pass a - // flag as hint whether to reseal based on whether we - // wrote the modeenv - expectReseal := modeenvRewritten - if err := resealKeyToModeenv(dirs.GlobalRootDir, u20.resealModel, u20.writeModeenv, expectReseal); err != nil { - return err - } + + // if there is ambiguity whether the boot chains have + // changed because of unasserted kernels, then pass a + // flag as hint whether to reseal based on whether we + // wrote the modeenv + expectReseal := modeenvRewritten + if err := resealKeyToModeenv(dirs.GlobalRootDir, u20.writeModeenv, expectReseal); err != nil { + return err } // finally handle any post-modeenv writing tasks @@ -290,9 +281,6 @@ // On commit, set CurrentKernels as just this kernel because that is the // successful kernel we booted u20.writeModeenv.CurrentKernels = []string{sn.Filename()} - - // keep track of the model for resealing - u20.resealForModel(ks20.dev.Model()) } return u20, nil @@ -327,9 +315,6 @@ // As such, set the next kernel as a post modeenv task. u20.postModeenv(func() error { return ks20.bks.setNextKernel(next, nextStatus) }) - // keep track of the model for resealing - u20.resealForModel(ks20.dev.Model()) - return rebootRequired, u20, nil } @@ -692,8 +677,6 @@ } // update modeenv u20.writeModeenv = newM - // keep track of the model for resealing - u20.resealForModel(ba20.dev.Model()) if len(dropAssets) == 0 { // nothing to drop, we're done @@ -758,7 +741,7 @@ return nil, err } - newM, err := observeSuccessfulSystems(brs20.dev.Model(), u20.writeModeenv) + newM, err := observeSuccessfulSystems(u20.writeModeenv) if err != nil { return nil, fmt.Errorf("cannot mark successful recovery system: %v", err) } @@ -769,3 +752,30 @@ func recoverySystemsBootState(dev Device) *bootState20RecoverySystem { return &bootState20RecoverySystem{dev: dev} } + +// bootState20Model implements the successfulBootState interface for device +// model related bookkeeping +type bootState20Model struct { + dev Device +} + +func (brs20 *bootState20Model) markSuccessful(update bootStateUpdate) (bootStateUpdate, error) { + u20, err := toBootStateUpdate20(update) + if err != nil { + return nil, err + } + + // sign key ID was not being populated in earlier versions of snapd, try + // to remedy that + if u20.modeenv.ModelSignKeyID == "" { + if err != nil { + return nil, err + } + u20.writeModeenv.ModelSignKeyID = brs20.dev.Model().SignKeyID() + } + return u20, nil +} + +func modelBootState(dev Device) *bootState20Model { + return &bootState20Model{dev: dev} +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/boottest/bootenv.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/boottest/bootenv.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/boottest/bootenv.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/boottest/bootenv.go 2023-03-23 08:10:58.000000000 +0000 @@ -75,7 +75,7 @@ return true } } - return true + return false } func exactlyType(which []snap.Type, t snap.Type) bool { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/boot_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/boot_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/boot_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/boot_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -207,8 +207,6 @@ bootloader *bootloadertest.MockBootloader } -var defaultUC20BootEnv = map[string]string{"kernel_status": boot.DefaultStatus} - var _ = Suite(&bootenv20Suite{}) var _ = Suite(&bootenv20EnvRefKernelSuite{}) @@ -878,6 +876,7 @@ coreDev := boottest.MockUC20Device("", nil) c.Assert(coreDev.HasModeenv(), Equals, true) + model := coreDev.Model() m := &boot.Modeenv{ Mode: "run", @@ -886,6 +885,10 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": {dataHash}, }, + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } r := setupUC20Bootenv( @@ -905,7 +908,7 @@ c.Assert(params.ModelParams, HasLen, 1) mp := params.ModelParams[0] - c.Check(mp.Model, DeepEquals, coreDev.Model()) + c.Check(mp.Model.Model(), Equals, model.Model()) for _, ch := range mp.EFILoadChains { printChain(c, ch, "-") } @@ -995,6 +998,10 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": {dataHash}, }, + Model: uc20Model.Model(), + BrandID: uc20Model.BrandID(), + Grade: string(uc20Model.Grade()), + ModelSignKeyID: uc20Model.SignKeyID(), } r := setupUC20Bootenv( @@ -1014,7 +1021,7 @@ c.Assert(params.ModelParams, HasLen, 1) mp := params.ModelParams[0] - c.Check(mp.Model, DeepEquals, uc20Model) + c.Check(mp.Model.Model(), Equals, uc20Model.Model()) for _, ch := range mp.EFILoadChains { printChain(c, ch, "-") } @@ -1101,6 +1108,11 @@ "asset": {dataHash}, }, CurrentKernelCommandLines: boot.BootCommandLines{"snapd_recovery_mode=run"}, + + Model: uc20Model.Model(), + BrandID: uc20Model.BrandID(), + Grade: string(uc20Model.Grade()), + ModelSignKeyID: uc20Model.SignKeyID(), } r := setupUC20Bootenv( @@ -1214,6 +1226,11 @@ "asset": {dataHash}, }, CurrentKernelCommandLines: boot.BootCommandLines{"snapd_recovery_mode=run"}, + + Model: uc20Model.Model(), + BrandID: uc20Model.BrandID(), + Grade: string(uc20Model.Grade()), + ModelSignKeyID: uc20Model.SignKeyID(), } r := setupUC20Bootenv( @@ -1548,10 +1565,41 @@ // checked by resealKeyToModeenv s.stampSealedKeys(c, dirs.GlobalRootDir) + // set up all the bits required for an encrypted system tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) + data := []byte("foobar") + // SHA3-384 + dataHash := "0fa8abfbdaf924ad307b74dd2ed183b9a4a398891a2f6bac8fd2db7041b77f068580f9c6c66f699b496c2da1cbcc7ed8" + c.Assert(os.MkdirAll(filepath.Join(boot.InitramfsUbuntuBootDir), 0755), IsNil) + c.Assert(ioutil.WriteFile(filepath.Join(boot.InitramfsUbuntuBootDir, "asset"), data, 0644), IsNil) + // mock the files in cache + mockAssetsCache(c, dirs.GlobalRootDir, "trusted", []string{ + "asset-" + dataHash, + }) + runKernelBf := bootloader.NewBootFile(filepath.Join(s.kern1.Filename()), "kernel.efi", bootloader.RoleRunMode) + // write boot-chains for current state that will stay unchanged even + // though base is changed + bootChains := []boot.BootChain{{ + BrandID: "my-brand", + Model: "my-model-uc20", + Grade: "dangerous", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", + AssetChain: []boot.BootAsset{{ + Role: bootloader.RoleRunMode, Name: "asset", Hashes: []string{ + "0fa8abfbdaf924ad307b74dd2ed183b9a4a398891a2f6bac8fd2db7041b77f068580f9c6c66f699b496c2da1cbcc7ed8", + }, + }}, + Kernel: "pc-kernel", + KernelRevision: "1", + KernelCmdlines: []string{"snapd_recovery_mode=run"}, + }} + + err := boot.WriteBootChains(boot.ToPredictableBootChains(bootChains), filepath.Join(dirs.SnapFDEDir, "boot-chains"), 0) + c.Assert(err, IsNil) coreDev := boottest.MockUC20Device("", nil) c.Assert(coreDev.HasModeenv(), Equals, true) + model := coreDev.Model() resealCalls := 0 restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { @@ -1560,13 +1608,24 @@ }) defer restore() - // we should not even need to build boot chains - tab.BootChainErr = errors.New("boom") + tab.BootChainList = []bootloader.BootFile{ + bootloader.NewBootFile("", "asset", bootloader.RoleRunMode), + runKernelBf, + } // default state m := &boot.Modeenv{ - Mode: "run", - Base: s.base1.Filename(), + Mode: "run", + Base: s.base1.Filename(), + CurrentKernels: []string{s.kern1.Filename()}, + CurrentTrustedBootAssets: boot.BootAssetsMap{ + "asset": {dataHash}, + }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } r := setupUC20Bootenv( c, @@ -1853,9 +1912,7 @@ dataHash := "0fa8abfbdaf924ad307b74dd2ed183b9a4a398891a2f6bac8fd2db7041b77f068580f9c6c66f699b496c2da1cbcc7ed8" c.Assert(os.MkdirAll(filepath.Join(boot.InitramfsUbuntuBootDir), 0755), IsNil) - c.Assert(os.MkdirAll(filepath.Join(boot.InitramfsUbuntuSeedDir), 0755), IsNil) c.Assert(ioutil.WriteFile(filepath.Join(boot.InitramfsUbuntuBootDir, "asset"), data, 0644), IsNil) - c.Assert(ioutil.WriteFile(filepath.Join(boot.InitramfsUbuntuSeedDir, "asset"), data, 0644), IsNil) // mock the files in cache mockAssetsCache(c, dirs.GlobalRootDir, "trusted", []string{ @@ -1863,13 +1920,17 @@ }) assetBf := bootloader.NewBootFile("", filepath.Join(dirs.SnapBootAssetsDir, "trusted", fmt.Sprintf("asset-%s", dataHash)), bootloader.RoleRunMode) - runKernelBf := bootloader.NewBootFile(filepath.Join(s.kern1.Filename()), "kernel.efi", bootloader.RoleRunMode) + newRunKernelBf := bootloader.NewBootFile(filepath.Join(s.kern2.Filename()), "kernel.efi", bootloader.RoleRunMode) tab.BootChainList = []bootloader.BootFile{ bootloader.NewBootFile("", "asset", bootloader.RoleRunMode), - runKernelBf, + newRunKernelBf, } + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + model := coreDev.Model() + // trying a kernel snap m := &boot.Modeenv{ Mode: "run", @@ -1878,6 +1939,10 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": {dataHash}, }, + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } r := setupUC20Bootenv( c, @@ -1891,8 +1956,38 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) + // write boot-chains that describe a state in which we have a new kernel + // candidate (pc-kernel_2) + bootChains := []boot.BootChain{{ + BrandID: "my-brand", + Model: "my-model-uc20", + Grade: "dangerous", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", + AssetChain: []boot.BootAsset{{ + Role: bootloader.RoleRunMode, Name: "asset", Hashes: []string{ + "0fa8abfbdaf924ad307b74dd2ed183b9a4a398891a2f6bac8fd2db7041b77f068580f9c6c66f699b496c2da1cbcc7ed8", + }, + }}, + Kernel: "pc-kernel", + KernelRevision: "1", + KernelCmdlines: []string{"snapd_recovery_mode=run"}, + }, { + BrandID: "my-brand", + Model: "my-model-uc20", + Grade: "dangerous", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", + AssetChain: []boot.BootAsset{{ + Role: bootloader.RoleRunMode, Name: "asset", Hashes: []string{ + "0fa8abfbdaf924ad307b74dd2ed183b9a4a398891a2f6bac8fd2db7041b77f068580f9c6c66f699b496c2da1cbcc7ed8", + }, + }}, + Kernel: "pc-kernel", + KernelRevision: "2", + KernelCmdlines: []string{"snapd_recovery_mode=run"}, + }} + + err := boot.WriteBootChains(boot.ToPredictableBootChains(bootChains), filepath.Join(dirs.SnapFDEDir, "boot-chains"), 0) + c.Assert(err, IsNil) resealCalls := 0 restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { @@ -1900,22 +1995,23 @@ c.Assert(params.ModelParams, HasLen, 1) mp := params.ModelParams[0] - c.Check(mp.Model, DeepEquals, coreDev.Model()) + c.Check(mp.Model.Model(), Equals, model.Model()) for _, ch := range mp.EFILoadChains { printChain(c, ch, "-") } c.Check(mp.EFILoadChains, DeepEquals, []*secboot.LoadChain{ secboot.NewLoadChain(assetBf, - secboot.NewLoadChain(runKernelBf)), + secboot.NewLoadChain(newRunKernelBf)), }) return nil }) defer restore() // mark successful - err := boot.MarkBootSuccessful(coreDev) + err = boot.MarkBootSuccessful(coreDev) c.Assert(err, IsNil) + c.Check(resealCalls, Equals, 1) // check the bootloader variables expected := map[string]string{ "kernel_status": boot.DefaultStatus, @@ -1923,13 +2019,12 @@ "snap_try_kernel": boot.DefaultStatus, } c.Assert(tab.BootVars, DeepEquals, expected) + c.Check(tab.BootChainKernelPath, DeepEquals, []string{s.kern2.MountFile()}) // check that the new kernel is the only one in modeenv m2, err := boot.ReadModeenv("") c.Assert(err, IsNil) c.Assert(m2.CurrentKernels, DeepEquals, []string{s.kern2.Filename()}) - - c.Check(resealCalls, Equals, 1) } func (s *bootenv20EnvRefKernelSuite) TestMarkBootSuccessful20KernelUpdate(c *C) { @@ -2083,7 +2178,7 @@ uc20Model := boottest.MakeMockUC20Model() restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { - return uc20Model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + return uc20Model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -2100,6 +2195,11 @@ "shim": {"recoveryshimhash", shimHash}, }, CurrentRecoverySystems: []string{"system"}, + + Model: uc20Model.Model(), + BrandID: uc20Model.BrandID(), + Grade: string(uc20Model.Grade()), + ModelSignKeyID: uc20Model.SignKeyID(), } r := setupUC20Bootenv( c, @@ -2121,7 +2221,7 @@ c.Assert(params.ModelParams, HasLen, 1) mp := params.ModelParams[0] - c.Check(mp.Model, DeepEquals, uc20Model) + c.Check(mp.Model.Model(), Equals, uc20Model.Model()) for _, ch := range mp.EFILoadChains { printChain(c, ch, "-") } @@ -2214,7 +2314,7 @@ uc20Model := boottest.MakeMockUC20Model() restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { - return uc20Model, []*seed.Snap{mockNamedKernelSeedSnap(c, snap.R(1), "pc-kernel-recovery"), mockGadgetSeedSnap(c, nil)}, nil + return uc20Model, []*seed.Snap{mockNamedKernelSeedSnap(snap.R(1), "pc-kernel-recovery"), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -2232,6 +2332,11 @@ }, CurrentRecoverySystems: []string{"system"}, CurrentKernelCommandLines: boot.BootCommandLines{"snapd_recovery_mode=run"}, + + Model: uc20Model.Model(), + BrandID: uc20Model.BrandID(), + Grade: string(uc20Model.Grade()), + ModelSignKeyID: uc20Model.SignKeyID(), } r := setupUC20Bootenv( c, @@ -2367,7 +2472,7 @@ uc20Model := boottest.MakeMockUC20Model() restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { - return uc20Model, []*seed.Snap{mockNamedKernelSeedSnap(c, snap.R(1), "pc-kernel-recovery"), mockGadgetSeedSnap(c, nil)}, nil + return uc20Model, []*seed.Snap{mockNamedKernelSeedSnap(snap.R(1), "pc-kernel-recovery"), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -2386,6 +2491,11 @@ CurrentRecoverySystems: []string{"system"}, GoodRecoverySystems: []string{"system"}, CurrentKernelCommandLines: boot.BootCommandLines{"snapd_recovery_mode=run"}, + // leave this comment to keep old gofmt happy + Model: "my-model-uc20", + BrandID: "my-brand", + Grade: "dangerous", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", } r := setupUC20Bootenv( c, @@ -2496,6 +2606,10 @@ "asset-two", }) + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + model := coreDev.Model() + // we were trying an update of boot assets m := &boot.Modeenv{ Mode: "run", @@ -2508,6 +2622,10 @@ CurrentTrustedRecoveryBootAssets: boot.BootAssetsMap{ "asset": {"one", "two"}, }, + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } r := setupUC20Bootenv( c, @@ -2520,9 +2638,6 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) - // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, ErrorMatches, fmt.Sprintf(`cannot mark boot successful: cannot mark successful boot assets: system booted with unexpected run mode bootloader asset "EFI/asset" hash %s`, dataHash)) @@ -2540,7 +2655,7 @@ }) } -func (s *bootenv20Suite) setupMarkBootSuccessful20CommandLine(c *C, mode string, cmdlines boot.BootCommandLines) *boot.Modeenv { +func (s *bootenv20Suite) setupMarkBootSuccessful20CommandLine(c *C, model *asserts.Model, mode string, cmdlines boot.BootCommandLines) *boot.Modeenv { // mock some state in the cache mockAssetsCache(c, dirs.GlobalRootDir, "trusted", []string{ "asset-one", @@ -2557,6 +2672,11 @@ "asset": {"one"}, }, CurrentKernelCommandLines: cmdlines, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } return m } @@ -2564,7 +2684,9 @@ func (s *bootenv20Suite) TestMarkBootSuccessful20CommandLineUpdatedHappy(c *C) { s.mockCmdline(c, "snapd_recovery_mode=run candidate panic=-1") tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) - m := s.setupMarkBootSuccessful20CommandLine(c, "run", boot.BootCommandLines{ + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + m := s.setupMarkBootSuccessful20CommandLine(c, coreDev.Model(), "run", boot.BootCommandLines{ "snapd_recovery_mode=run panic=-1", "snapd_recovery_mode=run candidate panic=-1", }) @@ -2579,9 +2701,6 @@ }, ) defer r() - - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, IsNil) @@ -2598,7 +2717,9 @@ func (s *bootenv20Suite) TestMarkBootSuccessful20CommandLineUpdatedOld(c *C) { s.mockCmdline(c, "snapd_recovery_mode=run panic=-1") tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) - m := s.setupMarkBootSuccessful20CommandLine(c, "run", boot.BootCommandLines{ + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + m := s.setupMarkBootSuccessful20CommandLine(c, coreDev.Model(), "run", boot.BootCommandLines{ "snapd_recovery_mode=run panic=-1", "snapd_recovery_mode=run candidate panic=-1", }) @@ -2613,8 +2734,6 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, IsNil) @@ -2631,7 +2750,9 @@ func (s *bootenv20Suite) TestMarkBootSuccessful20CommandLineUpdatedMismatch(c *C) { s.mockCmdline(c, "snapd_recovery_mode=run different") tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) - m := s.setupMarkBootSuccessful20CommandLine(c, "run", boot.BootCommandLines{ + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + m := s.setupMarkBootSuccessful20CommandLine(c, coreDev.Model(), "run", boot.BootCommandLines{ "snapd_recovery_mode=run", "snapd_recovery_mode=run candidate", }) @@ -2646,8 +2767,6 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, ErrorMatches, `cannot mark boot successful: cannot mark successful boot command line: current command line content "snapd_recovery_mode=run different" not matching any expected entry`) @@ -2657,7 +2776,9 @@ s.mockCmdline(c, "snapd_recovery_mode=run panic=-1") tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) tab.StaticCommandLine = "panic=-1" - m := s.setupMarkBootSuccessful20CommandLine(c, "run", nil) + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + m := s.setupMarkBootSuccessful20CommandLine(c, coreDev.Model(), "run", nil) r := setupUC20Bootenv( c, tab.MockBootloader, @@ -2669,8 +2790,6 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, IsNil) @@ -2688,7 +2807,9 @@ s.mockCmdline(c, "snapd_recovery_mode=run panic=-1 unexpected") tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) tab.StaticCommandLine = "panic=-1" - m := s.setupMarkBootSuccessful20CommandLine(c, "run", nil) + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + m := s.setupMarkBootSuccessful20CommandLine(c, coreDev.Model(), "run", nil) r := setupUC20Bootenv( c, tab.MockBootloader, @@ -2700,8 +2821,6 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, ErrorMatches, `cannot mark boot successful: cannot mark successful boot command line: unexpected current command line: "snapd_recovery_mode=run panic=-1 unexpected"`) @@ -2712,8 +2831,10 @@ s.mockCmdline(c, "snapd_recovery_mode=recover snapd_recovery_system=1234 panic=-1") tab := s.bootloaderWithTrustedAssets(c, []string{"asset"}) tab.StaticCommandLine = "panic=-1" + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) // current command line does not match any of the run mode command lines - m := s.setupMarkBootSuccessful20CommandLine(c, "recover", boot.BootCommandLines{ + m := s.setupMarkBootSuccessful20CommandLine(c, coreDev.Model(), "recover", boot.BootCommandLines{ "snapd_recovery_mode=run panic=-1", "snapd_recovery_mode=run candidate panic=-1", }) @@ -2728,8 +2849,6 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, IsNil) @@ -2747,7 +2866,9 @@ func (s *bootenv20Suite) TestMarkBootSuccessful20CommandLineUpdatedNoFDEManagedBootloader(c *C) { s.mockCmdline(c, "snapd_recovery_mode=run candidate panic=-1") tab := s.bootloaderWithTrustedAssets(c, nil) - m := s.setupMarkBootSuccessful20CommandLine(c, "run", boot.BootCommandLines{ + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + m := s.setupMarkBootSuccessful20CommandLine(c, coreDev.Model(), "run", boot.BootCommandLines{ "snapd_recovery_mode=run panic=-1", "snapd_recovery_mode=run candidate panic=-1", }) @@ -2768,8 +2889,6 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, IsNil) @@ -2789,7 +2908,9 @@ bl := bootloadertest.Mock("not-trusted", "") bootloader.Force(bl) s.AddCleanup(func() { bootloader.Force(nil) }) - m := s.setupMarkBootSuccessful20CommandLine(c, "run", nil) + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + m := s.setupMarkBootSuccessful20CommandLine(c, coreDev.Model(), "run", nil) // no trusted assets m.CurrentTrustedBootAssets = nil m.CurrentTrustedRecoveryBootAssets = nil @@ -2807,8 +2928,6 @@ ) defer r() - coreDev := boottest.MockUC20Device("", nil) - c.Assert(coreDev.HasModeenv(), Equals, true) // mark successful err := boot.MarkBootSuccessful(coreDev) c.Assert(err, IsNil) @@ -2893,6 +3012,48 @@ c.Check(m2.CurrentRecoverySystems, DeepEquals, []string{"1234", "9999"}) } +func (s *bootenv20Suite) TestMarkBootSuccessful20ModelSignKeyIDPopulated(c *C) { + b := bootloadertest.Mock("mock", s.bootdir) + s.forceBootloader(b) + + coreDev := boottest.MockUC20Device("", nil) + c.Assert(coreDev.HasModeenv(), Equals, true) + + m := &boot.Modeenv{ + Mode: "run", + Base: s.base1.Filename(), + CurrentKernels: []string{s.kern1.Filename()}, + Model: "my-model-uc20", + BrandID: "my-brand", + Grade: "dangerous", + // sign key ID is unset + } + + r := setupUC20Bootenv( + c, + b, + &bootenv20Setup{ + modeenv: m, + kern: s.kern1, + kernStatus: boot.DefaultStatus, + }, + ) + defer r() + + // mark successful + err := boot.MarkBootSuccessful(coreDev) + c.Assert(err, IsNil) + + // check the modeenv + m2, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + // model's sign key ID has been set + c.Check(m2.ModelSignKeyID, Equals, "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij") + c.Check(m2.Model, Equals, "my-model-uc20") + c.Check(m2.BrandID, Equals, "my-brand") + c.Check(m2.Grade, Equals, "dangerous") +} + type recoveryBootenv20Suite struct { baseBootenvSuite @@ -3772,6 +3933,7 @@ resealPanic := false restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { s.resealCalls++ + c.Logf("reseal call %v", s.resealCalls) c.Assert(params, NotNil) c.Assert(params.ModelParams, HasLen, 1) s.resealCommandLines = append(s.resealCommandLines, params.ModelParams[0].KernelCmdlines) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/cmdline.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/cmdline.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/cmdline.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/cmdline.go 2023-03-23 08:10:58.000000000 +0000 @@ -136,10 +136,7 @@ candidateEdition ) -func composeCommandLine(model *asserts.Model, currentOrCandidate int, mode, system, gadgetDirOrSnapPath string) (string, error) { - if model.Grade() == asserts.ModelGradeUnset { - return "", nil - } +func composeCommandLine(currentOrCandidate int, mode, system, gadgetDirOrSnapPath string) (string, error) { if mode != ModeRun && mode != ModeRecover { return "", fmt.Errorf("internal error: unsupported command line mode %q", mode) } @@ -196,27 +193,39 @@ // ComposeRecoveryCommandLine composes the kernel command line used when booting // a given system in recover mode. func ComposeRecoveryCommandLine(model *asserts.Model, system, gadgetDirOrSnapPath string) (string, error) { - return composeCommandLine(model, currentEdition, ModeRecover, system, gadgetDirOrSnapPath) + if model.Grade() == asserts.ModelGradeUnset { + return "", nil + } + return composeCommandLine(currentEdition, ModeRecover, system, gadgetDirOrSnapPath) } // ComposeCommandLine composes the kernel command line used when booting the // system in run mode. func ComposeCommandLine(model *asserts.Model, gadgetDirOrSnapPath string) (string, error) { - return composeCommandLine(model, currentEdition, ModeRun, "", gadgetDirOrSnapPath) + if model.Grade() == asserts.ModelGradeUnset { + return "", nil + } + return composeCommandLine(currentEdition, ModeRun, "", gadgetDirOrSnapPath) } // ComposeCandidateCommandLine composes the kernel command line used when // booting the system in run mode with the current built-in edition of managed // boot assets. func ComposeCandidateCommandLine(model *asserts.Model, gadgetDirOrSnapPath string) (string, error) { - return composeCommandLine(model, candidateEdition, ModeRun, "", gadgetDirOrSnapPath) + if model.Grade() == asserts.ModelGradeUnset { + return "", nil + } + return composeCommandLine(candidateEdition, ModeRun, "", gadgetDirOrSnapPath) } // ComposeCandidateRecoveryCommandLine composes the kernel command line used // when booting the given system in recover mode with the current built-in // edition of managed boot assets. func ComposeCandidateRecoveryCommandLine(model *asserts.Model, system, gadgetDirOrSnapPath string) (string, error) { - return composeCommandLine(model, candidateEdition, ModeRecover, system, gadgetDirOrSnapPath) + if model.Grade() == asserts.ModelGradeUnset { + return "", nil + } + return composeCommandLine(candidateEdition, ModeRecover, system, gadgetDirOrSnapPath) } // observeSuccessfulCommandLine observes a successful boot with a command line @@ -351,7 +360,7 @@ } expectReseal := true - if err := resealKeyToModeenv(dirs.GlobalRootDir, model, m, expectReseal); err != nil { + if err := resealKeyToModeenv(dirs.GlobalRootDir, m, expectReseal); err != nil { return false, err } return true, nil @@ -360,7 +369,7 @@ // kernelCommandLinesForResealWithFallback provides the list of kernel command // lines for use during reseal. During normal operation, the command lines will // be listed in the modeenv. -func kernelCommandLinesForResealWithFallback(model *asserts.Model, modeenv *Modeenv) (cmdlines []string, err error) { +func kernelCommandLinesForResealWithFallback(modeenv *Modeenv) (cmdlines []string, err error) { if len(modeenv.CurrentKernelCommandLines) > 0 { return modeenv.CurrentKernelCommandLines, nil } @@ -368,7 +377,8 @@ // default during snapd update, since this is a compatibility scenario // there would be no kernel command lines arguments coming from the // gadget either - cmdline, err := ComposeCommandLine(model, "") + gadgetDir := "" + cmdline, err := composeCommandLine(currentEdition, ModeRun, "", gadgetDir) if err != nil { return nil, err } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/debug.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/debug.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/debug.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/debug.go 2023-03-23 08:10:58.000000000 +0000 @@ -71,6 +71,7 @@ "kernel_status", "recovery_system_status", "try_recovery_system", + "snapd_good_recovery_systems", "snapd_extra_cmdline_args", "snapd_full_cmdline_args", } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/export_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/export_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/export_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/export_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -68,6 +68,8 @@ SealKeyModelParams = sealKeyModelParams BootVarsForTrustedCommandLineFromGadget = bootVarsForTrustedCommandLineFromGadget + + WriteModelToUbuntuBoot = writeModelToUbuntuBoot ) type BootAssetsMap = bootAssetsMap @@ -116,14 +118,6 @@ } } -func MockSecbootResealKeys(f func(params *secboot.ResealKeysParams) error) (restore func()) { - old := secbootResealKeys - secbootResealKeys = f - return func() { - secbootResealKeys = old - } -} - func MockSeedReadSystemEssential(f func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error)) (restore func()) { old := seedReadSystemEssential seedReadSystemEssential = f @@ -169,6 +163,8 @@ SetImageBootFlags = setImageBootFlags NextBootFlags = nextBootFlags SetNextBootFlags = setNextBootFlags + + ModelUniqueID = modelUniqueID ) func SetBootFlagsInBootloader(flags []string, rootDir string) error { @@ -191,8 +187,8 @@ return bl.SetBootVars(blVars) } -func (b *bootChain) SetModelAssertion(model *asserts.Model) { - b.model = model +func (b *bootChain) SecbootModelForSealing() secboot.ModelForSealing { + return b.modelForSealing() } func (b *bootChain) SetKernelBootFile(kbf bootloader.BootFile) { @@ -217,7 +213,7 @@ return func() { RunFDESetupHook = oldRunFDESetupHook } } -func MockResealKeyToModeenvUsingFDESetupHook(f func(string, *asserts.Model, *Modeenv, bool) error) (restore func()) { +func MockResealKeyToModeenvUsingFDESetupHook(f func(string, *Modeenv, bool) error) (restore func()) { old := resealKeyToModeenvUsingFDESetupHook resealKeyToModeenvUsingFDESetupHook = f return func() { @@ -232,3 +228,11 @@ understoodBootFlags = old } } + +func MockWriteModelToUbuntuBoot(mock func(*asserts.Model) error) (restore func()) { + old := writeModelToUbuntuBoot + writeModelToUbuntuBoot = mock + return func() { + writeModelToUbuntuBoot = old + } +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/flags.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/flags.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/flags.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/flags.go 2023-03-23 08:10:58.000000000 +0000 @@ -143,7 +143,7 @@ return nil, nil case ModeCloudImg: - // no boot flags are consumed / used on recover mode, so return nothing + // no boot flags are consumed / used on cloudimg mode, so return nothing return nil, nil case ModeRun: diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/flags_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/flags_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/flags_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/flags_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -25,13 +25,14 @@ "os" "path/filepath" + . "gopkg.in/check.v1" + "github.com/snapcore/snapd/boot" "github.com/snapcore/snapd/boot/boottest" "github.com/snapcore/snapd/bootloader" "github.com/snapcore/snapd/bootloader/grubenv" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/testutil" - . "gopkg.in/check.v1" ) type bootFlagsSuite struct { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/makebootable.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/makebootable.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/makebootable.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/makebootable.go 2023-03-23 08:10:58.000000000 +0000 @@ -73,7 +73,7 @@ if !bootWith.Recovery { return fmt.Errorf("internal error: MakeBootableImage called at runtime, use MakeRunnableSystem instead") } - return makeBootable20(model, rootdir, bootWith, bootFlags) + return makeBootable20(rootdir, bootWith, bootFlags) } // makeBootable16 setups the image filesystem for boot with UC16 @@ -153,7 +153,7 @@ return nil } -func makeBootable20(model *asserts.Model, rootdir string, bootWith *BootableSet, bootFlags []string) error { +func makeBootable20(rootdir string, bootWith *BootableSet, bootFlags []string) error { // we can only make a single recovery system bootable right now recoverySystems, err := filepath.Glob(filepath.Join(rootdir, "systems/*")) if err != nil { @@ -363,6 +363,7 @@ BrandID: model.BrandID(), Model: model.Model(), Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } // get the ubuntu-boot bootloader and extract the kernel there @@ -462,5 +463,10 @@ } } + // so far so good, we managed to install the system, so it can be used + // for recovery as well + if err := MarkRecoveryCapableSystem(recoverySystemLabel); err != nil { + return fmt.Errorf("cannot record %q as a recovery capable system: %v", recoverySystemLabel, err) + } return nil } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/makebootable_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/makebootable_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/makebootable_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/makebootable_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -457,6 +457,8 @@ c.Assert(err, IsNil) err = ioutil.WriteFile(mockSeedGrubCfg, []byte("# Snapd-Boot-Config-Edition: 1\n"), 0644) c.Assert(err, IsNil) + genv := grubenv.NewEnv(filepath.Join(mockSeedGrubDir, "grubenv")) + c.Assert(genv.Save(), IsNil) // setup recovery boot assets err = os.MkdirAll(filepath.Join(boot.InitramfsUbuntuSeedDir, "EFI/boot"), 0755) @@ -559,7 +561,7 @@ readSystemEssentialCalls := 0 restore = boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { readSystemEssentialCalls++ - return model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + return model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -613,7 +615,7 @@ c.Errorf("unexpected additional call to secboot.SealKeys (call # %d)", sealKeysCalls) } - c.Assert(params.ModelParams[0].Model.DisplayName(), Equals, "My Model") + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") return nil }) @@ -639,8 +641,9 @@ // ensure the bootvars got updated the right way mockSeedGrubenv := filepath.Join(mockSeedGrubDir, "grubenv") - c.Check(mockSeedGrubenv, testutil.FilePresent) + c.Assert(mockSeedGrubenv, testutil.FilePresent) c.Check(mockSeedGrubenv, testutil.FileContains, "snapd_recovery_mode=run") + c.Check(mockSeedGrubenv, testutil.FileContains, "snapd_good_recovery_systems=20191216") mockBootGrubenv := filepath.Join(mockBootGrubDir, "grubenv") c.Check(mockBootGrubenv, testutil.FilePresent) @@ -669,6 +672,7 @@ current_kernels=pc-kernel_5.snap model=my-brand/my-model-uc20 grade=dangerous +model_sign_key_id=Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij current_trusted_boot_assets={"grubx64.efi":["5ee042c15e104b825d6bc15c41cdb026589f1ec57ed966dd3f29f961d4d6924efc54b187743fa3a583b62722882d405d"]} current_trusted_recovery_boot_assets={"bootx64.efi":["39efae6545f16e39633fbfbef0d5e9fdd45a25d7df8764978ce4d81f255b038046a38d9855e42e5c7c4024e153fd2e37"],"grubx64.efi":["aa3c1a83e74bf6dd40dd64e5c5bd1971d75cdf55515b23b9eb379f66bf43d4661d22c4b8cf7d7a982d2013ab65c1c4c5"]} current_kernel_command_lines=["snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1"] @@ -898,7 +902,7 @@ readSystemEssentialCalls := 0 restore = boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { readSystemEssentialCalls++ - return model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + return model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -939,7 +943,7 @@ "snapd_recovery_mode=recover snapd_recovery_system=20191216 console=ttyS0 console=tty1 panic=-1", "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", }) - c.Assert(params.ModelParams[0].Model.DisplayName(), Equals, "My Model") + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") return fmt.Errorf("seal error") }) @@ -964,6 +968,8 @@ c.Assert(err, IsNil) err = ioutil.WriteFile(mockSeedGrubCfg, []byte("# Snapd-Boot-Config-Edition: 1\n"), 0644) c.Assert(err, IsNil) + genv := grubenv.NewEnv(filepath.Join(mockSeedGrubDir, "grubenv")) + c.Assert(genv.Save(), IsNil) // setup recovery boot assets err = os.MkdirAll(filepath.Join(boot.InitramfsUbuntuSeedDir, "EFI/boot"), 0755) @@ -1059,7 +1065,7 @@ readSystemEssentialCalls := 0 restore = boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { readSystemEssentialCalls++ - return model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, gadgetFiles)}, nil + return model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, gadgetFiles)}, nil }) defer restore() @@ -1086,7 +1092,7 @@ c.Errorf("unexpected additional call to secboot.SealKeys (call # %d)", sealKeysCalls) } - c.Assert(params.ModelParams[0].Model.DisplayName(), Equals, "My Model") + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") return nil }) @@ -1108,8 +1114,9 @@ // ensure the bootvars got updated the right way mockSeedGrubenv := filepath.Join(mockSeedGrubDir, "grubenv") - c.Check(mockSeedGrubenv, testutil.FilePresent) + c.Assert(mockSeedGrubenv, testutil.FilePresent) c.Check(mockSeedGrubenv, testutil.FileContains, "snapd_recovery_mode=run") + c.Check(mockSeedGrubenv, testutil.FileContains, "snapd_good_recovery_systems=20191216") mockBootGrubenv := filepath.Join(mockBootGrubDir, "grubenv") c.Check(mockBootGrubenv, testutil.FilePresent) systemGenv := grubenv.NewEnv(mockBootGrubenv) @@ -1133,6 +1140,7 @@ current_kernels=pc-kernel_5.snap model=my-brand/my-model-uc20 grade=dangerous +model_sign_key_id=Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij current_trusted_boot_assets={"grubx64.efi":["5ee042c15e104b825d6bc15c41cdb026589f1ec57ed966dd3f29f961d4d6924efc54b187743fa3a583b62722882d405d"]} current_trusted_recovery_boot_assets={"bootx64.efi":["39efae6545f16e39633fbfbef0d5e9fdd45a25d7df8764978ce4d81f255b038046a38d9855e42e5c7c4024e153fd2e37"],"grubx64.efi":["aa3c1a83e74bf6dd40dd64e5c5bd1971d75cdf55515b23b9eb379f66bf43d4661d22c4b8cf7d7a982d2013ab65c1c4c5"]} current_kernel_command_lines=["%v"] @@ -1164,6 +1172,102 @@ s.testMakeSystemRunnable20WithCustomKernelArgs(c, "cmdline.extra", "foo bar snapd=unhappy", errMsg, "", "") } +func (s *makeBootable20Suite) TestMakeSystemRunnable20UnhappyMarkRecoveryCapable(c *C) { + bootloader.Force(nil) + + model := boottest.MakeMockUC20Model() + seedSnapsDirs := filepath.Join(s.rootdir, "/snaps") + err := os.MkdirAll(seedSnapsDirs, 0755) + c.Assert(err, IsNil) + + // grub on ubuntu-seed + mockSeedGrubDir := filepath.Join(boot.InitramfsUbuntuSeedDir, "EFI", "ubuntu") + mockSeedGrubCfg := filepath.Join(mockSeedGrubDir, "grub.cfg") + err = os.MkdirAll(filepath.Dir(mockSeedGrubCfg), 0755) + c.Assert(err, IsNil) + err = ioutil.WriteFile(mockSeedGrubCfg, []byte("# Snapd-Boot-Config-Edition: 1\n"), 0644) + c.Assert(err, IsNil) + // there is no grubenv in ubuntu-seed so loading from it will fail + + // setup recovery boot assets + err = os.MkdirAll(filepath.Join(boot.InitramfsUbuntuSeedDir, "EFI/boot"), 0755) + c.Assert(err, IsNil) + err = ioutil.WriteFile(filepath.Join(boot.InitramfsUbuntuSeedDir, "EFI/boot/bootx64.efi"), + []byte("recovery shim content"), 0644) + c.Assert(err, IsNil) + err = ioutil.WriteFile(filepath.Join(boot.InitramfsUbuntuSeedDir, "EFI/boot/grubx64.efi"), + []byte("recovery grub content"), 0644) + c.Assert(err, IsNil) + + // grub on ubuntu-boot + mockBootGrubDir := filepath.Join(boot.InitramfsUbuntuBootDir, "EFI", "ubuntu") + mockBootGrubCfg := filepath.Join(mockBootGrubDir, "grub.cfg") + err = os.MkdirAll(filepath.Dir(mockBootGrubCfg), 0755) + c.Assert(err, IsNil) + err = ioutil.WriteFile(mockBootGrubCfg, nil, 0644) + c.Assert(err, IsNil) + + unpackedGadgetDir := c.MkDir() + grubRecoveryCfg := []byte("#grub-recovery cfg") + grubRecoveryCfgAsset := []byte("#grub-recovery cfg from assets") + grubCfg := []byte("#grub cfg") + grubCfgAsset := []byte("# Snapd-Boot-Config-Edition: 1\n#grub cfg from assets") + snaptest.PopulateDir(unpackedGadgetDir, [][]string{ + {"grub-recovery.conf", string(grubRecoveryCfg)}, + {"grub.conf", string(grubCfg)}, + {"bootx64.efi", "shim content"}, + {"grubx64.efi", "grub content"}, + {"meta/snap.yaml", gadgetSnapYaml}, + }) + restore := assets.MockInternal("grub-recovery.cfg", grubRecoveryCfgAsset) + defer restore() + restore = assets.MockInternal("grub.cfg", grubCfgAsset) + defer restore() + + // make the snaps symlinks so that we can ensure that makebootable follows + // the symlinks and copies the files and not the symlinks + baseFn, baseInfo := makeSnap(c, "core20", `name: core20 +type: base +version: 5.0 +`, snap.R(3)) + baseInSeed := filepath.Join(seedSnapsDirs, baseInfo.Filename()) + err = os.Symlink(baseFn, baseInSeed) + c.Assert(err, IsNil) + kernelFn, kernelInfo := makeSnapWithFiles(c, "pc-kernel", `name: pc-kernel +type: kernel +version: 5.0 +`, snap.R(5), + [][]string{ + {"kernel.efi", "I'm a kernel.efi"}, + }, + ) + kernelInSeed := filepath.Join(seedSnapsDirs, kernelInfo.Filename()) + err = os.Symlink(kernelFn, kernelInSeed) + c.Assert(err, IsNil) + + bootWith := &boot.BootableSet{ + RecoverySystemDir: "20191216", + BasePath: baseInSeed, + Base: baseInfo, + KernelPath: kernelInSeed, + Kernel: kernelInfo, + Recovery: false, + UnpackedGadgetDir: unpackedGadgetDir, + } + + // set a mock recovery kernel + readSystemEssentialCalls := 0 + restore = boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { + readSystemEssentialCalls++ + return model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + }) + defer restore() + + err = boot.MakeRunnableSystem(model, bootWith, nil) + c.Assert(err, ErrorMatches, `cannot record "20191216" as a recovery capable system: open .*/run/mnt/ubuntu-seed/EFI/ubuntu/grubenv: no such file or directory`) + +} + func (s *makeBootable20UbootSuite) TestUbootMakeBootableImage20TraditionalUbootenvFails(c *C) { bootloader.Force(nil) model := boottest.MakeMockUC20Model() @@ -1386,6 +1490,7 @@ current_kernels=arm-kernel_5.snap model=my-brand/my-model-uc20 grade=dangerous +model_sign_key_id=Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij `) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/modeenv.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/modeenv.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/modeenv.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/modeenv.go 2023-03-23 08:10:58.000000000 +0000 @@ -32,8 +32,11 @@ "github.com/mvo5/goconfigparser" + "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/osutil" + "github.com/snapcore/snapd/release" + "github.com/snapcore/snapd/secboot" ) type bootAssetsMap map[string][]string @@ -59,9 +62,18 @@ TryBase string `key:"try_base"` BaseStatus string `key:"base_status"` CurrentKernels []string `key:"current_kernels"` - Model string `key:"model"` - BrandID string `key:"model,secondary"` - Grade string `key:"grade"` + // Model, BrandID, Grade, SignKeyID describe the properties of current + // device model. + Model string `key:"model"` + BrandID string `key:"model,secondary"` + Grade string `key:"grade"` + ModelSignKeyID string `key:"model_sign_key_id"` + // TryModel, TryBrandID, TryGrade, TrySignKeyID describe the properties + // of the candidate model. + TryModel string `key:"try_model"` + TryBrandID string `key:"try_model,secondary"` + TryGrade string `key:"try_grade"` + TryModelSignKeyID string `key:"try_model_sign_key_id"` // BootFlags is the set of boot flags. Whether this applies for the current // or next boot is not indicated in the modeenv. When the modeenv is read in // the initramfs these flags apply to the current boot and are copied into @@ -176,6 +188,14 @@ m.Model = bm.model // expect the caller to validate the grade unmarshalModeenvValueFromCfg(cfg, "grade", &m.Grade) + unmarshalModeenvValueFromCfg(cfg, "model_sign_key_id", &m.ModelSignKeyID) + var tryBm modeenvModel + unmarshalModeenvValueFromCfg(cfg, "try_model", &tryBm) + m.TryBrandID = tryBm.brandID + m.TryModel = tryBm.model + unmarshalModeenvValueFromCfg(cfg, "try_grade", &m.TryGrade) + unmarshalModeenvValueFromCfg(cfg, "try_model_sign_key_id", &m.TryModelSignKeyID) + unmarshalModeenvValueFromCfg(cfg, "current_trusted_boot_assets", &m.CurrentTrustedBootAssets) unmarshalModeenvValueFromCfg(cfg, "current_trusted_recovery_boot_assets", &m.CurrentTrustedRecoveryBootAssets) unmarshalModeenvValueFromCfg(cfg, "current_kernel_command_lines", &m.CurrentKernelCommandLines) @@ -273,7 +293,20 @@ } marshalModeenvEntryTo(buf, "model", &modeenvModel{brandID: m.BrandID, model: m.Model}) } + // TODO: complain when grade or key are unset marshalModeenvEntryTo(buf, "grade", m.Grade) + marshalModeenvEntryTo(buf, "model_sign_key_id", m.ModelSignKeyID) + if m.TryModel != "" || m.TryGrade != "" { + if m.TryModel == "" { + return fmt.Errorf("internal error: try model is unset") + } + if m.TryBrandID == "" { + return fmt.Errorf("internal error: try brand is unset") + } + marshalModeenvEntryTo(buf, "try_model", &modeenvModel{brandID: m.TryBrandID, model: m.TryModel}) + } + marshalModeenvEntryTo(buf, "try_grade", m.TryGrade) + marshalModeenvEntryTo(buf, "try_model_sign_key_id", m.TryModelSignKeyID) marshalModeenvEntryTo(buf, "current_trusted_boot_assets", m.CurrentTrustedBootAssets) marshalModeenvEntryTo(buf, "current_trusted_recovery_boot_assets", m.CurrentTrustedRecoveryBootAssets) marshalModeenvEntryTo(buf, "current_kernel_command_lines", m.CurrentKernelCommandLines) @@ -295,6 +328,75 @@ return nil } +// modelForSealing is a helper type that implements +// github.com/snapcore/secboot.SnapModel interface. +type modelForSealing struct { + brandID string + model string + grade asserts.ModelGrade + modelSignKeyID string +} + +// dummy to verify interface match +var _ secboot.ModelForSealing = (*modelForSealing)(nil) + +func (m *modelForSealing) BrandID() string { return m.brandID } +func (m *modelForSealing) SignKeyID() string { return m.modelSignKeyID } +func (m *modelForSealing) Model() string { return m.model } +func (m *modelForSealing) Grade() asserts.ModelGrade { return m.grade } +func (m *modelForSealing) Series() string { return release.Series } + +// modelUniqueID returns a unique ID which can be used as a map index of the +// provided model. +func modelUniqueID(m secboot.ModelForSealing) string { + return fmt.Sprintf("%s/%s,%s,%s", m.BrandID(), m.Model(), m.Grade(), m.SignKeyID()) +} + +// ModelForSealing returns a wrapper implementing +// github.com/snapcore/secboot.SnapModel interface which describes the current +// model. +func (m *Modeenv) ModelForSealing() secboot.ModelForSealing { + return &modelForSealing{ + brandID: m.BrandID, + model: m.Model, + grade: asserts.ModelGrade(m.Grade), + modelSignKeyID: m.ModelSignKeyID, + } +} + +// TryModelForSealing returns a wrapper implementing +// github.com/snapcore/secboot.SnapModel interface which describes the candidate +// or try model. +func (m *Modeenv) TryModelForSealing() secboot.ModelForSealing { + return &modelForSealing{ + brandID: m.TryBrandID, + model: m.TryModel, + grade: asserts.ModelGrade(m.TryGrade), + modelSignKeyID: m.TryModelSignKeyID, + } +} + +func (m *Modeenv) setModel(model *asserts.Model) { + m.Model = model.Model() + m.BrandID = model.BrandID() + m.Grade = string(model.Grade()) + m.ModelSignKeyID = model.SignKeyID() +} + +func (m *Modeenv) setTryModel(model *asserts.Model) { + m.TryModel = model.Model() + m.TryBrandID = model.BrandID() + m.TryGrade = string(model.Grade()) + m.TryModelSignKeyID = model.SignKeyID() +} + +func (m *Modeenv) clearTryModel() { + m.TryModel = "" + m.TryBrandID = "" + m.TryGrade = "" + m.TryModelSignKeyID = "" +} + type modeenvValueMarshaller interface { MarshalModeenvValue() (string, error) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/modeenv_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/modeenv_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/modeenv_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/modeenv_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -31,6 +31,7 @@ "github.com/mvo5/goconfigparser" . "gopkg.in/check.v1" + "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/boot" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/testutil" @@ -60,12 +61,16 @@ "good_recovery_systems": true, "boot_flags": true, // keep this comment to make old go fmt happy - "base": true, - "try_base": true, - "base_status": true, - "current_kernels": true, - "model": true, - "grade": true, + "base": true, + "try_base": true, + "base_status": true, + "current_kernels": true, + "model": true, + "grade": true, + "model_sign_key_id": true, + "try_model": true, + "try_grade": true, + "try_model_sign_key_id": true, // keep this comment to make old go fmt happy "current_kernel_command_lines": true, "current_trusted_boot_assets": true, @@ -233,9 +238,10 @@ BaseStatus: "try", CurrentKernels: []string{"k1", "k2"}, - Model: "model", - BrandID: "brand", - Grade: "secured", + Model: "model", + BrandID: "brand", + Grade: "secured", + ModelSignKeyID: "9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn", BootFlags: []string{"foo", "factory"}, @@ -261,9 +267,10 @@ BaseStatus: "try", CurrentKernels: []string{"k1", "k2"}, - Model: "model", - BrandID: "brand", - Grade: "secured", + Model: "model", + BrandID: "brand", + Grade: "secured", + ModelSignKeyID: "9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn", BootFlags: []string{"foo", "factory"}, @@ -331,6 +338,12 @@ // change the list of good recovery systems modeenv2.GoodRecoverySystems = append(modeenv2.GoodRecoverySystems, "999") c.Assert(modeenv1.DeepEqual(modeenv2), Equals, false) + // restore it + modeenv2.GoodRecoverySystems = modeenv2.GoodRecoverySystems[:len(modeenv2.GoodRecoverySystems)-1] + + // change the sign key ID + modeenv2.ModelSignKeyID = "EAD4DbLxK_kn0gzNCXOs3kd6DeMU3f-L6BEsSEuJGBqCORR0gXkdDxMbOm11mRFu" + c.Assert(modeenv1.DeepEqual(modeenv2), Equals, false) } func (s *modeenvSuite) TestReadModeWithRecoverySystem(c *C) { @@ -554,6 +567,33 @@ c.Assert(err, ErrorMatches, `internal error: must use WriteTo with modeenv not read from disk`) } +func (s *modeenvSuite) TestWriteIncompleteModelBrand(c *C) { + modeenv := &boot.Modeenv{ + Mode: "run", + Grade: "dangerous", + } + + err := modeenv.WriteTo(s.tmpdir) + c.Assert(err, ErrorMatches, `internal error: model is unset`) + + modeenv.Model = "bar" + err = modeenv.WriteTo(s.tmpdir) + c.Assert(err, ErrorMatches, `internal error: brand is unset`) + + modeenv.BrandID = "foo" + modeenv.TryGrade = "dangerous" + err = modeenv.WriteTo(s.tmpdir) + c.Assert(err, ErrorMatches, `internal error: try model is unset`) + + modeenv.TryModel = "bar" + err = modeenv.WriteTo(s.tmpdir) + c.Assert(err, ErrorMatches, `internal error: try brand is unset`) + + modeenv.TryBrandID = "foo" + err = modeenv.WriteTo(s.tmpdir) + c.Assert(err, IsNil) +} + func (s *modeenvSuite) TestWriteToNonExistingFull(c *C) { c.Assert(s.mockModeenvPath, testutil.FileAbsent) @@ -752,3 +792,81 @@ `snapd_recovery_mode=run candidate panic=-1 console=ttyS0,io,9600n8`, }) } + +func (s *modeenvSuite) TestModeenvWithModelGradeSignKeyID(c *C) { + s.makeMockModeenvFile(c, `mode=run +model=canonical/ubuntu-core-20-amd64 +grade=dangerous +model_sign_key_id=9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn +try_model=developer1/testkeys-snapd-secured-core-20-amd64 +try_grade=secured +try_model_sign_key_id=EAD4DbLxK_kn0gzNCXOs3kd6DeMU3f-L6BEsSEuJGBqCORR0gXkdDxMbOm11mRFu +`) + + modeenv, err := boot.ReadModeenv(s.tmpdir) + c.Assert(err, IsNil) + c.Check(modeenv.Model, Equals, "ubuntu-core-20-amd64") + c.Check(modeenv.BrandID, Equals, "canonical") + c.Check(modeenv.Grade, Equals, "dangerous") + c.Check(modeenv.ModelSignKeyID, Equals, "9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn") + // candidate model + c.Check(modeenv.TryModel, Equals, "testkeys-snapd-secured-core-20-amd64") + c.Check(modeenv.TryBrandID, Equals, "developer1") + c.Check(modeenv.TryGrade, Equals, "secured") + c.Check(modeenv.TryModelSignKeyID, Equals, "EAD4DbLxK_kn0gzNCXOs3kd6DeMU3f-L6BEsSEuJGBqCORR0gXkdDxMbOm11mRFu") + + // change some model data now + modeenv.Model = "testkeys-snapd-signed-core-20-amd64" + modeenv.BrandID = "developer1" + modeenv.Grade = "signed" + modeenv.ModelSignKeyID = "EAD4DbLxK_kn0gzNCXOs3kd6DeMU3f-L6BEsSEuJGBqCORR0gXkdDxMbOm11mRFu" + + modeenv.TryModel = "bar" + modeenv.TryBrandID = "foo" + modeenv.TryGrade = "dangerous" + modeenv.TryModelSignKeyID = "9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn" + + // and write it + c.Assert(modeenv.Write(), IsNil) + + c.Assert(s.mockModeenvPath, testutil.FileEquals, `mode=run +model=developer1/testkeys-snapd-signed-core-20-amd64 +grade=signed +model_sign_key_id=EAD4DbLxK_kn0gzNCXOs3kd6DeMU3f-L6BEsSEuJGBqCORR0gXkdDxMbOm11mRFu +try_model=foo/bar +try_grade=dangerous +try_model_sign_key_id=9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn +`) +} + +func (s *modeenvSuite) TestModelForSealing(c *C) { + s.makeMockModeenvFile(c, `mode=run +model=canonical/ubuntu-core-20-amd64 +grade=dangerous +model_sign_key_id=9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn +try_model=developer1/testkeys-snapd-secured-core-20-amd64 +try_grade=secured +try_model_sign_key_id=EAD4DbLxK_kn0gzNCXOs3kd6DeMU3f-L6BEsSEuJGBqCORR0gXkdDxMbOm11mRFu +`) + + modeenv, err := boot.ReadModeenv(s.tmpdir) + c.Assert(err, IsNil) + + modelForSealing := modeenv.ModelForSealing() + c.Check(modelForSealing.Model(), Equals, "ubuntu-core-20-amd64") + c.Check(modelForSealing.BrandID(), Equals, "canonical") + c.Check(modelForSealing.Grade(), Equals, asserts.ModelGrade("dangerous")) + c.Check(modelForSealing.SignKeyID(), Equals, "9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn") + c.Check(modelForSealing.Series(), Equals, "16") + c.Check(boot.ModelUniqueID(modelForSealing), Equals, + "canonical/ubuntu-core-20-amd64,dangerous,9tydnLa6MTJ-jaQTFUXEwHl1yRx7ZS4K5cyFDhYDcPzhS7uyEkDxdUjg9g08BtNn") + + tryModelForSealing := modeenv.TryModelForSealing() + c.Check(tryModelForSealing.Model(), Equals, "testkeys-snapd-secured-core-20-amd64") + c.Check(tryModelForSealing.BrandID(), Equals, "developer1") + c.Check(tryModelForSealing.Grade(), Equals, asserts.ModelGrade("secured")) + c.Check(tryModelForSealing.SignKeyID(), Equals, "EAD4DbLxK_kn0gzNCXOs3kd6DeMU3f-L6BEsSEuJGBqCORR0gXkdDxMbOm11mRFu") + c.Check(tryModelForSealing.Series(), Equals, "16") + c.Check(boot.ModelUniqueID(tryModelForSealing), Equals, + "developer1/testkeys-snapd-secured-core-20-amd64,secured,EAD4DbLxK_kn0gzNCXOs3kd6DeMU3f-L6BEsSEuJGBqCORR0gXkdDxMbOm11mRFu") +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/model.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/model.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/model.go 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/model.go 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,157 @@ +// -*- Mode: Go; indent-tabs-mode: t -*- + +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +package boot + +import ( + "fmt" + "path/filepath" + + "github.com/snapcore/snapd/asserts" + "github.com/snapcore/snapd/dirs" + "github.com/snapcore/snapd/osutil" +) + +// DeviceChange handles a change of the underlying device. Specifically it can +// be used during remodel when a new device is associated with a new model. The +// encryption keys will be resealed for both models. The device model file which +// is measured during boot will be updated. The recovery systems that belong to +// the old model will no longer be usable. +func DeviceChange(from Device, to Device) error { + if !to.HasModeenv() { + // nothing useful happens on a non-UC20 system here + return nil + } + + m, err := loadModeenv() + if err != nil { + return err + } + + newModel := to.Model() + oldModel := from.Model() + modified := false + if modelUniqueID(m.TryModelForSealing()) != modelUniqueID(newModel) { + // we either haven't been here yet, or a reboot occurred after + // try model was cleared and modeenv was rewritten + m.setTryModel(newModel) + modified = true + } + if modelUniqueID(m.ModelForSealing()) != modelUniqueID(oldModel) { + // a modeenv with new model was already written, restore + // the 'expected' original state, the model file on disk + // will match one of the models + m.setModel(oldModel) + modified = true + } + if modified { + if err := m.Write(); err != nil { + return err + } + } + + // reseal with both models now, such that we'd still be able to boot + // even if there is a reboot before the device/model file is updated, or + // before the final reseal with one model + const expectReseal = true + if err := resealKeyToModeenv(dirs.GlobalRootDir, m, expectReseal); err != nil { + // best effort clear the modeenv's try model + m.clearTryModel() + if mErr := m.Write(); mErr != nil { + return fmt.Errorf("%v (restoring modeenv failed: %v)", err, mErr) + } + return err + } + + // update the device model file in boot (we may be overwriting the same + // model file if we reached this place before a reboot has occurred) + if err := writeModelToUbuntuBoot(to.Model()); err != nil { + err = fmt.Errorf("cannot write new model file: %v", err) + // the file has not been modified, so just clear the try model + m.clearTryModel() + if mErr := m.Write(); mErr != nil { + return fmt.Errorf("%v (restoring modeenv failed: %v)", err, mErr) + } + return err + } + + // now we can update the model to the new one + m.setModel(newModel) + // and clear the try model + m.clearTryModel() + + if err := m.Write(); err != nil { + // modeenv has not been written and still contains both the old + // and a new model, but the model file has been modified, + // restore the original model file + if restoreErr := writeModelToUbuntuBoot(from.Model()); restoreErr != nil { + return fmt.Errorf("%v (restoring model failed: %v)", err, restoreErr) + } + // however writing modeenv failed, so trying to clear the model + // and write it again could be pointless, let the failure + // percolate up the stack + return err + } + + // past a successful reseal, the old recovery systems become unusable and will + // not be able to access the data anymore + if err := resealKeyToModeenv(dirs.GlobalRootDir, m, expectReseal); err != nil { + // resealing failed, but modeenv and the file have been modified + + // first restore the modeenv in case we reboot, such that if the + // post reboot code reseals, it will allow both models (in case + // even more reboots occur) + m.setModel(from.Model()) + m.setTryModel(newModel) + if mErr := m.Write(); mErr != nil { + return fmt.Errorf("%v (writing modeenv failed: %v)", err, mErr) + } + + // restore the original model file (we have resealed for both + // models previously) + if restoreErr := writeModelToUbuntuBoot(from.Model()); restoreErr != nil { + return fmt.Errorf("%v (restoring model failed: %v)", err, restoreErr) + } + + // drop the tried model + m.clearTryModel() + if mErr := m.Write(); mErr != nil { + return fmt.Errorf("%v (restoring modeenv failed: %v)", err, mErr) + } + + // resealing failed, so no point in trying it again + return err + } + return nil +} + +var writeModelToUbuntuBoot = writeModelToUbuntuBootImpl + +func writeModelToUbuntuBootImpl(model *asserts.Model) error { + modelPath := filepath.Join(InitramfsUbuntuBootDir, "device/model") + f, err := osutil.NewAtomicFile(modelPath, 0644, 0, osutil.NoChown, osutil.NoChown) + if err != nil { + return err + } + defer f.Cancel() + if err := asserts.NewEncoder(f).Encode(model); err != nil { + return err + } + return f.Commit() +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/model_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/model_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/model_test.go 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/model_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,1230 @@ +// -*- Mode: Go; indent-tabs-mode: t -*- + +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +package boot_test + +import ( + "fmt" + "os" + "path/filepath" + + . "gopkg.in/check.v1" + + "github.com/snapcore/snapd/asserts" + "github.com/snapcore/snapd/asserts/assertstest" + "github.com/snapcore/snapd/boot" + "github.com/snapcore/snapd/boot/boottest" + "github.com/snapcore/snapd/bootloader" + "github.com/snapcore/snapd/bootloader/bootloadertest" + "github.com/snapcore/snapd/dirs" + "github.com/snapcore/snapd/secboot" + "github.com/snapcore/snapd/seed" + "github.com/snapcore/snapd/snap" + "github.com/snapcore/snapd/testutil" + "github.com/snapcore/snapd/timings" +) + +type modelSuite struct { + baseBootenvSuite + + oldUc20dev boot.Device + newUc20dev boot.Device + + runKernelBf bootloader.BootFile + recoveryKernelBf bootloader.BootFile + + keyID string + + readSystemEssentialCalls int +} + +var _ = Suite(&modelSuite{}) + +var ( + brandPrivKey, _ = assertstest.GenerateKey(752) +) + +func makeEncodableModel(signingAccounts *assertstest.SigningAccounts, overrides map[string]interface{}) *asserts.Model { + headers := map[string]interface{}{ + "model": "my-model-uc20", + "display-name": "My Model", + "architecture": "amd64", + "base": "core20", + "grade": "dangerous", + "snaps": []interface{}{ + map[string]interface{}{ + "name": "pc-kernel", + "id": "pckernelidididididididididididid", + "type": "kernel", + }, + map[string]interface{}{ + "name": "pc", + "id": "pcididididididididididididididid", + "type": "gadget", + }, + }, + } + for k, v := range overrides { + headers[k] = v + } + return signingAccounts.Model("canonical", headers["model"].(string), headers) +} + +func (s *modelSuite) SetUpTest(c *C) { + s.baseBootenvSuite.SetUpTest(c) + + store := assertstest.NewStoreStack("canonical", nil) + brands := assertstest.NewSigningAccounts(store) + brands.Register("my-brand", brandPrivKey, nil) + s.keyID = brands.Signing("canonical").KeyID + + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { return nil }) + s.AddCleanup(restore) + s.oldUc20dev = boottest.MockUC20Device("", makeEncodableModel(brands, nil)) + s.newUc20dev = boottest.MockUC20Device("", makeEncodableModel(brands, map[string]interface{}{ + "model": "my-new-model-uc20", + "grade": "secured", + })) + + model := s.oldUc20dev.Model() + + modeenv := &boot.Modeenv{ + Mode: "run", + // system 1234 corresponds to the new model + CurrentRecoverySystems: []string{"20200825", "1234"}, + GoodRecoverySystems: []string{"20200825", "1234"}, + CurrentTrustedRecoveryBootAssets: boot.BootAssetsMap{ + "asset": []string{"asset-hash-1"}, + }, + CurrentTrustedBootAssets: boot.BootAssetsMap{ + "asset": []string{"asset-hash-1"}, + }, + CurrentKernels: []string{"pc-kernel_500.snap"}, + CurrentKernelCommandLines: boot.BootCommandLines{ + "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", + }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), + } + c.Assert(modeenv.WriteTo(""), IsNil) + + mockAssetsCache(c, s.rootdir, "trusted", []string{ + "asset-asset-hash-1", + }) + + mtbl := bootloadertest.Mock("trusted", s.bootdir).WithTrustedAssets() + mtbl.TrustedAssetsList = []string{"asset-1"} + mtbl.StaticCommandLine = "static cmdline" + mtbl.BootChainList = []bootloader.BootFile{ + bootloader.NewBootFile("", "asset", bootloader.RoleRunMode), + s.runKernelBf, + } + mtbl.RecoveryBootChainList = []bootloader.BootFile{ + bootloader.NewBootFile("", "asset", bootloader.RoleRecovery), + s.recoveryKernelBf, + } + bootloader.Force(mtbl) + + s.AddCleanup(func() { bootloader.Force(nil) }) + + // run kernel + s.runKernelBf = bootloader.NewBootFile("/var/lib/snapd/snap/pc-kernel_500.snap", + "kernel.efi", bootloader.RoleRunMode) + // seed (recovery) kernel + s.recoveryKernelBf = bootloader.NewBootFile("/var/lib/snapd/seed/snaps/pc-kernel_1.snap", + "kernel.efi", bootloader.RoleRecovery) + + c.Assert(os.MkdirAll(filepath.Join(boot.InitramfsUbuntuBootDir, "device"), 0755), IsNil) + + s.readSystemEssentialCalls = 0 + restore = boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { + s.readSystemEssentialCalls++ + kernelRev := 1 + systemModel := s.oldUc20dev.Model() + if label == "1234" { + // recovery system for new model + kernelRev = 999 + systemModel = s.newUc20dev.Model() + } + return systemModel, []*seed.Snap{mockKernelSeedSnap(snap.R(kernelRev)), mockGadgetSeedSnap(c, nil)}, nil + }) + s.AddCleanup(restore) +} + +func (s *modelSuite) TestWriteModelToUbuntuBoot(c *C) { + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + // overwrite the file + err = boot.WriteModelToUbuntuBoot(s.newUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + + err = os.RemoveAll(filepath.Join(boot.InitramfsUbuntuBootDir)) + c.Assert(err, IsNil) + // fails when trying to write + err = boot.WriteModelToUbuntuBoot(s.newUc20dev.Model()) + c.Assert(err, ErrorMatches, `open .*/run/mnt/ubuntu-boot/device/model\..*: no such file or directory`) +} + +func (s *modelSuite) TestDeviceChangeHappy(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + switch resealKeysCalls { + case 1: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 2: // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + case 3: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 4: // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + + switch resealKeysCalls { + case 1, 2: + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // boot/device/model is still the old file + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: dangerous\n") + case 3, 4: + // and finally just for the new model + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + c.Assert(tryForSealing, Equals, "/,,") + // boot/device/model is the new model by this time + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: secured\n") + } + return nil + }) + defer restore() + + err = boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, IsNil) + c.Assert(resealKeysCalls, Equals, 4) + + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") +} + +func (s *modelSuite) TestDeviceChangeUnhappyFirstReseal(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + switch resealKeysCalls { + case 1: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + + switch resealKeysCalls { + case 1: + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // boot/device/model is still the old file + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: dangerous\n") + } + return fmt.Errorf("fail on first try") + }) + defer restore() + + err = boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, ErrorMatches, "cannot reseal the encryption key: fail on first try") + c.Assert(resealKeysCalls, Equals, 1) + // still the old model file + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") +} + +func (s *modelSuite) TestDeviceChangeUnhappyFirstSwapModelFile(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + switch resealKeysCalls { + case 1: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 2: + // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + + switch resealKeysCalls { + case 1, 2: + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // boot/device/model is still the old file + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: dangerous\n") + } + + if resealKeysCalls == 2 { + // break writing of the model file + c.Assert(os.RemoveAll(filepath.Join(boot.InitramfsUbuntuBootDir, "device")), IsNil) + } + return nil + }) + defer restore() + + err = boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, ErrorMatches, `cannot write new model file: open .*/run/mnt/ubuntu-boot/device/model\..*: no such file or directory`) + c.Assert(resealKeysCalls, Equals, 2) + + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") +} + +func (s *modelSuite) TestDeviceChangeUnhappySecondReseal(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // which keys? + switch resealKeysCalls { + case 1, 3: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 2: + // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + // what's in params? + switch resealKeysCalls { + case 1: + c.Assert(params.ModelParams, HasLen, 2) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[1].Model.Model(), Equals, "my-new-model-uc20") + case 2: + // recovery key resealed for current model only + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + case 3, 4: + // try model has become current + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-new-model-uc20") + } + // what's in modeenv? + switch resealKeysCalls { + case 1, 2: + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // boot/device/model is still the old file + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: dangerous\n") + case 3: + // and finally just for the new model + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + c.Assert(tryForSealing, Equals, "/,,") + // boot/device/model is the new model by this time + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: secured\n") + } + + if resealKeysCalls == 3 { + return fmt.Errorf("fail on second try") + } + + return nil + }) + defer restore() + + err = boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, ErrorMatches, `cannot reseal the encryption key: fail on second try`) + c.Assert(resealKeysCalls, Equals, 3) + // old model file was restored + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") +} + +func (s *modelSuite) TestDeviceChangeRebootBeforeNewModel(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + c.Logf("reseal key call: %v", resealKeysCalls) + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // timeline & calls: + // 1 - pre reboot, run & recovery keys, try model set + // 2 - pre reboot, recovery keys, try model set, unexpected reboot is triggered + // (reboot) + // no call for run key, boot chains haven't changes since call 1 + // 3 - recovery key, try model set + // 4, 5 - post reboot, run & recovery keys, after rewriting model file, try model cleared + + // which keys? + switch resealKeysCalls { + case 1, 4: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 2, 3, 5: + // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + // what's in params? + switch resealKeysCalls { + case 1: + c.Assert(params.ModelParams, HasLen, 2) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[1].Model.Model(), Equals, "my-new-model-uc20") + case 2: + // attempted reseal of recovery key before clearing try model + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + case 3: + // recovery keys are resealed only for current system + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + case 4, 5: + // try model has become current + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-new-model-uc20") + } + // what's in modeenv? + switch resealKeysCalls { + case 1, 2, 3: + // keys are first resealed for both models, which are restored to the modeenv + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // boot/device/model is still the old file + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: dangerous\n") + case 4, 5: + // and finally just for the new model + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + c.Assert(tryForSealing, Equals, "/,,") + // boot/device/model is the new model by this time + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: secured\n") + } + + if resealKeysCalls == 2 { + panic(fmt.Sprintf("mock reboot after first complete reseal")) + } + + return nil + }) + defer restore() + + c.Assert(func() { boot.DeviceChange(s.oldUc20dev, s.newUc20dev) }, PanicMatches, + `mock reboot after first complete reseal`) + c.Assert(resealKeysCalls, Equals, 2) + // still old model in place + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + // try model is already set + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + + // let's try again + err = boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, IsNil) + c.Assert(resealKeysCalls, Equals, 5) + // got new model now + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + + m, err = boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing = boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing = boot.ModelUniqueID(m.TryModelForSealing()) + // new model is current + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") + +} + +func (s *modelSuite) TestDeviceChangeRebootAfterNewModelFileWrite(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + c.Logf("reseal key call: %v", resealKeysCalls) + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // timeline & calls: + // 1, 2 - pre reboot, run & recovery keys, try model set + // 3 - run key, after model file has been modified, try model cleared, unexpected + // reboot is triggered + // (reboot) + // no reseal - boot chains are identical to what was in calls 1 & 2 which were successful + // 4, 5 - post reboot, run & recovery keys, after rewriting model file, try model cleared + + // which keys? + switch resealKeysCalls { + case 1, 3, 4: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 2, 5: + // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + // what's in params? + switch resealKeysCalls { + case 1: + c.Assert(params.ModelParams, HasLen, 2) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[1].Model.Model(), Equals, "my-new-model-uc20") + case 2: + // recovery key resealed for current model only + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + case 3: + // attempted reseal with of run key after clearing try model + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-new-model-uc20") + case 4, 5: + // try model has become current + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-new-model-uc20") + } + // what's in modeenv? + switch resealKeysCalls { + case 1, 2: + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // boot/device/model is still the old file + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + case 3, 4, 5: + // and finally just for the new model + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + c.Assert(tryForSealing, Equals, "/,,") + // boot/device/model is the new model by this time + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "grade: secured\n") + } + + if resealKeysCalls == 3 { + panic(fmt.Sprintf("mock reboot before second complete reseal")) + } + + return nil + }) + defer restore() + + c.Assert(func() { boot.DeviceChange(s.oldUc20dev, s.newUc20dev) }, PanicMatches, + `mock reboot before second complete reseal`) + c.Assert(resealKeysCalls, Equals, 3) + // model file has already been replaced + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // as well as modeenv + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + c.Assert(tryForSealing, Equals, "/,,") + + // let's try again (post reboot) + err = boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, IsNil) + c.Assert(resealKeysCalls, Equals, 5) + // got new model now + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + + m, err = boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing = boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing = boot.ModelUniqueID(m.TryModelForSealing()) + // new model is current + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") + +} + +func (s *modelSuite) TestDeviceChangeRebootPostSameModel(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + c.Logf("reseal key call: %v", resealKeysCalls) + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // timeline & calls: + // 1, 2 - pre reboot, run & recovery keys, try model set + // 3 - run key, after model file has been modified, try model cleared + // 4 - recovery key, model file has been modified, try model cleared, unexpected + // reboot is triggered + // (reboot) + // 5, 6 - run & recovery, try model set, new model also restored + // as 'old' model, params are grouped by model + // 7 - run only (recovery boot chains have not changed since) + + // which keys? + switch resealKeysCalls { + case 1, 3, 5, 7: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 2, 4, 6: + // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + // what's in params? + switch resealKeysCalls { + case 1: + c.Assert(params.ModelParams, HasLen, 2) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[1].Model.Model(), Equals, "my-new-model-uc20") + case 2: + // recovery key resealed for current model only + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + case 3, 4: + // try model has become current + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-new-model-uc20") + case 5, 6, 7: + // + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-new-model-uc20") + } + // what's in modeenv? + switch resealKeysCalls { + case 1, 2: + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // boot/device/model is still the old file + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + case 3, 4, 7: + // and finally just for the new model + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + c.Assert(tryForSealing, Equals, "/,,") + // boot/device/model is the new model by this time + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + case 5, 6: + // new model passed as old one + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // boot/device/model is still the old file + c.Assert(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + } + + if resealKeysCalls == 4 { + panic(fmt.Sprintf("mock reboot before second complete reseal")) + } + return nil + }) + defer restore() + + // as if called by device manager in task handler + c.Assert(func() { boot.DeviceChange(s.oldUc20dev, s.newUc20dev) }, PanicMatches, + `mock reboot before second complete reseal`) + c.Assert(resealKeysCalls, Equals, 4) + // model file has already been replaced + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + + // as if called by device manager, after the model has been changed, but + // the set-model task isn't marked as done + err = boot.DeviceChange(s.newUc20dev, s.newUc20dev) + c.Assert(err, IsNil) + c.Assert(resealKeysCalls, Equals, 7) + + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-new-model-uc20\n") + + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") +} + +type unhappyMockedWriteModelToBootTestCase struct { + breakModeenvAfterFirstWrite bool + modelRestoreFail bool + expectedErr string +} + +func (s *modelSuite) testDeviceChangeUnhappyMockedWriteModelToBoot(c *C, tc unhappyMockedWriteModelToBootTestCase) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + modeenvDir := filepath.Dir(dirs.SnapModeenvFileUnder(dirs.GlobalRootDir)) + defer os.Chmod(modeenvDir, 0755) + + writeModelToBootCalls := 0 + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + switch resealKeysCalls { + case 1: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 2: + // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + + switch resealKeysCalls { + case 1: + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + // no model has been written to ubuntu-boot yet + c.Assert(writeModelToBootCalls, Equals, 0) + } + return nil + }) + defer restore() + + restore = boot.MockWriteModelToUbuntuBoot(func(model *asserts.Model) error { + writeModelToBootCalls++ + c.Assert(model, NotNil) + switch writeModelToBootCalls { + case 1: + // a call to write the new model + c.Check(model.Model(), Equals, "my-new-model-uc20") + // only 2 calls to reseal until now + c.Check(resealKeysCalls, Equals, 2) + if tc.breakModeenvAfterFirstWrite { + c.Assert(os.Chmod(modeenvDir, 0000), IsNil) + return nil + } + case 2: + // a call to restore the old model + c.Check(model.Model(), Equals, "my-model-uc20") + if !tc.breakModeenvAfterFirstWrite { + c.Errorf("unexpected additional call to writeModelToBoot (call # %d)", writeModelToBootCalls) + } + if !tc.modelRestoreFail { + return nil + } + default: + c.Errorf("unexpected additional call to writeModelToBoot (call # %d)", writeModelToBootCalls) + } + return fmt.Errorf("mocked fail in write model to boot") + }) + defer restore() + + err = boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, ErrorMatches, tc.expectedErr) + c.Assert(resealKeysCalls, Equals, 2) + if tc.breakModeenvAfterFirstWrite { + // write to boot failed on the second call + c.Assert(writeModelToBootCalls, Equals, 2) + } else { + c.Assert(writeModelToBootCalls, Equals, 1) + } + // still the old model file, all writes were intercepted + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + if !tc.breakModeenvAfterFirstWrite { + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") + } +} + +func (s *modelSuite) TestDeviceChangeUnhappyMockedWriteModelToBootBeforeModelSwap(c *C) { + s.testDeviceChangeUnhappyMockedWriteModelToBoot(c, unhappyMockedWriteModelToBootTestCase{ + expectedErr: "cannot write new model file: mocked fail in write model to boot", + }) +} + +func (s *modelSuite) TestDeviceChangeUnhappyMockedWriteModelToBootAfterModelSwapFailingRestore(c *C) { + // writing modeenv after placing new model file on disk fails, and so + // does restoring of the old model + if os.Getuid() == 0 { + // the test is manipulating file permissions, which doesn't + // affect root + c.Skip("test cannot be executed by root") + } + s.testDeviceChangeUnhappyMockedWriteModelToBoot(c, unhappyMockedWriteModelToBootTestCase{ + breakModeenvAfterFirstWrite: true, + modelRestoreFail: true, + + expectedErr: `open .*/var/lib/snapd/modeenv\..*: permission denied \(restoring model failed: mocked fail in write model to boot\)`, + }) +} + +func (s *modelSuite) TestDeviceChangeUnhappyMockedWriteModelToBootAfterModelSwapHappyRestore(c *C) { + // writing modeenv after placing new model file on disk fails, but + // restore is successful + if os.Getuid() == 0 { + // the test is manipulating file permissions, which doesn't + // affect root + c.Skip("test cannot be executed by root") + } + s.testDeviceChangeUnhappyMockedWriteModelToBoot(c, unhappyMockedWriteModelToBootTestCase{ + breakModeenvAfterFirstWrite: true, + modelRestoreFail: false, + + expectedErr: `open .*/var/lib/snapd/modeenv\..*: permission denied$`, + }) +} + +func (s *modelSuite) TestDeviceChangeUnhappyFailReseaWithSwappedModelMockedWriteToBoot(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + // set up the old model file + err := boot.WriteModelToUbuntuBoot(s.oldUc20dev.Model()) + c.Assert(err, IsNil) + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + writeModelToBootCalls := 0 + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + if resealKeysCalls == 3 { + // we are resealing the run key, the old model has been + // replaced by the new one in modeenv + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + c.Assert(tryForSealing, Equals, "/,,") + // an new model has already been written + c.Assert(writeModelToBootCalls, Equals, 1) + return fmt.Errorf("mock reseal failure") + } + + return nil + }) + defer restore() + + restore = boot.MockWriteModelToUbuntuBoot(func(model *asserts.Model) error { + writeModelToBootCalls++ + switch writeModelToBootCalls { + case 1: + c.Assert(model, NotNil) + c.Check(model.Model(), Equals, "my-new-model-uc20") + // only 2 calls to reseal until now + c.Check(resealKeysCalls, Equals, 2) + case 2: + // handling of reseal with new model restores the old one on the disk + c.Check(model.Model(), Equals, "my-model-uc20") + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + // and both models are present in the modeenv + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + c.Assert(tryForSealing, Equals, "canonical/my-new-model-uc20,secured,"+s.keyID) + + default: + c.Errorf("unexpected additional call to writeModelToBoot (call # %d)", writeModelToBootCalls) + } + return nil + }) + defer restore() + + err = boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, ErrorMatches, `cannot reseal the encryption key: mock reseal failure`) + c.Assert(resealKeysCalls, Equals, 3) + c.Assert(writeModelToBootCalls, Equals, 2) + // still the old model file, all writes were intercepted + c.Check(filepath.Join(boot.InitramfsUbuntuBootDir, "device/model"), testutil.FileContains, + "model: my-model-uc20\n") + + // finally the try model has been dropped from modeenv + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "canonical/my-model-uc20,dangerous,"+s.keyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") +} + +func (s *modelSuite) TestDeviceChangeRebootRestoreModelKeyChangeMockedWriteModel(c *C) { + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + oldKeyID := "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij" + newKeyID := "ZZZ_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij" + // model can be mocked freely as we will not encode it as we mocked a + // function that writes out the model too + s.oldUc20dev = boottest.MockUC20Device("", boottest.MakeMockUC20Model(map[string]interface{}{ + "model": "my-model-uc20", + "brand-id": "my-brand", + "grade": "dangerous", + "sign-key-sha3-384": oldKeyID, + })) + + s.newUc20dev = boottest.MockUC20Device("", boottest.MakeMockUC20Model(map[string]interface{}{ + "model": "my-model-uc20", + "brand-id": "my-brand", + "grade": "dangerous", + "sign-key-sha3-384": newKeyID, + })) + + resealKeysCalls := 0 + restore := boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealKeysCalls++ + c.Logf("reseal key call: %v", resealKeysCalls) + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // timeline & calls: + // 1, 2 - pre reboot, run & recovery keys, try model set + // 3 - run key, after model file has been modified, try model cleared + // 4 - recovery key, model file has been modified, try model cleared, + // unexpected reboot is triggered + // (reboot) + // 5 - run with old model & key (since we resealed run key in + // call 3, and recovery has not changed), old model restored in modeenv + // 6 - run with new model and key, old current has been dropped + // 7 - recovery with new model only + + // which keys? + switch resealKeysCalls { + case 1, 3, 5, 6: + // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + case 2, 4, 7: + // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + // what's in params? + switch resealKeysCalls { + case 1, 5: + c.Assert(params.ModelParams, HasLen, 2) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[0].Model.SignKeyID(), Equals, oldKeyID) + c.Assert(params.ModelParams[1].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[1].Model.SignKeyID(), Equals, newKeyID) + case 2: + // recovery key resealed for current model only + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[0].Model.SignKeyID(), Equals, oldKeyID) + case 3, 4, 6, 7: + // try model has become current + c.Assert(params.ModelParams, HasLen, 1) + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[0].Model.SignKeyID(), Equals, newKeyID) + } + // what's in modeenv? + switch resealKeysCalls { + case 1, 2, 5: + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "my-brand/my-model-uc20,dangerous,"+oldKeyID) + c.Assert(tryForSealing, Equals, "my-brand/my-model-uc20,dangerous,"+newKeyID) + case 3, 4, 6, 7: + // and finally just for the new model + c.Assert(currForSealing, Equals, "my-brand/my-model-uc20,dangerous,"+newKeyID) + c.Assert(tryForSealing, Equals, "/,,") + } + + if resealKeysCalls == 4 { + panic(fmt.Sprintf("mock reboot before second complete reseal")) + } + return nil + }) + defer restore() + + writeModelToBootCalls := 0 + restore = boot.MockWriteModelToUbuntuBoot(func(model *asserts.Model) error { + writeModelToBootCalls++ + c.Logf("write model to boot call: %v", writeModelToBootCalls) + switch writeModelToBootCalls { + case 1: + c.Assert(model, NotNil) + c.Check(model.Model(), Equals, "my-model-uc20") + // only 2 calls to reseal until now + c.Check(resealKeysCalls, Equals, 2) + case 2: + // handling of reseal with new model restores the old one on the disk + c.Check(model.Model(), Equals, "my-model-uc20") + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + // and both models are present in the modeenv + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + // keys are first resealed for both models + c.Assert(currForSealing, Equals, "my-brand/my-model-uc20,dangerous,"+oldKeyID) + c.Assert(tryForSealing, Equals, "my-brand/my-model-uc20,dangerous,"+newKeyID) + + default: + c.Errorf("unexpected additional call to writeModelToBoot (call # %d)", writeModelToBootCalls) + } + return nil + }) + defer restore() + + // as if called by device manager in task handler + c.Assert(func() { boot.DeviceChange(s.oldUc20dev, s.newUc20dev) }, PanicMatches, + `mock reboot before second complete reseal`) + c.Assert(resealKeysCalls, Equals, 4) + c.Assert(writeModelToBootCalls, Equals, 1) + + err := boot.DeviceChange(s.oldUc20dev, s.newUc20dev) + c.Assert(err, IsNil) + c.Assert(resealKeysCalls, Equals, 7) + c.Assert(writeModelToBootCalls, Equals, 2) + + m, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + currForSealing := boot.ModelUniqueID(m.ModelForSealing()) + tryForSealing := boot.ModelUniqueID(m.TryModelForSealing()) + c.Assert(currForSealing, Equals, "my-brand/my-model-uc20,dangerous,"+newKeyID) + // try model has been cleared + c.Assert(tryForSealing, Equals, "/,,") +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/seal.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/seal.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/seal.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/seal.go 2023-03-23 08:10:58.000000000 +0000 @@ -71,6 +71,27 @@ sealingMethodFDESetupHook = sealingMethod("fde-setup-hook") ) +// MockSecbootResealKeys is only useful in testing. Note that this is a very low +// level call and may need significant environment setup. +func MockSecbootResealKeys(f func(params *secboot.ResealKeysParams) error) (restore func()) { + osutil.MustBeTestBinary("secbootResealKeys only can be mocked in tests") + old := secbootResealKeys + secbootResealKeys = f + return func() { + secbootResealKeys = old + } +} + +// MockResealKeyToModeenv is only useful in testing. +func MockResealKeyToModeenv(f func(rootdir string, modeenv *Modeenv, expectReseal bool) error) (restore func()) { + osutil.MustBeTestBinary("resealKeyToModeenv only can be mocked in tests") + old := resealKeyToModeenv + resealKeyToModeenv = f + return func() { + resealKeyToModeenv = old + } +} + func bootChainsFileUnder(rootdir string) string { return filepath.Join(dirs.SnapFDEDirUnder(rootdir), "boot-chains") } @@ -101,10 +122,10 @@ return fmt.Errorf("cannot check for fde-setup hook %v", err) } if hasHook { - return sealKeyToModeenvUsingFDESetupHook(key, saveKey, model, modeenv) + return sealKeyToModeenvUsingFDESetupHook(key, saveKey, modeenv) } - return sealKeyToModeenvUsingSecboot(key, saveKey, model, modeenv) + return sealKeyToModeenvUsingSecboot(key, saveKey, modeenv) } func runKeySealRequests(key secboot.EncryptionKey) []secboot.SealKeyRequest { @@ -132,7 +153,7 @@ } } -func sealKeyToModeenvUsingFDESetupHook(key, saveKey secboot.EncryptionKey, model *asserts.Model, modeenv *Modeenv) error { +func sealKeyToModeenvUsingFDESetupHook(key, saveKey secboot.EncryptionKey, modeenv *Modeenv) error { // XXX: Move the auxKey creation to a more generic place, see // PR#10123 for a possible way of doing this. However given // that the equivalent key for the TPM case is also created in @@ -144,7 +165,7 @@ return fmt.Errorf("cannot create aux key: %v", err) } params := secboot.SealKeysWithFDESetupHookParams{ - Model: model, + Model: modeenv.ModelForSealing(), AuxKey: auxKey, AuxKeyFile: filepath.Join(InstallHostFDESaveDir, "aux-key"), } @@ -160,7 +181,7 @@ return nil } -func sealKeyToModeenvUsingSecboot(key, saveKey secboot.EncryptionKey, model *asserts.Model, modeenv *Modeenv) error { +func sealKeyToModeenvUsingSecboot(key, saveKey secboot.EncryptionKey, modeenv *Modeenv) error { // build the recovery mode boot chain rbl, err := bootloader.Find(InitramfsUbuntuSeedDir, &bootloader.Options{ Role: bootloader.RoleRecovery, @@ -174,7 +195,8 @@ return fmt.Errorf("internal error: cannot seal keys without a trusted assets bootloader") } - recoveryBootChains, err := recoveryBootChainsForSystems([]string{modeenv.RecoverySystem}, tbl, model, modeenv) + includeTryModel := false + recoveryBootChains, err := recoveryBootChainsForSystems([]string{modeenv.RecoverySystem}, tbl, modeenv, includeTryModel) if err != nil { return fmt.Errorf("cannot compose recovery boot chains: %v", err) } @@ -190,7 +212,7 @@ // kernel command lines are filled during install cmdlines := modeenv.CurrentKernelCommandLines - runModeBootChains, err := runModeBootChains(rbl, bl, model, modeenv, cmdlines) + runModeBootChains, err := runModeBootChains(rbl, bl, modeenv, cmdlines) if err != nil { return fmt.Errorf("cannot compose run mode boot chains: %v", err) } @@ -309,9 +331,11 @@ return sealingMethod(content), err } +var resealKeyToModeenv = resealKeyToModeenvImpl + // resealKeyToModeenv reseals the existing encryption key to the // parameters specified in modeenv. -func resealKeyToModeenv(rootdir string, model *asserts.Model, modeenv *Modeenv, expectReseal bool) error { +func resealKeyToModeenvImpl(rootdir string, modeenv *Modeenv, expectReseal bool) error { method, err := sealedKeysMethod(rootdir) if err == errNoSealedKeys { // nothing to do @@ -322,9 +346,9 @@ } switch method { case sealingMethodFDESetupHook: - return resealKeyToModeenvUsingFDESetupHook(rootdir, model, modeenv, expectReseal) + return resealKeyToModeenvUsingFDESetupHook(rootdir, modeenv, expectReseal) case sealingMethodTPM, sealingMethodLegacyTPM: - return resealKeyToModeenvSecboot(rootdir, model, modeenv, expectReseal) + return resealKeyToModeenvSecboot(rootdir, modeenv, expectReseal) default: return fmt.Errorf("unknown key sealing method: %q", method) } @@ -332,7 +356,7 @@ var resealKeyToModeenvUsingFDESetupHook = resealKeyToModeenvUsingFDESetupHookImpl -func resealKeyToModeenvUsingFDESetupHookImpl(rootdir string, model *asserts.Model, modeenv *Modeenv, expectReseal bool) error { +func resealKeyToModeenvUsingFDESetupHookImpl(rootdir string, modeenv *Modeenv, expectReseal bool) error { // TODO: we need to implement reseal at least in terms of // rebinding the keys to models on remodeling @@ -354,7 +378,7 @@ } // TODO:UC20: allow more than one model to accommodate the remodel scenario -func resealKeyToModeenvSecboot(rootdir string, model *asserts.Model, modeenv *Modeenv, expectReseal bool) error { +func resealKeyToModeenvSecboot(rootdir string, modeenv *Modeenv, expectReseal bool) error { // build the recovery mode boot chain rbl, err := bootloader.Find(InitramfsUbuntuSeedDir, &bootloader.Options{ Role: bootloader.RoleRecovery, @@ -369,8 +393,12 @@ } // the recovery boot chains for the run key are generated for all - // recovery systems, including those that are being tried - recoveryBootChainsForRunKey, err := recoveryBootChainsForSystems(modeenv.CurrentRecoverySystems, tbl, model, modeenv) + // recovery systems, including those that are being tried; since this is + // a run key, the boot chains are generated for both models to + // accommodate the dynamics of a remodel + includeTryModel := true + recoveryBootChainsForRunKey, err := recoveryBootChainsForSystems(modeenv.CurrentRecoverySystems, tbl, + modeenv, includeTryModel) if err != nil { return fmt.Errorf("cannot compose recovery boot chains for run key: %v", err) } @@ -385,7 +413,10 @@ logger.Noticef("no good recovery systems for reseal, fallback to known current system %v", testedRecoverySystems[0]) } - recoveryBootChains, err := recoveryBootChainsForSystems(testedRecoverySystems, tbl, model, modeenv) + // use the current model as the recovery keys are not expected to be + // used during a remodel + includeTryModel = false + recoveryBootChains, err := recoveryBootChainsForSystems(testedRecoverySystems, tbl, modeenv, includeTryModel) if err != nil { return fmt.Errorf("cannot compose recovery boot chains: %v", err) } @@ -398,11 +429,11 @@ if err != nil { return fmt.Errorf("cannot find the bootloader: %v", err) } - cmdlines, err := kernelCommandLinesForResealWithFallback(model, modeenv) + cmdlines, err := kernelCommandLinesForResealWithFallback(modeenv) if err != nil { return err } - runModeBootChains, err := runModeBootChains(rbl, bl, model, modeenv, cmdlines) + runModeBootChains, err := runModeBootChains(rbl, bl, modeenv, cmdlines) if err != nil { return fmt.Errorf("cannot compose run mode boot chains: %v", err) } @@ -517,97 +548,135 @@ // TODO:UC20: this needs to take more than one model to accommodate the remodel // scenario -func recoveryBootChainsForSystems(systems []string, trbl bootloader.TrustedAssetsBootloader, model *asserts.Model, modeenv *Modeenv) (chains []bootChain, err error) { - for _, system := range systems { - // get kernel and gadget information from seed - perf := timings.New(nil) - _, snaps, err := seedReadSystemEssential(dirs.SnapSeedDir, system, []snap.Type{snap.TypeKernel, snap.TypeGadget}, perf) - if err != nil { - return nil, fmt.Errorf("cannot read system %q seed: %v", system, err) - } - if len(snaps) != 2 { - return nil, fmt.Errorf("cannot obtain recovery system snaps") - } - seedKernel, seedGadget := snaps[0], snaps[1] - if snaps[0].EssentialType == snap.TypeGadget { - seedKernel, seedGadget = seedGadget, seedKernel - } +func recoveryBootChainsForSystems(systems []string, trbl bootloader.TrustedAssetsBootloader, modeenv *Modeenv, includeTryModel bool) (chains []bootChain, err error) { - // get the command line - cmdline, err := ComposeRecoveryCommandLine(model, system, seedGadget.Path) - if err != nil { - return nil, fmt.Errorf("cannot obtain recovery kernel command line: %v", err) - } + chainsForModel := func(model secboot.ModelForSealing) error { + modelID := modelUniqueID(model) + for _, system := range systems { + // get kernel and gadget information from seed + perf := timings.New(nil) + seedSystemModel, snaps, err := seedReadSystemEssential(dirs.SnapSeedDir, system, []snap.Type{snap.TypeKernel, snap.TypeGadget}, perf) + if err != nil { + return fmt.Errorf("cannot read system %q seed: %v", system, err) + } + if len(snaps) != 2 { + return fmt.Errorf("cannot obtain recovery system snaps") + } + seedModelID := modelUniqueID(seedSystemModel) + // TODO: the generated unique ID contains the model's + // sign key ID, consider relaxing this to ignore the key + // ID when matching models, OTOH we would need to + // properly take into account key expiration and + // revocation + if seedModelID != modelID { + // could be an incompatible recovery system that + // is still currently tracked in modeenv + continue + } + seedKernel, seedGadget := snaps[0], snaps[1] + if snaps[0].EssentialType == snap.TypeGadget { + seedKernel, seedGadget = seedGadget, seedKernel + } - var kernelRev string - if seedKernel.SideInfo.Revision.Store() { - kernelRev = seedKernel.SideInfo.Revision.String() - } + // get the command line + cmdline, err := composeCommandLine(currentEdition, ModeRecover, system, seedGadget.Path) + if err != nil { + return fmt.Errorf("cannot obtain recovery kernel command line: %v", err) + } - recoveryBootChain, err := trbl.RecoveryBootChain(seedKernel.Path) - if err != nil { - return nil, err + var kernelRev string + if seedKernel.SideInfo.Revision.Store() { + kernelRev = seedKernel.SideInfo.Revision.String() + } + + recoveryBootChain, err := trbl.RecoveryBootChain(seedKernel.Path) + if err != nil { + return err + } + + // get asset chains + assetChain, kbf, err := buildBootAssets(recoveryBootChain, modeenv) + if err != nil { + return err + } + + chains = append(chains, bootChain{ + BrandID: model.BrandID(), + Model: model.Model(), + Grade: model.Grade(), + ModelSignKeyID: model.SignKeyID(), + AssetChain: assetChain, + Kernel: seedKernel.SnapName(), + KernelRevision: kernelRev, + KernelCmdlines: []string{cmdline}, + kernelBootFile: kbf, + }) } + return nil + } - // get asset chains - assetChain, kbf, err := buildBootAssets(recoveryBootChain, modeenv) - if err != nil { + if err := chainsForModel(modeenv.ModelForSealing()); err != nil { + return nil, err + } + + if modeenv.TryModel != "" && includeTryModel { + if err := chainsForModel(modeenv.TryModelForSealing()); err != nil { return nil, err } - - chains = append(chains, bootChain{ - BrandID: model.BrandID(), - Model: model.Model(), - Grade: model.Grade(), - ModelSignKeyID: model.SignKeyID(), - AssetChain: assetChain, - Kernel: seedKernel.SnapName(), - KernelRevision: kernelRev, - KernelCmdlines: []string{cmdline}, - model: model, - kernelBootFile: kbf, - }) } + return chains, nil } -func runModeBootChains(rbl, bl bootloader.Bootloader, model *asserts.Model, modeenv *Modeenv, cmdlines []string) ([]bootChain, error) { +func runModeBootChains(rbl, bl bootloader.Bootloader, modeenv *Modeenv, cmdlines []string) ([]bootChain, error) { tbl, ok := rbl.(bootloader.TrustedAssetsBootloader) if !ok { return nil, fmt.Errorf("recovery bootloader doesn't support trusted assets") } chains := make([]bootChain, 0, len(modeenv.CurrentKernels)) - for _, k := range modeenv.CurrentKernels { - info, err := snap.ParsePlaceInfoFromSnapFileName(k) - if err != nil { - return nil, err - } - runModeBootChain, err := tbl.BootChain(bl, info.MountFile()) - if err != nil { - return nil, err + + chainsForModel := func(model secboot.ModelForSealing) error { + for _, k := range modeenv.CurrentKernels { + info, err := snap.ParsePlaceInfoFromSnapFileName(k) + if err != nil { + return err + } + runModeBootChain, err := tbl.BootChain(bl, info.MountFile()) + if err != nil { + return err + } + + // get asset chains + assetChain, kbf, err := buildBootAssets(runModeBootChain, modeenv) + if err != nil { + return err + } + var kernelRev string + if info.SnapRevision().Store() { + kernelRev = info.SnapRevision().String() + } + chains = append(chains, bootChain{ + BrandID: model.BrandID(), + Model: model.Model(), + Grade: model.Grade(), + ModelSignKeyID: model.SignKeyID(), + AssetChain: assetChain, + Kernel: info.SnapName(), + KernelRevision: kernelRev, + KernelCmdlines: cmdlines, + kernelBootFile: kbf, + }) } + return nil + } + if err := chainsForModel(modeenv.ModelForSealing()); err != nil { + return nil, err + } - // get asset chains - assetChain, kbf, err := buildBootAssets(runModeBootChain, modeenv) - if err != nil { + if modeenv.TryModel != "" { + if err := chainsForModel(modeenv.TryModelForSealing()); err != nil { return nil, err } - var kernelRev string - if info.SnapRevision().Store() { - kernelRev = info.SnapRevision().String() - } - chains = append(chains, bootChain{ - BrandID: model.BrandID(), - Model: model.Model(), - Grade: model.Grade(), - ModelSignKeyID: model.SignKeyID(), - AssetChain: assetChain, - Kernel: info.SnapName(), - KernelRevision: kernelRev, - KernelCmdlines: cmdlines, - model: model, - kernelBootFile: kbf, - }) } return chains, nil } @@ -647,10 +716,13 @@ } func sealKeyModelParams(pbc predictableBootChains, roleToBlName map[bootloader.Role]string) ([]*secboot.SealKeyModelParams, error) { - modelToParams := map[*asserts.Model]*secboot.SealKeyModelParams{} + // seal parameters keyed by unique model ID + modelToParams := map[string]*secboot.SealKeyModelParams{} modelParams := make([]*secboot.SealKeyModelParams, 0, len(pbc)) for _, bc := range pbc { + modelForSealing := bc.modelForSealing() + modelID := modelUniqueID(modelForSealing) loadChains, err := bootAssetsToLoadChains(bc.AssetChain, bc.kernelBootFile, roleToBlName) if err != nil { return nil, fmt.Errorf("cannot build load chains with current boot assets: %s", err) @@ -658,17 +730,17 @@ // group parameters by model, reuse an existing SealKeyModelParams // if the model is the same. - if params, ok := modelToParams[bc.model]; ok { + if params, ok := modelToParams[modelID]; ok { params.KernelCmdlines = strutil.SortedListsUniqueMerge(params.KernelCmdlines, bc.KernelCmdlines) params.EFILoadChains = append(params.EFILoadChains, loadChains...) } else { param := &secboot.SealKeyModelParams{ - Model: bc.model, + Model: modelForSealing, KernelCmdlines: bc.KernelCmdlines, EFILoadChains: loadChains, } modelParams = append(modelParams, param) - modelToParams[bc.model] = param + modelToParams[modelID] = param } } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/seal_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/seal_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/seal_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/seal_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -59,11 +59,11 @@ s.AddCleanup(func() { dirs.SetRootDir("/") }) } -func mockKernelSeedSnap(c *C, rev snap.Revision) *seed.Snap { - return mockNamedKernelSeedSnap(c, rev, "pc-kernel") +func mockKernelSeedSnap(rev snap.Revision) *seed.Snap { + return mockNamedKernelSeedSnap(rev, "pc-kernel") } -func mockNamedKernelSeedSnap(c *C, rev snap.Revision, name string) *seed.Snap { +func mockNamedKernelSeedSnap(rev snap.Revision, name string) *seed.Snap { revAsString := rev.String() if rev.Unset() { revAsString = "unset" @@ -108,6 +108,8 @@ err = createMockGrubCfg(filepath.Join(rootdir, "run/mnt/ubuntu-boot")) c.Assert(err, IsNil) + model := boottest.MakeMockUC20Model() + modeenv := &boot.Modeenv{ RecoverySystem: "20200825", CurrentTrustedRecoveryBootAssets: boot.BootAssetsMap{ @@ -124,6 +126,10 @@ CurrentKernelCommandLines: boot.BootCommandLines{ "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", }, + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } // mock asset cache @@ -141,13 +147,11 @@ myKey2[i] = byte(128 + i) } - model := boottest.MakeMockUC20Model() - // set a mock recovery kernel readSystemEssentialCalls := 0 restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { readSystemEssentialCalls++ - return model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + return model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -213,7 +217,7 @@ default: c.Errorf("unexpected additional call to secboot.SealKeys (call # %d)", sealKeysCalls) } - c.Assert(params.ModelParams[0].Model.DisplayName(), Equals, "My Model") + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") return tc.sealErr }) @@ -365,6 +369,8 @@ err = createMockGrubCfg(filepath.Join(rootdir, "run/mnt/ubuntu-boot")) c.Assert(err, IsNil) + model := boottest.MakeMockUC20Model() + modeenv := &boot.Modeenv{ CurrentRecoverySystems: []string{"20200825"}, CurrentTrustedRecoveryBootAssets: boot.BootAssetsMap{ @@ -381,6 +387,10 @@ CurrentKernelCommandLines: boot.BootCommandLines{ "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", }, + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } if tc.reuseRunPbc { @@ -401,13 +411,11 @@ "grubx64.efi-run-grub-hash-2", }) - model := boottest.MakeMockUC20Model() - // set a mock recovery kernel readSystemEssentialCalls := 0 restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { readSystemEssentialCalls++ - return model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + return model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -420,7 +428,7 @@ c.Assert(params.ModelParams, HasLen, 1) // shared parameters - c.Assert(params.ModelParams[0].Model.DisplayName(), Equals, "My Model") + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") // recovery parameters shim := bootloader.NewBootFile("", filepath.Join(rootdir, "var/lib/snapd/boot-assets/grub/bootx64.efi-shim-hash-1"), bootloader.RoleRecovery) @@ -537,7 +545,7 @@ // the behavior with unasserted kernel is tested in // boot_test.go specific tests const expectReseal = false - err = boot.ResealKeyToModeenv(rootdir, model, modeenv, expectReseal) + err = boot.ResealKeyToModeenv(rootdir, modeenv, expectReseal) if !tc.sealedKeys || (tc.reuseRunPbc && tc.reuseRecoveryPbc) { // did nothing c.Assert(err, IsNil) @@ -680,6 +688,8 @@ err = createMockGrubCfg(filepath.Join(rootdir, "run/mnt/ubuntu-boot")) c.Assert(err, IsNil) + model := boottest.MakeMockUC20Model() + modeenv := &boot.Modeenv{ // where 1234 is being tried CurrentRecoverySystems: []string{"20200825", "1234"}, @@ -699,6 +709,10 @@ CurrentKernelCommandLines: boot.BootCommandLines{ "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", }, + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } // mock asset cache @@ -708,8 +722,6 @@ "grubx64.efi-run-grub-hash", }) - model := boottest.MakeMockUC20Model() - // set a mock recovery kernel readSystemEssentialCalls := 0 restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { @@ -718,7 +730,7 @@ if label == "1234" { kernelRev = 999 } - return model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(kernelRev)), mockGadgetSeedSnap(c, nil)}, nil + return model, []*seed.Snap{mockKernelSeedSnap(snap.R(kernelRev)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -731,7 +743,7 @@ c.Assert(params.ModelParams, HasLen, 1) // shared parameters - c.Assert(params.ModelParams[0].Model.DisplayName(), Equals, "My Model") + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") c.Logf("got:") for _, ch := range params.ModelParams[0].EFILoadChains { printChain(c, ch, "-") @@ -807,7 +819,7 @@ // the behavior with unasserted kernel is tested in // boot_test.go specific tests const expectReseal = false - err = boot.ResealKeyToModeenv(rootdir, model, modeenv, expectReseal) + err = boot.ResealKeyToModeenv(rootdir, modeenv, expectReseal) c.Assert(err, IsNil) c.Assert(resealKeysCalls, Equals, 2) @@ -949,6 +961,11 @@ // as if it is unset yet CurrentKernelCommandLines: nil, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } err = boot.WriteBootChains(nil, filepath.Join(dirs.SnapFDEDir, "boot-chains"), 9) @@ -982,7 +999,7 @@ readSystemEssentialCalls := 0 restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { readSystemEssentialCalls++ - return model, []*seed.Snap{mockKernelSeedSnap(c, snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil + return model, []*seed.Snap{mockKernelSeedSnap(snap.R(1)), mockGadgetSeedSnap(c, nil)}, nil }) defer restore() @@ -1010,7 +1027,7 @@ defer restore() const expectReseal = false - err = boot.ResealKeyToModeenv(rootdir, model, modeenv, expectReseal) + err = boot.ResealKeyToModeenv(rootdir, modeenv, expectReseal) c.Assert(err, IsNil) c.Assert(resealKeysCalls, Equals, 2) @@ -1060,13 +1077,14 @@ func (s *sealSuite) TestRecoveryBootChainsForSystems(c *C) { for _, tc := range []struct { - desc string - assetsMap boot.BootAssetsMap - recoverySystems []string - undefinedKernel bool - gadgetFilesForSystem map[string][][]string - expectedAssets []boot.BootAsset - expectedKernelRevs []int + desc string + assetsMap boot.BootAssetsMap + recoverySystems []string + undefinedKernel bool + gadgetFilesForSystem map[string][][]string + expectedAssets []boot.BootAsset + expectedKernelRevs []int + expectedBootChainsCount int // in the order of boot chains expectedCmdlines [][]string err string @@ -1147,6 +1165,24 @@ }, }, { + desc: "three systems, one with different model", + recoverySystems: []string{"20200825", "20200831", "off-model"}, + assetsMap: boot.BootAssetsMap{ + "grubx64.efi": []string{"grub-hash-1", "grub-hash-2"}, + "bootx64.efi": []string{"shim-hash-1"}, + }, + expectedAssets: []boot.BootAsset{ + {Role: bootloader.RoleRecovery, Name: "bootx64.efi", Hashes: []string{"shim-hash-1"}}, + {Role: bootloader.RoleRecovery, Name: "grubx64.efi", Hashes: []string{"grub-hash-1", "grub-hash-2"}}, + }, + expectedKernelRevs: []int{1, 3}, + expectedCmdlines: [][]string{ + {"snapd_recovery_mode=recover snapd_recovery_system=20200825 console=ttyS0 console=tty1 panic=-1"}, + {"snapd_recovery_mode=recover snapd_recovery_system=20200831 console=ttyS0 console=tty1 panic=-1"}, + }, + expectedBootChainsCount: 2, + }, + { desc: "invalid recovery system label", recoverySystems: []string{"0"}, err: `cannot read system "0" seed: invalid system seed`, @@ -1157,16 +1193,25 @@ dirs.SetRootDir(rootdir) defer dirs.SetRootDir("") + model := boottest.MakeMockUC20Model() + // set recovery kernel restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { - if label != "20200825" && label != "20200831" { - return nil, nil, fmt.Errorf("invalid system seed") - } + systemModel := model kernelRev := 1 - if label == "20200831" { + switch label { + case "20200825": + // nothing special + case "20200831": kernelRev = 3 + case "off-model": + systemModel = boottest.MakeMockUC20Model(map[string]interface{}{ + "model": "model-mismatch-uc20", + }) + default: + return nil, nil, fmt.Errorf("invalid system seed") } - return nil, []*seed.Snap{mockKernelSeedSnap(c, snap.R(kernelRev)), mockGadgetSeedSnap(c, tc.gadgetFilesForSystem[label])}, nil + return systemModel, []*seed.Snap{mockKernelSeedSnap(snap.R(kernelRev)), mockGadgetSeedSnap(c, tc.gadgetFilesForSystem[label])}, nil }) defer restore() @@ -1179,16 +1224,25 @@ tbl, ok := bl.(bootloader.TrustedAssetsBootloader) c.Assert(ok, Equals, true) - model := boottest.MakeMockUC20Model() - modeenv := &boot.Modeenv{ CurrentTrustedRecoveryBootAssets: tc.assetsMap, + + BrandID: model.BrandID(), + Model: model.Model(), + ModelSignKeyID: model.SignKeyID(), + Grade: string(model.Grade()), } - bc, err := boot.RecoveryBootChainsForSystems(tc.recoverySystems, tbl, model, modeenv) + includeTryModel := false + bc, err := boot.RecoveryBootChainsForSystems(tc.recoverySystems, tbl, modeenv, includeTryModel) if tc.err == "" { c.Assert(err, IsNil) - c.Assert(bc, HasLen, len(tc.recoverySystems)) + if tc.expectedBootChainsCount == 0 { + // usually there is a boot chain for each recovery system + c.Assert(bc, HasLen, len(tc.recoverySystems)) + } else { + c.Assert(bc, HasLen, tc.expectedBootChainsCount) + } c.Assert(tc.expectedCmdlines, HasLen, len(bc), Commentf("broken test, expected command lines must be of the same length as recovery systems and recovery boot chains")) for i, chain := range bc { c.Assert(chain.AssetChain, DeepEquals, tc.expectedAssets) @@ -1243,36 +1297,40 @@ // old recovery oldrc := boot.BootChain{ - BrandID: oldmodel.BrandID(), - Model: oldmodel.Model(), + BrandID: oldmodel.BrandID(), + Model: oldmodel.Model(), + Grade: oldmodel.Grade(), + ModelSignKeyID: oldmodel.SignKeyID(), AssetChain: []boot.BootAsset{ {Name: "shim", Role: bootloader.RoleRecovery, Hashes: []string{"shim-hash"}}, {Name: "loader", Role: bootloader.RoleRecovery, Hashes: []string{"loader-hash1"}}, }, KernelCmdlines: []string{"panic=1", "oldrc"}, } - oldrc.SetModelAssertion(oldmodel) oldkbf := bootloader.BootFile{Snap: "pc-kernel_1.snap"} oldrc.SetKernelBootFile(oldkbf) // recovery rc1 := boot.BootChain{ - BrandID: model.BrandID(), - Model: model.Model(), + BrandID: model.BrandID(), + Model: model.Model(), + Grade: model.Grade(), + ModelSignKeyID: model.SignKeyID(), AssetChain: []boot.BootAsset{ {Name: "shim", Role: bootloader.RoleRecovery, Hashes: []string{"shim-hash"}}, {Name: "loader", Role: bootloader.RoleRecovery, Hashes: []string{"loader-hash1"}}, }, KernelCmdlines: []string{"panic=1", "rc1"}, } - rc1.SetModelAssertion(model) rc1kbf := bootloader.BootFile{Snap: "pc-kernel_10.snap"} rc1.SetKernelBootFile(rc1kbf) // run system runc1 := boot.BootChain{ - BrandID: model.BrandID(), - Model: model.Model(), + BrandID: model.BrandID(), + Model: model.Model(), + Grade: model.Grade(), + ModelSignKeyID: model.SignKeyID(), AssetChain: []boot.BootAsset{ {Name: "shim", Role: bootloader.RoleRecovery, Hashes: []string{"shim-hash"}}, {Name: "loader", Role: bootloader.RoleRecovery, Hashes: []string{"loader-hash1"}}, @@ -1280,7 +1338,6 @@ }, KernelCmdlines: []string{"panic=1", "runc1"}, } - runc1.SetModelAssertion(model) runc1kbf := bootloader.BootFile{Snap: "pc-kernel_50.snap"} runc1.SetKernelBootFile(runc1kbf) @@ -1293,7 +1350,7 @@ params, err := boot.SealKeyModelParams(pbc, roleToBlName) c.Assert(err, IsNil) c.Check(params, HasLen, 2) - c.Check(params[0].Model, Equals, model) + c.Check(params[0].Model.Model(), Equals, model.Model()) // NB: merging of lists makes panic=1 appear once c.Check(params[0].KernelCmdlines, DeepEquals, []string{"panic=1", "rc1", "runc1"}) @@ -1307,7 +1364,7 @@ secboot.NewLoadChain(runc1kbf)))), }) - c.Check(params[1].Model, Equals, oldmodel) + c.Check(params[1].Model.Model(), Equals, oldmodel.Model()) c.Check(params[1].KernelCmdlines, DeepEquals, []string{"oldrc", "panic=1"}) c.Check(params[1].EFILoadChains, DeepEquals, []*secboot.LoadChain{ secboot.NewLoadChain(shim, @@ -1431,7 +1488,7 @@ defer restore() keyToSave := make(map[string][]byte) restore = boot.MockSecbootSealKeysWithFDESetupHook(func(runHook fde.RunSetupHookFunc, skrs []secboot.SealKeyRequest, params *secboot.SealKeysWithFDESetupHookParams) error { - c.Check(params.Model, DeepEquals, model) + c.Check(params.Model.Model(), Equals, model.Model()) c.Check(params.AuxKeyFile, Equals, filepath.Join(boot.InstallHostFDESaveDir, "aux-key")) for _, skr := range skrs { out, err := runHook(&fde.SetupRequest{ @@ -1447,6 +1504,10 @@ modeenv := &boot.Modeenv{ RecoverySystem: "20200825", + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } key := secboot.EncryptionKey{1, 2, 3, 4} saveKey := secboot.EncryptionKey{5, 6, 7, 8} @@ -1508,7 +1569,7 @@ defer dirs.SetRootDir("") resealKeyToModeenvUsingFDESetupHookCalled := 0 - restore := boot.MockResealKeyToModeenvUsingFDESetupHook(func(string, *asserts.Model, *boot.Modeenv, bool) error { + restore := boot.MockResealKeyToModeenvUsingFDESetupHook(func(string, *boot.Modeenv, bool) error { resealKeyToModeenvUsingFDESetupHookCalled++ return nil }) @@ -1528,13 +1589,16 @@ err = ioutil.WriteFile(marker, []byte("fde-setup-hook"), 0644) c.Assert(err, IsNil) + model := boottest.MakeMockUC20Model() modeenv := &boot.Modeenv{ RecoverySystem: "20200825", + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } - - model := boottest.MakeMockUC20Model() expectReseal := false - err = boot.ResealKeyToModeenv(rootdir, model, modeenv, expectReseal) + err = boot.ResealKeyToModeenv(rootdir, modeenv, expectReseal) c.Assert(err, IsNil) c.Check(resealKeyToModeenvUsingFDESetupHookCalled, Equals, 1) } @@ -1545,7 +1609,7 @@ defer dirs.SetRootDir("") resealKeyToModeenvUsingFDESetupHookCalled := 0 - restore := boot.MockResealKeyToModeenvUsingFDESetupHook(func(string, *asserts.Model, *boot.Modeenv, bool) error { + restore := boot.MockResealKeyToModeenvUsingFDESetupHook(func(string, *boot.Modeenv, bool) error { resealKeyToModeenvUsingFDESetupHookCalled++ return fmt.Errorf("fde setup hook failed") }) @@ -1557,13 +1621,320 @@ err = ioutil.WriteFile(marker, []byte("fde-setup-hook"), 0644) c.Assert(err, IsNil) + model := boottest.MakeMockUC20Model() modeenv := &boot.Modeenv{ RecoverySystem: "20200825", + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } - - model := boottest.MakeMockUC20Model() expectReseal := false - err = boot.ResealKeyToModeenv(rootdir, model, modeenv, expectReseal) + err = boot.ResealKeyToModeenv(rootdir, modeenv, expectReseal) c.Assert(err, ErrorMatches, "fde setup hook failed") c.Check(resealKeyToModeenvUsingFDESetupHookCalled, Equals, 1) } + +func (s *sealSuite) TestResealKeyToModeenvWithTryModel(c *C) { + rootdir := c.MkDir() + dirs.SetRootDir(rootdir) + defer dirs.SetRootDir("") + + c.Assert(os.MkdirAll(dirs.SnapFDEDir, 0755), IsNil) + err := ioutil.WriteFile(filepath.Join(dirs.SnapFDEDir, "sealed-keys"), nil, 0644) + c.Assert(err, IsNil) + + err = createMockGrubCfg(filepath.Join(rootdir, "run/mnt/ubuntu-seed")) + c.Assert(err, IsNil) + + err = createMockGrubCfg(filepath.Join(rootdir, "run/mnt/ubuntu-boot")) + c.Assert(err, IsNil) + + model := boottest.MakeMockUC20Model() + // a try model which would normally only appear during remodel + tryModel := boottest.MakeMockUC20Model(map[string]interface{}{ + "model": "try-my-model-uc20", + "grade": "secured", + }) + + modeenv := &boot.Modeenv{ + // recovery system set up like during a remodel, right before a + // set-device is called + CurrentRecoverySystems: []string{"20200825", "1234", "off-model"}, + GoodRecoverySystems: []string{"20200825", "1234"}, + + CurrentTrustedRecoveryBootAssets: boot.BootAssetsMap{ + "grubx64.efi": []string{"grub-hash"}, + "bootx64.efi": []string{"shim-hash"}, + }, + + CurrentTrustedBootAssets: boot.BootAssetsMap{ + "grubx64.efi": []string{"run-grub-hash"}, + }, + + CurrentKernels: []string{"pc-kernel_500.snap"}, + + CurrentKernelCommandLines: boot.BootCommandLines{ + "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", + }, + // the current model + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), + // the try model + TryModel: tryModel.Model(), + TryBrandID: tryModel.BrandID(), + TryGrade: string(tryModel.Grade()), + TryModelSignKeyID: tryModel.SignKeyID(), + } + + // mock asset cache + mockAssetsCache(c, rootdir, "grub", []string{ + "bootx64.efi-shim-hash", + "grubx64.efi-grub-hash", + "grubx64.efi-run-grub-hash", + }) + + // set a mock recovery kernel + readSystemEssentialCalls := 0 + restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { + readSystemEssentialCalls++ + kernelRev := 1 + systemModel := model + if label == "1234" { + // recovery system for new model + kernelRev = 999 + systemModel = tryModel + } + if label == "off-model" { + // a model that matches neither current not try models + systemModel = boottest.MakeMockUC20Model(map[string]interface{}{ + "model": "different-model-uc20", + "grade": "secured", + }) + } + return systemModel, []*seed.Snap{mockKernelSeedSnap(snap.R(kernelRev)), mockGadgetSeedSnap(c, nil)}, nil + }) + defer restore() + + // set mock key resealing + resealKeysCalls := 0 + restore = boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + c.Check(params.TPMPolicyAuthKeyFile, Equals, filepath.Join(dirs.SnapSaveDir, "device/fde", "tpm-policy-auth-key")) + c.Logf("got:") + for _, mp := range params.ModelParams { + c.Logf("model: %v", mp.Model.Model()) + for _, ch := range mp.EFILoadChains { + printChain(c, ch, "-") + } + } + + resealKeysCalls++ + + switch resealKeysCalls { + case 1: // run key + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + // 2 models, one current and one try model + c.Assert(params.ModelParams, HasLen, 2) + // shared parameters + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + c.Assert(params.ModelParams[0].KernelCmdlines, DeepEquals, []string{ + "snapd_recovery_mode=recover snapd_recovery_system=20200825 console=ttyS0 console=tty1 panic=-1", + "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", + }) + // 2 load chains (bootloader + run kernel, bootloader + recovery kernel) + c.Assert(params.ModelParams[0].EFILoadChains, HasLen, 2) + + c.Assert(params.ModelParams[1].Model.Model(), Equals, "try-my-model-uc20") + c.Assert(params.ModelParams[1].KernelCmdlines, DeepEquals, []string{ + "snapd_recovery_mode=recover snapd_recovery_system=1234 console=ttyS0 console=tty1 panic=-1", + "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", + }) + // 2 load chains (bootloader + run kernel, bootloader + recovery kernel) + c.Assert(params.ModelParams[1].EFILoadChains, HasLen, 2) + case 2: // recovery keys + c.Assert(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + // only the current model + c.Assert(params.ModelParams, HasLen, 1) + // shared parameters + c.Assert(params.ModelParams[0].Model.Model(), Equals, "my-model-uc20") + for _, mp := range params.ModelParams { + c.Assert(mp.KernelCmdlines, DeepEquals, []string{ + "snapd_recovery_mode=recover snapd_recovery_system=20200825 console=ttyS0 console=tty1 panic=-1", + }) + // load chains + c.Assert(mp.EFILoadChains, HasLen, 1) + } + default: + c.Errorf("unexpected additional call to secboot.ResealKeys (call # %d)", resealKeysCalls) + } + + // recovery parameters + shim := bootloader.NewBootFile("", filepath.Join(rootdir, "var/lib/snapd/boot-assets/grub/bootx64.efi-shim-hash"), bootloader.RoleRecovery) + grub := bootloader.NewBootFile("", filepath.Join(rootdir, "var/lib/snapd/boot-assets/grub/grubx64.efi-grub-hash"), bootloader.RoleRecovery) + kernelOldRecovery := bootloader.NewBootFile("/var/lib/snapd/seed/snaps/pc-kernel_1.snap", "kernel.efi", bootloader.RoleRecovery) + // kernel from a tried recovery system + kernelNewRecovery := bootloader.NewBootFile("/var/lib/snapd/seed/snaps/pc-kernel_999.snap", "kernel.efi", bootloader.RoleRecovery) + // run mode parameters + runGrub := bootloader.NewBootFile("", filepath.Join(rootdir, "var/lib/snapd/boot-assets/grub/grubx64.efi-run-grub-hash"), bootloader.RoleRunMode) + runKernel := bootloader.NewBootFile(filepath.Join(rootdir, "var/lib/snapd/snaps/pc-kernel_500.snap"), "kernel.efi", bootloader.RoleRunMode) + + // verify the load chains, which are identical for both models + switch resealKeysCalls { + case 1: // run load chain for 2 models, current and a try model + c.Assert(params.ModelParams, HasLen, 2) + // each load chain has either the run kernel (shared for + // both), or the kernel of the respective recovery + // system + c.Assert(params.ModelParams[0].EFILoadChains, DeepEquals, []*secboot.LoadChain{ + secboot.NewLoadChain(shim, + secboot.NewLoadChain(grub, + secboot.NewLoadChain(kernelOldRecovery), + )), + secboot.NewLoadChain(shim, + secboot.NewLoadChain(grub, + secboot.NewLoadChain(runGrub, + secboot.NewLoadChain(runKernel)), + )), + }) + c.Assert(params.ModelParams[1].EFILoadChains, DeepEquals, []*secboot.LoadChain{ + secboot.NewLoadChain(shim, + secboot.NewLoadChain(grub, + secboot.NewLoadChain(kernelNewRecovery), + )), + secboot.NewLoadChain(shim, + secboot.NewLoadChain(grub, + secboot.NewLoadChain(runGrub, + secboot.NewLoadChain(runKernel)), + )), + }) + case 2: // recovery load chains, only for the current model + c.Assert(params.ModelParams, HasLen, 1) + // load chain with a kernel from a recovery system that + // matches the current model only + c.Assert(params.ModelParams[0].EFILoadChains, DeepEquals, []*secboot.LoadChain{ + secboot.NewLoadChain(shim, + secboot.NewLoadChain(grub, + secboot.NewLoadChain(kernelOldRecovery), + )), + }) + } + + return nil + }) + defer restore() + + // here we don't have unasserted kernels so just set + // expectReseal to false as it doesn't matter; + // the behavior with unasserted kernel is tested in + // boot_test.go specific tests + const expectReseal = false + err = boot.ResealKeyToModeenv(rootdir, modeenv, expectReseal) + c.Assert(err, IsNil) + c.Assert(resealKeysCalls, Equals, 2) + + // verify the boot chains data file for run key + + recoveryAssetChain := []boot.BootAsset{{ + Role: "recovery", + Name: "bootx64.efi", + Hashes: []string{"shim-hash"}, + }, { + Role: "recovery", + Name: "grubx64.efi", + Hashes: []string{"grub-hash"}, + }} + runAssetChain := []boot.BootAsset{{ + Role: "recovery", + Name: "bootx64.efi", + Hashes: []string{"shim-hash"}, + }, { + Role: "recovery", + Name: "grubx64.efi", + Hashes: []string{"grub-hash"}, + }, { + Role: "run-mode", + Name: "grubx64.efi", + Hashes: []string{"run-grub-hash"}, + }} + runPbc, cnt, err := boot.ReadBootChains(filepath.Join(dirs.SnapFDEDir, "boot-chains")) + c.Assert(err, IsNil) + c.Assert(cnt, Equals, 1) + c.Check(runPbc, DeepEquals, boot.PredictableBootChains{ + // the current model + boot.BootChain{ + BrandID: "my-brand", + Model: "my-model-uc20", + Grade: "dangerous", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", + AssetChain: recoveryAssetChain, + Kernel: "pc-kernel", + KernelRevision: "1", + KernelCmdlines: []string{ + "snapd_recovery_mode=recover snapd_recovery_system=20200825 console=ttyS0 console=tty1 panic=-1", + }, + }, + boot.BootChain{ + BrandID: "my-brand", + Model: "my-model-uc20", + Grade: "dangerous", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", + AssetChain: runAssetChain, + Kernel: "pc-kernel", + KernelRevision: "500", + KernelCmdlines: []string{ + "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", + }, + }, + // the try model + boot.BootChain{ + BrandID: "my-brand", + Model: "try-my-model-uc20", + Grade: "secured", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", + AssetChain: recoveryAssetChain, + Kernel: "pc-kernel", + KernelRevision: "999", + KernelCmdlines: []string{ + "snapd_recovery_mode=recover snapd_recovery_system=1234 console=ttyS0 console=tty1 panic=-1", + }, + }, + boot.BootChain{ + BrandID: "my-brand", + Model: "try-my-model-uc20", + Grade: "secured", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", + AssetChain: runAssetChain, + Kernel: "pc-kernel", + KernelRevision: "500", + KernelCmdlines: []string{ + "snapd_recovery_mode=run console=ttyS0 console=tty1 panic=-1", + }, + }, + }) + // recovery boot chains + recoveryPbc, cnt, err := boot.ReadBootChains(filepath.Join(dirs.SnapFDEDir, "recovery-boot-chains")) + c.Assert(err, IsNil) + c.Assert(cnt, Equals, 1) + c.Check(recoveryPbc, DeepEquals, boot.PredictableBootChains{ + // recovery keys are sealed to current model only + boot.BootChain{ + BrandID: "my-brand", + Model: "my-model-uc20", + Grade: "dangerous", + ModelSignKeyID: "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij", + AssetChain: recoveryAssetChain, + Kernel: "pc-kernel", + KernelRevision: "1", + KernelCmdlines: []string{ + "snapd_recovery_mode=recover snapd_recovery_system=20200825 console=ttyS0 console=tty1 panic=-1", + }, + }, + }) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/systems.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/systems.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/systems.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/systems.go 2023-03-23 08:10:58.000000000 +0000 @@ -21,8 +21,8 @@ import ( "fmt" + "strings" - "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/bootloader" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/strutil" @@ -37,9 +37,10 @@ return systemsList, false } -// ClearTryRecoverySystem removes a given candidate recovery system from the -// modeenv state file, reseals and clears related bootloader variables. An empty -// system label can be passed when the boot variables state is inconsistent. +// ClearTryRecoverySystem removes a given candidate recovery system and clears +// the try model in the modeenv state file, then reseals and clears related +// bootloader variables. An empty system label can be passed when the boot +// variables state is inconsistent. func ClearTryRecoverySystem(dev Device, systemLabel string) error { if !dev.HasModeenv() { return fmt.Errorf("internal error: recovery systems can only be used on UC20") @@ -58,14 +59,24 @@ return err } + modified := false // we may be repeating the cleanup, in which case the system was already // removed from the modeenv and we don't need to rewrite the modeenv if updated, found := dropFromRecoverySystemsList(m.CurrentRecoverySystems, systemLabel); found { m.CurrentRecoverySystems = updated + modified = true + } + if m.TryModel != "" { + // recovery system is tried with a matching models + m.clearTryModel() + modified = true + } + if modified { if err := m.Write(); err != nil { return err } } + // clear both variables, no matter the values they hold vars := map[string]string{ "try_recovery_system": "", @@ -77,7 +88,7 @@ // but we still want to reseal, in case the cleanup did not reach this // point before const expectReseal = true - resealErr := resealKeyToModeenv(dirs.GlobalRootDir, dev.Model(), m, expectReseal) + resealErr := resealKeyToModeenv(dirs.GlobalRootDir, m, expectReseal) if resealErr != nil { return resealErr @@ -86,9 +97,11 @@ } // SetTryRecoverySystem sets up the boot environment for trying out a recovery -// system with given label and adds the new system to the list of current -// recovery systems in the modeenv. Once done, the caller should request -// switching to the given recovery system. +// system with given label in the context of the provided device. The call adds +// the new system to the list of current recovery systems in the modeenv, and +// optionally sets a try model, if the device model is different from the +// current one, which typically can happen during a remodel. Once done, the +// caller should request switching to the given recovery system. func SetTryRecoverySystem(dev Device, systemLabel string) (err error) { if !dev.HasModeenv() { return fmt.Errorf("internal error: recovery systems can only be used on UC20") @@ -108,10 +121,24 @@ return err } + modified := false // we could have rebooted before resealing the keys if !strutil.ListContains(m.CurrentRecoverySystems, systemLabel) { m.CurrentRecoverySystems = append(m.CurrentRecoverySystems, systemLabel) + modified = true + } + // we either have the current device context, in which case the model + // will match the current model in the modeenv, or a remodel device + // context carrying a new model, for which we may need to set the try + // model in the modeenv + model := dev.Model() + if modelUniqueID(model) != modelUniqueID(m.ModelForSealing()) { + // recovery system is tried with a matching model + m.setTryModel(model) + modified = true + } + if modified { if err := m.Write(); err != nil { return err } @@ -141,7 +168,7 @@ // tried system, data will still be inaccessible and the system will be // considered as nonoperational const expectReseal = true - return resealKeyToModeenv(dirs.GlobalRootDir, dev.Model(), m, expectReseal) + return resealKeyToModeenv(dirs.GlobalRootDir, m, expectReseal) } type errInconsistentRecoverySystemState struct { @@ -262,7 +289,7 @@ return bl.SetBootVars(vars) } -func observeSuccessfulSystems(model *asserts.Model, m *Modeenv) (*Modeenv, error) { +func observeSuccessfulSystems(m *Modeenv) (*Modeenv, error) { // updates happen in run mode only if m.Mode != "run" { return m, nil @@ -380,7 +407,7 @@ } const expectReseal = true - if err := resealKeyToModeenv(dirs.GlobalRootDir, dev.Model(), m, expectReseal); err != nil { + if err := resealKeyToModeenv(dirs.GlobalRootDir, m, expectReseal); err != nil { if cleanupErr := DropRecoverySystem(dev, systemLabel); cleanupErr != nil { err = fmt.Errorf("%v (cleanup failed: %v)", err, cleanupErr) } @@ -418,5 +445,54 @@ } const expectReseal = true - return resealKeyToModeenv(dirs.GlobalRootDir, dev.Model(), m, expectReseal) + return resealKeyToModeenv(dirs.GlobalRootDir, m, expectReseal) +} + +// MarkRecoveryCapableSystem records a given system as one that we can recover +// from. +func MarkRecoveryCapableSystem(systemLabel string) error { + opts := &bootloader.Options{ + // setup the recovery bootloader + Role: bootloader.RoleRecovery, + } + // TODO:UC20: seed may need to be switched to RW + bl, err := bootloader.Find(InitramfsUbuntuSeedDir, opts) + if err != nil { + return err + } + rbl, ok := bl.(bootloader.RecoveryAwareBootloader) + if !ok { + return nil + } + vars, err := rbl.GetBootVars("snapd_good_recovery_systems") + if err != nil { + return err + } + var systems []string + if vars["snapd_good_recovery_systems"] != "" { + systems = strings.Split(vars["snapd_good_recovery_systems"], ",") + } + // to be consistent with how modeeenv treats good recovery systems, we + // append the system, also make sure that the system appears last, such + // that the bootloader may pick the last entry and have a good default + foundPos := -1 + for idx, sys := range systems { + if sys == systemLabel { + foundPos = idx + break + } + } + if foundPos == -1 { + // not found in the list + systems = append(systems, systemLabel) + } else if foundPos < len(systems)-1 { + // not a last entry in the list of systems + systems = append(systems[0:foundPos], systems[foundPos+1:]...) + systems = append(systems, systemLabel) + } + + systemsForEnv := strings.Join(systems, ",") + return rbl.SetBootVars(map[string]string{ + "snapd_good_recovery_systems": systemsForEnv, + }) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/systems_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/systems_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/boot/systems_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/boot/systems_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -34,6 +34,7 @@ "github.com/snapcore/snapd/secboot" "github.com/snapcore/snapd/seed" "github.com/snapcore/snapd/snap" + "github.com/snapcore/snapd/testutil" "github.com/snapcore/snapd/timings" ) @@ -95,7 +96,7 @@ s.recoveryKernelBf = bootloader.NewBootFile("/var/lib/snapd/seed/snaps/pc-kernel_1.snap", "kernel.efi", bootloader.RoleRecovery) - s.seedKernelSnap = mockKernelSeedSnap(c, snap.R(1)) + s.seedKernelSnap = mockKernelSeedSnap(snap.R(1)) s.seedGadgetSnap = mockGadgetSeedSnap(c, nil) } @@ -111,6 +112,8 @@ // system is encrypted s.stampSealedKeys(c, s.rootdir) + model := s.uc20dev.Model() + modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy @@ -123,6 +126,11 @@ "asset": []string{"asset-hash-1"}, }, CurrentKernels: []string{"pc-kernel_500.snap"}, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } c.Assert(modeenv.WriteTo(""), IsNil) @@ -131,7 +139,7 @@ // the mock bootloader can only mock a single recovery boot // chain, so pretend both seeds use the same kernel, but keep track of the labels readSeedSeenLabels = append(readSeedSeenLabels, label) - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil }) defer restore() @@ -199,18 +207,163 @@ "asset": []string{"asset-hash-1"}, }, CurrentKernels: []string{"pc-kernel_500.snap"}, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), }), Equals, true) } +func (s *systemsSuite) TestSetTryRecoverySystemRemodelEncrypted(c *C) { + mockAssetsCache(c, s.rootdir, "trusted", []string{ + "asset-asset-hash-1", + }) + + mtbl := s.mockTrustedBootloaderWithAssetAndChains(c, s.runKernelBf, s.recoveryKernelBf) + bootloader.Force(mtbl) + defer bootloader.Force(nil) + + // system is encrypted + s.stampSealedKeys(c, s.rootdir) + + model := s.uc20dev.Model() + newModel := boottest.MakeMockUC20Model(map[string]interface{}{ + "model": "my-new-model", + }) + + modeenv := &boot.Modeenv{ + Mode: "run", + // keep this comment to make old gofmt happy + CurrentRecoverySystems: []string{"20200825"}, + GoodRecoverySystems: []string{"20200825"}, + CurrentTrustedRecoveryBootAssets: boot.BootAssetsMap{ + "asset": []string{"asset-hash-1"}, + }, + CurrentTrustedBootAssets: boot.BootAssetsMap{ + "asset": []string{"asset-hash-1"}, + }, + CurrentKernels: []string{"pc-kernel_500.snap"}, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), + } + c.Assert(modeenv.WriteTo(""), IsNil) + + var readSeedSeenLabels []string + restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { + // the mock bootloader can only mock a single recovery boot + // chain, so pretend both seeds use the same kernel, but keep track of the labels + readSeedSeenLabels = append(readSeedSeenLabels, label) + systemModel := model + if label == "1234" { + systemModel = newModel + } + return systemModel, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + }) + defer restore() + + resealCalls := 0 + restore = boot.MockSecbootResealKeys(func(params *secboot.ResealKeysParams) error { + resealCalls++ + // bootloader variables have already been modified + c.Check(mtbl.SetBootVarsCalls, Equals, 1) + c.Assert(params, NotNil) + switch resealCalls { + case 1: + c.Assert(params.ModelParams, HasLen, 2) + c.Check(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), + }) + c.Assert(params.ModelParams[0].KernelCmdlines, DeepEquals, []string{ + "snapd_recovery_mode=recover snapd_recovery_system=20200825 static cmdline", + "snapd_recovery_mode=run static cmdline", + }) + c.Assert(params.ModelParams[1].KernelCmdlines, DeepEquals, []string{ + "snapd_recovery_mode=recover snapd_recovery_system=1234 static cmdline", + "snapd_recovery_mode=run static cmdline", + }) + return nil + case 2: + c.Assert(params.ModelParams, HasLen, 1) + c.Check(params.KeyFiles, DeepEquals, []string{ + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), + filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-save.recovery.sealed-key"), + }) + c.Assert(params.ModelParams[0].KernelCmdlines, DeepEquals, []string{ + "snapd_recovery_mode=recover snapd_recovery_system=20200825 static cmdline", + }) + return nil + default: + c.Errorf("unexpected call to secboot.ResealKeys with count %v", resealCalls) + return fmt.Errorf("unexpected call") + } + }) + defer restore() + + // a remodel will pass the new device + newUC20Device := boottest.MockUC20Device("run", newModel) + err := boot.SetTryRecoverySystem(newUC20Device, "1234") + c.Assert(err, IsNil) + + vars, err := mtbl.GetBootVars("try_recovery_system", "recovery_system_status") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + "try_recovery_system": "1234", + "recovery_system_status": "try", + }) + // run and recovery keys + c.Check(resealCalls, Equals, 2) + c.Check(readSeedSeenLabels, DeepEquals, []string{ + "20200825", "1234", // current recovery systems for run key and current model from modeenv + "20200825", "1234", // current recovery systems for run key and try model from modeenv + "20200825", // good recovery systems for recovery keys + }) + + modeenvRead, err := boot.ReadModeenv("") + c.Assert(err, IsNil) + c.Check(modeenvRead, testutil.JsonEquals, boot.Modeenv{ + Mode: "run", + // keep this comment to make old gofmt happy + CurrentRecoverySystems: []string{"20200825", "1234"}, + GoodRecoverySystems: []string{"20200825"}, + CurrentTrustedRecoveryBootAssets: boot.BootAssetsMap{ + "asset": []string{"asset-hash-1"}, + }, + CurrentTrustedBootAssets: boot.BootAssetsMap{ + "asset": []string{"asset-hash-1"}, + }, + CurrentKernels: []string{"pc-kernel_500.snap"}, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), + + TryModel: newModel.Model(), + TryBrandID: newModel.BrandID(), + TryGrade: string(newModel.Grade()), + TryModelSignKeyID: newModel.SignKeyID(), + }) +} + func (s *systemsSuite) TestSetTryRecoverySystemSimple(c *C) { mtbl := bootloadertest.Mock("trusted", s.bootdir).WithTrustedAssets() bootloader.Force(mtbl) defer bootloader.Force(nil) + model := s.uc20dev.Model() modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy CurrentRecoverySystems: []string{"20200825"}, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } c.Assert(modeenv.WriteTo(""), IsNil) @@ -231,11 +384,16 @@ modeenvRead, err := boot.ReadModeenv("") c.Assert(err, IsNil) - c.Check(modeenvRead.DeepEqual(&boot.Modeenv{ + c.Check(modeenvRead, testutil.JsonEquals, boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy CurrentRecoverySystems: []string{"20200825", "1234"}, - }), Equals, true) + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), + }) } func (s *systemsSuite) TestSetTryRecoverySystemSetBootVarsErr(c *C) { @@ -299,6 +457,8 @@ // system is encrypted s.stampSealedKeys(c, s.rootdir) + model := s.uc20dev.Model() + modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy @@ -310,6 +470,11 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": []string{"asset-hash-1"}, }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } c.Assert(modeenv.WriteTo(""), IsNil) @@ -323,7 +488,7 @@ // called for the first system c.Assert(label, Equals, "20200825") c.Check(mtbl.SetBootVarsCalls, Equals, 1) - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil case 2: // called for the 'try' system c.Assert(label, Equals, "1234") @@ -346,7 +511,7 @@ c.Assert(label, Equals, "20200825") // boot variables already updated c.Check(mtbl.SetBootVarsCalls, Equals, 2) - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil default: return nil, nil, fmt.Errorf("unexpected call %v", readSeedCalls) } @@ -396,6 +561,8 @@ // system is encrypted s.stampSealedKeys(c, s.rootdir) + model := s.uc20dev.Model() + modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy @@ -407,6 +574,11 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": []string{"asset-hash-1"}, }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } c.Assert(modeenv.WriteTo(""), IsNil) @@ -420,7 +592,7 @@ // called for the first system c.Assert(label, Equals, "20200825") c.Check(mtbl.SetBootVarsCalls, Equals, 1) - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil case 2: // called for the 'try' system c.Assert(label, Equals, "1234") @@ -432,7 +604,7 @@ }) c.Check(mtbl.SetBootVarsCalls, Equals, 1) // still good - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil case 3: // recovery boot chains for a good recovery system c.Check(mtbl.SetBootVarsCalls, Equals, 1) @@ -448,7 +620,7 @@ if readSeedCalls >= 4 { c.Check(mtbl.SetBootVarsCalls, Equals, 2) } - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil default: return nil, nil, fmt.Errorf("unexpected call %v", readSeedCalls) } @@ -506,6 +678,7 @@ // system is encrypted s.stampSealedKeys(c, s.rootdir) + model := s.uc20dev.Model() modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy @@ -517,6 +690,11 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": []string{"asset-hash-1"}, }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } c.Assert(modeenv.WriteTo(""), IsNil) @@ -524,6 +702,7 @@ restore := boot.MockSeedReadSystemEssential(func(seedDir, label string, essentialTypes []snap.Type, tm timings.Measurer) (*asserts.Model, []*seed.Snap, error) { readSeedCalls++ // this is the reseal cleanup path + c.Logf("call %v label %v", readSeedCalls, label) switch readSeedCalls { case 1: // called for the first system @@ -543,7 +722,7 @@ fallthrough case 5: // (cleanup) recovery boot chains for recovery keys - c.Assert(label, Equals, "20200825") + c.Check(label, Equals, "20200825") return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil default: return nil, nil, fmt.Errorf("unexpected call %v", readSeedCalls) @@ -736,7 +915,14 @@ c.Check(vars, DeepEquals, badVars) } -func (s *systemsSuite) testClearRecoverySystem(c *C, mtbl *bootloadertest.MockTrustedAssetsBootloader, systemLabel string, resealErr error, expectedErr string) { +type clearRecoverySystemTestCase struct { + systemLabel string + tryModel *asserts.Model + resealErr error + expectedErr string +} + +func (s *systemsSuite) testClearRecoverySystem(c *C, mtbl *bootloadertest.MockTrustedAssetsBootloader, tc clearRecoverySystemTestCase) { mockAssetsCache(c, s.rootdir, "trusted", []string{ "asset-asset-hash-1", }) @@ -747,6 +933,8 @@ // system is encrypted s.stampSealedKeys(c, s.rootdir) + model := s.uc20dev.Model() + modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy @@ -760,9 +948,20 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": []string{"asset-hash-1"}, }, - } - if systemLabel != "" { - modeenv.CurrentRecoverySystems = append(modeenv.CurrentRecoverySystems, systemLabel) + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), + } + if tc.systemLabel != "" { + modeenv.CurrentRecoverySystems = append(modeenv.CurrentRecoverySystems, tc.systemLabel) + } + if tc.tryModel != nil { + modeenv.TryModel = tc.tryModel.Model() + modeenv.TryBrandID = tc.tryModel.BrandID() + modeenv.TryGrade = string(tc.tryModel.Grade()) + modeenv.TryModelSignKeyID = tc.tryModel.SignKeyID() } c.Assert(modeenv.WriteTo(""), IsNil) @@ -771,7 +970,7 @@ // the mock bootloader can only mock a single recovery boot // chain, so pretend both seeds use the same kernel, but keep track of the labels readSeedSeenLabels = append(readSeedSeenLabels, label) - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil }) defer restore() @@ -785,7 +984,7 @@ c.Check(params.KeyFiles, DeepEquals, []string{ filepath.Join(boot.InitramfsBootEncryptionKeyDir, "ubuntu-data.sealed-key"), }) - return resealErr + return tc.resealErr case 2: c.Check(params.KeyFiles, DeepEquals, []string{ filepath.Join(boot.InitramfsSeedEncryptionKeyDir, "ubuntu-data.recovery.sealed-key"), @@ -802,16 +1001,16 @@ }) defer restore() - err := boot.ClearTryRecoverySystem(s.uc20dev, systemLabel) - if expectedErr == "" { + err := boot.ClearTryRecoverySystem(s.uc20dev, tc.systemLabel) + if tc.expectedErr == "" { c.Assert(err, IsNil) } else { - c.Assert(err, ErrorMatches, expectedErr) + c.Assert(err, ErrorMatches, tc.expectedErr) } // only one seed system accessed c.Check(readSeedSeenLabels, DeepEquals, []string{"20200825", "20200825"}) - if resealErr == nil { + if tc.resealErr == nil { // called twice, for run and recovery keys c.Check(resealCalls, Equals, 2) } else { @@ -822,8 +1021,25 @@ modeenvRead, err := boot.ReadModeenv("") c.Assert(err, IsNil) // modeenv systems list has one entry only - c.Check(modeenvRead.CurrentRecoverySystems, DeepEquals, []string{ - "20200825", + c.Check(modeenvRead, testutil.JsonEquals, boot.Modeenv{ + Mode: "run", + // keep this comment to make old gofmt happy + CurrentRecoverySystems: []string{"20200825"}, + GoodRecoverySystems: []string{"20200825"}, + CurrentTrustedRecoveryBootAssets: boot.BootAssetsMap{ + "asset": []string{"asset-hash-1"}, + }, + + CurrentTrustedBootAssets: boot.BootAssetsMap{ + "asset": []string{"asset-hash-1"}, + }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), + + // try model if set, has been cleared }) } @@ -836,7 +1052,7 @@ err := mtbl.SetBootVars(setVars) c.Assert(err, IsNil) - s.testClearRecoverySystem(c, mtbl, "1234", nil, "") + s.testClearRecoverySystem(c, mtbl, clearRecoverySystemTestCase{systemLabel: "1234"}) // bootloader variables have been cleared vars, err := mtbl.GetBootVars("try_recovery_system", "recovery_system_status") c.Assert(err, IsNil) @@ -855,7 +1071,7 @@ err := mtbl.SetBootVars(setVars) c.Assert(err, IsNil) - s.testClearRecoverySystem(c, mtbl, "1234", nil, "") + s.testClearRecoverySystem(c, mtbl, clearRecoverySystemTestCase{systemLabel: "1234"}) // bootloader variables have been cleared vars, err := mtbl.GetBootVars("try_recovery_system", "recovery_system_status") c.Assert(err, IsNil) @@ -874,7 +1090,7 @@ err := mtbl.SetBootVars(setVars) c.Assert(err, IsNil) - s.testClearRecoverySystem(c, mtbl, "1234", nil, "") + s.testClearRecoverySystem(c, mtbl, clearRecoverySystemTestCase{systemLabel: "1234"}) // bootloader variables have been cleared vars, err := mtbl.GetBootVars("try_recovery_system", "recovery_system_status") c.Assert(err, IsNil) @@ -896,7 +1112,31 @@ // clear without passing the system label, just clears the relevant boot // variables const noLabel = "" - s.testClearRecoverySystem(c, mtbl, noLabel, nil, "") + s.testClearRecoverySystem(c, mtbl, clearRecoverySystemTestCase{systemLabel: noLabel}) + // bootloader variables have been cleared + vars, err := mtbl.GetBootVars("try_recovery_system", "recovery_system_status") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + "try_recovery_system": "", + "recovery_system_status": "", + }) +} + +func (s *systemsSuite) TestClearRecoverySystemRemodelHappy(c *C) { + setVars := map[string]string{ + "recovery_system_status": "try", + "try_recovery_system": "1234", + } + mtbl := s.mockTrustedBootloaderWithAssetAndChains(c, s.runKernelBf, s.recoveryKernelBf) + err := mtbl.SetBootVars(setVars) + c.Assert(err, IsNil) + + s.testClearRecoverySystem(c, mtbl, clearRecoverySystemTestCase{ + systemLabel: "1234", + tryModel: boottest.MakeMockUC20Model(map[string]interface{}{ + "tryModelodel": "my-new-model", + }), + }) // bootloader variables have been cleared vars, err := mtbl.GetBootVars("try_recovery_system", "recovery_system_status") c.Assert(err, IsNil) @@ -915,7 +1155,11 @@ err := mtbl.SetBootVars(setVars) c.Assert(err, IsNil) - s.testClearRecoverySystem(c, mtbl, "1234", fmt.Errorf("reseal fails"), "cannot reseal the encryption key: reseal fails") + s.testClearRecoverySystem(c, mtbl, clearRecoverySystemTestCase{ + systemLabel: "1234", + resealErr: fmt.Errorf("reseal fails"), + expectedErr: "cannot reseal the encryption key: reseal fails", + }) // bootloader variables have been cleared vars, err := mtbl.GetBootVars("try_recovery_system", "recovery_system_status") c.Assert(err, IsNil) @@ -936,7 +1180,10 @@ c.Assert(err, IsNil) mtbl.SetErr = fmt.Errorf("set boot vars fails") - s.testClearRecoverySystem(c, mtbl, "1234", nil, "set boot vars fails") + s.testClearRecoverySystem(c, mtbl, clearRecoverySystemTestCase{ + systemLabel: "1234", + expectedErr: "set boot vars fails", + }) } func (s *systemsSuite) TestClearRecoverySystemReboot(c *C) { @@ -958,6 +1205,8 @@ // system is encrypted s.stampSealedKeys(c, s.rootdir) + model := s.uc20dev.Model() + modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy @@ -970,6 +1219,11 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": []string{"asset-hash-1"}, }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } c.Assert(modeenv.WriteTo(""), IsNil) @@ -978,7 +1232,7 @@ // the mock bootloader can only mock a single recovery boot // chain, so pretend both seeds use the same kernel, but keep track of the labels readSeedSeenLabels = append(readSeedSeenLabels, label) - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil }) defer restore() @@ -1085,6 +1339,8 @@ // system is encrypted s.stampSealedKeys(c, s.rootdir) + model := s.uc20dev.Model() + modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy @@ -1098,6 +1354,11 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": []string{"asset-hash-1"}, }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } if tc.systemLabelAddToCurrent { modeenv.CurrentRecoverySystems = append(modeenv.CurrentRecoverySystems, systemLabel) @@ -1113,7 +1374,7 @@ // the mock bootloader can only mock a single recovery boot // chain, so pretend both seeds use the same kernel, but keep track of the labels readSeedSeenLabels = append(readSeedSeenLabels, label) - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil }) defer restore() @@ -1343,6 +1604,8 @@ // system is encrypted s.stampSealedKeys(c, s.rootdir) + model := s.uc20dev.Model() + modeenv := &boot.Modeenv{ Mode: "run", // keep this comment to make old gofmt happy @@ -1356,6 +1619,11 @@ CurrentTrustedBootAssets: boot.BootAssetsMap{ "asset": []string{"asset-hash-1"}, }, + + Model: model.Model(), + BrandID: model.BrandID(), + Grade: string(model.Grade()), + ModelSignKeyID: model.SignKeyID(), } if tc.systemLabelAddToCurrent { modeenv.CurrentRecoverySystems = append(modeenv.CurrentRecoverySystems, systemLabel) @@ -1371,7 +1639,7 @@ // the mock bootloader can only mock a single recovery boot // chain, so pretend both seeds use the same kernel, but keep track of the labels readSeedSeenLabels = append(readSeedSeenLabels, label) - return s.uc20dev.Model(), []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil + return model, []*seed.Snap{s.seedKernelSnap, s.seedGadgetSnap}, nil }) defer restore() @@ -1467,6 +1735,143 @@ }) } +func (s *systemsSuite) TestMarkRecoveryCapableSystemHappy(c *C) { + rbl := bootloadertest.Mock("recovery", c.MkDir()).RecoveryAware() + bootloader.Force(rbl) + + err := boot.MarkRecoveryCapableSystem("1234") + c.Assert(err, IsNil) + vars, err := rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + "snapd_good_recovery_systems": "1234", + }) + // try the same system again + err = boot.MarkRecoveryCapableSystem("1234") + c.Assert(err, IsNil) + vars, err = rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + // still a single entry + "snapd_good_recovery_systems": "1234", + }) + + // try something new + err = boot.MarkRecoveryCapableSystem("4567") + c.Assert(err, IsNil) + vars, err = rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + // entry added + "snapd_good_recovery_systems": "1234,4567", + }) + + // try adding the old one again + err = boot.MarkRecoveryCapableSystem("1234") + c.Assert(err, IsNil) + vars, err = rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + // system got moved to the end of the list + "snapd_good_recovery_systems": "4567,1234", + }) + + // and the new one again + err = boot.MarkRecoveryCapableSystem("4567") + c.Assert(err, IsNil) + vars, err = rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + // and it became the last entry + "snapd_good_recovery_systems": "1234,4567", + }) +} + +func (s *systemsSuite) TestMarkRecoveryCapableSystemAlwaysLast(c *C) { + rbl := bootloadertest.Mock("recovery", c.MkDir()).RecoveryAware() + bootloader.Force(rbl) + + err := rbl.SetBootVars(map[string]string{ + "snapd_good_recovery_systems": "1234,2222", + }) + c.Assert(err, IsNil) + + err = boot.MarkRecoveryCapableSystem("1234") + c.Assert(err, IsNil) + vars, err := rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + "snapd_good_recovery_systems": "2222,1234", + }) + + err = rbl.SetBootVars(map[string]string{ + "snapd_good_recovery_systems": "1111,1234,2222", + }) + c.Assert(err, IsNil) + err = boot.MarkRecoveryCapableSystem("1234") + c.Assert(err, IsNil) + vars, err = rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + "snapd_good_recovery_systems": "1111,2222,1234", + }) + + err = rbl.SetBootVars(map[string]string{ + "snapd_good_recovery_systems": "1111,2222", + }) + c.Assert(err, IsNil) + err = boot.MarkRecoveryCapableSystem("1234") + c.Assert(err, IsNil) + vars, err = rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + "snapd_good_recovery_systems": "1111,2222,1234", + }) +} + +func (s *systemsSuite) TestMarkRecoveryCapableSystemErr(c *C) { + rbl := bootloadertest.Mock("recovery", c.MkDir()).RecoveryAware() + bootloader.Force(rbl) + + err := boot.MarkRecoveryCapableSystem("1234") + c.Assert(err, IsNil) + vars, err := rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + "snapd_good_recovery_systems": "1234", + }) + + rbl.SetErr = fmt.Errorf("mocked error") + err = boot.MarkRecoveryCapableSystem("4567") + c.Assert(err, ErrorMatches, "mocked error") + vars, err = rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + // mocked error is returned after variable is set + "snapd_good_recovery_systems": "1234,4567", + }) + + // but mocked panic happens earlier + rbl.SetMockToPanic("SetBootVars") + c.Assert(func() { boot.MarkRecoveryCapableSystem("9999") }, + PanicMatches, "mocked reboot panic in SetBootVars") + vars, err = rbl.GetBootVars("snapd_good_recovery_systems") + c.Assert(err, IsNil) + c.Check(vars, DeepEquals, map[string]string{ + "snapd_good_recovery_systems": "1234,4567", + }) + +} + +func (s *systemsSuite) TestMarkRecoveryCapableSystemNonRecoveryAware(c *C) { + bl := bootloadertest.Mock("recovery", c.MkDir()) + bootloader.Force(bl) + + err := boot.MarkRecoveryCapableSystem("1234") + c.Assert(err, IsNil) + c.Check(bl.SetBootVarsCalls, Equals, 0) +} + type initramfsMarkTryRecoverySystemSuite struct { baseSystemsSuite diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/data/grub-recovery.cfg ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/data/grub-recovery.cfg --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/data/grub-recovery.cfg 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/data/grub-recovery.cfg 2023-03-23 08:10:58.000000000 +0000 @@ -32,7 +32,9 @@ # globbing in grub does not sort for label in /systems/*; do - regexp --set 1:label "/([0-9]*)\$" "$label" + # match the system labels generated by snapd, which are usually just + # numbers. eg. 20210706, but can be hyphen separated numbers and letters + regexp --set 1:label "/([a-z0-9](-?[a-z0-9])*)\$" "$label" if [ -z "$label" ]; then continue fi diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/generate.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/generate.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/generate.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/generate.go 2023-03-23 08:10:58.000000000 +0000 @@ -19,5 +19,5 @@ package assets -//go:generate go run ./genasset/main.go -name grub.cfg -in ./data/grub.cfg -out ./grub_cfg_asset.go -//go:generate go run ./genasset/main.go -name grub-recovery.cfg -in ./data/grub-recovery.cfg -out ./grub_recovery_cfg_asset.go +//go:generate go run $GOINVOKEFLAGS ./genasset/main.go -name grub.cfg -in ./data/grub.cfg -out ./grub_cfg_asset.go +//go:generate go run $GOINVOKEFLAGS ./genasset/main.go -name grub-recovery.cfg -in ./data/grub-recovery.cfg -out ./grub_recovery_cfg_asset.go diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/grub_recovery_cfg_asset.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/grub_recovery_cfg_asset.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/grub_recovery_cfg_asset.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/assets/grub_recovery_cfg_asset.go 2023-03-23 08:10:58.000000000 +0000 @@ -76,90 +76,100 @@ 0x6e, 0x20, 0x67, 0x72, 0x75, 0x62, 0x20, 0x64, 0x6f, 0x65, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x73, 0x6f, 0x72, 0x74, 0x0a, 0x66, 0x6f, 0x72, 0x20, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, 0x69, 0x6e, 0x20, 0x2f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x2a, 0x3b, 0x20, 0x64, 0x6f, - 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x67, 0x65, 0x78, 0x70, 0x20, 0x2d, 0x2d, 0x73, 0x65, - 0x74, 0x20, 0x31, 0x3a, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, 0x22, 0x2f, 0x28, 0x5b, 0x30, 0x2d, - 0x39, 0x5d, 0x2a, 0x29, 0x5c, 0x24, 0x22, 0x20, 0x22, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x22, - 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x5b, 0x20, 0x2d, 0x7a, 0x20, 0x22, 0x24, 0x6c, - 0x61, 0x62, 0x65, 0x6c, 0x22, 0x20, 0x5d, 0x3b, 0x20, 0x74, 0x68, 0x65, 0x6e, 0x0a, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x69, 0x6e, 0x75, 0x65, 0x0a, 0x20, - 0x20, 0x20, 0x20, 0x66, 0x69, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x23, 0x20, 0x79, 0x65, 0x73, 0x2c, - 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6e, 0x65, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x62, 0x61, 0x63, - 0x6b, 0x73, 0x6c, 0x61, 0x73, 0x68, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x6c, 0x65, 0x73, 0x73, - 0x2d, 0x74, 0x68, 0x61, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x5b, 0x20, 0x2d, - 0x7a, 0x20, 0x22, 0x24, 0x62, 0x65, 0x73, 0x74, 0x22, 0x20, 0x2d, 0x6f, 0x20, 0x22, 0x24, 0x6c, - 0x61, 0x62, 0x65, 0x6c, 0x22, 0x20, 0x5c, 0x3c, 0x20, 0x22, 0x24, 0x62, 0x65, 0x73, 0x74, 0x22, - 0x20, 0x5d, 0x3b, 0x20, 0x74, 0x68, 0x65, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x73, 0x65, 0x74, 0x20, 0x62, 0x65, 0x73, 0x74, 0x3d, 0x22, 0x24, 0x6c, 0x61, 0x62, 0x65, - 0x6c, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x69, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x23, 0x20, - 0x69, 0x66, 0x20, 0x67, 0x72, 0x75, 0x62, 0x65, 0x6e, 0x76, 0x20, 0x64, 0x69, 0x64, 0x20, 0x6e, - 0x6f, 0x74, 0x20, 0x70, 0x69, 0x63, 0x6b, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x2d, 0x73, 0x79, 0x73, - 0x74, 0x65, 0x6d, 0x2c, 0x20, 0x75, 0x73, 0x65, 0x20, 0x62, 0x65, 0x73, 0x74, 0x20, 0x6f, 0x6e, - 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x5b, 0x20, 0x2d, 0x7a, 0x20, 0x22, 0x24, - 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x73, - 0x79, 0x73, 0x74, 0x65, 0x6d, 0x22, 0x20, 0x5d, 0x3b, 0x20, 0x74, 0x68, 0x65, 0x6e, 0x0a, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x3d, 0x24, - 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6d, - 0x6f, 0x64, 0x65, 0x2d, 0x24, 0x62, 0x65, 0x73, 0x74, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x69, - 0x0a, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, - 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x3d, 0x0a, - 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x65, 0x6e, 0x76, 0x20, 0x2d, 0x2d, 0x66, - 0x69, 0x6c, 0x65, 0x20, 0x2f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x24, 0x6c, 0x61, - 0x62, 0x65, 0x6c, 0x2f, 0x67, 0x72, 0x75, 0x62, 0x65, 0x6e, 0x76, 0x20, 0x73, 0x6e, 0x61, 0x70, - 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6b, 0x65, 0x72, 0x6e, 0x65, - 0x6c, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x65, 0x78, 0x74, 0x72, 0x61, 0x5f, 0x63, 0x6d, - 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, - 0x5f, 0x66, 0x75, 0x6c, 0x6c, 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, - 0x67, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x20, 0x63, 0x6d, 0x64, 0x6c, 0x69, - 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x3d, 0x22, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, - 0x73, 0x74, 0x61, 0x74, 0x69, 0x63, 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, - 0x72, 0x67, 0x73, 0x20, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x65, 0x78, 0x74, 0x72, 0x61, - 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x22, 0x0a, 0x20, - 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x5b, 0x20, 0x2d, 0x6e, 0x20, 0x22, 0x24, 0x73, 0x6e, 0x61, - 0x70, 0x64, 0x5f, 0x66, 0x75, 0x6c, 0x6c, 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, - 0x61, 0x72, 0x67, 0x73, 0x22, 0x20, 0x5d, 0x3b, 0x20, 0x74, 0x68, 0x65, 0x6e, 0x0a, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x20, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, - 0x5f, 0x61, 0x72, 0x67, 0x73, 0x3d, 0x22, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x66, 0x75, - 0x6c, 0x6c, 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x22, - 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x69, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x23, 0x20, 0x57, - 0x65, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x22, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, - 0x2f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, - 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x2f, - 0x67, 0x72, 0x75, 0x62, 0x2e, 0x63, 0x66, 0x67, 0x22, 0x20, 0x68, 0x65, 0x72, 0x65, 0x20, 0x61, - 0x73, 0x20, 0x77, 0x65, 0x6c, 0x6c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x65, 0x6e, 0x75, 0x65, - 0x6e, 0x74, 0x72, 0x79, 0x20, 0x22, 0x52, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x75, 0x73, - 0x69, 0x6e, 0x67, 0x20, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x22, 0x20, 0x2d, 0x2d, 0x68, 0x6f, - 0x74, 0x6b, 0x65, 0x79, 0x3d, 0x72, 0x20, 0x2d, 0x2d, 0x69, 0x64, 0x3d, 0x72, 0x65, 0x63, 0x6f, - 0x76, 0x65, 0x72, 0x2d, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, 0x24, 0x73, 0x6e, 0x61, 0x70, - 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6b, 0x65, 0x72, 0x6e, 0x65, - 0x6c, 0x20, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, - 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x6f, 0x70, 0x62, - 0x61, 0x63, 0x6b, 0x20, 0x6c, 0x6f, 0x6f, 0x70, 0x20, 0x24, 0x32, 0x0a, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x65, 0x72, 0x20, - 0x28, 0x6c, 0x6f, 0x6f, 0x70, 0x29, 0x2f, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x2e, 0x65, 0x66, - 0x69, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, - 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x3d, 0x24, 0x33, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, - 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x3d, 0x24, - 0x34, 0x20, 0x24, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x0a, - 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x65, 0x6e, 0x75, 0x65, 0x6e, - 0x74, 0x72, 0x79, 0x20, 0x22, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x20, 0x75, 0x73, 0x69, - 0x6e, 0x67, 0x20, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x22, 0x20, 0x2d, 0x2d, 0x68, 0x6f, 0x74, - 0x6b, 0x65, 0x79, 0x3d, 0x69, 0x20, 0x2d, 0x2d, 0x69, 0x64, 0x3d, 0x69, 0x6e, 0x73, 0x74, 0x61, - 0x6c, 0x6c, 0x2d, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, - 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, - 0x20, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x20, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, - 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x6f, 0x70, 0x62, 0x61, - 0x63, 0x6b, 0x20, 0x6c, 0x6f, 0x6f, 0x70, 0x20, 0x24, 0x32, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x65, 0x72, 0x20, 0x28, - 0x6c, 0x6f, 0x6f, 0x70, 0x29, 0x2f, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x2e, 0x65, 0x66, 0x69, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x23, 0x20, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x20, 0x74, 0x68, 0x65, + 0x20, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x20, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x73, 0x20, 0x67, + 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x73, 0x6e, 0x61, 0x70, + 0x64, 0x2c, 0x20, 0x77, 0x68, 0x69, 0x63, 0x68, 0x20, 0x61, 0x72, 0x65, 0x20, 0x75, 0x73, 0x75, + 0x61, 0x6c, 0x6c, 0x79, 0x20, 0x6a, 0x75, 0x73, 0x74, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x23, 0x20, + 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x2e, 0x20, 0x65, 0x67, 0x2e, 0x20, 0x32, 0x30, 0x32, + 0x31, 0x30, 0x37, 0x30, 0x36, 0x2c, 0x20, 0x62, 0x75, 0x74, 0x20, 0x63, 0x61, 0x6e, 0x20, 0x62, + 0x65, 0x20, 0x68, 0x79, 0x70, 0x68, 0x65, 0x6e, 0x20, 0x73, 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, + 0x65, 0x64, 0x20, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x6c, + 0x65, 0x74, 0x74, 0x65, 0x72, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x67, 0x65, 0x78, + 0x70, 0x20, 0x2d, 0x2d, 0x73, 0x65, 0x74, 0x20, 0x31, 0x3a, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, + 0x22, 0x2f, 0x28, 0x5b, 0x61, 0x2d, 0x7a, 0x30, 0x2d, 0x39, 0x5d, 0x28, 0x2d, 0x3f, 0x5b, 0x61, + 0x2d, 0x7a, 0x30, 0x2d, 0x39, 0x5d, 0x29, 0x2a, 0x29, 0x5c, 0x24, 0x22, 0x20, 0x22, 0x24, 0x6c, + 0x61, 0x62, 0x65, 0x6c, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x5b, 0x20, 0x2d, + 0x7a, 0x20, 0x22, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x22, 0x20, 0x5d, 0x3b, 0x20, 0x74, 0x68, + 0x65, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x69, + 0x6e, 0x75, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x69, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x23, + 0x20, 0x79, 0x65, 0x73, 0x2c, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6e, 0x65, 0x65, 0x64, 0x20, 0x74, + 0x6f, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x73, 0x6c, 0x61, 0x73, 0x68, 0x20, 0x74, 0x68, 0x61, 0x74, + 0x20, 0x6c, 0x65, 0x73, 0x73, 0x2d, 0x74, 0x68, 0x61, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, + 0x66, 0x20, 0x5b, 0x20, 0x2d, 0x7a, 0x20, 0x22, 0x24, 0x62, 0x65, 0x73, 0x74, 0x22, 0x20, 0x2d, + 0x6f, 0x20, 0x22, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x22, 0x20, 0x5c, 0x3c, 0x20, 0x22, 0x24, + 0x62, 0x65, 0x73, 0x74, 0x22, 0x20, 0x5d, 0x3b, 0x20, 0x74, 0x68, 0x65, 0x6e, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x20, 0x62, 0x65, 0x73, 0x74, 0x3d, 0x22, + 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x69, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x23, 0x20, 0x69, 0x66, 0x20, 0x67, 0x72, 0x75, 0x62, 0x65, 0x6e, 0x76, 0x20, + 0x64, 0x69, 0x64, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x70, 0x69, 0x63, 0x6b, 0x20, 0x6d, 0x6f, 0x64, + 0x65, 0x2d, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x2c, 0x20, 0x75, 0x73, 0x65, 0x20, 0x62, 0x65, + 0x73, 0x74, 0x20, 0x6f, 0x6e, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x5b, 0x20, + 0x2d, 0x7a, 0x20, 0x22, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, + 0x65, 0x72, 0x79, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x22, 0x20, 0x5d, 0x3b, 0x20, 0x74, + 0x68, 0x65, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x61, + 0x75, 0x6c, 0x74, 0x3d, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, + 0x65, 0x72, 0x79, 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x2d, 0x24, 0x62, 0x65, 0x73, 0x74, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x66, 0x69, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x20, 0x73, 0x6e, + 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6b, 0x65, 0x72, + 0x6e, 0x65, 0x6c, 0x3d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x61, 0x64, 0x5f, 0x65, 0x6e, + 0x76, 0x20, 0x2d, 0x2d, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x2f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, + 0x73, 0x2f, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x2f, 0x67, 0x72, 0x75, 0x62, 0x65, 0x6e, 0x76, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, - 0x6d, 0x6f, 0x64, 0x65, 0x3d, 0x24, 0x33, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, - 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x3d, 0x24, 0x34, - 0x20, 0x24, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x0a, 0x20, - 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x64, 0x6f, 0x6e, 0x65, 0x0a, 0x0a, 0x6d, 0x65, 0x6e, 0x75, 0x65, - 0x6e, 0x74, 0x72, 0x79, 0x20, 0x27, 0x55, 0x45, 0x46, 0x49, 0x20, 0x46, 0x69, 0x72, 0x6d, 0x77, - 0x61, 0x72, 0x65, 0x20, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x27, 0x20, 0x2d, 0x2d, - 0x68, 0x6f, 0x74, 0x6b, 0x65, 0x79, 0x3d, 0x66, 0x20, 0x27, 0x75, 0x65, 0x66, 0x69, 0x2d, 0x66, - 0x69, 0x72, 0x6d, 0x77, 0x61, 0x72, 0x65, 0x27, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, - 0x77, 0x73, 0x65, 0x74, 0x75, 0x70, 0x0a, 0x7d, 0x0a, + 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x65, 0x78, 0x74, + 0x72, 0x61, 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x20, + 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x66, 0x75, 0x6c, 0x6c, 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, + 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x20, + 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x3d, 0x22, 0x24, 0x73, + 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x69, 0x63, 0x5f, 0x63, 0x6d, 0x64, 0x6c, + 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x20, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, + 0x65, 0x78, 0x74, 0x72, 0x61, 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, + 0x67, 0x73, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x5b, 0x20, 0x2d, 0x6e, 0x20, + 0x22, 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x66, 0x75, 0x6c, 0x6c, 0x5f, 0x63, 0x6d, 0x64, + 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x22, 0x20, 0x5d, 0x3b, 0x20, 0x74, 0x68, + 0x65, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x20, 0x63, 0x6d, + 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, 0x72, 0x67, 0x73, 0x3d, 0x22, 0x24, 0x73, 0x6e, 0x61, + 0x70, 0x64, 0x5f, 0x66, 0x75, 0x6c, 0x6c, 0x5f, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, + 0x61, 0x72, 0x67, 0x73, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x69, 0x0a, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x23, 0x20, 0x57, 0x65, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x22, 0x73, 0x6f, + 0x75, 0x72, 0x63, 0x65, 0x20, 0x2f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x24, 0x73, + 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x73, 0x79, + 0x73, 0x74, 0x65, 0x6d, 0x2f, 0x67, 0x72, 0x75, 0x62, 0x2e, 0x63, 0x66, 0x67, 0x22, 0x20, 0x68, + 0x65, 0x72, 0x65, 0x20, 0x61, 0x73, 0x20, 0x77, 0x65, 0x6c, 0x6c, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x6d, 0x65, 0x6e, 0x75, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x20, 0x22, 0x52, 0x65, 0x63, 0x6f, 0x76, + 0x65, 0x72, 0x20, 0x75, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x22, + 0x20, 0x2d, 0x2d, 0x68, 0x6f, 0x74, 0x6b, 0x65, 0x79, 0x3d, 0x72, 0x20, 0x2d, 0x2d, 0x69, 0x64, + 0x3d, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x2d, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, + 0x24, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, + 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x20, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x24, + 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x6c, 0x6f, 0x6f, 0x70, 0x62, 0x61, 0x63, 0x6b, 0x20, 0x6c, 0x6f, 0x6f, 0x70, 0x20, 0x24, 0x32, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x6c, 0x6f, + 0x61, 0x64, 0x65, 0x72, 0x20, 0x28, 0x6c, 0x6f, 0x6f, 0x70, 0x29, 0x2f, 0x6b, 0x65, 0x72, 0x6e, + 0x65, 0x6c, 0x2e, 0x65, 0x66, 0x69, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, + 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x3d, 0x24, 0x33, 0x20, 0x73, 0x6e, + 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x73, 0x79, 0x73, + 0x74, 0x65, 0x6d, 0x3d, 0x24, 0x34, 0x20, 0x24, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, + 0x61, 0x72, 0x67, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6d, + 0x65, 0x6e, 0x75, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x20, 0x22, 0x49, 0x6e, 0x73, 0x74, 0x61, 0x6c, + 0x6c, 0x20, 0x75, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x22, 0x20, + 0x2d, 0x2d, 0x68, 0x6f, 0x74, 0x6b, 0x65, 0x79, 0x3d, 0x69, 0x20, 0x2d, 0x2d, 0x69, 0x64, 0x3d, + 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x2d, 0x24, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x20, 0x24, + 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6b, + 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x20, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x20, 0x24, 0x6c, + 0x61, 0x62, 0x65, 0x6c, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, + 0x6f, 0x6f, 0x70, 0x62, 0x61, 0x63, 0x6b, 0x20, 0x6c, 0x6f, 0x6f, 0x70, 0x20, 0x24, 0x32, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x6c, 0x6f, 0x61, + 0x64, 0x65, 0x72, 0x20, 0x28, 0x6c, 0x6f, 0x6f, 0x70, 0x29, 0x2f, 0x6b, 0x65, 0x72, 0x6e, 0x65, + 0x6c, 0x2e, 0x65, 0x66, 0x69, 0x20, 0x73, 0x6e, 0x61, 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, + 0x76, 0x65, 0x72, 0x79, 0x5f, 0x6d, 0x6f, 0x64, 0x65, 0x3d, 0x24, 0x33, 0x20, 0x73, 0x6e, 0x61, + 0x70, 0x64, 0x5f, 0x72, 0x65, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x5f, 0x73, 0x79, 0x73, 0x74, + 0x65, 0x6d, 0x3d, 0x24, 0x34, 0x20, 0x24, 0x63, 0x6d, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x5f, 0x61, + 0x72, 0x67, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x64, 0x6f, 0x6e, 0x65, 0x0a, 0x0a, + 0x6d, 0x65, 0x6e, 0x75, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x20, 0x27, 0x55, 0x45, 0x46, 0x49, 0x20, + 0x46, 0x69, 0x72, 0x6d, 0x77, 0x61, 0x72, 0x65, 0x20, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, + 0x73, 0x27, 0x20, 0x2d, 0x2d, 0x68, 0x6f, 0x74, 0x6b, 0x65, 0x79, 0x3d, 0x66, 0x20, 0x27, 0x75, + 0x65, 0x66, 0x69, 0x2d, 0x66, 0x69, 0x72, 0x6d, 0x77, 0x61, 0x72, 0x65, 0x27, 0x20, 0x7b, 0x0a, + 0x20, 0x20, 0x20, 0x20, 0x66, 0x77, 0x73, 0x65, 0x74, 0x75, 0x70, 0x0a, 0x7d, 0x0a, }) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/bootloadertest/bootloadertest.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/bootloadertest/bootloadertest.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/bootloadertest/bootloadertest.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/bootloadertest/bootloadertest.go 2023-03-23 08:10:58.000000000 +0000 @@ -252,11 +252,10 @@ // MockExtractedRunKernelImageMixin implements the // ExtractedRunKernelImageBootloader interface. type MockExtractedRunKernelImageMixin struct { - runKernelImageEnableKernelCalls []snap.PlaceInfo - runKernelImageEnableTryKernelCalls []snap.PlaceInfo - runKernelImageDisableTryKernelCalls []snap.PlaceInfo - runKernelImageEnabledKernel snap.PlaceInfo - runKernelImageEnabledTryKernel snap.PlaceInfo + runKernelImageEnableKernelCalls []snap.PlaceInfo + runKernelImageEnableTryKernelCalls []snap.PlaceInfo + runKernelImageEnabledKernel snap.PlaceInfo + runKernelImageEnabledTryKernel snap.PlaceInfo runKernelImageMockedErrs map[string]error runKernelImageMockedNumCalls map[string]int diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/export_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/export_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/export_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/export_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -123,17 +123,41 @@ lkBootDisk := &disks.MockDiskMapping{ // mock the partition labels, since these structures won't have // filesystems, but they will have partition labels - PartitionLabelToPartUUID: map[string]string{ - "snapbootsel": "snapbootsel-partuuid", - "snapbootselbak": "snapbootselbak-partuuid", - "snaprecoverysel": "snaprecoverysel-partuuid", - "snaprecoveryselbak": "snaprecoveryselbak-partuuid", + Structure: []disks.Partition{ + { + PartitionLabel: "snapbootsel", + PartitionUUID: "snapbootsel-partuuid", + }, + { + PartitionLabel: "snapbootselbak", + PartitionUUID: "snapbootselbak-partuuid", + }, + { + PartitionLabel: "snaprecoverysel", + PartitionUUID: "snaprecoverysel-partuuid", + }, + { + PartitionLabel: "snaprecoveryselbak", + PartitionUUID: "snaprecoveryselbak-partuuid", + }, // for run mode kernel snaps - "boot_a": "boot-a-partuuid", - "boot_b": "boot-b-partuuid", + { + PartitionLabel: "boot_a", + PartitionUUID: "boot-a-partuuid", + }, + { + PartitionLabel: "boot_b", + PartitionUUID: "boot-b-partuuid", + }, // for recovery system kernel snaps - "boot_ra": "boot-ra-partuuid", - "boot_rb": "boot-rb-partuuid", + { + PartitionLabel: "boot_ra", + PartitionUUID: "boot-ra-partuuid", + }, + { + PartitionLabel: "boot_rb", + PartitionUUID: "boot-rb-partuuid", + }, }, DiskHasPartitions: true, DevNum: "lk-boot-disk-dev-num", @@ -144,7 +168,7 @@ } // mock the disk - r := disks.MockDeviceNameDisksToPartitionMapping(m) + r := disks.MockDeviceNameToDiskMapping(m) cleanups = append(cleanups, r) // now mock the kernel command line diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/grub.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/grub.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/grub.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/grub.go 2023-03-23 08:10:58.000000000 +0000 @@ -81,13 +81,13 @@ return filepath.Join(g.rootdir, g.basedir) } -func (g *grub) installManagedRecoveryBootConfig(gadgetDir string) error { +func (g *grub) installManagedRecoveryBootConfig() error { assetName := g.Name() + "-recovery.cfg" systemFile := filepath.Join(g.rootdir, "/EFI/ubuntu/grub.cfg") return genericSetBootConfigFromAsset(systemFile, assetName) } -func (g *grub) installManagedBootConfig(gadgetDir string) error { +func (g *grub) installManagedBootConfig() error { assetName := g.Name() + ".cfg" systemFile := filepath.Join(g.rootdir, "/EFI/ubuntu/grub.cfg") return genericSetBootConfigFromAsset(systemFile, assetName) @@ -96,11 +96,11 @@ func (g *grub) InstallBootConfig(gadgetDir string, opts *Options) error { if opts != nil && opts.Role == RoleRecovery { // install managed config for the recovery partition - return g.installManagedRecoveryBootConfig(gadgetDir) + return g.installManagedRecoveryBootConfig() } if opts != nil && opts.Role == RoleRunMode { // install managed boot config that can handle kernel.efi - return g.installManagedBootConfig(gadgetDir) + return g.installManagedBootConfig() } gadgetFile := filepath.Join(gadgetDir, g.Name()+".conf") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/lkenv/lkenv.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/lkenv/lkenv.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/lkenv/lkenv.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/lkenv/lkenv.go 2023-03-23 08:10:58.000000000 +0000 @@ -529,17 +529,6 @@ // a mapping of boot image partition label to either a kernel revision or a // recovery system label. -// bootimgKernelMatrix is essentially a map of boot image partition label to -// kernel revision, but implemented as a matrix of byte arrays, where the first -// row of the matrix is the boot image partition label and the second row is the -// corresponding kernel revision (for a given column). -type bootimgKernelMatrix [SNAP_BOOTIMG_PART_NUM][2][SNAP_FILE_NAME_MAX_LEN]byte - -// bootimgRecoverySystemMatrix is the same idea as bootimgKernelMatrix, but -// instead of mapping boot image partition labels to kernel revisions, it maps -// to recovery system labels for UC20. -type bootimgRecoverySystemMatrix [SNAP_RECOVERY_BOOTIMG_PART_NUM][2][SNAP_FILE_NAME_MAX_LEN]byte - // bootimgMatrixGeneric is a generic slice version of the above two matrix types // which are both statically sized arrays, and thus not able to be used // interchangeably while the slice is. diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/lk.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/lk.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/bootloader/lk.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/bootloader/lk.go 2023-03-23 08:10:58.000000000 +0000 @@ -26,13 +26,14 @@ "os" "path/filepath" + "golang.org/x/xerrors" + "github.com/snapcore/snapd/bootloader/lkenv" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/logger" "github.com/snapcore/snapd/osutil" "github.com/snapcore/snapd/osutil/disks" "github.com/snapcore/snapd/snap" - "golang.org/x/xerrors" ) const ( diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/build-aux/snap/snapcraft.yaml ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/build-aux/snap/snapcraft.yaml --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/build-aux/snap/snapcraft.yaml 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/build-aux/snap/snapcraft.yaml 2023-03-23 08:10:58.000000000 +0000 @@ -29,9 +29,13 @@ snapd-deb: plugin: nil source: . - build-snaps: [go/1.10/stable] + build-snaps: [go/1.13/stable] override-pull: | snapcraftctl pull + # Ensure that ./debian/ packaging which we are about to use + # matches the current `build-base` release. I.e. ubuntu-16.04 + # for build-base:core, etc. + ./generate-packaging-dir # install build dependencies export DEBIAN_FRONTEND=noninteractive export DEBCONF_NONINTERACTIVE_SEEN=true @@ -90,6 +94,7 @@ stage-packages: - libc6 - libc-bin + - libgcc1 stage: - lib/* - usr/lib/* diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/.clang-format ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/.clang-format --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/.clang-format 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/.clang-format 2023-03-23 08:10:58.000000000 +0000 @@ -1,3 +1,4 @@ BasedOnStyle: Google IndentWidth: 4 ColumnLimit: 120 +IncludeBlocks: Preserve diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/apps.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/apps.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/apps.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/apps.go 2023-03-23 08:10:58.000000000 +0000 @@ -108,8 +108,22 @@ PID string `json:"pid"` // The process identifier } +// String will format the log entry with the timestamp in the local timezone func (l Log) String() string { - return fmt.Sprintf("%s %s[%s]: %s", l.Timestamp.Format(time.RFC3339), l.SID, l.PID, l.Message) + return l.fmtLog(time.Local) +} + +// StringInUTC will format the log entry with the timestamp in UTC +func (l Log) StringInUTC() string { + return l.fmtLog(time.UTC) +} + +func (l Log) fmtLog(timezone *time.Location) string { + if timezone == nil { + timezone = time.Local + } + + return fmt.Sprintf("%s %s[%s]: %s", l.Timestamp.In(timezone).Format(time.RFC3339), l.SID, l.PID, l.Message) } // Logs asks for the logs of a series of services, by name. diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/asserts.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/asserts.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/asserts.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/asserts.go 2023-03-23 08:10:58.000000000 +0000 @@ -29,7 +29,8 @@ "golang.org/x/xerrors" - "github.com/snapcore/snapd/asserts" // for parsing + // for parsing + "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/snap" ) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/asserts_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/asserts_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/asserts_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/asserts_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -26,7 +26,6 @@ "net/url" "golang.org/x/xerrors" - . "gopkg.in/check.v1" "github.com/snapcore/snapd/asserts" diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/client.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/client.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/client.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/client.go 2023-03-23 08:10:58.000000000 +0000 @@ -23,6 +23,7 @@ "bytes" "context" "encoding/json" + "errors" "fmt" "io" "io/ioutil" @@ -175,10 +176,15 @@ return fmt.Sprintf("cannot build request: %v", e.error) } -type AuthorizationError struct{ error } +type AuthorizationError struct{ Err error } func (e AuthorizationError) Error() string { - return fmt.Sprintf("cannot add authorization: %v", e.error) + return fmt.Sprintf("cannot add authorization: %v", e.Err) +} + +func (e AuthorizationError) Is(target error) bool { + _, ok := target.(AuthorizationError) + return ok } type ConnectionError struct{ Err error } @@ -200,6 +206,17 @@ return e.Err } +type InternalClientError struct{ Err error } + +func (e InternalClientError) Error() string { + return fmt.Sprintf("internal error: %s", e.Err.Error()) +} + +func (e InternalClientError) Is(target error) bool { + _, ok := target.(InternalClientError) + return ok +} + // AllowInteractionHeader is the HTTP request header used to indicate // that the client is willing to allow interaction. const AllowInteractionHeader = "X-Allow-Interaction" @@ -267,7 +284,7 @@ func (client *Client) rawWithTimeout(ctx context.Context, method, urlpath string, query url.Values, headers map[string]string, body io.Reader, opts *doOptions) (*http.Response, context.CancelFunc, error) { opts = ensureDoOpts(opts) if opts.Timeout <= 0 { - return nil, nil, fmt.Errorf("internal error: timeout not set in options for rawWithTimeout") + return nil, nil, InternalClientError{fmt.Errorf("timeout not set in options for rawWithTimeout")} } ctx, cancel := context.WithTimeout(ctx, opts.Timeout) @@ -349,13 +366,13 @@ client.checkMaintenanceJSON() var rsp *http.Response - var ctx context.Context = context.Background() + ctx := context.Background() if opts.Timeout <= 0 { // no timeout and retries rsp, err = client.raw(ctx, method, path, query, headers, body) } else { if opts.Retry <= 0 { - return 0, fmt.Errorf("internal error: retry setting %s invalid", opts.Retry) + return 0, InternalClientError{fmt.Errorf("retry setting %s invalid", opts.Retry)} } retry := time.NewTicker(opts.Retry) defer retry.Stop() @@ -371,7 +388,7 @@ if err == nil { defer cancel() } - if err == nil || method != "GET" { + if err == nil || shouldNotRetryError(err) || method != "GET" { break } select { @@ -396,6 +413,11 @@ return rsp.StatusCode, nil } +func shouldNotRetryError(err error) bool { + return errors.Is(err, AuthorizationError{}) || + errors.Is(err, InternalClientError{}) +} + func decodeInto(reader io.Reader, v interface{}) error { dec := json.NewDecoder(reader) if err := dec.Decode(v); err != nil { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/client_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/client_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/client_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/client_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -225,6 +225,26 @@ c.Assert(cs.doCalls < 1100, Equals, true, Commentf("got %v calls", cs.doCalls)) } +func (cs *clientSuite) TestClientOnlyRetryAppropriateErrors(c *C) { + reqBody := ioutil.NopCloser(strings.NewReader("")) + doOpts := &client.DoOptions{ + Retry: time.Millisecond, + Timeout: 1 * time.Minute, + } + + for _, t := range []struct{ error }{ + {client.InternalClientError{Err: fmt.Errorf("boom")}}, + {client.AuthorizationError{Err: fmt.Errorf("boom")}}, + } { + cs.doCalls = 0 + cs.err = t.error + + _, err := cs.cli.Do("GET", "/this", nil, reqBody, nil, doOpts) + c.Check(err, ErrorMatches, fmt.Sprintf(".*%s", t.error.Error())) + c.Assert(cs.doCalls, Equals, 1) + } +} + func (cs *clientSuite) TestClientUnderstandsStatusCode(c *C) { var v []int cs.status = 202 diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/clientutil/snapinfo.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/clientutil/snapinfo.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/clientutil/snapinfo.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/clientutil/snapinfo.go 2023-03-23 08:10:58.000000000 +0000 @@ -74,7 +74,7 @@ Confinement: string(confinement), Apps: apps, Broken: snapInfo.Broken, - Contact: snapInfo.Contact, + Contact: snapInfo.Contact(), Title: snapInfo.Title(), License: snapInfo.License, Media: snapInfo.Media, diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/clientutil/snapinfo_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/clientutil/snapinfo_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/clientutil/snapinfo_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/clientutil/snapinfo_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -72,7 +72,7 @@ EditedSummary: "the-summary", EditedDescription: "the-description", Channel: "latest/stable", - Contact: "https://thingy.com", + EditedContact: "https://thingy.com", Private: true, }, Channels: map[string]*snap.ChannelSnapInfo{}, diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/cohort_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/cohort_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/cohort_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/cohort_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -25,7 +25,6 @@ "io/ioutil" "golang.org/x/xerrors" - "gopkg.in/check.v1" ) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/errors.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/errors.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/errors.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/errors.go 2023-03-23 08:10:58.000000000 +0000 @@ -104,6 +104,13 @@ // `snap-name`, `change-kind` of the ongoing change. ErrorKindSnapChangeConflict ErrorKind = "snap-change-conflict" + // ErrorKindQuotaChangeConflict: the requested operation would + // conflict with a currently ongoing change affecting the quota + // group. This is a temporary error. The error `value` is an + // object with optional fields `quota-name`, `change-kind` of the + // ongoing change. + ErrorKindQuotaChangeConflict ErrorKind = "quota-change-conflict" + // ErrorKindNotSnap: the given snap or directory does not // look like a snap. ErrorKindNotSnap ErrorKind = "snap-not-a-snap" diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/icons_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/icons_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/icons_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/icons_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -25,7 +25,6 @@ "net/http" "golang.org/x/xerrors" - . "gopkg.in/check.v1" ) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/interfaces_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/interfaces_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/interfaces_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/interfaces_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -70,7 +70,7 @@ } func (cs *clientSuite) TestClientInterfacesConnected(c *check.C) { - // Ask for for a summary of connected interfaces. + // Ask for a summary of connected interfaces. cs.rsp = `{ "type": "sync", "result": [ diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/model_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/model_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/model_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/model_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -26,7 +26,6 @@ "net/http" "golang.org/x/xerrors" - . "gopkg.in/check.v1" "github.com/snapcore/snapd/asserts" diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/quota.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/quota.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/quota.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/quota.go 2023-03-23 08:10:58.000000000 +0000 @@ -24,30 +24,35 @@ "encoding/json" "fmt" - "golang.org/x/xerrors" + "github.com/snapcore/snapd/gadget/quantity" ) type postQuotaData struct { - Action string `json:"action"` - GroupName string `json:"group-name"` - Parent string `json:"parent,omitempty"` - Snaps []string `json:"snaps,omitempty"` - MaxMemory uint64 `json:"max-memory,omitempty"` + Action string `json:"action"` + GroupName string `json:"group-name"` + Parent string `json:"parent,omitempty"` + Snaps []string `json:"snaps,omitempty"` + Constraints *QuotaValues `json:"constraints,omitempty"` } type QuotaGroupResult struct { - GroupName string `json:"group-name"` - Parent string `json:"parent,omitempty"` - Subgroups []string `json:"subgroups,omitempty"` - Snaps []string `json:"snaps,omitempty"` - MaxMemory uint64 `json:"max-memory"` + GroupName string `json:"group-name"` + Parent string `json:"parent,omitempty"` + Subgroups []string `json:"subgroups,omitempty"` + Snaps []string `json:"snaps,omitempty"` + Constraints *QuotaValues `json:"constraints,omitempty"` + Current *QuotaValues `json:"current,omitempty"` +} + +type QuotaValues struct { + Memory quantity.Size `json:"memory,omitempty"` } // EnsureQuota creates a quota group or updates an existing group. // The list of snaps can be empty. -func (client *Client) EnsureQuota(groupName string, parent string, snaps []string, maxMemory uint64) error { +func (client *Client) EnsureQuota(groupName string, parent string, snaps []string, maxMemory quantity.Size) (changeID string, err error) { if groupName == "" { - return xerrors.Errorf("cannot create or update quota group without a name") + return "", fmt.Errorf("cannot create or update quota group without a name") } // TODO: use naming.ValidateQuotaGroup() @@ -56,23 +61,26 @@ GroupName: groupName, Parent: parent, Snaps: snaps, - MaxMemory: maxMemory, + Constraints: &QuotaValues{ + Memory: maxMemory, + }, } var body bytes.Buffer if err := json.NewEncoder(&body).Encode(data); err != nil { - return err + return "", err } - if _, err := client.doSync("POST", "/v2/quotas", nil, nil, &body, nil); err != nil { - fmt := "cannot create or update quota group: %w" - return xerrors.Errorf(fmt, err) + chgID, err := client.doAsync("POST", "/v2/quotas", nil, nil, &body) + + if err != nil { + return "", err } - return nil + return chgID, nil } func (client *Client) GetQuotaGroup(groupName string) (*QuotaGroupResult, error) { if groupName == "" { - return nil, xerrors.Errorf("cannot get quota group without a name") + return nil, fmt.Errorf("cannot get quota group without a name") } var res *QuotaGroupResult @@ -80,12 +88,13 @@ if _, err := client.doSync("GET", path, nil, nil, nil, &res); err != nil { return nil, err } + return res, nil } -func (client *Client) RemoveQuotaGroup(groupName string) error { +func (client *Client) RemoveQuotaGroup(groupName string) (changeID string, err error) { if groupName == "" { - return xerrors.Errorf("cannot remove quota group without a name") + return "", fmt.Errorf("cannot remove quota group without a name") } data := &postQuotaData{ Action: "remove", @@ -94,12 +103,14 @@ var body bytes.Buffer if err := json.NewEncoder(&body).Encode(data); err != nil { - return err + return "", err } - if _, err := client.doSync("POST", "/v2/quotas", nil, nil, &body, nil); err != nil { - return err + chgID, err := client.doAsync("POST", "/v2/quotas", nil, nil, &body) + if err != nil { + return "", fmt.Errorf("cannot remove quota group: %w", err) } - return nil + + return chgID, nil } func (client *Client) Quotas() ([]*QuotaGroupResult, error) { @@ -107,5 +118,6 @@ if _, err := client.doSync("GET", "/v2/quotas", nil, nil, nil, &res); err != nil { return nil, err } + return res, nil } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/quota_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/quota_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/quota_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/quota_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -20,47 +20,56 @@ package client_test import ( + "bytes" "encoding/json" "io/ioutil" "gopkg.in/check.v1" "github.com/snapcore/snapd/client" + "github.com/snapcore/snapd/gadget/quantity" + "github.com/snapcore/snapd/jsonutil" ) func (cs *clientSuite) TestCreateQuotaGroupInvalidName(c *check.C) { - err := cs.cli.EnsureQuota("", "", nil, 0) + _, err := cs.cli.EnsureQuota("", "", nil, 0) c.Check(err, check.ErrorMatches, `cannot create or update quota group without a name`) } func (cs *clientSuite) TestEnsureQuotaGroup(c *check.C) { + cs.status = 202 cs.rsp = `{ - "type": "sync", - "status-code": 200 + "type": "async", + "status-code": 202, + "change": "42" }` - c.Assert(cs.cli.EnsureQuota("foo", "bar", []string{"snap-a", "snap-b"}, 1001), check.IsNil) + chgID, err := cs.cli.EnsureQuota("foo", "bar", []string{"snap-a", "snap-b"}, 1001) + c.Assert(err, check.IsNil) + c.Assert(chgID, check.Equals, "42") c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/quotas") body, err := ioutil.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} - err = json.Unmarshal(body, &req) + err = jsonutil.DecodeWithNumber(bytes.NewReader(body), &req) c.Assert(err, check.IsNil) c.Assert(req, check.DeepEquals, map[string]interface{}{ "action": "ensure", "group-name": "foo", "parent": "bar", "snaps": []interface{}{"snap-a", "snap-b"}, - "max-memory": float64(1001), + "constraints": map[string]interface{}{ + "memory": json.Number("1001"), + }, }) } func (cs *clientSuite) TestEnsureQuotaGroupError(c *check.C) { cs.status = 500 cs.rsp = `{"type": "error"}` - err := cs.cli.EnsureQuota("foo", "bar", []string{"snap-a"}, 1) - c.Check(err, check.ErrorMatches, `cannot create or update quota group: server error: "Internal Server Error"`) + _, err := cs.cli.EnsureQuota("foo", "bar", []string{"snap-a"}, 1) + c.Check(err, check.ErrorMatches, `server error: "Internal Server Error"`) } func (cs *clientSuite) TestGetQuotaGroupInvalidName(c *check.C) { @@ -72,7 +81,14 @@ cs.rsp = `{ "type": "sync", "status-code": 200, - "result": {"group-name":"foo", "parent":"bar", "subgroups":["foo-subgrp"], "snaps":["snap-a"], "max-memory":999} + "result": { + "group-name":"foo", + "parent":"bar", + "subgroups":["foo-subgrp"], + "snaps":["snap-a"], + "constraints": { "memory": 999 }, + "current": { "memory": 450 } + } }` grp, err := cs.cli.GetQuotaGroup("foo") @@ -80,11 +96,12 @@ c.Check(cs.req.Method, check.Equals, "GET") c.Check(cs.req.URL.Path, check.Equals, "/v2/quotas/foo") c.Check(grp, check.DeepEquals, &client.QuotaGroupResult{ - GroupName: "foo", - Parent: "bar", - Subgroups: []string{"foo-subgrp"}, - MaxMemory: 999, - Snaps: []string{"snap-a"}, + GroupName: "foo", + Parent: "bar", + Subgroups: []string{"foo-subgrp"}, + Constraints: &client.QuotaValues{Memory: quantity.Size(999)}, + Current: &client.QuotaValues{Memory: quantity.Size(450)}, + Snaps: []string{"snap-a"}, }) } @@ -96,13 +113,16 @@ } func (cs *clientSuite) TestRemoveQuotaGroup(c *check.C) { + cs.status = 202 cs.rsp = `{ - "type": "sync", - "status-code": 200 + "type": "async", + "status-code": 202, + "change": "42" }` - err := cs.cli.RemoveQuotaGroup("foo") + chgID, err := cs.cli.RemoveQuotaGroup("foo") c.Assert(err, check.IsNil) + c.Assert(chgID, check.Equals, "42") c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/quotas") body, err := ioutil.ReadAll(cs.req.Body) @@ -119,6 +139,6 @@ func (cs *clientSuite) TestRemoveQuotaGroupError(c *check.C) { cs.status = 500 cs.rsp = `{"type": "error"}` - err := cs.cli.RemoveQuotaGroup("foo") - c.Check(err, check.ErrorMatches, `server error: "Internal Server Error"`) + _, err := cs.cli.RemoveQuotaGroup("foo") + c.Check(err, check.ErrorMatches, `cannot remove quota group: server error: "Internal Server Error"`) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/snapctl_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/snapctl_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/client/snapctl_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/client/snapctl_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -24,9 +24,9 @@ "encoding/base64" "encoding/json" - "github.com/snapcore/snapd/client" - "gopkg.in/check.v1" + + "github.com/snapcore/snapd/client" ) func (cs *clientSuite) TestClientRunSnapctlCallsEndpoint(c *check.C) { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/autogen.sh ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/autogen.sh --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/autogen.sh 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/autogen.sh 2023-03-23 08:10:58.000000000 +0000 @@ -44,7 +44,10 @@ fedora|centos|rhel) extra_opts="--libexecdir=/usr/libexec/snapd --with-snap-mount-dir=/var/lib/snapd/snap --enable-merged-usr --disable-apparmor --enable-selinux" ;; - opensuse|opensuse-tumbleweed) + opensuse-tumbleweed) + extra_opts="--libexecdir=/usr/libexec/snapd --enable-nvidia-biarch --with-32bit-libdir=/usr/lib --enable-merged-usr" + ;; + opensuse) extra_opts="--libexecdir=/usr/lib/snapd --enable-nvidia-biarch --with-32bit-libdir=/usr/lib --enable-merged-usr" ;; solus) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/.clangd ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/.clangd --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/.clangd 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/.clangd 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,2 @@ +CompileFlags: + Add: -I/usr/include/glib-2.0 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes -Wno-missing-field-initializers -Wno-unused-parameter \ No newline at end of file diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/configure.ac ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/configure.ac --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/configure.ac 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/configure.ac 2023-03-23 08:10:58.000000000 +0000 @@ -226,5 +226,31 @@ SYSTEMD_SYSTEM_ENV_GENERATOR_DIR="${prefix}/lib/systemd/system-environment-generators" AC_SUBST(SYSTEMD_SYSTEM_ENV_GENERATOR_DIR) +AC_ARG_ENABLE([bpf], +AS_HELP_STRING([--enable-bpf], [Enable BPF support]), +[case "${enableval}" in +yes) enable_bpf=yes ;; +no) enable_bpf=no ;; +*) AC_MSG_ERROR([bad value ${enableval} for --enable-bpf]) +esac], +[enable_bpf=yes]) +AM_CONDITIONAL([ENABLE_BPF], [test "x$enable_bpf" = "xyes"]) + +if test "x$enable_bpf" = "xyes"; then +AC_DEFINE([ENABLE_BPF], [1], [Enable BPF support]) +AC_MSG_CHECKING([whether host BPF headers are usable]) +AC_COMPILE_IFELSE([ +#include +void foo(enum bpf_attach_type type) {} +void bar() { struct bpf_cgroup_dev_ctx ctx = {0}; } +], [host_bpf_headers_usable=yes], [host_bpf_headers_usable=no]) +if test "x$host_bpf_headers_usable" = "xyes"; then + AC_MSG_RESULT([yes]) +else + AC_MSG_RESULT([no, using vendored BPF headers]) +fi +fi +AM_CONDITIONAL([USE_INTERNAL_BPF_HEADERS], [test "x$host_bpf_headers_usable" = "xno"]) + AC_CONFIG_FILES([Makefile]) AC_OUTPUT diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/bpf-insn.h ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/bpf-insn.h --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/bpf-insn.h 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/bpf-insn.h 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,311 @@ +/* SPDX-License-Identifier: GPL-2.0 */ + +/* imported from the Linux kernel, commit + * 77d34a4683b053108ecd466cc7c4193b45805528 (v5.13-11855-g77d34a4683b0) */ + +#ifndef __BPF_INSN_H__ +#define __BPF_INSN_H__ + +#include + +/* ALU ops on registers, bpf_add|sub|...: dst_reg += src_reg */ + +#define BPF_ALU64_REG(OP, DST, SRC) \ + ((struct bpf_insn) { \ + .code = BPF_ALU64 | BPF_OP(OP) | BPF_X, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = 0, \ + .imm = 0 }) + +#define BPF_ALU32_REG(OP, DST, SRC) \ + ((struct bpf_insn) { \ + .code = BPF_ALU | BPF_OP(OP) | BPF_X, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = 0, \ + .imm = 0 }) + +/* ALU ops on immediates, bpf_add|sub|...: dst_reg += imm32 */ + +#define BPF_ALU64_IMM(OP, DST, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_ALU64 | BPF_OP(OP) | BPF_K, \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = 0, \ + .imm = IMM }) + +#define BPF_ALU32_IMM(OP, DST, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_ALU | BPF_OP(OP) | BPF_K, \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = 0, \ + .imm = IMM }) + +/* Endianess conversion, cpu_to_{l,b}e(), {l,b}e_to_cpu() */ + +#define BPF_ENDIAN(TYPE, DST, LEN) \ + ((struct bpf_insn) { \ + .code = BPF_ALU | BPF_END | BPF_SRC(TYPE), \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = 0, \ + .imm = LEN }) + +/* Short form of mov, dst_reg = src_reg */ + +#define BPF_MOV64_REG(DST, SRC) \ + ((struct bpf_insn) { \ + .code = BPF_ALU64 | BPF_MOV | BPF_X, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = 0, \ + .imm = 0 }) + +#define BPF_MOV32_REG(DST, SRC) \ + ((struct bpf_insn) { \ + .code = BPF_ALU | BPF_MOV | BPF_X, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = 0, \ + .imm = 0 }) + +/* Short form of mov, dst_reg = imm32 */ + +#define BPF_MOV64_IMM(DST, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_ALU64 | BPF_MOV | BPF_K, \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = 0, \ + .imm = IMM }) + +#define BPF_MOV32_IMM(DST, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_ALU | BPF_MOV | BPF_K, \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = 0, \ + .imm = IMM }) + +/* Special form of mov32, used for doing explicit zero extension on dst. */ +#define BPF_ZEXT_REG(DST) \ + ((struct bpf_insn) { \ + .code = BPF_ALU | BPF_MOV | BPF_X, \ + .dst_reg = DST, \ + .src_reg = DST, \ + .off = 0, \ + .imm = 1 }) + +/* BPF_LD_IMM64 macro encodes single 'load 64-bit immediate' insn */ +#define BPF_LD_IMM64(DST, IMM) \ + BPF_LD_IMM64_RAW(DST, 0, IMM) + +#define BPF_LD_IMM64_RAW(DST, SRC, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_LD | BPF_DW | BPF_IMM, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = 0, \ + .imm = (__u32) (IMM) }), \ + ((struct bpf_insn) { \ + .code = 0, /* zero is reserved opcode */ \ + .dst_reg = 0, \ + .src_reg = 0, \ + .off = 0, \ + .imm = ((__u64) (IMM)) >> 32 }) + +/* pseudo BPF_LD_IMM64 insn used to refer to process-local map_fd */ +#define BPF_LD_MAP_FD(DST, MAP_FD) \ + BPF_LD_IMM64_RAW(DST, BPF_PSEUDO_MAP_FD, MAP_FD) + +/* Short form of mov based on type, BPF_X: dst_reg = src_reg, BPF_K: dst_reg = imm32 */ + +#define BPF_MOV64_RAW(TYPE, DST, SRC, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_ALU64 | BPF_MOV | BPF_SRC(TYPE), \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = 0, \ + .imm = IMM }) + +#define BPF_MOV32_RAW(TYPE, DST, SRC, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_ALU | BPF_MOV | BPF_SRC(TYPE), \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = 0, \ + .imm = IMM }) + +/* Direct packet access, R0 = *(uint *) (skb->data + imm32) */ + +#define BPF_LD_ABS(SIZE, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_LD | BPF_SIZE(SIZE) | BPF_ABS, \ + .dst_reg = 0, \ + .src_reg = 0, \ + .off = 0, \ + .imm = IMM }) + +/* Indirect packet access, R0 = *(uint *) (skb->data + src_reg + imm32) */ + +#define BPF_LD_IND(SIZE, SRC, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_LD | BPF_SIZE(SIZE) | BPF_IND, \ + .dst_reg = 0, \ + .src_reg = SRC, \ + .off = 0, \ + .imm = IMM }) + +/* Memory load, dst_reg = *(uint *) (src_reg + off16) */ + +#define BPF_LDX_MEM(SIZE, DST, SRC, OFF) \ + ((struct bpf_insn) { \ + .code = BPF_LDX | BPF_SIZE(SIZE) | BPF_MEM, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = OFF, \ + .imm = 0 }) + +/* Memory store, *(uint *) (dst_reg + off16) = src_reg */ + +#define BPF_STX_MEM(SIZE, DST, SRC, OFF) \ + ((struct bpf_insn) { \ + .code = BPF_STX | BPF_SIZE(SIZE) | BPF_MEM, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = OFF, \ + .imm = 0 }) + +/* + * Atomic operations: + * + * BPF_ADD *(uint *) (dst_reg + off16) += src_reg + * BPF_AND *(uint *) (dst_reg + off16) &= src_reg + * BPF_OR *(uint *) (dst_reg + off16) |= src_reg + * BPF_XOR *(uint *) (dst_reg + off16) ^= src_reg + * BPF_ADD | BPF_FETCH src_reg = atomic_fetch_add(dst_reg + off16, src_reg); + * BPF_AND | BPF_FETCH src_reg = atomic_fetch_and(dst_reg + off16, src_reg); + * BPF_OR | BPF_FETCH src_reg = atomic_fetch_or(dst_reg + off16, src_reg); + * BPF_XOR | BPF_FETCH src_reg = atomic_fetch_xor(dst_reg + off16, src_reg); + * BPF_XCHG src_reg = atomic_xchg(dst_reg + off16, src_reg) + * BPF_CMPXCHG r0 = atomic_cmpxchg(dst_reg + off16, r0, src_reg) + */ + +#define BPF_ATOMIC_OP(SIZE, OP, DST, SRC, OFF) \ + ((struct bpf_insn) { \ + .code = BPF_STX | BPF_SIZE(SIZE) | BPF_ATOMIC, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = OFF, \ + .imm = OP }) + +/* Legacy alias */ +#define BPF_STX_XADD(SIZE, DST, SRC, OFF) BPF_ATOMIC_OP(SIZE, BPF_ADD, DST, SRC, OFF) + +/* Memory store, *(uint *) (dst_reg + off16) = imm32 */ + +#define BPF_ST_MEM(SIZE, DST, OFF, IMM) \ + ((struct bpf_insn) { \ + .code = BPF_ST | BPF_SIZE(SIZE) | BPF_MEM, \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = OFF, \ + .imm = IMM }) + +/* Conditional jumps against registers, if (dst_reg 'op' src_reg) goto pc + off16 */ + +#define BPF_JMP_REG(OP, DST, SRC, OFF) \ + ((struct bpf_insn) { \ + .code = BPF_JMP | BPF_OP(OP) | BPF_X, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = OFF, \ + .imm = 0 }) + +/* Conditional jumps against immediates, if (dst_reg 'op' imm32) goto pc + off16 */ + +#define BPF_JMP_IMM(OP, DST, IMM, OFF) \ + ((struct bpf_insn) { \ + .code = BPF_JMP | BPF_OP(OP) | BPF_K, \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = OFF, \ + .imm = IMM }) + +/* Like BPF_JMP_REG, but with 32-bit wide operands for comparison. */ + +#define BPF_JMP32_REG(OP, DST, SRC, OFF) \ + ((struct bpf_insn) { \ + .code = BPF_JMP32 | BPF_OP(OP) | BPF_X, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = OFF, \ + .imm = 0 }) + +/* Like BPF_JMP_IMM, but with 32-bit wide operands for comparison. */ + +#define BPF_JMP32_IMM(OP, DST, IMM, OFF) \ + ((struct bpf_insn) { \ + .code = BPF_JMP32 | BPF_OP(OP) | BPF_K, \ + .dst_reg = DST, \ + .src_reg = 0, \ + .off = OFF, \ + .imm = IMM }) + +/* Unconditional jumps, goto pc + off16 */ + +#define BPF_JMP_A(OFF) \ + ((struct bpf_insn) { \ + .code = BPF_JMP | BPF_JA, \ + .dst_reg = 0, \ + .src_reg = 0, \ + .off = OFF, \ + .imm = 0 }) + +/* Relative call */ + +#define BPF_CALL_REL(TGT) \ + ((struct bpf_insn) { \ + .code = BPF_JMP | BPF_CALL, \ + .dst_reg = 0, \ + .src_reg = BPF_PSEUDO_CALL, \ + .off = 0, \ + .imm = TGT }) + +/* Function call */ + +#define BPF_CAST_CALL(x) \ + ((u64 (*)(u64, u64, u64, u64, u64))(x)) + +#define BPF_EMIT_CALL(FUNC) \ + ((struct bpf_insn) { \ + .code = BPF_JMP | BPF_CALL, \ + .dst_reg = 0, \ + .src_reg = 0, \ + .off = 0, \ + .imm = ((FUNC) - __bpf_call_base) }) + +/* Raw code statement block */ + +#define BPF_RAW_INSN(CODE, DST, SRC, OFF, IMM) \ + ((struct bpf_insn) { \ + .code = CODE, \ + .dst_reg = DST, \ + .src_reg = SRC, \ + .off = OFF, \ + .imm = IMM }) + +/* Program exit */ + +#define BPF_EXIT_INSN() \ + ((struct bpf_insn) { \ + .code = BPF_JMP | BPF_EXIT, \ + .dst_reg = 0, \ + .src_reg = 0, \ + .off = 0, \ + .imm = 0 }) + +#endif /* __BPF_INSN_H__ */ diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/vendor/linux/bpf_common.h ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/vendor/linux/bpf_common.h --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/vendor/linux/bpf_common.h 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/vendor/linux/bpf_common.h 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef _UAPI__LINUX_BPF_COMMON_H__ +#define _UAPI__LINUX_BPF_COMMON_H__ + +/* Instruction classes */ +#define BPF_CLASS(code) ((code) & 0x07) +#define BPF_LD 0x00 +#define BPF_LDX 0x01 +#define BPF_ST 0x02 +#define BPF_STX 0x03 +#define BPF_ALU 0x04 +#define BPF_JMP 0x05 +#define BPF_RET 0x06 +#define BPF_MISC 0x07 + +/* ld/ldx fields */ +#define BPF_SIZE(code) ((code) & 0x18) +#define BPF_W 0x00 /* 32-bit */ +#define BPF_H 0x08 /* 16-bit */ +#define BPF_B 0x10 /* 8-bit */ +/* eBPF BPF_DW 0x18 64-bit */ +#define BPF_MODE(code) ((code) & 0xe0) +#define BPF_IMM 0x00 +#define BPF_ABS 0x20 +#define BPF_IND 0x40 +#define BPF_MEM 0x60 +#define BPF_LEN 0x80 +#define BPF_MSH 0xa0 + +/* alu/jmp fields */ +#define BPF_OP(code) ((code) & 0xf0) +#define BPF_ADD 0x00 +#define BPF_SUB 0x10 +#define BPF_MUL 0x20 +#define BPF_DIV 0x30 +#define BPF_OR 0x40 +#define BPF_AND 0x50 +#define BPF_LSH 0x60 +#define BPF_RSH 0x70 +#define BPF_NEG 0x80 +#define BPF_MOD 0x90 +#define BPF_XOR 0xa0 + +#define BPF_JA 0x00 +#define BPF_JEQ 0x10 +#define BPF_JGT 0x20 +#define BPF_JGE 0x30 +#define BPF_JSET 0x40 +#define BPF_SRC(code) ((code) & 0x08) +#define BPF_K 0x00 +#define BPF_X 0x08 + +#ifndef BPF_MAXINSNS +#define BPF_MAXINSNS 4096 +#endif + +#endif /* _UAPI__LINUX_BPF_COMMON_H__ */ diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/vendor/linux/bpf.h ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/vendor/linux/bpf.h --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/vendor/linux/bpf.h 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf/vendor/linux/bpf.h 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,6152 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU General Public + * License as published by the Free Software Foundation. + */ +#ifndef _UAPI__LINUX_BPF_H__ +#define _UAPI__LINUX_BPF_H__ + +#include +#include + +/* Extended instruction set based on top of classic BPF */ + +/* instruction classes */ +#define BPF_JMP32 0x06 /* jmp mode in word width */ +#define BPF_ALU64 0x07 /* alu mode in double word width */ + +/* ld/ldx fields */ +#define BPF_DW 0x18 /* double word (64-bit) */ +#define BPF_ATOMIC 0xc0 /* atomic memory ops - op type in immediate */ +#define BPF_XADD 0xc0 /* exclusive add - legacy name */ + +/* alu/jmp fields */ +#define BPF_MOV 0xb0 /* mov reg to reg */ +#define BPF_ARSH 0xc0 /* sign extending arithmetic shift right */ + +/* change endianness of a register */ +#define BPF_END 0xd0 /* flags for endianness conversion: */ +#define BPF_TO_LE 0x00 /* convert to little-endian */ +#define BPF_TO_BE 0x08 /* convert to big-endian */ +#define BPF_FROM_LE BPF_TO_LE +#define BPF_FROM_BE BPF_TO_BE + +/* jmp encodings */ +#define BPF_JNE 0x50 /* jump != */ +#define BPF_JLT 0xa0 /* LT is unsigned, '<' */ +#define BPF_JLE 0xb0 /* LE is unsigned, '<=' */ +#define BPF_JSGT 0x60 /* SGT is signed '>', GT in x86 */ +#define BPF_JSGE 0x70 /* SGE is signed '>=', GE in x86 */ +#define BPF_JSLT 0xc0 /* SLT is signed, '<' */ +#define BPF_JSLE 0xd0 /* SLE is signed, '<=' */ +#define BPF_CALL 0x80 /* function call */ +#define BPF_EXIT 0x90 /* function return */ + +/* atomic op type fields (stored in immediate) */ +#define BPF_FETCH 0x01 /* not an opcode on its own, used to build others */ +#define BPF_XCHG (0xe0 | BPF_FETCH) /* atomic exchange */ +#define BPF_CMPXCHG (0xf0 | BPF_FETCH) /* atomic compare-and-write */ + +/* Register numbers */ +enum { + BPF_REG_0 = 0, + BPF_REG_1, + BPF_REG_2, + BPF_REG_3, + BPF_REG_4, + BPF_REG_5, + BPF_REG_6, + BPF_REG_7, + BPF_REG_8, + BPF_REG_9, + BPF_REG_10, + __MAX_BPF_REG, +}; + +/* BPF has 10 general purpose 64-bit registers and stack frame. */ +#define MAX_BPF_REG __MAX_BPF_REG + +struct bpf_insn { + __u8 code; /* opcode */ + __u8 dst_reg:4; /* dest register */ + __u8 src_reg:4; /* source register */ + __s16 off; /* signed offset */ + __s32 imm; /* signed immediate constant */ +}; + +/* Key of an a BPF_MAP_TYPE_LPM_TRIE entry */ +struct bpf_lpm_trie_key { + __u32 prefixlen; /* up to 32 for AF_INET, 128 for AF_INET6 */ + __u8 data[0]; /* Arbitrary size */ +}; + +struct bpf_cgroup_storage_key { + __u64 cgroup_inode_id; /* cgroup inode id */ + __u32 attach_type; /* program attach type */ +}; + +union bpf_iter_link_info { + struct { + __u32 map_fd; + } map; +}; + +/* BPF syscall commands, see bpf(2) man-page for more details. */ +/** + * DOC: eBPF Syscall Preamble + * + * The operation to be performed by the **bpf**\ () system call is determined + * by the *cmd* argument. Each operation takes an accompanying argument, + * provided via *attr*, which is a pointer to a union of type *bpf_attr* (see + * below). The size argument is the size of the union pointed to by *attr*. + */ +/** + * DOC: eBPF Syscall Commands + * + * BPF_MAP_CREATE + * Description + * Create a map and return a file descriptor that refers to the + * map. The close-on-exec file descriptor flag (see **fcntl**\ (2)) + * is automatically enabled for the new file descriptor. + * + * Applying **close**\ (2) to the file descriptor returned by + * **BPF_MAP_CREATE** will delete the map (but see NOTES). + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_MAP_LOOKUP_ELEM + * Description + * Look up an element with a given *key* in the map referred to + * by the file descriptor *map_fd*. + * + * The *flags* argument may be specified as one of the + * following: + * + * **BPF_F_LOCK** + * Look up the value of a spin-locked map without + * returning the lock. This must be specified if the + * elements contain a spinlock. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_MAP_UPDATE_ELEM + * Description + * Create or update an element (key/value pair) in a specified map. + * + * The *flags* argument should be specified as one of the + * following: + * + * **BPF_ANY** + * Create a new element or update an existing element. + * **BPF_NOEXIST** + * Create a new element only if it did not exist. + * **BPF_EXIST** + * Update an existing element. + * **BPF_F_LOCK** + * Update a spin_lock-ed map element. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * May set *errno* to **EINVAL**, **EPERM**, **ENOMEM**, + * **E2BIG**, **EEXIST**, or **ENOENT**. + * + * **E2BIG** + * The number of elements in the map reached the + * *max_entries* limit specified at map creation time. + * **EEXIST** + * If *flags* specifies **BPF_NOEXIST** and the element + * with *key* already exists in the map. + * **ENOENT** + * If *flags* specifies **BPF_EXIST** and the element with + * *key* does not exist in the map. + * + * BPF_MAP_DELETE_ELEM + * Description + * Look up and delete an element by key in a specified map. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_MAP_GET_NEXT_KEY + * Description + * Look up an element by key in a specified map and return the key + * of the next element. Can be used to iterate over all elements + * in the map. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * The following cases can be used to iterate over all elements of + * the map: + * + * * If *key* is not found, the operation returns zero and sets + * the *next_key* pointer to the key of the first element. + * * If *key* is found, the operation returns zero and sets the + * *next_key* pointer to the key of the next element. + * * If *key* is the last element, returns -1 and *errno* is set + * to **ENOENT**. + * + * May set *errno* to **ENOMEM**, **EFAULT**, **EPERM**, or + * **EINVAL** on error. + * + * BPF_PROG_LOAD + * Description + * Verify and load an eBPF program, returning a new file + * descriptor associated with the program. + * + * Applying **close**\ (2) to the file descriptor returned by + * **BPF_PROG_LOAD** will unload the eBPF program (but see NOTES). + * + * The close-on-exec file descriptor flag (see **fcntl**\ (2)) is + * automatically enabled for the new file descriptor. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_OBJ_PIN + * Description + * Pin an eBPF program or map referred by the specified *bpf_fd* + * to the provided *pathname* on the filesystem. + * + * The *pathname* argument must not contain a dot ("."). + * + * On success, *pathname* retains a reference to the eBPF object, + * preventing deallocation of the object when the original + * *bpf_fd* is closed. This allow the eBPF object to live beyond + * **close**\ (\ *bpf_fd*\ ), and hence the lifetime of the parent + * process. + * + * Applying **unlink**\ (2) or similar calls to the *pathname* + * unpins the object from the filesystem, removing the reference. + * If no other file descriptors or filesystem nodes refer to the + * same object, it will be deallocated (see NOTES). + * + * The filesystem type for the parent directory of *pathname* must + * be **BPF_FS_MAGIC**. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_OBJ_GET + * Description + * Open a file descriptor for the eBPF object pinned to the + * specified *pathname*. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_PROG_ATTACH + * Description + * Attach an eBPF program to a *target_fd* at the specified + * *attach_type* hook. + * + * The *attach_type* specifies the eBPF attachment point to + * attach the program to, and must be one of *bpf_attach_type* + * (see below). + * + * The *attach_bpf_fd* must be a valid file descriptor for a + * loaded eBPF program of a cgroup, flow dissector, LIRC, sockmap + * or sock_ops type corresponding to the specified *attach_type*. + * + * The *target_fd* must be a valid file descriptor for a kernel + * object which depends on the attach type of *attach_bpf_fd*: + * + * **BPF_PROG_TYPE_CGROUP_DEVICE**, + * **BPF_PROG_TYPE_CGROUP_SKB**, + * **BPF_PROG_TYPE_CGROUP_SOCK**, + * **BPF_PROG_TYPE_CGROUP_SOCK_ADDR**, + * **BPF_PROG_TYPE_CGROUP_SOCKOPT**, + * **BPF_PROG_TYPE_CGROUP_SYSCTL**, + * **BPF_PROG_TYPE_SOCK_OPS** + * + * Control Group v2 hierarchy with the eBPF controller + * enabled. Requires the kernel to be compiled with + * **CONFIG_CGROUP_BPF**. + * + * **BPF_PROG_TYPE_FLOW_DISSECTOR** + * + * Network namespace (eg /proc/self/ns/net). + * + * **BPF_PROG_TYPE_LIRC_MODE2** + * + * LIRC device path (eg /dev/lircN). Requires the kernel + * to be compiled with **CONFIG_BPF_LIRC_MODE2**. + * + * **BPF_PROG_TYPE_SK_SKB**, + * **BPF_PROG_TYPE_SK_MSG** + * + * eBPF map of socket type (eg **BPF_MAP_TYPE_SOCKHASH**). + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_PROG_DETACH + * Description + * Detach the eBPF program associated with the *target_fd* at the + * hook specified by *attach_type*. The program must have been + * previously attached using **BPF_PROG_ATTACH**. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_PROG_TEST_RUN + * Description + * Run the eBPF program associated with the *prog_fd* a *repeat* + * number of times against a provided program context *ctx_in* and + * data *data_in*, and return the modified program context + * *ctx_out*, *data_out* (for example, packet data), result of the + * execution *retval*, and *duration* of the test run. + * + * The sizes of the buffers provided as input and output + * parameters *ctx_in*, *ctx_out*, *data_in*, and *data_out* must + * be provided in the corresponding variables *ctx_size_in*, + * *ctx_size_out*, *data_size_in*, and/or *data_size_out*. If any + * of these parameters are not provided (ie set to NULL), the + * corresponding size field must be zero. + * + * Some program types have particular requirements: + * + * **BPF_PROG_TYPE_SK_LOOKUP** + * *data_in* and *data_out* must be NULL. + * + * **BPF_PROG_TYPE_XDP** + * *ctx_in* and *ctx_out* must be NULL. + * + * **BPF_PROG_TYPE_RAW_TRACEPOINT**, + * **BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE** + * + * *ctx_out*, *data_in* and *data_out* must be NULL. + * *repeat* must be zero. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * **ENOSPC** + * Either *data_size_out* or *ctx_size_out* is too small. + * **ENOTSUPP** + * This command is not supported by the program type of + * the program referred to by *prog_fd*. + * + * BPF_PROG_GET_NEXT_ID + * Description + * Fetch the next eBPF program currently loaded into the kernel. + * + * Looks for the eBPF program with an id greater than *start_id* + * and updates *next_id* on success. If no other eBPF programs + * remain with ids higher than *start_id*, returns -1 and sets + * *errno* to **ENOENT**. + * + * Return + * Returns zero on success. On error, or when no id remains, -1 + * is returned and *errno* is set appropriately. + * + * BPF_MAP_GET_NEXT_ID + * Description + * Fetch the next eBPF map currently loaded into the kernel. + * + * Looks for the eBPF map with an id greater than *start_id* + * and updates *next_id* on success. If no other eBPF maps + * remain with ids higher than *start_id*, returns -1 and sets + * *errno* to **ENOENT**. + * + * Return + * Returns zero on success. On error, or when no id remains, -1 + * is returned and *errno* is set appropriately. + * + * BPF_PROG_GET_FD_BY_ID + * Description + * Open a file descriptor for the eBPF program corresponding to + * *prog_id*. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_MAP_GET_FD_BY_ID + * Description + * Open a file descriptor for the eBPF map corresponding to + * *map_id*. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_OBJ_GET_INFO_BY_FD + * Description + * Obtain information about the eBPF object corresponding to + * *bpf_fd*. + * + * Populates up to *info_len* bytes of *info*, which will be in + * one of the following formats depending on the eBPF object type + * of *bpf_fd*: + * + * * **struct bpf_prog_info** + * * **struct bpf_map_info** + * * **struct bpf_btf_info** + * * **struct bpf_link_info** + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_PROG_QUERY + * Description + * Obtain information about eBPF programs associated with the + * specified *attach_type* hook. + * + * The *target_fd* must be a valid file descriptor for a kernel + * object which depends on the attach type of *attach_bpf_fd*: + * + * **BPF_PROG_TYPE_CGROUP_DEVICE**, + * **BPF_PROG_TYPE_CGROUP_SKB**, + * **BPF_PROG_TYPE_CGROUP_SOCK**, + * **BPF_PROG_TYPE_CGROUP_SOCK_ADDR**, + * **BPF_PROG_TYPE_CGROUP_SOCKOPT**, + * **BPF_PROG_TYPE_CGROUP_SYSCTL**, + * **BPF_PROG_TYPE_SOCK_OPS** + * + * Control Group v2 hierarchy with the eBPF controller + * enabled. Requires the kernel to be compiled with + * **CONFIG_CGROUP_BPF**. + * + * **BPF_PROG_TYPE_FLOW_DISSECTOR** + * + * Network namespace (eg /proc/self/ns/net). + * + * **BPF_PROG_TYPE_LIRC_MODE2** + * + * LIRC device path (eg /dev/lircN). Requires the kernel + * to be compiled with **CONFIG_BPF_LIRC_MODE2**. + * + * **BPF_PROG_QUERY** always fetches the number of programs + * attached and the *attach_flags* which were used to attach those + * programs. Additionally, if *prog_ids* is nonzero and the number + * of attached programs is less than *prog_cnt*, populates + * *prog_ids* with the eBPF program ids of the programs attached + * at *target_fd*. + * + * The following flags may alter the result: + * + * **BPF_F_QUERY_EFFECTIVE** + * Only return information regarding programs which are + * currently effective at the specified *target_fd*. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_RAW_TRACEPOINT_OPEN + * Description + * Attach an eBPF program to a tracepoint *name* to access kernel + * internal arguments of the tracepoint in their raw form. + * + * The *prog_fd* must be a valid file descriptor associated with + * a loaded eBPF program of type **BPF_PROG_TYPE_RAW_TRACEPOINT**. + * + * No ABI guarantees are made about the content of tracepoint + * arguments exposed to the corresponding eBPF program. + * + * Applying **close**\ (2) to the file descriptor returned by + * **BPF_RAW_TRACEPOINT_OPEN** will delete the map (but see NOTES). + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_BTF_LOAD + * Description + * Verify and load BPF Type Format (BTF) metadata into the kernel, + * returning a new file descriptor associated with the metadata. + * BTF is described in more detail at + * https://www.kernel.org/doc/html/latest/bpf/btf.html. + * + * The *btf* parameter must point to valid memory providing + * *btf_size* bytes of BTF binary metadata. + * + * The returned file descriptor can be passed to other **bpf**\ () + * subcommands such as **BPF_PROG_LOAD** or **BPF_MAP_CREATE** to + * associate the BTF with those objects. + * + * Similar to **BPF_PROG_LOAD**, **BPF_BTF_LOAD** has optional + * parameters to specify a *btf_log_buf*, *btf_log_size* and + * *btf_log_level* which allow the kernel to return freeform log + * output regarding the BTF verification process. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_BTF_GET_FD_BY_ID + * Description + * Open a file descriptor for the BPF Type Format (BTF) + * corresponding to *btf_id*. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_TASK_FD_QUERY + * Description + * Obtain information about eBPF programs associated with the + * target process identified by *pid* and *fd*. + * + * If the *pid* and *fd* are associated with a tracepoint, kprobe + * or uprobe perf event, then the *prog_id* and *fd_type* will + * be populated with the eBPF program id and file descriptor type + * of type **bpf_task_fd_type**. If associated with a kprobe or + * uprobe, the *probe_offset* and *probe_addr* will also be + * populated. Optionally, if *buf* is provided, then up to + * *buf_len* bytes of *buf* will be populated with the name of + * the tracepoint, kprobe or uprobe. + * + * The resulting *prog_id* may be introspected in deeper detail + * using **BPF_PROG_GET_FD_BY_ID** and **BPF_OBJ_GET_INFO_BY_FD**. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_MAP_LOOKUP_AND_DELETE_ELEM + * Description + * Look up an element with the given *key* in the map referred to + * by the file descriptor *fd*, and if found, delete the element. + * + * For **BPF_MAP_TYPE_QUEUE** and **BPF_MAP_TYPE_STACK** map + * types, the *flags* argument needs to be set to 0, but for other + * map types, it may be specified as: + * + * **BPF_F_LOCK** + * Look up and delete the value of a spin-locked map + * without returning the lock. This must be specified if + * the elements contain a spinlock. + * + * The **BPF_MAP_TYPE_QUEUE** and **BPF_MAP_TYPE_STACK** map types + * implement this command as a "pop" operation, deleting the top + * element rather than one corresponding to *key*. + * The *key* and *key_len* parameters should be zeroed when + * issuing this operation for these map types. + * + * This command is only valid for the following map types: + * * **BPF_MAP_TYPE_QUEUE** + * * **BPF_MAP_TYPE_STACK** + * * **BPF_MAP_TYPE_HASH** + * * **BPF_MAP_TYPE_PERCPU_HASH** + * * **BPF_MAP_TYPE_LRU_HASH** + * * **BPF_MAP_TYPE_LRU_PERCPU_HASH** + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_MAP_FREEZE + * Description + * Freeze the permissions of the specified map. + * + * Write permissions may be frozen by passing zero *flags*. + * Upon success, no future syscall invocations may alter the + * map state of *map_fd*. Write operations from eBPF programs + * are still possible for a frozen map. + * + * Not supported for maps of type **BPF_MAP_TYPE_STRUCT_OPS**. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_BTF_GET_NEXT_ID + * Description + * Fetch the next BPF Type Format (BTF) object currently loaded + * into the kernel. + * + * Looks for the BTF object with an id greater than *start_id* + * and updates *next_id* on success. If no other BTF objects + * remain with ids higher than *start_id*, returns -1 and sets + * *errno* to **ENOENT**. + * + * Return + * Returns zero on success. On error, or when no id remains, -1 + * is returned and *errno* is set appropriately. + * + * BPF_MAP_LOOKUP_BATCH + * Description + * Iterate and fetch multiple elements in a map. + * + * Two opaque values are used to manage batch operations, + * *in_batch* and *out_batch*. Initially, *in_batch* must be set + * to NULL to begin the batched operation. After each subsequent + * **BPF_MAP_LOOKUP_BATCH**, the caller should pass the resultant + * *out_batch* as the *in_batch* for the next operation to + * continue iteration from the current point. + * + * The *keys* and *values* are output parameters which must point + * to memory large enough to hold *count* items based on the key + * and value size of the map *map_fd*. The *keys* buffer must be + * of *key_size* * *count*. The *values* buffer must be of + * *value_size* * *count*. + * + * The *elem_flags* argument may be specified as one of the + * following: + * + * **BPF_F_LOCK** + * Look up the value of a spin-locked map without + * returning the lock. This must be specified if the + * elements contain a spinlock. + * + * On success, *count* elements from the map are copied into the + * user buffer, with the keys copied into *keys* and the values + * copied into the corresponding indices in *values*. + * + * If an error is returned and *errno* is not **EFAULT**, *count* + * is set to the number of successfully processed elements. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * May set *errno* to **ENOSPC** to indicate that *keys* or + * *values* is too small to dump an entire bucket during + * iteration of a hash-based map type. + * + * BPF_MAP_LOOKUP_AND_DELETE_BATCH + * Description + * Iterate and delete all elements in a map. + * + * This operation has the same behavior as + * **BPF_MAP_LOOKUP_BATCH** with two exceptions: + * + * * Every element that is successfully returned is also deleted + * from the map. This is at least *count* elements. Note that + * *count* is both an input and an output parameter. + * * Upon returning with *errno* set to **EFAULT**, up to + * *count* elements may be deleted without returning the keys + * and values of the deleted elements. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_MAP_UPDATE_BATCH + * Description + * Update multiple elements in a map by *key*. + * + * The *keys* and *values* are input parameters which must point + * to memory large enough to hold *count* items based on the key + * and value size of the map *map_fd*. The *keys* buffer must be + * of *key_size* * *count*. The *values* buffer must be of + * *value_size* * *count*. + * + * Each element specified in *keys* is sequentially updated to the + * value in the corresponding index in *values*. The *in_batch* + * and *out_batch* parameters are ignored and should be zeroed. + * + * The *elem_flags* argument should be specified as one of the + * following: + * + * **BPF_ANY** + * Create new elements or update a existing elements. + * **BPF_NOEXIST** + * Create new elements only if they do not exist. + * **BPF_EXIST** + * Update existing elements. + * **BPF_F_LOCK** + * Update spin_lock-ed map elements. This must be + * specified if the map value contains a spinlock. + * + * On success, *count* elements from the map are updated. + * + * If an error is returned and *errno* is not **EFAULT**, *count* + * is set to the number of successfully processed elements. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * May set *errno* to **EINVAL**, **EPERM**, **ENOMEM**, or + * **E2BIG**. **E2BIG** indicates that the number of elements in + * the map reached the *max_entries* limit specified at map + * creation time. + * + * May set *errno* to one of the following error codes under + * specific circumstances: + * + * **EEXIST** + * If *flags* specifies **BPF_NOEXIST** and the element + * with *key* already exists in the map. + * **ENOENT** + * If *flags* specifies **BPF_EXIST** and the element with + * *key* does not exist in the map. + * + * BPF_MAP_DELETE_BATCH + * Description + * Delete multiple elements in a map by *key*. + * + * The *keys* parameter is an input parameter which must point + * to memory large enough to hold *count* items based on the key + * size of the map *map_fd*, that is, *key_size* * *count*. + * + * Each element specified in *keys* is sequentially deleted. The + * *in_batch*, *out_batch*, and *values* parameters are ignored + * and should be zeroed. + * + * The *elem_flags* argument may be specified as one of the + * following: + * + * **BPF_F_LOCK** + * Look up the value of a spin-locked map without + * returning the lock. This must be specified if the + * elements contain a spinlock. + * + * On success, *count* elements from the map are updated. + * + * If an error is returned and *errno* is not **EFAULT**, *count* + * is set to the number of successfully processed elements. If + * *errno* is **EFAULT**, up to *count* elements may be been + * deleted. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_LINK_CREATE + * Description + * Attach an eBPF program to a *target_fd* at the specified + * *attach_type* hook and return a file descriptor handle for + * managing the link. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_LINK_UPDATE + * Description + * Update the eBPF program in the specified *link_fd* to + * *new_prog_fd*. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_LINK_GET_FD_BY_ID + * Description + * Open a file descriptor for the eBPF Link corresponding to + * *link_id*. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_LINK_GET_NEXT_ID + * Description + * Fetch the next eBPF link currently loaded into the kernel. + * + * Looks for the eBPF link with an id greater than *start_id* + * and updates *next_id* on success. If no other eBPF links + * remain with ids higher than *start_id*, returns -1 and sets + * *errno* to **ENOENT**. + * + * Return + * Returns zero on success. On error, or when no id remains, -1 + * is returned and *errno* is set appropriately. + * + * BPF_ENABLE_STATS + * Description + * Enable eBPF runtime statistics gathering. + * + * Runtime statistics gathering for the eBPF runtime is disabled + * by default to minimize the corresponding performance overhead. + * This command enables statistics globally. + * + * Multiple programs may independently enable statistics. + * After gathering the desired statistics, eBPF runtime statistics + * may be disabled again by calling **close**\ (2) for the file + * descriptor returned by this function. Statistics will only be + * disabled system-wide when all outstanding file descriptors + * returned by prior calls for this subcommand are closed. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_ITER_CREATE + * Description + * Create an iterator on top of the specified *link_fd* (as + * previously created using **BPF_LINK_CREATE**) and return a + * file descriptor that can be used to trigger the iteration. + * + * If the resulting file descriptor is pinned to the filesystem + * using **BPF_OBJ_PIN**, then subsequent **read**\ (2) syscalls + * for that path will trigger the iterator to read kernel state + * using the eBPF program attached to *link_fd*. + * + * Return + * A new file descriptor (a nonnegative integer), or -1 if an + * error occurred (in which case, *errno* is set appropriately). + * + * BPF_LINK_DETACH + * Description + * Forcefully detach the specified *link_fd* from its + * corresponding attachment point. + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * BPF_PROG_BIND_MAP + * Description + * Bind a map to the lifetime of an eBPF program. + * + * The map identified by *map_fd* is bound to the program + * identified by *prog_fd* and only released when *prog_fd* is + * released. This may be used in cases where metadata should be + * associated with a program which otherwise does not contain any + * references to the map (for example, embedded in the eBPF + * program instructions). + * + * Return + * Returns zero on success. On error, -1 is returned and *errno* + * is set appropriately. + * + * NOTES + * eBPF objects (maps and programs) can be shared between processes. + * + * * After **fork**\ (2), the child inherits file descriptors + * referring to the same eBPF objects. + * * File descriptors referring to eBPF objects can be transferred over + * **unix**\ (7) domain sockets. + * * File descriptors referring to eBPF objects can be duplicated in the + * usual way, using **dup**\ (2) and similar calls. + * * File descriptors referring to eBPF objects can be pinned to the + * filesystem using the **BPF_OBJ_PIN** command of **bpf**\ (2). + * + * An eBPF object is deallocated only after all file descriptors referring + * to the object have been closed and no references remain pinned to the + * filesystem or attached (for example, bound to a program or device). + */ +enum bpf_cmd { + BPF_MAP_CREATE, + BPF_MAP_LOOKUP_ELEM, + BPF_MAP_UPDATE_ELEM, + BPF_MAP_DELETE_ELEM, + BPF_MAP_GET_NEXT_KEY, + BPF_PROG_LOAD, + BPF_OBJ_PIN, + BPF_OBJ_GET, + BPF_PROG_ATTACH, + BPF_PROG_DETACH, + BPF_PROG_TEST_RUN, + BPF_PROG_RUN = BPF_PROG_TEST_RUN, + BPF_PROG_GET_NEXT_ID, + BPF_MAP_GET_NEXT_ID, + BPF_PROG_GET_FD_BY_ID, + BPF_MAP_GET_FD_BY_ID, + BPF_OBJ_GET_INFO_BY_FD, + BPF_PROG_QUERY, + BPF_RAW_TRACEPOINT_OPEN, + BPF_BTF_LOAD, + BPF_BTF_GET_FD_BY_ID, + BPF_TASK_FD_QUERY, + BPF_MAP_LOOKUP_AND_DELETE_ELEM, + BPF_MAP_FREEZE, + BPF_BTF_GET_NEXT_ID, + BPF_MAP_LOOKUP_BATCH, + BPF_MAP_LOOKUP_AND_DELETE_BATCH, + BPF_MAP_UPDATE_BATCH, + BPF_MAP_DELETE_BATCH, + BPF_LINK_CREATE, + BPF_LINK_UPDATE, + BPF_LINK_GET_FD_BY_ID, + BPF_LINK_GET_NEXT_ID, + BPF_ENABLE_STATS, + BPF_ITER_CREATE, + BPF_LINK_DETACH, + BPF_PROG_BIND_MAP, +}; + +enum bpf_map_type { + BPF_MAP_TYPE_UNSPEC, + BPF_MAP_TYPE_HASH, + BPF_MAP_TYPE_ARRAY, + BPF_MAP_TYPE_PROG_ARRAY, + BPF_MAP_TYPE_PERF_EVENT_ARRAY, + BPF_MAP_TYPE_PERCPU_HASH, + BPF_MAP_TYPE_PERCPU_ARRAY, + BPF_MAP_TYPE_STACK_TRACE, + BPF_MAP_TYPE_CGROUP_ARRAY, + BPF_MAP_TYPE_LRU_HASH, + BPF_MAP_TYPE_LRU_PERCPU_HASH, + BPF_MAP_TYPE_LPM_TRIE, + BPF_MAP_TYPE_ARRAY_OF_MAPS, + BPF_MAP_TYPE_HASH_OF_MAPS, + BPF_MAP_TYPE_DEVMAP, + BPF_MAP_TYPE_SOCKMAP, + BPF_MAP_TYPE_CPUMAP, + BPF_MAP_TYPE_XSKMAP, + BPF_MAP_TYPE_SOCKHASH, + BPF_MAP_TYPE_CGROUP_STORAGE, + BPF_MAP_TYPE_REUSEPORT_SOCKARRAY, + BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE, + BPF_MAP_TYPE_QUEUE, + BPF_MAP_TYPE_STACK, + BPF_MAP_TYPE_SK_STORAGE, + BPF_MAP_TYPE_DEVMAP_HASH, + BPF_MAP_TYPE_STRUCT_OPS, + BPF_MAP_TYPE_RINGBUF, + BPF_MAP_TYPE_INODE_STORAGE, + BPF_MAP_TYPE_TASK_STORAGE, +}; + +/* Note that tracing related programs such as + * BPF_PROG_TYPE_{KPROBE,TRACEPOINT,PERF_EVENT,RAW_TRACEPOINT} + * are not subject to a stable API since kernel internal data + * structures can change from release to release and may + * therefore break existing tracing BPF programs. Tracing BPF + * programs correspond to /a/ specific kernel which is to be + * analyzed, and not /a/ specific kernel /and/ all future ones. + */ +enum bpf_prog_type { + BPF_PROG_TYPE_UNSPEC, + BPF_PROG_TYPE_SOCKET_FILTER, + BPF_PROG_TYPE_KPROBE, + BPF_PROG_TYPE_SCHED_CLS, + BPF_PROG_TYPE_SCHED_ACT, + BPF_PROG_TYPE_TRACEPOINT, + BPF_PROG_TYPE_XDP, + BPF_PROG_TYPE_PERF_EVENT, + BPF_PROG_TYPE_CGROUP_SKB, + BPF_PROG_TYPE_CGROUP_SOCK, + BPF_PROG_TYPE_LWT_IN, + BPF_PROG_TYPE_LWT_OUT, + BPF_PROG_TYPE_LWT_XMIT, + BPF_PROG_TYPE_SOCK_OPS, + BPF_PROG_TYPE_SK_SKB, + BPF_PROG_TYPE_CGROUP_DEVICE, + BPF_PROG_TYPE_SK_MSG, + BPF_PROG_TYPE_RAW_TRACEPOINT, + BPF_PROG_TYPE_CGROUP_SOCK_ADDR, + BPF_PROG_TYPE_LWT_SEG6LOCAL, + BPF_PROG_TYPE_LIRC_MODE2, + BPF_PROG_TYPE_SK_REUSEPORT, + BPF_PROG_TYPE_FLOW_DISSECTOR, + BPF_PROG_TYPE_CGROUP_SYSCTL, + BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, + BPF_PROG_TYPE_CGROUP_SOCKOPT, + BPF_PROG_TYPE_TRACING, + BPF_PROG_TYPE_STRUCT_OPS, + BPF_PROG_TYPE_EXT, + BPF_PROG_TYPE_LSM, + BPF_PROG_TYPE_SK_LOOKUP, + BPF_PROG_TYPE_SYSCALL, /* a program that can execute syscalls */ +}; + +enum bpf_attach_type { + BPF_CGROUP_INET_INGRESS, + BPF_CGROUP_INET_EGRESS, + BPF_CGROUP_INET_SOCK_CREATE, + BPF_CGROUP_SOCK_OPS, + BPF_SK_SKB_STREAM_PARSER, + BPF_SK_SKB_STREAM_VERDICT, + BPF_CGROUP_DEVICE, + BPF_SK_MSG_VERDICT, + BPF_CGROUP_INET4_BIND, + BPF_CGROUP_INET6_BIND, + BPF_CGROUP_INET4_CONNECT, + BPF_CGROUP_INET6_CONNECT, + BPF_CGROUP_INET4_POST_BIND, + BPF_CGROUP_INET6_POST_BIND, + BPF_CGROUP_UDP4_SENDMSG, + BPF_CGROUP_UDP6_SENDMSG, + BPF_LIRC_MODE2, + BPF_FLOW_DISSECTOR, + BPF_CGROUP_SYSCTL, + BPF_CGROUP_UDP4_RECVMSG, + BPF_CGROUP_UDP6_RECVMSG, + BPF_CGROUP_GETSOCKOPT, + BPF_CGROUP_SETSOCKOPT, + BPF_TRACE_RAW_TP, + BPF_TRACE_FENTRY, + BPF_TRACE_FEXIT, + BPF_MODIFY_RETURN, + BPF_LSM_MAC, + BPF_TRACE_ITER, + BPF_CGROUP_INET4_GETPEERNAME, + BPF_CGROUP_INET6_GETPEERNAME, + BPF_CGROUP_INET4_GETSOCKNAME, + BPF_CGROUP_INET6_GETSOCKNAME, + BPF_XDP_DEVMAP, + BPF_CGROUP_INET_SOCK_RELEASE, + BPF_XDP_CPUMAP, + BPF_SK_LOOKUP, + BPF_XDP, + BPF_SK_SKB_VERDICT, + BPF_SK_REUSEPORT_SELECT, + BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, + __MAX_BPF_ATTACH_TYPE +}; + +#define MAX_BPF_ATTACH_TYPE __MAX_BPF_ATTACH_TYPE + +enum bpf_link_type { + BPF_LINK_TYPE_UNSPEC = 0, + BPF_LINK_TYPE_RAW_TRACEPOINT = 1, + BPF_LINK_TYPE_TRACING = 2, + BPF_LINK_TYPE_CGROUP = 3, + BPF_LINK_TYPE_ITER = 4, + BPF_LINK_TYPE_NETNS = 5, + BPF_LINK_TYPE_XDP = 6, + + MAX_BPF_LINK_TYPE, +}; + +/* cgroup-bpf attach flags used in BPF_PROG_ATTACH command + * + * NONE(default): No further bpf programs allowed in the subtree. + * + * BPF_F_ALLOW_OVERRIDE: If a sub-cgroup installs some bpf program, + * the program in this cgroup yields to sub-cgroup program. + * + * BPF_F_ALLOW_MULTI: If a sub-cgroup installs some bpf program, + * that cgroup program gets run in addition to the program in this cgroup. + * + * Only one program is allowed to be attached to a cgroup with + * NONE or BPF_F_ALLOW_OVERRIDE flag. + * Attaching another program on top of NONE or BPF_F_ALLOW_OVERRIDE will + * release old program and attach the new one. Attach flags has to match. + * + * Multiple programs are allowed to be attached to a cgroup with + * BPF_F_ALLOW_MULTI flag. They are executed in FIFO order + * (those that were attached first, run first) + * The programs of sub-cgroup are executed first, then programs of + * this cgroup and then programs of parent cgroup. + * When children program makes decision (like picking TCP CA or sock bind) + * parent program has a chance to override it. + * + * With BPF_F_ALLOW_MULTI a new program is added to the end of the list of + * programs for a cgroup. Though it's possible to replace an old program at + * any position by also specifying BPF_F_REPLACE flag and position itself in + * replace_bpf_fd attribute. Old program at this position will be released. + * + * A cgroup with MULTI or OVERRIDE flag allows any attach flags in sub-cgroups. + * A cgroup with NONE doesn't allow any programs in sub-cgroups. + * Ex1: + * cgrp1 (MULTI progs A, B) -> + * cgrp2 (OVERRIDE prog C) -> + * cgrp3 (MULTI prog D) -> + * cgrp4 (OVERRIDE prog E) -> + * cgrp5 (NONE prog F) + * the event in cgrp5 triggers execution of F,D,A,B in that order. + * if prog F is detached, the execution is E,D,A,B + * if prog F and D are detached, the execution is E,A,B + * if prog F, E and D are detached, the execution is C,A,B + * + * All eligible programs are executed regardless of return code from + * earlier programs. + */ +#define BPF_F_ALLOW_OVERRIDE (1U << 0) +#define BPF_F_ALLOW_MULTI (1U << 1) +#define BPF_F_REPLACE (1U << 2) + +/* If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the + * verifier will perform strict alignment checking as if the kernel + * has been built with CONFIG_EFFICIENT_UNALIGNED_ACCESS not set, + * and NET_IP_ALIGN defined to 2. + */ +#define BPF_F_STRICT_ALIGNMENT (1U << 0) + +/* If BPF_F_ANY_ALIGNMENT is used in BPF_PROF_LOAD command, the + * verifier will allow any alignment whatsoever. On platforms + * with strict alignment requirements for loads ands stores (such + * as sparc and mips) the verifier validates that all loads and + * stores provably follow this requirement. This flag turns that + * checking and enforcement off. + * + * It is mostly used for testing when we want to validate the + * context and memory access aspects of the verifier, but because + * of an unaligned access the alignment check would trigger before + * the one we are interested in. + */ +#define BPF_F_ANY_ALIGNMENT (1U << 1) + +/* BPF_F_TEST_RND_HI32 is used in BPF_PROG_LOAD command for testing purpose. + * Verifier does sub-register def/use analysis and identifies instructions whose + * def only matters for low 32-bit, high 32-bit is never referenced later + * through implicit zero extension. Therefore verifier notifies JIT back-ends + * that it is safe to ignore clearing high 32-bit for these instructions. This + * saves some back-ends a lot of code-gen. However such optimization is not + * necessary on some arches, for example x86_64, arm64 etc, whose JIT back-ends + * hence hasn't used verifier's analysis result. But, we really want to have a + * way to be able to verify the correctness of the described optimization on + * x86_64 on which testsuites are frequently exercised. + * + * So, this flag is introduced. Once it is set, verifier will randomize high + * 32-bit for those instructions who has been identified as safe to ignore them. + * Then, if verifier is not doing correct analysis, such randomization will + * regress tests to expose bugs. + */ +#define BPF_F_TEST_RND_HI32 (1U << 2) + +/* The verifier internal test flag. Behavior is undefined */ +#define BPF_F_TEST_STATE_FREQ (1U << 3) + +/* If BPF_F_SLEEPABLE is used in BPF_PROG_LOAD command, the verifier will + * restrict map and helper usage for such programs. Sleepable BPF programs can + * only be attached to hooks where kernel execution context allows sleeping. + * Such programs are allowed to use helpers that may sleep like + * bpf_copy_from_user(). + */ +#define BPF_F_SLEEPABLE (1U << 4) + +/* When BPF ldimm64's insn[0].src_reg != 0 then this can have + * the following extensions: + * + * insn[0].src_reg: BPF_PSEUDO_MAP_[FD|IDX] + * insn[0].imm: map fd or fd_idx + * insn[1].imm: 0 + * insn[0].off: 0 + * insn[1].off: 0 + * ldimm64 rewrite: address of map + * verifier type: CONST_PTR_TO_MAP + */ +#define BPF_PSEUDO_MAP_FD 1 +#define BPF_PSEUDO_MAP_IDX 5 + +/* insn[0].src_reg: BPF_PSEUDO_MAP_[IDX_]VALUE + * insn[0].imm: map fd or fd_idx + * insn[1].imm: offset into value + * insn[0].off: 0 + * insn[1].off: 0 + * ldimm64 rewrite: address of map[0]+offset + * verifier type: PTR_TO_MAP_VALUE + */ +#define BPF_PSEUDO_MAP_VALUE 2 +#define BPF_PSEUDO_MAP_IDX_VALUE 6 + +/* insn[0].src_reg: BPF_PSEUDO_BTF_ID + * insn[0].imm: kernel btd id of VAR + * insn[1].imm: 0 + * insn[0].off: 0 + * insn[1].off: 0 + * ldimm64 rewrite: address of the kernel variable + * verifier type: PTR_TO_BTF_ID or PTR_TO_MEM, depending on whether the var + * is struct/union. + */ +#define BPF_PSEUDO_BTF_ID 3 +/* insn[0].src_reg: BPF_PSEUDO_FUNC + * insn[0].imm: insn offset to the func + * insn[1].imm: 0 + * insn[0].off: 0 + * insn[1].off: 0 + * ldimm64 rewrite: address of the function + * verifier type: PTR_TO_FUNC. + */ +#define BPF_PSEUDO_FUNC 4 + +/* when bpf_call->src_reg == BPF_PSEUDO_CALL, bpf_call->imm == pc-relative + * offset to another bpf function + */ +#define BPF_PSEUDO_CALL 1 +/* when bpf_call->src_reg == BPF_PSEUDO_KFUNC_CALL, + * bpf_call->imm == btf_id of a BTF_KIND_FUNC in the running kernel + */ +#define BPF_PSEUDO_KFUNC_CALL 2 + +/* flags for BPF_MAP_UPDATE_ELEM command */ +enum { + BPF_ANY = 0, /* create new element or update existing */ + BPF_NOEXIST = 1, /* create new element if it didn't exist */ + BPF_EXIST = 2, /* update existing element */ + BPF_F_LOCK = 4, /* spin_lock-ed map_lookup/map_update */ +}; + +/* flags for BPF_MAP_CREATE command */ +enum { + BPF_F_NO_PREALLOC = (1U << 0), +/* Instead of having one common LRU list in the + * BPF_MAP_TYPE_LRU_[PERCPU_]HASH map, use a percpu LRU list + * which can scale and perform better. + * Note, the LRU nodes (including free nodes) cannot be moved + * across different LRU lists. + */ + BPF_F_NO_COMMON_LRU = (1U << 1), +/* Specify numa node during map creation */ + BPF_F_NUMA_NODE = (1U << 2), + +/* Flags for accessing BPF object from syscall side. */ + BPF_F_RDONLY = (1U << 3), + BPF_F_WRONLY = (1U << 4), + +/* Flag for stack_map, store build_id+offset instead of pointer */ + BPF_F_STACK_BUILD_ID = (1U << 5), + +/* Zero-initialize hash function seed. This should only be used for testing. */ + BPF_F_ZERO_SEED = (1U << 6), + +/* Flags for accessing BPF object from program side. */ + BPF_F_RDONLY_PROG = (1U << 7), + BPF_F_WRONLY_PROG = (1U << 8), + +/* Clone map from listener for newly accepted socket */ + BPF_F_CLONE = (1U << 9), + +/* Enable memory-mapping BPF map */ + BPF_F_MMAPABLE = (1U << 10), + +/* Share perf_event among processes */ + BPF_F_PRESERVE_ELEMS = (1U << 11), + +/* Create a map that is suitable to be an inner map with dynamic max entries */ + BPF_F_INNER_MAP = (1U << 12), +}; + +/* Flags for BPF_PROG_QUERY. */ + +/* Query effective (directly attached + inherited from ancestor cgroups) + * programs that will be executed for events within a cgroup. + * attach_flags with this flag are returned only for directly attached programs. + */ +#define BPF_F_QUERY_EFFECTIVE (1U << 0) + +/* Flags for BPF_PROG_TEST_RUN */ + +/* If set, run the test on the cpu specified by bpf_attr.test.cpu */ +#define BPF_F_TEST_RUN_ON_CPU (1U << 0) + +/* type for BPF_ENABLE_STATS */ +enum bpf_stats_type { + /* enabled run_time_ns and run_cnt */ + BPF_STATS_RUN_TIME = 0, +}; + +enum bpf_stack_build_id_status { + /* user space need an empty entry to identify end of a trace */ + BPF_STACK_BUILD_ID_EMPTY = 0, + /* with valid build_id and offset */ + BPF_STACK_BUILD_ID_VALID = 1, + /* couldn't get build_id, fallback to ip */ + BPF_STACK_BUILD_ID_IP = 2, +}; + +#define BPF_BUILD_ID_SIZE 20 +struct bpf_stack_build_id { + __s32 status; + unsigned char build_id[BPF_BUILD_ID_SIZE]; + union { + __u64 offset; + __u64 ip; + }; +}; + +#define BPF_OBJ_NAME_LEN 16U + +union bpf_attr { + struct { /* anonymous struct used by BPF_MAP_CREATE command */ + __u32 map_type; /* one of enum bpf_map_type */ + __u32 key_size; /* size of key in bytes */ + __u32 value_size; /* size of value in bytes */ + __u32 max_entries; /* max number of entries in a map */ + __u32 map_flags; /* BPF_MAP_CREATE related + * flags defined above. + */ + __u32 inner_map_fd; /* fd pointing to the inner map */ + __u32 numa_node; /* numa node (effective only if + * BPF_F_NUMA_NODE is set). + */ + char map_name[BPF_OBJ_NAME_LEN]; + __u32 map_ifindex; /* ifindex of netdev to create on */ + __u32 btf_fd; /* fd pointing to a BTF type data */ + __u32 btf_key_type_id; /* BTF type_id of the key */ + __u32 btf_value_type_id; /* BTF type_id of the value */ + __u32 btf_vmlinux_value_type_id;/* BTF type_id of a kernel- + * struct stored as the + * map value + */ + }; + + struct { /* anonymous struct used by BPF_MAP_*_ELEM commands */ + __u32 map_fd; + __aligned_u64 key; + union { + __aligned_u64 value; + __aligned_u64 next_key; + }; + __u64 flags; + }; + + struct { /* struct used by BPF_MAP_*_BATCH commands */ + __aligned_u64 in_batch; /* start batch, + * NULL to start from beginning + */ + __aligned_u64 out_batch; /* output: next start batch */ + __aligned_u64 keys; + __aligned_u64 values; + __u32 count; /* input/output: + * input: # of key/value + * elements + * output: # of filled elements + */ + __u32 map_fd; + __u64 elem_flags; + __u64 flags; + } batch; + + struct { /* anonymous struct used by BPF_PROG_LOAD command */ + __u32 prog_type; /* one of enum bpf_prog_type */ + __u32 insn_cnt; + __aligned_u64 insns; + __aligned_u64 license; + __u32 log_level; /* verbosity level of verifier */ + __u32 log_size; /* size of user buffer */ + __aligned_u64 log_buf; /* user supplied buffer */ + __u32 kern_version; /* not used */ + __u32 prog_flags; + char prog_name[BPF_OBJ_NAME_LEN]; + __u32 prog_ifindex; /* ifindex of netdev to prep for */ + /* For some prog types expected attach type must be known at + * load time to verify attach type specific parts of prog + * (context accesses, allowed helpers, etc). + */ + __u32 expected_attach_type; + __u32 prog_btf_fd; /* fd pointing to BTF type data */ + __u32 func_info_rec_size; /* userspace bpf_func_info size */ + __aligned_u64 func_info; /* func info */ + __u32 func_info_cnt; /* number of bpf_func_info records */ + __u32 line_info_rec_size; /* userspace bpf_line_info size */ + __aligned_u64 line_info; /* line info */ + __u32 line_info_cnt; /* number of bpf_line_info records */ + __u32 attach_btf_id; /* in-kernel BTF type id to attach to */ + union { + /* valid prog_fd to attach to bpf prog */ + __u32 attach_prog_fd; + /* or valid module BTF object fd or 0 to attach to vmlinux */ + __u32 attach_btf_obj_fd; + }; + __u32 :32; /* pad */ + __aligned_u64 fd_array; /* array of FDs */ + }; + + struct { /* anonymous struct used by BPF_OBJ_* commands */ + __aligned_u64 pathname; + __u32 bpf_fd; + __u32 file_flags; + }; + + struct { /* anonymous struct used by BPF_PROG_ATTACH/DETACH commands */ + __u32 target_fd; /* container object to attach to */ + __u32 attach_bpf_fd; /* eBPF program to attach */ + __u32 attach_type; + __u32 attach_flags; + __u32 replace_bpf_fd; /* previously attached eBPF + * program to replace if + * BPF_F_REPLACE is used + */ + }; + + struct { /* anonymous struct used by BPF_PROG_TEST_RUN command */ + __u32 prog_fd; + __u32 retval; + __u32 data_size_in; /* input: len of data_in */ + __u32 data_size_out; /* input/output: len of data_out + * returns ENOSPC if data_out + * is too small. + */ + __aligned_u64 data_in; + __aligned_u64 data_out; + __u32 repeat; + __u32 duration; + __u32 ctx_size_in; /* input: len of ctx_in */ + __u32 ctx_size_out; /* input/output: len of ctx_out + * returns ENOSPC if ctx_out + * is too small. + */ + __aligned_u64 ctx_in; + __aligned_u64 ctx_out; + __u32 flags; + __u32 cpu; + } test; + + struct { /* anonymous struct used by BPF_*_GET_*_ID */ + union { + __u32 start_id; + __u32 prog_id; + __u32 map_id; + __u32 btf_id; + __u32 link_id; + }; + __u32 next_id; + __u32 open_flags; + }; + + struct { /* anonymous struct used by BPF_OBJ_GET_INFO_BY_FD */ + __u32 bpf_fd; + __u32 info_len; + __aligned_u64 info; + } info; + + struct { /* anonymous struct used by BPF_PROG_QUERY command */ + __u32 target_fd; /* container object to query */ + __u32 attach_type; + __u32 query_flags; + __u32 attach_flags; + __aligned_u64 prog_ids; + __u32 prog_cnt; + } query; + + struct { /* anonymous struct used by BPF_RAW_TRACEPOINT_OPEN command */ + __u64 name; + __u32 prog_fd; + } raw_tracepoint; + + struct { /* anonymous struct for BPF_BTF_LOAD */ + __aligned_u64 btf; + __aligned_u64 btf_log_buf; + __u32 btf_size; + __u32 btf_log_size; + __u32 btf_log_level; + }; + + struct { + __u32 pid; /* input: pid */ + __u32 fd; /* input: fd */ + __u32 flags; /* input: flags */ + __u32 buf_len; /* input/output: buf len */ + __aligned_u64 buf; /* input/output: + * tp_name for tracepoint + * symbol for kprobe + * filename for uprobe + */ + __u32 prog_id; /* output: prod_id */ + __u32 fd_type; /* output: BPF_FD_TYPE_* */ + __u64 probe_offset; /* output: probe_offset */ + __u64 probe_addr; /* output: probe_addr */ + } task_fd_query; + + struct { /* struct used by BPF_LINK_CREATE command */ + __u32 prog_fd; /* eBPF program to attach */ + union { + __u32 target_fd; /* object to attach to */ + __u32 target_ifindex; /* target ifindex */ + }; + __u32 attach_type; /* attach type */ + __u32 flags; /* extra flags */ + union { + __u32 target_btf_id; /* btf_id of target to attach to */ + struct { + __aligned_u64 iter_info; /* extra bpf_iter_link_info */ + __u32 iter_info_len; /* iter_info length */ + }; + }; + } link_create; + + struct { /* struct used by BPF_LINK_UPDATE command */ + __u32 link_fd; /* link fd */ + /* new program fd to update link with */ + __u32 new_prog_fd; + __u32 flags; /* extra flags */ + /* expected link's program fd; is specified only if + * BPF_F_REPLACE flag is set in flags */ + __u32 old_prog_fd; + } link_update; + + struct { + __u32 link_fd; + } link_detach; + + struct { /* struct used by BPF_ENABLE_STATS command */ + __u32 type; + } enable_stats; + + struct { /* struct used by BPF_ITER_CREATE command */ + __u32 link_fd; + __u32 flags; + } iter_create; + + struct { /* struct used by BPF_PROG_BIND_MAP command */ + __u32 prog_fd; + __u32 map_fd; + __u32 flags; /* extra flags */ + } prog_bind_map; + +} __attribute__((aligned(8))); + +/* The description below is an attempt at providing documentation to eBPF + * developers about the multiple available eBPF helper functions. It can be + * parsed and used to produce a manual page. The workflow is the following, + * and requires the rst2man utility: + * + * $ ./scripts/bpf_doc.py \ + * --filename include/uapi/linux/bpf.h > /tmp/bpf-helpers.rst + * $ rst2man /tmp/bpf-helpers.rst > /tmp/bpf-helpers.7 + * $ man /tmp/bpf-helpers.7 + * + * Note that in order to produce this external documentation, some RST + * formatting is used in the descriptions to get "bold" and "italics" in + * manual pages. Also note that the few trailing white spaces are + * intentional, removing them would break paragraphs for rst2man. + * + * Start of BPF helper function descriptions: + * + * void *bpf_map_lookup_elem(struct bpf_map *map, const void *key) + * Description + * Perform a lookup in *map* for an entry associated to *key*. + * Return + * Map value associated to *key*, or **NULL** if no entry was + * found. + * + * long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags) + * Description + * Add or update the value of the entry associated to *key* in + * *map* with *value*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * Flag value **BPF_NOEXIST** cannot be used for maps of types + * **BPF_MAP_TYPE_ARRAY** or **BPF_MAP_TYPE_PERCPU_ARRAY** (all + * elements always exist), the helper would return an error. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_map_delete_elem(struct bpf_map *map, const void *key) + * Description + * Delete entry with *key* from *map*. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read(void *dst, u32 size, const void *unsafe_ptr) + * Description + * For tracing programs, safely attempt to read *size* bytes from + * kernel space address *unsafe_ptr* and store the data in *dst*. + * + * Generally, use **bpf_probe_read_user**\ () or + * **bpf_probe_read_kernel**\ () instead. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_ktime_get_ns(void) + * Description + * Return the time elapsed since system boot, in nanoseconds. + * Does not include time the system was suspended. + * See: **clock_gettime**\ (**CLOCK_MONOTONIC**) + * Return + * Current *ktime*. + * + * long bpf_trace_printk(const char *fmt, u32 fmt_size, ...) + * Description + * This helper is a "printk()-like" facility for debugging. It + * prints a message defined by format *fmt* (of size *fmt_size*) + * to file *\/sys/kernel/debug/tracing/trace* from DebugFS, if + * available. It can take up to three additional **u64** + * arguments (as an eBPF helpers, the total number of arguments is + * limited to five). + * + * Each time the helper is called, it appends a line to the trace. + * Lines are discarded while *\/sys/kernel/debug/tracing/trace* is + * open, use *\/sys/kernel/debug/tracing/trace_pipe* to avoid this. + * The format of the trace is customizable, and the exact output + * one will get depends on the options set in + * *\/sys/kernel/debug/tracing/trace_options* (see also the + * *README* file under the same directory). However, it usually + * defaults to something like: + * + * :: + * + * telnet-470 [001] .N.. 419421.045894: 0x00000001: + * + * In the above: + * + * * ``telnet`` is the name of the current task. + * * ``470`` is the PID of the current task. + * * ``001`` is the CPU number on which the task is + * running. + * * In ``.N..``, each character refers to a set of + * options (whether irqs are enabled, scheduling + * options, whether hard/softirqs are running, level of + * preempt_disabled respectively). **N** means that + * **TIF_NEED_RESCHED** and **PREEMPT_NEED_RESCHED** + * are set. + * * ``419421.045894`` is a timestamp. + * * ``0x00000001`` is a fake value used by BPF for the + * instruction pointer register. + * * ```` is the message formatted with + * *fmt*. + * + * The conversion specifiers supported by *fmt* are similar, but + * more limited than for printk(). They are **%d**, **%i**, + * **%u**, **%x**, **%ld**, **%li**, **%lu**, **%lx**, **%lld**, + * **%lli**, **%llu**, **%llx**, **%p**, **%s**. No modifier (size + * of field, padding with zeroes, etc.) is available, and the + * helper will return **-EINVAL** (but print nothing) if it + * encounters an unknown specifier. + * + * Also, note that **bpf_trace_printk**\ () is slow, and should + * only be used for debugging purposes. For this reason, a notice + * block (spanning several lines) is printed to kernel logs and + * states that the helper should not be used "for production use" + * the first time this helper is used (or more precisely, when + * **trace_printk**\ () buffers are allocated). For passing values + * to user space, perf events should be preferred. + * Return + * The number of bytes written to the buffer, or a negative error + * in case of failure. + * + * u32 bpf_get_prandom_u32(void) + * Description + * Get a pseudo-random number. + * + * From a security point of view, this helper uses its own + * pseudo-random internal state, and cannot be used to infer the + * seed of other random functions in the kernel. However, it is + * essential to note that the generator used by the helper is not + * cryptographically secure. + * Return + * A random 32-bit unsigned value. + * + * u32 bpf_get_smp_processor_id(void) + * Description + * Get the SMP (symmetric multiprocessing) processor id. Note that + * all programs run with preemption disabled, which means that the + * SMP processor id is stable during all the execution of the + * program. + * Return + * The SMP id of the processor running the program. + * + * long bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from, u32 len, u64 flags) + * Description + * Store *len* bytes from address *from* into the packet + * associated to *skb*, at *offset*. *flags* are a combination of + * **BPF_F_RECOMPUTE_CSUM** (automatically recompute the + * checksum for the packet after storing the bytes) and + * **BPF_F_INVALIDATE_HASH** (set *skb*\ **->hash**, *skb*\ + * **->swhash** and *skb*\ **->l4hash** to 0). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_l3_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 size) + * Description + * Recompute the layer 3 (e.g. IP) checksum for the packet + * associated to *skb*. Computation is incremental, so the helper + * must know the former value of the header field that was + * modified (*from*), the new value of this field (*to*), and the + * number of bytes (2 or 4) for this field, stored in *size*. + * Alternatively, it is possible to store the difference between + * the previous and the new values of the header field in *to*, by + * setting *from* and *size* to 0. For both methods, *offset* + * indicates the location of the IP checksum within the packet. + * + * This helper works in combination with **bpf_csum_diff**\ (), + * which does not update the checksum in-place, but offers more + * flexibility and can handle sizes larger than 2 or 4 for the + * checksum to update. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_l4_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 flags) + * Description + * Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the + * packet associated to *skb*. Computation is incremental, so the + * helper must know the former value of the header field that was + * modified (*from*), the new value of this field (*to*), and the + * number of bytes (2 or 4) for this field, stored on the lowest + * four bits of *flags*. Alternatively, it is possible to store + * the difference between the previous and the new values of the + * header field in *to*, by setting *from* and the four lowest + * bits of *flags* to 0. For both methods, *offset* indicates the + * location of the IP checksum within the packet. In addition to + * the size of the field, *flags* can be added (bitwise OR) actual + * flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is left + * untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and + * for updates resulting in a null checksum the value is set to + * **CSUM_MANGLED_0** instead. Flag **BPF_F_PSEUDO_HDR** indicates + * the checksum is to be computed against a pseudo-header. + * + * This helper works in combination with **bpf_csum_diff**\ (), + * which does not update the checksum in-place, but offers more + * flexibility and can handle sizes larger than 2 or 4 for the + * checksum to update. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_tail_call(void *ctx, struct bpf_map *prog_array_map, u32 index) + * Description + * This special helper is used to trigger a "tail call", or in + * other words, to jump into another eBPF program. The same stack + * frame is used (but values on stack and in registers for the + * caller are not accessible to the callee). This mechanism allows + * for program chaining, either for raising the maximum number of + * available eBPF instructions, or to execute given programs in + * conditional blocks. For security reasons, there is an upper + * limit to the number of successive tail calls that can be + * performed. + * + * Upon call of this helper, the program attempts to jump into a + * program referenced at index *index* in *prog_array_map*, a + * special map of type **BPF_MAP_TYPE_PROG_ARRAY**, and passes + * *ctx*, a pointer to the context. + * + * If the call succeeds, the kernel immediately runs the first + * instruction of the new program. This is not a function call, + * and it never returns to the previous program. If the call + * fails, then the helper has no effect, and the caller continues + * to run its subsequent instructions. A call can fail if the + * destination program for the jump does not exist (i.e. *index* + * is superior to the number of entries in *prog_array_map*), or + * if the maximum number of tail calls has been reached for this + * chain of programs. This limit is defined in the kernel by the + * macro **MAX_TAIL_CALL_CNT** (not accessible to user space), + * which is currently set to 32. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_clone_redirect(struct sk_buff *skb, u32 ifindex, u64 flags) + * Description + * Clone and redirect the packet associated to *skb* to another + * net device of index *ifindex*. Both ingress and egress + * interfaces can be used for redirection. The **BPF_F_INGRESS** + * value in *flags* is used to make the distinction (ingress path + * is selected if the flag is present, egress path otherwise). + * This is the only flag supported for now. + * + * In comparison with **bpf_redirect**\ () helper, + * **bpf_clone_redirect**\ () has the associated cost of + * duplicating the packet buffer, but this can be executed out of + * the eBPF program. Conversely, **bpf_redirect**\ () is more + * efficient, but it is handled through an action code where the + * redirection happens only after the eBPF program has returned. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_get_current_pid_tgid(void) + * Return + * A 64-bit integer containing the current tgid and pid, and + * created as such: + * *current_task*\ **->tgid << 32 \|** + * *current_task*\ **->pid**. + * + * u64 bpf_get_current_uid_gid(void) + * Return + * A 64-bit integer containing the current GID and UID, and + * created as such: *current_gid* **<< 32 \|** *current_uid*. + * + * long bpf_get_current_comm(void *buf, u32 size_of_buf) + * Description + * Copy the **comm** attribute of the current task into *buf* of + * *size_of_buf*. The **comm** attribute contains the name of + * the executable (excluding the path) for the current task. The + * *size_of_buf* must be strictly positive. On success, the + * helper makes sure that the *buf* is NUL-terminated. On failure, + * it is filled with zeroes. + * Return + * 0 on success, or a negative error in case of failure. + * + * u32 bpf_get_cgroup_classid(struct sk_buff *skb) + * Description + * Retrieve the classid for the current task, i.e. for the net_cls + * cgroup to which *skb* belongs. + * + * This helper can be used on TC egress path, but not on ingress. + * + * The net_cls cgroup provides an interface to tag network packets + * based on a user-provided identifier for all traffic coming from + * the tasks belonging to the related cgroup. See also the related + * kernel documentation, available from the Linux sources in file + * *Documentation/admin-guide/cgroup-v1/net_cls.rst*. + * + * The Linux kernel has two versions for cgroups: there are + * cgroups v1 and cgroups v2. Both are available to users, who can + * use a mixture of them, but note that the net_cls cgroup is for + * cgroup v1 only. This makes it incompatible with BPF programs + * run on cgroups, which is a cgroup-v2-only feature (a socket can + * only hold data for one version of cgroups at a time). + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_CGROUP_NET_CLASSID** configuration option set to + * "**y**" or to "**m**". + * Return + * The classid, or 0 for the default unconfigured classid. + * + * long bpf_skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci) + * Description + * Push a *vlan_tci* (VLAN tag control information) of protocol + * *vlan_proto* to the packet associated to *skb*, then update + * the checksum. Note that if *vlan_proto* is different from + * **ETH_P_8021Q** and **ETH_P_8021AD**, it is considered to + * be **ETH_P_8021Q**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_vlan_pop(struct sk_buff *skb) + * Description + * Pop a VLAN header from the packet associated to *skb*. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_get_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, u32 size, u64 flags) + * Description + * Get tunnel metadata. This helper takes a pointer *key* to an + * empty **struct bpf_tunnel_key** of **size**, that will be + * filled with tunnel metadata for the packet associated to *skb*. + * The *flags* can be set to **BPF_F_TUNINFO_IPV6**, which + * indicates that the tunnel is based on IPv6 protocol instead of + * IPv4. + * + * The **struct bpf_tunnel_key** is an object that generalizes the + * principal parameters used by various tunneling protocols into a + * single struct. This way, it can be used to easily make a + * decision based on the contents of the encapsulation header, + * "summarized" in this struct. In particular, it holds the IP + * address of the remote end (IPv4 or IPv6, depending on the case) + * in *key*\ **->remote_ipv4** or *key*\ **->remote_ipv6**. Also, + * this struct exposes the *key*\ **->tunnel_id**, which is + * generally mapped to a VNI (Virtual Network Identifier), making + * it programmable together with the **bpf_skb_set_tunnel_key**\ + * () helper. + * + * Let's imagine that the following code is part of a program + * attached to the TC ingress interface, on one end of a GRE + * tunnel, and is supposed to filter out all messages coming from + * remote ends with IPv4 address other than 10.0.0.1: + * + * :: + * + * int ret; + * struct bpf_tunnel_key key = {}; + * + * ret = bpf_skb_get_tunnel_key(skb, &key, sizeof(key), 0); + * if (ret < 0) + * return TC_ACT_SHOT; // drop packet + * + * if (key.remote_ipv4 != 0x0a000001) + * return TC_ACT_SHOT; // drop packet + * + * return TC_ACT_OK; // accept packet + * + * This interface can also be used with all encapsulation devices + * that can operate in "collect metadata" mode: instead of having + * one network device per specific configuration, the "collect + * metadata" mode only requires a single device where the + * configuration can be extracted from this helper. + * + * This can be used together with various tunnels such as VXLan, + * Geneve, GRE or IP in IP (IPIP). + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_set_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, u32 size, u64 flags) + * Description + * Populate tunnel metadata for packet associated to *skb.* The + * tunnel metadata is set to the contents of *key*, of *size*. The + * *flags* can be set to a combination of the following values: + * + * **BPF_F_TUNINFO_IPV6** + * Indicate that the tunnel is based on IPv6 protocol + * instead of IPv4. + * **BPF_F_ZERO_CSUM_TX** + * For IPv4 packets, add a flag to tunnel metadata + * indicating that checksum computation should be skipped + * and checksum set to zeroes. + * **BPF_F_DONT_FRAGMENT** + * Add a flag to tunnel metadata indicating that the + * packet should not be fragmented. + * **BPF_F_SEQ_NUMBER** + * Add a flag to tunnel metadata indicating that a + * sequence number should be added to tunnel header before + * sending the packet. This flag was added for GRE + * encapsulation, but might be used with other protocols + * as well in the future. + * + * Here is a typical usage on the transmit path: + * + * :: + * + * struct bpf_tunnel_key key; + * populate key ... + * bpf_skb_set_tunnel_key(skb, &key, sizeof(key), 0); + * bpf_clone_redirect(skb, vxlan_dev_ifindex, 0); + * + * See also the description of the **bpf_skb_get_tunnel_key**\ () + * helper for additional information. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_perf_event_read(struct bpf_map *map, u64 flags) + * Description + * Read the value of a perf event counter. This helper relies on a + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of + * the perf event counter is selected when *map* is updated with + * perf event file descriptors. The *map* is an array whose size + * is the number of available CPUs, and each cell contains a value + * relative to one CPU. The value to retrieve is indicated by + * *flags*, that contains the index of the CPU to look up, masked + * with **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to + * **BPF_F_CURRENT_CPU** to indicate that the value for the + * current CPU should be retrieved. + * + * Note that before Linux 4.13, only hardware perf event can be + * retrieved. + * + * Also, be aware that the newer helper + * **bpf_perf_event_read_value**\ () is recommended over + * **bpf_perf_event_read**\ () in general. The latter has some ABI + * quirks where error and counter value are used as a return code + * (which is wrong to do since ranges may overlap). This issue is + * fixed with **bpf_perf_event_read_value**\ (), which at the same + * time provides more features over the **bpf_perf_event_read**\ + * () interface. Please refer to the description of + * **bpf_perf_event_read_value**\ () for details. + * Return + * The value of the perf event counter read from the map, or a + * negative error code in case of failure. + * + * long bpf_redirect(u32 ifindex, u64 flags) + * Description + * Redirect the packet to another net device of index *ifindex*. + * This helper is somewhat similar to **bpf_clone_redirect**\ + * (), except that the packet is not cloned, which provides + * increased performance. + * + * Except for XDP, both ingress and egress interfaces can be used + * for redirection. The **BPF_F_INGRESS** value in *flags* is used + * to make the distinction (ingress path is selected if the flag + * is present, egress path otherwise). Currently, XDP only + * supports redirection to the egress interface, and accepts no + * flag at all. + * + * The same effect can also be attained with the more generic + * **bpf_redirect_map**\ (), which uses a BPF map to store the + * redirect target instead of providing it directly to the helper. + * Return + * For XDP, the helper returns **XDP_REDIRECT** on success or + * **XDP_ABORTED** on error. For other program types, the values + * are **TC_ACT_REDIRECT** on success or **TC_ACT_SHOT** on + * error. + * + * u32 bpf_get_route_realm(struct sk_buff *skb) + * Description + * Retrieve the realm or the route, that is to say the + * **tclassid** field of the destination for the *skb*. The + * identifier retrieved is a user-provided tag, similar to the + * one used with the net_cls cgroup (see description for + * **bpf_get_cgroup_classid**\ () helper), but here this tag is + * held by a route (a destination entry), not by a task. + * + * Retrieving this identifier works with the clsact TC egress hook + * (see also **tc-bpf(8)**), or alternatively on conventional + * classful egress qdiscs, but not on TC ingress path. In case of + * clsact TC egress hook, this has the advantage that, internally, + * the destination entry has not been dropped yet in the transmit + * path. Therefore, the destination entry does not need to be + * artificially held via **netif_keep_dst**\ () for a classful + * qdisc until the *skb* is freed. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_IP_ROUTE_CLASSID** configuration option. + * Return + * The realm of the route for the packet associated to *skb*, or 0 + * if none was found. + * + * long bpf_perf_event_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) + * Description + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * The context of the program *ctx* needs also be passed to the + * helper. + * + * On user space, a program willing to read the values needs to + * call **perf_event_open**\ () on the perf event (either for + * one or for all CPUs) and to store the file descriptor into the + * *map*. This must be done before the eBPF program can send data + * into it. An example is available in file + * *samples/bpf/trace_output_user.c* in the Linux kernel source + * tree (the eBPF program counterpart is in + * *samples/bpf/trace_output_kern.c*). + * + * **bpf_perf_event_output**\ () achieves better performance + * than **bpf_trace_printk**\ () for sharing data with user + * space, and is much better suitable for streaming data from eBPF + * programs. + * + * Note that this helper is not restricted to tracing use cases + * and can be used with programs attached to TC or XDP as well, + * where it allows for passing data to user space listeners. Data + * can be: + * + * * Only custom structs, + * * Only the packet payload, or + * * A combination of both. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_load_bytes(const void *skb, u32 offset, void *to, u32 len) + * Description + * This helper was provided as an easy way to load data from a + * packet. It can be used to load *len* bytes from *offset* from + * the packet associated to *skb*, into the buffer pointed by + * *to*. + * + * Since Linux 4.7, usage of this helper has mostly been replaced + * by "direct packet access", enabling packet data to be + * manipulated with *skb*\ **->data** and *skb*\ **->data_end** + * pointing respectively to the first byte of packet data and to + * the byte after the last byte of packet data. However, it + * remains useful if one wishes to read large quantities of data + * at once from a packet into the eBPF stack. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_get_stackid(void *ctx, struct bpf_map *map, u64 flags) + * Description + * Walk a user or a kernel stack and return its id. To achieve + * this, the helper needs *ctx*, which is a pointer to the context + * on which the tracing program is executed, and a pointer to a + * *map* of type **BPF_MAP_TYPE_STACK_TRACE**. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * a combination of the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_FAST_STACK_CMP** + * Compare stacks by hash only. + * **BPF_F_REUSE_STACKID** + * If two different stacks hash into the same *stackid*, + * discard the old one. + * + * The stack id retrieved is a 32 bit long integer handle which + * can be further combined with other data (including other stack + * ids) and used as a key into maps. This can be useful for + * generating a variety of graphs (such as flame graphs or off-cpu + * graphs). + * + * For walking a stack, this helper is an improvement over + * **bpf_probe_read**\ (), which can be used with unrolled loops + * but is not efficient and consumes a lot of eBPF instructions. + * Instead, **bpf_get_stackid**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * Return + * The positive or null stack id on success, or a negative error + * in case of failure. + * + * s64 bpf_csum_diff(__be32 *from, u32 from_size, __be32 *to, u32 to_size, __wsum seed) + * Description + * Compute a checksum difference, from the raw buffer pointed by + * *from*, of length *from_size* (that must be a multiple of 4), + * towards the raw buffer pointed by *to*, of size *to_size* + * (same remark). An optional *seed* can be added to the value + * (this can be cascaded, the seed may come from a previous call + * to the helper). + * + * This is flexible enough to be used in several ways: + * + * * With *from_size* == 0, *to_size* > 0 and *seed* set to + * checksum, it can be used when pushing new data. + * * With *from_size* > 0, *to_size* == 0 and *seed* set to + * checksum, it can be used when removing data from a packet. + * * With *from_size* > 0, *to_size* > 0 and *seed* set to 0, it + * can be used to compute a diff. Note that *from_size* and + * *to_size* do not need to be equal. + * + * This helper can be used in combination with + * **bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ (), to + * which one can feed in the difference computed with + * **bpf_csum_diff**\ (). + * Return + * The checksum result, or a negative error code in case of + * failure. + * + * long bpf_skb_get_tunnel_opt(struct sk_buff *skb, void *opt, u32 size) + * Description + * Retrieve tunnel options metadata for the packet associated to + * *skb*, and store the raw tunnel option data to the buffer *opt* + * of *size*. + * + * This helper can be used with encapsulation devices that can + * operate in "collect metadata" mode (please refer to the related + * note in the description of **bpf_skb_get_tunnel_key**\ () for + * more details). A particular example where this can be used is + * in combination with the Geneve encapsulation protocol, where it + * allows for pushing (with **bpf_skb_get_tunnel_opt**\ () helper) + * and retrieving arbitrary TLVs (Type-Length-Value headers) from + * the eBPF program. This allows for full customization of these + * headers. + * Return + * The size of the option data retrieved. + * + * long bpf_skb_set_tunnel_opt(struct sk_buff *skb, void *opt, u32 size) + * Description + * Set tunnel options metadata for the packet associated to *skb* + * to the option data contained in the raw buffer *opt* of *size*. + * + * See also the description of the **bpf_skb_get_tunnel_opt**\ () + * helper for additional information. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_change_proto(struct sk_buff *skb, __be16 proto, u64 flags) + * Description + * Change the protocol of the *skb* to *proto*. Currently + * supported are transition from IPv4 to IPv6, and from IPv6 to + * IPv4. The helper takes care of the groundwork for the + * transition, including resizing the socket buffer. The eBPF + * program is expected to fill the new headers, if any, via + * **skb_store_bytes**\ () and to recompute the checksums with + * **bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ + * (). The main case for this helper is to perform NAT64 + * operations out of an eBPF program. + * + * Internally, the GSO type is marked as dodgy so that headers are + * checked and segments are recalculated by the GSO/GRO engine. + * The size for GSO target is adapted as well. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_change_type(struct sk_buff *skb, u32 type) + * Description + * Change the packet type for the packet associated to *skb*. This + * comes down to setting *skb*\ **->pkt_type** to *type*, except + * the eBPF program does not have a write access to *skb*\ + * **->pkt_type** beside this helper. Using a helper here allows + * for graceful handling of errors. + * + * The major use case is to change incoming *skb*s to + * **PACKET_HOST** in a programmatic way instead of having to + * recirculate via **redirect**\ (..., **BPF_F_INGRESS**), for + * example. + * + * Note that *type* only allows certain values. At this time, they + * are: + * + * **PACKET_HOST** + * Packet is for us. + * **PACKET_BROADCAST** + * Send packet to all. + * **PACKET_MULTICAST** + * Send packet to group. + * **PACKET_OTHERHOST** + * Send packet to someone else. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_under_cgroup(struct sk_buff *skb, struct bpf_map *map, u32 index) + * Description + * Check whether *skb* is a descendant of the cgroup2 held by + * *map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*. + * Return + * The return value depends on the result of the test, and can be: + * + * * 0, if the *skb* failed the cgroup2 descendant test. + * * 1, if the *skb* succeeded the cgroup2 descendant test. + * * A negative error code, if an error occurred. + * + * u32 bpf_get_hash_recalc(struct sk_buff *skb) + * Description + * Retrieve the hash of the packet, *skb*\ **->hash**. If it is + * not set, in particular if the hash was cleared due to mangling, + * recompute this hash. Later accesses to the hash can be done + * directly with *skb*\ **->hash**. + * + * Calling **bpf_set_hash_invalid**\ (), changing a packet + * prototype with **bpf_skb_change_proto**\ (), or calling + * **bpf_skb_store_bytes**\ () with the + * **BPF_F_INVALIDATE_HASH** are actions susceptible to clear + * the hash and to trigger a new computation for the next call to + * **bpf_get_hash_recalc**\ (). + * Return + * The 32-bit hash. + * + * u64 bpf_get_current_task(void) + * Return + * A pointer to the current task struct. + * + * long bpf_probe_write_user(void *dst, const void *src, u32 len) + * Description + * Attempt in a safe way to write *len* bytes from the buffer + * *src* to *dst* in memory. It only works for threads that are in + * user context, and *dst* must be a valid user space address. + * + * This helper should not be used to implement any kind of + * security mechanism because of TOC-TOU attacks, but rather to + * debug, divert, and manipulate execution of semi-cooperative + * processes. + * + * Keep in mind that this feature is meant for experiments, and it + * has a risk of crashing the system and running programs. + * Therefore, when an eBPF program using this helper is attached, + * a warning including PID and process name is printed to kernel + * logs. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_current_task_under_cgroup(struct bpf_map *map, u32 index) + * Description + * Check whether the probe is being run is the context of a given + * subset of the cgroup2 hierarchy. The cgroup2 to test is held by + * *map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*. + * Return + * The return value depends on the result of the test, and can be: + * + * * 0, if current task belongs to the cgroup2. + * * 1, if current task does not belong to the cgroup2. + * * A negative error code, if an error occurred. + * + * long bpf_skb_change_tail(struct sk_buff *skb, u32 len, u64 flags) + * Description + * Resize (trim or grow) the packet associated to *skb* to the + * new *len*. The *flags* are reserved for future usage, and must + * be left at zero. + * + * The basic idea is that the helper performs the needed work to + * change the size of the packet, then the eBPF program rewrites + * the rest via helpers like **bpf_skb_store_bytes**\ (), + * **bpf_l3_csum_replace**\ (), **bpf_l3_csum_replace**\ () + * and others. This helper is a slow path utility intended for + * replies with control messages. And because it is targeted for + * slow path, the helper itself can afford to be slow: it + * implicitly linearizes, unclones and drops offloads from the + * *skb*. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_pull_data(struct sk_buff *skb, u32 len) + * Description + * Pull in non-linear data in case the *skb* is non-linear and not + * all of *len* are part of the linear section. Make *len* bytes + * from *skb* readable and writable. If a zero value is passed for + * *len*, then the whole length of the *skb* is pulled. + * + * This helper is only needed for reading and writing with direct + * packet access. + * + * For direct packet access, testing that offsets to access + * are within packet boundaries (test on *skb*\ **->data_end**) is + * susceptible to fail if offsets are invalid, or if the requested + * data is in non-linear parts of the *skb*. On failure the + * program can just bail out, or in the case of a non-linear + * buffer, use a helper to make the data available. The + * **bpf_skb_load_bytes**\ () helper is a first solution to access + * the data. Another one consists in using **bpf_skb_pull_data** + * to pull in once the non-linear parts, then retesting and + * eventually access the data. + * + * At the same time, this also makes sure the *skb* is uncloned, + * which is a necessary condition for direct write. As this needs + * to be an invariant for the write part only, the verifier + * detects writes and adds a prologue that is calling + * **bpf_skb_pull_data()** to effectively unclone the *skb* from + * the very beginning in case it is indeed cloned. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * s64 bpf_csum_update(struct sk_buff *skb, __wsum csum) + * Description + * Add the checksum *csum* into *skb*\ **->csum** in case the + * driver has supplied a checksum for the entire packet into that + * field. Return an error otherwise. This helper is intended to be + * used in combination with **bpf_csum_diff**\ (), in particular + * when the checksum needs to be updated after data has been + * written into the packet through direct packet access. + * Return + * The checksum on success, or a negative error code in case of + * failure. + * + * void bpf_set_hash_invalid(struct sk_buff *skb) + * Description + * Invalidate the current *skb*\ **->hash**. It can be used after + * mangling on headers through direct packet access, in order to + * indicate that the hash is outdated and to trigger a + * recalculation the next time the kernel tries to access this + * hash or when the **bpf_get_hash_recalc**\ () helper is called. + * + * long bpf_get_numa_node_id(void) + * Description + * Return the id of the current NUMA node. The primary use case + * for this helper is the selection of sockets for the local NUMA + * node, when the program is attached to sockets using the + * **SO_ATTACH_REUSEPORT_EBPF** option (see also **socket(7)**), + * but the helper is also available to other eBPF program types, + * similarly to **bpf_get_smp_processor_id**\ (). + * Return + * The id of current NUMA node. + * + * long bpf_skb_change_head(struct sk_buff *skb, u32 len, u64 flags) + * Description + * Grows headroom of packet associated to *skb* and adjusts the + * offset of the MAC header accordingly, adding *len* bytes of + * space. It automatically extends and reallocates memory as + * required. + * + * This helper can be used on a layer 3 *skb* to push a MAC header + * for redirection into a layer 2 device. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_xdp_adjust_head(struct xdp_buff *xdp_md, int delta) + * Description + * Adjust (move) *xdp_md*\ **->data** by *delta* bytes. Note that + * it is possible to use a negative value for *delta*. This helper + * can be used to prepare the packet for pushing or popping + * headers. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read_str(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Copy a NUL terminated string from an unsafe kernel address + * *unsafe_ptr* to *dst*. See **bpf_probe_read_kernel_str**\ () for + * more details. + * + * Generally, use **bpf_probe_read_user_str**\ () or + * **bpf_probe_read_kernel_str**\ () instead. + * Return + * On success, the strictly positive length of the string, + * including the trailing NUL character. On error, a negative + * value. + * + * u64 bpf_get_socket_cookie(struct sk_buff *skb) + * Description + * If the **struct sk_buff** pointed by *skb* has a known socket, + * retrieve the cookie (generated by the kernel) of this socket. + * If no cookie has been set yet, generate a new cookie. Once + * generated, the socket cookie remains stable for the life of the + * socket. This helper can be useful for monitoring per socket + * networking traffic statistics as it provides a global socket + * identifier that can be assumed unique. + * Return + * A 8-byte long unique number on success, or 0 if the socket + * field is missing inside *skb*. + * + * u64 bpf_get_socket_cookie(struct bpf_sock_addr *ctx) + * Description + * Equivalent to bpf_get_socket_cookie() helper that accepts + * *skb*, but gets socket from **struct bpf_sock_addr** context. + * Return + * A 8-byte long unique number. + * + * u64 bpf_get_socket_cookie(struct bpf_sock_ops *ctx) + * Description + * Equivalent to **bpf_get_socket_cookie**\ () helper that accepts + * *skb*, but gets socket from **struct bpf_sock_ops** context. + * Return + * A 8-byte long unique number. + * + * u64 bpf_get_socket_cookie(struct sock *sk) + * Description + * Equivalent to **bpf_get_socket_cookie**\ () helper that accepts + * *sk*, but gets socket from a BTF **struct sock**. This helper + * also works for sleepable programs. + * Return + * A 8-byte long unique number or 0 if *sk* is NULL. + * + * u32 bpf_get_socket_uid(struct sk_buff *skb) + * Return + * The owner UID of the socket associated to *skb*. If the socket + * is **NULL**, or if it is not a full socket (i.e. if it is a + * time-wait or a request socket instead), **overflowuid** value + * is returned (note that **overflowuid** might also be the actual + * UID value for the socket). + * + * long bpf_set_hash(struct sk_buff *skb, u32 hash) + * Description + * Set the full hash for *skb* (set the field *skb*\ **->hash**) + * to value *hash*. + * Return + * 0 + * + * long bpf_setsockopt(void *bpf_socket, int level, int optname, void *optval, int optlen) + * Description + * Emulate a call to **setsockopt()** on the socket associated to + * *bpf_socket*, which must be a full socket. The *level* at + * which the option resides and the name *optname* of the option + * must be specified, see **setsockopt(2)** for more information. + * The option value of length *optlen* is pointed by *optval*. + * + * *bpf_socket* should be one of the following: + * + * * **struct bpf_sock_ops** for **BPF_PROG_TYPE_SOCK_OPS**. + * * **struct bpf_sock_addr** for **BPF_CGROUP_INET4_CONNECT** + * and **BPF_CGROUP_INET6_CONNECT**. + * + * This helper actually implements a subset of **setsockopt()**. + * It supports the following *level*\ s: + * + * * **SOL_SOCKET**, which supports the following *optname*\ s: + * **SO_RCVBUF**, **SO_SNDBUF**, **SO_MAX_PACING_RATE**, + * **SO_PRIORITY**, **SO_RCVLOWAT**, **SO_MARK**, + * **SO_BINDTODEVICE**, **SO_KEEPALIVE**. + * * **IPPROTO_TCP**, which supports the following *optname*\ s: + * **TCP_CONGESTION**, **TCP_BPF_IW**, + * **TCP_BPF_SNDCWND_CLAMP**, **TCP_SAVE_SYN**, + * **TCP_KEEPIDLE**, **TCP_KEEPINTVL**, **TCP_KEEPCNT**, + * **TCP_SYNCNT**, **TCP_USER_TIMEOUT**, **TCP_NOTSENT_LOWAT**. + * * **IPPROTO_IP**, which supports *optname* **IP_TOS**. + * * **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_adjust_room(struct sk_buff *skb, s32 len_diff, u32 mode, u64 flags) + * Description + * Grow or shrink the room for data in the packet associated to + * *skb* by *len_diff*, and according to the selected *mode*. + * + * By default, the helper will reset any offloaded checksum + * indicator of the skb to CHECKSUM_NONE. This can be avoided + * by the following flag: + * + * * **BPF_F_ADJ_ROOM_NO_CSUM_RESET**: Do not reset offloaded + * checksum data of the skb to CHECKSUM_NONE. + * + * There are two supported modes at this time: + * + * * **BPF_ADJ_ROOM_MAC**: Adjust room at the mac layer + * (room space is added or removed below the layer 2 header). + * + * * **BPF_ADJ_ROOM_NET**: Adjust room at the network layer + * (room space is added or removed below the layer 3 header). + * + * The following flags are supported at this time: + * + * * **BPF_F_ADJ_ROOM_FIXED_GSO**: Do not adjust gso_size. + * Adjusting mss in this way is not allowed for datagrams. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L3_IPV4**, + * **BPF_F_ADJ_ROOM_ENCAP_L3_IPV6**: + * Any new space is reserved to hold a tunnel header. + * Configure skb offsets and other fields accordingly. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L4_GRE**, + * **BPF_F_ADJ_ROOM_ENCAP_L4_UDP**: + * Use with ENCAP_L3 flags to further specify the tunnel type. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L2**\ (*len*): + * Use with ENCAP_L3/L4 flags to further specify the tunnel + * type; *len* is the length of the inner MAC header. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L2_ETH**: + * Use with BPF_F_ADJ_ROOM_ENCAP_L2 flag to further specify the + * L2 type as Ethernet. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags) + * Description + * Redirect the packet to the endpoint referenced by *map* at + * index *key*. Depending on its type, this *map* can contain + * references to net devices (for forwarding packets through other + * ports), or to CPUs (for redirecting XDP frames to another CPU; + * but this is only implemented for native XDP (with driver + * support) as of this writing). + * + * The lower two bits of *flags* are used as the return code if + * the map lookup fails. This is so that the return value can be + * one of the XDP program return codes up to **XDP_TX**, as chosen + * by the caller. The higher bits of *flags* can be set to + * BPF_F_BROADCAST or BPF_F_EXCLUDE_INGRESS as defined below. + * + * With BPF_F_BROADCAST the packet will be broadcasted to all the + * interfaces in the map, with BPF_F_EXCLUDE_INGRESS the ingress + * interface will be excluded when do broadcasting. + * + * See also **bpf_redirect**\ (), which only supports redirecting + * to an ifindex, but doesn't require a map to do so. + * Return + * **XDP_REDIRECT** on success, or the value of the two lower bits + * of the *flags* argument on error. + * + * long bpf_sk_redirect_map(struct sk_buff *skb, struct bpf_map *map, u32 key, u64 flags) + * Description + * Redirect the packet to the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * Return + * **SK_PASS** on success, or **SK_DROP** on error. + * + * long bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags) + * Description + * Add an entry to, or update a *map* referencing sockets. The + * *skops* is used as a new value for the entry associated to + * *key*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * If the *map* has eBPF programs (parser and verdict), those will + * be inherited by the socket being added. If the socket is + * already attached to eBPF programs, this results in an error. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_xdp_adjust_meta(struct xdp_buff *xdp_md, int delta) + * Description + * Adjust the address pointed by *xdp_md*\ **->data_meta** by + * *delta* (which can be positive or negative). Note that this + * operation modifies the address stored in *xdp_md*\ **->data**, + * so the latter must be loaded only after the helper has been + * called. + * + * The use of *xdp_md*\ **->data_meta** is optional and programs + * are not required to use it. The rationale is that when the + * packet is processed with XDP (e.g. as DoS filter), it is + * possible to push further meta data along with it before passing + * to the stack, and to give the guarantee that an ingress eBPF + * program attached as a TC classifier on the same device can pick + * this up for further post-processing. Since TC works with socket + * buffers, it remains possible to set from XDP the **mark** or + * **priority** pointers, or other pointers for the socket buffer. + * Having this scratch space generic and programmable allows for + * more flexibility as the user is free to store whatever meta + * data they need. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_perf_event_read_value(struct bpf_map *map, u64 flags, struct bpf_perf_event_value *buf, u32 buf_size) + * Description + * Read the value of a perf event counter, and store it into *buf* + * of size *buf_size*. This helper relies on a *map* of type + * **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of the perf event + * counter is selected when *map* is updated with perf event file + * descriptors. The *map* is an array whose size is the number of + * available CPUs, and each cell contains a value relative to one + * CPU. The value to retrieve is indicated by *flags*, that + * contains the index of the CPU to look up, masked with + * **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to + * **BPF_F_CURRENT_CPU** to indicate that the value for the + * current CPU should be retrieved. + * + * This helper behaves in a way close to + * **bpf_perf_event_read**\ () helper, save that instead of + * just returning the value observed, it fills the *buf* + * structure. This allows for additional data to be retrieved: in + * particular, the enabled and running times (in *buf*\ + * **->enabled** and *buf*\ **->running**, respectively) are + * copied. In general, **bpf_perf_event_read_value**\ () is + * recommended over **bpf_perf_event_read**\ (), which has some + * ABI issues and provides fewer functionalities. + * + * These values are interesting, because hardware PMU (Performance + * Monitoring Unit) counters are limited resources. When there are + * more PMU based perf events opened than available counters, + * kernel will multiplex these events so each event gets certain + * percentage (but not all) of the PMU time. In case that + * multiplexing happens, the number of samples or counter value + * will not reflect the case compared to when no multiplexing + * occurs. This makes comparison between different runs difficult. + * Typically, the counter value should be normalized before + * comparing to other experiments. The usual normalization is done + * as follows. + * + * :: + * + * normalized_counter = counter * t_enabled / t_running + * + * Where t_enabled is the time enabled for event and t_running is + * the time running for event since last normalization. The + * enabled and running times are accumulated since the perf event + * open. To achieve scaling factor between two invocations of an + * eBPF program, users can use CPU id as the key (which is + * typical for perf array usage model) to remember the previous + * value and do the calculation inside the eBPF program. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_perf_prog_read_value(struct bpf_perf_event_data *ctx, struct bpf_perf_event_value *buf, u32 buf_size) + * Description + * For en eBPF program attached to a perf event, retrieve the + * value of the event counter associated to *ctx* and store it in + * the structure pointed by *buf* and of size *buf_size*. Enabled + * and running times are also stored in the structure (see + * description of helper **bpf_perf_event_read_value**\ () for + * more details). + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_getsockopt(void *bpf_socket, int level, int optname, void *optval, int optlen) + * Description + * Emulate a call to **getsockopt()** on the socket associated to + * *bpf_socket*, which must be a full socket. The *level* at + * which the option resides and the name *optname* of the option + * must be specified, see **getsockopt(2)** for more information. + * The retrieved value is stored in the structure pointed by + * *opval* and of length *optlen*. + * + * *bpf_socket* should be one of the following: + * + * * **struct bpf_sock_ops** for **BPF_PROG_TYPE_SOCK_OPS**. + * * **struct bpf_sock_addr** for **BPF_CGROUP_INET4_CONNECT** + * and **BPF_CGROUP_INET6_CONNECT**. + * + * This helper actually implements a subset of **getsockopt()**. + * It supports the following *level*\ s: + * + * * **IPPROTO_TCP**, which supports *optname* + * **TCP_CONGESTION**. + * * **IPPROTO_IP**, which supports *optname* **IP_TOS**. + * * **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_override_return(struct pt_regs *regs, u64 rc) + * Description + * Used for error injection, this helper uses kprobes to override + * the return value of the probed function, and to set it to *rc*. + * The first argument is the context *regs* on which the kprobe + * works. + * + * This helper works by setting the PC (program counter) + * to an override function which is run in place of the original + * probed function. This means the probed function is not run at + * all. The replacement function just returns with the required + * value. + * + * This helper has security implications, and thus is subject to + * restrictions. It is only available if the kernel was compiled + * with the **CONFIG_BPF_KPROBE_OVERRIDE** configuration + * option, and in this case it only works on functions tagged with + * **ALLOW_ERROR_INJECTION** in the kernel code. + * + * Also, the helper is only available for the architectures having + * the CONFIG_FUNCTION_ERROR_INJECTION option. As of this writing, + * x86 architecture is the only one to support this feature. + * Return + * 0 + * + * long bpf_sock_ops_cb_flags_set(struct bpf_sock_ops *bpf_sock, int argval) + * Description + * Attempt to set the value of the **bpf_sock_ops_cb_flags** field + * for the full TCP socket associated to *bpf_sock_ops* to + * *argval*. + * + * The primary use of this field is to determine if there should + * be calls to eBPF programs of type + * **BPF_PROG_TYPE_SOCK_OPS** at various points in the TCP + * code. A program of the same type can change its value, per + * connection and as necessary, when the connection is + * established. This field is directly accessible for reading, but + * this helper must be used for updates in order to return an + * error if an eBPF program tries to set a callback that is not + * supported in the current kernel. + * + * *argval* is a flag array which can combine these flags: + * + * * **BPF_SOCK_OPS_RTO_CB_FLAG** (retransmission time out) + * * **BPF_SOCK_OPS_RETRANS_CB_FLAG** (retransmission) + * * **BPF_SOCK_OPS_STATE_CB_FLAG** (TCP state change) + * * **BPF_SOCK_OPS_RTT_CB_FLAG** (every RTT) + * + * Therefore, this function can be used to clear a callback flag by + * setting the appropriate bit to zero. e.g. to disable the RTO + * callback: + * + * **bpf_sock_ops_cb_flags_set(bpf_sock,** + * **bpf_sock->bpf_sock_ops_cb_flags & ~BPF_SOCK_OPS_RTO_CB_FLAG)** + * + * Here are some examples of where one could call such eBPF + * program: + * + * * When RTO fires. + * * When a packet is retransmitted. + * * When the connection terminates. + * * When a packet is sent. + * * When a packet is received. + * Return + * Code **-EINVAL** if the socket is not a full TCP socket; + * otherwise, a positive number containing the bits that could not + * be set is returned (which comes down to 0 if all bits were set + * as required). + * + * long bpf_msg_redirect_map(struct sk_msg_buff *msg, struct bpf_map *map, u32 key, u64 flags) + * Description + * This helper is used in programs implementing policies at the + * socket level. If the message *msg* is allowed to pass (i.e. if + * the verdict eBPF program returns **SK_PASS**), redirect it to + * the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * Return + * **SK_PASS** on success, or **SK_DROP** on error. + * + * long bpf_msg_apply_bytes(struct sk_msg_buff *msg, u32 bytes) + * Description + * For socket policies, apply the verdict of the eBPF program to + * the next *bytes* (number of bytes) of message *msg*. + * + * For example, this helper can be used in the following cases: + * + * * A single **sendmsg**\ () or **sendfile**\ () system call + * contains multiple logical messages that the eBPF program is + * supposed to read and for which it should apply a verdict. + * * An eBPF program only cares to read the first *bytes* of a + * *msg*. If the message has a large payload, then setting up + * and calling the eBPF program repeatedly for all bytes, even + * though the verdict is already known, would create unnecessary + * overhead. + * + * When called from within an eBPF program, the helper sets a + * counter internal to the BPF infrastructure, that is used to + * apply the last verdict to the next *bytes*. If *bytes* is + * smaller than the current data being processed from a + * **sendmsg**\ () or **sendfile**\ () system call, the first + * *bytes* will be sent and the eBPF program will be re-run with + * the pointer for start of data pointing to byte number *bytes* + * **+ 1**. If *bytes* is larger than the current data being + * processed, then the eBPF verdict will be applied to multiple + * **sendmsg**\ () or **sendfile**\ () calls until *bytes* are + * consumed. + * + * Note that if a socket closes with the internal counter holding + * a non-zero value, this is not a problem because data is not + * being buffered for *bytes* and is sent as it is received. + * Return + * 0 + * + * long bpf_msg_cork_bytes(struct sk_msg_buff *msg, u32 bytes) + * Description + * For socket policies, prevent the execution of the verdict eBPF + * program for message *msg* until *bytes* (byte number) have been + * accumulated. + * + * This can be used when one needs a specific number of bytes + * before a verdict can be assigned, even if the data spans + * multiple **sendmsg**\ () or **sendfile**\ () calls. The extreme + * case would be a user calling **sendmsg**\ () repeatedly with + * 1-byte long message segments. Obviously, this is bad for + * performance, but it is still valid. If the eBPF program needs + * *bytes* bytes to validate a header, this helper can be used to + * prevent the eBPF program to be called again until *bytes* have + * been accumulated. + * Return + * 0 + * + * long bpf_msg_pull_data(struct sk_msg_buff *msg, u32 start, u32 end, u64 flags) + * Description + * For socket policies, pull in non-linear data from user space + * for *msg* and set pointers *msg*\ **->data** and *msg*\ + * **->data_end** to *start* and *end* bytes offsets into *msg*, + * respectively. + * + * If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a + * *msg* it can only parse data that the (**data**, **data_end**) + * pointers have already consumed. For **sendmsg**\ () hooks this + * is likely the first scatterlist element. But for calls relying + * on the **sendpage** handler (e.g. **sendfile**\ ()) this will + * be the range (**0**, **0**) because the data is shared with + * user space and by default the objective is to avoid allowing + * user space to modify data while (or after) eBPF verdict is + * being decided. This helper can be used to pull in data and to + * set the start and end pointer to given values. Data will be + * copied if necessary (i.e. if data was not linear and if start + * and end pointers do not point to the same chunk). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_bind(struct bpf_sock_addr *ctx, struct sockaddr *addr, int addr_len) + * Description + * Bind the socket associated to *ctx* to the address pointed by + * *addr*, of length *addr_len*. This allows for making outgoing + * connection from the desired IP address, which can be useful for + * example when all processes inside a cgroup should use one + * single IP address on a host that has multiple IP configured. + * + * This helper works for IPv4 and IPv6, TCP and UDP sockets. The + * domain (*addr*\ **->sa_family**) must be **AF_INET** (or + * **AF_INET6**). It's advised to pass zero port (**sin_port** + * or **sin6_port**) which triggers IP_BIND_ADDRESS_NO_PORT-like + * behavior and lets the kernel efficiently pick up an unused + * port as long as 4-tuple is unique. Passing non-zero port might + * lead to degraded performance. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_xdp_adjust_tail(struct xdp_buff *xdp_md, int delta) + * Description + * Adjust (move) *xdp_md*\ **->data_end** by *delta* bytes. It is + * possible to both shrink and grow the packet tail. + * Shrink done via *delta* being a negative integer. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_get_xfrm_state(struct sk_buff *skb, u32 index, struct bpf_xfrm_state *xfrm_state, u32 size, u64 flags) + * Description + * Retrieve the XFRM state (IP transform framework, see also + * **ip-xfrm(8)**) at *index* in XFRM "security path" for *skb*. + * + * The retrieved value is stored in the **struct bpf_xfrm_state** + * pointed by *xfrm_state* and of length *size*. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_XFRM** configuration option. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_get_stack(void *ctx, void *buf, u32 size, u64 flags) + * Description + * Return a user or a kernel stack in bpf program provided buffer. + * To achieve this, the helper needs *ctx*, which is a pointer + * to the context on which the tracing program is executed. + * To store the stacktrace, the bpf program provides *buf* with + * a nonnegative *size*. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_USER_BUILD_ID** + * Collect buildid+offset instead of ips for user stack, + * only valid if **BPF_F_USER_STACK** is also specified. + * + * **bpf_get_stack**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames, subject + * to sufficient large buffer size. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * Return + * A non-negative value equal to or less than *size* on success, + * or a negative error in case of failure. + * + * long bpf_skb_load_bytes_relative(const void *skb, u32 offset, void *to, u32 len, u32 start_header) + * Description + * This helper is similar to **bpf_skb_load_bytes**\ () in that + * it provides an easy way to load *len* bytes from *offset* + * from the packet associated to *skb*, into the buffer pointed + * by *to*. The difference to **bpf_skb_load_bytes**\ () is that + * a fifth argument *start_header* exists in order to select a + * base offset to start from. *start_header* can be one of: + * + * **BPF_HDR_START_MAC** + * Base offset to load data from is *skb*'s mac header. + * **BPF_HDR_START_NET** + * Base offset to load data from is *skb*'s network header. + * + * In general, "direct packet access" is the preferred method to + * access packet data, however, this helper is in particular useful + * in socket filters where *skb*\ **->data** does not always point + * to the start of the mac header and where "direct packet access" + * is not available. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_fib_lookup(void *ctx, struct bpf_fib_lookup *params, int plen, u32 flags) + * Description + * Do FIB lookup in kernel tables using parameters in *params*. + * If lookup is successful and result shows packet is to be + * forwarded, the neighbor tables are searched for the nexthop. + * If successful (ie., FIB lookup shows forwarding and nexthop + * is resolved), the nexthop address is returned in ipv4_dst + * or ipv6_dst based on family, smac is set to mac address of + * egress device, dmac is set to nexthop mac address, rt_metric + * is set to metric from route (IPv4/IPv6 only), and ifindex + * is set to the device index of the nexthop from the FIB lookup. + * + * *plen* argument is the size of the passed in struct. + * *flags* argument can be a combination of one or more of the + * following values: + * + * **BPF_FIB_LOOKUP_DIRECT** + * Do a direct table lookup vs full lookup using FIB + * rules. + * **BPF_FIB_LOOKUP_OUTPUT** + * Perform lookup from an egress perspective (default is + * ingress). + * + * *ctx* is either **struct xdp_md** for XDP programs or + * **struct sk_buff** tc cls_act programs. + * Return + * * < 0 if any input argument is invalid + * * 0 on success (packet is forwarded, nexthop neighbor exists) + * * > 0 one of **BPF_FIB_LKUP_RET_** codes explaining why the + * packet is not forwarded or needs assist from full stack + * + * If lookup fails with BPF_FIB_LKUP_RET_FRAG_NEEDED, then the MTU + * was exceeded and output params->mtu_result contains the MTU. + * + * long bpf_sock_hash_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags) + * Description + * Add an entry to, or update a sockhash *map* referencing sockets. + * The *skops* is used as a new value for the entry associated to + * *key*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * If the *map* has eBPF programs (parser and verdict), those will + * be inherited by the socket being added. If the socket is + * already attached to eBPF programs, this results in an error. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_msg_redirect_hash(struct sk_msg_buff *msg, struct bpf_map *map, void *key, u64 flags) + * Description + * This helper is used in programs implementing policies at the + * socket level. If the message *msg* is allowed to pass (i.e. if + * the verdict eBPF program returns **SK_PASS**), redirect it to + * the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * Return + * **SK_PASS** on success, or **SK_DROP** on error. + * + * long bpf_sk_redirect_hash(struct sk_buff *skb, struct bpf_map *map, void *key, u64 flags) + * Description + * This helper is used in programs implementing policies at the + * skb socket level. If the sk_buff *skb* is allowed to pass (i.e. + * if the verdict eBPF program returns **SK_PASS**), redirect it + * to the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress otherwise). This is the only flag supported for now. + * Return + * **SK_PASS** on success, or **SK_DROP** on error. + * + * long bpf_lwt_push_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len) + * Description + * Encapsulate the packet associated to *skb* within a Layer 3 + * protocol header. This header is provided in the buffer at + * address *hdr*, with *len* its size in bytes. *type* indicates + * the protocol of the header and can be one of: + * + * **BPF_LWT_ENCAP_SEG6** + * IPv6 encapsulation with Segment Routing Header + * (**struct ipv6_sr_hdr**). *hdr* only contains the SRH, + * the IPv6 header is computed by the kernel. + * **BPF_LWT_ENCAP_SEG6_INLINE** + * Only works if *skb* contains an IPv6 packet. Insert a + * Segment Routing Header (**struct ipv6_sr_hdr**) inside + * the IPv6 header. + * **BPF_LWT_ENCAP_IP** + * IP encapsulation (GRE/GUE/IPIP/etc). The outer header + * must be IPv4 or IPv6, followed by zero or more + * additional headers, up to **LWT_BPF_MAX_HEADROOM** + * total bytes in all prepended headers. Please note that + * if **skb_is_gso**\ (*skb*) is true, no more than two + * headers can be prepended, and the inner header, if + * present, should be either GRE or UDP/GUE. + * + * **BPF_LWT_ENCAP_SEG6**\ \* types can be called by BPF programs + * of type **BPF_PROG_TYPE_LWT_IN**; **BPF_LWT_ENCAP_IP** type can + * be called by bpf programs of types **BPF_PROG_TYPE_LWT_IN** and + * **BPF_PROG_TYPE_LWT_XMIT**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_lwt_seg6_store_bytes(struct sk_buff *skb, u32 offset, const void *from, u32 len) + * Description + * Store *len* bytes from address *from* into the packet + * associated to *skb*, at *offset*. Only the flags, tag and TLVs + * inside the outermost IPv6 Segment Routing Header can be + * modified through this helper. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_lwt_seg6_adjust_srh(struct sk_buff *skb, u32 offset, s32 delta) + * Description + * Adjust the size allocated to TLVs in the outermost IPv6 + * Segment Routing Header contained in the packet associated to + * *skb*, at position *offset* by *delta* bytes. Only offsets + * after the segments are accepted. *delta* can be as well + * positive (growing) as negative (shrinking). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_lwt_seg6_action(struct sk_buff *skb, u32 action, void *param, u32 param_len) + * Description + * Apply an IPv6 Segment Routing action of type *action* to the + * packet associated to *skb*. Each action takes a parameter + * contained at address *param*, and of length *param_len* bytes. + * *action* can be one of: + * + * **SEG6_LOCAL_ACTION_END_X** + * End.X action: Endpoint with Layer-3 cross-connect. + * Type of *param*: **struct in6_addr**. + * **SEG6_LOCAL_ACTION_END_T** + * End.T action: Endpoint with specific IPv6 table lookup. + * Type of *param*: **int**. + * **SEG6_LOCAL_ACTION_END_B6** + * End.B6 action: Endpoint bound to an SRv6 policy. + * Type of *param*: **struct ipv6_sr_hdr**. + * **SEG6_LOCAL_ACTION_END_B6_ENCAP** + * End.B6.Encap action: Endpoint bound to an SRv6 + * encapsulation policy. + * Type of *param*: **struct ipv6_sr_hdr**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_rc_repeat(void *ctx) + * Description + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded repeat key message. This delays + * the generation of a key up event for previously generated + * key down event. + * + * Some IR protocols like NEC have a special IR message for + * repeating last button, for when a button is held down. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * Return + * 0 + * + * long bpf_rc_keydown(void *ctx, u32 protocol, u64 scancode, u32 toggle) + * Description + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded key press with *scancode*, + * *toggle* value in the given *protocol*. The scancode will be + * translated to a keycode using the rc keymap, and reported as + * an input key down event. After a period a key up event is + * generated. This period can be extended by calling either + * **bpf_rc_keydown**\ () again with the same values, or calling + * **bpf_rc_repeat**\ (). + * + * Some protocols include a toggle bit, in case the button was + * released and pressed again between consecutive scancodes. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * The *protocol* is the decoded protocol number (see + * **enum rc_proto** for some predefined values). + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * Return + * 0 + * + * u64 bpf_skb_cgroup_id(struct sk_buff *skb) + * Description + * Return the cgroup v2 id of the socket associated with the *skb*. + * This is roughly similar to the **bpf_get_cgroup_classid**\ () + * helper for cgroup v1 by providing a tag resp. identifier that + * can be matched on or used for map lookups e.g. to implement + * policy. The cgroup v2 id of a given path in the hierarchy is + * exposed in user space through the f_handle API in order to get + * to the same 64-bit id. + * + * This helper can be used on TC egress path, but not on ingress, + * and is available only if the kernel was compiled with the + * **CONFIG_SOCK_CGROUP_DATA** configuration option. + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * u64 bpf_get_current_cgroup_id(void) + * Return + * A 64-bit integer containing the current cgroup id based + * on the cgroup within which the current task is running. + * + * void *bpf_get_local_storage(void *map, u64 flags) + * Description + * Get the pointer to the local storage area. + * The type and the size of the local storage is defined + * by the *map* argument. + * The *flags* meaning is specific for each map type, + * and has to be 0 for cgroup local storage. + * + * Depending on the BPF program type, a local storage area + * can be shared between multiple instances of the BPF program, + * running simultaneously. + * + * A user should care about the synchronization by himself. + * For example, by using the **BPF_ATOMIC** instructions to alter + * the shared data. + * Return + * A pointer to the local storage area. + * + * long bpf_sk_select_reuseport(struct sk_reuseport_md *reuse, struct bpf_map *map, void *key, u64 flags) + * Description + * Select a **SO_REUSEPORT** socket from a + * **BPF_MAP_TYPE_REUSEPORT_ARRAY** *map*. + * It checks the selected socket is matching the incoming + * request in the socket buffer. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_skb_ancestor_cgroup_id(struct sk_buff *skb, int ancestor_level) + * Description + * Return id of cgroup v2 that is ancestor of cgroup associated + * with the *skb* at the *ancestor_level*. The root cgroup is at + * *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with *skb*, then return value will be same as that + * of **bpf_skb_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with *skb*. + * + * The format of returned id and helper limitations are same as in + * **bpf_skb_cgroup_id**\ (). + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * struct bpf_sock *bpf_sk_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) + * Description + * Look for TCP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * The *ctx* should point to the context of the program, such as + * the skb or socket (depending on the hook in use). This is used + * to determine the base network namespace for the lookup. + * + * *tuple_size* must be one of: + * + * **sizeof**\ (*tuple*\ **->ipv4**) + * Look for an IPv4 socket. + * **sizeof**\ (*tuple*\ **->ipv6**) + * Look for an IPv6 socket. + * + * If the *netns* is a negative signed 32-bit integer, then the + * socket lookup table in the netns associated with the *ctx* + * will be used. For the TC hooks, this is the netns of the device + * in the skb. For socket hooks, this is the netns of the socket. + * If *netns* is any other signed 32-bit value greater than or + * equal to zero then it specifies the ID of the netns relative to + * the netns associated with the *ctx*. *netns* values beyond the + * range of 32-bit integers are reserved for future use. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * Return + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + * + * struct bpf_sock *bpf_sk_lookup_udp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) + * Description + * Look for UDP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * The *ctx* should point to the context of the program, such as + * the skb or socket (depending on the hook in use). This is used + * to determine the base network namespace for the lookup. + * + * *tuple_size* must be one of: + * + * **sizeof**\ (*tuple*\ **->ipv4**) + * Look for an IPv4 socket. + * **sizeof**\ (*tuple*\ **->ipv6**) + * Look for an IPv6 socket. + * + * If the *netns* is a negative signed 32-bit integer, then the + * socket lookup table in the netns associated with the *ctx* + * will be used. For the TC hooks, this is the netns of the device + * in the skb. For socket hooks, this is the netns of the socket. + * If *netns* is any other signed 32-bit value greater than or + * equal to zero then it specifies the ID of the netns relative to + * the netns associated with the *ctx*. *netns* values beyond the + * range of 32-bit integers are reserved for future use. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * Return + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + * + * long bpf_sk_release(void *sock) + * Description + * Release the reference held by *sock*. *sock* must be a + * non-**NULL** pointer that was returned from + * **bpf_sk_lookup_xxx**\ (). + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_map_push_elem(struct bpf_map *map, const void *value, u64 flags) + * Description + * Push an element *value* in *map*. *flags* is one of: + * + * **BPF_EXIST** + * If the queue/stack is full, the oldest element is + * removed to make room for this. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_map_pop_elem(struct bpf_map *map, void *value) + * Description + * Pop an element from *map*. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_map_peek_elem(struct bpf_map *map, void *value) + * Description + * Get an element from *map* without removing it. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_msg_push_data(struct sk_msg_buff *msg, u32 start, u32 len, u64 flags) + * Description + * For socket policies, insert *len* bytes into *msg* at offset + * *start*. + * + * If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a + * *msg* it may want to insert metadata or options into the *msg*. + * This can later be read and used by any of the lower layer BPF + * hooks. + * + * This helper may fail if under memory pressure (a malloc + * fails) in these cases BPF programs will get an appropriate + * error and BPF programs will need to handle them. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_msg_pop_data(struct sk_msg_buff *msg, u32 start, u32 len, u64 flags) + * Description + * Will remove *len* bytes from a *msg* starting at byte *start*. + * This may result in **ENOMEM** errors under certain situations if + * an allocation and copy are required due to a full ring buffer. + * However, the helper will try to avoid doing the allocation + * if possible. Other errors can occur if input parameters are + * invalid either due to *start* byte not being valid part of *msg* + * payload and/or *pop* value being to large. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_rc_pointer_rel(void *ctx, s32 rel_x, s32 rel_y) + * Description + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded pointer movement. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * Return + * 0 + * + * long bpf_spin_lock(struct bpf_spin_lock *lock) + * Description + * Acquire a spinlock represented by the pointer *lock*, which is + * stored as part of a value of a map. Taking the lock allows to + * safely update the rest of the fields in that value. The + * spinlock can (and must) later be released with a call to + * **bpf_spin_unlock**\ (\ *lock*\ ). + * + * Spinlocks in BPF programs come with a number of restrictions + * and constraints: + * + * * **bpf_spin_lock** objects are only allowed inside maps of + * types **BPF_MAP_TYPE_HASH** and **BPF_MAP_TYPE_ARRAY** (this + * list could be extended in the future). + * * BTF description of the map is mandatory. + * * The BPF program can take ONE lock at a time, since taking two + * or more could cause dead locks. + * * Only one **struct bpf_spin_lock** is allowed per map element. + * * When the lock is taken, calls (either BPF to BPF or helpers) + * are not allowed. + * * The **BPF_LD_ABS** and **BPF_LD_IND** instructions are not + * allowed inside a spinlock-ed region. + * * The BPF program MUST call **bpf_spin_unlock**\ () to release + * the lock, on all execution paths, before it returns. + * * The BPF program can access **struct bpf_spin_lock** only via + * the **bpf_spin_lock**\ () and **bpf_spin_unlock**\ () + * helpers. Loading or storing data into the **struct + * bpf_spin_lock** *lock*\ **;** field of a map is not allowed. + * * To use the **bpf_spin_lock**\ () helper, the BTF description + * of the map value must be a struct and have **struct + * bpf_spin_lock** *anyname*\ **;** field at the top level. + * Nested lock inside another struct is not allowed. + * * The **struct bpf_spin_lock** *lock* field in a map value must + * be aligned on a multiple of 4 bytes in that value. + * * Syscall with command **BPF_MAP_LOOKUP_ELEM** does not copy + * the **bpf_spin_lock** field to user space. + * * Syscall with command **BPF_MAP_UPDATE_ELEM**, or update from + * a BPF program, do not update the **bpf_spin_lock** field. + * * **bpf_spin_lock** cannot be on the stack or inside a + * networking packet (it can only be inside of a map values). + * * **bpf_spin_lock** is available to root only. + * * Tracing programs and socket filter programs cannot use + * **bpf_spin_lock**\ () due to insufficient preemption checks + * (but this may change in the future). + * * **bpf_spin_lock** is not allowed in inner maps of map-in-map. + * Return + * 0 + * + * long bpf_spin_unlock(struct bpf_spin_lock *lock) + * Description + * Release the *lock* previously locked by a call to + * **bpf_spin_lock**\ (\ *lock*\ ). + * Return + * 0 + * + * struct bpf_sock *bpf_sk_fullsock(struct bpf_sock *sk) + * Description + * This helper gets a **struct bpf_sock** pointer such + * that all the fields in this **bpf_sock** can be accessed. + * Return + * A **struct bpf_sock** pointer on success, or **NULL** in + * case of failure. + * + * struct bpf_tcp_sock *bpf_tcp_sock(struct bpf_sock *sk) + * Description + * This helper gets a **struct bpf_tcp_sock** pointer from a + * **struct bpf_sock** pointer. + * Return + * A **struct bpf_tcp_sock** pointer on success, or **NULL** in + * case of failure. + * + * long bpf_skb_ecn_set_ce(struct sk_buff *skb) + * Description + * Set ECN (Explicit Congestion Notification) field of IP header + * to **CE** (Congestion Encountered) if current value is **ECT** + * (ECN Capable Transport). Otherwise, do nothing. Works with IPv6 + * and IPv4. + * Return + * 1 if the **CE** flag is set (either by the current helper call + * or because it was already present), 0 if it is not set. + * + * struct bpf_sock *bpf_get_listener_sock(struct bpf_sock *sk) + * Description + * Return a **struct bpf_sock** pointer in **TCP_LISTEN** state. + * **bpf_sk_release**\ () is unnecessary and not allowed. + * Return + * A **struct bpf_sock** pointer on success, or **NULL** in + * case of failure. + * + * struct bpf_sock *bpf_skc_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) + * Description + * Look for TCP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * This function is identical to **bpf_sk_lookup_tcp**\ (), except + * that it also returns timewait or request sockets. Use + * **bpf_sk_fullsock**\ () or **bpf_tcp_sock**\ () to access the + * full structure. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * Return + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + * + * long bpf_tcp_check_syncookie(void *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len) + * Description + * Check whether *iph* and *th* contain a valid SYN cookie ACK for + * the listening socket in *sk*. + * + * *iph* points to the start of the IPv4 or IPv6 header, while + * *iph_len* contains **sizeof**\ (**struct iphdr**) or + * **sizeof**\ (**struct ip6hdr**). + * + * *th* points to the start of the TCP header, while *th_len* + * contains **sizeof**\ (**struct tcphdr**). + * Return + * 0 if *iph* and *th* are a valid SYN cookie ACK, or a negative + * error otherwise. + * + * long bpf_sysctl_get_name(struct bpf_sysctl *ctx, char *buf, size_t buf_len, u64 flags) + * Description + * Get name of sysctl in /proc/sys/ and copy it into provided by + * program buffer *buf* of size *buf_len*. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * + * If *flags* is zero, full name (e.g. "net/ipv4/tcp_mem") is + * copied. Use **BPF_F_SYSCTL_BASE_NAME** flag to copy base name + * only (e.g. "tcp_mem"). + * Return + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + * + * long bpf_sysctl_get_current_value(struct bpf_sysctl *ctx, char *buf, size_t buf_len) + * Description + * Get current value of sysctl as it is presented in /proc/sys + * (incl. newline, etc), and copy it as a string into provided + * by program buffer *buf* of size *buf_len*. + * + * The whole value is copied, no matter what file position user + * space issued e.g. sys_read at. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * Return + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + * + * **-EINVAL** if current value was unavailable, e.g. because + * sysctl is uninitialized and read returns -EIO for it. + * + * long bpf_sysctl_get_new_value(struct bpf_sysctl *ctx, char *buf, size_t buf_len) + * Description + * Get new value being written by user space to sysctl (before + * the actual write happens) and copy it as a string into + * provided by program buffer *buf* of size *buf_len*. + * + * User space may write new value at file position > 0. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * Return + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + * + * **-EINVAL** if sysctl is being read. + * + * long bpf_sysctl_set_new_value(struct bpf_sysctl *ctx, const char *buf, size_t buf_len) + * Description + * Override new value being written by user space to sysctl with + * value provided by program in buffer *buf* of size *buf_len*. + * + * *buf* should contain a string in same form as provided by user + * space on sysctl write. + * + * User space may write new value at file position > 0. To override + * the whole sysctl value file position should be set to zero. + * Return + * 0 on success. + * + * **-E2BIG** if the *buf_len* is too big. + * + * **-EINVAL** if sysctl is being read. + * + * long bpf_strtol(const char *buf, size_t buf_len, u64 flags, long *res) + * Description + * Convert the initial part of the string from buffer *buf* of + * size *buf_len* to a long integer according to the given base + * and save the result in *res*. + * + * The string may begin with an arbitrary amount of white space + * (as determined by **isspace**\ (3)) followed by a single + * optional '**-**' sign. + * + * Five least significant bits of *flags* encode base, other bits + * are currently unused. + * + * Base must be either 8, 10, 16 or 0 to detect it automatically + * similar to user space **strtol**\ (3). + * Return + * Number of characters consumed on success. Must be positive but + * no more than *buf_len*. + * + * **-EINVAL** if no valid digits were found or unsupported base + * was provided. + * + * **-ERANGE** if resulting value was out of range. + * + * long bpf_strtoul(const char *buf, size_t buf_len, u64 flags, unsigned long *res) + * Description + * Convert the initial part of the string from buffer *buf* of + * size *buf_len* to an unsigned long integer according to the + * given base and save the result in *res*. + * + * The string may begin with an arbitrary amount of white space + * (as determined by **isspace**\ (3)). + * + * Five least significant bits of *flags* encode base, other bits + * are currently unused. + * + * Base must be either 8, 10, 16 or 0 to detect it automatically + * similar to user space **strtoul**\ (3). + * Return + * Number of characters consumed on success. Must be positive but + * no more than *buf_len*. + * + * **-EINVAL** if no valid digits were found or unsupported base + * was provided. + * + * **-ERANGE** if resulting value was out of range. + * + * void *bpf_sk_storage_get(struct bpf_map *map, void *sk, void *value, u64 flags) + * Description + * Get a bpf-local-storage from a *sk*. + * + * Logically, it could be thought of getting the value from + * a *map* with *sk* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *sk*) except this + * helper enforces the key must be a full socket and the map must + * be a **BPF_MAP_TYPE_SK_STORAGE** also. + * + * Underneath, the value is stored locally at *sk* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf-local-storages residing at *sk*. + * + * *sk* is a kernel **struct sock** pointer for LSM program. + * *sk* is a **struct bpf_sock** pointer for other program types. + * + * An optional *flags* (**BPF_SK_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf-local-storage will be + * created if one does not exist. *value* can be used + * together with **BPF_SK_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf-local-storage. If *value* is + * **NULL**, the new bpf-local-storage will be zero initialized. + * Return + * A bpf-local-storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf-local-storage. + * + * long bpf_sk_storage_delete(struct bpf_map *map, void *sk) + * Description + * Delete a bpf-local-storage from a *sk*. + * Return + * 0 on success. + * + * **-ENOENT** if the bpf-local-storage cannot be found. + * **-EINVAL** if sk is not a fullsock (e.g. a request_sock). + * + * long bpf_send_signal(u32 sig) + * Description + * Send signal *sig* to the process of the current task. + * The signal may be delivered to any of this process's threads. + * Return + * 0 on success or successfully queued. + * + * **-EBUSY** if work queue under nmi is full. + * + * **-EINVAL** if *sig* is invalid. + * + * **-EPERM** if no permission to send the *sig*. + * + * **-EAGAIN** if bpf program can try again. + * + * s64 bpf_tcp_gen_syncookie(void *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len) + * Description + * Try to issue a SYN cookie for the packet with corresponding + * IP/TCP headers, *iph* and *th*, on the listening socket in *sk*. + * + * *iph* points to the start of the IPv4 or IPv6 header, while + * *iph_len* contains **sizeof**\ (**struct iphdr**) or + * **sizeof**\ (**struct ip6hdr**). + * + * *th* points to the start of the TCP header, while *th_len* + * contains the length of the TCP header. + * Return + * On success, lower 32 bits hold the generated SYN cookie in + * followed by 16 bits which hold the MSS value for that cookie, + * and the top 16 bits are unused. + * + * On failure, the returned value is one of the following: + * + * **-EINVAL** SYN cookie cannot be issued due to error + * + * **-ENOENT** SYN cookie should not be issued (no SYN flood) + * + * **-EOPNOTSUPP** kernel configuration does not enable SYN cookies + * + * **-EPROTONOSUPPORT** IP packet version is not 4 or 6 + * + * long bpf_skb_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) + * Description + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * *ctx* is a pointer to in-kernel struct sk_buff. + * + * This helper is similar to **bpf_perf_event_output**\ () but + * restricted to raw_tracepoint bpf programs. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read_user(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Safely attempt to read *size* bytes from user space address + * *unsafe_ptr* and store the data in *dst*. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Safely attempt to read *size* bytes from kernel space address + * *unsafe_ptr* and store the data in *dst*. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read_user_str(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Copy a NUL terminated string from an unsafe user address + * *unsafe_ptr* to *dst*. The *size* should include the + * terminating NUL byte. In case the string length is smaller than + * *size*, the target is not padded with further NUL bytes. If the + * string length is larger than *size*, just *size*-1 bytes are + * copied and the last byte is set to NUL. + * + * On success, returns the number of bytes that were written, + * including the terminal NUL. This makes this helper useful in + * tracing programs for reading strings, and more importantly to + * get its length at runtime. See the following snippet: + * + * :: + * + * SEC("kprobe/sys_open") + * void bpf_sys_open(struct pt_regs *ctx) + * { + * char buf[PATHLEN]; // PATHLEN is defined to 256 + * int res = bpf_probe_read_user_str(buf, sizeof(buf), + * ctx->di); + * + * // Consume buf, for example push it to + * // userspace via bpf_perf_event_output(); we + * // can use res (the string length) as event + * // size, after checking its boundaries. + * } + * + * In comparison, using **bpf_probe_read_user**\ () helper here + * instead to read the string would require to estimate the length + * at compile time, and would often result in copying more memory + * than necessary. + * + * Another useful use case is when parsing individual process + * arguments or individual environment variables navigating + * *current*\ **->mm->arg_start** and *current*\ + * **->mm->env_start**: using this helper and the return value, + * one can quickly iterate at the right offset of the memory area. + * Return + * On success, the strictly positive length of the output string, + * including the trailing NUL character. On error, a negative + * value. + * + * long bpf_probe_read_kernel_str(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Copy a NUL terminated string from an unsafe kernel address *unsafe_ptr* + * to *dst*. Same semantics as with **bpf_probe_read_user_str**\ () apply. + * Return + * On success, the strictly positive length of the string, including + * the trailing NUL character. On error, a negative value. + * + * long bpf_tcp_send_ack(void *tp, u32 rcv_nxt) + * Description + * Send out a tcp-ack. *tp* is the in-kernel struct **tcp_sock**. + * *rcv_nxt* is the ack_seq to be sent out. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_send_signal_thread(u32 sig) + * Description + * Send signal *sig* to the thread corresponding to the current task. + * Return + * 0 on success or successfully queued. + * + * **-EBUSY** if work queue under nmi is full. + * + * **-EINVAL** if *sig* is invalid. + * + * **-EPERM** if no permission to send the *sig*. + * + * **-EAGAIN** if bpf program can try again. + * + * u64 bpf_jiffies64(void) + * Description + * Obtain the 64bit jiffies + * Return + * The 64 bit jiffies + * + * long bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, u32 size, u64 flags) + * Description + * For an eBPF program attached to a perf event, retrieve the + * branch records (**struct perf_branch_entry**) associated to *ctx* + * and store it in the buffer pointed by *buf* up to size + * *size* bytes. + * Return + * On success, number of bytes written to *buf*. On error, a + * negative value. + * + * The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to + * instead return the number of bytes required to store all the + * branch entries. If this flag is set, *buf* may be NULL. + * + * **-EINVAL** if arguments invalid or **size** not a multiple + * of **sizeof**\ (**struct perf_branch_entry**\ ). + * + * **-ENOENT** if architecture does not support branch records. + * + * long bpf_get_ns_current_pid_tgid(u64 dev, u64 ino, struct bpf_pidns_info *nsdata, u32 size) + * Description + * Returns 0 on success, values for *pid* and *tgid* as seen from the current + * *namespace* will be returned in *nsdata*. + * Return + * 0 on success, or one of the following in case of failure: + * + * **-EINVAL** if dev and inum supplied don't match dev_t and inode number + * with nsfs of current task, or if dev conversion to dev_t lost high bits. + * + * **-ENOENT** if pidns does not exists for the current task. + * + * long bpf_xdp_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) + * Description + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * *ctx* is a pointer to in-kernel struct xdp_buff. + * + * This helper is similar to **bpf_perf_eventoutput**\ () but + * restricted to raw_tracepoint bpf programs. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_get_netns_cookie(void *ctx) + * Description + * Retrieve the cookie (generated by the kernel) of the network + * namespace the input *ctx* is associated with. The network + * namespace cookie remains stable for its lifetime and provides + * a global identifier that can be assumed unique. If *ctx* is + * NULL, then the helper returns the cookie for the initial + * network namespace. The cookie itself is very similar to that + * of **bpf_get_socket_cookie**\ () helper, but for network + * namespaces instead of sockets. + * Return + * A 8-byte long opaque number. + * + * u64 bpf_get_current_ancestor_cgroup_id(int ancestor_level) + * Description + * Return id of cgroup v2 that is ancestor of the cgroup associated + * with the current task at the *ancestor_level*. The root cgroup + * is at *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with the current task, then return value will be the + * same as that of **bpf_get_current_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with the current task. + * + * The format of returned id and helper limitations are same as in + * **bpf_get_current_cgroup_id**\ (). + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * long bpf_sk_assign(struct sk_buff *skb, void *sk, u64 flags) + * Description + * Helper is overloaded depending on BPF program type. This + * description applies to **BPF_PROG_TYPE_SCHED_CLS** and + * **BPF_PROG_TYPE_SCHED_ACT** programs. + * + * Assign the *sk* to the *skb*. When combined with appropriate + * routing configuration to receive the packet towards the socket, + * will cause *skb* to be delivered to the specified socket. + * Subsequent redirection of *skb* via **bpf_redirect**\ (), + * **bpf_clone_redirect**\ () or other methods outside of BPF may + * interfere with successful delivery to the socket. + * + * This operation is only valid from TC ingress path. + * + * The *flags* argument must be zero. + * Return + * 0 on success, or a negative error in case of failure: + * + * **-EINVAL** if specified *flags* are not supported. + * + * **-ENOENT** if the socket is unavailable for assignment. + * + * **-ENETUNREACH** if the socket is unreachable (wrong netns). + * + * **-EOPNOTSUPP** if the operation is not supported, for example + * a call from outside of TC ingress. + * + * **-ESOCKTNOSUPPORT** if the socket type is not supported + * (reuseport). + * + * long bpf_sk_assign(struct bpf_sk_lookup *ctx, struct bpf_sock *sk, u64 flags) + * Description + * Helper is overloaded depending on BPF program type. This + * description applies to **BPF_PROG_TYPE_SK_LOOKUP** programs. + * + * Select the *sk* as a result of a socket lookup. + * + * For the operation to succeed passed socket must be compatible + * with the packet description provided by the *ctx* object. + * + * L4 protocol (**IPPROTO_TCP** or **IPPROTO_UDP**) must + * be an exact match. While IP family (**AF_INET** or + * **AF_INET6**) must be compatible, that is IPv6 sockets + * that are not v6-only can be selected for IPv4 packets. + * + * Only TCP listeners and UDP unconnected sockets can be + * selected. *sk* can also be NULL to reset any previous + * selection. + * + * *flags* argument can combination of following values: + * + * * **BPF_SK_LOOKUP_F_REPLACE** to override the previous + * socket selection, potentially done by a BPF program + * that ran before us. + * + * * **BPF_SK_LOOKUP_F_NO_REUSEPORT** to skip + * load-balancing within reuseport group for the socket + * being selected. + * + * On success *ctx->sk* will point to the selected socket. + * + * Return + * 0 on success, or a negative errno in case of failure. + * + * * **-EAFNOSUPPORT** if socket family (*sk->family*) is + * not compatible with packet family (*ctx->family*). + * + * * **-EEXIST** if socket has been already selected, + * potentially by another program, and + * **BPF_SK_LOOKUP_F_REPLACE** flag was not specified. + * + * * **-EINVAL** if unsupported flags were specified. + * + * * **-EPROTOTYPE** if socket L4 protocol + * (*sk->protocol*) doesn't match packet protocol + * (*ctx->protocol*). + * + * * **-ESOCKTNOSUPPORT** if socket is not in allowed + * state (TCP listening or UDP unconnected). + * + * u64 bpf_ktime_get_boot_ns(void) + * Description + * Return the time elapsed since system boot, in nanoseconds. + * Does include the time the system was suspended. + * See: **clock_gettime**\ (**CLOCK_BOOTTIME**) + * Return + * Current *ktime*. + * + * long bpf_seq_printf(struct seq_file *m, const char *fmt, u32 fmt_size, const void *data, u32 data_len) + * Description + * **bpf_seq_printf**\ () uses seq_file **seq_printf**\ () to print + * out the format string. + * The *m* represents the seq_file. The *fmt* and *fmt_size* are for + * the format string itself. The *data* and *data_len* are format string + * arguments. The *data* are a **u64** array and corresponding format string + * values are stored in the array. For strings and pointers where pointees + * are accessed, only the pointer values are stored in the *data* array. + * The *data_len* is the size of *data* in bytes. + * + * Formats **%s**, **%p{i,I}{4,6}** requires to read kernel memory. + * Reading kernel memory may fail due to either invalid address or + * valid address but requiring a major memory fault. If reading kernel memory + * fails, the string for **%s** will be an empty string, and the ip + * address for **%p{i,I}{4,6}** will be 0. Not returning error to + * bpf program is consistent with what **bpf_trace_printk**\ () does for now. + * Return + * 0 on success, or a negative error in case of failure: + * + * **-EBUSY** if per-CPU memory copy buffer is busy, can try again + * by returning 1 from bpf program. + * + * **-EINVAL** if arguments are invalid, or if *fmt* is invalid/unsupported. + * + * **-E2BIG** if *fmt* contains too many format specifiers. + * + * **-EOVERFLOW** if an overflow happened: The same object will be tried again. + * + * long bpf_seq_write(struct seq_file *m, const void *data, u32 len) + * Description + * **bpf_seq_write**\ () uses seq_file **seq_write**\ () to write the data. + * The *m* represents the seq_file. The *data* and *len* represent the + * data to write in bytes. + * Return + * 0 on success, or a negative error in case of failure: + * + * **-EOVERFLOW** if an overflow happened: The same object will be tried again. + * + * u64 bpf_sk_cgroup_id(void *sk) + * Description + * Return the cgroup v2 id of the socket *sk*. + * + * *sk* must be a non-**NULL** pointer to a socket, e.g. one + * returned from **bpf_sk_lookup_xxx**\ (), + * **bpf_sk_fullsock**\ (), etc. The format of returned id is + * same as in **bpf_skb_cgroup_id**\ (). + * + * This helper is available only if the kernel was compiled with + * the **CONFIG_SOCK_CGROUP_DATA** configuration option. + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * u64 bpf_sk_ancestor_cgroup_id(void *sk, int ancestor_level) + * Description + * Return id of cgroup v2 that is ancestor of cgroup associated + * with the *sk* at the *ancestor_level*. The root cgroup is at + * *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with *sk*, then return value will be same as that + * of **bpf_sk_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with *sk*. + * + * The format of returned id and helper limitations are same as in + * **bpf_sk_cgroup_id**\ (). + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * long bpf_ringbuf_output(void *ringbuf, void *data, u64 size, u64 flags) + * Description + * Copy *size* bytes from *data* into a ring buffer *ringbuf*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * If **0** is specified in *flags*, an adaptive notification + * of new data availability is sent. + * + * An adaptive notification is a notification sent whenever the user-space + * process has caught up and consumed all available payloads. In case the user-space + * process is still processing a previous payload, then no notification is needed + * as it will process the newly added payload automatically. + * Return + * 0 on success, or a negative error in case of failure. + * + * void *bpf_ringbuf_reserve(void *ringbuf, u64 size, u64 flags) + * Description + * Reserve *size* bytes of payload in a ring buffer *ringbuf*. + * *flags* must be 0. + * Return + * Valid pointer with *size* bytes of memory available; NULL, + * otherwise. + * + * void bpf_ringbuf_submit(void *data, u64 flags) + * Description + * Submit reserved ring buffer sample, pointed to by *data*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * If **0** is specified in *flags*, an adaptive notification + * of new data availability is sent. + * + * See 'bpf_ringbuf_output()' for the definition of adaptive notification. + * Return + * Nothing. Always succeeds. + * + * void bpf_ringbuf_discard(void *data, u64 flags) + * Description + * Discard reserved ring buffer sample, pointed to by *data*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * If **0** is specified in *flags*, an adaptive notification + * of new data availability is sent. + * + * See 'bpf_ringbuf_output()' for the definition of adaptive notification. + * Return + * Nothing. Always succeeds. + * + * u64 bpf_ringbuf_query(void *ringbuf, u64 flags) + * Description + * Query various characteristics of provided ring buffer. What + * exactly is queries is determined by *flags*: + * + * * **BPF_RB_AVAIL_DATA**: Amount of data not yet consumed. + * * **BPF_RB_RING_SIZE**: The size of ring buffer. + * * **BPF_RB_CONS_POS**: Consumer position (can wrap around). + * * **BPF_RB_PROD_POS**: Producer(s) position (can wrap around). + * + * Data returned is just a momentary snapshot of actual values + * and could be inaccurate, so this facility should be used to + * power heuristics and for reporting, not to make 100% correct + * calculation. + * Return + * Requested value, or 0, if *flags* are not recognized. + * + * long bpf_csum_level(struct sk_buff *skb, u64 level) + * Description + * Change the skbs checksum level by one layer up or down, or + * reset it entirely to none in order to have the stack perform + * checksum validation. The level is applicable to the following + * protocols: TCP, UDP, GRE, SCTP, FCOE. For example, a decap of + * | ETH | IP | UDP | GUE | IP | TCP | into | ETH | IP | TCP | + * through **bpf_skb_adjust_room**\ () helper with passing in + * **BPF_F_ADJ_ROOM_NO_CSUM_RESET** flag would require one call + * to **bpf_csum_level**\ () with **BPF_CSUM_LEVEL_DEC** since + * the UDP header is removed. Similarly, an encap of the latter + * into the former could be accompanied by a helper call to + * **bpf_csum_level**\ () with **BPF_CSUM_LEVEL_INC** if the + * skb is still intended to be processed in higher layers of the + * stack instead of just egressing at tc. + * + * There are three supported level settings at this time: + * + * * **BPF_CSUM_LEVEL_INC**: Increases skb->csum_level for skbs + * with CHECKSUM_UNNECESSARY. + * * **BPF_CSUM_LEVEL_DEC**: Decreases skb->csum_level for skbs + * with CHECKSUM_UNNECESSARY. + * * **BPF_CSUM_LEVEL_RESET**: Resets skb->csum_level to 0 and + * sets CHECKSUM_NONE to force checksum validation by the stack. + * * **BPF_CSUM_LEVEL_QUERY**: No-op, returns the current + * skb->csum_level. + * Return + * 0 on success, or a negative error in case of failure. In the + * case of **BPF_CSUM_LEVEL_QUERY**, the current skb->csum_level + * is returned or the error code -EACCES in case the skb is not + * subject to CHECKSUM_UNNECESSARY. + * + * struct tcp6_sock *bpf_skc_to_tcp6_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *tcp6_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * struct tcp_sock *bpf_skc_to_tcp_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *tcp_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * struct tcp_timewait_sock *bpf_skc_to_tcp_timewait_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *tcp_timewait_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * struct tcp_request_sock *bpf_skc_to_tcp_request_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *tcp_request_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * struct udp6_sock *bpf_skc_to_udp6_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *udp6_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * long bpf_get_task_stack(struct task_struct *task, void *buf, u32 size, u64 flags) + * Description + * Return a user or a kernel stack in bpf program provided buffer. + * To achieve this, the helper needs *task*, which is a valid + * pointer to **struct task_struct**. To store the stacktrace, the + * bpf program provides *buf* with a nonnegative *size*. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_USER_BUILD_ID** + * Collect buildid+offset instead of ips for user stack, + * only valid if **BPF_F_USER_STACK** is also specified. + * + * **bpf_get_task_stack**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames, subject + * to sufficient large buffer size. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * Return + * A non-negative value equal to or less than *size* on success, + * or a negative error in case of failure. + * + * long bpf_load_hdr_opt(struct bpf_sock_ops *skops, void *searchby_res, u32 len, u64 flags) + * Description + * Load header option. Support reading a particular TCP header + * option for bpf program (**BPF_PROG_TYPE_SOCK_OPS**). + * + * If *flags* is 0, it will search the option from the + * *skops*\ **->skb_data**. The comment in **struct bpf_sock_ops** + * has details on what skb_data contains under different + * *skops*\ **->op**. + * + * The first byte of the *searchby_res* specifies the + * kind that it wants to search. + * + * If the searching kind is an experimental kind + * (i.e. 253 or 254 according to RFC6994). It also + * needs to specify the "magic" which is either + * 2 bytes or 4 bytes. It then also needs to + * specify the size of the magic by using + * the 2nd byte which is "kind-length" of a TCP + * header option and the "kind-length" also + * includes the first 2 bytes "kind" and "kind-length" + * itself as a normal TCP header option also does. + * + * For example, to search experimental kind 254 with + * 2 byte magic 0xeB9F, the searchby_res should be + * [ 254, 4, 0xeB, 0x9F, 0, 0, .... 0 ]. + * + * To search for the standard window scale option (3), + * the *searchby_res* should be [ 3, 0, 0, .... 0 ]. + * Note, kind-length must be 0 for regular option. + * + * Searching for No-Op (0) and End-of-Option-List (1) are + * not supported. + * + * *len* must be at least 2 bytes which is the minimal size + * of a header option. + * + * Supported flags: + * + * * **BPF_LOAD_HDR_OPT_TCP_SYN** to search from the + * saved_syn packet or the just-received syn packet. + * + * Return + * > 0 when found, the header option is copied to *searchby_res*. + * The return value is the total length copied. On failure, a + * negative error code is returned: + * + * **-EINVAL** if a parameter is invalid. + * + * **-ENOMSG** if the option is not found. + * + * **-ENOENT** if no syn packet is available when + * **BPF_LOAD_HDR_OPT_TCP_SYN** is used. + * + * **-ENOSPC** if there is not enough space. Only *len* number of + * bytes are copied. + * + * **-EFAULT** on failure to parse the header options in the + * packet. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + * + * long bpf_store_hdr_opt(struct bpf_sock_ops *skops, const void *from, u32 len, u64 flags) + * Description + * Store header option. The data will be copied + * from buffer *from* with length *len* to the TCP header. + * + * The buffer *from* should have the whole option that + * includes the kind, kind-length, and the actual + * option data. The *len* must be at least kind-length + * long. The kind-length does not have to be 4 byte + * aligned. The kernel will take care of the padding + * and setting the 4 bytes aligned value to th->doff. + * + * This helper will check for duplicated option + * by searching the same option in the outgoing skb. + * + * This helper can only be called during + * **BPF_SOCK_OPS_WRITE_HDR_OPT_CB**. + * + * Return + * 0 on success, or negative error in case of failure: + * + * **-EINVAL** If param is invalid. + * + * **-ENOSPC** if there is not enough space in the header. + * Nothing has been written + * + * **-EEXIST** if the option already exists. + * + * **-EFAULT** on failrue to parse the existing header options. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + * + * long bpf_reserve_hdr_opt(struct bpf_sock_ops *skops, u32 len, u64 flags) + * Description + * Reserve *len* bytes for the bpf header option. The + * space will be used by **bpf_store_hdr_opt**\ () later in + * **BPF_SOCK_OPS_WRITE_HDR_OPT_CB**. + * + * If **bpf_reserve_hdr_opt**\ () is called multiple times, + * the total number of bytes will be reserved. + * + * This helper can only be called during + * **BPF_SOCK_OPS_HDR_OPT_LEN_CB**. + * + * Return + * 0 on success, or negative error in case of failure: + * + * **-EINVAL** if a parameter is invalid. + * + * **-ENOSPC** if there is not enough space in the header. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + * + * void *bpf_inode_storage_get(struct bpf_map *map, void *inode, void *value, u64 flags) + * Description + * Get a bpf_local_storage from an *inode*. + * + * Logically, it could be thought of as getting the value from + * a *map* with *inode* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *inode*) except this + * helper enforces the key must be an inode and the map must also + * be a **BPF_MAP_TYPE_INODE_STORAGE**. + * + * Underneath, the value is stored locally at *inode* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf_local_storage residing at *inode*. + * + * An optional *flags* (**BPF_LOCAL_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf_local_storage will be + * created if one does not exist. *value* can be used + * together with **BPF_LOCAL_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf_local_storage. If *value* is + * **NULL**, the new bpf_local_storage will be zero initialized. + * Return + * A bpf_local_storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf_local_storage. + * + * int bpf_inode_storage_delete(struct bpf_map *map, void *inode) + * Description + * Delete a bpf_local_storage from an *inode*. + * Return + * 0 on success. + * + * **-ENOENT** if the bpf_local_storage cannot be found. + * + * long bpf_d_path(struct path *path, char *buf, u32 sz) + * Description + * Return full path for given **struct path** object, which + * needs to be the kernel BTF *path* object. The path is + * returned in the provided buffer *buf* of size *sz* and + * is zero terminated. + * + * Return + * On success, the strictly positive length of the string, + * including the trailing NUL character. On error, a negative + * value. + * + * long bpf_copy_from_user(void *dst, u32 size, const void *user_ptr) + * Description + * Read *size* bytes from user space address *user_ptr* and store + * the data in *dst*. This is a wrapper of **copy_from_user**\ (). + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_snprintf_btf(char *str, u32 str_size, struct btf_ptr *ptr, u32 btf_ptr_size, u64 flags) + * Description + * Use BTF to store a string representation of *ptr*->ptr in *str*, + * using *ptr*->type_id. This value should specify the type + * that *ptr*->ptr points to. LLVM __builtin_btf_type_id(type, 1) + * can be used to look up vmlinux BTF type ids. Traversing the + * data structure using BTF, the type information and values are + * stored in the first *str_size* - 1 bytes of *str*. Safe copy of + * the pointer data is carried out to avoid kernel crashes during + * operation. Smaller types can use string space on the stack; + * larger programs can use map data to store the string + * representation. + * + * The string can be subsequently shared with userspace via + * bpf_perf_event_output() or ring buffer interfaces. + * bpf_trace_printk() is to be avoided as it places too small + * a limit on string size to be useful. + * + * *flags* is a combination of + * + * **BTF_F_COMPACT** + * no formatting around type information + * **BTF_F_NONAME** + * no struct/union member names/types + * **BTF_F_PTR_RAW** + * show raw (unobfuscated) pointer values; + * equivalent to printk specifier %px. + * **BTF_F_ZERO** + * show zero-valued struct/union members; they + * are not displayed by default + * + * Return + * The number of bytes that were written (or would have been + * written if output had to be truncated due to string size), + * or a negative error in cases of failure. + * + * long bpf_seq_printf_btf(struct seq_file *m, struct btf_ptr *ptr, u32 ptr_size, u64 flags) + * Description + * Use BTF to write to seq_write a string representation of + * *ptr*->ptr, using *ptr*->type_id as per bpf_snprintf_btf(). + * *flags* are identical to those used for bpf_snprintf_btf. + * Return + * 0 on success or a negative error in case of failure. + * + * u64 bpf_skb_cgroup_classid(struct sk_buff *skb) + * Description + * See **bpf_get_cgroup_classid**\ () for the main description. + * This helper differs from **bpf_get_cgroup_classid**\ () in that + * the cgroup v1 net_cls class is retrieved only from the *skb*'s + * associated socket instead of the current process. + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * long bpf_redirect_neigh(u32 ifindex, struct bpf_redir_neigh *params, int plen, u64 flags) + * Description + * Redirect the packet to another net device of index *ifindex* + * and fill in L2 addresses from neighboring subsystem. This helper + * is somewhat similar to **bpf_redirect**\ (), except that it + * populates L2 addresses as well, meaning, internally, the helper + * relies on the neighbor lookup for the L2 address of the nexthop. + * + * The helper will perform a FIB lookup based on the skb's + * networking header to get the address of the next hop, unless + * this is supplied by the caller in the *params* argument. The + * *plen* argument indicates the len of *params* and should be set + * to 0 if *params* is NULL. + * + * The *flags* argument is reserved and must be 0. The helper is + * currently only supported for tc BPF program types, and enabled + * for IPv4 and IPv6 protocols. + * Return + * The helper returns **TC_ACT_REDIRECT** on success or + * **TC_ACT_SHOT** on error. + * + * void *bpf_per_cpu_ptr(const void *percpu_ptr, u32 cpu) + * Description + * Take a pointer to a percpu ksym, *percpu_ptr*, and return a + * pointer to the percpu kernel variable on *cpu*. A ksym is an + * extern variable decorated with '__ksym'. For ksym, there is a + * global var (either static or global) defined of the same name + * in the kernel. The ksym is percpu if the global var is percpu. + * The returned pointer points to the global percpu var on *cpu*. + * + * bpf_per_cpu_ptr() has the same semantic as per_cpu_ptr() in the + * kernel, except that bpf_per_cpu_ptr() may return NULL. This + * happens if *cpu* is larger than nr_cpu_ids. The caller of + * bpf_per_cpu_ptr() must check the returned value. + * Return + * A pointer pointing to the kernel percpu variable on *cpu*, or + * NULL, if *cpu* is invalid. + * + * void *bpf_this_cpu_ptr(const void *percpu_ptr) + * Description + * Take a pointer to a percpu ksym, *percpu_ptr*, and return a + * pointer to the percpu kernel variable on this cpu. See the + * description of 'ksym' in **bpf_per_cpu_ptr**\ (). + * + * bpf_this_cpu_ptr() has the same semantic as this_cpu_ptr() in + * the kernel. Different from **bpf_per_cpu_ptr**\ (), it would + * never return NULL. + * Return + * A pointer pointing to the kernel percpu variable on this cpu. + * + * long bpf_redirect_peer(u32 ifindex, u64 flags) + * Description + * Redirect the packet to another net device of index *ifindex*. + * This helper is somewhat similar to **bpf_redirect**\ (), except + * that the redirection happens to the *ifindex*' peer device and + * the netns switch takes place from ingress to ingress without + * going through the CPU's backlog queue. + * + * The *flags* argument is reserved and must be 0. The helper is + * currently only supported for tc BPF program types at the ingress + * hook and for veth device types. The peer device must reside in a + * different network namespace. + * Return + * The helper returns **TC_ACT_REDIRECT** on success or + * **TC_ACT_SHOT** on error. + * + * void *bpf_task_storage_get(struct bpf_map *map, struct task_struct *task, void *value, u64 flags) + * Description + * Get a bpf_local_storage from the *task*. + * + * Logically, it could be thought of as getting the value from + * a *map* with *task* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *task*) except this + * helper enforces the key must be an task_struct and the map must also + * be a **BPF_MAP_TYPE_TASK_STORAGE**. + * + * Underneath, the value is stored locally at *task* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf_local_storage residing at *task*. + * + * An optional *flags* (**BPF_LOCAL_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf_local_storage will be + * created if one does not exist. *value* can be used + * together with **BPF_LOCAL_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf_local_storage. If *value* is + * **NULL**, the new bpf_local_storage will be zero initialized. + * Return + * A bpf_local_storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf_local_storage. + * + * long bpf_task_storage_delete(struct bpf_map *map, struct task_struct *task) + * Description + * Delete a bpf_local_storage from a *task*. + * Return + * 0 on success. + * + * **-ENOENT** if the bpf_local_storage cannot be found. + * + * struct task_struct *bpf_get_current_task_btf(void) + * Description + * Return a BTF pointer to the "current" task. + * This pointer can also be used in helpers that accept an + * *ARG_PTR_TO_BTF_ID* of type *task_struct*. + * Return + * Pointer to the current task. + * + * long bpf_bprm_opts_set(struct linux_binprm *bprm, u64 flags) + * Description + * Set or clear certain options on *bprm*: + * + * **BPF_F_BPRM_SECUREEXEC** Set the secureexec bit + * which sets the **AT_SECURE** auxv for glibc. The bit + * is cleared if the flag is not specified. + * Return + * **-EINVAL** if invalid *flags* are passed, zero otherwise. + * + * u64 bpf_ktime_get_coarse_ns(void) + * Description + * Return a coarse-grained version of the time elapsed since + * system boot, in nanoseconds. Does not include time the system + * was suspended. + * + * See: **clock_gettime**\ (**CLOCK_MONOTONIC_COARSE**) + * Return + * Current *ktime*. + * + * long bpf_ima_inode_hash(struct inode *inode, void *dst, u32 size) + * Description + * Returns the stored IMA hash of the *inode* (if it's avaialable). + * If the hash is larger than *size*, then only *size* + * bytes will be copied to *dst* + * Return + * The **hash_algo** is returned on success, + * **-EOPNOTSUP** if IMA is disabled or **-EINVAL** if + * invalid arguments are passed. + * + * struct socket *bpf_sock_from_file(struct file *file) + * Description + * If the given file represents a socket, returns the associated + * socket. + * Return + * A pointer to a struct socket on success or NULL if the file is + * not a socket. + * + * long bpf_check_mtu(void *ctx, u32 ifindex, u32 *mtu_len, s32 len_diff, u64 flags) + * Description + * Check packet size against exceeding MTU of net device (based + * on *ifindex*). This helper will likely be used in combination + * with helpers that adjust/change the packet size. + * + * The argument *len_diff* can be used for querying with a planned + * size change. This allows to check MTU prior to changing packet + * ctx. Providing an *len_diff* adjustment that is larger than the + * actual packet size (resulting in negative packet size) will in + * principle not exceed the MTU, why it is not considered a + * failure. Other BPF-helpers are needed for performing the + * planned size change, why the responsability for catch a negative + * packet size belong in those helpers. + * + * Specifying *ifindex* zero means the MTU check is performed + * against the current net device. This is practical if this isn't + * used prior to redirect. + * + * On input *mtu_len* must be a valid pointer, else verifier will + * reject BPF program. If the value *mtu_len* is initialized to + * zero then the ctx packet size is use. When value *mtu_len* is + * provided as input this specify the L3 length that the MTU check + * is done against. Remember XDP and TC length operate at L2, but + * this value is L3 as this correlate to MTU and IP-header tot_len + * values which are L3 (similar behavior as bpf_fib_lookup). + * + * The Linux kernel route table can configure MTUs on a more + * specific per route level, which is not provided by this helper. + * For route level MTU checks use the **bpf_fib_lookup**\ () + * helper. + * + * *ctx* is either **struct xdp_md** for XDP programs or + * **struct sk_buff** for tc cls_act programs. + * + * The *flags* argument can be a combination of one or more of the + * following values: + * + * **BPF_MTU_CHK_SEGS** + * This flag will only works for *ctx* **struct sk_buff**. + * If packet context contains extra packet segment buffers + * (often knows as GSO skb), then MTU check is harder to + * check at this point, because in transmit path it is + * possible for the skb packet to get re-segmented + * (depending on net device features). This could still be + * a MTU violation, so this flag enables performing MTU + * check against segments, with a different violation + * return code to tell it apart. Check cannot use len_diff. + * + * On return *mtu_len* pointer contains the MTU value of the net + * device. Remember the net device configured MTU is the L3 size, + * which is returned here and XDP and TC length operate at L2. + * Helper take this into account for you, but remember when using + * MTU value in your BPF-code. + * + * Return + * * 0 on success, and populate MTU value in *mtu_len* pointer. + * + * * < 0 if any input argument is invalid (*mtu_len* not updated) + * + * MTU violations return positive values, but also populate MTU + * value in *mtu_len* pointer, as this can be needed for + * implementing PMTU handing: + * + * * **BPF_MTU_CHK_RET_FRAG_NEEDED** + * * **BPF_MTU_CHK_RET_SEGS_TOOBIG** + * + * long bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, void *callback_ctx, u64 flags) + * Description + * For each element in **map**, call **callback_fn** function with + * **map**, **callback_ctx** and other map-specific parameters. + * The **callback_fn** should be a static function and + * the **callback_ctx** should be a pointer to the stack. + * The **flags** is used to control certain aspects of the helper. + * Currently, the **flags** must be 0. + * + * The following are a list of supported map types and their + * respective expected callback signatures: + * + * BPF_MAP_TYPE_HASH, BPF_MAP_TYPE_PERCPU_HASH, + * BPF_MAP_TYPE_LRU_HASH, BPF_MAP_TYPE_LRU_PERCPU_HASH, + * BPF_MAP_TYPE_ARRAY, BPF_MAP_TYPE_PERCPU_ARRAY + * + * long (\*callback_fn)(struct bpf_map \*map, const void \*key, void \*value, void \*ctx); + * + * For per_cpu maps, the map_value is the value on the cpu where the + * bpf_prog is running. + * + * If **callback_fn** return 0, the helper will continue to the next + * element. If return value is 1, the helper will skip the rest of + * elements and return. Other return values are not used now. + * + * Return + * The number of traversed map elements for success, **-EINVAL** for + * invalid **flags**. + * + * long bpf_snprintf(char *str, u32 str_size, const char *fmt, u64 *data, u32 data_len) + * Description + * Outputs a string into the **str** buffer of size **str_size** + * based on a format string stored in a read-only map pointed by + * **fmt**. + * + * Each format specifier in **fmt** corresponds to one u64 element + * in the **data** array. For strings and pointers where pointees + * are accessed, only the pointer values are stored in the *data* + * array. The *data_len* is the size of *data* in bytes. + * + * Formats **%s** and **%p{i,I}{4,6}** require to read kernel + * memory. Reading kernel memory may fail due to either invalid + * address or valid address but requiring a major memory fault. If + * reading kernel memory fails, the string for **%s** will be an + * empty string, and the ip address for **%p{i,I}{4,6}** will be 0. + * Not returning error to bpf program is consistent with what + * **bpf_trace_printk**\ () does for now. + * + * Return + * The strictly positive length of the formatted string, including + * the trailing zero character. If the return value is greater than + * **str_size**, **str** contains a truncated string, guaranteed to + * be zero-terminated except when **str_size** is 0. + * + * Or **-EBUSY** if the per-CPU memory copy buffer is busy. + * + * long bpf_sys_bpf(u32 cmd, void *attr, u32 attr_size) + * Description + * Execute bpf syscall with given arguments. + * Return + * A syscall result. + * + * long bpf_btf_find_by_name_kind(char *name, int name_sz, u32 kind, int flags) + * Description + * Find BTF type with given name and kind in vmlinux BTF or in module's BTFs. + * Return + * Returns btf_id and btf_obj_fd in lower and upper 32 bits. + * + * long bpf_sys_close(u32 fd) + * Description + * Execute close syscall for given FD. + * Return + * A syscall result. + */ +#define __BPF_FUNC_MAPPER(FN) \ + FN(unspec), \ + FN(map_lookup_elem), \ + FN(map_update_elem), \ + FN(map_delete_elem), \ + FN(probe_read), \ + FN(ktime_get_ns), \ + FN(trace_printk), \ + FN(get_prandom_u32), \ + FN(get_smp_processor_id), \ + FN(skb_store_bytes), \ + FN(l3_csum_replace), \ + FN(l4_csum_replace), \ + FN(tail_call), \ + FN(clone_redirect), \ + FN(get_current_pid_tgid), \ + FN(get_current_uid_gid), \ + FN(get_current_comm), \ + FN(get_cgroup_classid), \ + FN(skb_vlan_push), \ + FN(skb_vlan_pop), \ + FN(skb_get_tunnel_key), \ + FN(skb_set_tunnel_key), \ + FN(perf_event_read), \ + FN(redirect), \ + FN(get_route_realm), \ + FN(perf_event_output), \ + FN(skb_load_bytes), \ + FN(get_stackid), \ + FN(csum_diff), \ + FN(skb_get_tunnel_opt), \ + FN(skb_set_tunnel_opt), \ + FN(skb_change_proto), \ + FN(skb_change_type), \ + FN(skb_under_cgroup), \ + FN(get_hash_recalc), \ + FN(get_current_task), \ + FN(probe_write_user), \ + FN(current_task_under_cgroup), \ + FN(skb_change_tail), \ + FN(skb_pull_data), \ + FN(csum_update), \ + FN(set_hash_invalid), \ + FN(get_numa_node_id), \ + FN(skb_change_head), \ + FN(xdp_adjust_head), \ + FN(probe_read_str), \ + FN(get_socket_cookie), \ + FN(get_socket_uid), \ + FN(set_hash), \ + FN(setsockopt), \ + FN(skb_adjust_room), \ + FN(redirect_map), \ + FN(sk_redirect_map), \ + FN(sock_map_update), \ + FN(xdp_adjust_meta), \ + FN(perf_event_read_value), \ + FN(perf_prog_read_value), \ + FN(getsockopt), \ + FN(override_return), \ + FN(sock_ops_cb_flags_set), \ + FN(msg_redirect_map), \ + FN(msg_apply_bytes), \ + FN(msg_cork_bytes), \ + FN(msg_pull_data), \ + FN(bind), \ + FN(xdp_adjust_tail), \ + FN(skb_get_xfrm_state), \ + FN(get_stack), \ + FN(skb_load_bytes_relative), \ + FN(fib_lookup), \ + FN(sock_hash_update), \ + FN(msg_redirect_hash), \ + FN(sk_redirect_hash), \ + FN(lwt_push_encap), \ + FN(lwt_seg6_store_bytes), \ + FN(lwt_seg6_adjust_srh), \ + FN(lwt_seg6_action), \ + FN(rc_repeat), \ + FN(rc_keydown), \ + FN(skb_cgroup_id), \ + FN(get_current_cgroup_id), \ + FN(get_local_storage), \ + FN(sk_select_reuseport), \ + FN(skb_ancestor_cgroup_id), \ + FN(sk_lookup_tcp), \ + FN(sk_lookup_udp), \ + FN(sk_release), \ + FN(map_push_elem), \ + FN(map_pop_elem), \ + FN(map_peek_elem), \ + FN(msg_push_data), \ + FN(msg_pop_data), \ + FN(rc_pointer_rel), \ + FN(spin_lock), \ + FN(spin_unlock), \ + FN(sk_fullsock), \ + FN(tcp_sock), \ + FN(skb_ecn_set_ce), \ + FN(get_listener_sock), \ + FN(skc_lookup_tcp), \ + FN(tcp_check_syncookie), \ + FN(sysctl_get_name), \ + FN(sysctl_get_current_value), \ + FN(sysctl_get_new_value), \ + FN(sysctl_set_new_value), \ + FN(strtol), \ + FN(strtoul), \ + FN(sk_storage_get), \ + FN(sk_storage_delete), \ + FN(send_signal), \ + FN(tcp_gen_syncookie), \ + FN(skb_output), \ + FN(probe_read_user), \ + FN(probe_read_kernel), \ + FN(probe_read_user_str), \ + FN(probe_read_kernel_str), \ + FN(tcp_send_ack), \ + FN(send_signal_thread), \ + FN(jiffies64), \ + FN(read_branch_records), \ + FN(get_ns_current_pid_tgid), \ + FN(xdp_output), \ + FN(get_netns_cookie), \ + FN(get_current_ancestor_cgroup_id), \ + FN(sk_assign), \ + FN(ktime_get_boot_ns), \ + FN(seq_printf), \ + FN(seq_write), \ + FN(sk_cgroup_id), \ + FN(sk_ancestor_cgroup_id), \ + FN(ringbuf_output), \ + FN(ringbuf_reserve), \ + FN(ringbuf_submit), \ + FN(ringbuf_discard), \ + FN(ringbuf_query), \ + FN(csum_level), \ + FN(skc_to_tcp6_sock), \ + FN(skc_to_tcp_sock), \ + FN(skc_to_tcp_timewait_sock), \ + FN(skc_to_tcp_request_sock), \ + FN(skc_to_udp6_sock), \ + FN(get_task_stack), \ + FN(load_hdr_opt), \ + FN(store_hdr_opt), \ + FN(reserve_hdr_opt), \ + FN(inode_storage_get), \ + FN(inode_storage_delete), \ + FN(d_path), \ + FN(copy_from_user), \ + FN(snprintf_btf), \ + FN(seq_printf_btf), \ + FN(skb_cgroup_classid), \ + FN(redirect_neigh), \ + FN(per_cpu_ptr), \ + FN(this_cpu_ptr), \ + FN(redirect_peer), \ + FN(task_storage_get), \ + FN(task_storage_delete), \ + FN(get_current_task_btf), \ + FN(bprm_opts_set), \ + FN(ktime_get_coarse_ns), \ + FN(ima_inode_hash), \ + FN(sock_from_file), \ + FN(check_mtu), \ + FN(for_each_map_elem), \ + FN(snprintf), \ + FN(sys_bpf), \ + FN(btf_find_by_name_kind), \ + FN(sys_close), \ + /* */ + +/* integer value in 'imm' field of BPF_CALL instruction selects which helper + * function eBPF program intends to call + */ +#define __BPF_ENUM_FN(x) BPF_FUNC_ ## x +enum bpf_func_id { + __BPF_FUNC_MAPPER(__BPF_ENUM_FN) + __BPF_FUNC_MAX_ID, +}; +#undef __BPF_ENUM_FN + +/* All flags used by eBPF helper functions, placed here. */ + +/* BPF_FUNC_skb_store_bytes flags. */ +enum { + BPF_F_RECOMPUTE_CSUM = (1ULL << 0), + BPF_F_INVALIDATE_HASH = (1ULL << 1), +}; + +/* BPF_FUNC_l3_csum_replace and BPF_FUNC_l4_csum_replace flags. + * First 4 bits are for passing the header field size. + */ +enum { + BPF_F_HDR_FIELD_MASK = 0xfULL, +}; + +/* BPF_FUNC_l4_csum_replace flags. */ +enum { + BPF_F_PSEUDO_HDR = (1ULL << 4), + BPF_F_MARK_MANGLED_0 = (1ULL << 5), + BPF_F_MARK_ENFORCE = (1ULL << 6), +}; + +/* BPF_FUNC_clone_redirect and BPF_FUNC_redirect flags. */ +enum { + BPF_F_INGRESS = (1ULL << 0), +}; + +/* BPF_FUNC_skb_set_tunnel_key and BPF_FUNC_skb_get_tunnel_key flags. */ +enum { + BPF_F_TUNINFO_IPV6 = (1ULL << 0), +}; + +/* flags for both BPF_FUNC_get_stackid and BPF_FUNC_get_stack. */ +enum { + BPF_F_SKIP_FIELD_MASK = 0xffULL, + BPF_F_USER_STACK = (1ULL << 8), +/* flags used by BPF_FUNC_get_stackid only. */ + BPF_F_FAST_STACK_CMP = (1ULL << 9), + BPF_F_REUSE_STACKID = (1ULL << 10), +/* flags used by BPF_FUNC_get_stack only. */ + BPF_F_USER_BUILD_ID = (1ULL << 11), +}; + +/* BPF_FUNC_skb_set_tunnel_key flags. */ +enum { + BPF_F_ZERO_CSUM_TX = (1ULL << 1), + BPF_F_DONT_FRAGMENT = (1ULL << 2), + BPF_F_SEQ_NUMBER = (1ULL << 3), +}; + +/* BPF_FUNC_perf_event_output, BPF_FUNC_perf_event_read and + * BPF_FUNC_perf_event_read_value flags. + */ +enum { + BPF_F_INDEX_MASK = 0xffffffffULL, + BPF_F_CURRENT_CPU = BPF_F_INDEX_MASK, +/* BPF_FUNC_perf_event_output for sk_buff input context. */ + BPF_F_CTXLEN_MASK = (0xfffffULL << 32), +}; + +/* Current network namespace */ +enum { + BPF_F_CURRENT_NETNS = (-1L), +}; + +/* BPF_FUNC_csum_level level values. */ +enum { + BPF_CSUM_LEVEL_QUERY, + BPF_CSUM_LEVEL_INC, + BPF_CSUM_LEVEL_DEC, + BPF_CSUM_LEVEL_RESET, +}; + +/* BPF_FUNC_skb_adjust_room flags. */ +enum { + BPF_F_ADJ_ROOM_FIXED_GSO = (1ULL << 0), + BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 = (1ULL << 1), + BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 = (1ULL << 2), + BPF_F_ADJ_ROOM_ENCAP_L4_GRE = (1ULL << 3), + BPF_F_ADJ_ROOM_ENCAP_L4_UDP = (1ULL << 4), + BPF_F_ADJ_ROOM_NO_CSUM_RESET = (1ULL << 5), + BPF_F_ADJ_ROOM_ENCAP_L2_ETH = (1ULL << 6), +}; + +enum { + BPF_ADJ_ROOM_ENCAP_L2_MASK = 0xff, + BPF_ADJ_ROOM_ENCAP_L2_SHIFT = 56, +}; + +#define BPF_F_ADJ_ROOM_ENCAP_L2(len) (((__u64)len & \ + BPF_ADJ_ROOM_ENCAP_L2_MASK) \ + << BPF_ADJ_ROOM_ENCAP_L2_SHIFT) + +/* BPF_FUNC_sysctl_get_name flags. */ +enum { + BPF_F_SYSCTL_BASE_NAME = (1ULL << 0), +}; + +/* BPF_FUNC__storage_get flags */ +enum { + BPF_LOCAL_STORAGE_GET_F_CREATE = (1ULL << 0), + /* BPF_SK_STORAGE_GET_F_CREATE is only kept for backward compatibility + * and BPF_LOCAL_STORAGE_GET_F_CREATE must be used instead. + */ + BPF_SK_STORAGE_GET_F_CREATE = BPF_LOCAL_STORAGE_GET_F_CREATE, +}; + +/* BPF_FUNC_read_branch_records flags. */ +enum { + BPF_F_GET_BRANCH_RECORDS_SIZE = (1ULL << 0), +}; + +/* BPF_FUNC_bpf_ringbuf_commit, BPF_FUNC_bpf_ringbuf_discard, and + * BPF_FUNC_bpf_ringbuf_output flags. + */ +enum { + BPF_RB_NO_WAKEUP = (1ULL << 0), + BPF_RB_FORCE_WAKEUP = (1ULL << 1), +}; + +/* BPF_FUNC_bpf_ringbuf_query flags */ +enum { + BPF_RB_AVAIL_DATA = 0, + BPF_RB_RING_SIZE = 1, + BPF_RB_CONS_POS = 2, + BPF_RB_PROD_POS = 3, +}; + +/* BPF ring buffer constants */ +enum { + BPF_RINGBUF_BUSY_BIT = (1U << 31), + BPF_RINGBUF_DISCARD_BIT = (1U << 30), + BPF_RINGBUF_HDR_SZ = 8, +}; + +/* BPF_FUNC_sk_assign flags in bpf_sk_lookup context. */ +enum { + BPF_SK_LOOKUP_F_REPLACE = (1ULL << 0), + BPF_SK_LOOKUP_F_NO_REUSEPORT = (1ULL << 1), +}; + +/* Mode for BPF_FUNC_skb_adjust_room helper. */ +enum bpf_adj_room_mode { + BPF_ADJ_ROOM_NET, + BPF_ADJ_ROOM_MAC, +}; + +/* Mode for BPF_FUNC_skb_load_bytes_relative helper. */ +enum bpf_hdr_start_off { + BPF_HDR_START_MAC, + BPF_HDR_START_NET, +}; + +/* Encapsulation type for BPF_FUNC_lwt_push_encap helper. */ +enum bpf_lwt_encap_mode { + BPF_LWT_ENCAP_SEG6, + BPF_LWT_ENCAP_SEG6_INLINE, + BPF_LWT_ENCAP_IP, +}; + +/* Flags for bpf_bprm_opts_set helper */ +enum { + BPF_F_BPRM_SECUREEXEC = (1ULL << 0), +}; + +/* Flags for bpf_redirect_map helper */ +enum { + BPF_F_BROADCAST = (1ULL << 3), + BPF_F_EXCLUDE_INGRESS = (1ULL << 4), +}; + +#define __bpf_md_ptr(type, name) \ +union { \ + type name; \ + __u64 :64; \ +} __attribute__((aligned(8))) + +/* user accessible mirror of in-kernel sk_buff. + * new fields can only be added to the end of this structure + */ +struct __sk_buff { + __u32 len; + __u32 pkt_type; + __u32 mark; + __u32 queue_mapping; + __u32 protocol; + __u32 vlan_present; + __u32 vlan_tci; + __u32 vlan_proto; + __u32 priority; + __u32 ingress_ifindex; + __u32 ifindex; + __u32 tc_index; + __u32 cb[5]; + __u32 hash; + __u32 tc_classid; + __u32 data; + __u32 data_end; + __u32 napi_id; + + /* Accessed by BPF_PROG_TYPE_sk_skb types from here to ... */ + __u32 family; + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ + /* ... here. */ + + __u32 data_meta; + __bpf_md_ptr(struct bpf_flow_keys *, flow_keys); + __u64 tstamp; + __u32 wire_len; + __u32 gso_segs; + __bpf_md_ptr(struct bpf_sock *, sk); + __u32 gso_size; +}; + +struct bpf_tunnel_key { + __u32 tunnel_id; + union { + __u32 remote_ipv4; + __u32 remote_ipv6[4]; + }; + __u8 tunnel_tos; + __u8 tunnel_ttl; + __u16 tunnel_ext; /* Padding, future use. */ + __u32 tunnel_label; +}; + +/* user accessible mirror of in-kernel xfrm_state. + * new fields can only be added to the end of this structure + */ +struct bpf_xfrm_state { + __u32 reqid; + __u32 spi; /* Stored in network byte order */ + __u16 family; + __u16 ext; /* Padding, future use. */ + union { + __u32 remote_ipv4; /* Stored in network byte order */ + __u32 remote_ipv6[4]; /* Stored in network byte order */ + }; +}; + +/* Generic BPF return codes which all BPF program types may support. + * The values are binary compatible with their TC_ACT_* counter-part to + * provide backwards compatibility with existing SCHED_CLS and SCHED_ACT + * programs. + * + * XDP is handled seprately, see XDP_*. + */ +enum bpf_ret_code { + BPF_OK = 0, + /* 1 reserved */ + BPF_DROP = 2, + /* 3-6 reserved */ + BPF_REDIRECT = 7, + /* >127 are reserved for prog type specific return codes. + * + * BPF_LWT_REROUTE: used by BPF_PROG_TYPE_LWT_IN and + * BPF_PROG_TYPE_LWT_XMIT to indicate that skb had been + * changed and should be routed based on its new L3 header. + * (This is an L3 redirect, as opposed to L2 redirect + * represented by BPF_REDIRECT above). + */ + BPF_LWT_REROUTE = 128, +}; + +struct bpf_sock { + __u32 bound_dev_if; + __u32 family; + __u32 type; + __u32 protocol; + __u32 mark; + __u32 priority; + /* IP address also allows 1 and 2 bytes access */ + __u32 src_ip4; + __u32 src_ip6[4]; + __u32 src_port; /* host byte order */ + __u32 dst_port; /* network byte order */ + __u32 dst_ip4; + __u32 dst_ip6[4]; + __u32 state; + __s32 rx_queue_mapping; +}; + +struct bpf_tcp_sock { + __u32 snd_cwnd; /* Sending congestion window */ + __u32 srtt_us; /* smoothed round trip time << 3 in usecs */ + __u32 rtt_min; + __u32 snd_ssthresh; /* Slow start size threshold */ + __u32 rcv_nxt; /* What we want to receive next */ + __u32 snd_nxt; /* Next sequence we send */ + __u32 snd_una; /* First byte we want an ack for */ + __u32 mss_cache; /* Cached effective mss, not including SACKS */ + __u32 ecn_flags; /* ECN status bits. */ + __u32 rate_delivered; /* saved rate sample: packets delivered */ + __u32 rate_interval_us; /* saved rate sample: time elapsed */ + __u32 packets_out; /* Packets which are "in flight" */ + __u32 retrans_out; /* Retransmitted packets out */ + __u32 total_retrans; /* Total retransmits for entire connection */ + __u32 segs_in; /* RFC4898 tcpEStatsPerfSegsIn + * total number of segments in. + */ + __u32 data_segs_in; /* RFC4898 tcpEStatsPerfDataSegsIn + * total number of data segments in. + */ + __u32 segs_out; /* RFC4898 tcpEStatsPerfSegsOut + * The total number of segments sent. + */ + __u32 data_segs_out; /* RFC4898 tcpEStatsPerfDataSegsOut + * total number of data segments sent. + */ + __u32 lost_out; /* Lost packets */ + __u32 sacked_out; /* SACK'd packets */ + __u64 bytes_received; /* RFC4898 tcpEStatsAppHCThruOctetsReceived + * sum(delta(rcv_nxt)), or how many bytes + * were acked. + */ + __u64 bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked + * sum(delta(snd_una)), or how many bytes + * were acked. + */ + __u32 dsack_dups; /* RFC4898 tcpEStatsStackDSACKDups + * total number of DSACK blocks received + */ + __u32 delivered; /* Total data packets delivered incl. rexmits */ + __u32 delivered_ce; /* Like the above but only ECE marked packets */ + __u32 icsk_retransmits; /* Number of unrecovered [RTO] timeouts */ +}; + +struct bpf_sock_tuple { + union { + struct { + __be32 saddr; + __be32 daddr; + __be16 sport; + __be16 dport; + } ipv4; + struct { + __be32 saddr[4]; + __be32 daddr[4]; + __be16 sport; + __be16 dport; + } ipv6; + }; +}; + +struct bpf_xdp_sock { + __u32 queue_id; +}; + +#define XDP_PACKET_HEADROOM 256 + +/* User return codes for XDP prog type. + * A valid XDP program must return one of these defined values. All other + * return codes are reserved for future use. Unknown return codes will + * result in packet drops and a warning via bpf_warn_invalid_xdp_action(). + */ +enum xdp_action { + XDP_ABORTED = 0, + XDP_DROP, + XDP_PASS, + XDP_TX, + XDP_REDIRECT, +}; + +/* user accessible metadata for XDP packet hook + * new fields must be added to the end of this structure + */ +struct xdp_md { + __u32 data; + __u32 data_end; + __u32 data_meta; + /* Below access go through struct xdp_rxq_info */ + __u32 ingress_ifindex; /* rxq->dev->ifindex */ + __u32 rx_queue_index; /* rxq->queue_index */ + + __u32 egress_ifindex; /* txq->dev->ifindex */ +}; + +/* DEVMAP map-value layout + * + * The struct data-layout of map-value is a configuration interface. + * New members can only be added to the end of this structure. + */ +struct bpf_devmap_val { + __u32 ifindex; /* device index */ + union { + int fd; /* prog fd on map write */ + __u32 id; /* prog id on map read */ + } bpf_prog; +}; + +/* CPUMAP map-value layout + * + * The struct data-layout of map-value is a configuration interface. + * New members can only be added to the end of this structure. + */ +struct bpf_cpumap_val { + __u32 qsize; /* queue size to remote target CPU */ + union { + int fd; /* prog fd on map write */ + __u32 id; /* prog id on map read */ + } bpf_prog; +}; + +enum sk_action { + SK_DROP = 0, + SK_PASS, +}; + +/* user accessible metadata for SK_MSG packet hook, new fields must + * be added to the end of this structure + */ +struct sk_msg_md { + __bpf_md_ptr(void *, data); + __bpf_md_ptr(void *, data_end); + + __u32 family; + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ + __u32 size; /* Total size of sk_msg */ + + __bpf_md_ptr(struct bpf_sock *, sk); /* current socket */ +}; + +struct sk_reuseport_md { + /* + * Start of directly accessible data. It begins from + * the tcp/udp header. + */ + __bpf_md_ptr(void *, data); + /* End of directly accessible data */ + __bpf_md_ptr(void *, data_end); + /* + * Total length of packet (starting from the tcp/udp header). + * Note that the directly accessible bytes (data_end - data) + * could be less than this "len". Those bytes could be + * indirectly read by a helper "bpf_skb_load_bytes()". + */ + __u32 len; + /* + * Eth protocol in the mac header (network byte order). e.g. + * ETH_P_IP(0x0800) and ETH_P_IPV6(0x86DD) + */ + __u32 eth_protocol; + __u32 ip_protocol; /* IP protocol. e.g. IPPROTO_TCP, IPPROTO_UDP */ + __u32 bind_inany; /* Is sock bound to an INANY address? */ + __u32 hash; /* A hash of the packet 4 tuples */ + /* When reuse->migrating_sk is NULL, it is selecting a sk for the + * new incoming connection request (e.g. selecting a listen sk for + * the received SYN in the TCP case). reuse->sk is one of the sk + * in the reuseport group. The bpf prog can use reuse->sk to learn + * the local listening ip/port without looking into the skb. + * + * When reuse->migrating_sk is not NULL, reuse->sk is closed and + * reuse->migrating_sk is the socket that needs to be migrated + * to another listening socket. migrating_sk could be a fullsock + * sk that is fully established or a reqsk that is in-the-middle + * of 3-way handshake. + */ + __bpf_md_ptr(struct bpf_sock *, sk); + __bpf_md_ptr(struct bpf_sock *, migrating_sk); +}; + +#define BPF_TAG_SIZE 8 + +struct bpf_prog_info { + __u32 type; + __u32 id; + __u8 tag[BPF_TAG_SIZE]; + __u32 jited_prog_len; + __u32 xlated_prog_len; + __aligned_u64 jited_prog_insns; + __aligned_u64 xlated_prog_insns; + __u64 load_time; /* ns since boottime */ + __u32 created_by_uid; + __u32 nr_map_ids; + __aligned_u64 map_ids; + char name[BPF_OBJ_NAME_LEN]; + __u32 ifindex; + __u32 gpl_compatible:1; + __u32 :31; /* alignment pad */ + __u64 netns_dev; + __u64 netns_ino; + __u32 nr_jited_ksyms; + __u32 nr_jited_func_lens; + __aligned_u64 jited_ksyms; + __aligned_u64 jited_func_lens; + __u32 btf_id; + __u32 func_info_rec_size; + __aligned_u64 func_info; + __u32 nr_func_info; + __u32 nr_line_info; + __aligned_u64 line_info; + __aligned_u64 jited_line_info; + __u32 nr_jited_line_info; + __u32 line_info_rec_size; + __u32 jited_line_info_rec_size; + __u32 nr_prog_tags; + __aligned_u64 prog_tags; + __u64 run_time_ns; + __u64 run_cnt; + __u64 recursion_misses; +} __attribute__((aligned(8))); + +struct bpf_map_info { + __u32 type; + __u32 id; + __u32 key_size; + __u32 value_size; + __u32 max_entries; + __u32 map_flags; + char name[BPF_OBJ_NAME_LEN]; + __u32 ifindex; + __u32 btf_vmlinux_value_type_id; + __u64 netns_dev; + __u64 netns_ino; + __u32 btf_id; + __u32 btf_key_type_id; + __u32 btf_value_type_id; +} __attribute__((aligned(8))); + +struct bpf_btf_info { + __aligned_u64 btf; + __u32 btf_size; + __u32 id; + __aligned_u64 name; + __u32 name_len; + __u32 kernel_btf; +} __attribute__((aligned(8))); + +struct bpf_link_info { + __u32 type; + __u32 id; + __u32 prog_id; + union { + struct { + __aligned_u64 tp_name; /* in/out: tp_name buffer ptr */ + __u32 tp_name_len; /* in/out: tp_name buffer len */ + } raw_tracepoint; + struct { + __u32 attach_type; + __u32 target_obj_id; /* prog_id for PROG_EXT, otherwise btf object id */ + __u32 target_btf_id; /* BTF type id inside the object */ + } tracing; + struct { + __u64 cgroup_id; + __u32 attach_type; + } cgroup; + struct { + __aligned_u64 target_name; /* in/out: target_name buffer ptr */ + __u32 target_name_len; /* in/out: target_name buffer len */ + union { + struct { + __u32 map_id; + } map; + }; + } iter; + struct { + __u32 netns_ino; + __u32 attach_type; + } netns; + struct { + __u32 ifindex; + } xdp; + }; +} __attribute__((aligned(8))); + +/* User bpf_sock_addr struct to access socket fields and sockaddr struct passed + * by user and intended to be used by socket (e.g. to bind to, depends on + * attach type). + */ +struct bpf_sock_addr { + __u32 user_family; /* Allows 4-byte read, but no write. */ + __u32 user_ip4; /* Allows 1,2,4-byte read and 4-byte write. + * Stored in network byte order. + */ + __u32 user_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. + * Stored in network byte order. + */ + __u32 user_port; /* Allows 1,2,4-byte read and 4-byte write. + * Stored in network byte order + */ + __u32 family; /* Allows 4-byte read, but no write */ + __u32 type; /* Allows 4-byte read, but no write */ + __u32 protocol; /* Allows 4-byte read, but no write */ + __u32 msg_src_ip4; /* Allows 1,2,4-byte read and 4-byte write. + * Stored in network byte order. + */ + __u32 msg_src_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. + * Stored in network byte order. + */ + __bpf_md_ptr(struct bpf_sock *, sk); +}; + +/* User bpf_sock_ops struct to access socket values and specify request ops + * and their replies. + * Some of this fields are in network (bigendian) byte order and may need + * to be converted before use (bpf_ntohl() defined in samples/bpf/bpf_endian.h). + * New fields can only be added at the end of this structure + */ +struct bpf_sock_ops { + __u32 op; + union { + __u32 args[4]; /* Optionally passed to bpf program */ + __u32 reply; /* Returned by bpf program */ + __u32 replylong[4]; /* Optionally returned by bpf prog */ + }; + __u32 family; + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ + __u32 is_fullsock; /* Some TCP fields are only valid if + * there is a full socket. If not, the + * fields read as zero. + */ + __u32 snd_cwnd; + __u32 srtt_us; /* Averaged RTT << 3 in usecs */ + __u32 bpf_sock_ops_cb_flags; /* flags defined in uapi/linux/tcp.h */ + __u32 state; + __u32 rtt_min; + __u32 snd_ssthresh; + __u32 rcv_nxt; + __u32 snd_nxt; + __u32 snd_una; + __u32 mss_cache; + __u32 ecn_flags; + __u32 rate_delivered; + __u32 rate_interval_us; + __u32 packets_out; + __u32 retrans_out; + __u32 total_retrans; + __u32 segs_in; + __u32 data_segs_in; + __u32 segs_out; + __u32 data_segs_out; + __u32 lost_out; + __u32 sacked_out; + __u32 sk_txhash; + __u64 bytes_received; + __u64 bytes_acked; + __bpf_md_ptr(struct bpf_sock *, sk); + /* [skb_data, skb_data_end) covers the whole TCP header. + * + * BPF_SOCK_OPS_PARSE_HDR_OPT_CB: The packet received + * BPF_SOCK_OPS_HDR_OPT_LEN_CB: Not useful because the + * header has not been written. + * BPF_SOCK_OPS_WRITE_HDR_OPT_CB: The header and options have + * been written so far. + * BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB: The SYNACK that concludes + * the 3WHS. + * BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB: The ACK that concludes + * the 3WHS. + * + * bpf_load_hdr_opt() can also be used to read a particular option. + */ + __bpf_md_ptr(void *, skb_data); + __bpf_md_ptr(void *, skb_data_end); + __u32 skb_len; /* The total length of a packet. + * It includes the header, options, + * and payload. + */ + __u32 skb_tcp_flags; /* tcp_flags of the header. It provides + * an easy way to check for tcp_flags + * without parsing skb_data. + * + * In particular, the skb_tcp_flags + * will still be available in + * BPF_SOCK_OPS_HDR_OPT_LEN even though + * the outgoing header has not + * been written yet. + */ +}; + +/* Definitions for bpf_sock_ops_cb_flags */ +enum { + BPF_SOCK_OPS_RTO_CB_FLAG = (1<<0), + BPF_SOCK_OPS_RETRANS_CB_FLAG = (1<<1), + BPF_SOCK_OPS_STATE_CB_FLAG = (1<<2), + BPF_SOCK_OPS_RTT_CB_FLAG = (1<<3), + /* Call bpf for all received TCP headers. The bpf prog will be + * called under sock_ops->op == BPF_SOCK_OPS_PARSE_HDR_OPT_CB + * + * Please refer to the comment in BPF_SOCK_OPS_PARSE_HDR_OPT_CB + * for the header option related helpers that will be useful + * to the bpf programs. + * + * It could be used at the client/active side (i.e. connect() side) + * when the server told it that the server was in syncookie + * mode and required the active side to resend the bpf-written + * options. The active side can keep writing the bpf-options until + * it received a valid packet from the server side to confirm + * the earlier packet (and options) has been received. The later + * example patch is using it like this at the active side when the + * server is in syncookie mode. + * + * The bpf prog will usually turn this off in the common cases. + */ + BPF_SOCK_OPS_PARSE_ALL_HDR_OPT_CB_FLAG = (1<<4), + /* Call bpf when kernel has received a header option that + * the kernel cannot handle. The bpf prog will be called under + * sock_ops->op == BPF_SOCK_OPS_PARSE_HDR_OPT_CB. + * + * Please refer to the comment in BPF_SOCK_OPS_PARSE_HDR_OPT_CB + * for the header option related helpers that will be useful + * to the bpf programs. + */ + BPF_SOCK_OPS_PARSE_UNKNOWN_HDR_OPT_CB_FLAG = (1<<5), + /* Call bpf when the kernel is writing header options for the + * outgoing packet. The bpf prog will first be called + * to reserve space in a skb under + * sock_ops->op == BPF_SOCK_OPS_HDR_OPT_LEN_CB. Then + * the bpf prog will be called to write the header option(s) + * under sock_ops->op == BPF_SOCK_OPS_WRITE_HDR_OPT_CB. + * + * Please refer to the comment in BPF_SOCK_OPS_HDR_OPT_LEN_CB + * and BPF_SOCK_OPS_WRITE_HDR_OPT_CB for the header option + * related helpers that will be useful to the bpf programs. + * + * The kernel gets its chance to reserve space and write + * options first before the BPF program does. + */ + BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG = (1<<6), +/* Mask of all currently supported cb flags */ + BPF_SOCK_OPS_ALL_CB_FLAGS = 0x7F, +}; + +/* List of known BPF sock_ops operators. + * New entries can only be added at the end + */ +enum { + BPF_SOCK_OPS_VOID, + BPF_SOCK_OPS_TIMEOUT_INIT, /* Should return SYN-RTO value to use or + * -1 if default value should be used + */ + BPF_SOCK_OPS_RWND_INIT, /* Should return initial advertized + * window (in packets) or -1 if default + * value should be used + */ + BPF_SOCK_OPS_TCP_CONNECT_CB, /* Calls BPF program right before an + * active connection is initialized + */ + BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB, /* Calls BPF program when an + * active connection is + * established + */ + BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB, /* Calls BPF program when a + * passive connection is + * established + */ + BPF_SOCK_OPS_NEEDS_ECN, /* If connection's congestion control + * needs ECN + */ + BPF_SOCK_OPS_BASE_RTT, /* Get base RTT. The correct value is + * based on the path and may be + * dependent on the congestion control + * algorithm. In general it indicates + * a congestion threshold. RTTs above + * this indicate congestion + */ + BPF_SOCK_OPS_RTO_CB, /* Called when an RTO has triggered. + * Arg1: value of icsk_retransmits + * Arg2: value of icsk_rto + * Arg3: whether RTO has expired + */ + BPF_SOCK_OPS_RETRANS_CB, /* Called when skb is retransmitted. + * Arg1: sequence number of 1st byte + * Arg2: # segments + * Arg3: return value of + * tcp_transmit_skb (0 => success) + */ + BPF_SOCK_OPS_STATE_CB, /* Called when TCP changes state. + * Arg1: old_state + * Arg2: new_state + */ + BPF_SOCK_OPS_TCP_LISTEN_CB, /* Called on listen(2), right after + * socket transition to LISTEN state. + */ + BPF_SOCK_OPS_RTT_CB, /* Called on every RTT. + */ + BPF_SOCK_OPS_PARSE_HDR_OPT_CB, /* Parse the header option. + * It will be called to handle + * the packets received at + * an already established + * connection. + * + * sock_ops->skb_data: + * Referring to the received skb. + * It covers the TCP header only. + * + * bpf_load_hdr_opt() can also + * be used to search for a + * particular option. + */ + BPF_SOCK_OPS_HDR_OPT_LEN_CB, /* Reserve space for writing the + * header option later in + * BPF_SOCK_OPS_WRITE_HDR_OPT_CB. + * Arg1: bool want_cookie. (in + * writing SYNACK only) + * + * sock_ops->skb_data: + * Not available because no header has + * been written yet. + * + * sock_ops->skb_tcp_flags: + * The tcp_flags of the + * outgoing skb. (e.g. SYN, ACK, FIN). + * + * bpf_reserve_hdr_opt() should + * be used to reserve space. + */ + BPF_SOCK_OPS_WRITE_HDR_OPT_CB, /* Write the header options + * Arg1: bool want_cookie. (in + * writing SYNACK only) + * + * sock_ops->skb_data: + * Referring to the outgoing skb. + * It covers the TCP header + * that has already been written + * by the kernel and the + * earlier bpf-progs. + * + * sock_ops->skb_tcp_flags: + * The tcp_flags of the outgoing + * skb. (e.g. SYN, ACK, FIN). + * + * bpf_store_hdr_opt() should + * be used to write the + * option. + * + * bpf_load_hdr_opt() can also + * be used to search for a + * particular option that + * has already been written + * by the kernel or the + * earlier bpf-progs. + */ +}; + +/* List of TCP states. There is a build check in net/ipv4/tcp.c to detect + * changes between the TCP and BPF versions. Ideally this should never happen. + * If it does, we need to add code to convert them before calling + * the BPF sock_ops function. + */ +enum { + BPF_TCP_ESTABLISHED = 1, + BPF_TCP_SYN_SENT, + BPF_TCP_SYN_RECV, + BPF_TCP_FIN_WAIT1, + BPF_TCP_FIN_WAIT2, + BPF_TCP_TIME_WAIT, + BPF_TCP_CLOSE, + BPF_TCP_CLOSE_WAIT, + BPF_TCP_LAST_ACK, + BPF_TCP_LISTEN, + BPF_TCP_CLOSING, /* Now a valid state */ + BPF_TCP_NEW_SYN_RECV, + + BPF_TCP_MAX_STATES /* Leave at the end! */ +}; + +enum { + TCP_BPF_IW = 1001, /* Set TCP initial congestion window */ + TCP_BPF_SNDCWND_CLAMP = 1002, /* Set sndcwnd_clamp */ + TCP_BPF_DELACK_MAX = 1003, /* Max delay ack in usecs */ + TCP_BPF_RTO_MIN = 1004, /* Min delay ack in usecs */ + /* Copy the SYN pkt to optval + * + * BPF_PROG_TYPE_SOCK_OPS only. It is similar to the + * bpf_getsockopt(TCP_SAVED_SYN) but it does not limit + * to only getting from the saved_syn. It can either get the + * syn packet from: + * + * 1. the just-received SYN packet (only available when writing the + * SYNACK). It will be useful when it is not necessary to + * save the SYN packet for latter use. It is also the only way + * to get the SYN during syncookie mode because the syn + * packet cannot be saved during syncookie. + * + * OR + * + * 2. the earlier saved syn which was done by + * bpf_setsockopt(TCP_SAVE_SYN). + * + * The bpf_getsockopt(TCP_BPF_SYN*) option will hide where the + * SYN packet is obtained. + * + * If the bpf-prog does not need the IP[46] header, the + * bpf-prog can avoid parsing the IP header by using + * TCP_BPF_SYN. Otherwise, the bpf-prog can get both + * IP[46] and TCP header by using TCP_BPF_SYN_IP. + * + * >0: Total number of bytes copied + * -ENOSPC: Not enough space in optval. Only optlen number of + * bytes is copied. + * -ENOENT: The SYN skb is not available now and the earlier SYN pkt + * is not saved by setsockopt(TCP_SAVE_SYN). + */ + TCP_BPF_SYN = 1005, /* Copy the TCP header */ + TCP_BPF_SYN_IP = 1006, /* Copy the IP[46] and TCP header */ + TCP_BPF_SYN_MAC = 1007, /* Copy the MAC, IP[46], and TCP header */ +}; + +enum { + BPF_LOAD_HDR_OPT_TCP_SYN = (1ULL << 0), +}; + +/* args[0] value during BPF_SOCK_OPS_HDR_OPT_LEN_CB and + * BPF_SOCK_OPS_WRITE_HDR_OPT_CB. + */ +enum { + BPF_WRITE_HDR_TCP_CURRENT_MSS = 1, /* Kernel is finding the + * total option spaces + * required for an established + * sk in order to calculate the + * MSS. No skb is actually + * sent. + */ + BPF_WRITE_HDR_TCP_SYNACK_COOKIE = 2, /* Kernel is in syncookie mode + * when sending a SYN. + */ +}; + +struct bpf_perf_event_value { + __u64 counter; + __u64 enabled; + __u64 running; +}; + +enum { + BPF_DEVCG_ACC_MKNOD = (1ULL << 0), + BPF_DEVCG_ACC_READ = (1ULL << 1), + BPF_DEVCG_ACC_WRITE = (1ULL << 2), +}; + +enum { + BPF_DEVCG_DEV_BLOCK = (1ULL << 0), + BPF_DEVCG_DEV_CHAR = (1ULL << 1), +}; + +struct bpf_cgroup_dev_ctx { + /* access_type encoded as (BPF_DEVCG_ACC_* << 16) | BPF_DEVCG_DEV_* */ + __u32 access_type; + __u32 major; + __u32 minor; +}; + +struct bpf_raw_tracepoint_args { + __u64 args[0]; +}; + +/* DIRECT: Skip the FIB rules and go to FIB table associated with device + * OUTPUT: Do lookup from egress perspective; default is ingress + */ +enum { + BPF_FIB_LOOKUP_DIRECT = (1U << 0), + BPF_FIB_LOOKUP_OUTPUT = (1U << 1), +}; + +enum { + BPF_FIB_LKUP_RET_SUCCESS, /* lookup successful */ + BPF_FIB_LKUP_RET_BLACKHOLE, /* dest is blackholed; can be dropped */ + BPF_FIB_LKUP_RET_UNREACHABLE, /* dest is unreachable; can be dropped */ + BPF_FIB_LKUP_RET_PROHIBIT, /* dest not allowed; can be dropped */ + BPF_FIB_LKUP_RET_NOT_FWDED, /* packet is not forwarded */ + BPF_FIB_LKUP_RET_FWD_DISABLED, /* fwding is not enabled on ingress */ + BPF_FIB_LKUP_RET_UNSUPP_LWT, /* fwd requires encapsulation */ + BPF_FIB_LKUP_RET_NO_NEIGH, /* no neighbor entry for nh */ + BPF_FIB_LKUP_RET_FRAG_NEEDED, /* fragmentation required to fwd */ +}; + +struct bpf_fib_lookup { + /* input: network family for lookup (AF_INET, AF_INET6) + * output: network family of egress nexthop + */ + __u8 family; + + /* set if lookup is to consider L4 data - e.g., FIB rules */ + __u8 l4_protocol; + __be16 sport; + __be16 dport; + + union { /* used for MTU check */ + /* input to lookup */ + __u16 tot_len; /* L3 length from network hdr (iph->tot_len) */ + + /* output: MTU value */ + __u16 mtu_result; + }; + /* input: L3 device index for lookup + * output: device index from FIB lookup + */ + __u32 ifindex; + + union { + /* inputs to lookup */ + __u8 tos; /* AF_INET */ + __be32 flowinfo; /* AF_INET6, flow_label + priority */ + + /* output: metric of fib result (IPv4/IPv6 only) */ + __u32 rt_metric; + }; + + union { + __be32 ipv4_src; + __u32 ipv6_src[4]; /* in6_addr; network order */ + }; + + /* input to bpf_fib_lookup, ipv{4,6}_dst is destination address in + * network header. output: bpf_fib_lookup sets to gateway address + * if FIB lookup returns gateway route + */ + union { + __be32 ipv4_dst; + __u32 ipv6_dst[4]; /* in6_addr; network order */ + }; + + /* output */ + __be16 h_vlan_proto; + __be16 h_vlan_TCI; + __u8 smac[6]; /* ETH_ALEN */ + __u8 dmac[6]; /* ETH_ALEN */ +}; + +struct bpf_redir_neigh { + /* network family for lookup (AF_INET, AF_INET6) */ + __u32 nh_family; + /* network address of nexthop; skips fib lookup to find gateway */ + union { + __be32 ipv4_nh; + __u32 ipv6_nh[4]; /* in6_addr; network order */ + }; +}; + +/* bpf_check_mtu flags*/ +enum bpf_check_mtu_flags { + BPF_MTU_CHK_SEGS = (1U << 0), +}; + +enum bpf_check_mtu_ret { + BPF_MTU_CHK_RET_SUCCESS, /* check and lookup successful */ + BPF_MTU_CHK_RET_FRAG_NEEDED, /* fragmentation required to fwd */ + BPF_MTU_CHK_RET_SEGS_TOOBIG, /* GSO re-segmentation needed to fwd */ +}; + +enum bpf_task_fd_type { + BPF_FD_TYPE_RAW_TRACEPOINT, /* tp name */ + BPF_FD_TYPE_TRACEPOINT, /* tp name */ + BPF_FD_TYPE_KPROBE, /* (symbol + offset) or addr */ + BPF_FD_TYPE_KRETPROBE, /* (symbol + offset) or addr */ + BPF_FD_TYPE_UPROBE, /* filename + offset */ + BPF_FD_TYPE_URETPROBE, /* filename + offset */ +}; + +enum { + BPF_FLOW_DISSECTOR_F_PARSE_1ST_FRAG = (1U << 0), + BPF_FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL = (1U << 1), + BPF_FLOW_DISSECTOR_F_STOP_AT_ENCAP = (1U << 2), +}; + +struct bpf_flow_keys { + __u16 nhoff; + __u16 thoff; + __u16 addr_proto; /* ETH_P_* of valid addrs */ + __u8 is_frag; + __u8 is_first_frag; + __u8 is_encap; + __u8 ip_proto; + __be16 n_proto; + __be16 sport; + __be16 dport; + union { + struct { + __be32 ipv4_src; + __be32 ipv4_dst; + }; + struct { + __u32 ipv6_src[4]; /* in6_addr; network order */ + __u32 ipv6_dst[4]; /* in6_addr; network order */ + }; + }; + __u32 flags; + __be32 flow_label; +}; + +struct bpf_func_info { + __u32 insn_off; + __u32 type_id; +}; + +#define BPF_LINE_INFO_LINE_NUM(line_col) ((line_col) >> 10) +#define BPF_LINE_INFO_LINE_COL(line_col) ((line_col) & 0x3ff) + +struct bpf_line_info { + __u32 insn_off; + __u32 file_name_off; + __u32 line_off; + __u32 line_col; +}; + +struct bpf_spin_lock { + __u32 val; +}; + +struct bpf_sysctl { + __u32 write; /* Sysctl is being read (= 0) or written (= 1). + * Allows 1,2,4-byte read, but no write. + */ + __u32 file_pos; /* Sysctl file position to read from, write to. + * Allows 1,2,4-byte read an 4-byte write. + */ +}; + +struct bpf_sockopt { + __bpf_md_ptr(struct bpf_sock *, sk); + __bpf_md_ptr(void *, optval); + __bpf_md_ptr(void *, optval_end); + + __s32 level; + __s32 optname; + __s32 optlen; + __s32 retval; +}; + +struct bpf_pidns_info { + __u32 pid; + __u32 tgid; +}; + +/* User accessible data for SK_LOOKUP programs. Add new fields at the end. */ +struct bpf_sk_lookup { + union { + __bpf_md_ptr(struct bpf_sock *, sk); /* Selected socket */ + __u64 cookie; /* Non-zero if socket was selected in PROG_TEST_RUN */ + }; + + __u32 family; /* Protocol family (AF_INET, AF_INET6) */ + __u32 protocol; /* IP protocol (IPPROTO_TCP, IPPROTO_UDP) */ + __u32 remote_ip4; /* Network byte order */ + __u32 remote_ip6[4]; /* Network byte order */ + __u32 remote_port; /* Network byte order */ + __u32 local_ip4; /* Network byte order */ + __u32 local_ip6[4]; /* Network byte order */ + __u32 local_port; /* Host byte order */ +}; + +/* + * struct btf_ptr is used for typed pointer representation; the + * type id is used to render the pointer data as the appropriate type + * via the bpf_snprintf_btf() helper described above. A flags field - + * potentially to specify additional details about the BTF pointer + * (rather than its mode of display) - is included for future use. + * Display flags - BTF_F_* - are passed to bpf_snprintf_btf separately. + */ +struct btf_ptr { + void *ptr; + __u32 type_id; + __u32 flags; /* BTF ptr flags; unused at present. */ +}; + +/* + * Flags to control bpf_snprintf_btf() behaviour. + * - BTF_F_COMPACT: no formatting around type information + * - BTF_F_NONAME: no struct/union member names/types + * - BTF_F_PTR_RAW: show raw (unobfuscated) pointer values; + * equivalent to %px. + * - BTF_F_ZERO: show zero-valued struct/union members; they + * are not displayed by default + */ +enum { + BTF_F_COMPACT = (1ULL << 0), + BTF_F_NONAME = (1ULL << 1), + BTF_F_PTR_RAW = (1ULL << 2), + BTF_F_ZERO = (1ULL << 3), +}; + +#endif /* _UAPI__LINUX_BPF_H__ */ diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf-support.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf-support.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf-support.c 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf-support.c 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +#include "bpf-support.h" + +#include +#include +#include +#include +#include +#include + +#include "utils.h" + +static int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr, size_t size) { +#ifdef SYS_bpf + return syscall(SYS_bpf, cmd, attr, size); +#else + errno = ENOSYS; + return -1; +#endif +} + +#define __ptr_as_u64(__x) ((uint64_t)(uintptr_t)__x) + +int bpf_create_map(enum bpf_map_type type, size_t key_size, size_t value_size, size_t max_entries) { + debug("create bpf map of type 0x%x, key size %zu, value size %zu, entries %zu", type, key_size, value_size, + max_entries); + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + attr.map_type = type; + attr.key_size = key_size; + attr.value_size = value_size; + attr.max_entries = max_entries; + return sys_bpf(BPF_MAP_CREATE, &attr, sizeof(attr)); +} + +int bpf_update_map(int map_fd, const void *key, const void *value) { + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + attr.map_fd = map_fd; + attr.key = __ptr_as_u64(key); + attr.value = __ptr_as_u64(value); + /* update or create an existing element */ + attr.flags = BPF_ANY; + return sys_bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr)); +} + +int bpf_pin_to_path(int fd, const char *path) { + debug("pin bpf object %d to path %s", fd, path); + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + attr.bpf_fd = fd; + /* pointer must be converted to a u64 */ + attr.pathname = __ptr_as_u64(path); + + return sys_bpf(BPF_OBJ_PIN, &attr, sizeof(attr)); +} + +int bpf_get_by_path(const char *path) { + debug("get bpf object at path %s", path); + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + /* pointer must be converted to a u64 */ + attr.pathname = __ptr_as_u64(path); + + return sys_bpf(BPF_OBJ_GET, &attr, sizeof(attr)); +} + +int bpf_load_prog(enum bpf_prog_type type, const struct bpf_insn *insns, size_t insns_cnt, char *log_buf, + size_t log_buf_size) { + if (type == BPF_PROG_TYPE_UNSPEC) { + errno = EINVAL; + return -1; + } + debug("load program of type 0x%x, %zu instructions", type, insns_cnt); + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + attr.prog_type = type; + attr.insns = __ptr_as_u64(insns); + attr.insn_cnt = (uint64_t)insns_cnt; + attr.license = __ptr_as_u64("GPL"); + if (log_buf != NULL) { + attr.log_buf = __ptr_as_u64(log_buf); + attr.log_size = log_buf_size; + attr.log_level = 1; + } + + /* XXX: libbpf does a while loop checking for EAGAIN */ + /* XXX: do we need to handle E2BIG? */ + return sys_bpf(BPF_PROG_LOAD, &attr, sizeof(attr)); +} + +int bpf_prog_attach(enum bpf_attach_type type, int cgroup_fd, int prog_fd) { + debug("attach type 0x%x program %d to cgroup %d", type, prog_fd, cgroup_fd); + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + + attr.attach_type = type; + attr.target_fd = cgroup_fd; + attr.attach_bpf_fd = prog_fd; + + return sys_bpf(BPF_PROG_ATTACH, &attr, sizeof(attr)); +} + +int bpf_map_get_next_key(int map_fd, const void *key, void *next_key) { + debug("get next key for map %d", map_fd); + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + + attr.map_fd = map_fd; + attr.key = __ptr_as_u64(key); + attr.next_key = __ptr_as_u64(next_key); + + return sys_bpf(BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr)); +} + +int bpf_map_delete_batch(int map_fd, const void *keys, size_t cnt) { +#if 0 +/* + * XXX: batch operations don't seem to work with 5.13.10, getting -EINVAL + * XXX: also batch operations are supported by recent kernels only + */ + debug("batch delete in map %d keys cnt %zu", map_fd, cnt); + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + + attr.map_fd = map_fd; + attr.batch.keys = __ptr_as_u64(keys); + attr.batch.count = cnt; + /* TODO: getting EINVAL? */ + int ret = sys_bpf(BPF_MAP_DELETE_BATCH, &attr, sizeof(attr)); + debug("returned count %d", attr.batch.count); + return ret; +#endif + errno = ENOSYS; + return -1; +} + +int bpf_map_delete_elem(int map_fd, const void *key) { + debug("delete elem in map %d", map_fd); + union bpf_attr attr; + memset(&attr, 0, sizeof(attr)); + + attr.map_fd = map_fd; + attr.key = __ptr_as_u64(key); + + return sys_bpf(BPF_MAP_DELETE_ELEM, &attr, sizeof(attr)); +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf-support.h ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf-support.h --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf-support.h 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/bpf-support.h 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +#ifndef SNAP_CONFINE_BPF_SUPPORT_H +#define SNAP_CONFINE_BPF_SUPPORT_H + +#include +#include + +/** + * bpf_pin_to_path pins an object referenced by fd to a path under a bpffs + * mount. + */ +int bpf_pin_to_path(int fd, const char *path); + +/** + * bpf_get_by_path obtains the file handle to the object referenced by a path + * under bpffs filesystem. The returned file descriptor has O_CLOEXEC flag set + * on it. + */ +int bpf_get_by_path(const char *path); + +/** + * bpf_load_prog loads a given BPF program and returns a file descriptor handle + * to it. + * + * The program is passed as an insns_cnt long array of BPF instructions. + * Passing non-NULL log buf, will populate the buffer with output from verifier + * if the program is found to be invalid. The returned file descriptor has + * O_CLOEXEC flag set on it. + */ +int bpf_load_prog(enum bpf_prog_type type, const struct bpf_insn *insns, size_t insns_cnt, char *log_buf, + size_t log_buf_size); + +int bpf_prog_attach(enum bpf_attach_type type, int cgroup_fd, int prog_fd); + +/** + * bf_create_map creates a BPF map and returns a file descriptor handle to it. + * The returned file descriptor has O_CLOEXEC flag set on it. + */ +int bpf_create_map(enum bpf_map_type type, size_t key_size, size_t value_size, size_t max_entries); + +/** + * bpf_update_map updates the value of element with a given key (or adds it to + * the map). + */ +int bpf_update_map(int map_fd, const void *key, const void *value); + +/** + * bpf_map_get_next_key iterates over keys of the map. + * + * When key does not match anything in the map, it is set to the first element + * of the map and next_key holds the next key. Subsequent calls will obtain the + * next_key following key. When an end if reached, -1 is returned and error is + * set to ENOENT. + */ +int bpf_map_get_next_key(int map_fd, const void *key, void *next_key); + +/** + * bpf_map_delete_batch performs a batch delete of elements with keys, where cnt + * is the number of keys. + */ +int bpf_map_delete_batch(int map_fd, const void *keys, size_t cnt); + +/** + * bpf_map_delete_elem deletes an element with a key from the map, returns -1 + * and ENOENT when the element did not exist. + */ +int bpf_map_delete_elem(int map_fd, const void *key); + +#endif /* SNAP_CONFINE_BPF_SUPPORT_H */ diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-freezer-support.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-freezer-support.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-freezer-support.c 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-freezer-support.c 2023-03-23 08:10:58.000000000 +0000 @@ -115,8 +115,9 @@ if (errno != ENOENT) { die("cannot stat /proc/%s", line_buf); } + continue; } - debug("found process %s belonging to user %d", + debug("found live process %s belonging to user %d", line_buf, statbuf.st_uid); return true; } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support.c 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support.c 2023-03-23 08:10:58.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Canonical Ltd + * Copyright (C) 2019-2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -15,12 +15,13 @@ * */ -// For AT_EMPTY_PATH and O_PATH #define _GNU_SOURCE #include "cgroup-support.h" +#include #include +#include #include #include #include @@ -71,15 +72,14 @@ static const char *cgroup_dir = "/sys/fs/cgroup"; // from statfs(2) -#ifndef CGRUOP2_SUPER_MAGIC +#ifndef CGROUP2_SUPER_MAGIC #define CGROUP2_SUPER_MAGIC 0x63677270 #endif // Detect if we are running in cgroup v2 unified mode (as opposed to // hybrid or legacy) The algorithm is described in // https://systemd.io/CGROUP_DELEGATION/ -bool sc_cgroup_is_v2() { - static bool did_warn = false; +bool sc_cgroup_is_v2(void) { struct statfs buf; if (statfs(cgroup_dir, &buf) != 0) { @@ -89,11 +89,153 @@ die("cannot statfs %s", cgroup_dir); } if (buf.f_type == CGROUP2_SUPER_MAGIC) { - if (!did_warn) { - fprintf(stderr, "WARNING: cgroup v2 is not fully supported yet, proceeding with partial confinement\n"); - did_warn = true; - } return true; } return false; } + +static const size_t max_traversal_depth = 32; + +static bool traverse_looking_for_prefix_in_dir(DIR *root, const char *prefix, const char *skip, size_t depth) { + if (depth > max_traversal_depth) { + die("cannot traverse cgroups hierarchy deeper than %zu levels", max_traversal_depth); + } + while (true) { + errno = 0; + struct dirent *ent = readdir(root); + if (ent == NULL) { + // is this an error? + if (errno != 0) { + if (errno == ENOENT) { + // the processes may exit and the group entries may go away at + // any time + // the entries may go away at any time + break; + } + die("cannot read directory entry"); + } + break; + } + if (ent->d_type != DT_DIR) { + continue; + } + if (sc_streq(ent->d_name, "..") || sc_streq(ent->d_name, ".")) { + // we don't want to go up or process the current directory again + continue; + } + if (sc_streq(ent->d_name, skip)) { + // we were asked to skip this group + continue; + } + if (sc_startswith(ent->d_name, prefix)) { + debug("found matching prefix in \"%s\"", ent->d_name); + // the directory starts with our prefix + return true; + } + // entfd is consumed by fdopendir() and freed with closedir() + int entfd = openat(dirfd(root), ent->d_name, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); + if (entfd == -1) { + if (errno == ENOENT) { + // the processes may exit and the group entries may go away at + // any time + return false; + } + die("cannot open directory entry \"%s\"", ent->d_name); + } + // takes ownership of the file descriptor + DIR *entdir SC_CLEANUP(sc_cleanup_closedir) = fdopendir(entfd); + if (entdir == NULL) { + // we have the fd, so ENOENT isn't possible here + die("cannot fdopendir directory \"%s\"", ent->d_name); + } + bool found = traverse_looking_for_prefix_in_dir(entdir, prefix, skip, depth + 1); + if (found == true) { + return true; + } + } + return false; +} + +bool sc_cgroup_v2_is_tracking_snap(const char *snap_instance) { + debug("is cgroup tracking snap %s?", snap_instance); + char tracking_group_name[PATH_MAX] = {0}; + // tracking groups created by snap run chain have a format: + // snap....scope, while the groups corresponding to snap + // services created by systemd are named like this: + // snap...service + sc_must_snprintf(tracking_group_name, sizeof tracking_group_name, "snap.%s.", snap_instance); + + // when running with cgroup v2, the snap run chain or systemd would create a + // tracking cgroup which the current process would execute in and would + // match the pattern we are looking for, thus it needs to be skipped + char *own_group SC_CLEANUP(sc_cleanup_string) = sc_cgroup_v2_own_path_full(); + if (own_group == NULL) { + die("cannot obtain own cgroup v2 group path"); + } + debug("own group: %s", own_group); + char *just_leaf = strrchr(own_group, '/'); + if (just_leaf == NULL) { + die("cannot obtain the leaf group path"); + } + // pointing at /, advance to the next char + just_leaf += 1; + + // this would otherwise be inherently racy, but the caller is expected to + // keep the snap instance lock, thus preventing new apps of that snap from + // starting; note that we can still return false positive if the currently + // running process exits but we look at the hierarchy before systemd has + // cleaned up the group + + debug("opening cgroup root dir at %s", cgroup_dir); + DIR *root SC_CLEANUP(sc_cleanup_closedir) = opendir(cgroup_dir); + if (root == NULL) { + if (errno == ENOENT) { + return false; + } + die("cannot open cgroup root dir"); + } + // traverse the cgroup hierarchy tree looking for other groups that + // correspond to the snap (i.e. their name matches the pattern), but skip + // our own group in the process + return traverse_looking_for_prefix_in_dir(root, tracking_group_name, just_leaf, 1); +} + +static const char *self_cgroup = "/proc/self/cgroup"; + +char *sc_cgroup_v2_own_path_full(void) { + FILE *in SC_CLEANUP(sc_cleanup_file) = fopen(self_cgroup, "r"); + if (in == NULL) { + die("cannot open %s", self_cgroup); + } + + char *own_group = NULL; + + while (true) { + char *line SC_CLEANUP(sc_cleanup_string) = NULL; + size_t linesz = 0; + ssize_t sz = getline(&line, &linesz, in); + if (sz < 0 && errno != 0) { + die("cannot read line from %s", self_cgroup); + } + if (sz < 0) { + // end of file + break; + } + if (!sc_startswith(line, "0::")) { + continue; + } + size_t len = strlen(line); + if (len <= 3) { + die("unexpected content of group entry %s", line); + } + // \n does not normally appear inside the group path, but if it did, it + // would be escaped anyway + char *newline = strchr(line, '\n'); + if (newline != NULL) { + *newline = '\0'; + } + own_group = sc_strdup(line + 3); + break; + } + return own_group; +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support.h ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support.h --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support.h 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support.h 2023-03-23 08:10:58.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 Canonical Ltd + * Copyright (C) 2019-2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -37,4 +37,29 @@ **/ bool sc_cgroup_is_v2(void); +/** + * sc_cgroup_is_tracking_snap checks whether any snap process other than the + * caller are currently being tracked in a cgroup. + * + * Note that this call will traverse the cgroups hierarchy looking for a group + * name with a specific prefix corresponding to the snap name. This is + * inherently racy. The caller must have taken the per snap instance lock to + * prevent new applications of that snap from being started. However, it is + * still possible that the application may exit but the cgroup has not been + * cleaned up yet, in which case this call will return a false positive. + * + * It is possible that the current process is already being tracked in cgroup, + * in which case the code will skip its own group. + */ +bool sc_cgroup_v2_is_tracking_snap(const char *snap_instance); + +/** + * sc_cgroup_v2_own_path_full return the full path of the owning cgroup as + * reported by the kernel. + * + * Returns the full path of the group in the unified hierarchy relative to its + * root. The string is owned by the caller. + */ +char *sc_cgroup_v2_own_path_full(void); + #endif diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support-test.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support-test.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support-test.c 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cgroup-support-test.c 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,366 @@ +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +#include "cgroup-support.c" + +#include +#include +#include +#include +#include +#include + +#include "../libsnap-confine-private/cleanup-funcs.h" +#include "../libsnap-confine-private/test-utils.h" +#include "cgroup-support.h" + +static void sc_set_self_cgroup_path(const char *mock); + +static void sc_set_cgroup_root(const char *mock) { cgroup_dir = mock; } + +typedef struct _cgroupv2_is_tracking_fixture { + char *self_cgroup; + char *root; +} cgroupv2_is_tracking_fixture; + +static void cgroupv2_is_tracking_set_up(cgroupv2_is_tracking_fixture *fixture, gconstpointer user_data) { + GError *err = NULL; + int fd = g_file_open_tmp("s-c-unit-is-tracking-self-group.XXXXXX", &fixture->self_cgroup, &err); + g_assert_no_error(err); + g_assert_cmpint(fd, >=, 0); + g_close(fd, &err); + g_assert_no_error(err); + sc_set_self_cgroup_path(fixture->self_cgroup); + + fixture->root = g_dir_make_tmp("s-c-unit-test-root.XXXXXX", &err); + sc_set_cgroup_root(fixture->root); +} + +static void cgroupv2_is_tracking_tear_down(cgroupv2_is_tracking_fixture *fixture, gconstpointer user_data) { + GError *err = NULL; + + sc_set_self_cgroup_path("/proc/self/cgroup"); + /* mocked file may have been removed by the test */ + (void)g_remove(fixture->self_cgroup); + g_free(fixture->self_cgroup); + + sc_set_cgroup_root("/sys/fs/cgroup"); + char *cmd = g_strdup_printf("rm -rf %s", fixture->root); + g_debug("cleanup command: %s", cmd); + g_spawn_command_line_sync(cmd, NULL, NULL, NULL, &err); + g_free(cmd); + g_assert_no_error(err); + g_free(fixture->root); +} + +static void _test_sc_cgroupv2_is_tracking_happy(cgroupv2_is_tracking_fixture *fixture) { + /* there exist 3 groups with processes from a given snap */ + const char *dirs[] = { + "/foo/bar/baz/snap.foo.app.1234-1234.scope", + "/foo/bar/snap.foo.app.1111-1111.scope", + "/foo/bar/bad", + "/system.slice/snap.foo.bar.service", + "/user/slice/other/app", + }; + + for (size_t i = 0; i < sizeof dirs / sizeof dirs[0]; i++) { + char *np = g_build_filename(fixture->root, dirs[i], NULL); + int ret = g_mkdir_with_parents(np, 0755); + g_assert_cmpint(ret, ==, 0); + g_free(np); + } + + bool is_tracking = sc_cgroup_v2_is_tracking_snap("foo"); + g_assert_true(is_tracking); +} + +static void test_sc_cgroupv2_is_tracking_happy_scope(cgroupv2_is_tracking_fixture *fixture, gconstpointer user_data) { + g_assert_true(g_file_set_contents(fixture->self_cgroup, "0::/foo/bar/baz/snap.foo.app.1234-1234.scope", -1, NULL)); + + _test_sc_cgroupv2_is_tracking_happy(fixture); +} + +static void test_sc_cgroupv2_is_tracking_happy_service(cgroupv2_is_tracking_fixture *fixture, gconstpointer user_data) { + g_assert_true(g_file_set_contents(fixture->self_cgroup, "0::/system.slice/snap.foo.svc.service", -1, NULL)); + + _test_sc_cgroupv2_is_tracking_happy(fixture); +} + +static void test_sc_cgroupv2_is_tracking_just_own_group(cgroupv2_is_tracking_fixture *fixture, + gconstpointer user_data) { + g_assert_true(g_file_set_contents(fixture->self_cgroup, "0::/foo/bar/baz/snap.foo.app.1234-1234.scope", -1, NULL)); + + /* our group is the only one for this snap */ + const char *dirs[] = { + "/foo/bar/baz/snap.foo.app.1234-1234.scope", + "/foo/bar/bad", + "/system.slice/some/app/other", + "/user/slice/other/app", + }; + + for (size_t i = 0; i < sizeof dirs / sizeof dirs[0]; i++) { + char *np = g_build_filename(fixture->root, dirs[i], NULL); + int ret = g_mkdir_with_parents(np, 0755); + g_assert_cmpint(ret, ==, 0); + g_free(np); + } + + bool is_tracking = sc_cgroup_v2_is_tracking_snap("foo"); + /* our own group is skipped */ + g_assert_false(is_tracking); +} + +static void test_sc_cgroupv2_is_tracking_other_snaps(cgroupv2_is_tracking_fixture *fixture, gconstpointer user_data) { + g_assert_true(g_file_set_contents(fixture->self_cgroup, "0::/foo/bar/baz/snap.foo.app.1234-1234.scope", -1, NULL)); + + /* our group is the only one for this snap */ + const char *dirs[] = { + "/foo/bar/baz/snap.other.app.1234-1234.scope", + "/foo/bar/bad", + "/system.slice/some/app/snap.one-more.app.service", + "/user/slice/other/app", + }; + + for (size_t i = 0; i < sizeof dirs / sizeof dirs[0]; i++) { + char *np = g_build_filename(fixture->root, dirs[i], NULL); + int ret = g_mkdir_with_parents(np, 0755); + g_assert_cmpint(ret, ==, 0); + g_free(np); + } + + bool is_tracking = sc_cgroup_v2_is_tracking_snap("foo"); + /* our own group is skipped */ + g_assert_false(is_tracking); +} + +static void test_sc_cgroupv2_is_tracking_no_dirs(cgroupv2_is_tracking_fixture *fixture, gconstpointer user_data) { + g_assert_true(g_file_set_contents(fixture->self_cgroup, "0::/foo/bar/baz/snap.foo.app.scope", -1, NULL)); + + bool is_tracking = sc_cgroup_v2_is_tracking_snap("foo"); + g_assert_false(is_tracking); +} + +static void test_sc_cgroupv2_is_tracking_bad_self_group(cgroupv2_is_tracking_fixture *fixture, + gconstpointer user_data) { + /* trigger a failure in own group handling */ + g_assert_true(g_file_set_contents(fixture->self_cgroup, "", -1, NULL)); + + if (g_test_subprocess()) { + sc_cgroup_v2_is_tracking_snap("foo"); + } + g_test_trap_subprocess(NULL, 0, 0); + g_test_trap_assert_failed(); + g_test_trap_assert_stderr("cannot obtain own cgroup v2 group path\n"); +} + +static void test_sc_cgroupv2_is_tracking_bad_nesting(cgroupv2_is_tracking_fixture *fixture, gconstpointer user_data) { + g_assert_true(g_file_set_contents(fixture->self_cgroup, "0::/foo/bar/baz/snap.foo.app.scope", -1, NULL)); + + /* create a hierarchy so deep that it triggers the nesting error */ + char *prev_path = g_build_filename(fixture->root, NULL); + for (size_t i = 0; i < max_traversal_depth; i++) { + char *np = g_build_filename(prev_path, "nested", NULL); + int ret = g_mkdir_with_parents(np, 0755); + g_assert_cmpint(ret, ==, 0); + g_free(prev_path); + prev_path = np; + } + g_free(prev_path); + + if (g_test_subprocess()) { + sc_cgroup_v2_is_tracking_snap("foo"); + } + g_test_trap_subprocess(NULL, 0, 0); + g_test_trap_assert_failed(); + g_test_trap_assert_stderr("cannot traverse cgroups hierarchy deeper than 32 levels\n"); +} + +static void test_sc_cgroupv2_is_tracking_dir_permissions(cgroupv2_is_tracking_fixture *fixture, + gconstpointer user_data) { + if (geteuid() == 0) { + g_test_skip("the test will not work when running as root"); + return; + } + g_assert_true(g_file_set_contents(fixture->self_cgroup, "0::/foo/bar/baz/snap.foo.app.1234-1234.scope", -1, NULL)); + + /* there exist 2 groups with processes from a given snap */ + const char *dirs[] = { + "/foo/bar/bad", + "/foo/bar/bad/badperm", + }; + for (size_t i = 0; i < sizeof dirs / sizeof dirs[0]; i++) { + int mode = 0755; + if (g_str_has_suffix(dirs[i], "/badperm")) { + mode = 0000; + } + char *np = g_build_filename(fixture->root, dirs[i], NULL); + int ret = g_mkdir_with_parents(np, mode); + g_assert_cmpint(ret, ==, 0); + g_free(np); + } + + /* dies when hitting an error traversing the hierarchy */ + if (g_test_subprocess()) { + sc_cgroup_v2_is_tracking_snap("foo"); + } + g_test_trap_subprocess(NULL, 0, 0); + g_test_trap_assert_failed(); + g_test_trap_assert_stderr("cannot open directory entry \"badperm\": Permission denied\n"); +} + +static void test_sc_cgroupv2_is_tracking_no_cgroup_root(cgroupv2_is_tracking_fixture *fixture, + gconstpointer user_data) { + g_assert_true(g_file_set_contents(fixture->self_cgroup, "0::/foo/bar/baz/snap.foo.app.1234-1234.scope", -1, NULL)); + + sc_set_cgroup_root("/does/not/exist"); + + // does not die when cgroup root is not present + bool is_tracking = sc_cgroup_v2_is_tracking_snap("foo"); + g_assert_false(is_tracking); +} + +static void sc_set_self_cgroup_path(const char *mock) { self_cgroup = mock; } + +typedef struct _cgroupv2_own_group_fixture { + char *self_cgroup; +} cgroupv2_own_group_fixture; + +static void cgroupv2_own_group_set_up(cgroupv2_own_group_fixture *fixture, gconstpointer user_data) { + GError *err = NULL; + int fd = g_file_open_tmp("s-c-unit-test.XXXXXX", &fixture->self_cgroup, &err); + g_assert_no_error(err); + g_close(fd, &err); + g_assert_no_error(err); + sc_set_self_cgroup_path(fixture->self_cgroup); +} + +static void cgroupv2_own_group_tear_down(cgroupv2_own_group_fixture *fixture, gconstpointer user_data) { + sc_set_self_cgroup_path("/proc/self/cgroup"); + g_remove(fixture->self_cgroup); + g_free(fixture->self_cgroup); +} + +static void test_sc_cgroupv2_own_group_path_simple_happy_scope(cgroupv2_own_group_fixture *fixture, + gconstpointer user_data) { + char *p SC_CLEANUP(sc_cleanup_string) = NULL; + g_assert_true(g_file_set_contents(fixture->self_cgroup, (char *)user_data, -1, NULL)); + p = sc_cgroup_v2_own_path_full(); + g_assert_cmpstr(p, ==, "/foo/bar/baz.slice/snap.foo.bar.1234-1234.scope"); +} + +static void test_sc_cgroupv2_own_group_path_simple_happy_service(cgroupv2_own_group_fixture *fixture, + gconstpointer user_data) { + char *p SC_CLEANUP(sc_cleanup_string) = NULL; + g_assert_true(g_file_set_contents(fixture->self_cgroup, (char *)user_data, -1, NULL)); + p = sc_cgroup_v2_own_path_full(); + g_assert_cmpstr(p, ==, "/system.slice/snap.foo.bar.service"); +} + +static void test_sc_cgroupv2_own_group_path_empty(cgroupv2_own_group_fixture *fixture, gconstpointer user_data) { + char *p SC_CLEANUP(sc_cleanup_string) = NULL; + g_assert_true(g_file_set_contents(fixture->self_cgroup, (char *)user_data, -1, NULL)); + p = sc_cgroup_v2_own_path_full(); + g_assert_null(p); +} + +static void _test_sc_cgroupv2_own_group_path_die_with_message(const char *msg) { + if (g_test_subprocess()) { + char *p = NULL; + p = sc_cgroup_v2_own_path_full(); + /* not reached */ + sc_cleanup_string(&p); + } + g_test_trap_subprocess(NULL, 0, 0); + g_test_trap_assert_failed(); + g_test_trap_assert_stderr(msg); +} + +static void test_sc_cgroupv2_own_group_path_die(cgroupv2_own_group_fixture *fixture, gconstpointer user_data) { + g_assert_true(g_file_set_contents(fixture->self_cgroup, (char *)user_data, -1, NULL)); + _test_sc_cgroupv2_own_group_path_die_with_message("unexpected content of group entry 0::\n"); +} + +static void test_sc_cgroupv2_own_group_path_no_file(cgroupv2_own_group_fixture *fixture, gconstpointer user_data) { + /* make sure that the file is removed if it exists */ + (void)g_remove(fixture->self_cgroup); + _test_sc_cgroupv2_own_group_path_die_with_message("cannot open *\n"); +} + +static void test_sc_cgroupv2_own_group_path_permission(cgroupv2_own_group_fixture *fixture, gconstpointer user_data) { + if (geteuid() == 0) { + g_test_skip("the test will not work when running as root"); + return; + } + int ret = g_chmod(fixture->self_cgroup, 0000); + g_assert_cmpint(ret, ==, 0); + _test_sc_cgroupv2_own_group_path_die_with_message("cannot open *: Permission denied\n"); +} + +static void __attribute__((constructor)) init(void) { + g_test_add("/cgroup/v2/own_path_full_newline", cgroupv2_own_group_fixture, + "0::/foo/bar/baz.slice/snap.foo.bar.1234-1234.scope\n", cgroupv2_own_group_set_up, + test_sc_cgroupv2_own_group_path_simple_happy_scope, cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_no_newline", cgroupv2_own_group_fixture, + "0::/foo/bar/baz.slice/snap.foo.bar.1234-1234.scope", cgroupv2_own_group_set_up, + test_sc_cgroupv2_own_group_path_simple_happy_scope, cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_firstline", cgroupv2_own_group_fixture, + "0::/foo/bar/baz.slice/snap.foo.bar.1234-1234.scope\n" + "0::/bad\n", + cgroupv2_own_group_set_up, test_sc_cgroupv2_own_group_path_simple_happy_scope, + cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_ignore_non_unified", cgroupv2_own_group_fixture, + "1::/ignored\n" + "0::/foo/bar/baz.slice/snap.foo.bar.1234-1234.scope\n", + cgroupv2_own_group_set_up, test_sc_cgroupv2_own_group_path_simple_happy_scope, + cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_service", cgroupv2_own_group_fixture, + "0::/system.slice/snap.foo.bar.service\n", cgroupv2_own_group_set_up, + test_sc_cgroupv2_own_group_path_simple_happy_service, cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_empty", cgroupv2_own_group_fixture, "", cgroupv2_own_group_set_up, + test_sc_cgroupv2_own_group_path_empty, cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_not_found", cgroupv2_own_group_fixture, + /* missing 0:: group */ + "1::/ignored\n" + "2::/foo/bar/baz.slice\n", + cgroupv2_own_group_set_up, test_sc_cgroupv2_own_group_path_empty, cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_die", cgroupv2_own_group_fixture, "0::", cgroupv2_own_group_set_up, + test_sc_cgroupv2_own_group_path_die, cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_no_file", cgroupv2_own_group_fixture, NULL, cgroupv2_own_group_set_up, + test_sc_cgroupv2_own_group_path_no_file, cgroupv2_own_group_tear_down); + g_test_add("/cgroup/v2/own_path_full_permission", cgroupv2_own_group_fixture, NULL, cgroupv2_own_group_set_up, + test_sc_cgroupv2_own_group_path_permission, cgroupv2_own_group_tear_down); + + g_test_add("/cgroup/v2/is_tracking_happy_scope", cgroupv2_is_tracking_fixture, NULL, cgroupv2_is_tracking_set_up, + test_sc_cgroupv2_is_tracking_happy_scope, cgroupv2_is_tracking_tear_down); + g_test_add("/cgroup/v2/is_tracking_happy_service", cgroupv2_is_tracking_fixture, NULL, cgroupv2_is_tracking_set_up, + test_sc_cgroupv2_is_tracking_happy_service, cgroupv2_is_tracking_tear_down); + g_test_add("/cgroup/v2/is_tracking_just_own", cgroupv2_is_tracking_fixture, NULL, cgroupv2_is_tracking_set_up, + test_sc_cgroupv2_is_tracking_just_own_group, cgroupv2_is_tracking_tear_down); + g_test_add("/cgroup/v2/is_tracking_only_other_snaps", cgroupv2_is_tracking_fixture, NULL, + cgroupv2_is_tracking_set_up, test_sc_cgroupv2_is_tracking_other_snaps, cgroupv2_is_tracking_tear_down); + g_test_add("/cgroup/v2/is_tracking_empty_groups", cgroupv2_is_tracking_fixture, NULL, cgroupv2_is_tracking_set_up, + test_sc_cgroupv2_is_tracking_no_dirs, cgroupv2_is_tracking_tear_down); + g_test_add("/cgroup/v2/is_tracking_bad_self_group", cgroupv2_is_tracking_fixture, NULL, cgroupv2_is_tracking_set_up, + test_sc_cgroupv2_is_tracking_bad_self_group, cgroupv2_is_tracking_tear_down); + g_test_add("/cgroup/v2/is_tracking_bad_dir_permissions", cgroupv2_is_tracking_fixture, NULL, + cgroupv2_is_tracking_set_up, test_sc_cgroupv2_is_tracking_dir_permissions, + cgroupv2_is_tracking_tear_down); + g_test_add("/cgroup/v2/is_tracking_bad_nesting", cgroupv2_is_tracking_fixture, NULL, cgroupv2_is_tracking_set_up, + test_sc_cgroupv2_is_tracking_bad_nesting, cgroupv2_is_tracking_tear_down); + g_test_add("/cgroup/v2/is_tracking_no_cgroup_root", cgroupv2_is_tracking_fixture, NULL, cgroupv2_is_tracking_set_up, + test_sc_cgroupv2_is_tracking_no_cgroup_root, cgroupv2_is_tracking_tear_down); +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/classic-test.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/classic-test.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/classic-test.c 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/classic-test.c 2023-03-23 08:10:58.000000000 +0000 @@ -35,7 +35,7 @@ const char *old = os_release; if (mocked != NULL) { os_release = "os-release.test"; - g_file_set_contents(os_release, mocked, -1, NULL); + g_assert_true(g_file_set_contents(os_release, mocked, -1, NULL)); } else { os_release = "os-release.missing"; } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cleanup-funcs-test.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cleanup-funcs-test.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cleanup-funcs-test.c 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/cleanup-funcs-test.c 2023-03-23 08:10:58.000000000 +0000 @@ -91,12 +91,12 @@ gint mock_fstab_fd = g_file_open_tmp("s-c-test-fstab-mock.XXXXXX", &mock_fstab, &err); g_assert_no_error(err); - g_close(mock_fstab_fd, &err); - g_assert_no_error(err); + g_assert_cmpint(mock_fstab_fd, >=, 0); + g_assert_true(g_close(mock_fstab_fd, NULL)); /* XXX: not strictly needed as the test only calls setmntent */ const char *mock_fstab_data = "/dev/foo / ext4 defaults 0 1"; - g_file_set_contents(mock_fstab, mock_fstab_data, -1, &err); - g_assert_no_error(err); + g_assert_true(g_file_set_contents + (mock_fstab, mock_fstab_data, -1, NULL)); f = setmntent(mock_fstab, "rt"); g_assert_nonnull(f); diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/device-cgroup-support.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/device-cgroup-support.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/device-cgroup-support.c 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/device-cgroup-support.c 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,720 @@ +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ +#include "config.h" + +#include +#include +#include +#include +#include +#include + +#include "cgroup-support.h" +#include "cleanup-funcs.h" +#include "snap.h" +#include "string-utils.h" +#include "utils.h" + +#ifdef ENABLE_BPF +#include "bpf-support.h" +#include "bpf/bpf-insn.h" +#endif +#include "device-cgroup-support.h" + +typedef struct sc_cgroup_fds { + int devices_allow_fd; + int devices_deny_fd; + int cgroup_procs_fd; +} sc_cgroup_fds; + +static sc_cgroup_fds sc_cgroup_fds_new(void) { + /* Note that -1 is the neutral value for a file descriptor. + * This is relevant as a cleanup handler for sc_cgroup_fds, + * closes all file descriptors that are not -1. */ + sc_cgroup_fds empty = {-1, -1, -1}; + return empty; +} + +struct sc_device_cgroup { + bool is_v2; + char *security_tag; + union { + struct { + sc_cgroup_fds fds; + } v1; + struct { + int cgroup_fd; + int devmap_fd; + char *tag; + struct rlimit old_limit; + } v2; + }; +}; + +__attribute__((format(printf, 2, 3))) static void sc_dprintf(int fd, const char *format, ...); + +static int sc_udev_open_cgroup_v1(const char *security_tag, int flags, sc_cgroup_fds *fds); +static void sc_cleanup_cgroup_fds(sc_cgroup_fds *fds); + +static int _sc_cgroup_v1_init(sc_device_cgroup *self, int flags) { + self->v1.fds = sc_cgroup_fds_new(); + + /* initialize to something sane */ + if (sc_udev_open_cgroup_v1(self->security_tag, flags, &self->v1.fds) < 0) { + if ((flags & SC_DEVICE_CGROUP_FROM_EXISTING) != 0) { + return -1; + } + die("cannot prepare cgroup v1 device hierarchy"); + } + /* Deny device access by default. + * + * Write 'a' to devices.deny to remove all existing devices that were added + * in previous launcher invocations, then add the static and assigned + * devices. This ensures that at application launch the cgroup only has + * what is currently assigned. */ + sc_dprintf(self->v1.fds.devices_deny_fd, "a"); + return 0; +} + +static void _sc_cgroup_v1_close(sc_device_cgroup *self) { sc_cleanup_cgroup_fds(&self->v1.fds); } + +static void _sc_cgroup_v1_action(int fd, int kind, int major, int minor) { + if ((uint32_t)minor != SC_DEVICE_MINOR_ANY) { + sc_dprintf(fd, "%c %u:%u rwm\n", (kind == S_IFCHR) ? 'c' : 'b', major, minor); + } else { + /* use a mask to allow/deny all minor devices for that major */ + sc_dprintf(fd, "%c %u:* rwm\n", (kind == S_IFCHR) ? 'c' : 'b', major); + } +} + +static void _sc_cgroup_v1_allow(sc_device_cgroup *self, int kind, int major, int minor) { + _sc_cgroup_v1_action(self->v1.fds.devices_allow_fd, kind, major, minor); +} + +static void _sc_cgroup_v1_deny(sc_device_cgroup *self, int kind, int major, int minor) { + _sc_cgroup_v1_action(self->v1.fds.devices_deny_fd, kind, major, minor); +} + +static void _sc_cgroup_v1_attach_pid(sc_device_cgroup *self, pid_t pid) { + sc_dprintf(self->v1.fds.cgroup_procs_fd, "%i\n", pid); +} + +/** + * sc_cgroup_v2_device_key is the key in the map holding allowed devices + */ +struct sc_cgroup_v2_device_key { + uint8_t type; + uint32_t major; + uint32_t minor; +} __attribute__((packed)); +typedef struct sc_cgroup_v2_device_key sc_cgroup_v2_device_key; + +/** + * sc_cgroup_v2_device_value holds the value stored in the map + * + * Note that this type is just a helper, the map cannot be used as a set with 0 + * sized value so we always store something in it (specifically value 1) in the + * map. + */ +typedef uint8_t sc_cgroup_v2_device_value; + +static void _sc_cgroup_v2_attach_pid(sc_device_cgroup *self, pid_t pid) { + /* nothing to do here, the device controller is attached to the cgroup + * already, and we are part of it */ +} + +#ifdef ENABLE_BPF +static int load_devcgroup_prog(int map_fd) { + /* Basic rules about registers: + * r0 - return value of built in functions and exit code of the program + * r1-r5 - respective arguments to built in functions, clobbered by calls + * r6-r9 - general purpose, preserved by callees + * r10 - read only, stack pointer + * Stack is 512 bytes. + * + * The function declaration implementing a device cgroup program looks like + * this: + * int program(struct bpf_cgroup_dev_ctx * ctx) + * where *ctx is passed in r1, while the result goes to r0 + */ + + /* just a placeholder for map value where the value is 1 byte, but + * effectively ignored at this time. Ideally it should be possible to use + * the map as a set with 0 sized key, but this is currently unsupported by + * the kernel (as of 5.13) */ + sc_cgroup_v2_device_value map_value __attribute__((unused)); + /* we need to place the key structure on the stack and pull a nasty hack + * here, the structure is packed and its size isn't aligned to multiples of + * 4; if we place it on a stack at an address aligned to 4 bytes, the + * starting offsets of major and minor would be unaligned; however, the + * first field of the structure is 1 byte, so we can put the structure at 4 + * byte aligned address -1 and thus major and minor end up aligned without + * too much hassle; since we are doing the stack management ourselves have + * the key structure start at the offset that meets the alignment properties + * described above and such that the whole structure fits on the stack (even + * with some spare room) */ + size_t key_start = 17; + struct bpf_insn prog[] = { + /* r1 holds pointer to bpf_cgroup_dev_ctx */ + /* initialize r0 */ + BPF_MOV64_IMM(BPF_REG_0, 0), /* r0 = 0 */ + /* make some place on the stack for the key */ + BPF_MOV64_REG(BPF_REG_6, BPF_REG_10), /* r6 = r10 (sp) */ + /* r6 = where the key starts on the stack */ + BPF_ALU64_IMM(BPF_ADD, BPF_REG_6, -key_start), /* r6 = sp + (-key start offset) */ + /* copy major to our key */ + BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, + offsetof(struct bpf_cgroup_dev_ctx, major)), /* r2 = *(u32)(r1->major) */ + BPF_STX_MEM(BPF_W, BPF_REG_6, BPF_REG_2, + offsetof(struct sc_cgroup_v2_device_key, major)), /* *(r6 + offsetof(major)) = r2 */ + /* copy minor to our key */ + BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, + offsetof(struct bpf_cgroup_dev_ctx, minor)), /* r2 = *(u32)(r1->minor) */ + BPF_STX_MEM(BPF_W, BPF_REG_6, BPF_REG_2, + offsetof(struct sc_cgroup_v2_device_key, minor)), /* *(r6 + offsetof(minor)) = r2 */ + /* copy device access_type to r2 */ + BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, + offsetof(struct bpf_cgroup_dev_ctx, access_type)), /* r2 = *(u32*)(r1->access_type) */ + /* access_type is encoded as (BPF_DEVCG_ACC_* << 16) | BPF_DEVCG_DEV_*, + * but we only care about type */ + BPF_ALU32_IMM(BPF_AND, BPF_REG_2, 0xffff), /* r2 = r2 & 0xffff */ + /* is it a block device? */ + BPF_JMP_IMM(BPF_JNE, BPF_REG_2, BPF_DEVCG_DEV_BLOCK, 2), /* if (r2 != BPF_DEVCG_DEV_BLOCK) goto pc + 2 */ + BPF_ST_MEM(BPF_B, BPF_REG_6, offsetof(struct sc_cgroup_v2_device_key, type), + 'b'), /* *(uint8*)(r6->type) = 'b' */ + BPF_JMP_A(5), + BPF_JMP_IMM(BPF_JNE, BPF_REG_2, BPF_DEVCG_DEV_CHAR, 2), /* if (r2 != BPF_DEVCG_DEV_CHAR) goto pc + 2 */ + BPF_ST_MEM(BPF_B, BPF_REG_6, offsetof(struct sc_cgroup_v2_device_key, type), + 'c'), /* *(uint8*)(r6->type) = 'c' */ + BPF_JMP_A(2), + /* unknown device type */ + BPF_MOV64_IMM(BPF_REG_0, 0), /* r0 = 0 */ + BPF_EXIT_INSN(), + /* back on happy path, prepare arguments for map lookup */ + BPF_LD_MAP_FD(BPF_REG_1, map_fd), + BPF_MOV64_REG(BPF_REG_2, BPF_REG_6), /* r2 = (struct key *) r6, */ + BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), /* r0 = bpf_map_lookup_elem(, + &key) */ + BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 1), /* if (value_ptr == 0) goto pc + 1 */ + /* we found an exact match */ + BPF_JMP_A(5), /* else goto pc + 5 */ + /* maybe the minor number is using 0xffffffff (any) mask */ + BPF_ST_MEM(BPF_W, BPF_REG_6, offsetof(struct sc_cgroup_v2_device_key, minor), UINT32_MAX), + BPF_LD_MAP_FD(BPF_REG_1, map_fd), + BPF_MOV64_REG(BPF_REG_2, BPF_REG_6), /* r2 = (struct key *) r6, */ + BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), /* r0 = bpf_map_lookup_elem(, + &key) */ + BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2), /* if (value_ptr == 0) goto pc + 2 */ + /* we found a match with any minor number for that type|major */ + BPF_MOV64_IMM(BPF_REG_0, 1), /* r0 = 1 */ + BPF_JMP_A(1), + BPF_MOV64_IMM(BPF_REG_0, 0), /* r0 = 0 */ + BPF_EXIT_INSN(), + }; + + char log_buf[4096] = {0}; + + int prog_fd = + bpf_load_prog(BPF_PROG_TYPE_CGROUP_DEVICE, prog, sizeof(prog) / sizeof(prog[0]), log_buf, sizeof(log_buf)); + if (prog_fd < 0) { + die("cannot load program:\n%s\n", log_buf); + } + return prog_fd; +} + +static void _sc_cleanup_v2_device_key(sc_cgroup_v2_device_key **keyptr) { + if (keyptr == NULL || *keyptr == NULL) { + return; + } + free(*keyptr); + *keyptr = NULL; +} + +static void _sc_cgroup_v2_set_memlock_limit(struct rlimit limit) { + /* we may be setting the limit over the current max, which requires root + * privileges */ + sc_identity old = sc_set_effective_identity(sc_root_group_identity()); + if (setrlimit(RLIMIT_MEMLOCK, &limit) < 0) { + die("cannot set memlock limit to %llu:%llu", (long long unsigned int)limit.rlim_cur, + (long long unsigned int)limit.rlim_max); + } + (void)sc_set_effective_identity(old); +} + +// _sc_cgroup_v2_adjust_memlock_limit updates the memlock limit which used to be +// consulted by pre 5.11 kernels when creating BPF maps or loading BPF programs. +// It has been observed that some systems (eg. Debian using 5.10 kernel) have +// the default limit set to 64k, which combined with an older way of accounting +// of memory use by BPF objects, renders snap-confine unable to create the BPF +// map. The situation is made worse by the fact that there is no right value +// here, for example older systemd set the limit to 64MB while newer versions +// set it even higher). Returns the old limit setting. +static struct rlimit _sc_cgroup_v2_adjust_memlock_limit(void) { + struct rlimit old_limit = {0}; + + if (getrlimit(RLIMIT_MEMLOCK, &old_limit) < 0) { + die("cannot obtain the current memlock limit"); + } + /* this should be more than enough for creating the map and loading the + * filtering program */ + const rlim_t min_memlock_limit = 512 * 1024; + if (old_limit.rlim_max >= min_memlock_limit) { + return old_limit; + } + debug("adjusting memlock limit to %llu", (long long unsigned int)min_memlock_limit); + struct rlimit limit = { + .rlim_cur = min_memlock_limit, + .rlim_max = min_memlock_limit, + }; + _sc_cgroup_v2_set_memlock_limit(limit); + return old_limit; +} + +static bool _sc_is_snap_cgroup(const char *group) { + /* make a copy as basename may modify its input */ + char copy[PATH_MAX] = {0}; + strncpy(copy, group, sizeof(copy) - 1); + char *leaf = basename(copy); + if (!sc_startswith(leaf, "snap.")) { + return false; + } + if (!sc_endswith(leaf, ".service") && !sc_endswith(leaf, ".scope")) { + return false; + } + return true; +} + +static int _sc_cgroup_v2_init_bpf(sc_device_cgroup *self, int flags) { + self->v2.devmap_fd = -1; + self->v2.cgroup_fd = -1; + + char *own_group SC_CLEANUP(sc_cleanup_string) = sc_cgroup_v2_own_path_full(); + if (own_group == NULL) { + die("cannot obtain own group path"); + } + debug("process in cgroup %s", own_group); + if (!_sc_is_snap_cgroup(own_group)) { + /* we cannot proceed to install a device filtering program when the + * process is not in a snap specific cgroup, as we would effectively + * lock down the group that can be shared with other processes or even + * the whole desktop session */ + die("%s is not a snap cgroup", own_group); + } + + /* fix the memlock limit if needed, this affects creating maps */ + self->v2.old_limit = _sc_cgroup_v2_adjust_memlock_limit(); + + const bool from_existing = (flags & SC_DEVICE_CGROUP_FROM_EXISTING) != 0; + + char own_group_full[PATH_MAX] = {0}; + sc_must_snprintf(own_group_full, sizeof(own_group_full), "/sys/fs/cgroup/%s", own_group); + int cgroup_fd = open(own_group_full, O_PATH | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (cgroup_fd < 0) { + die("cannot open own cgroup directory %s", own_group_full); + } + debug("cgroup %s opened at %d", own_group_full, cgroup_fd); + + self->v2.tag = sc_strdup(self->security_tag); + /* bpffs is unhappy about dots in the name, replace all with underscores */ + for (char *c = strchr(self->v2.tag, '.'); c != NULL; c = strchr(c, '.')) { + *c = '_'; + } + + char path[PATH_MAX] = {0}; + sc_must_snprintf(path, sizeof path, "/sys/fs/bpf/snap/%s", self->v2.tag); + + /* TODO: open("/sys/fs/bpf") and then mkdirat? */ + /* create /sys/fs/bpf/snap as root */ + sc_identity old = sc_set_effective_identity(sc_root_group_identity()); + if (mkdir("/sys/fs/bpf/snap", 0700) < 0) { + if (errno != EEXIST) { + die("cannot create /sys/fs/bpf/snap directory"); + } + } + /* and obtain a file descriptor to the map, also as root */ + int devmap_fd = bpf_get_by_path(path); + (void)sc_set_effective_identity(old); + /* XXX: this should be more than enough keys */ + const size_t max_entries = 500; + if (devmap_fd < 0) { + if (errno != ENOENT) { + die("cannot get existing device map"); + } + if (from_existing) { + /* there is no map, and we haven't been asked to setup a new cgroup */ + return -1; + } + debug("device map not present yet"); + /* map not created and pinned yet */ + const size_t value_size = 1; + /* create the map as root, also pinning the map creates a file entry + * under /sys/bpf/snap, make sure it's owned by root too */ + (void)sc_set_effective_identity(sc_root_group_identity()); + /* kernels used to do account of BPF memory using rlimit memlock pool, + * thus on older kernels (seen on 5.10), the map effectively locks 11 + * pages (45k) of memlock memory, while on newer kernels (5.11+) only 2 (8k) */ + devmap_fd = bpf_create_map(BPF_MAP_TYPE_HASH, sizeof(struct sc_cgroup_v2_device_key), value_size, max_entries); + if (devmap_fd < 0) { + die("cannot create bpf map"); + } + debug("got bpf map at fd: %d", devmap_fd); + /* the map can only be referenced by a fd like object which is valid + * here and referenced by the BPF program that we'll load; by pinning + * the map to a well known path, it is possible to obtain a reference to + * it from another process, which is used by snap-device-helper to + * dynamically update device access permissions; the downside is a tiny + * bit of kernel memory still in use as, even once all BPF programs + * referencing the map go away with their respective cgroups, the map + * will stay around as it is still referenced by the path */ + if (bpf_pin_to_path(devmap_fd, path) < 0) { + /* we checked that the map did not exist, so fail on EEXIST too */ + die("cannot pin map to %s", path); + } + (void)sc_set_effective_identity(old); + } else if (!from_existing) { + /* the devices access map exists, and we have been asked to setup a + * cgroup, so clear the old map first so it was like it never existed */ + + debug("found existing device map"); + /* the v1 implementation blocks all devices by default and then adds + * each assigned one individually, however for v2 there's no way to drop + * all the contents of the map, so we need to find out what keys are + * there in the map */ + + /* first collect all keys in the map */ + sc_cgroup_v2_device_key *existing_keys SC_CLEANUP(_sc_cleanup_v2_device_key) = + calloc(max_entries, sizeof(sc_cgroup_v2_device_key)); + /* 'current' key is zeroed, such that no entry can match it and thus + * we'll iterate over the keys from the beginning */ + sc_cgroup_v2_device_key key = {0}; + size_t existing_count = 0; + while (true) { + sc_cgroup_v2_device_key next = {0}; + if (existing_count >= max_entries) { + die("too many elements in the map"); + } + if (existing_count > 0) { + /* grab the previous key */ + key = existing_keys[existing_count - 1]; + } + int ret = bpf_map_get_next_key(devmap_fd, &key, &next); + if (ret == -1) { + if (errno != ENOENT) { + die("cannot lookup existing device map keys"); + } + /* we are done */ + break; + } + existing_keys[existing_count] = next; + existing_count++; + } + debug("found %zu existing entries in devices map", existing_count); + if (existing_count > 0) { +#if 0 + /* XXX: we should be doing a batch delete of elements, however: + * - on Arch with 5.13 kernel I'm getting EINVAL + * - the linux/bpf.h header present during build on 16.04 does not + * support batch operations + */ + if (bpf_map_delete_batch(devmap_fd, existing_keys, existing_count) < 0) { + die("cannot dump all elements from devices map"); + } +#endif + for (size_t i = 0; i < existing_count; i++) { + sc_cgroup_v2_device_key key = existing_keys[i]; + debug("delete key for %c %d:%d", key.type, key.major, key.minor); + if (bpf_map_delete_elem(devmap_fd, &key) < 0) { + die("cannot delete device map entry for %c %d:%d", key.type, key.major, key.minor); + } + } + } + } + + if (!from_existing) { + /* load and attach the BPF program as root */ + (void)sc_set_effective_identity(sc_root_group_identity()); + int prog_fd = load_devcgroup_prog(devmap_fd); + int attach = bpf_prog_attach(BPF_CGROUP_DEVICE, cgroup_fd, prog_fd); + if (attach < 0) { + die("cannot attach cgroup program"); + } + (void)sc_set_effective_identity(old); + } + + self->v2.devmap_fd = devmap_fd; + self->v2.cgroup_fd = cgroup_fd; + + return 0; +} + +static void _sc_cgroup_v2_close_bpf(sc_device_cgroup *self) { + /* restore the old limit */ + _sc_cgroup_v2_set_memlock_limit(self->v2.old_limit); + + sc_cleanup_string(&self->v2.tag); + /* the map is pinned to a per-snap-application file and referenced by the + * program */ + sc_cleanup_close(&self->v2.devmap_fd); + sc_cleanup_close(&self->v2.cgroup_fd); +} + +static void _sc_cgroup_v2_allow_bpf(sc_device_cgroup *self, int kind, int major, int minor) { + struct sc_cgroup_v2_device_key key = { + .major = major, + .minor = minor, + .type = (kind == S_IFCHR) ? 'c' : 'b', + }; + sc_cgroup_v2_device_value value = 1; + debug("v2 allow %c %u:%u", (char)key.type, key.major, key.minor); + if (bpf_update_map(self->v2.devmap_fd, &key, &value) < 0) { + die("cannot update device map for key %c %u:%u", key.type, key.major, key.minor); + } +} + +static void _sc_cgroup_v2_deny_bpf(sc_device_cgroup *self, int kind, int major, int minor) { + struct sc_cgroup_v2_device_key key = { + .major = major, + .minor = minor, + .type = (kind == S_IFCHR) ? 'c' : 'b', + }; + debug("v2 deny %c %u:%u", (char)key.type, key.major, key.minor); + if (bpf_map_delete_elem(self->v2.devmap_fd, &key) < 0 && errno != ENOENT) { + die("cannot delete device map entry for key %c %u:%u", key.type, key.major, key.minor); + } +} +#endif /* ENABLE_BPF */ + +static void _sc_cgroup_v2_close(sc_device_cgroup *self) { +#ifdef ENABLE_BPF + _sc_cgroup_v2_close_bpf(self); +#endif +} + +static void _sc_cgroup_v2_allow(sc_device_cgroup *self, int kind, int major, int minor) { +#ifdef ENABLE_BPF + _sc_cgroup_v2_allow_bpf(self, kind, major, minor); +#else + die("device cgroup v2 is not enabled"); +#endif +} + +static void _sc_cgroup_v2_deny(sc_device_cgroup *self, int kind, int major, int minor) { +#ifdef ENABLE_BPF + _sc_cgroup_v2_deny_bpf(self, kind, major, minor); +#else + die("device cgroup v2 is not enabled"); +#endif +} + +static int _sc_cgroup_v2_init(sc_device_cgroup *self, int flags) { +#ifdef ENABLE_BPF + return _sc_cgroup_v2_init_bpf(self, flags); +#else + if ((flags & SC_DEVICE_CGROUP_FROM_EXISTING) != 0) { + errno = ENOSYS; + return -1; + } + die("device cgroup v2 is not enabled"); + return -1; +#endif +} + +static void sc_device_cgroup_close(sc_device_cgroup *self); + +sc_device_cgroup *sc_device_cgroup_new(const char *security_tag, int flags) { + sc_device_cgroup *self = calloc(1, sizeof(sc_device_cgroup)); + if (self == NULL) { + die("cannot allocate device cgroup wrapper"); + } + self->is_v2 = sc_cgroup_is_v2(); + self->security_tag = sc_strdup(security_tag); + + int ret = 0; + if (self->is_v2) { + ret = _sc_cgroup_v2_init(self, flags); + } else { + ret = _sc_cgroup_v1_init(self, flags); + } + + if (ret < 0) { + sc_device_cgroup_close(self); + return NULL; + } + return self; +} + +static void sc_device_cgroup_close(sc_device_cgroup *self) { + if (self->is_v2) { + _sc_cgroup_v2_close(self); + } else { + _sc_cgroup_v1_close(self); + } + sc_cleanup_string(&self->security_tag); + free(self); +} + +void sc_device_cgroup_cleanup(sc_device_cgroup **self) { + if (*self == NULL) { + return; + } + sc_device_cgroup_close(*self); + *self = NULL; +} + +int sc_device_cgroup_allow(sc_device_cgroup *self, int kind, int major, int minor) { + if (kind != S_IFCHR && kind != S_IFBLK) { + die("unsupported device kind 0x%04x", kind); + } + if (self->is_v2) { + _sc_cgroup_v2_allow(self, kind, major, minor); + } else { + _sc_cgroup_v1_allow(self, kind, major, minor); + } + return 0; +} + +int sc_device_cgroup_deny(sc_device_cgroup *self, int kind, int major, int minor) { + if (kind != S_IFCHR && kind != S_IFBLK) { + die("unsupported device kind 0x%04x", kind); + } + if (self->is_v2) { + _sc_cgroup_v2_deny(self, kind, major, minor); + } else { + _sc_cgroup_v1_deny(self, kind, major, minor); + } + return 0; +} + +int sc_device_cgroup_attach_pid(sc_device_cgroup *self, pid_t pid) { + if (self->is_v2) { + _sc_cgroup_v2_attach_pid(self, pid); + } else { + _sc_cgroup_v1_attach_pid(self, pid); + } + return 0; +} + +static void sc_dprintf(int fd, const char *format, ...) { + va_list ap1; + va_list ap2; + int n_expected, n_actual; + + va_start(ap1, format); + va_copy(ap2, ap1); + n_expected = vsnprintf(NULL, 0, format, ap2); + n_actual = vdprintf(fd, format, ap1); + if (n_actual == -1 || n_expected != n_actual) { + die("cannot write to fd %d", fd); + } + va_end(ap2); + va_end(ap1); +} + +static int sc_udev_open_cgroup_v1(const char *security_tag, int flags, sc_cgroup_fds *fds) { + /* Open /sys/fs/cgroup */ + const char *cgroup_path = "/sys/fs/cgroup"; + int SC_CLEANUP(sc_cleanup_close) cgroup_fd = -1; + cgroup_fd = open(cgroup_path, O_PATH | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (cgroup_fd < 0) { + die("cannot open %s", cgroup_path); + } + + const bool from_existing = (flags & SC_DEVICE_CGROUP_FROM_EXISTING) != 0; + /* Open devices relative to /sys/fs/cgroup */ + const char *devices_relpath = "devices"; + int SC_CLEANUP(sc_cleanup_close) devices_fd = -1; + devices_fd = openat(cgroup_fd, devices_relpath, O_PATH | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (devices_fd < 0) { + die("cannot open %s/%s", cgroup_path, devices_relpath); + } + + const char *security_tag_relpath = security_tag; + if (!from_existing) { + /* Open snap.$SNAP_NAME.$APP_NAME relative to /sys/fs/cgroup/devices, + * creating the directory if necessary. Note that we always chown the + * resulting directory to root:root. */ + sc_identity old = sc_set_effective_identity(sc_root_group_identity()); + if (mkdirat(devices_fd, security_tag_relpath, 0755) < 0) { + if (errno != EEXIST) { + die("cannot create directory %s/%s/%s", cgroup_path, devices_relpath, security_tag_relpath); + } + } + (void)sc_set_effective_identity(old); + } + + int SC_CLEANUP(sc_cleanup_close) security_tag_fd = -1; + security_tag_fd = openat(devices_fd, security_tag_relpath, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW); + if (security_tag_fd < 0) { + if (from_existing && errno == ENOENT) { + return -1; + } + die("cannot open %s/%s/%s", cgroup_path, devices_relpath, security_tag_relpath); + } + + /* Open devices.allow relative to /sys/fs/cgroup/devices/snap.$SNAP_NAME.$APP_NAME */ + const char *devices_allow_relpath = "devices.allow"; + int SC_CLEANUP(sc_cleanup_close) devices_allow_fd = -1; + devices_allow_fd = openat(security_tag_fd, devices_allow_relpath, O_WRONLY | O_CLOEXEC | O_NOFOLLOW); + if (devices_allow_fd < 0) { + if (from_existing && errno == ENOENT) { + return -1; + } + die("cannot open %s/%s/%s/%s", cgroup_path, devices_relpath, security_tag_relpath, devices_allow_relpath); + } + + /* Open devices.deny relative to /sys/fs/cgroup/devices/snap.$SNAP_NAME.$APP_NAME */ + const char *devices_deny_relpath = "devices.deny"; + int SC_CLEANUP(sc_cleanup_close) devices_deny_fd = -1; + devices_deny_fd = openat(security_tag_fd, devices_deny_relpath, O_WRONLY | O_CLOEXEC | O_NOFOLLOW); + if (devices_deny_fd < 0) { + if (from_existing && errno == ENOENT) { + return -1; + } + die("cannot open %s/%s/%s/%s", cgroup_path, devices_relpath, security_tag_relpath, devices_deny_relpath); + } + + /* Open cgroup.procs relative to /sys/fs/cgroup/devices/snap.$SNAP_NAME.$APP_NAME */ + const char *cgroup_procs_relpath = "cgroup.procs"; + int SC_CLEANUP(sc_cleanup_close) cgroup_procs_fd = -1; + cgroup_procs_fd = openat(security_tag_fd, cgroup_procs_relpath, O_WRONLY | O_CLOEXEC | O_NOFOLLOW); + if (cgroup_procs_fd < 0) { + if (from_existing && errno == ENOENT) { + return -1; + } + die("cannot open %s/%s/%s/%s", cgroup_path, devices_relpath, security_tag_relpath, cgroup_procs_relpath); + } + + /* Everything worked so pack the result and "move" the descriptors over so + * that they are not closed by the cleanup functions associated with the + * individual variables. */ + fds->devices_allow_fd = devices_allow_fd; + fds->devices_deny_fd = devices_deny_fd; + fds->cgroup_procs_fd = cgroup_procs_fd; + /* Reset the locals so that they are not closed by the cleanup handlers. */ + devices_allow_fd = -1; + devices_deny_fd = -1; + cgroup_procs_fd = -1; + return 0; +} + +static void sc_cleanup_cgroup_fds(sc_cgroup_fds *fds) { + if (fds != NULL) { + sc_cleanup_close(&fds->devices_allow_fd); + sc_cleanup_close(&fds->devices_deny_fd); + sc_cleanup_close(&fds->cgroup_procs_fd); + } +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/device-cgroup-support.h ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/device-cgroup-support.h --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/device-cgroup-support.h 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/device-cgroup-support.h 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +#ifndef SNAP_CONFINE_DEVICE_CGROUP_SUPPORT_H +#define SNAP_CONFINE_DEVICE_CGROUP_SUPPORT_H + +#include +#include + +struct sc_device_cgroup; +typedef struct sc_device_cgroup sc_device_cgroup; + +enum { + /* when creating a device cgroup wrapped, do not set up a new cgroup but + * rather use an existing one */ + SC_DEVICE_CGROUP_FROM_EXISTING = 1, +}; + +/** + * sc_device_cgroup_new returns a new cgroup device wrapper that is suitable for + * the current system. Flags can contain SC_DEVICE_CGROUP_FROM_EXISTING in which + * case an existing cgroup will be used, and a -1 return value with errno set to + * ENOENT indicates that the group was not found. Otherwise, a new device cgroup + * for a given tag will be set up. + */ +sc_device_cgroup* sc_device_cgroup_new(const char* security_tag, int flags); +/** + * sc_device_cgroup_cleanup disposes of the cgroup wrapper and is suitable for + * use with SC_CLEANUP + */ +void sc_device_cgroup_cleanup(sc_device_cgroup** self); + +/** + * SC_DEVICE_MINOR_ANY is used to indicate any minor device. + */ +static const uint32_t SC_DEVICE_MINOR_ANY = UINT32_MAX; + +/** + * sc_device_cgroup_allow sets up the cgroup to allow access to a given device + * or a set of devices if SC_MINOR_ANY is passed as the minor number. The kind + * must be one of S_IFCHR, S_IFBLK. + */ +int sc_device_cgroup_allow(sc_device_cgroup* self, int kind, int major, int minor); + +/** + * sc_device_cgroup_deny sets up the cgroup to deny access to a given device or + * a set of devices if SC_MINOR_ANY is passed as the minor number. The kind must + * be one of S_IFCHR, S_IFBLK. + */ +int sc_device_cgroup_deny(sc_device_cgroup* self, int kind, int major, int minor); + +/** + * sc_device_cgroup_attach_pid attaches given process ID to the associated + * cgroup. + */ +int sc_device_cgroup_attach_pid(sc_device_cgroup* self, pid_t pid); + +#endif /* SNAP_CONFINE_DEVICE_CGROUP_SUPPORT_H */ diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/feature-test.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/feature-test.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/feature-test.c 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/feature-test.c 2023-03-23 08:10:58.000000000 +0000 @@ -54,14 +54,14 @@ char subd[PATH_MAX]; sc_must_snprintf(subd, sizeof subd, "%s/absent", d); sc_mock_feature_flag_dir(subd); - g_assert(!sc_feature_enabled(SC_FEATURE_PER_USER_MOUNT_NAMESPACE)); + g_assert_false(sc_feature_enabled(SC_FEATURE_PER_USER_MOUNT_NAMESPACE)); } static void test_feature_enabled__missing_file(void) { const char *d = sc_testdir(); sc_mock_feature_flag_dir(d); - g_assert(!sc_feature_enabled(SC_FEATURE_PER_USER_MOUNT_NAMESPACE)); + g_assert_false(sc_feature_enabled(SC_FEATURE_PER_USER_MOUNT_NAMESPACE)); } static void test_feature_enabled__present_file(void) @@ -70,9 +70,9 @@ sc_mock_feature_flag_dir(d); char pname[PATH_MAX]; sc_must_snprintf(pname, sizeof pname, "%s/per-user-mount-namespace", d); - g_file_set_contents(pname, "", -1, NULL); + g_assert_true(g_file_set_contents(pname, "", -1, NULL)); - g_assert(sc_feature_enabled(SC_FEATURE_PER_USER_MOUNT_NAMESPACE)); + g_assert_true(sc_feature_enabled(SC_FEATURE_PER_USER_MOUNT_NAMESPACE)); } static void test_feature_parallel_instances(void) @@ -80,13 +80,13 @@ const char *d = sc_testdir(); sc_mock_feature_flag_dir(d); - g_assert(!sc_feature_enabled(SC_FEATURE_PARALLEL_INSTANCES)); + g_assert_false(sc_feature_enabled(SC_FEATURE_PARALLEL_INSTANCES)); char pname[PATH_MAX]; sc_must_snprintf(pname, sizeof pname, "%s/parallel-instances", d); - g_file_set_contents(pname, "", -1, NULL); + g_assert_true(g_file_set_contents(pname, "", -1, NULL)); - g_assert(sc_feature_enabled(SC_FEATURE_PARALLEL_INSTANCES)); + g_assert_true(sc_feature_enabled(SC_FEATURE_PARALLEL_INSTANCES)); } static void test_feature_hidden_snap_folder(void) @@ -94,13 +94,13 @@ const char *d = sc_testdir(); sc_mock_feature_flag_dir(d); - g_assert(!sc_feature_enabled(SC_FEATURE_HIDDEN_SNAP_FOLDER)); + g_assert_false(sc_feature_enabled(SC_FEATURE_HIDDEN_SNAP_FOLDER)); char pname[PATH_MAX]; sc_must_snprintf(pname, sizeof pname, "%s/hidden-snap-folder", d); - g_file_set_contents(pname, "", -1, NULL); + g_assert_true(g_file_set_contents(pname, "", -1, NULL)); - g_assert(sc_feature_enabled(SC_FEATURE_HIDDEN_SNAP_FOLDER)); + g_assert_true(sc_feature_enabled(SC_FEATURE_HIDDEN_SNAP_FOLDER)); } static void __attribute__((constructor)) init(void) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/mount-opt-test.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/mount-opt-test.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/mount-opt-test.c 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/mount-opt-test.c 2023-03-23 08:10:58.000000000 +0000 @@ -216,7 +216,8 @@ if (g_test_subprocess()) { sc_break("mount", broken_mount); if (GPOINTER_TO_INT(snap_debug) == 1) { - g_setenv("SNAP_CONFINE_DEBUG", "1", true); + g_assert_true(g_setenv + ("SNAP_CONFINE_DEBUG", "1", true)); } sc_do_mount("/foo", "/bar", "ext4", MS_RDONLY, NULL); @@ -251,7 +252,8 @@ if (g_test_subprocess()) { sc_break("umount", broken_umount); if (GPOINTER_TO_INT(snap_debug) == 1) { - g_setenv("SNAP_CONFINE_DEBUG", "1", true); + g_assert_true(g_setenv + ("SNAP_CONFINE_DEBUG", "1", true)); } sc_do_umount("/foo", MNT_DETACH); @@ -294,7 +296,8 @@ if (g_test_subprocess()) { sc_break("mount", broken_mount); if (GPOINTER_TO_INT(snap_debug) == 1) { - g_setenv("SNAP_CONFINE_DEBUG", "1", true); + g_assert_true(g_setenv + ("SNAP_CONFINE_DEBUG", "1", true)); } (void)sc_do_optional_mount("/foo", "/bar", "ext4", MS_RDONLY, NULL); diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/test-utils.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/test-utils.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/test-utils.c 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/test-utils.c 2023-03-23 08:10:58.000000000 +0000 @@ -23,6 +23,11 @@ #include +#if !GLIB_CHECK_VERSION(2, 69, 0) +// g_spawn_check_exit_status is considered deprecated since 2.69 +#define g_spawn_check_wait_status(x, y) (g_spawn_check_exit_status (x, y)) +#endif + void rm_rf_tmp(const char *dir) { // Sanity check, don't remove anything that's not in the temporary @@ -60,7 +65,7 @@ (working_directory, argv, envp, flags, child_setup, user_data, standard_output, standard_error, &exit_status, &error)); - g_assert_true(g_spawn_check_exit_status(exit_status, NULL)); + g_assert_true(g_spawn_check_wait_status(exit_status, NULL)); if (error != NULL) { g_test_message("cannot remove temporary directory: %s\n", error->message); diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/utils.c ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/utils.c --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/utils.c 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/utils.c 2023-03-23 08:10:58.000000000 +0000 @@ -86,7 +86,7 @@ * printed to stderr. If the environment variable is unset, set value to the * default_value as if the environment variable was set to default_value. **/ -static bool getenv_bool(const char *name, bool default_value) +bool getenv_bool(const char *name, bool default_value) { const char *str_value = getenv(name); bool value = default_value; diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/utils.h ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/utils.h --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/utils.h 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/libsnap-confine-private/utils.h 2023-03-23 08:10:58.000000000 +0000 @@ -28,6 +28,16 @@ void debug(const char *fmt, ...); /** + * Get an environment variable and convert it to a boolean. + * + * Supported values are those of parse_bool(), namely "yes", "no" as well as "1" + * and "0". All other values are treated as false and a diagnostic message is + * printed to stderr. If the environment variable is unset, set value to the + * default_value as if the environment variable was set to default_value. + **/ +bool getenv_bool(const char *name, bool default_value); + +/** * Return true if debugging is enabled. * * This can used to avoid costly computation that is only useful for debugging. diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/Makefile.am ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/Makefile.am --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/Makefile.am 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/Makefile.am 2023-03-23 08:10:58.000000000 +0000 @@ -15,9 +15,14 @@ CHECK_CFLAGS += -Werror endif +if USE_INTERNAL_BPF_HEADERS +VENDOR_BPF_HEADERS_CFLAGS = -I$(srcdir)/libsnap-confine-private/bpf/vendor +endif + subdirs = \ libsnap-confine-private \ snap-confine \ + snap-device-helper \ snap-discard-ns \ snap-gdb-shim \ snap-update-ns \ @@ -45,18 +50,24 @@ .PHONY: check-unit-tests if WITH_UNIT_TESTS -check-unit-tests: snap-confine/unit-tests system-shutdown/unit-tests libsnap-confine-private/unit-tests +check-unit-tests: snap-confine/unit-tests system-shutdown/unit-tests libsnap-confine-private/unit-tests snap-device-helper/unit-tests $(HAVE_VALGRIND) ./libsnap-confine-private/unit-tests - SNAP_DEVICE_HELPER=$(srcdir)/snap-confine/snap-device-helper $(HAVE_VALGRIND) ./snap-confine/unit-tests + $(HAVE_VALGRIND) ./snap-confine/unit-tests $(HAVE_VALGRIND) ./system-shutdown/unit-tests + $(HAVE_VALGRIND) ./snap-device-helper/unit-tests else check-unit-tests: echo "unit tests are disabled (rebuild with --enable-unit-tests)" endif new_format = \ + libsnap-confine-private/bpf-support.c \ + libsnap-confine-private/bpf-support.h \ libsnap-confine-private/cgroup-support.c \ libsnap-confine-private/cgroup-support.h \ + libsnap-confine-private/cgroup-support-test.c \ + libsnap-confine-private/device-cgroup-support.c \ + libsnap-confine-private/device-cgroup-support.h \ libsnap-confine-private/infofile-test.c \ libsnap-confine-private/infofile.c \ libsnap-confine-private/infofile.h \ @@ -70,6 +81,10 @@ snap-confine/snap-confine-invocation-test.c \ snap-confine/snap-confine-invocation.c \ snap-confine/snap-confine-invocation.h \ + snap-device-helper/main.c \ + snap-device-helper/snap-device-helper.c \ + snap-device-helper/snap-device-helper.h \ + snap-device-helper/snap-device-helper-test.c \ snap-discard-ns/snap-discard-ns.c \ snap-gdb-shim/snap-gdb-shim.c \ snap-gdb-shim/snap-gdbserver-shim.c @@ -85,7 +100,7 @@ # The hack target helps developers work on snap-confine on their live system by # installing a fresh copy of snap confine and the appropriate apparmor profile. .PHONY: hack -hack: snap-confine/snap-confine-debug snap-confine/snap-confine.apparmor snap-update-ns/snap-update-ns snap-seccomp/snap-seccomp snap-discard-ns/snap-discard-ns +hack: snap-confine/snap-confine-debug snap-confine/snap-confine.apparmor snap-update-ns/snap-update-ns snap-seccomp/snap-seccomp snap-discard-ns/snap-discard-ns snap-device-helper/snap-device-helper sudo install -D -m 4755 snap-confine/snap-confine-debug $(DESTDIR)$(libexecdir)/snap-confine if [ -d /etc/apparmor.d ]; then sudo install -m 644 snap-confine/snap-confine.apparmor $(DESTDIR)/etc/apparmor.d/$(patsubst .%,%,$(subst /,.,$(libexecdir))).snap-confine.real; fi sudo install -d -m 755 $(DESTDIR)/var/lib/snapd/apparmor/snap-confine/ @@ -93,11 +108,13 @@ sudo install -m 755 snap-update-ns/snap-update-ns $(DESTDIR)$(libexecdir)/snap-update-ns sudo install -m 755 snap-discard-ns/snap-discard-ns $(DESTDIR)$(libexecdir)/snap-discard-ns sudo install -m 755 snap-seccomp/snap-seccomp $(DESTDIR)$(libexecdir)/snap-seccomp + sudo install -m 755 snap-device-helper/snap-device-helper $(DESTDIR)$(libexecdir)/snap-device-helper if [ "$$(command -v restorecon)" != "" ]; then sudo restorecon -R -v $(DESTDIR)$(libexecdir)/; fi # for the hack target also: snap-update-ns/snap-update-ns: snap-update-ns/*.go snap-update-ns/*.[ch] - cd snap-update-ns && GOPATH=$(or $(GOPATH),$(realpath $(srcdir)/../../../../..)) go build -v + cd snap-update-ns && GOPATH=$(or $(GOPATH),$(realpath $(srcdir)/../../../../..)) go build \ + -ldflags='-extldflags=-static -linkmode=external' -v snap-seccomp/snap-seccomp: snap-seccomp/*.go cd snap-seccomp && GOPATH=$(or $(GOPATH),$(realpath $(srcdir)/../../../../..)) go build -v @@ -114,6 +131,8 @@ libsnap-confine-private/cgroup-freezer-support.h \ libsnap-confine-private/cgroup-support.c \ libsnap-confine-private/cgroup-support.h \ + libsnap-confine-private/device-cgroup-support.c \ + libsnap-confine-private/device-cgroup-support.h \ libsnap-confine-private/classic.c \ libsnap-confine-private/classic.h \ libsnap-confine-private/cleanup-funcs.c \ @@ -145,15 +164,21 @@ libsnap-confine-private/tool.h \ libsnap-confine-private/utils.c \ libsnap-confine-private/utils.h -libsnap_confine_private_a_CFLAGS = $(CHECK_CFLAGS) +if ENABLE_BPF +libsnap_confine_private_a_SOURCES += \ + libsnap-confine-private/bpf-support.c \ + libsnap-confine-private/bpf-support.h +endif +libsnap_confine_private_a_CFLAGS = $(CHECK_CFLAGS) $(VENDOR_BPF_HEADERS_CFLAGS) noinst_LIBRARIES += libsnap-confine-private-debug.a libsnap_confine_private_debug_a_SOURCES = $(libsnap_confine_private_a_SOURCES) -libsnap_confine_private_debug_a_CFLAGS = $(CHECK_CFLAGS) -DSNAP_CONFINE_DEBUG_BUILD=1 +libsnap_confine_private_debug_a_CFLAGS = $(CHECK_CFLAGS) $(VENDOR_BPF_HEADERS_CFLAGS) -DSNAP_CONFINE_DEBUG_BUILD=1 if WITH_UNIT_TESTS noinst_PROGRAMS += libsnap-confine-private/unit-tests libsnap_confine_private_unit_tests_SOURCES = \ + libsnap-confine-private/cgroup-support-test.c \ libsnap-confine-private/classic-test.c \ libsnap-confine-private/cleanup-funcs-test.c \ libsnap-confine-private/error-test.c \ @@ -174,7 +199,8 @@ libsnap-confine-private/unit-tests.c \ libsnap-confine-private/unit-tests.h \ libsnap-confine-private/utils-test.c -libsnap_confine_private_unit_tests_CFLAGS = $(CHECK_CFLAGS) $(GLIB_CFLAGS) + +libsnap_confine_private_unit_tests_CFLAGS = $(CHECK_CFLAGS) $(VENDOR_BPF_HEADERS_CFLAGS) $(GLIB_CFLAGS) libsnap_confine_private_unit_tests_LDADD = $(GLIB_LIBS) libsnap_confine_private_unit_tests_CFLAGS += -D_ENABLE_FAULT_INJECTION libsnap_confine_private_unit_tests_STATIC = @@ -266,7 +292,7 @@ # all external libraries, this way it can be reused in # snap_confine_snap_confine_debug_LDADD withouth applying any text # transformations -snap_confine_snap_confine_extra_libs = $(LIBUDEV_LIBS) +snap_confine_snap_confine_extra_libs = $(LIBUDEV_LIBS) -ldl if STATIC_LIBCAP snap_confine_snap_confine_STATIC += -lcap @@ -335,8 +361,7 @@ snap-confine/mount-support-test.c \ snap-confine/ns-support-test.c \ snap-confine/snap-confine-args-test.c \ - snap-confine/snap-confine-invocation-test.c \ - snap-confine/snap-device-helper-test.c + snap-confine/snap-confine-invocation-test.c snap_confine_unit_tests_CFLAGS = $(snap_confine_snap_confine_CFLAGS) $(GLIB_CFLAGS) snap_confine_unit_tests_LDADD = $(snap_confine_snap_confine_LDADD) $(GLIB_LIBS) snap_confine_unit_tests_LDFLAGS = $(snap_confine_snap_confine_LDFLAGS) @@ -416,16 +441,35 @@ ## snap-device-helper ## -EXTRA_DIST += \ - snap-confine/snap-device-helper +libexec_PROGRAMS += \ + snap-device-helper/snap-device-helper -# NOTE: This makes distcheck fail but it is required for udev, so go figure. -# http://www.gnu.org/software/automake/manual/automake.html#Hard_002dCoded-Install-Paths -# -# Install support script for udev rules -install-exec-local:: - install -d -m 755 $(DESTDIR)$(libexecdir) - install -m 755 $(srcdir)/snap-confine/snap-device-helper $(DESTDIR)$(libexecdir) +snap_device_helper_snap_device_helper_SOURCES = \ + snap-device-helper/main.c \ + snap-device-helper/snap-device-helper.c +snap_device_helper_snap_device_helper_CFLAGS = $(CHECK_CFLAGS) $(AM_CFLAGS) +snap_device_helper_snap_device_helper_LDFLAGS = $(AM_LDFLAGS) +snap_device_helper_snap_device_helper_LDADD = libsnap-confine-private.a + +if WITH_UNIT_TESTS +noinst_PROGRAMS += snap-device-helper/unit-tests +snap_device_helper_unit_tests_SOURCES = \ + libsnap-confine-private/test-utils.c \ + libsnap-confine-private/string-utils.c \ + libsnap-confine-private/utils.c \ + libsnap-confine-private/cleanup-funcs.c \ + libsnap-confine-private/panic.c \ + libsnap-confine-private/snap.c \ + libsnap-confine-private/error.c \ + libsnap-confine-private/unit-tests-main.c \ + libsnap-confine-private/unit-tests.c \ + libsnap-confine-private/unit-tests.h \ + snap-device-helper/snap-device-helper-test.c +snap_device_helper_unit_tests_CFLAGS = $(snap_device_helper_snap_device_helper_CFLAGS) $(GLIB_CFLAGS) +snap_device_helper_unit_tests_LDADD = $(GLIB_LIBS) +snap_device_helper_unit_tests_LDFLAGS =$(snap_device_helper_snap_device_helper_LDFLAGS) + +endif # WITH_UNIT_TESTS ## ## snap-discard-ns @@ -487,6 +531,7 @@ snap-gdb-shim/snap-gdb-shim.c snap_gdb_shim_snap_gdb_shim_LDADD = libsnap-confine-private.a +snap_gdb_shim_snap_gdb_shim_LDFLAGS = -static ## ## snap-gdbserver-shim @@ -498,6 +543,7 @@ snap-gdb-shim/snap-gdbserver-shim.c snap_gdb_shim_snap_gdbserver_shim_LDADD = libsnap-confine-private.a +snap_gdb_shim_snap_gdbserver_shim_LDFLAGS = -static ## ## snapd-generator diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_buy.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_buy.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_buy.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_buy.go 2023-03-23 08:10:58.000000000 +0000 @@ -23,10 +23,10 @@ "fmt" "strings" + "github.com/jessevdk/go-flags" + "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/i18n" - - "github.com/jessevdk/go-flags" ) var shortBuyHelp = i18n.G("Buy a snap") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_changes.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_changes.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_changes.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_changes.go 2023-03-23 08:10:58.000000000 +0000 @@ -24,10 +24,10 @@ "regexp" "sort" + "github.com/jessevdk/go-flags" + "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/i18n" - - "github.com/jessevdk/go-flags" ) var shortChangesHelp = i18n.G("List system changes") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_confinement.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_confinement.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_confinement.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_confinement.go 2023-03-23 08:10:58.000000000 +0000 @@ -20,11 +20,11 @@ package main import ( - "github.com/snapcore/snapd/i18n" - "fmt" "github.com/jessevdk/go-flags" + + "github.com/snapcore/snapd/i18n" ) var shortConfinementHelp = i18n.G("Print the confinement mode the system operates in") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_connect.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_connect.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_connect.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_connect.go 2023-03-23 08:10:58.000000000 +0000 @@ -20,9 +20,9 @@ package main import ( - "github.com/snapcore/snapd/i18n" - "github.com/jessevdk/go-flags" + + "github.com/snapcore/snapd/i18n" ) type cmdConnect struct { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_create_key.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_create_key.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_create_key.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_create_key.go 2023-03-23 08:10:58.000000000 +0000 @@ -20,11 +20,9 @@ package main import ( - "errors" "fmt" "github.com/jessevdk/go-flags" - "golang.org/x/crypto/ssh/terminal" "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/i18n" @@ -68,25 +66,9 @@ return fmt.Errorf(i18n.G("key name %q is not valid; only ASCII letters, digits, and hyphens are allowed"), keyName) } - fmt.Fprint(Stdout, i18n.G("Passphrase: ")) - passphrase, err := terminal.ReadPassword(0) - fmt.Fprint(Stdout, "\n") + keypairMgr, err := getKeypairManager() if err != nil { return err } - fmt.Fprint(Stdout, i18n.G("Confirm passphrase: ")) - confirmPassphrase, err := terminal.ReadPassword(0) - fmt.Fprint(Stdout, "\n") - if err != nil { - return err - } - if string(passphrase) != string(confirmPassphrase) { - return errors.New("passphrases do not match") - } - if err != nil { - return err - } - - manager := asserts.NewGPGKeypairManager() - return manager.Generate(string(passphrase), keyName) + return generateKey(keypairMgr, keyName) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_bootvars_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_bootvars_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_bootvars_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_bootvars_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -102,12 +102,13 @@ bloader := bootloadertest.Mock("mock", c.MkDir()) bootloader.Force(bloader) err := bloader.SetBootVars(map[string]string{ - "snapd_recovery_system": "1234", - "snapd_recovery_mode": "run", - "unrelated": "thing", - "snap_kernel": "pc-kernel_3.snap", - "recovery_system_status": "try", - "try_recovery_system": "9999", + "snapd_recovery_system": "1234", + "snapd_recovery_mode": "run", + "unrelated": "thing", + "snap_kernel": "pc-kernel_3.snap", + "recovery_system_status": "try", + "try_recovery_system": "9999", + "snapd_good_recovery_systems": "0000", }) c.Assert(err, check.IsNil) @@ -122,6 +123,7 @@ kernel_status= recovery_system_status=try try_recovery_system=9999 +snapd_good_recovery_systems=0000 snapd_extra_cmdline_args= snapd_full_cmdline_args= `) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_state.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_state.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_state.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_state.go 2023-03-23 08:10:58.000000000 +0000 @@ -93,19 +93,27 @@ func (t byLaneAndWaitTaskChain) Len() int { return len(t) } func (t byLaneAndWaitTaskChain) Swap(i, j int) { t[i], t[j] = t[j], t[i] } func (t byLaneAndWaitTaskChain) Less(i, j int) bool { + if t[i].ID() == t[j].ID() { + return false + } // cover the typical case (just one lane), and order by first lane if t[i].Lanes()[0] == t[j].Lanes()[0] { - return waitChainSearch(t[i], t[j]) + seenTasks := make(map[string]bool) + return t.waitChainSearch(t[i], t[j], seenTasks) } return t[i].Lanes()[0] < t[j].Lanes()[0] } -func waitChainSearch(startT, searchT *state.Task) bool { +func (t *byLaneAndWaitTaskChain) waitChainSearch(startT, searchT *state.Task, seenTasks map[string]bool) bool { + if seenTasks[startT.ID()] { + return false + } + seenTasks[startT.ID()] = true for _, cand := range startT.HaltTasks() { if cand == searchT { return true } - if waitChainSearch(cand, searchT) { + if t.waitChainSearch(cand, searchT, seenTasks) { return true } } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_state_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_state_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_state_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_state_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -98,6 +98,51 @@ } `) +var stateCyclesJSON = []byte(` +{ + "last-task-id": 14, + "last-change-id": 2, + + "data": { + "snaps": {}, + "seeded": true + }, + "changes": { + "1": { + "id": "1", + "kind": "install-snap", + "summary": "install a snap", + "status": 0, + "task-ids": ["11","12","13"] + } + }, + "tasks": { + "11": { + "id": "11", + "change": "1", + "kind": "foo", + "summary": "Foo task", + "status": 4, + "halt-tasks": ["13"] + }, + "12": { + "id": "12", + "change": "1", + "kind": "bar", + "summary": "Bar task", + "halt-tasks": ["13"] + }, + "13": { + "id": "13", + "change": "1", + "kind": "bar", + "summary": "Bar task", + "halt-tasks": ["11","12"] + } + } +} +`) + func (s *SnapSuite) TestDebugChanges(c *C) { dir := c.MkDir() stateFile := filepath.Join(dir, "test-state.json") @@ -202,6 +247,22 @@ c.Check(s.Stderr(), Equals, "") } +func (s *SnapSuite) TestDebugTasksWithCycles(c *C) { + dir := c.MkDir() + stateFile := filepath.Join(dir, "test-state.json") + c.Assert(ioutil.WriteFile(stateFile, stateCyclesJSON, 0644), IsNil) + + rest, err := main.Parser(main.Client()).ParseArgs([]string{"debug", "state", "--abs-time", "--change=1", stateFile}) + c.Assert(err, IsNil) + c.Assert(rest, DeepEquals, []string{}) + c.Check(s.Stdout(), Matches, + "Lanes ID Status Spawn Ready Kind Summary\n"+ + "0 13 Do 0001-01-01T00:00:00Z 0001-01-01T00:00:00Z bar Bar task\n"+ + "0 12 Do 0001-01-01T00:00:00Z 0001-01-01T00:00:00Z bar Bar task\n"+ + "0 11 Done 0001-01-01T00:00:00Z 0001-01-01T00:00:00Z foo Foo task\n") + c.Check(s.Stderr(), Equals, "") +} + func (s *SnapSuite) TestDebugTasksMissingState(c *C) { _, err := main.Parser(main.Client()).ParseArgs([]string{"debug", "state", "--change=1", "/missing-state.json"}) c.Check(err, ErrorMatches, "cannot read the state file: open /missing-state.json: no such file or directory") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_timings.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_timings.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_timings.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_debug_timings.go 2023-03-23 08:10:58.000000000 +0000 @@ -33,7 +33,7 @@ type cmdChangeTimings struct { changeIDMixin - EnsureTag string `long:"ensure" choice:"auto-refresh" choice:"become-operational" choice:"refresh-catalogs" choice:"refresh-hints" choice:"seed"` + EnsureTag string `long:"ensure" choice:"auto-refresh" choice:"become-operational" choice:"refresh-catalogs" choice:"refresh-hints" choice:"seed" choice:"install-system"` All bool `long:"all"` StartupTag string `long:"startup" choice:"load-state" choice:"ifacemgr"` Verbose bool `long:"verbose"` diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_delete_key.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_delete_key.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_delete_key.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_delete_key.go 2023-03-23 08:10:58.000000000 +0000 @@ -20,6 +20,8 @@ package main import ( + "fmt" + "github.com/jessevdk/go-flags" "github.com/snapcore/snapd/asserts" @@ -56,6 +58,13 @@ return ErrExtraArgs } - manager := asserts.NewGPGKeypairManager() - return manager.Delete(string(x.Positional.KeyName)) + keypairMgr, err := getKeypairManager() + if err != nil { + return err + } + err = keypairMgr.Delete(string(x.Positional.KeyName)) + if _, ok := err.(*asserts.ExternalUnsupportedOpError); ok { + return fmt.Errorf(i18n.G("cannot delete external keypair manager key via snap command, use the appropriate external procedure")) + } + return err } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_delete_key_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_delete_key_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_delete_key_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_delete_key_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -62,3 +62,14 @@ c.Check(obtainedResponse, DeepEquals, expectedResponse) c.Check(s.Stderr(), Equals, "") } + +func (s *SnapKeysSuite) TestDeleteKeyExternalUnsupported(c *C) { + _, restore := mockNopExtKeyMgr(c) + defer restore() + + _, err := snap.Parser(snap.Client()).ParseArgs([]string{"delete-key", "key"}) + c.Assert(err, NotNil) + c.Check(err.Error(), Equals, "cannot delete external keypair manager key via snap command, use the appropriate external procedure") + c.Check(s.Stdout(), Equals, "") + c.Check(s.Stderr(), Equals, "") +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_disconnect.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_disconnect.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_disconnect.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_disconnect.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,10 +22,10 @@ import ( "fmt" + "github.com/jessevdk/go-flags" + "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/i18n" - - "github.com/jessevdk/go-flags" ) type cmdDisconnect struct { @@ -73,8 +73,8 @@ return ErrExtraArgs } - offer := x.Positionals.Offer.SnapAndName - use := x.Positionals.Use.SnapAndName + offer := x.Positionals.Offer.SnapAndNameStrict + use := x.Positionals.Use.SnapAndNameStrict // snap disconnect : // snap disconnect @@ -82,9 +82,6 @@ // Swap Offer and Use around offer, use = use, offer } - if use.Name == "" { - return fmt.Errorf("please provide the plug or slot name to disconnect from snap %q", use.Snap) - } opts := &client.DisconnectOptions{Forget: x.Forget} id, err := x.client.Disconnect(offer.Snap, offer.Name, use.Snap, use.Name, opts) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_disconnect_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_disconnect_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_disconnect_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_disconnect_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -209,7 +209,7 @@ c.Fatalf("expected nothing to reach the server") }) rest, err := Parser(Client()).ParseArgs([]string{"disconnect", "consumer"}) - c.Assert(err, ErrorMatches, `please provide the plug or slot name to disconnect from snap "consumer"`) + c.Assert(err, ErrorMatches, `invalid value: "consumer" \(want snap:name or :name\)`) c.Assert(rest, DeepEquals, []string{"consumer"}) c.Assert(s.Stdout(), Equals, "") c.Assert(s.Stderr(), Equals, "") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_download.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_download.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_download.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_download.go 2023-03-23 08:10:58.000000000 +0000 @@ -116,29 +116,29 @@ // for testing var downloadDirect = downloadDirectImpl -func downloadDirectImpl(snapName string, revision snap.Revision, dlOpts image.DownloadOptions) error { +func downloadDirectImpl(snapName string, revision snap.Revision, dlOpts image.DownloadSnapOptions) error { tsto, err := image.NewToolingStore() if err != nil { return err } fmt.Fprintf(Stdout, i18n.G("Fetching snap %q\n"), snapName) - snapPath, snapInfo, _, err := tsto.DownloadSnap(snapName, dlOpts) + dlSnap, err := tsto.DownloadSnap(snapName, dlOpts) if err != nil { return err } fmt.Fprintf(Stdout, i18n.G("Fetching assertions for %q\n"), snapName) - assertPath, err := fetchSnapAssertionsDirect(tsto, snapPath, snapInfo) + assertPath, err := fetchSnapAssertionsDirect(tsto, dlSnap.Path, dlSnap.Info) if err != nil { return err } - printInstallHint(assertPath, snapPath) + printInstallHint(assertPath, dlSnap.Path) return nil } func (x *cmdDownload) downloadFromStore(snapName string, revision snap.Revision) error { - dlOpts := image.DownloadOptions{ + dlOpts := image.DownloadSnapOptions{ TargetDir: x.TargetDir, Basename: x.Basename, Channel: x.Channel, diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_download_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_download_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_download_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_download_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -87,7 +87,7 @@ func (s *SnapSuite) TestDownloadDirect(c *check.C) { var n int - restore := snapCmd.MockDownloadDirect(func(snapName string, revision snap.Revision, dlOpts image.DownloadOptions) error { + restore := snapCmd.MockDownloadDirect(func(snapName string, revision snap.Revision, dlOpts image.DownloadSnapOptions) error { c.Check(snapName, check.Equals, "a-snap") c.Check(revision, check.Equals, snap.R(0)) c.Check(dlOpts.Basename, check.Equals, "some-base-name") @@ -114,7 +114,7 @@ func (s *SnapSuite) TestDownloadDirectErrors(c *check.C) { var n int - restore := snapCmd.MockDownloadDirect(func(snapName string, revision snap.Revision, dlOpts image.DownloadOptions) error { + restore := snapCmd.MockDownloadDirect(func(snapName string, revision snap.Revision, dlOpts image.DownloadSnapOptions) error { n++ return fmt.Errorf("some-error") }) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_export_key.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_export_key.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_export_key.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_export_key.go 2023-03-23 08:10:58.000000000 +0000 @@ -1,7 +1,7 @@ // -*- Mode: Go; indent-tabs-mode: t -*- /* - * Copyright (C) 2016 Canonical Ltd + * Copyright (C) 2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -66,9 +66,12 @@ keyName = "default" } - manager := asserts.NewGPGKeypairManager() + keypairMgr, err := getKeypairManager() + if err != nil { + return err + } if x.Account != "" { - privKey, err := manager.GetByName(keyName) + privKey, err := keypairMgr.GetByName(keyName) if err != nil { return err } @@ -90,7 +93,7 @@ } fmt.Fprint(Stdout, string(asserts.Encode(assertion))) } else { - encoded, err := manager.Export(keyName) + encoded, err := keypairMgr.Export(keyName) if err != nil { return err } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_help_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_help_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_help_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_help_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -141,7 +141,7 @@ // regexp matches "Usage: snap " plus an arbitrary // number of [] plus an arbitrary number of // <> optionally ending in ellipsis - c.Check(s.Stdout(), check.Matches, fmt.Sprintf(`(?sm)Usage:\s+snap %s(?: \[[^][]+\])*(?:(?: <[^<>]+>)+(?:\.\.\.)?)?$.*`, cmd), comment) + c.Check(s.Stdout(), check.Matches, fmt.Sprintf(`(?sm)Usage:\s+snap %s(?: \[[^][]+\])*(?:(?: <[^<>]+>(?:\.<[^<>]+>)?)+(?:\.\.\.)?)?(?: \[[^][]+\])?$.*`, cmd), comment) c.Check(s.Stderr(), check.Equals, "", comment) } } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_interface.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_interface.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_interface.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_interface.go 2023-03-23 08:10:58.000000000 +0000 @@ -26,10 +26,10 @@ "sort" "text/tabwriter" + "github.com/jessevdk/go-flags" + "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/i18n" - - "github.com/jessevdk/go-flags" ) type cmdInterface struct { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_interfaces.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_interfaces.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_interfaces.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_interfaces.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,10 +22,10 @@ import ( "fmt" + "github.com/jessevdk/go-flags" + "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/i18n" - - "github.com/jessevdk/go-flags" ) type cmdInterfaces struct { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_keys.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_keys.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_keys.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_keys.go 2023-03-23 08:10:58.000000000 +0000 @@ -1,7 +1,7 @@ // -*- Mode: Go; indent-tabs-mode: t -*- /* - * Copyright (C) 2016 Canonical Ltd + * Copyright (C) 2016-2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -23,10 +23,9 @@ "encoding/json" "fmt" - "github.com/snapcore/snapd/asserts" - "github.com/snapcore/snapd/i18n" - "github.com/jessevdk/go-flags" + + "github.com/snapcore/snapd/i18n" ) type cmdKeys struct { @@ -86,21 +85,21 @@ return ErrExtraArgs } - keys := []Key{} - - manager := asserts.NewGPGKeypairManager() - collect := func(privk asserts.PrivateKey, fpr string, uid string) error { - key := Key{ - Name: uid, - Sha3_384: privk.PublicKey().ID(), - } - keys = append(keys, key) - return nil + keypairMgr, err := getKeypairManager() + if err != nil { + return err } - err := manager.Walk(collect) + + kinfos, err := keypairMgr.List() if err != nil { return err } + keys := make([]Key, len(kinfos)) + for i, kinfo := range kinfos { + keys[i].Name = kinfo.Name + keys[i].Sha3_384 = kinfo.ID + } + if x.JSON { return outputJSON(keys) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_known_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_known_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_known_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_known_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -29,9 +29,8 @@ "gopkg.in/check.v1" "github.com/snapcore/snapd/client" - "github.com/snapcore/snapd/store" - snap "github.com/snapcore/snapd/cmd/snap" + "github.com/snapcore/snapd/store" ) // acquire example data via: diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_login.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_login.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_login.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_login.go 2023-03-23 08:10:58.000000000 +0000 @@ -45,8 +45,8 @@ will then be made using those credentials. It's not necessary to log in to interact with snapd. Doing so, however, enables -purchasing of snaps using 'snap buy', as well as some some developer-oriented -features as detailed in the help for the find, install and refresh commands. +interactions without sudo, as well as some some developer-oriented features as +detailed in the help for the find, install and refresh commands. An account can be set up at https://login.ubuntu.com `) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_managed.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_managed.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_managed.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_managed.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,9 +22,9 @@ import ( "fmt" - "github.com/snapcore/snapd/i18n" - "github.com/jessevdk/go-flags" + + "github.com/snapcore/snapd/i18n" ) var shortIsManagedHelp = i18n.G("Print whether the system is managed") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_model.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_model.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_model.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_model.go 2023-03-23 08:10:58.000000000 +0000 @@ -71,7 +71,8 @@ "store", "system-user-authority", "timestamp", - "required-snaps", + "required-snaps", // for uc16 and uc18 models + "snaps", // for uc20 models "device-key-sha3-384", "device-key", } @@ -232,6 +233,11 @@ fmt.Fprintf(w, "grade%s\t%s\n", separator, grade) } + storageSafety := modelAssertion.HeaderString("storage-safety") + if storageSafety != "" { + fmt.Fprintf(w, "storage-safety%s\t%s\n", separator, storageSafety) + } + // serial is same for all variants fmt.Fprintf(w, "serial%s\t%s\n", separator, serial) @@ -304,6 +310,72 @@ fmt.Fprintln(w, "device-key-sha3-384: |") wrapLine(w, []rune(headerString), " ", termWidth) } + case "snaps": + // also flush the writer before continuing so the previous keys + // don't try to align with this key + w.Flush() + snapsHeader, ok := headerValue.([]interface{}) + if !ok { + return invalidTypeErr + } + if len(snapsHeader) == 0 { + // unexpected why this is an empty list, but just ignore for + // now + continue + } + fmt.Fprintf(w, "snaps:\n") + for _, sn := range snapsHeader { + snMap, ok := sn.(map[string]interface{}) + if !ok { + return invalidTypeErr + } + // iterate over all keys in the map in a stable, visually + // appealing ordering + // first do snap name, which will always be present since we + // parsed a valid assertion + name := snMap["name"].(string) + fmt.Fprintf(w, " - name:\t%s\n", name) + + // the rest of these may be absent, but they are all still + // simple strings + for _, snKey := range []string{"id", "type", "default-channel", "presence"} { + snValue, ok := snMap[snKey] + if !ok { + continue + } + snStrValue, ok := snValue.(string) + if !ok { + return invalidTypeErr + } + if snStrValue != "" { + fmt.Fprintf(w, " %s:\t%s\n", snKey, snStrValue) + } + } + + // finally handle "modes" which is a list + modes, ok := snMap["modes"] + if !ok { + continue + } + modesSlice, ok := modes.([]interface{}) + if !ok { + return invalidTypeErr + } + if len(modesSlice) == 0 { + continue + } + + modeStrSlice := make([]string, 0, len(modesSlice)) + for _, mode := range modesSlice { + modeStr, ok := mode.(string) + if !ok { + return invalidTypeErr + } + modeStrSlice = append(modeStrSlice, modeStr) + } + modesSliceYamlStr := "[" + strings.Join(modeStrSlice, ", ") + "]" + fmt.Fprintf(w, " modes:\t%s\n", modesSliceYamlStr) + } // long base64 key we can rewrap safely case "device-key": diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_model_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_model_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_model_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_model_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -66,7 +66,8 @@ model: test-snapd-core-20-amd64 architecture: amd64 base: core20 -grade: secured +storage-safety: prefer-encrypted +grade: dangerous snaps: - default-channel: 20/edge @@ -79,6 +80,13 @@ name: pc-kernel type: kernel - + name: app-snap + default-channel: foo + presence: optional + modes: + - recover + - run + - default-channel: latest/stable id: DLqre5XGLbDqg9jPtiAhRRjDuPVa5X1q name: core20 @@ -354,10 +362,11 @@ modelF: simpleHappyResponder(happyUC20ModelAssertionResponse), serialF: simpleHappyResponder(happySerialUC20AssertionResponse), outText: ` -brand MeMeMe (meuser*) -model test-snapd-core-20-amd64 -grade secured -serial 7777 +brand MeMeMe (meuser*) +model test-snapd-core-20-amd64 +grade dangerous +storage-safety prefer-encrypted +serial 7777 `[1:], }, { @@ -427,6 +436,51 @@ `[1:]) c.Check(s.Stderr(), check.Equals, "") } + +func (s *SnapSuite) TestModelVerboseUC20(c *check.C) { + s.RedirectClientToTestServer( + makeHappyTestServerHandler( + c, + simpleHappyResponder(happyUC20ModelAssertionResponse), + simpleHappyResponder(happySerialAssertionResponse), + simpleAssertionAccountResponder(happyAccountAssertionResponse), + )) + rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"model", "--verbose", "--abs-time"}) + c.Assert(err, check.IsNil) + c.Assert(rest, check.DeepEquals, []string{}) + c.Check(s.Stdout(), check.Equals, ` +brand-id: testrootorg +model: test-snapd-core-20-amd64 +grade: dangerous +storage-safety: prefer-encrypted +serial: serialserial +architecture: amd64 +base: core20 +timestamp: 2018-09-11T22:00:00Z +snaps: + - name: pc + id: UqFziVZDHLSyO3TqSWgNBoAdHbLI4dAH + type: gadget + default-channel: 20/edge + - name: pc-kernel + id: pYVQrBcKmBa0mZ4CCN7ExT6jH8rY1hza + type: kernel + default-channel: 20/edge + - name: app-snap + default-channel: foo + presence: optional + modes: [recover, run] + - name: core20 + id: DLqre5XGLbDqg9jPtiAhRRjDuPVa5X1q + type: base + default-channel: latest/stable + - name: snapd + id: PMrrV4ml8uWuEUDBT8dSGnKUYbevVhc4 + type: snapd + default-channel: latest/stable +`[1:]) + c.Check(s.Stderr(), check.Equals, "") +} func (s *SnapSuite) TestModelVerboseDisplayName(c *check.C) { s.RedirectClientToTestServer( diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_pack.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_pack.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_pack.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_pack.go 2023-03-23 08:10:58.000000000 +0000 @@ -23,16 +23,15 @@ "fmt" "path/filepath" - "golang.org/x/xerrors" - "github.com/jessevdk/go-flags" + "golang.org/x/xerrors" "github.com/snapcore/snapd/i18n" - "github.com/snapcore/snapd/snap" - "github.com/snapcore/snapd/snap/pack" // for SanitizePlugsSlots "github.com/snapcore/snapd/interfaces/builtin" + "github.com/snapcore/snapd/snap" + "github.com/snapcore/snapd/snap/pack" ) type packCmd struct { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_prefer.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_prefer.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_prefer.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_prefer.go 2023-03-23 08:10:58.000000000 +0000 @@ -20,9 +20,9 @@ package main import ( - "github.com/snapcore/snapd/i18n" - "github.com/jessevdk/go-flags" + + "github.com/snapcore/snapd/i18n" ) type cmdPrefer struct { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_quota.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_quota.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_quota.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_quota.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,21 +22,21 @@ import ( "fmt" "sort" + "strings" "github.com/jessevdk/go-flags" "github.com/snapcore/snapd/client" + "github.com/snapcore/snapd/gadget/quantity" "github.com/snapcore/snapd/i18n" "github.com/snapcore/snapd/strutil" ) -var shortQuotaHelp = i18n.G("Create, update or show quota group for a set of snaps") +var shortQuotaHelp = i18n.G("Show quota group for a set of snaps") var longQuotaHelp = i18n.G(` -The quota command creates, updates or shows quota groups for a a set of snaps. - -A quota group sets resource limits (currently maximum memory only) on the set of -snaps that belong to it. Snaps can be at most in one quota group. Quota groups -can be nested. +The quota command shows information about a quota group, including the set of +snaps and any sub-groups it contains, as well as its resource constraints and +the current usage of those constrained resources. `) var shortQuotasHelp = i18n.G("Show quota groups") @@ -45,24 +45,48 @@ `) var shortRemoveQuotaHelp = i18n.G("Remove quota group") -var longRemoveQuotaHelp = i18n.G(`The remove-quota command removes the given quota group.`) +var longRemoveQuotaHelp = i18n.G(` +The remove-quota command removes the given quota group. -type cmdQuota struct { - clientMixin - // MaxMemory and MemoryMax are mutually exclusive and provided for - // convienience, they mean the same. - MaxMemory string `long:"max-memory" optional:"true"` - MemoryMax string `long:"memory-max" optional:"true"` - Parent string `long:"parent" optional:"true"` - Positional struct { - GroupName string `positional-arg-name:"" required:"true"` - Snaps []installedSnapName `positional-arg-name:"" optional:"true"` - } `positional-args:"yes"` -} +Currently, only quota groups with no sub-groups can be removed. In order to +remove a quota group with sub-groups, the sub-groups must first be removed until +there are no sub-groups for the group, then the group itself can be removed. +`) + +var shortSetQuotaHelp = i18n.G(`Create or update a quota group.`) +var longSetQuotaHelp = i18n.G(` +The set-quota command updates or creates a quota group with the specified set of +snaps. + +A quota group sets resource limits on the set of snaps it contains. Only maximum +memory is currently supported. Snaps can be at most in one quota group but quota +groups can be nested. Nested quota groups are subject to the restriction that +the total sum of maximum memory in sub-groups cannot exceed that of the parent +group the nested groups are part of. + +All provided snaps are appended to the group; to remove a snap from a +quota group, the entire group must be removed with remove-quota and recreated +without the quota group. To remove a sub-group from the quota group, the +sub-group must be removed directly with the remove-quota command. + +The memory limit for a quota group can be increased but not decreased. To +decrease the memory limit for a quota group, the entire group must be removed +with the remove-quota command and recreated with a lower limit. Increasing the +memory limit for a quota group does not restart any services associated with +snaps in the quota group. + +Adding new snaps to a quota group will result in all non-disabled services in +that snap being restarted. + +An existing sub group cannot be moved from one parent to another. +`) func init() { - cmd := addCommand("quota", shortQuotaHelp, longQuotaHelp, func() flags.Commander { return &cmdQuota{} }, nil, nil) - // XXX: unhide + // TODO: unhide the commands when non-experimental + cmd := addCommand("set-quota", shortSetQuotaHelp, longSetQuotaHelp, func() flags.Commander { return &cmdSetQuota{} }, nil, nil) + cmd.hidden = true + + cmd = addCommand("quota", shortQuotaHelp, longQuotaHelp, func() flags.Commander { return &cmdQuota{} }, nil, nil) cmd.hidden = true cmd = addCommand("quotas", shortQuotasHelp, longQuotasHelp, func() flags.Commander { return &cmdQuotas{} }, nil, nil) @@ -72,57 +96,160 @@ cmd.hidden = true } -func (x *cmdQuota) Execute(args []string) (err error) { +type cmdSetQuota struct { + waitMixin + + MemoryMax string `long:"memory" optional:"true"` + Parent string `long:"parent" optional:"true"` + Positional struct { + GroupName string `positional-arg-name:"" required:"true"` + Snaps []installedSnapName `positional-arg-name:"" optional:"true"` + } `positional-args:"yes"` +} + +func (x *cmdSetQuota) Execute(args []string) (err error) { var maxMemory string switch { - case x.MaxMemory != "" && x.MemoryMax != "": - return fmt.Errorf("cannot use --max-memory and --memory-max together") - case x.MaxMemory != "": - maxMemory = x.MaxMemory case x.MemoryMax != "": maxMemory = x.MemoryMax } - if maxMemory == "" && x.Parent == "" && len(x.Positional.Snaps) == 0 { - return x.showQuotaGroupInfo(x.Positional.GroupName) + names := installedSnapNames(x.Positional.Snaps) + + // figure out if the group exists or not to make error messages more useful + groupExists := false + if _, err = x.client.GetQuotaGroup(x.Positional.GroupName); err == nil { + groupExists = true } - // TODO: update without max-memory (i.e. append snaps operation). - // Also how do we remove snaps from a group? Should the default be append? - // Do we want a "reset" operation to start from scratch? - if maxMemory == "" { - return fmt.Errorf("missing required --max-memory argument") + var chgID string + + switch { + case maxMemory == "" && x.Parent == "" && len(x.Positional.Snaps) == 0: + // no snaps were specified, no memory limit was specified, and no parent + // was specified, so just the group name was provided - this is not + // supported since there is nothing to change/create + + if groupExists { + return fmt.Errorf("no options set to change quota group") + } + return fmt.Errorf("cannot create quota group without memory limit") + + case maxMemory == "" && x.Parent != "" && len(x.Positional.Snaps) == 0: + // this is either trying to create a new group with a parent and forgot + // to specify the memory limit for the new group, or the user is trying + // to re-parent a group, i.e. move it from the current parent to a + // different one, which is currently unsupported + + if groupExists { + // TODO: or this could be setting the parent to the existing parent, + // which is effectively no change or update but maybe we allow since + // it's a noop? + return fmt.Errorf("cannot move a quota group to a new parent") + } + return fmt.Errorf("cannot create quota group without memory limit") + + case maxMemory != "": + // we have a memory limit to set for this group, so specify that along + // with whatever snaps may have been provided and whatever parent may + // have been specified + + mem, err := strutil.ParseByteSize(maxMemory) + if err != nil { + return err + } + + // note that the group could currently exist with a parent, and we could + // be specifying x.Parent as "" here - in the future that may mean to + // orphan a sub-group to no longer have a parent, but currently it just + // means leave the group with whatever parent it has, or if it doesn't + // currently exist, create the group without a parent group + chgID, err = x.client.EnsureQuota(x.Positional.GroupName, x.Parent, names, quantity.Size(mem)) + if err != nil { + return err + } + case len(x.Positional.Snaps) != 0: + // there are snaps specified for this group but no memory limit, so the + // group must already exist and we must be adding the specified snaps to + // the group + + // TODO: this case may someday also imply overwriting the current set of + // snaps with whatever was specified with some option, but we don't + // currently support that, so currently all snaps specified here are + // just added to the group + + chgID, err = x.client.EnsureQuota(x.Positional.GroupName, x.Parent, names, 0) + if err != nil { + return err + } + default: + // should be logically impossible to reach here + panic("impossible set of options") } - mem, err := strutil.ParseByteSize(maxMemory) - if err != nil { + if _, err := x.wait(chgID); err != nil { + if err == noWait { + return nil + } return err } - names := installedSnapNames(x.Positional.Snaps) - return x.client.EnsureQuota(x.Positional.GroupName, x.Parent, names, uint64(mem)) + return nil +} + +type cmdQuota struct { + clientMixin + + Positional struct { + GroupName string `positional-arg-name:"" required:"true"` + } `positional-args:"yes"` } -func (x *cmdQuota) showQuotaGroupInfo(groupName string) error { - w := Stdout +func (x *cmdQuota) Execute(args []string) (err error) { + if len(args) != 0 { + return fmt.Errorf("too many arguments provided") + } + group, err := x.client.GetQuotaGroup(x.Positional.GroupName) if err != nil { return err } - // TODO: show current quota usage + w := tabWriter() + defer w.Flush() - fmt.Fprintf(w, "name: %s\n", group.GroupName) + fmt.Fprintf(w, "name:\t%s\n", group.GroupName) if group.Parent != "" { - fmt.Fprintf(w, "parent: %s\n", group.Parent) + fmt.Fprintf(w, "parent:\t%s\n", group.Parent) + } + + fmt.Fprintf(w, "constraints:\n") + + // Constraints should always be non-nil, since a quota group always needs to + // have a memory limit + if group.Constraints == nil { + return fmt.Errorf("internal error: constraints is missing from daemon response") + } + val := strings.TrimSpace(fmtSize(int64(group.Constraints.Memory))) + fmt.Fprintf(w, " memory:\t%s\n", val) + + fmt.Fprintf(w, "current:\n") + if group.Current == nil { + // current however may be missing if there is no memory usage + val = "0B" + } else { + // use the value from the response + val = strings.TrimSpace(fmtSize(int64(group.Current.Memory))) } + + fmt.Fprintf(w, " memory:\t%s\n", val) + if len(group.Subgroups) > 0 { fmt.Fprint(w, "subgroups:\n") for _, name := range group.Subgroups { fmt.Fprintf(w, " - %s\n", name) } } - fmt.Fprintf(w, "max-memory: %s\n", fmtSize(int64(group.MaxMemory))) if len(group.Snaps) > 0 { fmt.Fprint(w, "snaps:\n") for _, snapName := range group.Snaps { @@ -134,14 +261,27 @@ } type cmdRemoveQuota struct { - clientMixin + waitMixin + Positional struct { GroupName string `positional-arg-name:"" required:"true"` } `positional-args:"yes"` } func (x *cmdRemoveQuota) Execute(args []string) (err error) { - return x.client.RemoveQuotaGroup(x.Positional.GroupName) + chgID, err := x.client.RemoveQuotaGroup(x.Positional.GroupName) + if err != nil { + return err + } + + if _, err := x.wait(chgID); err != nil { + if err == noWait { + return nil + } + return err + } + + return nil } type cmdQuotas struct { @@ -159,9 +299,20 @@ } w := tabWriter() - fmt.Fprintf(w, "Quota\tParent\tMax-Memory\n") - err = processQuotaGroupsTree(res, func(q *client.QuotaGroupResult) { - fmt.Fprintf(w, "%s\t%s\t%s\n", q.GroupName, q.Parent, fmtSize(int64(q.MaxMemory))) + fmt.Fprintf(w, "Quota\tParent\tConstraints\tCurrent\n") + err = processQuotaGroupsTree(res, func(q *client.QuotaGroupResult) error { + if q.Constraints == nil { + return fmt.Errorf("internal error: constraints is missing from daemon response") + } + + constraintVal := "memory=" + strings.TrimSpace(fmtSize(int64(q.Constraints.Memory))) + currentVal := "" + if q.Current != nil && q.Current.Memory != 0 { + currentVal = "memory=" + strings.TrimSpace(fmtSize(int64(q.Current.Memory))) + } + fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", q.GroupName, q.Parent, constraintVal, currentVal) + + return nil }) if err != nil { return err @@ -183,7 +334,7 @@ // processQuotaGroupsTree recreates the hierarchy of quotas and then visits it // recursively following the hierarchy first, then naming order. -func processQuotaGroupsTree(quotas []*client.QuotaGroupResult, handleGroup func(q *client.QuotaGroupResult)) error { +func processQuotaGroupsTree(quotas []*client.QuotaGroupResult, handleGroup func(q *client.QuotaGroupResult) error) error { var roots []*quotaGroup groupLookup := make(map[string]*quotaGroup, len(quotas)) @@ -210,16 +361,19 @@ } } - var processGroups func(groups []*quotaGroup) - processGroups = func(groups []*quotaGroup) { + var processGroups func(groups []*quotaGroup) error + processGroups = func(groups []*quotaGroup) error { for _, g := range groups { - handleGroup(g.res) + if err := handleGroup(g.res); err != nil { + return err + } if len(g.subGroups) > 0 { - processGroups(g.subGroups) + if err := processGroups(g.subGroups); err != nil { + return err + } } } + return nil } - processGroups(roots) - - return nil + return processGroups(roots) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_quota_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_quota_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_quota_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_quota_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -20,14 +20,16 @@ package main_test import ( + "bytes" + "encoding/json" "fmt" "io/ioutil" "net/http" - "strings" "gopkg.in/check.v1" main "github.com/snapcore/snapd/cmd/snap" + "github.com/snapcore/snapd/jsonutil" ) type quotaSuite struct { @@ -36,6 +38,23 @@ var _ = check.Suite("aSuite{}) +func makeFakeGetQuotaGroupNotFoundHandler(c *check.C, group string) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + c.Check(r.URL.Path, check.Equals, "/v2/quotas/"+group) + c.Check(r.Method, check.Equals, "GET") + w.WriteHeader(404) + fmt.Fprintln(w, `{ + "result": { + "message": "not found" + }, + "status": "Not Found", + "status-code": 404, + "type": "error" + }`) + } + +} + func makeFakeGetQuotaGroupHandler(c *check.C, body string) func(w http.ResponseWriter, r *http.Request) { var called bool return func(w http.ResponseWriter, r *http.Request) { @@ -64,7 +83,34 @@ } } -func makeFakeQuotaPostHandler(c *check.C, action, body, groupName, parentName string, snaps []string, maxMemory int64) func(w http.ResponseWriter, r *http.Request) { +func dispatchFakeHandlers(c *check.C, routes map[string]http.HandlerFunc) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + if router, ok := routes[r.URL.Path]; ok { + router(w, r) + return + } + c.Errorf("unexpected call to %s", r.URL.Path) + } +} + +type fakeQuotaGroupPostHandlerOpts struct { + action string + body string + groupName string + parentName string + snaps []string + maxMemory int64 +} + +type quotasEnsureBody struct { + Action string `json:"action"` + GroupName string `json:"group-name,omitempty"` + ParentName string `json:"parent,omitempty"` + Snaps []string `json:"snaps,omitempty"` + Constraints map[string]interface{} `json:"constraints,omitempty"` +} + +func makeFakeQuotaPostHandler(c *check.C, opts fakeQuotaGroupPostHandlerOpts) func(w http.ResponseWriter, r *http.Request) { var called bool return func(w http.ResponseWriter, r *http.Request) { if called { @@ -77,34 +123,61 @@ buf, err := ioutil.ReadAll(r.Body) c.Assert(err, check.IsNil) - switch action { + switch opts.action { case "remove": - c.Check(string(buf), check.Equals, fmt.Sprintf(`{"action":"remove","group-name":%q}`+"\n", groupName)) + c.Check(string(buf), check.Equals, fmt.Sprintf(`{"action":"remove","group-name":%q}`+"\n", opts.groupName)) case "ensure": - var snapNames []string - for _, sn := range snaps { - snapNames = append(snapNames, fmt.Sprintf("%q", sn)) + exp := quotasEnsureBody{ + Action: "ensure", + GroupName: opts.groupName, + ParentName: opts.parentName, + Snaps: opts.snaps, + Constraints: map[string]interface{}{}, + } + if opts.maxMemory != 0 { + exp.Constraints["memory"] = json.Number(fmt.Sprintf("%d", opts.maxMemory)) } - snapsStr := strings.Join(snapNames, ",") - c.Check(string(buf), check.Equals, fmt.Sprintf(`{"action":"ensure","group-name":%q,"parent":%q,"snaps":[%s],"max-memory":%d}`+"\n", groupName, parentName, snapsStr, maxMemory)) + + postJSON := quotasEnsureBody{} + err := jsonutil.DecodeWithNumber(bytes.NewReader(buf), &postJSON) + c.Assert(err, check.IsNil) + c.Assert(postJSON, check.DeepEquals, exp) default: - c.Fatalf("unexpected action %q", action) + c.Fatalf("unexpected action %q", opts.action) } - w.WriteHeader(200) - fmt.Fprintln(w, body) + w.WriteHeader(202) + fmt.Fprintln(w, opts.body) } } -func (s *quotaSuite) TestQuotaInvalidArgs(c *check.C) { +func makeChangesHandler(c *check.C) func(w http.ResponseWriter, r *http.Request) { + n := 0 + return func(w http.ResponseWriter, r *http.Request) { + n++ + switch n { + case 1: + c.Check(r.Method, check.Equals, "GET") + c.Check(r.URL.Path, check.Equals, "/v2/changes/42") + fmt.Fprintln(w, `{"type": "sync", "result": {"status": "Doing"}}`) + case 2: + c.Check(r.Method, check.Equals, "GET") + c.Check(r.URL.Path, check.Equals, "/v2/changes/42") + fmt.Fprintln(w, `{"type": "sync", "result": {"ready": true, "status": "Done"}}`) + default: + c.Fatalf("expected to get 2 requests, now on %d", n+1) + } + } +} + +func (s *quotaSuite) TestSetQuotaInvalidArgs(c *check.C) { for _, args := range []struct { args []string err string }{ - {[]string{"quota"}, "the required argument `` was not provided"}, - {[]string{"quota", "--memory-max=99B"}, "the required argument `` was not provided"}, - {[]string{"quota", "--memory-max=99B", "--max-memory=88B", "foo"}, `cannot use --max-memory and --memory-max together`}, - {[]string{"quota", "--memory-max=99", "foo"}, `cannot parse "99": need a number with a unit as input`}, - {[]string{"quota", "--memory-max=888X", "foo"}, `cannot parse "888X\": try 'kB' or 'MB'`}, + {[]string{"set-quota"}, "the required argument `` was not provided"}, + {[]string{"set-quota", "--memory=99B"}, "the required argument `` was not provided"}, + {[]string{"set-quota", "--memory=99", "foo"}, `cannot parse "99": need a number with a unit as input`}, + {[]string{"set-quota", "--memory=888X", "foo"}, `cannot parse "888X\": try 'kB' or 'MB'`}, // remove-quota command {[]string{"remove-quota"}, "the required argument `` was not provided"}, } { @@ -120,40 +193,223 @@ restore := main.MockIsStdinTTY(true) defer restore() - s.RedirectClientToTestServer(makeFakeGetQuotaGroupHandler(c, `{"type": "sync", "status-code": 200, "result": {"group-name":"foo","parent":"bar","subgroups":["subgrp1"],"snaps":["snap-a","snap-b"],"max-memory":1000}}`)) + const json = `{ + "type": "sync", + "status-code": 200, + "result": { + "group-name":"foo", + "parent":"bar", + "subgroups":["subgrp1"], + "snaps":["snap-a","snap-b"], + "constraints": { "memory": 1000 }, + "current": { "memory": 900 } + } + }` + + s.RedirectClientToTestServer(makeFakeGetQuotaGroupHandler(c, json)) rest, err := main.Parser(main.Client()).ParseArgs([]string{"quota", "foo"}) c.Assert(err, check.IsNil) c.Check(rest, check.HasLen, 0) c.Check(s.Stderr(), check.Equals, "") - c.Check(s.Stdout(), check.Equals, "name: foo\n"+ - "parent: bar\n"+ - "subgroups:\n"+ - " - subgrp1\n"+ - "max-memory: 1000B\n"+ - "snaps:\n"+ - " - snap-a\n"+ - " - snap-b\n") + c.Check(s.Stdout(), check.Equals, ` +name: foo +parent: bar +constraints: + memory: 1000B +current: + memory: 900B +subgroups: + - subgrp1 +snaps: + - snap-a + - snap-b +`[1:]) } func (s *quotaSuite) TestGetQuotaGroupSimple(c *check.C) { restore := main.MockIsStdinTTY(true) defer restore() - s.RedirectClientToTestServer(makeFakeGetQuotaGroupHandler(c, `{"type": "sync", "status-code": 200, "result": {"group-name":"foo","max-memory":1000}}`)) + const jsonTemplate = `{ + "type": "sync", + "status-code": 200, + "result": { + "group-name": "foo", + "constraints": {"memory": 1000}, + "current": {"memory": %d} + } + }` + + s.RedirectClientToTestServer(makeFakeGetQuotaGroupHandler(c, fmt.Sprintf(jsonTemplate, 0))) + + outputTemplate := ` +name: foo +constraints: + memory: 1000B +current: + memory: %dB +`[1:] rest, err := main.Parser(main.Client()).ParseArgs([]string{"quota", "foo"}) c.Assert(err, check.IsNil) c.Check(rest, check.HasLen, 0) c.Check(s.Stderr(), check.Equals, "") - c.Check(s.Stdout(), check.Equals, "name: foo\n"+ - "max-memory: 1000B\n") + c.Check(s.Stdout(), check.Equals, fmt.Sprintf(outputTemplate, 0)) + + s.stdout.Reset() + s.stderr.Reset() + + s.RedirectClientToTestServer(makeFakeGetQuotaGroupHandler(c, fmt.Sprintf(jsonTemplate, 500))) + + rest, err = main.Parser(main.Client()).ParseArgs([]string{"quota", "foo"}) + c.Assert(err, check.IsNil) + c.Check(rest, check.HasLen, 0) + c.Check(s.Stderr(), check.Equals, "") + c.Check(s.Stdout(), check.Equals, fmt.Sprintf(outputTemplate, 500)) +} + +func (s *quotaSuite) TestSetQuotaGroupCreateNew(c *check.C) { + const postJSON = `{"type": "async", "status-code": 202,"change":"42", "result": []}` + fakeHandlerOpts := fakeQuotaGroupPostHandlerOpts{ + action: "ensure", + body: postJSON, + groupName: "foo", + parentName: "bar", + snaps: []string{"snap-a"}, + maxMemory: 999, + } + + routes := map[string]http.HandlerFunc{ + "/v2/quotas": makeFakeQuotaPostHandler( + c, + fakeHandlerOpts, + ), + // the foo quota group is not found since it doesn't exist yet + "/v2/quotas/foo": makeFakeGetQuotaGroupNotFoundHandler(c, "foo"), + + "/v2/changes/42": makeChangesHandler(c), + } + + s.RedirectClientToTestServer(dispatchFakeHandlers(c, routes)) + + rest, err := main.Parser(main.Client()).ParseArgs([]string{"set-quota", "foo", "--memory=999B", "--parent=bar", "snap-a"}) + c.Assert(err, check.IsNil) + c.Check(rest, check.HasLen, 0) + c.Check(s.Stderr(), check.Equals, "") + c.Check(s.Stdout(), check.Equals, "") +} + +func (s *quotaSuite) TestSetQuotaGroupUpdateExistingUnhappy(c *check.C) { + const exists = true + s.testSetQuotaGroupUpdateExistingUnhappy(c, "no options set to change quota group", exists) +} + +func (s *quotaSuite) TestSetQuotaGroupCreateNewUnhappy(c *check.C) { + const exists = false + s.testSetQuotaGroupUpdateExistingUnhappy(c, "cannot create quota group without memory limit", exists) +} + +func (s *quotaSuite) TestSetQuotaGroupCreateNewUnhappyWithParent(c *check.C) { + const exists = false + s.testSetQuotaGroupUpdateExistingUnhappy(c, "cannot create quota group without memory limit", exists, "--parent=bar") } -func (s *quotaSuite) TestCreateQuotaGroup(c *check.C) { - s.RedirectClientToTestServer(makeFakeQuotaPostHandler(c, "ensure", `{"type": "sync", "status-code": 200, "result": []}`, "foo", "bar", []string{"snap-a"}, 999)) +func (s *quotaSuite) TestSetQuotaGroupUpdateExistingUnhappyWithParent(c *check.C) { + const exists = true + s.testSetQuotaGroupUpdateExistingUnhappy(c, "cannot move a quota group to a new parent", exists, "--parent=bar") +} + +func (s *quotaSuite) testSetQuotaGroupUpdateExistingUnhappy(c *check.C, errPattern string, exists bool, args ...string) { + if exists { + // existing group has 1000 memory limit + const getJson = `{ + "type": "sync", + "status-code": 200, + "result": { + "group-name":"foo", + "current": { + "memory": 500 + }, + "constraints": { + "memory": 1000 + } + } + }` - rest, err := main.Parser(main.Client()).ParseArgs([]string{"quota", "foo", "--max-memory=999B", "--parent=bar", "snap-a"}) + s.RedirectClientToTestServer(makeFakeGetQuotaGroupHandler(c, getJson)) + } else { + s.RedirectClientToTestServer(makeFakeGetQuotaGroupNotFoundHandler(c, "foo")) + } + + cmdArgs := append([]string{"set-quota", "foo"}, args...) + _, err := main.Parser(main.Client()).ParseArgs(cmdArgs) + c.Assert(err, check.ErrorMatches, errPattern) + c.Check(s.Stdout(), check.Equals, "") +} + +func (s *quotaSuite) TestSetQuotaGroupUpdateExisting(c *check.C) { + const postJSON = `{"type": "async", "status-code": 202,"change":"42", "result": []}` + fakeHandlerOpts := fakeQuotaGroupPostHandlerOpts{ + action: "ensure", + body: postJSON, + groupName: "foo", + maxMemory: 2000, + } + + const getJsonTemplate = `{ + "type": "sync", + "status-code": 200, + "result": { + "group-name":"foo", + "constraints": { "memory": %d }, + "current": { "memory": 500 } + } + }` + + routes := map[string]http.HandlerFunc{ + "/v2/quotas": makeFakeQuotaPostHandler( + c, + fakeHandlerOpts, + ), + "/v2/quotas/foo": makeFakeGetQuotaGroupHandler(c, fmt.Sprintf(getJsonTemplate, 1000)), + "/v2/changes/42": makeChangesHandler(c), + } + + s.RedirectClientToTestServer(dispatchFakeHandlers(c, routes)) + + // increase the memory limit to 2000 + rest, err := main.Parser(main.Client()).ParseArgs([]string{"set-quota", "foo", "--memory=2000B"}) + c.Assert(err, check.IsNil) + c.Check(rest, check.HasLen, 0) + c.Check(s.Stderr(), check.Equals, "") + c.Check(s.Stdout(), check.Equals, "") + + s.stdout.Reset() + s.stderr.Reset() + + fakeHandlerOpts2 := fakeQuotaGroupPostHandlerOpts{ + action: "ensure", + body: postJSON, + groupName: "foo", + snaps: []string{"some-snap"}, + } + + routes = map[string]http.HandlerFunc{ + "/v2/quotas": makeFakeQuotaPostHandler( + c, + fakeHandlerOpts2, + ), + // the group was updated to have a 2000 memory limit now + "/v2/quotas/foo": makeFakeGetQuotaGroupHandler(c, fmt.Sprintf(getJsonTemplate, 2000)), + + "/v2/changes/42": makeChangesHandler(c), + } + + s.RedirectClientToTestServer(dispatchFakeHandlers(c, routes)) + + // add a snap to the group + rest, err = main.Parser(main.Client()).ParseArgs([]string{"set-quota", "foo", "some-snap"}) c.Assert(err, check.IsNil) c.Check(rest, check.HasLen, 0) c.Check(s.Stderr(), check.Equals, "") @@ -161,7 +417,20 @@ } func (s *quotaSuite) TestRemoveQuotaGroup(c *check.C) { - s.RedirectClientToTestServer(makeFakeQuotaPostHandler(c, "remove", `{"type": "sync", "status-code": 200, "result": []}`, "foo", "", nil, 0)) + const json = `{"type": "async", "status-code": 202,"change": "42"}` + fakeHandlerOpts := fakeQuotaGroupPostHandlerOpts{ + action: "remove", + body: json, + groupName: "foo", + } + + routes := map[string]http.HandlerFunc{ + "/v2/quotas": makeFakeQuotaPostHandler(c, fakeHandlerOpts), + + "/v2/changes/42": makeChangesHandler(c), + } + + s.RedirectClientToTestServer(dispatchFakeHandlers(c, routes)) rest, err := main.Parser(main.Client()).ParseArgs([]string{"remove-quota", "foo"}) c.Assert(err, check.IsNil) @@ -176,28 +445,31 @@ s.RedirectClientToTestServer(makeFakeGetQuotaGroupsHandler(c, `{"type": "sync", "status-code": 200, "result": [ - {"group-name":"aaa","subgroups":["ccc","ddd"],"parent":"zzz","max-memory":1000}, - {"group-name":"ddd","parent":"aaa","max-memory":400}, - {"group-name":"bbb","parent":"zzz","max-memory":1000}, - {"group-name":"yyyyyyy","max-memory":1000}, - {"group-name":"zzz","subgroups":["bbb","aaa"],"max-memory":5000}, - {"group-name":"ccc","parent":"aaa","max-memory":400}, - {"group-name":"xxx","max-memory":9900} + {"group-name":"aaa","subgroups":["ccc","ddd","fff"],"parent":"zzz","constraints":{"memory":1000}}, + {"group-name":"ddd","parent":"aaa","constraints":{"memory":400}}, + {"group-name":"bbb","parent":"zzz","constraints":{"memory":1000},"current":{"memory":400}}, + {"group-name":"yyyyyyy","constraints":{"memory":1000}}, + {"group-name":"zzz","subgroups":["bbb","aaa"],"constraints":{"memory":5000}}, + {"group-name":"ccc","parent":"aaa","constraints":{"memory":400}}, + {"group-name":"fff","parent":"aaa","constraints":{"memory":1000},"current":{"memory":0}}, + {"group-name":"xxx","constraints":{"memory":9900},"current":{"memory":10000}} ]}`)) rest, err := main.Parser(main.Client()).ParseArgs([]string{"quotas"}) c.Assert(err, check.IsNil) c.Check(rest, check.HasLen, 0) c.Check(s.Stderr(), check.Equals, "") - c.Check(s.Stdout(), check.Equals, - "Quota Parent Max-Memory\n"+ - "xxx 9.9kB\n"+ - "yyyyyyy 1000B\n"+ - "zzz 5000B\n"+ - "aaa zzz 1000B\n"+ - "ccc aaa 400B\n"+ - "ddd aaa 400B\n"+ - "bbb zzz 1000B\n") + c.Check(s.Stdout(), check.Equals, ` +Quota Parent Constraints Current +xxx memory=9.9kB memory=10.0kB +yyyyyyy memory=1000B +zzz memory=5000B +aaa zzz memory=1000B +ccc aaa memory=400B +ddd aaa memory=400B +fff aaa memory=1000B +bbb zzz memory=1000B memory=400B +`[1:]) } func (s *quotaSuite) TestGetAllQuotaGroupsInconsistencyError(c *check.C) { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_remove_user.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_remove_user.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_remove_user.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_remove_user.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,10 +22,10 @@ import ( "fmt" + "github.com/jessevdk/go-flags" + "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/i18n" - - "github.com/jessevdk/go-flags" ) var shortRemoveUserHelp = i18n.G("Remove a local system user") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_run.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_run.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_run.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_run.go 2023-03-23 08:10:58.000000000 +0000 @@ -39,8 +39,9 @@ "github.com/jessevdk/go-flags" "github.com/snapcore/snapd/client" - "github.com/snapcore/snapd/dbusutil" + "github.com/snapcore/snapd/desktop/portal" "github.com/snapcore/snapd/dirs" + "github.com/snapcore/snapd/features" "github.com/snapcore/snapd/i18n" "github.com/snapcore/snapd/interfaces" "github.com/snapcore/snapd/logger" @@ -111,7 +112,7 @@ // TRANSLATORS: This should not start with a lowercase letter. "gdb": i18n.G("Run the command with gdb (deprecated, use --gdbserver instead)"), // TRANSLATORS: This should not start with a lowercase letter. - "gdbserver": i18n.G("Run the command with gdbserver"), + "gdbserver": i18n.G("Run the command with gdbserver"), "experimental-gdbserver": "", // TRANSLATORS: This should not start with a lowercase letter. "timer": i18n.G("Run as a timer service with given schedule"), @@ -202,6 +203,10 @@ return fmt.Errorf("timeout waiting for snap system profiles to get updated") } +func (x *cmdRun) Usage() string { + return "[run-OPTIONS] . [...]" +} + func (x *cmdRun) Execute(args []string) error { if len(args) == 0 { return fmt.Errorf(i18n.G("need the application to run as argument")) @@ -248,6 +253,16 @@ return x.snapRunApp(snapApp, args) } +func maybeWaitWhileInhibited(snapName string) error { + // If the snap is inhibited from being used then postpone running it until + // that condition passes. Inhibition UI can be dismissed by the user, in + // which case we don't run the application at all. + if features.RefreshAppAwareness.IsEnabled() { + return waitWhileInhibited(snapName) + } + return nil +} + // antialias changes snapApp and args if snapApp is actually an alias // for something else. If not, or if the args aren't what's expected // for completion, it returns them unchanged. @@ -464,6 +479,12 @@ return fmt.Errorf(i18n.G("cannot find app %q in %q"), appName, snapName) } + if !app.IsService() { + if err := maybeWaitWhileInhibited(snapName); err != nil { + return err + } + } + return x.runSnapConfine(info, app.SecurityTag(), snapApp, "", args) } @@ -693,15 +714,14 @@ return nil } - u, err := userCurrent() + documentPortal := &portal.Document{} + expectedMountPoint, err := documentPortal.GetDefaultMountPoint() if err != nil { - return fmt.Errorf(i18n.G("cannot get the current user: %s"), err) + return err } - xdgRuntimeDir := filepath.Join(dirs.XdgRuntimeDirBase, u.Uid) // If $XDG_RUNTIME_DIR/doc appears to be a mount point, assume // that the document portal is up and running. - expectedMountPoint := filepath.Join(xdgRuntimeDir, "doc") if mounted, err := osutil.IsMounted(expectedMountPoint); err != nil { logger.Noticef("Could not check document portal mount state: %s", err) } else if mounted { @@ -722,20 +742,18 @@ // // As the file is in $XDG_RUNTIME_DIR, it will be cleared over // full logout/login or reboot cycles. + xdgRuntimeDir, err := documentPortal.GetUserXdgRuntimeDir() + if err != nil { + return err + } + portalsUnavailableFile := filepath.Join(xdgRuntimeDir, ".portals-unavailable") if osutil.FileExists(portalsUnavailableFile) { return nil } - conn, err := dbusutil.SessionBus() + actualMountPoint, err := documentPortal.GetMountPoint() if err != nil { - return err - } - - portal := conn.Object("org.freedesktop.portal.Documents", - "/org/freedesktop/portal/documents") - var mountPoint []byte - if err := portal.Call("org.freedesktop.portal.Documents.GetMountPoint", 0).Store(&mountPoint); err != nil { // It is not considered an error if // xdg-document-portal is not available on the system. if dbusErr, ok := err.(dbus.Error); ok && dbusErr.Name == "org.freedesktop.DBus.Error.ServiceUnknown" { @@ -752,7 +770,6 @@ // Sanity check to make sure the document portal is exposed // where we think it is. - actualMountPoint := strings.TrimRight(string(mountPoint), "\x00") if actualMountPoint != expectedMountPoint { return fmt.Errorf(i18n.G("Expected portal at %#v, got %#v"), expectedMountPoint, actualMountPoint) } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_run_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_run_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_run_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_run_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,6 +22,7 @@ import ( "errors" "fmt" + "io/ioutil" "net/http" "os" "os/user" @@ -32,9 +33,13 @@ "gopkg.in/check.v1" snaprun "github.com/snapcore/snapd/cmd/snap" + "github.com/snapcore/snapd/cmd/snaplock/runinhibit" "github.com/snapcore/snapd/dirs" + "github.com/snapcore/snapd/features" "github.com/snapcore/snapd/logger" "github.com/snapcore/snapd/osutil" + "github.com/snapcore/snapd/progress" + "github.com/snapcore/snapd/progress/progresstest" "github.com/snapcore/snapd/sandbox/cgroup" "github.com/snapcore/snapd/sandbox/selinux" "github.com/snapcore/snapd/snap" @@ -89,6 +94,8 @@ s.AddCleanup(snaprun.MockCreateTransientScopeForTracking(func(string, *cgroup.TrackingOptions) error { return nil })) + restoreIsGraphicalSession := snaprun.MockIsGraphicalSession(false) + s.AddCleanup(restoreIsGraphicalSession) } func (s *RunSuite) TestInvalidParameters(c *check.C) { @@ -205,6 +212,132 @@ c.Check(execEnv, testutil.Contains, fmt.Sprintf("TMPDIR=%s", tmpdir)) } +func (s *RunSuite) TestSnapRunAppRunsChecksInhibitionLock(c *check.C) { + defer mockSnapConfine(dirs.DistroLibExecDir)() + + // mock installed snap + snaptest.MockSnapCurrent(c, string(mockYaml), &snap.SideInfo{Revision: snap.R("x2")}) + + var execArg0 string + var execArgs []string + restorer := snaprun.MockSyscallExec(func(arg0 string, args []string, envv []string) error { + execArg0 = arg0 + execArgs = args + return nil + }) + defer restorer() + + c.Assert(runinhibit.LockWithHint("snapname", runinhibit.HintInhibitedForRefresh), check.IsNil) + c.Assert(os.MkdirAll(dirs.FeaturesDir, 0755), check.IsNil) + c.Assert(ioutil.WriteFile(features.RefreshAppAwareness.ControlFile(), []byte(nil), 0644), check.IsNil) + + var called int + restore := snaprun.MockWaitInhibitUnlock(func(snapName string, waitFor runinhibit.Hint, errCh <-chan error) (bool, error) { + called++ + return false, nil + }) + defer restore() + + rest, err := snaprun.Parser(snaprun.Client()).ParseArgs([]string{"run", "--", "snapname.app", "--arg1"}) + c.Assert(err, check.IsNil) + c.Check(called, check.Equals, 2) + c.Assert(rest, check.DeepEquals, []string{"snapname.app", "--arg1"}) + c.Check(execArg0, check.Equals, filepath.Join(dirs.DistroLibExecDir, "snap-confine")) + c.Check(execArgs, check.DeepEquals, []string{ + filepath.Join(dirs.DistroLibExecDir, "snap-confine"), + "snap.snapname.app", + filepath.Join(dirs.CoreLibExecDir, "snap-exec"), + "snapname.app", "--arg1"}) +} + +func (s *RunSuite) TestSnapRunHookNoRuninhibit(c *check.C) { + defer mockSnapConfine(dirs.DistroLibExecDir)() + + // mock installed snap + snaptest.MockSnapCurrent(c, string(mockYaml), &snap.SideInfo{ + Revision: snap.R(42), + }) + + // redirect exec + execArg0 := "" + execArgs := []string{} + execEnv := []string{} + restorer := snaprun.MockSyscallExec(func(arg0 string, args []string, envv []string) error { + execArg0 = arg0 + execArgs = args + execEnv = envv + return nil + }) + defer restorer() + + var called bool + restore := snaprun.MockWaitInhibitUnlock(func(snapName string, waitFor runinhibit.Hint, errCh <-chan error) (bool, error) { + called = true + c.Errorf("WaitInhibitUnlock should not have been called") + return false, nil + }) + defer restore() + + c.Assert(runinhibit.LockWithHint("snapname", runinhibit.HintInhibitedForRefresh), check.IsNil) + c.Assert(os.MkdirAll(dirs.FeaturesDir, 0755), check.IsNil) + c.Assert(ioutil.WriteFile(features.RefreshAppAwareness.ControlFile(), []byte(nil), 0644), check.IsNil) + + // Run a hook from the active revision + _, err := snaprun.Parser(snaprun.Client()).ParseArgs([]string{"run", "--hook=configure", "--", "snapname"}) + c.Assert(err, check.IsNil) + c.Check(execArg0, check.Equals, filepath.Join(dirs.DistroLibExecDir, "snap-confine")) + c.Check(execArgs, check.DeepEquals, []string{ + filepath.Join(dirs.DistroLibExecDir, "snap-confine"), + "snap.snapname.hook.configure", + filepath.Join(dirs.CoreLibExecDir, "snap-exec"), + "--hook=configure", "snapname"}) + c.Check(execEnv, testutil.Contains, "SNAP_REVISION=42") + c.Check(called, check.Equals, false) +} + +func (s *RunSuite) TestSnapRunAppRuninhibitSkipsServices(c *check.C) { + defer mockSnapConfine(dirs.DistroLibExecDir)() + + // mock installed snap + snaptest.MockSnapCurrent(c, string(mockYaml), &snap.SideInfo{Revision: snap.R("x2")}) + + var execArg0 string + var execArgs []string + restorer := snaprun.MockSyscallExec(func(arg0 string, args []string, envv []string) error { + execArg0 = arg0 + execArgs = args + return nil + }) + defer restorer() + + c.Assert(runinhibit.LockWithHint("snapname", runinhibit.HintInhibitedForRefresh), check.IsNil) + c.Assert(os.MkdirAll(dirs.FeaturesDir, 0755), check.IsNil) + c.Assert(ioutil.WriteFile(features.RefreshAppAwareness.ControlFile(), []byte(nil), 0644), check.IsNil) + + var called bool + restore := snaprun.MockWaitInhibitUnlock(func(snapName string, waitFor runinhibit.Hint, errCh <-chan error) (bool, error) { + called = true + c.Errorf("WaitInhibitUnlock should not have been called") + return false, nil + }) + defer restore() + + restore = snaprun.MockConfirmSystemdServiceTracking(func(securityTag string) error { + c.Assert(securityTag, check.Equals, "snap.snapname.svc") + return nil + }) + defer restore() + + rest, err := snaprun.Parser(snaprun.Client()).ParseArgs([]string{"run", "--", "snapname.svc"}) + c.Assert(err, check.IsNil) + c.Check(called, check.Equals, false) + c.Assert(rest, check.DeepEquals, []string{"snapname.svc"}) + c.Check(execArg0, check.Equals, filepath.Join(dirs.DistroLibExecDir, "snap-confine")) + c.Check(execArgs, check.DeepEquals, []string{ + filepath.Join(dirs.DistroLibExecDir, "snap-confine"), "snap.snapname.svc", + filepath.Join(dirs.CoreLibExecDir, "snap-exec"), "snapname.svc"}) +} + func (s *RunSuite) TestSnapRunClassicAppIntegration(c *check.C) { defer mockSnapConfine(dirs.DistroLibExecDir)() @@ -780,11 +913,11 @@ app, outArgs = snaprun.Antialias("alias", inArgs) c.Check(app, check.Equals, "an-app") c.Check(outArgs, check.DeepEquals, []string{ - "99", // COMP_TYPE (no change) - "99", // COMP_KEY (no change) - "11", // COMP_POINT (+1 because "an-app" is one longer than "alias") - "2", // COMP_CWORD (no change) - " ", // COMP_WORDBREAKS (no change) + "99", // COMP_TYPE (no change) + "99", // COMP_KEY (no change) + "11", // COMP_POINT (+1 because "an-app" is one longer than "alias") + "2", // COMP_CWORD (no change) + " ", // COMP_WORDBREAKS (no change) "an-app alias bo-alias", // COMP_LINE (argv[0] changed) "an-app", // argv (arv[0] changed) "alias", @@ -805,12 +938,12 @@ weird2[5] = "alias " for desc, inArgs := range map[string][]string{ - "nil args": nil, - "too-short args": {"alias"}, - "COMP_POINT not a number": mkCompArgs("hello", "alias"), - "COMP_POINT is inside argv[0]": mkCompArgs("2", "alias", ""), - "COMP_POINT is outside argv": mkCompArgs("99", "alias", ""), - "COMP_WORDS[0] is not argv[0]": mkCompArgs("10", "not-alias", ""), + "nil args": nil, + "too-short args": {"alias"}, + "COMP_POINT not a number": mkCompArgs("hello", "alias"), + "COMP_POINT is inside argv[0]": mkCompArgs("2", "alias", ""), + "COMP_POINT is outside argv": mkCompArgs("99", "alias", ""), + "COMP_WORDS[0] is not argv[0]": mkCompArgs("10", "not-alias", ""), "mismatch between argv[0], COMP_LINE and COMP_WORDS, #1": weird1, "mismatch between argv[0], COMP_LINE and COMP_WORDS, #2": weird2, } { @@ -1583,3 +1716,106 @@ _, err := snaprun.Parser(snaprun.Client()).ParseArgs([]string{"run", "--gdbserver", "snapname.app"}) c.Assert(err, check.ErrorMatches, "please install gdbserver on your system") } + +func (s *RunSuite) TestWaitInhibitUnlock(c *check.C) { + var called int + restore := snaprun.MockIsLocked(func(snapName string) (runinhibit.Hint, error) { + called++ + if called < 5 { + return runinhibit.HintInhibitedForRefresh, nil + } + return runinhibit.HintNotInhibited, nil + }) + defer restore() + + notInhibited, err := snaprun.WaitInhibitUnlock("some-snap", runinhibit.HintNotInhibited, nil) + c.Assert(err, check.IsNil) + c.Check(notInhibited, check.Equals, true) + c.Check(called, check.Equals, 5) +} + +func (s *RunSuite) TestWaitInhibitUnlockWaitsForSpecificHint(c *check.C) { + var called int + restore := snaprun.MockIsLocked(func(snapName string) (runinhibit.Hint, error) { + called++ + if called < 5 { + return runinhibit.HintInhibitedGateRefresh, nil + } + return runinhibit.HintInhibitedForRefresh, nil + }) + defer restore() + + notInhibited, err := snaprun.WaitInhibitUnlock("some-snap", runinhibit.HintInhibitedForRefresh, nil) + c.Assert(err, check.IsNil) + c.Check(notInhibited, check.Equals, false) + c.Check(called, check.Equals, 5) +} + +func (s *RunSuite) TestWaitInhibitUnlockWithErrorChannel(c *check.C) { + errCh := make(chan error, 1) + var called int + restore := snaprun.MockIsLocked(func(snapName string) (runinhibit.Hint, error) { + called++ + if called == 1 { + errCh <- fmt.Errorf("boom") + } + return runinhibit.HintInhibitedForRefresh, nil + }) + defer restore() + + notInhibited, err := snaprun.WaitInhibitUnlock("some-snap", runinhibit.HintNotInhibited, errCh) + c.Assert(err, check.IsNil) + c.Check(notInhibited, check.Equals, false) + c.Check(called, check.Equals, 1) + c.Check(s.Stderr(), check.Equals, `boom`) +} + +func (s *RunSuite) TestWaitWhileInhibitedNoop(c *check.C) { + var called int + restore := snaprun.MockIsLocked(func(snapName string) (runinhibit.Hint, error) { + called++ + if called < 2 { + return runinhibit.HintInhibitedGateRefresh, nil + } + return runinhibit.HintNotInhibited, nil + }) + defer restore() + + meter := &progresstest.Meter{} + defer progress.MockMeter(meter)() + + c.Assert(runinhibit.LockWithHint("some-snap", runinhibit.HintInhibitedGateRefresh), check.IsNil) + c.Assert(snaprun.WaitWhileInhibited("some-snap"), check.IsNil) + c.Check(called, check.Equals, 2) + + c.Check(meter.Values, check.HasLen, 0) + c.Check(meter.Written, check.HasLen, 0) + c.Check(meter.Finishes, check.Equals, 0) + c.Check(meter.Labels, check.HasLen, 0) + c.Check(meter.Labels, check.HasLen, 0) +} + +func (s *RunSuite) TestWaitWhileInhibitedTextFlow(c *check.C) { + var called int + restore := snaprun.MockIsLocked(func(snapName string) (runinhibit.Hint, error) { + called++ + if called < 2 { + return runinhibit.HintInhibitedForRefresh, nil + } + return runinhibit.HintNotInhibited, nil + }) + defer restore() + + meter := &progresstest.Meter{} + defer progress.MockMeter(meter)() + + c.Assert(runinhibit.LockWithHint("some-snap", runinhibit.HintInhibitedGateRefresh), check.IsNil) + c.Assert(snaprun.WaitWhileInhibited("some-snap"), check.IsNil) + c.Check(called, check.Equals, 2) + + c.Check(s.Stdout(), check.Equals, "snap package cannot be used now: gate-refresh\n") + c.Check(meter.Values, check.HasLen, 0) + c.Check(meter.Written, check.HasLen, 0) + c.Check(meter.Finishes, check.Equals, 1) + c.Check(meter.Labels, check.DeepEquals, []string{"please wait..."}) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_services.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_services.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_services.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_services.go 2023-03-23 08:10:58.000000000 +0000 @@ -40,6 +40,7 @@ type svcLogs struct { clientMixin + timeMixin N string `short:"n" default:"10"` Follow bool `short:"f"` Positional struct { @@ -84,12 +85,12 @@ }} addCommand("services", shortServicesHelp, longServicesHelp, func() flags.Commander { return &svcStatus{} }, nil, argdescs) addCommand("logs", shortLogsHelp, longLogsHelp, func() flags.Commander { return &svcLogs{} }, - map[string]string{ + timeDescs.also(map[string]string{ // TRANSLATORS: This should not start with a lowercase letter. "n": i18n.G("Show only the given number of lines, or 'all'."), // TRANSLATORS: This should not start with a lowercase letter. "f": i18n.G("Wait for new lines and print them as they come in."), - }, argdescs) + }), argdescs) addCommand("start", shortStartHelp, longStartHelp, func() flags.Commander { return &svcStart{} }, waitDescs.also(map[string]string{ @@ -173,7 +174,11 @@ } for log := range logs { - fmt.Fprintln(Stdout, log) + if s.AbsTime { + fmt.Fprintln(Stdout, log.StringInUTC()) + } else { + fmt.Fprintln(Stdout, log) + } } return nil diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_services_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_services_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_services_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_services_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -315,3 +315,90 @@ // ensure that the fake server api was actually hit c.Check(n, check.Equals, 1) } + +func (s *appOpSuite) TestLogsCommand(c *check.C) { + n := 0 + timestamp := "2021-08-16T17:33:55Z" + message := "Thing occurred\n" + sid := "service1" + pid := "1000" + + s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { + switch n { + case 0: + c.Check(r.URL.Path, check.Equals, "/v2/logs") + c.Check(r.Method, check.Equals, "GET") + w.WriteHeader(200) + _, err := w.Write([]byte{0x1E}) + c.Assert(err, check.IsNil) + + enc := json.NewEncoder(w) + err = enc.Encode(map[string]interface{}{ + "timestamp": timestamp, + "message": message, + "sid": sid, + "pid": pid, + }) + c.Assert(err, check.IsNil) + + default: + c.Fatalf("expected to get 1 requests, now on %d", n+1) + } + n++ + }) + + rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"logs", "snap"}) + c.Assert(err, check.IsNil) + c.Assert(rest, check.HasLen, 0) + + utcTime, err := time.Parse(time.RFC3339, timestamp) + c.Assert(err, check.IsNil) + localTime := utcTime.In(time.Local).Format(time.RFC3339) + + c.Check(s.Stdout(), check.Equals, fmt.Sprintf("%s %s[%s]: %s\n", localTime, sid, pid, message)) + c.Check(s.Stderr(), check.Equals, "") + // ensure that the fake server api was actually hit + c.Check(n, check.Equals, 1) +} + +func (s *appOpSuite) TestLogsCommandWithAbsTimeFlag(c *check.C) { + n := 0 + timestamp := "2021-08-16T17:33:55Z" + message := "Thing occurred" + sid := "service1" + pid := "1000" + + s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { + switch n { + case 0: + c.Check(r.URL.Path, check.Equals, "/v2/logs") + c.Check(r.Method, check.Equals, "GET") + w.WriteHeader(200) + _, err := w.Write([]byte{0x1E}) + c.Assert(err, check.IsNil) + + enc := json.NewEncoder(w) + err = enc.Encode(map[string]interface{}{ + "timestamp": timestamp, + "message": message, + "sid": sid, + "pid": pid, + }) + c.Assert(err, check.IsNil) + + default: + c.Fatalf("expected to get 1 requests, now on %d", n+1) + } + n++ + }) + + rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"logs", "snap", "--abs-time"}) + c.Assert(err, check.IsNil) + c.Assert(rest, check.HasLen, 0) + + c.Check(s.Stdout(), check.Equals, fmt.Sprintf("%s %s[%s]: %s\n", timestamp, sid, pid, message)) + c.Check(s.Stderr(), check.Equals, "") + + // ensure that the fake server api was actually hit + c.Check(n, check.Equals, 1) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_set.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_set.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_set.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_set.go 2023-03-23 08:10:58.000000000 +0000 @@ -52,24 +52,37 @@ Snap installedSnapName ConfValues []string `required:"1"` } `positional-args:"yes" required:"yes"` + + Typed bool `short:"t"` + String bool `short:"s"` } func init() { - addCommand("set", shortSetHelp, longSetHelp, func() flags.Commander { return &cmdSet{} }, waitDescs, []argDesc{ - { - name: "", + addCommand("set", shortSetHelp, longSetHelp, func() flags.Commander { return &cmdSet{} }, + waitDescs.also(map[string]string{ // TRANSLATORS: This should not start with a lowercase letter. - desc: i18n.G("The snap to configure (e.g. hello-world)"), - }, { - // TRANSLATORS: This needs to begin with < and end with > - name: i18n.G(""), + "t": i18n.G("Parse the value strictly as JSON document"), // TRANSLATORS: This should not start with a lowercase letter. - desc: i18n.G("Set (key=value) or unset (key!) configuration value"), - }, - }) + "s": i18n.G("Parse the value as a string"), + }), []argDesc{ + { + name: "", + // TRANSLATORS: This should not start with a lowercase letter. + desc: i18n.G("The snap to configure (e.g. hello-world)"), + }, { + // TRANSLATORS: This needs to begin with < and end with > + name: i18n.G(""), + // TRANSLATORS: This should not start with a lowercase letter. + desc: i18n.G("Set (key=value) or unset (key!) configuration value"), + }, + }) } func (x *cmdSet) Execute(args []string) error { + if x.String && x.Typed { + return fmt.Errorf(i18n.G("cannot use -t and -s together")) + } + patchValues := make(map[string]interface{}) for _, patchValue := range x.Positional.ConfValues { parts := strings.SplitN(patchValue, "=", 2) @@ -80,12 +93,21 @@ if len(parts) != 2 { return fmt.Errorf(i18n.G("invalid configuration: %q (want key=value)"), patchValue) } - var value interface{} - if err := jsonutil.DecodeWithNumber(strings.NewReader(parts[1]), &value); err != nil { - // Not valid JSON-- just save the string as-is. + + if x.String { patchValues[parts[0]] = parts[1] } else { - patchValues[parts[0]] = value + var value interface{} + if err := jsonutil.DecodeWithNumber(strings.NewReader(parts[1]), &value); err != nil { + if x.Typed { + return fmt.Errorf("failed to parse JSON: %w", err) + } + + // Not valid JSON-- just save the string as-is. + patchValues[parts[0]] = parts[1] + } else { + patchValues[parts[0]] = value + } } } diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_set_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_set_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_set_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_set_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -109,6 +109,35 @@ c.Check(s.setConfApiCalls, check.Equals, 1) } +func (s *snapSetSuite) TestSnapSetParseStrictJSON(c *check.C) { + // mock server + s.mockSetConfigServer(c, map[string]interface{}{"a": "b", "c": json.Number("1"), "d": map[string]interface{}{"e": "f"}}) + + _, err := snapset.Parser(snapset.Client()).ParseArgs([]string{"set", "snapname", "-t", `key={"a":"b", "c":1, "d": {"e": "f"}}`}) + c.Assert(err, check.IsNil) + c.Check(s.setConfApiCalls, check.Equals, 1) +} + +func (s *snapSetSuite) TestSnapSetFailParsingWithStrictJSON(c *check.C) { + _, err := snapset.Parser(snapset.Client()).ParseArgs([]string{"set", "snapname", "-t", `key=notJSON`}) + c.Assert(err, check.ErrorMatches, "failed to parse JSON:.*") +} + +func (s *snapSetSuite) TestSnapSetFailOnStrictJSONAndString(c *check.C) { + _, err := snapset.Parser(snapset.Client()).ParseArgs([]string{"set", "snapname", "-t", "-s", "key={}"}) + c.Assert(err, check.ErrorMatches, "cannot use -t and -s together") +} + +func (s *snapSetSuite) TestSnapSetAsString(c *check.C) { + // mock server + value := `{"a":"b", "c":1}` + s.mockSetConfigServer(c, value) + + _, err := snapset.Parser(snapset.Client()).ParseArgs([]string{"set", "snapname", "-s", fmt.Sprintf("key=%s", value)}) + c.Assert(err, check.IsNil) + c.Check(s.setConfApiCalls, check.Equals, 1) +} + func (s *snapSetSuite) mockSetConfigServer(c *check.C, expectedValue interface{}) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign_build.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign_build.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign_build.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign_build.go 2023-03-23 08:10:58.000000000 +0000 @@ -1,7 +1,7 @@ // -*- Mode: Go; indent-tabs-mode: t -*- /* - * Copyright (C) 2014-2015 Canonical Ltd + * Copyright (C) 2014-2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -23,10 +23,11 @@ "fmt" "time" - _ "golang.org/x/crypto/sha3" // expected for digests - "github.com/jessevdk/go-flags" + // expected for digests + _ "golang.org/x/crypto/sha3" + "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/i18n" ) @@ -83,8 +84,11 @@ return err } - gkm := asserts.NewGPGKeypairManager() - privKey, err := gkm.GetByName(string(x.KeyName)) + keypairMgr, err := getKeypairManager() + if err != nil { + return err + } + privKey, err := keypairMgr.GetByName(string(x.KeyName)) if err != nil { // TRANSLATORS: %q is the key name, %v the error message return fmt.Errorf(i18n.G("cannot use %q key: %v"), x.KeyName, err) @@ -104,7 +108,7 @@ } adb, err := asserts.OpenDatabase(&asserts.DatabaseConfig{ - KeypairManager: gkm, + KeypairManager: keypairMgr, }) if err != nil { return fmt.Errorf(i18n.G("cannot open the assertions database: %v"), err) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign.go 2023-03-23 08:10:58.000000000 +0000 @@ -1,7 +1,7 @@ // -*- Mode: Go; indent-tabs-mode: t -*- /* - * Copyright (C) 2014-2015 Canonical Ltd + * Copyright (C) 2014-2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -25,7 +25,6 @@ "github.com/jessevdk/go-flags" - "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/asserts/signtool" "github.com/snapcore/snapd/i18n" ) @@ -81,7 +80,10 @@ return fmt.Errorf(i18n.G("cannot read assertion input: %v"), err) } - keypairMgr := asserts.NewGPGKeypairManager() + keypairMgr, err := getKeypairManager() + if err != nil { + return err + } privKey, err := keypairMgr.GetByName(string(x.KeyName)) if err != nil { // TRANSLATORS: %q is the key name, %v the error message diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_sign_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -26,7 +26,6 @@ . "gopkg.in/check.v1" "github.com/snapcore/snapd/asserts" - snap "github.com/snapcore/snapd/cmd/snap" ) diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_snap_op.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_snap_op.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_snap_op.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_snap_op.go 2023-03-23 08:10:58.000000000 +0000 @@ -474,9 +474,10 @@ Name string `long:"name"` - Cohort string `long:"cohort"` - IgnoreRunning bool `long:"ignore-running" hidden:"yes"` - Positional struct { + Cohort string `long:"cohort"` + IgnoreValidation bool `long:"ignore-validation"` + IgnoreRunning bool `long:"ignore-running" hidden:"yes"` + Positional struct { Snaps []remoteSnapName `positional-arg-name:""` } `positional-args:"yes" required:"yes"` } @@ -592,12 +593,13 @@ dangerous := x.Dangerous || x.ForceDangerous opts := &client.SnapOptions{ - Channel: x.Channel, - Revision: x.Revision, - Dangerous: dangerous, - Unaliased: x.Unaliased, - CohortKey: x.Cohort, - IgnoreRunning: x.IgnoreRunning, + Channel: x.Channel, + Revision: x.Revision, + Dangerous: dangerous, + Unaliased: x.Unaliased, + CohortKey: x.Cohort, + IgnoreValidation: x.IgnoreValidation, + IgnoreRunning: x.IgnoreRunning, } x.setModes(opts) @@ -618,6 +620,9 @@ if x.asksForMode() || x.asksForChannel() { return errors.New(i18n.G("a single snap name is needed to specify mode or channel flags")) } + if x.IgnoreValidation { + return errors.New(i18n.G("a single snap name must be specified when ignoring validation")) + } if x.Name != "" { return errors.New(i18n.G("cannot use instance name when installing multiple snaps")) @@ -763,9 +768,9 @@ defer w.Flush() // TRANSLATORS: the %s is to insert a filler escape sequence (please keep it flush to the column header, with no extra spaces) - fmt.Fprintf(w, i18n.G("Name\tVersion\tRev\tPublisher%s\tNotes\n"), fillerPublisher(esc)) + fmt.Fprintf(w, i18n.G("Name\tVersion\tRev\tSize\tPublisher%s\tNotes\n"), fillerPublisher(esc)) for _, snap := range snaps { - fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", snap.Name, snap.Version, snap.Revision, shortPublisher(esc, snap.Publisher), NotesFromRemote(snap, nil)) + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", snap.Name, snap.Version, snap.Revision, strutil.SizeToStr(snap.DownloadSize), shortPublisher(esc, snap.Publisher), NotesFromRemote(snap, nil)) } return nil @@ -1107,6 +1112,8 @@ // TRANSLATORS: This should not start with a lowercase letter. "cohort": i18n.G("Install the snap in the given cohort"), // TRANSLATORS: This should not start with a lowercase letter. + "ignore-validation": i18n.G("Ignore validation by other snaps blocking the installation"), + // TRANSLATORS: This should not start with a lowercase letter. "ignore-running": i18n.G("Ignore running hooks or applications blocking the installation"), }), nil) addCommand("refresh", shortRefreshHelp, longRefreshHelp, func() flags.Commander { return &cmdRefresh{} }, diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_snap_op_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_snap_op_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_snap_op_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_snap_op_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -229,6 +229,12 @@ func (s *SnapOpSuite) TestInstallNoPATH(c *check.C) { // PATH restored by test tear down os.Setenv("PATH", "/bin:/usr/bin:/sbin:/usr/sbin") + // SUDO_UID env must be unset in this test + if sudoUidEnv, isSet := os.LookupEnv("SUDO_UID"); isSet { + os.Unsetenv("SUDO_UID") + defer os.Setenv("SUDO_UID", sudoUidEnv) + } + s.srv.checker = func(r *http.Request) { c.Check(r.URL.Path, check.Equals, "/v2/snaps/foo") c.Check(DecodedRequestBody(c, r), check.DeepEquals, map[string]interface{}{ @@ -1072,7 +1078,7 @@ c.Check(r.Method, check.Equals, "GET") c.Check(r.URL.Path, check.Equals, "/v2/find") c.Check(r.URL.Query().Get("select"), check.Equals, "refresh") - fmt.Fprintln(w, `{"type": "sync", "result": [{"name": "foo", "status": "active", "version": "4.2update1", "developer": "bar", "publisher": {"id": "bar-id", "username": "bar", "display-name": "Bar", "validation": "unproven"}, "revision":17,"summary":"some summary"}]}`) + fmt.Fprintln(w, `{"type": "sync", "result": [{"name": "foo", "status": "active", "version": "4.2update1", "developer": "bar", "download-size": 436375552, "publisher": {"id": "bar-id", "username": "bar", "display-name": "Bar", "validation": "unproven"}, "revision":17,"summary":"some summary"}]}`) default: c.Fatalf("expected to get 1 requests, now on %d", n+1) } @@ -1082,8 +1088,8 @@ rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"refresh", "--list"}) c.Assert(err, check.IsNil) c.Assert(rest, check.DeepEquals, []string{}) - c.Check(s.Stdout(), check.Matches, `Name +Version +Rev +Publisher +Notes -foo +4.2update1 +17 +bar +-.* + c.Check(s.Stdout(), check.Matches, `Name +Version +Rev +Size +Publisher +Notes +foo +4.2update1 +17 +436MB +bar +-.* `) c.Check(s.Stderr(), check.Equals, "") // ensure that the fake server api was actually hit @@ -1621,6 +1627,26 @@ c.Check(s.srv.n, check.Equals, s.srv.total) } +func (s *SnapOpSuite) TestInstallOneIgnoreValidation(c *check.C) { + s.RedirectClientToTestServer(s.srv.handle) + s.srv.checker = func(r *http.Request) { + c.Check(r.Method, check.Equals, "POST") + c.Check(r.URL.Path, check.Equals, "/v2/snaps/one") + c.Check(DecodedRequestBody(c, r), check.DeepEquals, map[string]interface{}{ + "action": "install", + "ignore-validation": true, + }) + } + _, err := snap.Parser(snap.Client()).ParseArgs([]string{"install", "--ignore-validation", "one"}) + c.Assert(err, check.IsNil) +} + +func (s *SnapOpSuite) TestInstallManyIgnoreValidation(c *check.C) { + s.RedirectClientToTestServer(nil) + _, err := snap.Parser(snap.Client()).ParseArgs([]string{"install", "--ignore-validation", "one", "two"}) + c.Assert(err, check.ErrorMatches, `a single snap name must be specified when ignoring validation`) +} + func (s *SnapOpSuite) TestEnable(c *check.C) { s.srv.total = 3 s.srv.checker = func(r *http.Request) { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_unalias.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_unalias.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_unalias.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_unalias.go 2023-03-23 08:10:58.000000000 +0000 @@ -20,9 +20,9 @@ package main import ( - "github.com/snapcore/snapd/i18n" - "github.com/jessevdk/go-flags" + + "github.com/snapcore/snapd/i18n" ) type cmdUnalias struct { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_whoami.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_whoami.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_whoami.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_whoami.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,9 +22,9 @@ import ( "fmt" - "github.com/snapcore/snapd/i18n" - "github.com/jessevdk/go-flags" + + "github.com/snapcore/snapd/i18n" ) var shortWhoAmIHelp = i18n.G("Show the email the user is logged in with") diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_whoami_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_whoami_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_whoami_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/cmd_whoami_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,11 +22,10 @@ import ( "net/http" - "github.com/snapcore/snapd/osutil" - . "gopkg.in/check.v1" snap "github.com/snapcore/snapd/cmd/snap" + "github.com/snapcore/snapd/osutil" ) func (s *SnapSuite) TestWhoamiLoggedInUser(c *C) { diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/color_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/color_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/color_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/color_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -22,8 +22,6 @@ import ( "os" "runtime" - // "fmt" - // "net/http" "gopkg.in/check.v1" diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/complete.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/complete.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/complete.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/complete.go 2023-03-23 08:10:58.000000000 +0000 @@ -1,7 +1,7 @@ // -*- Mode: Go; indent-tabs-mode: t -*- /* - * Copyright (C) 2016 Canonical Ltd + * Copyright (C) 2016-2021 Canonical Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as @@ -28,7 +28,6 @@ "github.com/jessevdk/go-flags" - "github.com/snapcore/snapd/asserts" "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/i18n" @@ -185,18 +184,25 @@ type keyName string func (s keyName) Complete(match string) []flags.Completion { + keypairManager, err := getKeypairManager() + if err != nil { + return nil + } + keys, err := keypairManager.List() + if err != nil { + return nil + } var res []flags.Completion - asserts.NewGPGKeypairManager().Walk(func(_ asserts.PrivateKey, _ string, uid string) error { - if strings.HasPrefix(uid, match) { - res = append(res, flags.Completion{Item: uid}) + for _, k := range keys { + if strings.HasPrefix(k.Name, match) { + res = append(res, flags.Completion{Item: k.Name}) } - return nil - }) + } return res } type disconnectSlotOrPlugSpec struct { - SnapAndName + SnapAndNameStrict } func (dps disconnectSlotOrPlugSpec) Complete(match string) []flags.Completion { @@ -211,7 +217,7 @@ } type disconnectSlotSpec struct { - SnapAndName + SnapAndNameStrict } // TODO: look at what the previous arg is, and filter accordingly diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/export_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/export_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/export_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/export_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -27,6 +27,7 @@ "github.com/jessevdk/go-flags" "github.com/snapcore/snapd/client" + "github.com/snapcore/snapd/cmd/snaplock/runinhibit" "github.com/snapcore/snapd/image" "github.com/snapcore/snapd/sandbox/cgroup" "github.com/snapcore/snapd/sandbox/selinux" @@ -91,6 +92,9 @@ PrintInstallHint = printInstallHint IsStopping = isStopping + + GetKeypairManager = getKeypairManager + GenerateKey = generateKey ) func HiddenCmd(descr string, completeHidden bool) *cmdInfo { @@ -134,6 +138,9 @@ MaybePrintSum = (*infoWriter).maybePrintSum MaybePrintCohortKey = (*infoWriter).maybePrintCohortKey MaybePrintHealth = (*infoWriter).maybePrintHealth + WaitInhibitUnlock = waitInhibitUnlock + WaitWhileInhibited = waitWhileInhibited + IsLocked = isLocked ) func MockPollTime(d time.Duration) (restore func()) { @@ -377,7 +384,7 @@ } } -func MockDownloadDirect(f func(snapName string, revision snap.Revision, dlOpts image.DownloadOptions) error) (restore func()) { +func MockDownloadDirect(f func(snapName string, revision snap.Revision, dlOpts image.DownloadSnapOptions) error) (restore func()) { old := downloadDirect downloadDirect = f return func() { @@ -408,3 +415,29 @@ osChmod = old } } + +func MockWaitInhibitUnlock(f func(snapName string, waitFor runinhibit.Hint, errCh <-chan error) (bool, error)) (restore func()) { + old := waitInhibitUnlock + waitInhibitUnlock = f + return func() { + waitInhibitUnlock = old + } +} + +func MockIsLocked(f func(snapName string) (runinhibit.Hint, error)) (restore func()) { + old := isLocked + isLocked = f + return func() { + isLocked = old + } +} + +func MockIsGraphicalSession(graphical bool) (restore func()) { + old := isGraphicalSession + isGraphicalSession = func() bool { + return graphical + } + return func() { + isGraphicalSession = old + } +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/inhibit.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/inhibit.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/inhibit.go 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/inhibit.go 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,161 @@ +// -*- Mode: Go; indent-tabs-mode: t -*- + +/* + * Copyright (C) 2020 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +package main + +import ( + "fmt" + "os" + "os/exec" + "time" + + "github.com/snapcore/snapd/cmd/snaplock/runinhibit" + "github.com/snapcore/snapd/i18n" + "github.com/snapcore/snapd/osutil" + "github.com/snapcore/snapd/progress" +) + +func waitWhileInhibited(snapName string) error { + hint, err := runinhibit.IsLocked(snapName) + if err != nil { + return err + } + if hint == runinhibit.HintNotInhibited { + return nil + } + + // wait for HintInhibitedForRefresh set by gate-auto-refresh hook handler + // when it has finished; the hook starts with HintInhibitedGateRefresh lock + // and then either unlocks it or changes to HintInhibitedForRefresh (see + // gateAutoRefreshHookHandler in hooks.go). + // waitInhibitUnlock will return also on HintNotInhibited. + notInhibited, err := waitInhibitUnlock(snapName, runinhibit.HintInhibitedForRefresh, nil) + if err != nil { + return err + } + if notInhibited { + return nil + } + + if isGraphicalSession() && hasZenityExecutable() { + return zenityFlow(snapName, hint) + } + // terminal and headless + return textFlow(snapName, hint) +} + +func inhibitMessage(snapName string, hint runinhibit.Hint) string { + switch hint { + case runinhibit.HintInhibitedForRefresh: + return fmt.Sprintf(i18n.G("snap package %q is being refreshed, please wait"), snapName) + default: + return fmt.Sprintf(i18n.G("snap package cannot be used now: %s"), string(hint)) + } +} + +var isGraphicalSession = func() bool { + return os.Getenv("DISPLAY") != "" || os.Getenv("WAYLAND_DISPLAY") != "" +} + +var hasZenityExecutable = func() bool { + return osutil.ExecutableExists("zenity") +} + +func zenityFlow(snapName string, hint runinhibit.Hint) error { + zenityTitle := i18n.G("Snap package waiting for update") + + // Run zenity with a progress bar. + // TODO: while we are waiting ask snapd for progress updates and send those + // to zenity via stdin. + zenityDied := make(chan error, 1) + + // TODO: use a dbus API to allow integration with native desktop environment. + cmd := exec.Command( + "zenity", + // [generic options] + "--title="+zenityTitle, + // [progress options] + "--progress", + "--text="+inhibitMessage(snapName, hint), + "--pulsate", + ) + if err := cmd.Start(); err != nil { + return err + } + // Make sure that zenity is eventually terminated. + defer cmd.Process.Signal(os.Interrupt) + // Wait for zenity to terminate and store the error code. + // The way we invoke zenity --progress makes it wait forever. + // so it will typically be an external operation. + go func() { + zenityErr := cmd.Wait() + if zenityErr != nil { + zenityErr = fmt.Errorf("zenity error: %s\n", zenityErr) + } + zenityDied <- zenityErr + }() + + if _, err := waitInhibitUnlock(snapName, runinhibit.HintNotInhibited, zenityDied); err != nil { + return err + } + + return nil +} + +func textFlow(snapName string, hint runinhibit.Hint) error { + fmt.Fprintf(Stdout, "%s\n", inhibitMessage(snapName, hint)) + pb := progress.MakeProgressBar() + pb.Spin(i18n.G("please wait...")) + _, err := waitInhibitUnlock(snapName, runinhibit.HintNotInhibited, nil) + pb.Finished() + return err +} + +var isLocked = runinhibit.IsLocked + +// waitInhibitUnlock waits until the runinhibit lock hint has a specific waitFor value +// or isn't inhibited anymore. In addition the optional errCh channel is monitored +// for an error - any error is printed to stderr and immediately returns false (the error +// value isn't returned). +var waitInhibitUnlock = func(snapName string, waitFor runinhibit.Hint, errCh <-chan error) (notInhibited bool, err error) { + // Every 0.5s check if the inhibition file is still present. + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + for { + select { + case err := <-errCh: + if err != nil { + fmt.Fprintf(Stderr, "%s", err) + } + return false, nil + case <-ticker.C: + // Half a second has elapsed, let's check again. + hint, err := isLocked(snapName) + if err != nil { + return false, err + } + if hint == runinhibit.HintNotInhibited { + return true, nil + } + if hint == waitFor { + return false, nil + } + } + } +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/interfaces_common.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/interfaces_common.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/interfaces_common.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/interfaces_common.go 2023-03-23 08:10:58.000000000 +0000 @@ -32,7 +32,12 @@ Name string } -// UnmarshalFlag unmarshals snap and plug or slot name. +// UnmarshalFlag unmarshals the snap and plug or slot name. The following +// combinations are allowed: +// * : +// * +// * : +// Every other combination results in an error. func (sn *SnapAndName) UnmarshalFlag(value string) error { parts := strings.Split(value, ":") sn.Snap = "" @@ -53,3 +58,29 @@ } return nil } + +// SnapAndNameStrict holds a plug or slot name and, optionally, a snap name. +// The following combinations are allowed: +// * : +// * : +// Every other combination results in an error. +type SnapAndNameStrict struct { + SnapAndName +} + +// UnmarshalFlag unmarshals the snap and plug or slot name. The following +// combinations are allowed: +// * : +// * : +// Every other combination results in an error. +func (sn *SnapAndNameStrict) UnmarshalFlag(value string) error { + sn.Snap, sn.Name = "", "" + + parts := strings.Split(value, ":") + if len(parts) != 2 || parts[1] == "" { + return fmt.Errorf(i18n.G("invalid value: %q (want snap:name or :name)"), value) + } + + sn.Snap, sn.Name = parts[0], parts[1] + return nil +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/interfaces_common_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/interfaces_common_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/interfaces_common_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/interfaces_common_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -54,3 +54,33 @@ c.Check(sn.Name, Equals, "") } } + +func (s *SnapAndNameSuite) TestUnmarshalFlagStrict(c *C) { + var sn SnapAndNameStrict + + // Typical + err := sn.UnmarshalFlag("snap:name") + c.Assert(err, IsNil) + c.Check(sn.Snap, Equals, "snap") + c.Check(sn.Name, Equals, "name") + + // Core snap + err = sn.UnmarshalFlag(":name") + c.Assert(err, IsNil) + c.Check(sn.Snap, Equals, "") + c.Check(sn.Name, Equals, "name") + + // Invalid + for _, input := range []string{ + "snap:", // Empty name, should be spelled as "snap" + ":", // Both snap and name empty, makes no sense + "snap:name:more", // Name containing :, probably a typo + "", // Empty input + "snap", // Name empty unsupported for strict + } { + err = sn.UnmarshalFlag(input) + c.Assert(err, ErrorMatches, `invalid value: ".*" \(want snap:name or :name\)`) + c.Check(sn.Snap, Equals, "") + c.Check(sn.Name, Equals, "") + } +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/keymgr.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/keymgr.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/keymgr.go 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/keymgr.go 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,96 @@ +// -*- Mode: Go; indent-tabs-mode: t -*- + +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +package main + +import ( + "errors" + "fmt" + "os" + + "golang.org/x/crypto/ssh/terminal" + + "github.com/snapcore/snapd/asserts" + "github.com/snapcore/snapd/i18n" +) + +type KeypairManager interface { + asserts.KeypairManager + + GetByName(keyNname string) (asserts.PrivateKey, error) + Export(keyName string) ([]byte, error) + List() ([]asserts.ExternalKeyInfo, error) + Delete(keyName string) error +} + +func getKeypairManager() (KeypairManager, error) { + keymgrPath := os.Getenv("SNAPD_EXT_KEYMGR") + if keymgrPath != "" { + keypairMgr, err := asserts.NewExternalKeypairManager(keymgrPath) + if err != nil { + return nil, fmt.Errorf(i18n.G("cannot setup external keypair manager: %v"), err) + } + return keypairMgr, nil + } + keypairMgr := asserts.NewGPGKeypairManager() + return keypairMgr, nil +} + +type takingPassKeyGen interface { + Generate(passphrase string, keyName string) error +} + +type ownSecuringKeyGen interface { + Generate(keyName string) error +} + +func generateKey(keypairMgr KeypairManager, keyName string) error { + switch keyGen := keypairMgr.(type) { + case takingPassKeyGen: + return takePassGenKey(keyGen, keyName) + case ownSecuringKeyGen: + err := keyGen.Generate(keyName) + if _, ok := err.(*asserts.ExternalUnsupportedOpError); ok { + return fmt.Errorf(i18n.G("cannot generate external keypair manager key via snap command, use the appropriate external procedure to create a 4096-bit RSA key under the name/label %q"), keyName) + } + return err + default: + return fmt.Errorf("internal error: unsupported keypair manager %T", keypairMgr) + } +} + +func takePassGenKey(keyGen takingPassKeyGen, keyName string) error { + fmt.Fprint(Stdout, i18n.G("Passphrase: ")) + passphrase, err := terminal.ReadPassword(0) + fmt.Fprint(Stdout, "\n") + if err != nil { + return err + } + fmt.Fprint(Stdout, i18n.G("Confirm passphrase: ")) + confirmPassphrase, err := terminal.ReadPassword(0) + fmt.Fprint(Stdout, "\n") + if err != nil { + return err + } + if string(passphrase) != string(confirmPassphrase) { + return errors.New(i18n.G("passphrases do not match")) + } + + return keyGen.Generate(string(passphrase), keyName) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/keymgr_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/keymgr_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/keymgr_test.go 1970-01-01 00:00:00.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/keymgr_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -0,0 +1,91 @@ +// -*- Mode: Go; indent-tabs-mode: t -*- + +/* + * Copyright (C) 2021 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program 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 program. If not, see . + * + */ + +package main_test + +import ( + "os" + + "gopkg.in/check.v1" + + "github.com/snapcore/snapd/asserts" + snap "github.com/snapcore/snapd/cmd/snap" + "github.com/snapcore/snapd/testutil" +) + +type keymgrSuite struct{} + +var _ = check.Suite(&keymgrSuite{}) + +func (keymgrSuite) TestGPGKeypairManager(c *check.C) { + keypairMgr, err := snap.GetKeypairManager() + c.Check(err, check.IsNil) + c.Check(keypairMgr, check.FitsTypeOf, &asserts.GPGKeypairManager{}) +} + +func mockNopExtKeyMgr(c *check.C) (pgm *testutil.MockCmd, restore func()) { + os.Setenv("SNAPD_EXT_KEYMGR", "keymgr") + pgm = testutil.MockCommand(c, "keymgr", ` +if [ "$1" == "features" ]; then + echo '{"signing":["RSA-PKCS"] , "public-keys":["DER"]}' + exit 0 +fi +exit 1 +`) + r := func() { + pgm.Restore() + os.Unsetenv("SNAPD_EXT_KEYMGR") + } + + return pgm, r +} + +func (keymgrSuite) TestExternalKeypairManager(c *check.C) { + pgm, restore := mockNopExtKeyMgr(c) + defer restore() + + keypairMgr, err := snap.GetKeypairManager() + c.Check(err, check.IsNil) + c.Check(keypairMgr, check.FitsTypeOf, &asserts.ExternalKeypairManager{}) + c.Check(pgm.Calls(), check.HasLen, 1) +} + +func (keymgrSuite) TestExternalKeypairManagerError(c *check.C) { + os.Setenv("SNAPD_EXT_KEYMGR", "keymgr") + defer os.Unsetenv("SNAPD_EXT_KEYMGR") + + pgm := testutil.MockCommand(c, "keymgr", ` +exit 1 +`) + defer pgm.Restore() + + _, err := snap.GetKeypairManager() + c.Check(err, check.ErrorMatches, `cannot setup external keypair manager: external keypair manager "keymgr" \[features\] failed: exit status 1.*`) +} + +func (keymgrSuite) TestExternalKeypairManagerGenerateKey(c *check.C) { + _, restore := mockNopExtKeyMgr(c) + defer restore() + + keypairMgr, err := snap.GetKeypairManager() + c.Check(err, check.IsNil) + + err = snap.GenerateKey(keypairMgr, "key") + c.Check(err, check.ErrorMatches, `cannot generate external keypair manager key via snap command, use the appropriate external procedure to create a 4096-bit RSA key under the name/label "key"`) +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/main.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/main.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/main.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/main.go 2023-03-23 08:10:58.000000000 +0000 @@ -30,11 +30,9 @@ "unicode" "unicode/utf8" - "golang.org/x/xerrors" - "github.com/jessevdk/go-flags" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/xerrors" "github.com/snapcore/snapd/client" "github.com/snapcore/snapd/dirs" @@ -52,11 +50,6 @@ // set User-Agent for when 'snap' talks to the store directly (snap download etc...) snapdenv.SetUserAgentFromVersion(snapdtool.Version, nil, "snap") - if osutil.GetenvBool("SNAPD_DEBUG") || snapdenv.Testing() { - // in tests or when debugging, enforce the "tidy" lint checks - noticef = logger.Panicf - } - // plug/slot sanitization not used by snap commands (except for snap pack // which re-sets it), make it no-op. snap.SanitizePlugsSlots = func(snapInfo *snap.Info) {} @@ -69,8 +62,6 @@ Stderr io.Writer = os.Stderr // overridden for testing ReadPassword = terminal.ReadPassword - // set to logger.Panicf in testing - noticef = logger.Noticef ) type options struct { @@ -173,7 +164,7 @@ r, _ := utf8.DecodeRuneInString(desc) // note IsLower != !IsUpper for runes with no upper/lower. if unicode.IsLower(r) && !strings.HasPrefix(desc, "login.ubuntu.com") && !strings.HasPrefix(desc, cmdName) { - noticef("description of %s's %q is lowercase in locale %q: %q", cmdName, optName, i18n.CurrentLocale(), desc) + panicOnDebug("description of %s's %q is lowercase in locale %q: %q", cmdName, optName, i18n.CurrentLocale(), desc) } } } @@ -187,7 +178,7 @@ // see comment in fixupArg about the >s case return } - noticef("argument %q's %q should begin with < and end with >", cmdName, optName) + panicOnDebug("argument %q's %q should begin with < and end with >", cmdName, optName) } func fixupArg(optName string) string { @@ -591,3 +582,9 @@ return nil } + +func panicOnDebug(msg string, v ...interface{}) { + if osutil.GetenvBool("SNAPD_DEBUG") || snapdenv.Testing() { + logger.Panicf(msg, v...) + } +} diff -Nru ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/main_test.go ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/main_test.go --- ubuntu-core-initramfs-46+ppa4/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/main_test.go 2021-06-08 14:57:50.000000000 +0000 +++ ubuntu-core-initramfs-51.5/vendor/gopath/src/github.com/snapcore/snapd/cmd/snap/main_test.go 2023-03-23 08:10:58.000000000 +0000 @@ -35,14 +35,14 @@ "golang.org/x/crypto/ssh/terminal" . "gopkg.in/check.v1" + snap "github.com/snapcore/snapd/cmd/snap" "github.com/snapcore/snapd/dirs" "github.com/snapcore/snapd/interfaces" "github.com/snapcore/snapd/logger" "github.com/snapcore/snapd/osutil" + "github.com/snapcore/snapd/snapdenv" "github.com/snapcore/snapd/snapdtool" "github.com/snapcore/snapd/testutil" - - snap "github.com/snapcore/snapd/cmd/snap" ) // Hook up check.v1 into the "go test" runner @@ -337,6 +337,13 @@ log, restore := logger.MockLogger() defer restore() + // LintDesc doesn't panic or log if SNAPD_DEBUG or testing are unset + snap.LintDesc("command", "