kani_install.py
verification/tools/kani_install.py
1#!/usr/bin/env python32"""Read-only content admission for the pinned Kani/native-Rust installation.34The release archive authenticates Kani-owned executables, libraries and models,5with exactly one reviewed, content-pinned replacement of bin/cbmc.6Authored pins identify the previously provisioned native Rust and launcher7inputs. They are bootstrap trust anchors, not a proof of compiler correctness or8of the external ELF loader/system libraries. No tool is executed or installed.9"""10from pathlib import Path, PurePosixPath11import hashlib12import io13import json14import os15import re16import stat17import tarfile18import tomllib192021HERE = Path(__file__).resolve()22PATCH = HERE.with_name('cbmc-nested-offset.patch')23INPUTS = (HERE, HERE.with_suffix('.toml'), HERE.with_name('kani.toml'), PATCH)24PIN = tomllib.loads(INPUTS[2].read_text())25CLOSURE = tomllib.loads(INPUTS[1].read_text())262728def require(condition, message):29 if not condition:30 raise RuntimeError(message)313233def file_hash(path):34 digest = hashlib.sha256()35 with path.open('rb') as stream:36 for block in iter(lambda: stream.read(1024 * 1024), b''):37 digest.update(block)38 return digest.hexdigest()394041def digest(records):42 """Canonical path/type/content digest; timestamps never establish identity."""43 value = hashlib.sha256(b'kani-input-tree-v1\n')44 for name in sorted(records):45 value.update((json.dumps([name, *records[name]], separators=(',', ':'))46 + '\n').encode())47 return value.hexdigest()484950def inventory(root, *, exclude=(), roots=('.',), top_files=()):51 """Inventory selected trees without following an interior symbolic link."""52 records = {}5354 def visit(path, recursive=True):55 name = path.relative_to(root).as_posix()56 if name in exclude:57 return58 mode = path.lstat().st_mode59 require(not stat.S_ISLNK(mode), 'Tool input symlink refused: ' + str(path))60 if stat.S_ISDIR(mode):61 records[name] = ('D',)62 if recursive:63 for child in sorted(path.iterdir()):64 visit(child)65 else:66 require(stat.S_ISREG(mode), 'Tool input is not a regular file: ' + str(path))67 if mode & 0o111:68 require(mode & stat.S_IXUSR and os.access(path, os.X_OK, effective_ids=True),69 'Tool executable lacks owner/effective execute permission: ' + str(path))70 records[name] = ('F', bool(mode & 0o111), path.stat().st_size, file_hash(path))7172 for relative in roots:73 visit(root / relative)74 for relative in top_files:75 folder = root / relative76 visit(folder, recursive=False)77 for child in sorted(folder.iterdir()):78 require(not child.is_symlink(), 'Tool input symlink refused: ' + str(child))79 if not child.is_dir():80 visit(child)81 return records828384def release_inventory(archive, root_name):85 """Decode only after its caller authenticates the complete archive bytes."""86 records = {'.': ('D',)}87 seen = set()88 with tarfile.open(fileobj=io.BytesIO(archive), mode='r:gz') as bundle:89 for member in bundle:90 path = PurePosixPath(member.name)91 require(not path.is_absolute() and '..' not in path.parts92 and path.parts and path.parts[0] == root_name,93 'Unsafe Kani release archive path: ' + member.name)94 name = PurePosixPath(*path.parts[1:]).as_posix()95 require(name not in seen, 'Duplicate Kani release archive member: ' + name)96 seen.add(name)97 if member.isdir():98 records[name] = ('D',)99 else:100 require(member.isfile() and member.sparse is None,101 'Unsupported Kani release archive member: ' + name)102 value = hashlib.sha256()103 stream = bundle.extractfile(member)104 require(stream is not None, 'Missing Kani release file: ' + name)105 with stream:106 for block in iter(lambda: stream.read(1024 * 1024), b''):107 value.update(block)108 records[name] = ('F', bool(member.mode & 0o111), member.size, value.hexdigest())109 require(len(records) > 1, 'Empty Kani release archive')110 return records111112113def rust_inventory(root, target):114 # Compiler/driver/LLVM libraries, all native target libraries and linkers,115 # and the compiler's auxiliary binaries. Rust docs and other targets are116 # deliberately excluded; adding a new proof target needs a new pin/scope.117 return inventory(root, roots=('bin', 'libexec', 'lib/rustlib/' + target),118 top_files=('lib',))119120121def capture(temp):122 """Authenticate selected inputs and return the identity for this invocation."""123 temp = Path(temp).resolve()124 require(type(CLOSURE['schema']) is int and CLOSURE['schema'] == 2125 and CLOSURE['version'] == PIN['version']126 and CLOSURE['target'] == PIN['target']127 and CLOSURE['rust_toolchain'] == PIN['rust_toolchain'],128 'Kani closure pin does not match the verifier pin')129 require(PIN.get('home_dir') == 'kani-fixed-home', 'Only the reviewed corrected Kani home is supported')130 backend = CLOSURE.get('backend')131 require(type(backend) is dict and set(backend) == {'source_commit', 'patch_sha256', 'sha256', 'size'}132 and all(type(backend[name]) is str and re.fullmatch(r'[0-9a-f]{64}', backend[name])133 for name in ('patch_sha256', 'sha256'))134 and type(backend['source_commit']) is str and re.fullmatch(r'[0-9a-f]{40}', backend['source_commit'])135 and type(backend['size']) is int and backend['size'] > 0,136 'Incomplete or malformed corrected backend pin')137 require(PATCH.is_file() and not PATCH.is_symlink() and file_hash(PATCH) == backend['patch_sha256'],138 'Corrected backend source patch differs from its reviewed pin')139 home = temp / 'rustup'140 require(home.is_dir() and not home.is_symlink(),141 'Kani requires a real private Rustup home, not a shared-home symlink')142 provisioned = home / 'toolchains' / PIN['rust_toolchain']143 require((provisioned / 'bin/rustc').is_file(),144 'Kani proof toolchain absent; implicit installation is not permitted')145 name = 'kani-' + PIN['version']146 selected_home = temp / PIN['home_dir']147 require(selected_home.is_dir() and {path.name for path in selected_home.iterdir()} == {name},148 'Kani home must contain only the selected release; setup markers or extra entries are forbidden')149 required = selected_home / name150 require(required.is_dir(), 'Missing corrected Kani installation; integration owner must provision it')151 release = required.resolve(strict=True)152 require(release.is_dir(), 'Missing Kani release installation')153 rust = (release / 'toolchain').resolve(strict=True)154 require(rust == provisioned.resolve(),155 'Kani sysroot and private Rustup pin refer to different toolchains')156 archive = temp / (name + '.tar.gz')157 require(archive.is_file(), 'Missing authenticated Kani release archive')158 archive_bytes = archive.read_bytes()159 require(hashlib.sha256(archive_bytes).hexdigest() == PIN['bundle_sha256'],160 'Kani release archive differs from its published content pin')161 expected = release_inventory(archive_bytes, name)162 del archive_bytes163 base_release = digest(expected)164 original = expected.get('bin/cbmc')165 require(original is not None and original[:2] == ('F', True), 'Archive lacks the executable CBMC base')166 require(backend['sha256'] != original[3], 'Corrected backend must replace the archived backend')167 expected['bin/cbmc'] = ('F', True, backend['size'], backend['sha256'])168 actual = inventory(release, exclude=('toolchain',))169 require(actual == expected, 'Installed Kani tree differs from archive plus its exact corrected backend')170 require((release / 'rust-toolchain-version').read_text().strip() == PIN['rust_toolchain'],171 'Kani release requests a different Rust toolchain')172 native = rust_inventory(rust, PIN['target'])173 launchers = (temp / 'kani-launcher/bin').resolve(strict=True)174 launcher = inventory(launchers)175 require(digest(native) == CLOSURE['native_rust_sha256'],176 'Native proof compiler/sysroot differs from its reviewed content pin')177 require(digest(launcher) == CLOSURE['launcher_sha256'],178 'Kani bootstrap launchers differ from their reviewed content pin')179 return {180 'schema': 2,181 'version': PIN['version'],182 'target': PIN['target'],183 'rust_toolchain': PIN['rust_toolchain'],184 'archive_sha256': PIN['bundle_sha256'],185 'base_release_sha256': base_release,186 'release_sha256': digest(actual),187 'backend': {**backend, 'version': PIN['cbmc_version'],188 'base_sha256': original[3], 'base_size': original[2]},189 'native_rust_sha256': digest(native),190 'launcher_sha256': digest(launcher),191 'release_files': sum(value[0] == 'F' for value in actual.values()),192 'native_rust_files': sum(value[0] == 'F' for value in native.values()),193 'launcher_files': sum(value[0] == 'F' for value in launcher.values()),194 'paths': {'home': str(selected_home.resolve(strict=True)),195 'release': str(release), 'native_rust': str(rust),196 'launchers': str(launchers), 'archive': str(archive.resolve())},197 }198199200def verify(identity, temp):201 """Recheck actual content at consumption; do not trust a saved receipt."""202 require(type(identity) is dict203 and json.dumps(identity, sort_keys=True) == json.dumps(capture(temp), sort_keys=True),204 'Kani tool inputs changed since admission')205206207if __name__ == '__main__':208 import argparse209 parser = argparse.ArgumentParser(description=__doc__)210 parser.add_argument('--temp', type=Path, default=HERE.parents[1] / 'tmp')211 options = parser.parse_args()212 print(json.dumps(capture(options.temp), indent=2))