#!/usr/bin/env python3
"""FortNIX preliminary Linux checks. No packages, mounts, kernel changes or BPF loads."""
import argparse
import datetime
import gzip
import json
import os
import platform
import re
import shutil
import socket
import ssl
import sys
from pathlib import Path
from urllib.parse import urlsplit

VERSION = '0.1.0-preview'
MIB = 1024 * 1024
FLAGS = ('CONFIG_BPF', 'CONFIG_BPF_SYSCALL', 'CONFIG_BPF_LSM', 'CONFIG_DEBUG_INFO_BTF')
RUNTIME_TESTS = [
    'Create the required BPF ring-buffer map and LSM program with approved privileges.',
    'Load and attach every required sensor hook on this exact kernel; preserve existing LSM decisions.',
    'Observe a safe real action through the sensor and confirm receipt in the correct tenant.',
]


def read_text(path, limit=2*MIB):
    try:
        with path.open('rb') as stream:
            data = stream.read(limit+1)
        if len(data) > limit:
            return None
        return data.decode('utf-8', errors='replace')
    except OSError:
        return None


def collect(root=Path('/')):
    release = platform.release()
    distro = {}
    for line in (read_text(root/'etc/os-release', 65536) or '').splitlines():
        match = re.match(r'^(ID|VERSION_ID)=(.*)$', line)
        if match:
            distro[match[1]] = match[2].strip().strip('"\'')
    config = None
    try:
        with gzip.open(root/'proc/config.gz', 'rt') as stream:
            value = stream.read(2*MIB+1)
        if len(value) <= 2*MIB:
            config = value
    except (OSError, EOFError, UnicodeError):
        pass
    if config is None and re.fullmatch(r'[A-Za-z0-9._+\-]+', release):
        config = read_text(root/('boot/config-'+release))
    flags = {}
    if config is not None:
        for flag in FLAGS:
            match = re.search(r'^'+flag+r'=(y|m|n)$', config, re.M)
            if match:
                flags[flag] = match[1]
            elif re.search(r'^# '+flag+r' is not set$', config, re.M):
                flags[flag] = 'n'
    btf = None
    try:
        with (root/'sys/kernel/btf/vmlinux').open('rb') as stream:
            btf = stream.read(2) in (b'\x9f\xeb', b'\xeb\x9f')
    except FileNotFoundError:
        btf = False
    except OSError:
        pass
    lsm_text = read_text(root/'sys/kernel/security/lsm', 65536)
    lsm = None if lsm_text is None else lsm_text.strip().split(',')
    memory = read_text(root/'proc/meminfo', 65536) or ''
    available = re.search(r'^MemAvailable:\s+(\d+)\s+kB$', memory, re.M)
    tracepoints = None
    for directory in ('sys/kernel/tracing/events/syscalls', 'sys/kernel/debug/tracing/events/syscalls'):
        parent = root/directory
        try:
            names = {p.name for p in parent.iterdir()}
        except OSError:
            continue
        tracepoints = {name: name in names for name in ('sys_enter_execve', 'sys_enter_execveat')}
        break
    try:
        free = shutil.disk_usage(root/'opt' if (root/'opt').exists() else root).free
    except OSError:
        free = None
    return {
        'system': platform.system(), 'architecture': platform.machine(), 'kernel': release,
        'distro': distro, 'config_flags': flags, 'btf_readable': btf, 'active_lsm': lsm,
        'syscall_tracepoints': tracepoints,
        'systemd': (root/'run/systemd/system').is_dir(),
        'container': (root/'.dockerenv').exists() or (root/'run/.containerenv').exists(),
        'available_memory_bytes': int(available[1])*1024 if available else None,
        'free_install_bytes': free, 'lockdown': read_text(root/'sys/kernel/security/lockdown', 4096),
        'effective_root': os.geteuid() == 0 if hasattr(os, 'geteuid') else False,
    }


def check_endpoint(url, ca_file=None):
    parsed = urlsplit(url)
    if (parsed.scheme != 'https' or not parsed.hostname or parsed.username is not None
            or parsed.password is not None or parsed.query or parsed.fragment or parsed.path not in ('', '/')):
        raise ValueError('Endpoint must be a bare HTTPS origin without credentials, query or fragment')
    port = parsed.port or 443
    if not 1 <= port <= 65535:
        raise ValueError('Invalid endpoint port')
    context = ssl.create_default_context(cafile=ca_file)
    try:
        with socket.create_connection((parsed.hostname, port), timeout=8) as raw:
            with context.wrap_socket(raw, server_hostname=parsed.hostname):
                pass
        return {'status':'pass', 'message':'TCP and server TLS identity verified; enrollment and client authentication NOT tested'}
    except ssl.SSLCertVerificationError:
        return {'status':'fail', 'message':'Server certificate/hostname is not trusted; do not disable TLS validation'}
    except (OSError, ssl.SSLError):
        return {'status':'unknown', 'message':'Connection/TLS could not be verified; inspect DNS, route, firewall, trust and mTLS requirements'}


