249 lines
14 KiB
Python
249 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Validate a protected checkout of an already authenticated layer commit.
|
|
|
|
Private artifact-index adapter v0 implementing RFC-0008's indexed layout. This
|
|
does not authenticate an OSTree commit: the service verifies its configured
|
|
remote/signature before supplying the checkout. It never executes layer code.
|
|
"""
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import sys
|
|
|
|
spec = importlib.util.spec_from_file_location('materialize', Path(__file__).with_name('materialize.py'))
|
|
objects = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(objects)
|
|
require = objects.require
|
|
|
|
|
|
def pairs(items):
|
|
result = {}
|
|
for key, value in items:
|
|
require(key not in result, 'Duplicate JSON key: ' + key)
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def digest(value):
|
|
return isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value)
|
|
|
|
|
|
def reject_number(value):
|
|
raise ValueError('Non-integer JSON number: ' + value)
|
|
|
|
|
|
def version(value):
|
|
return type(value) is int and value == 0
|
|
|
|
|
|
def object_shape(value):
|
|
require(isinstance(value, dict), 'Expected payload object')
|
|
kind = value.get('kind')
|
|
require(kind in ('file', 'directory', 'symlink'), 'Invalid object kind')
|
|
field_set(value, ['kind', 'mode', 'uid', 'gid', 'xattrs'] +
|
|
(['sha256'] if kind == 'file' else ['target'] if kind == 'symlink' else []))
|
|
for field, maximum in [('mode', 0o7777), ('uid', 2**32 - 1), ('gid', 2**32 - 1)]:
|
|
require(type(value[field]) is int and 0 <= value[field] <= maximum, 'Invalid object ' + field)
|
|
require(isinstance(value['xattrs'], dict), 'Invalid xattrs')
|
|
for key, data in value['xattrs'].items():
|
|
require(isinstance(key, str) and key and '\0' not in key and isinstance(data, str) and
|
|
len(data) % 2 == 0 and all(c in '0123456789abcdef' for c in data), 'Invalid xattr')
|
|
if kind == 'file':
|
|
require(digest(value['sha256']), 'Invalid file digest')
|
|
if kind == 'symlink':
|
|
require(isinstance(value['target'], str) and value['target'] and '\0' not in value['target'] and
|
|
value['mode'] == 0o777, 'Invalid symlink')
|
|
|
|
|
|
def image_path(path):
|
|
objects.relative(path)
|
|
# Locked private v0 Arch /usr-merge and vendor-defaults profile.
|
|
for alias, destination in [('/bin', '/usr/bin'), ('/sbin', '/usr/bin'),
|
|
('/lib', '/usr/lib'), ('/lib64', '/usr/lib'), ('/etc', '/usr/etc')]:
|
|
if path == alias or path.startswith(alias + '/'):
|
|
return destination + path[len(alias):]
|
|
return path
|
|
|
|
|
|
def authored_files(manifest, rows, sources):
|
|
require(isinstance(sources, dict), 'Invalid locked authored sources')
|
|
used_sources = set()
|
|
declared = {}
|
|
for entry in manifest['spec'].get('files', []):
|
|
path = image_path(entry['path'])
|
|
require(path not in declared, 'Duplicate normalized authored path')
|
|
declared[path] = entry
|
|
authored = {row['path']: row['object'] for row in rows if row['package'] is None}
|
|
require(authored.keys() == declared.keys(), 'Authored payload does not match manifest files')
|
|
for path, entry in declared.items():
|
|
value = authored[path]
|
|
require(value['kind'] == entry.get('type', 'file') and value['mode'] == int(entry['mode'], 8),
|
|
'Authored type/mode differs from manifest')
|
|
# Other identities require locked resolution evidence, not host NSS lookup.
|
|
require(entry['owner'] == entry['group'] == 'root' and value['uid'] == value['gid'] == 0,
|
|
'Authored ownership requires supported locked identity resolution')
|
|
require(not value['xattrs'], 'Undeclared authored xattrs')
|
|
if value['kind'] == 'file':
|
|
source = entry['source']
|
|
relative(source)
|
|
require(source in sources and digest(sources[source]) and sources[source] == value['sha256'],
|
|
'Authored bytes differ from locked source')
|
|
used_sources.add(source)
|
|
if value['kind'] == 'symlink':
|
|
require(value['target'] == entry['target'], 'Authored symlink target mismatch')
|
|
require(used_sources == sources.keys(), 'Unused locked authored source')
|
|
|
|
|
|
def relative(value):
|
|
require(isinstance(value, str) and not value.startswith('/'), 'Expected relative artifact path')
|
|
return objects.relative('/' + value)
|
|
|
|
|
|
def read(root, name):
|
|
rel = relative(name)
|
|
objects.safe_parent(root, rel)
|
|
path = root / rel
|
|
info = path.lstat()
|
|
require(stat.S_ISREG(info.st_mode) and info.st_size <= 16 * 1024 * 1024, 'Invalid metadata file: ' + name)
|
|
raw = path.read_bytes()
|
|
return json.loads(raw, object_pairs_hook=pairs, parse_float=reject_number,
|
|
parse_constant=reject_number), hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def field_set(value, required, optional=()):
|
|
require(isinstance(value, dict) and set(required) <= value.keys() and
|
|
value.keys() <= set(required) | set(optional), 'Unknown or missing index fields')
|
|
|
|
|
|
def alpm_fields(raw):
|
|
fields = {}
|
|
active = None
|
|
for line in raw.decode('utf-8').splitlines():
|
|
if line.startswith('%') and line.endswith('%'):
|
|
require(line not in fields, 'Duplicate ALPM record field')
|
|
fields[line] = []
|
|
active = line
|
|
elif line:
|
|
require(active is not None, 'Invalid ALPM record')
|
|
fields[active].append(line)
|
|
return fields
|
|
|
|
|
|
def check(root):
|
|
require(root.is_absolute() and root.is_dir() and not root.is_symlink(), 'Invalid checkout root')
|
|
require(all(not parent.is_symlink() for parent in root.parents), 'Checkout symlink ancestor')
|
|
manifest, manifest_digest = read(root, 'metadata/manifest.json')
|
|
lock, lock_digest = read(root, 'metadata/lock.json')
|
|
packages, packages_digest = read(root, 'metadata/packages.json')
|
|
files, files_digest = read(root, 'metadata/files.json')
|
|
field_set(lock, ['version', 'manifest_sha256', 'snapshot_id', 'architecture', 'packages_sha256', 'files_sha256', 'requirements', 'authored_sources'], ['requirement_bindings'])
|
|
require(version(lock['version']) and lock['manifest_sha256'] == manifest_digest and
|
|
lock['packages_sha256'] == packages_digest and lock['files_sha256'] == files_digest,
|
|
'Lock does not bind the exact manifest and indexes')
|
|
require(digest(lock['snapshot_id']) and lock['architecture'] == 'x86_64', 'Invalid locked target')
|
|
# Full Layer v1 structural/semantic validation is performed by the Rust reader.
|
|
require(manifest['apiVersion'] == 'archipelago/v1' and manifest['kind'] == 'Layer', 'Wrong manifest kind')
|
|
require(manifest['spec']['architecture'] == lock['architecture'], 'Manifest architecture mismatch')
|
|
field_set(packages, ['version', 'packages'])
|
|
field_set(files, ['version', 'objects'])
|
|
require(version(packages['version']) and version(files['version']), 'Unsupported private index version')
|
|
require(isinstance(packages['packages'], list) and len(packages['packages']) <= 100000, 'Invalid package list')
|
|
require(isinstance(files['objects'], list) and len(files['objects']) <= 1000000, 'Invalid file list')
|
|
package_ids = {}
|
|
package_names = set()
|
|
contribution_inputs = {}
|
|
for package in packages['packages']:
|
|
field_set(package, ['name', 'version', 'architecture', 'identity', 'archive_sha256', 'dependencies', 'alpm'])
|
|
name = package['name']
|
|
require(isinstance(package['version'], str) and package['version'], 'Invalid package version')
|
|
require(isinstance(name, str) and name and all(c.isascii() and (c.isalnum() or c in '@._+-') for c in name), 'Invalid package name')
|
|
require(name not in package_names and digest(package['identity']) and digest(package['archive_sha256']), 'Invalid/duplicate package identity')
|
|
require(package['identity'] not in package_ids and package['architecture'] in ('any', 'x86_64'), 'Invalid package architecture/identity')
|
|
require(isinstance(package['dependencies'], list) and all(isinstance(dep, str) and dep for dep in package['dependencies']) and
|
|
len(set(package['dependencies'])) == len(package['dependencies']), 'Invalid resolved dependency list')
|
|
record = relative(package['alpm'])
|
|
require(str(record) == 'metadata/alpm/' + package['identity'], 'ALPM record outside its package namespace')
|
|
objects.safe_parent(root, record / 'desc')
|
|
data = {}
|
|
for filename in ('desc', 'files', 'mtree'):
|
|
path = root / record / filename
|
|
require(stat.S_ISREG(path.lstat().st_mode), 'Missing original ALPM record')
|
|
require(path.stat().st_size <= 16 * 1024 * 1024, 'Oversized ALPM record')
|
|
data[filename] = path.read_bytes()
|
|
fields = alpm_fields(data['desc'])
|
|
for key, expected in [('%NAME%', name), ('%VERSION%', package['version']), ('%ARCH%', package['architecture'])]:
|
|
require(fields.get(key) == [expected], 'ALPM identity disagrees with package index')
|
|
package_ids[package['identity']] = package
|
|
contribution_inputs[package['identity']] = dict(name=name, version=package['version'],
|
|
architecture=package['architecture'], archive_sha256=package['archive_sha256'],
|
|
dependencies=sorted(package['dependencies']),
|
|
alpm={filename: hashlib.sha256(raw).hexdigest() for filename, raw in data.items()}, objects=[])
|
|
package_names.add(name)
|
|
requirements = lock['requirements']
|
|
require(isinstance(requirements, list) and all(isinstance(name, str) and name in package_names for name in requirements) and
|
|
len(set(requirements)) == len(requirements), 'Invalid locked package requirements')
|
|
declarations = manifest['spec'].get('packages', {}).get('runtime', [])
|
|
declared = {item['name'] for item in declarations}
|
|
if 'requirement_bindings' in lock:
|
|
bindings = lock['requirement_bindings']
|
|
require(isinstance(bindings, list), 'Invalid requirement bindings')
|
|
expected = {item['name'] + item.get('constraint', '') for item in declarations}
|
|
seen = set()
|
|
resolved = set()
|
|
for binding in bindings:
|
|
field_set(binding, ['requirement', 'package'])
|
|
require(isinstance(binding['requirement'], str) and binding['requirement'] in expected and
|
|
binding['requirement'] not in seen and isinstance(binding['package'], str) and
|
|
binding['package'] in package_names, 'Unknown, duplicate or unresolved requirement binding')
|
|
seen.add(binding['requirement'])
|
|
resolved.add(binding['package'])
|
|
require(seen == expected and resolved == set(requirements), 'Incomplete resolved requirement bindings')
|
|
else:
|
|
require(set(requirements) == declared, 'Lock does not retain the declared package requirements')
|
|
indexed = set()
|
|
destinations = set()
|
|
for row in files['objects']:
|
|
field_set(row, ['source', 'path', 'package', 'object'])
|
|
source = relative(row['source'])
|
|
target = row['path']
|
|
objects.relative(target)
|
|
require(target.startswith('/usr/') and target != '/usr/local' and not target.startswith('/usr/local/'), 'Unadapted persistent or boot path')
|
|
package_id = row['package']
|
|
require(package_id is None or (isinstance(package_id, str) and package_id in package_ids), 'Unknown object package')
|
|
prefix = 'payload/files/root/' if package_id is None else 'payload/packages/' + package_id + '/root/'
|
|
require(str(source) == prefix + target.lstrip('/'), 'Payload source/target mapping mismatch')
|
|
require(str(source) not in indexed and (package_id, target) not in destinations, 'Duplicate indexed object')
|
|
objects.safe_parent(root, source)
|
|
object_shape(row['object'])
|
|
require(objects.identity(root / source) == row['object'], 'Payload identity mismatch: ' + str(source))
|
|
indexed.add(str(source))
|
|
destinations.add((package_id, target))
|
|
if package_id is not None:
|
|
contribution_inputs[package_id]['objects'].append(dict(path=target, object=row['object']))
|
|
authored_files(manifest, files['objects'], lock['authored_sources'])
|
|
for identity, contribution in contribution_inputs.items():
|
|
contribution['objects'].sort(key=lambda row: row['path'])
|
|
canonical = json.dumps(contribution, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
|
|
require(hashlib.sha256(canonical).hexdigest() == identity, 'Package contribution identity mismatch')
|
|
# Structural namespace directories may be implicit; all contributed payload
|
|
# objects, including empty directories, must be indexed explicitly.
|
|
parents = set()
|
|
for source in indexed:
|
|
parents.update(str(p) for p in Path(source).parents if str(p) != '.')
|
|
payload = root / 'payload'
|
|
require(payload.is_dir() and not payload.is_symlink(), 'Missing payload tree')
|
|
for parent, directories, leaves in os.walk(payload, followlinks=False):
|
|
for name in directories + leaves:
|
|
path = Path(parent) / name
|
|
rel = path.relative_to(root).as_posix()
|
|
require(rel in indexed or (rel in parents and stat.S_ISDIR(path.lstat().st_mode)), 'Unindexed payload: ' + rel)
|
|
return dict(version=0, manifest=manifest, lock=lock, lock_sha256=lock_digest,
|
|
packages=packages['packages'], objects=files['objects'])
|
|
|
|
|
|
if __name__ == '__main__':
|
|
require(len(sys.argv) == 2, 'Usage: artifact.py AUTHENTICATED_CHECKOUT')
|
|
print(json.dumps(check(Path(sys.argv[1])), separators=(',', ':'), sort_keys=True))
|