Skip to content

Fixing the web API, ONVIF and RTSP issues from the November security reports - #103

Merged
wberube merged 4 commits into
masterfrom
input-and-bounds-hardening
Nov 20, 2026
Merged

wberube merged 4 commits into
masterfrom
input-and-bounds-hardening

Conversation

@widgetii

Copy link
Copy Markdown
Member

Fixes GHSA-g3hw-cxmj-vrr2, GHSA-95p3-p37v-q53f and GHSA-w8hv-4jp5-3993. One commit per advisory.

Web API (g3hw)

  • region_fill_formatted() no longer writes past out[80]. Also fixed nearby:
    • $B no longer spins when getifaddrs() fails;
    • $C survives a missing /proc/stat;
    • the OSD thread's copy of the text and /api/time?fmt= are now always terminated.
  • unescape_uri() drops decoded control characters, so a %0A in a setting can no longer add a section (e.g. a stream: with a foreign dest) to the saved divinus.yaml. It is rewritten without the undefined double *++src; + keeps its old meaning.
  • A request to /exit, or to /api/ with parameters, is refused with 403 when its Sec-Fetch-Site, Origin or Referer names another site. Scripts and NVRs that send none of these headers are unaffected, and parameterless reads stay open.

ONVIF (95p3)

  • The snapshot and stream URIs no longer embed the web or RTSP credentials.

RTSP (w8hv)

  • track= is bounds-checked. The error now survives the header lines that reset the parser.
  • A connection that drops mid-request is no longer dispatched. This removed the vfprintf(NULL) crash and a double detach.
  • A full connection pool refuses the new client instead of ending the RTSP thread.
  • A TCP client that stops reading is dropped after about a second instead of blocking the encoder path for every viewer.

Tests: ./test.sh --all passes (8/8), including two new tests that both fail on master:

  • tst/osd-expand, built with ASan: master reports a stack-buffer-overflow, a 20-byte WRITE;
  • tst/unescape-uri.

Builds: hisi-v4, hisi-v4a and star6e build cleanly.

Hardware: checked on a hi3516ev300 + IMX335 running OpenIPC ultimate, against this build. Two non-destructive checks were also run against the board's stock divinus as controls.

Check stock divinus this build
ONVIF GetSnapshotUri / GetStreamUri, no ONVIF auth http://admin:12345@…/image.jpg, rtsp://admin:12345@… no credentials
/api/time?fmt= with a foreign Origin 200, setting changed 403
Same request with same Origin, or no headers — 200
/exit, /api/cmd?save from a foreign origin — 403
adc_device with %0A-separated sections, then save — one stream: section, value kept on its own line
OSD text $t$t$t$t$t — runs on, stream fine
SETUP track=1000 / track=4294967295, with and without auth — error reply, server keeps running
Request missing its final CRLF, then close — server keeps running
17 idle connections — 17th refused, RTSP keeps serving afterwards
TCP client that stops reading mid-PLAY — dropped (EOF); a second client streams 1080p H.264 meanwhile

The crash cases were not run against the stock binary on hardware: they would have tripped its watchdog.

…sites

- region_fill_formatted() appended every placeholder to out[80] with an
  unchecked strcat; with the default time format five $t already ran past
  it, and a full OSD text of them wrote a kilobyte onto the stack. Every
  append now goes through a bounded helper. Also: $B no longer spins when
  getifaddrs() fails, $C survives a missing /proc/stat and a negative
  reading, the OSD thread's copy of the text is terminated, and
  /api/time?fmt= no longer leaves the format unterminated.
- unescape_uri() drops decoded control characters: settings are saved to
  divinus.yaml a line each, so a %0A in one (adc_device, say) wrote a
  section of the caller's choosing -- a stream: whose dest sent the video
  elsewhere. The decoder is rewritten without the undefined double *++src;
  '+' keeps its old meaning.
- Every setting and command is a GET with parameters, which any page can
  send with the Basic credentials a browser holds. A request to /exit, or
  to /api/ with parameters, whose Sec-Fetch-Site, Origin or Referer names
  another site is now refused with 403. Clients that send none of these
  headers (scripts, NVRs) are unaffected, and parameterless reads stay open.

tst/osd-expand (built with AddressSanitizer) and tst/unescape-uri cover the
first two; both fail on the previous code.
GetSnapshotUri returned the web admin's user:password inside the snapshot
URI, and GetStreamUri the RTSP credentials inside the stream URI. /onvif is
answered before the web auth check and ONVIF auth defaults off, so anyone
who could reach the web port got the admin password, which opens the whole
/api. The URIs now carry no credentials; clients authenticate to them as
they do with any other camera.
- SETUP's track= indexed trans[2] unchecked, and the Transport header of
  the same request wrote through it before auth was decided. Out of range
  is now a parse error, kept past the header lines that reset the parser.
