Files
mikrotik-olsr/tools/routeros.py
T
feedc0de 5bb6e0fe55
Check source / check (push) Successful in 16s
Initial version (not finished, work in progress)
2026-11-18 10:10:39 +01:00

215 lines
9.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""Build custom-key RouterOS v7 packages from official inputs."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import secrets
import shutil
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'vendor/mikrotikpatch'))
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
from npk import NovaPackage, NpkPartID, NpkFileContainer
from toyecc import ECPrivateKey, getcurvebyname
import keypatch
OFFICIAL_NPK_KEY = 'c293ced638a2a33c681fc8de98ee26c54eadc5390c2dfce197d35c83c416cf59'
def load_keys(path):
data = json.loads(Path(path).read_text())
if data.get('format') != 1:
raise ValueError('Unsupported keyset format')
for name in ('eddsa_public', 'kcdsa_public'):
if len(bytes.fromhex(data[name])) != 32:
raise ValueError('Invalid public key length')
if 'eddsa_private' in data:
actual = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(data['eddsa_private'])).public_key().public_bytes_raw().hex()
if actual != data['eddsa_public']:
raise ValueError('Ed25519 keypair mismatch')
if 'kcdsa_private' in data:
actual = ECPrivateKey(int.from_bytes(bytes.fromhex(data['kcdsa_private']), 'little'), getcurvebyname('Curve25519')).pubkey.point.x
if int(actual).to_bytes(32, 'little').hex() != data['kcdsa_public']:
raise ValueError('KCDSA keypair mismatch')
return data
def keygen(args):
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
ed = Ed25519PrivateKey.generate()
curve = getcurvebyname('Curve25519')
scalar = secrets.randbelow(curve.n - 1) + 1
key = ECPrivateKey(scalar, curve)
data = dict(format=1, eddsa_private=ed.private_bytes_raw().hex(),
eddsa_public=ed.public_key().public_bytes_raw().hex(),
kcdsa_private=scalar.to_bytes(32, 'little').hex(),
kcdsa_public=int(key.pubkey.point.x).to_bytes(32, 'little').hex())
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as f:
json.dump(data, f, indent=2)
f.write('\n')
print(f'Created private keyset: {output}. Back it up; never publish it.')
def public(args):
keys = load_keys(args.keys)
data = {k: v for k, v in keys.items() if not k.endswith('_private')}
data['fingerprint_sha256'] = hashlib.sha256(bytes.fromhex(keys['eddsa_public'])).hexdigest()
Path(args.output).write_text(json.dumps(data, indent=2) + '\n')
def packages(npk):
return npk._packages or [npk]
def verify_ed(npk, public_key):
for part in packages(npk):
package = None if part is npk else part
signature = part[NpkPartID.SIGNATURE].data
if len(signature) != 132:
raise ValueError('Expected a RouterOS v7 132-byte package signature')
if npk.get_digest(hashlib.sha1(), package) != signature[:20]:
raise ValueError('Package SHA-1 digest mismatch')
Ed25519PublicKey.from_public_bytes(public_key).verify(signature[68:], npk.get_digest(hashlib.sha256(), package))
def pack_squashfs(source, output):
subprocess.run(['mksquashfs', str(source), str(output), '-noappend', '-comp', 'xz',
'-b', '256k', '-all-root', '-no-xattrs', '-no-progress', '-quiet'], check=True)
def patch_tree(root, mapping):
hits = []
for file in sorted(Path(root).rglob('*')):
if file.is_symlink() or not file.is_file():
continue
data = file.read_bytes()
updated = data
for old, new in mapping.items():
updated = keypatch.replace_key(old, new, updated, str(file.relative_to(root)))
if updated != data:
file.write_bytes(updated)
hits.append(str(file.relative_to(root)))
if not hits:
raise ValueError('No package-verification keys found in the system filesystem')
return hits
def sign_save(npk, keys, output):
# Upstream set_null_block rebuilds SquashFS to preserve alignment.
npk.sign(bytes.fromhex(keys['kcdsa_private']), bytes.fromhex(keys['eddsa_private']))
if not npk.verify(bytes.fromhex(keys['kcdsa_public']), bytes.fromhex(keys['eddsa_public'])):
raise ValueError('Self-verification failed after signing')
npk.save(str(output))
verify_ed(NovaPackage.load(str(output)), bytes.fromhex(keys['eddsa_public']))
def npk_build(args):
keys = load_keys(args.keys)
npk = NovaPackage.load(args.input)
old = bytes.fromhex(args.source_key)
verify_ed(npk, old)
os.environ['ARCH'] = args.arch
mapping = {old: bytes.fromhex(keys['eddsa_public'])}
changed_kernel = False
changed_system = False
for pkg in packages(npk):
if pkg[NpkPartID.NAME_INFO].data.name != 'system':
continue
if not args.patch_system:
raise ValueError('System package requires --patch-system, not just re-signing')
for part in pkg:
if part.id == NpkPartID.FILE_CONTAINER:
container = NpkFileContainer.unserialize_from(part.data)
for item in container:
if item.name in (b'boot/kernel', b'boot/initrd.rgz'):
original = item.data
item.data = keypatch.patch_kernel(original, mapping)
if original == item.data:
raise ValueError('Kernel verification key was not patched')
changed_kernel = True
part.data = container.serialize()
elif part.id == NpkPartID.SQUASHFS:
with tempfile.TemporaryDirectory() as temporary:
work = Path(temporary)
image = work / 'input.sfs'
tree = work / 'root'
image.write_bytes(part.data)
subprocess.run(['unsquashfs', '-no-progress', '-d', str(tree), str(image)], check=True, stdout=subprocess.DEVNULL)
print('Patched system files:', ', '.join(patch_tree(tree, mapping)))
pack_squashfs(tree, work / 'output.sfs')
part.data = (work / 'output.sfs').read_bytes()
changed_system = True
if args.patch_system and not (changed_system and changed_kernel):
raise ValueError('Expected both a system filesystem and a kernel; unsupported package layout')
sign_save(npk, keys, args.output)
print(f'Created and verified {args.output}')
def create(args):
keys = load_keys(args.keys)
npk = NovaPackage.load(args.template)
verify_ed(npk, bytes.fromhex(args.source_key))
if npk._packages or npk[NpkPartID.NAME_INFO].data.name == 'system':
raise ValueError('Use a small official add-on NPK (for example gps) as the template')
if not args.name.isascii() or not args.name.replace('-', '').isalnum() or len(args.name) > 15:
raise ValueError('Package name must be 1-15 ASCII letters, digits, or hyphens')
npk[NpkPartID.NAME_INFO].data.name = args.name
npk[NpkPartID.DESCRIPTION].data = args.description.encode()
# Never inherit an unrelated package installation or removal script.
npk._parts = [p for p in npk._parts if p.id not in (NpkPartID.INSTALL_SCRIPT, NpkPartID.UNINSTALL_SCRIPT, NpkPartID.FILE_CONTAINER)]
with tempfile.TemporaryDirectory() as temporary:
image = Path(temporary) / 'package.sfs'
pack_squashfs(args.root, image)
npk[NpkPartID.SQUASHFS].data = image.read_bytes()
sign_save(npk, keys, args.output)
print(f'Created and verified {args.output}')
def netinstall(args):
keys = load_keys(args.keys)
source = Path(args.input)
output = Path(args.output)
if source.resolve() == output.resolve():
raise ValueError('Keep the official installer: use a separate output path')
os.environ['ARCH'] = 'x86'
keypatch.patch_netinstall({bytes.fromhex(args.source_key): bytes.fromhex(keys['eddsa_public'])}, str(source), str(output))
if source.read_bytes() == output.read_bytes():
raise ValueError('Installer was not modified')
if source.read_bytes().startswith(b'\x7fELF'):
output.chmod(source.stat().st_mode | 0o111)
if len(source.read_bytes()) != len(output.read_bytes()):
raise ValueError('ELF size changed unexpectedly')
print(f'Created {output}')
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
p = sub.add_parser('keygen'); p.add_argument('--output', required=True); p.set_defaults(func=keygen)
p = sub.add_parser('public-key'); p.add_argument('--keys', required=True); p.add_argument('--output', required=True); p.set_defaults(func=public)
for name, function in [('netinstall', netinstall), ('npk', npk_build), ('create', create)]:
p = sub.add_parser(name)
p.add_argument('--keys', required=True); p.add_argument('--output', required=True)
p.add_argument('--source-key', default=OFFICIAL_NPK_KEY, help='Public Ed25519 key of the input publisher')
if name == 'create':
p.add_argument('--template', required=True); p.add_argument('--root', required=True)
p.add_argument('--name', required=True); p.add_argument('--description', default='Custom package')
else:
p.add_argument('input')
if name == 'npk':
p.add_argument('--arch', choices=['arm', 'arm64', 'x86', 'mipsbe', 'mmips', 'smips', 'ppc'], required=True)
p.add_argument('--patch-system', action='store_true')
p.set_defaults(func=function)
args = parser.parse_args()
args.func(args)
if __name__ == '__main__':
main()