#!/bin/sh
set -eu
command -v python3 >/dev/null 2>&1 || { echo 'Python 3.5+ is required' >&2; exit 1; }
command -v openssl >/dev/null 2>&1 || { echo 'OpenSSL is required' >&2; exit 1; }
if [ "$(id -u)" -ne 0 ]; then
    echo 'Download and review this installer, then run: sudo sh install-linux.sh' >&2
    exit 1
fi
exec python3 -I - download --version "${VG_VERSION:-3.0.261116}" --base-url "${VG_DOWNLOAD_BASE:-https://videograce.ru/download}" "$@" <<'VG_SIGNED_BOOTSTRAP_PYTHON'
#!/usr/bin/env python3
"""Signed Linux releases. Python 3.5+, OpenSSL 1.0.2+. No network PKI lookup."""
from __future__ import print_function
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import urllib.request

# Trust is anchored in this reviewed bootstrap / installed verifier, never in
# a certificate supplied by an untrusted download. Rotation requires an update
# of this trusted code. Certificate expiry is checked by the signing tool;
# verification pins the certificate and verifies content, not live PKI/OCSP.
PINNED_CERTIFICATE = '''-----BEGIN CERTIFICATE-----
MIIHRDCCBSygAwIBAgIMBH4snkCkafo4jMbbMA0GCSqGSIb3DQEBCwUAMFkxCzAJ
BgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMS8wLQYDVQQDEyZH
bG9iYWxTaWduIEdDQyBSNDUgQ29kZVNpZ25pbmcgQ0EgMjAyMDAeFw0yNjA0MjMx
NDMwNTFaFw0yNzA0MjQxNDMwNTFaMIGOMQswCQYDVQQGEwJSVTEZMBcGA1UECBMQ
U2FpbnQgUGV0ZXJzYnVyZzEZMBcGA1UEBxMQU2FpbnQgUGV0ZXJzYnVyZzEQMA4G
A1UEChMHVEFTIExMQzEQMA4GA1UEAxMHVEFTIExMQzElMCMGCSqGSIb3DQEJARYW
c3VwcG9ydEB2aWRlb2dyYWNlLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC
AgoCggIBAKle17gARPuchzMwtltNTWax5KJnJE9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RodHRwOi8vY3JsLmdsb2JhbHNpZ24uY29tL2dzZ2NjcjQ1Y29kZXNp
Z25jYTIwMjAuY3JsMCEGA1UdEQQaMBiBFnN1cHBvcnRAdmlkZW9ncmFjZS5jb20w
EwYDVR0lBAwwCgYIKwYBBQUHAwMwHwYDVR0jBBgwFoAU2rONwCSQo2t30wygWd0h
Z2R2C3gwHQYDVR0OBBYEFOXZ1vslFtJ5dCoPQJnut89hqA/nMA0GCSqGSIb3DQEB
CwUAA4ICAQCNGkT7dfO454A2uWLeTMuQeM5zKq20OxNtvFyA8pBQUMlaD/001U39
CwCVkENPZU0isxy+gzGEJ8PzjkacJU7pEyTUAub+bhGo9UEFSye9J2shoN+6B7GD
zoiKKBmJHv63Hn4ye4fa9+J7fG08xbzE0qakTyv8xx1eCHyG6abezM967KlxdX4W
0t/hxhbMrryhpi69jEpqyqVK11Kyqet8SUIPK4pp/O2dDVEFyRHHOKpLr15OPG1g
iYqZpNnH8uN1vVnTJtyjNGr8U+ZEVxOJCwuLwQvrhnOYBBTSnaxmPxQIKcfxnzU4
eFh5qvuCSwLjh1OAbm7B4knfn33tp1v6uKfLnyd+kTrEtotYvcLKMhYbn5Xd8D4d
xcrkP9AzFfrNf4pA80RUMaYV8OnW6lIj9htNd+VwEbzahYaHa8LEggYyKSKmnIMO
4NWoWu8tSU0JLo2kjiezBemdyBAIUrk+qe5QpMiEpVNZtgpKBX/x7WtOyS/BVSiU
CqEeRjoZUDRP1LBKfnGk+/HOhGJmh6RDmL5pcHluoAoOdfye4Npgq6nhF2fbzQHN
qA9++IW6XrJKkiYF0uMp3UOe3NaHj5ZxhrledDTIBzsQwwbhszjcTYKDCflBeDZp
VxNaPRxwaDmLcHPymDFQ9qnR4tjHvHDCeZXt5fJ/4H3BqwYuAF6azw==
-----END CERTIFICATE-----
'''
FORMAT = 'videograce-linux-release-v1'
METADATA = ('release-manifest.json', 'release-manifest.json.p7s')
MAX_MANIFEST = 32 * 1024 * 1024
MAX_SIGNATURE = 1024 * 1024
TARGET = Path('/opt/VideoGrace/Server')