- A request missing its final CRLF made __read_line detach the connection,
  after which the request was still answered -- into a NULL FILE. A
  connection that went away mid-request is no longer dispatched.
- A full connection pool used to end the RTSP thread, so 16 idle
  connections took RTSP down until restart. The extra client is refused
  instead.
- A TCP client that stopped reading made __tcp_flush wait for ever on the
  encoder's path, freezing video for every viewer. It now waits about a
  second, then shuts the socket down for the RTSP thread to clean up.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Harden web API, ONVIF, OSD, and RTSP security boundaries

🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Bound OSD expansion and sanitize decoded settings to prevent memory corruption and configuration
 injection.
• Reject cross-site API changes and stop exposing credentials in ONVIF URIs.
• Keep RTSP serving after malformed requests, pool exhaustion, or stalled TCP viewers.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 7 capabilities

  • 7 affected capabilities span independent functional scopes: camera_osd_rendering, onvif_media_integration, rtsp_service, rtsp_streaming, web_camera_configuration, web_camera_control.
  • The decoder is shared by the camera's HTTP configuration endpoints, and the resulting values directly control bounded camera settings and commands.
  • These are one administration integration despite being implemented across the request parser and individual endpoint branches.
  • The capability is the end-to-end ONVIF operation from GetSnapshotUri to fetching /image.jpg.
  • The ONVIF response builder and HTTP image route are producer/consumer hops of one media integration.
  • The capability is the end-to-end ONVIF operation from GetStreamUri to opening the returned RTSP stream.
  • The URL generator and RTSP authentication consumer belong to the same ONVIF media integration.
  • The changed parser, connection-pool admission, and session setup all determine whether an RTSP client can establish and maintain a session.
  • They are distinct technical branches of one RTSP service capability.
  • The flush operation is on the end-to-end RTP delivery path for an RTSP viewer.
  • It affects delivery of the stream, not an independent encoder or socket capability.
  • The affected behavior is the end-to-end ability to submit state-changing camera commands and settings through the HTTP API.
  • The common request guard and endpoint handlers are one bounded web-control integration.
  • The API stores the time-format value and the region formatter consumes it to produce displayed time text.
  • These are producer and consumer hops of the same OSD time-display behavior.
Behavioral complexity 🔴 High 🧩 Concurrent ordering

  • Before, a non-reading client could keep the flush loop waiting indefinitely.
  • After, the flush introduces a bounded retry/timeout protocol and a shutdown handoff to another thread.
  • The new correctness condition is ordering between timeout, socket shutdown, connection-list cleanup and continued flushing of other clients; this is a concurrency/ownership interaction, not merely use of poll().
Potential damage 🔴 High 🩹 Integrity

  • If the new protection has a false-negative path, a browser holding camera credentials could still be induced to change settings, save configuration, restart, or issue other covered commands.
  • Those changes can persist beyond code rollback and may require manual restoration.
  • A false positive instead causes temporary loss of browser control, but the security-relevant plausible consequence is unauthorized state change.
  • Restore affected settings or configuration manually and rotate credentials if exposed; reverting the code prevents future requests but does not undo already applied commands or persisted values.
Assessed commit cc627d2
Diagram

graph TD
    Client(["Clients"]) --> Gate["Origin gate"] --> Web["Web API"] --> Decoder["URI decoder"] --> OSD["OSD expansion"]
    Client --> ONVIF["ONVIF URIs"]
    Client --> RTSP["RTSP parser"] --> Flush["TCP flush"]
    ONVIF -. "credential-free URI" .-> RTSP
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Require CSRF tokens for state-changing web requests
  • ➕ Provides an explicit authorization check even when origin-related headers are absent.
  • ➖ Requires UI and API-client changes and may break existing scripts or NVR integrations.

Recommendation: The header-based gate is a pragmatic compatibility-preserving fix for browser-initiated cross-site requests, alongside targeted bounds and lifecycle checks. Consider CSRF tokens as a follow-up if protecting state-changing requests without origin headers becomes a requirement.

Files changed (10) +287 / -58

Bug fix (6) +156 / -58
tools.cSanitize decoded query values +32/-10

Sanitize decoded query values

• Rewrites in-place percent decoding with explicit hex validation and removes decoded control characters that could inject lines into saved configuration. Preserves the existing context-dependent treatment of '+'.

src/hal/tools.c

