Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,8 @@ The kernel exposes a filesystem interface (mounted at `/sys/fs/multikernel/`) th
python = "^3.8"
pylibfdt = "^1.7.0" # Device tree parsing (from dtc project)
cryptography = ">=3.1" # Signing spawn kernels (kerf sign)
zstandard = ">=0.15" # Unpacking zstd compressed kernels
lz4 = ">=3.0" # Unpacking LZ4 compressed kernels
```

### Installation
Expand Down
4 changes: 4 additions & 0 deletions packaging/nfpm.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ overrides:
- python3-pyudev (>= 0.24)
- python3-cryptography (>= 3.1)
- python3-libfdt (>= 1.7.0)
- python3-zstandard
- python3-lz4
rpm:
depends:
- python3 >= 3.9
Expand All @@ -42,3 +44,5 @@ overrides:
- python3-pyudev >= 0.24
- python3-cryptography >= 3.1
- python3-libfdt >= 1.7.0
- python3-zstandard
- python3-lz4
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ click = "^8.0.0"
pyyaml = "^6.0"
pyudev = "^0.24.0"
cryptography = ">=3.1"
zstandard = ">=0.15"
lz4 = ">=3.0"

[tool.poetry.group.dev.dependencies]
pytest = "^7.0.0"
Expand Down
65 changes: 44 additions & 21 deletions src/kerf/vmlinuz.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
"""

import bz2
import importlib
import lzma
import os
import struct
import subprocess
import zlib

from .exceptions import KerfError
Expand All @@ -46,6 +46,10 @@ class VmlinuzError(KerfError):
BZIMAGE_PAYLOAD_LENGTH = 0x24C
BZIMAGE_HEADER_SIZE = 0x250

LZ4_LEGACY_MAGIC = b"\x02\x21\x4c\x18"
# A legacy LZ4 block holds at most this much data
LZ4_LEGACY_BLOCK_SIZE = 8 << 20


def is_bzimage(data: bytes) -> bool:
"""Check for the x86 boot protocol magic in a kernel image."""
Expand All @@ -68,45 +72,64 @@ def _bunzip2(payload: bytes) -> bytes:
return bz2.BZ2Decompressor().decompress(payload)


def _decompress_cli(argv: list, payload: bytes) -> bytes:
def _codec(module: str):
"""Import a compression library that only some kernels need."""
try:
proc = subprocess.run(
argv, input=payload, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, check=False,
)
except FileNotFoundError:
return importlib.import_module(module)
except ImportError:
raise VmlinuzError(
f"'{argv[0]}' binary not found, required to decompress this kernel"
f"the Python module '{module.partition('.')[0]}' is required to decompress this kernel"
) from None
# The CLI tools complain about data trailing the compressed stream
# (relocations, appended size), but still emit the decoded output
if not proc.stdout:
raise VmlinuzError(f"{argv[0]} failed to decompress kernel payload")
return proc.stdout


# The decompressors stop at the end of the compressed stream, which the
# kernel build follows with the size of the vmlinux


def _unzstd(payload: bytes) -> bytes:
try:
import zstandard
except ImportError:
return _decompress_cli(["zstd", "-d", "-c"], payload)
zstandard = _codec("zstandard")
try:
return zstandard.ZstdDecompressor().decompressobj().decompress(payload)
except zstandard.ZstdError as e:
raise VmlinuzError(f"kernel payload decompression failed: {e}") from e


def _unlz4(payload: bytes) -> bytes:
return _decompress_cli(["lz4", "-d", "-c"], payload)
def _unlz4_legacy(payload: bytes) -> bytes:
"""Decompress the legacy LZ4 format, the one the kernel build uses (lz4 -l)."""
block = _codec("lz4.block")
vmlinux = []
offset = len(LZ4_LEGACY_MAGIC)
while offset + 4 <= len(payload):
size = struct.unpack_from("<I", payload, offset)[0]
offset += 4
# The appended vmlinux size reads as a block that the payload has no room for.
if not 0 < size <= len(payload) - offset:
break
try:
vmlinux.append(block.decompress(
payload[offset:offset + size], uncompressed_size=LZ4_LEGACY_BLOCK_SIZE
))
except block.LZ4BlockError as e:
raise VmlinuzError(f"kernel payload decompression failed: {e}") from e
offset += size
return b"".join(vmlinux)


def _unlz4_frame(payload: bytes) -> bytes:
frame = _codec("lz4.frame")
try:
return frame.LZ4FrameDecompressor().decompress(payload)
except RuntimeError as e:
raise VmlinuzError(f"kernel payload decompression failed: {e}") from e


_DECOMPRESSORS = [
(b"\x1f\x8b", "gzip", _gunzip),
(b"\xfd7zXZ\x00", "xz", _unxz),
(b"BZh", "bzip2", _bunzip2),
(b"\x28\xb5\x2f\xfd", "zstd", _unzstd),
(b"\x02\x21\x4c\x18", "lz4", _unlz4),
(b"\x04\x22\x4d\x18", "lz4", _unlz4),
(LZ4_LEGACY_MAGIC, "lz4", _unlz4_legacy),
(b"\x04\x22\x4d\x18", "lz4", _unlz4_frame),
(b"\x5d\x00", "lzma", _unlzma),
]

Expand Down
50 changes: 49 additions & 1 deletion tests/test_vmlinuz.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,14 @@

import pytest

from kerf.vmlinuz import VmlinuzError, extract_vmlinux, is_bzimage, open_kernel_fd
from kerf.vmlinuz import (
LZ4_LEGACY_BLOCK_SIZE,
LZ4_LEGACY_MAGIC,
VmlinuzError,
extract_vmlinux,
is_bzimage,
open_kernel_fd,
)


def make_elf64(body: bytes = b"kernel code segment") -> bytes:
Expand Down Expand Up @@ -136,6 +143,47 @@ def test_extracts_zstd_payload(self):
data = make_bzimage(payload)
assert extract_vmlinux(data) == elf

def test_extracts_lz4_payload(self):
block = pytest.importorskip("lz4.block")
# More than one block of the legacy format, which is what lz4 -l writes
elf = make_elf64(os.urandom(64) * (LZ4_LEGACY_BLOCK_SIZE // 64) + b"second block")
blocks = [
block.compress(elf[offset:offset + LZ4_LEGACY_BLOCK_SIZE], store_size=False)
for offset in range(0, len(elf), LZ4_LEGACY_BLOCK_SIZE)
]
assert len(blocks) == 2
payload = LZ4_LEGACY_MAGIC + b"".join(
struct.pack("<I", len(compressed)) + compressed for compressed in blocks
) + struct.pack("<I", len(elf))
data = make_bzimage(payload)
assert extract_vmlinux(data) == elf

def test_extracts_lz4_frame_payload(self):
frame = pytest.importorskip("lz4.frame")
elf = make_elf64()
payload = frame.compress(elf) + struct.pack("<I", len(elf))
data = make_bzimage(payload)
assert extract_vmlinux(data) == elf

def test_rejects_corrupt_lz4_payload(self):
pytest.importorskip("lz4.block")
payload = LZ4_LEGACY_MAGIC + struct.pack("<I", 8) + b"\xff" * 8 + struct.pack("<I", 64)
with pytest.raises(VmlinuzError, match="decompression failed"):
extract_vmlinux(make_bzimage(payload))

@pytest.mark.parametrize("magic, module", [
(b"\x28\xb5\x2f\xfd", "zstandard"),
(LZ4_LEGACY_MAGIC, "lz4"),
(b"\x04\x22\x4d\x18", "lz4"),
])
def test_names_the_module_a_kernel_needs(self, monkeypatch, magic, module):
def missing(name):
raise ImportError(name)

monkeypatch.setattr("importlib.import_module", missing)
with pytest.raises(VmlinuzError, match=f"Python module '{module}' is required"):
extract_vmlinux(make_bzimage(magic + b"payload"))

def test_truncates_trailing_relocations(self):
elf = make_elf64()
data = make_bzimage(gzip.compress(elf + b"RELOCATION-TABLE" * 8))
Expand Down
Loading