def digest(path):
    result = hashlib.sha256()
    with Path(path).open('rb') as source:
        for block in iter(lambda: source.read(1024 * 1024), b''):
            result.update(block)
    return result.hexdigest()


def safe_path(value):
    if not isinstance(value, str) or not value or '\\' in value or '\x00' in value:
        raise ValueError('Invalid release path')
    path = PurePosixPath(value)
    if path.is_absolute() or '..' in path.parts or str(path) != value or value == '.':
        raise ValueError('Unsafe release path: ' + value)
    return value


def no_duplicates(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('Duplicate manifest field: ' + key)
        result[key] = value
    return result


def validate_manifest(data):
    if data.get('format') != FORMAT or data.get('platform') != 'linux-x64':
        raise ValueError('Unsupported release format/platform')
    version = data.get('version', '')
    if not isinstance(version, str) or not re.match(r'^\d+\.\d+\.\d+$', version):
        raise ValueError('Invalid release version')
    root = 'VideoGraceServer-' + version + '-x64'
    if data.get('root') != root or data.get('archive', {}).get('name') != root + '.tar.bz2':
        raise ValueError('Release name/version mismatch')
    entries = data.get('files')
    if not isinstance(entries, dict) or not entries:
        raise ValueError('Empty file manifest')
    for name, spec in entries.items():
        safe_path(name)
        if name in METADATA:
            raise ValueError('Reserved metadata path')
        validate_spec(spec)
    validate_spec(data['archive'])
    for required in ('install.sh', 'update.sh', 'vgserver/VideoGraceServer'):
        if required not in entries:
            raise ValueError('Missing required release file: ' + required)
    return data


def validate_spec(spec):
    if not isinstance(spec, dict) or not re.match(r'^[a-f0-9]{64}$', spec.get('sha256', '')):
        raise ValueError('Invalid SHA256 specification')
    if type(spec.get('size')) is not int or spec['size'] < 0:
        raise ValueError('Invalid size specification')


def verify_manifest(manifest, signature):
    manifest, signature = Path(manifest), Path(signature)
    if not manifest.is_file() or not signature.is_file():
        raise ValueError('Signed release manifest is required; unsigned releases are not accepted')
    if manifest.stat().st_size > MAX_MANIFEST or signature.stat().st_size > MAX_SIGNATURE:
        raise ValueError('Release metadata is too large')
    # Read once: parse exactly the bytes whose signature was verified.
    raw, sig = manifest.read_bytes(), signature.read_bytes()
    with tempfile.TemporaryDirectory(prefix='vg-release-check-') as folder:
        folder = Path(folder)
        (folder / 'manifest').write_bytes(raw)
        (folder / 'signature').write_bytes(sig)
        (folder / 'signer.pem').write_text(PINNED_CERTIFICATE)
        result = subprocess.call([
            'openssl', 'cms', '-verify', '-binary', '-inform', 'DER',
            '-in', str(folder / 'signature'), '-content', str(folder / 'manifest'),
            '-nointern', '-certfile', str(folder / 'signer.pem'), '-noverify',
            '-out', os.devnull,
        ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if result != 0:
            raise ValueError('Release signature verification FAILED')
    return validate_manifest(json.loads(raw.decode('utf-8'), object_pairs_hook=no_duplicates))


def check_file(path, spec):
    path = Path(path)
    if path.is_symlink() or not path.is_file() or path.stat().st_size != spec['size'] or digest(path) != spec['sha256']:
        raise ValueError('Release checksum mismatch: ' + str(path))


def tree_files(root):
    result = {}
    for current, directories, files in os.walk(str(root), followlinks=False):
        for name in directories + files:
            path = Path(current) / name
            mode = path.lstat().st_mode
            if stat.S_ISLNK(mode) or not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)):
                raise ValueError('Links/special files are forbidden: ' + str(path))
        for name in files:
            path = Path(current) / name
            relative = path.relative_to(root).as_posix()
            if relative not in METADATA:
                result[safe_path(relative)] = path
    return result


def verify_tree(root, data):
    files = tree_files(Path(root))
    if set(files) != set(data['files']):
        raise ValueError('Release file inventory differs (missing or unexpected files)')
    for name, path in files.items():
        check_file(path, data['files'][name])


def verify_directory(root):
    root = Path(root).resolve()
    data = verify_manifest(root / METADATA[0], root / METADATA[1])
    if root.name != data['root']:
        raise ValueError('Release directory/version mismatch')
    verify_tree(root, data)
    return data


def inspect_archive(archive, data):
    # Do this only after verifying the signed archive checksum.
    with tarfile.open(str(archive), 'r:bz2') as bundle:
        names = set()
        regular = set()
        for member in bundle.getmembers():
            name = safe_path(member.name.rstrip('/'))
            if name in names or not (member.isfile() or member.isdir()):
                raise ValueError('Duplicate/unsafe archive member: ' + name)
            names.add(name)
            if name != data['root'] and not name.startswith(data['root'] + '/'):
                raise ValueError('Unexpected archive root')
            if member.isfile():
                relative = name[len(data['root']) + 1:]
                if relative not in data['files'] or member.size != data['files'][relative]['size']:
                    raise ValueError('Archive file inventory differs')
                regular.add(relative)
        if regular != set(data['files']):
            raise ValueError('Archive is missing signed files')


def verify_archive(archive, manifest, signature):
    data = verify_manifest(manifest, signature)
    if Path(archive).name != data['archive']['name']:
        raise ValueError('Archive filename/version mismatch')
    check_file(archive, data['archive'])
    inspect_archive(archive, data)
    return data


def extract_verified(archive, destination, data, manifest, signature):
    # destination is a newly created private directory, with no attacker links.
    with tarfile.open(str(archive), 'r:bz2') as bundle:
        bundle.extractall(str(destination))
    root = Path(destination) / data['root']
    verify_tree(root, data)
    shutil.copyfile(str(manifest), str(root / METADATA[0]))
    shutil.copyfile(str(signature), str(root / METADATA[1]))
    return root


def create_manifest(archive, root, version, destination):
    root = Path(root).resolve()
    if any((root / name).exists() for name in METADATA):
        raise ValueError('Remove old release metadata before creating a new archive')
    files = {name: {'size': path.stat().st_size, 'sha256': digest(path)} for name, path in tree_files(root).items()}
    archive = Path(archive)
    data = validate_manifest({'format': FORMAT, 'platform': 'linux-x64', 'version': version,
        'root': root.name, 'archive': {'name': archive.name, 'size': archive.stat().st_size, 'sha256': digest(archive)}, 'files': files})
    inspect_archive(archive, data)
    # Check payload hashes inside the archive, not just the staging directory.
    with tarfile.open(str(archive), 'r:bz2') as bundle:
        for member in bundle.getmembers():
            if member.isfile():
                source = bundle.extractfile(member)
                value = hashlib.sha256()
                for block in iter(lambda: source.read(1024 * 1024), b''):
                    value.update(block)
                if value.hexdigest() != files[member.name[len(root.name) + 1:]]['sha256']:
                    raise ValueError('Archive and staging tree differ')
    Path(destination).write_text(json.dumps(data, ensure_ascii=True, sort_keys=True, indent=2) + '\n')


def fetch(url, destination, limit):
    if not url.startswith('https://'):
        raise ValueError('Only HTTPS download URLs are accepted')
    total = 0
    with urllib.request.urlopen(url, timeout=60) as response, Path(destination).open('wb') as output:
        if not response.geturl().startswith('https://'):
            raise ValueError('Redirect outside HTTPS')
        while True:
            chunk = response.read(1024 * 1024)
            if not chunk:
                break
            total += len(chunk)
            if total > limit:
                raise ValueError('Download exceeds signed size limit')
            output.write(chunk)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest='command')
    create = commands.add_parser('manifest')
    create.add_argument('--archive', required=True)
    create.add_argument('--root', required=True)
    create.add_argument('--version', required=True)
    create.add_argument('--output', required=True)
    check = commands.add_parser('verify')
    check.add_argument('archive')
    tree = commands.add_parser('verify-tree')
    tree.add_argument('directory')
    apply = commands.add_parser('apply')
    apply.add_argument('archive')
    apply.add_argument('--mode', choices=['install', 'update'], required=True)
    download = commands.add_parser('download')
    download.add_argument('--version', required=True)
    download.add_argument('--base-url', default='https://videograce.ru/download')
    download.add_argument('--mode', choices=['install', 'update'], default='install')
    args = parser.parse_args()
    if args.command == 'manifest':
        create_manifest(args.archive, args.root, args.version, args.output)
        print('Unsigned manifest ready; sign on Windows before publication: ' + args.output)
        return
    if args.command == 'verify-tree':
        verify_directory(args.directory)
        print('Signed release contents verified')
        return
    if args.command not in ('verify', 'apply', 'download'):
        parser.error('Choose a command')
    if args.command != 'verify' and os.geteuid() != 0:
        raise ValueError('Run the trusted installer/updater with sudo')
    with tempfile.TemporaryDirectory(prefix='vg-signed-release-') as folder:
        folder = Path(folder)
        if args.command == 'download':
            if not re.match(r'^\d+\.\d+\.\d+$', args.version):
                raise ValueError('Invalid version')
            archive = folder / ('VideoGraceServer-' + args.version + '-x64.tar.bz2')
            manifest, signature = Path(str(archive) + '.release.json'), Path(str(archive) + '.release.json.p7s')
            base = args.base_url.rstrip('/') + '/'
            fetch(base + manifest.name, manifest, MAX_MANIFEST)
            fetch(base + signature.name, signature, MAX_SIGNATURE)
            data = verify_manifest(manifest, signature)
            if data['version'] != args.version:
                raise ValueError('Requested release version differs')
            fetch(base + archive.name, archive, data['archive']['size'])
        else:
            source = Path(args.archive).resolve()
            archive = folder / source.name
            manifest, signature = Path(str(archive) + '.release.json'), Path(str(archive) + '.release.json.p7s')
            # Snapshot caller-controlled inputs before root verification/extraction.
            shutil.copyfile(str(source), str(archive))
            shutil.copyfile(str(source) + '.release.json', str(manifest))
            shutil.copyfile(str(source) + '.release.json.p7s', str(signature))
        data = verify_archive(archive, manifest, signature)
        print('Signature and archive SHA256 verified: ' + data['version'], flush=True)
        if args.command == 'verify':
            return
        if args.mode == 'install' and TARGET.exists():
            raise ValueError('Existing installation found; use --mode update')
        if args.mode == 'update' and not (TARGET / 'VideoGraceServer').exists():
            raise ValueError('No existing server to update')
        root = extract_verified(archive, folder, data, manifest, signature)
        subprocess.check_call(['sh', str(root / (args.mode + '.sh'))])


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, subprocess.CalledProcessError) as error:
        print('VideoGrace release verification/installation failed: ' + str(error), file=sys.stderr)
        sys.exit(1)

VG_SIGNED_BOOTSTRAP_PYTHON