onvif.cRemove credentials from ONVIF media URIs +10/-20

Remove credentials from ONVIF media URIs

• Snapshot and stream responses now provide URLs without embedded web or RTSP usernames and passwords, leaving clients to authenticate to those endpoints separately.

src/onvif.c

region.cBound OSD expansion and handle placeholder failures +27/-19

Bound OSD expansion and handle placeholder failures

• Routes placeholder output through a bounded append helper and handles failed network-stat and time-format operations. Initializes the OSD thread’s text copy so it remains terminated.

src/region.c

rtp.cLimit waits on stalled TCP viewers +18/-4

Limit waits on stalled TCP viewers

• Caps repeated waits when a TCP client stops reading and shuts down the stalled socket so the RTSP thread can clean it up without indefinitely blocking the encoder path.

src/rtsp/rtp.c

rtsp.cGuard RTSP tracks and connection lifecycles +31/-4

Guard RTSP tracks and connection lifecycles

• Bounds-checks SETUP track indices and preserves the error through header parsing. Avoids dispatch after disconnect and refuses excess clients without terminating the RTSP thread.

src/rtsp/rtsp.c

server.cReject cross-site API changes +38/-1

Reject cross-site API changes

• Returns 403 for cross-site /exit and parameterized /api/ requests based on fetch metadata, Origin, or Referer while retaining access for clients without those headers. Also ensures the API time format is terminated.

src/server.c

Tests (4) +131 / -0
osd_test.cCover bounded OSD placeholder expansion +63/-0

Cover bounded OSD placeholder expansion

• Adds checks for ordinary placeholders, repeated time expansion at the output limit, and an oversized time format.

tst/osd-expand/osd_test.c

run.shRun OSD regression checks with AddressSanitizer +16/-0

Run OSD regression checks with AddressSanitizer

• Builds the OSD test against the relevant source files with AddressSanitizer to detect stack-buffer writes.

tst/osd-expand/run.sh

run.shBuild and run URI decoder regression checks +11/-0

Build and run URI decoder regression checks

• Compiles the standalone URI decoder test with the production decoder and runs it through the test harness.

tst/unescape-uri/run.sh

unescape_test.cCover decoding and configuration-injection inputs +41/-0

Cover decoding and configuration-injection inputs

• Tests normal escapes, existing '+' behavior, malformed escapes, UTF-8 bytes, and removal of decoded control characters including configuration-injecting newlines.

tst/unescape-uri/unescape_test.c

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Sibling sites can change camera settings ✓ Resolved

Resolving commit: da2d8f2

Resolution reason
same-site requests are no longer accepted unconditionally; they fall through to the Origin/Referer
host comparison (names_another_host), so a sibling-subdomain page is rejected with 403. same-origin
and none remain exempt. Mutating /api/ requests without query strings (e.g., POST bodies) are also
now covered by the cross-site check.
Description
cross_site_request() treats Sec-Fetch-Site: same-site as safe without checking whether Origin
names the camera's host. When an authenticated visitor opens a page on a different subdomain of the
camera's site, that page can send query-driven API requests to the camera.

2. Headerless browser requests can change settings 🐞 Bug ⛨ Security
Description
cross_site_request() returns false when Sec-Fetch-Site, Origin, and Referer are all absent.
A cross-site GET that suppresses its referrer reaches commands such as /api/cmd?restart in
browsers that do not send Fetch Metadata, including when the browser has cached the camera's Basic
credentials.
Code

src/server.c[R630-632]

+    const char *from = request_header("Origin");
+    if (!from) from = request_header("Referer");
+    return from && names_another_host(from, request_header("Host"));
Evidence
Absent headers resolve to NULL, making the guard's final expression false; the command handler
subsequently executes state-changing requests.

src/server.c[505-511]
src/server.c[583-602]
src/server.c[625-633]
src/server.c[752-756]
src/server.c[980-1007]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An attacker can suppress Referer on a cross-site GET; without Fetch Metadata, the new check cannot distinguish it from headerless automation.
## Fix Focus Areas
- src/server.c[625-633]
- src/server.c[752-756]
## Recommended Fix
Require an independently verifiable safeguard for state-changing requests that lack provenance headers, rather than treating missing headers as proof of safety. Preserve automation through an explicit authenticated mechanism and test a headerless mutating request.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. A slowly reading client still freezes video ✓ Resolved

Resolving commit: da2d8f2