def evaluate(facts, endpoint=None):
    checks = []
    def add(name, status, message, action=''):
        checks.append({'id':name, 'status':status, 'message':message, 'recommendation':action})
    add('linux', 'pass' if facts['system']=='Linux' else 'fail', 'A Linux host is required')
    distro = facts['distro']
    candidate = distro.get('ID')=='ubuntu' and distro.get('VERSION_ID') in ('26.04', '26.04.1')
    add('os_profile', 'pass' if candidate else 'unknown',
        'Ubuntu 26.04 LTS is a candidate profile, NOT a certified FortNIX configuration' if candidate else 'This OS profile has not been validated for this release',
        'Use the tested release matrix when published; do not reinstall a production OS automatically')
    add('architecture', 'pass' if facts['architecture'] in ('x86_64', 'amd64') else 'unknown',
        'First complete-sensor build targets x86_64; ARM64 transport alone does not validate the ARM64 sensor')
    add('systemd', 'pass' if facts['systemd'] else 'fail', 'The planned installer requires host systemd')
    add('host_scope', 'unknown' if facts['container'] else 'pass',
        'Run this check on the actual host to protect, not an ordinary container' if facts['container'] else 'No common container marker found; virtualization is not certified by this check')
    for flag in FLAGS:
        value = facts['config_flags'].get(flag)
        add(flag, 'pass' if value=='y' else 'unknown' if value is None else 'fail',
            'Enabled' if value=='y' else 'Kernel configuration unavailable' if value is None else 'Required kernel feature disabled',
            'If unreadable, rerun this read-only check with sudo; if disabled, plan a supported distribution kernel and a rollback/reboot window')
    btf = facts['btf_readable']
    add('kernel_btf', 'pass' if btf is True else 'unknown' if btf is None else 'fail',
        'Kernel BTF header readable' if btf else 'Kernel BTF missing, unreadable or invalid',
        'Check /sys/kernel/btf/vmlinux and the supported kernel; a BTF file alone does not prove sensor hook compatibility')
    lsm = facts['active_lsm']
    add('active_bpf_lsm', 'unknown' if lsm is None else 'pass' if 'bpf' in lsm else 'fail',
        'Active LSM list unreadable' if lsm is None else 'BPF must be present among active LSMs',
        'Preserve existing AppArmor/SELinux/LSMs. If necessary, add bpf without replacing the existing list; boot changes require an approved maintenance window')
    points = facts['syscall_tracepoints']
    add('exec_tracepoints', 'unknown' if points is None else 'pass' if all(points.values()) else 'fail',
        'Tracefs syscall event IDs unreadable/unmounted' if points is None else 'execve and execveat tracepoints checked',
        'Verify tracefs and the required syscall tracepoints. This script does not mount filesystems')
    for name, value, target in [('memory_headroom',facts['available_memory_bytes'],512*MIB), ('disk_headroom',facts['free_install_bytes'],1024*MIB)]:
        add(name, 'unknown' if value is None else 'pass' if value>=target else 'warning',
            'Preliminary headroom target: '+str(target//MIB)+' MiB; sizing is not yet validated',
            'Measure real sensor/queue use on the test host; do not delete customer data or resize automatically')
    if facts.get('lockdown') and '[none]' not in facts['lockdown']:
        add('kernel_lockdown','warning','Kernel lockdown is active; actual BPF load needs validation','Do not disable Secure Boot or security policy automatically')
    if endpoint is None:
        add('control_plane_network','unknown','No public client-enrollment endpoint supplied','Repeat with --endpoint when the client control endpoint is published; a website is not proof of enrollment availability')
    else:
        add('control_plane_network', endpoint['status'], endpoint['message'])
    statuses = {c['status'] for c in checks}
    outcome = 'needs_changes' if 'fail' in statuses else 'incomplete' if statuses & {'unknown','warning'} else 'static_checks_ready'
    return {
        'schema_version':1, 'tool_version':VERSION,
        'checked_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),
        'outcome':outcome, 'certified_compatible':False,
        'runtime_sensor_test_required':True, 'runtime_tests':RUNTIME_TESTS,
        'host':{k:facts[k] for k in ('system','architecture','kernel','distro','effective_root')},
        'checks':checks,
        'privacy':'No hostname, machine ID, environment variables, process list, file contents or keys collected. Report is not uploaded.',
    }


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--json', action='store_true', help='Print the local JSON report')
    parser.add_argument('--endpoint', help='Published control/enrollment HTTPS origin; optional explicit network probe')
    parser.add_argument('--ca-file', help='Trusted public CA PEM for the endpoint; never a private key')
    args = parser.parse_args(argv)
    if args.ca_file and not args.endpoint:
        parser.error('--ca-file requires --endpoint')
    try:
        endpoint = check_endpoint(args.endpoint,args.ca_file) if args.endpoint else None
        report = evaluate(collect(),endpoint)
    except (OSError,ValueError):
        print('Preflight configuration/collection failed; verify local arguments and public CA file. No system changes made.', file=sys.stderr)
        return 4
    if args.json:
        print(json.dumps(report,ensure_ascii=False,indent=2))
    else:
        print('FortNIX preflight '+VERSION+' — '+report['outcome'])
        for check in report['checks']:
            print('[{}] {}: {}'.format(check['status'].upper(),check['id'],check['message']))
            if check['recommendation'] and check['status']!='pass':print('  '+check['recommendation'])
        print('NOT a compatibility certificate: actual sensor load/attach and end-to-end delivery still require testing.')
        print(report['privacy'])
    return {'static_checks_ready':0,'needs_changes':2,'incomplete':3}[report['outcome']]

if __name__ == '__main__':
    sys.exit(main())