Resolution reason
Replaced the progress-resettable wait counter with a 1000 ms deadline measured from the start of the
flush. Partial sends no longer extend the budget, and on expiry the connection is shut down and
FAILURE returned, so a slow-trickle client can no longer hold write_mutex indefinitely.
Description
__tcp_flush resets waits = 0 whenever send() returns any positive count, so the one-second
limit only applies to a client that makes no progress at all. A client that drains a few bytes every
few hundred milliseconds (a tiny receive window) keeps the encoder thread inside one flush for as
long as the whole tx_buf takes to trickle out, which can be minutes, and holds write_mutex the
whole time, so every viewer's video stalls just as before.

4. Cross-site image upload to the OSD is not blocked ✓ Resolved

Resolving commit: da2d8f2

Resolution reason
The /api/ guard condition in respond_request now reads (req->query || !EQUALS(req->method, "GET")),
so any non-GET /api/ request (including body-only multipart POSTs to /api/osd/N) is passed to
cross_site_request(). This is the exact extension the suggested fix prompt recommends.
cross_site_request() was also tightened so same-site requests still must name the host, which
further closes the cross-site path.
Description
The cross-site guard checks /api/ requests only when req->query is present, leaving body-only
multipart POSTs to /api/osd/N unchecked. A cross-site HTML form can send such a request without a
preflight, and the browser attaches cached Basic credentials, allowing the handler to write
/tmp/osdN.png|bmp and replace the region’s text.


Informational

5. A failed stream open closes the socket twice ✓ Resolved

Resolving commit: da2d8f2

Resolution reason
Ownership of fd is moved entirely to __connection_list_add: pool-full failures now close fd there
via ({ close(fd); return FAILURE; }) in both the ASSERT and DASSERT paths, and the caller's
close(fd) after a failed __connection_list_add was removed, so fd is closed exactly once on every
failure path.
Description
When __connection_list_add fails after it has stored the fd (one of the fdopen calls fails), its
error path __connection_reset already closes client_fd via FCLOSE/CLOSE. The new close(fd) in
__accept_proc_sock then closes the same number again, and by then the number may belong to a
descriptor another thread just opened (encoder, HTTP server), which silently cuts that thread off.

Grey Divider

Tip of the day
💡 Did you know, you can turn on the rule miner and Qodo learns your standards from review history

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

- cross_site_request(): Sec-Fetch-Site: same-site no longer skips the
  Origin/Referer check -- another port on the camera's own address is the
  same site. Only same-origin and none are settled by Fetch Metadata.
- The guard also covers /api/ requests with a body: /api/osd/N takes an
  image as a multipart POST with no query, which a form elsewhere can send.
- __tcp_flush() gives up after a 1 s deadline instead of after ten idle
  waits in a row, so a client that reads a few bytes now and then can no
  longer hold the encoder path either.
- __connection_list_add() now owns the fd on every failure: a full pool
  closes it there, a failed fdopen through __connection_reset. The caller's
  extra close() could hit a number another thread had just been given.
@widgetii

Copy link
Copy Markdown
Member Author

Addressed Qodo's review in da2d8f2. Re-checked on the hi3516ev300 board.

  1. same-site: fixed. It now goes through the Origin/Referer check; only same-origin and none skip it. On the board, same-site from another port returns 403, and same-site naming this host returns 200.
  2. Requests with no provenance headers: valid, and not fixed here. Browsers don't send Fetch Metadata to plain-http origins, and a page can suppress the Referer, so a cross-site <img referrerpolicy="no-referrer"> GET still passes. This guard stops the default cases: forms, links, and fetches that carry an Origin. Closing the rest needs state changes to stop being plain GETs, through POST or a custom header. That changes the API that scripts and NVRs use today, so it's a call for the maintainer, and I'd rather it were a separate PR than folded into this one.
  3. Slow reader: fixed. The flush is bounded by a 1 s deadline instead of idle-wait counts. On the board, a client reading 256 B every 200 ms is shut down (server side in FIN_WAIT1, about 512 KB still queued), and a second client meanwhile streams 1080p H.264 in 1.6 s.
  4. Multipart POST to /api/osd/N: fixed. The guard now covers any non-GET /api/ request. On the board, a cross-site multipart upload with no query returns 403.
  5. Double close: fixed. __connection_list_add() now owns the fd on every failure path, and the caller no longer closes it. The 17-connection case still refuses the extra client and keeps serving.

./test.sh --all passes (8/8). hisi-v4, hisi-v4a and star6e build.

@wberube
wberube merged commit 006560c into master Nov 20, 2026
1 check passed
@wberube

wberube commented Nov 20, 2026

Copy link
Copy Markdown
Member

Thank you very much, those are some nice findings!

@wberube
wberube deleted the input-and-bounds-hardening branch November 20, 2026 16:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants