Commit bc8ba23
authored
fix(mediaplayer): native C/C++ security hardening (parser/protocol memory safety + fuzzing) (#968)
## Summary
Security hardening for the media player's native C/C++ (`Native~/`),
from a memory-safety review of the parser/protocol layer. That code
parses attacker-controlled bytes in-process — a peer-broadcast URL is
parsed by every client in a room — so the findings here are remotely
reachable. This closes five higher-severity and five medium issues, and
extends the fuzz harness to two parsers that had no coverage. One commit
per concern so each fix can be reviewed independently.
**Out-of-bounds write / SSRF / DoS (higher severity)**
- **RTSP Basic-auth base64 OOB stack write** — a `rtsp://user:pass@host`
URL could encode a 255-byte `user:pass` into a 256-byte field (340 bytes
out), an 85-byte overwrite of adjacent stack fields. Size the field for
the true maximum and bound the encode loop.
- **HLS sub-resource SSRF** — the managed URL check only validates the
top-level playlist; variant/segment/`EXT-X-MAP` URIs from the playlist
body were fetched with no host check, so a hostile playlist could steer
a fetch at `169.254.169.254`/RFC1918/loopback. Every HLS fetch now goes
through a resolved-address block (fail-closed, `http(s)`-only), with
policy rejection distinguished from transient failure so a blocked
reload/segment terminates deterministically instead of skipping or
busy-looping. The non-global-unicast IPv4 classifier is also aligned to
the full IANA special-use set in both the native and managed guards.
- **MP4 box-tree recursion** — `parse_box_tree` recursed with no depth
limit; a small crafted `moov` overflowed the demux-thread stack. Capped
at 32.
- **MPEG-TS PES accumulation** — a stream that sets PUSI once and
streams continuation packets forever grew the PES buffer unbounded, with
a signed-overflow in the growth math. 8 MiB cap, 64-bit math.
- **Android Vulkan output-texture UAF** — the framebuffer/image-view
were destroyed on the main thread while the render thread could be
mid-present, on a mid-stream resolution change. The destroy is deferred
to the render thread under the lock, with one consistent target extent
for the framebuffer and render area.
**Medium**
- Render-event liveness registry so a late `OnRenderEvent` can't
use-after-free an engine freed by `basis_media_close`.
- RTMP `_result` AMF parsing bounds every read (was reading up to 8
bytes past the buffer).
- RTSP RTP reassembly buffers capped (16 MiB) with the overflow fixed; a
cap hit drops the whole AU/frame rather than a truncated one.
- Windows Media Foundation allocations checked (a large declared sample
turned an alloc failure into a null-deref); COM buffer unlock/HRESULT
hygiene; software-fallback size bounded against overflow.
- Android `AMediaCodec_getInputBuffer` null-checked, sizes compared as
`size_t`, and the codec queue status propagated so a dropped frame isn't
reported as accepted.
**Fuzzing** — new `fuzz_url`, `fuzz_hls`, `fuzz_rtsp` and `fuzz_rtmp`
targets under ASan/UBSan, wired into `build.sh`; the URL/HLS/RTSP/RTMP
parsers were all previously unfuzzed. HLS uses an in-memory HTTP
provider; RTSP/RTMP `#include` the real `.c` and provide a `basis_io`
stub (byte-serving the socket-read paths), driving
`parse_sdp`/`depkt_video`/`depkt_audio`/`amf_find_stream_id`/FLV tag
parsers directly. The RTSP target earned its keep — it found a signed
left-shift UB in the RTP timestamp read (`rtp[4] << 24` on a byte ≥ 128)
on its first run, fixed here and pinned as a replay repro. Deeper
full-session RTSP/RTMP coverage (a scripted handshake, or an injected
transport vtable that would also enable RTSP/RTMP unit tests) is tracked
as a backlog follow-up.
**Docs / tooling** — also retires the self-hosted
`tools/media-test-streams` Docker stack and its TESTING.md guidance. The
public endpoints already listed cover the common lanes, the CI
conformance gate (`tools/media-conformance`) already proves the demuxers
on every supported container/codec, and the remaining lanes (live
RTSP/RTMP/RIST, split-stream, captions, LPCM 7.1, `localhost`) are
cheaper to serve from your own files/server than to maintain a bundled
stack. TESTING.md now lists the supported container/codec/transport
inputs to bring your own of, framed around what CI can't touch (real
decode + present, A/V sync, live transports).
## Required checks
All boxes below must be ticked before this PR can merge. If a check is
genuinely N/A, tick it anyway and explain under **Notes**.
<!-- required-checks-start -->
<!-- Tick the boxes in place — do not edit the line text. The
pr-checklist workflow parses this block; per-PR context goes under
Notes. -->
- [x] **Tested** — I built and ran this locally. The change works in the
editor and (where relevant) in a built player.
- [x] **Transform access is combined and limited** — In hot paths,
transform reads/writes go through `TransformAccessArray` or are
otherwise batched. I have not added per-frame `transform.position` /
`transform.rotation` / `transform.localPosition` calls inside loops.
Whenever I need both position and rotation, I use the combined APIs —
`SetPositionAndRotation` / `SetLocalPositionAndRotation` for writes,
`GetPositionAndRotation` / `GetLocalPositionAndRotation` for reads —
instead of two separate property accesses; the combined call does one
local-to-world matrix traversal instead of two.
- [x] **Addressables used for asset/memory loading** — Any new asset
loads go through Addressables. No new `Resources.Load`, no direct asset
references that pull large content into memory on scene load.
- [x] **No new `GetComponent` / `AddComponent` where avoidable** — Where
unavoidable, the result is cached on a field, and any `GetComponent<T>`
is replaced with `TryGetComponent<T>(out var x)` — bare `GetComponent`
will be denied. `TryGetComponent` is the modern API (Unity 2019.2+) and
skips the Editor-only GC allocation `GetComponent` causes when a
component is missing: Unity wraps the `null` return in a managed "fake
null" object so its overloaded `==` operator can still detect destroyed
C++ objects, and constructing that wrapper allocates; `TryGetComponent`
returns a `bool` plus `out` parameter and never builds the wrapper. None
of these calls run inside `Update`, `LateUpdate`, `FixedUpdate`, jobs,
or other per-frame code paths.
- [x] **Per-frame work is scheduled through `BasisEventDriver`** — Any
new per-frame work hooks into `BasisEventDriver` rather than adding
standalone `Update` / `LateUpdate` / `FixedUpdate` callbacks on a
MonoBehaviour.
- [x] **Anything added to `BasisEventDriver` is bulletproof, or guarded
by `try`/`catch`** — `BasisEventDriver` runs the single per-frame tick
that drives the whole framework (network apply, local player sim,
blendshapes, JigglePhysics, nameplates, and more) as one sequential
chain. An unhandled exception anywhere in that chain aborts the rest of
the tick, so every step after the throwing one is silently skipped for
that frame. New work added to the driver must either be guaranteed not
to throw, or be wrapped in a `try`/`catch` that contains the failure and
surfaces it through `BasisDebug` — logged once / rate-limited, never
every frame (see the existing `HVRBasisBuiltInAddresses.Simulate()`
guard for the pattern). Expect this to be scrutinized closely in review.
- [x] **Considered jobification** — I asked whether this work can be
moved to a Unity Job (Burst-compiled where possible). If it can, it is.
If it cannot, the reason is in **Notes**.
- [x] **No needless `{ get; set; }` properties or access lockdowns** —
Public fields are fine; Basis is meant to be read and modified freely,
so don't wall things off `private`/`internal` without a real reason.
Don't wrap a field in `{ get; set; }` when the accessors do nothing —
property accessors have a real performance cost vs direct field access,
and the lead maintainer prefers plain fields (or a method / setter-only
property when only the setter needs logic) over a noop-getter pair. For
`.Instance` singletons, callers reassigning `Type.Instance` is allowed;
if that would break your code, log a warning or throw — don't block the
assignment. Locking down access is not your call.
- [x] **Camera access goes through `BasisLocalCameraDriver`** — Code
that needs the local camera (transform, projection, rig data, etc.)
pulls it from `BasisLocalCameraDriver` rather than looking one up
itself. Don't roll a separate camera discovery path.
- [x] **Logging uses `BasisDebug`** — All new logging calls go through
`BasisDebug.Log` / `BasisDebug.LogWarning` / `BasisDebug.LogError` (with
an appropriate `LogTag`) instead of `UnityEngine.Debug.Log` /
`Debug.LogWarning` / `Debug.LogError`. `BasisDebug` routes through
Basis's tagged, color-coded logger and respects the project-wide
`LoggingDisabled` toggle so logging can be killed at runtime; bare
`Debug.Log` calls bypass that and will be denied.
- [x] **No scene-wide discovery for dependencies** — New code is
architected so it does not need `FindObjectOfType` / `FindObjectsOfType`
/ `GameObject.Find` / `FindGameObjectsWithTag` to locate what it depends
on. References are wired in — registered through an existing
manager/driver, injected at init, or passed in by the caller — rather
than discovered by scanning the scene at runtime. If a scene scan is
genuinely unavoidable, justify it under **Notes**.
- [x] **No allocations in hot paths** — Per-frame code (Update /
LateUpdate / FixedUpdate, simulation loops, jobs, anything called once
per frame or more) does not allocate. No `new` on reference types, no
LINQ, no `string` concatenation/interpolation, no boxing, no `foreach`
over interface-typed collections. Allocate once at init and reuse the
buffer.
- [x] **No debugging in hot paths** — No log calls of any kind on
per-frame paths, including `BasisDebug`. Hot-path logging floods the
console and incurs cost on every frame regardless of whether the message
is filtered out downstream. If a hot-path log is needed while iterating,
gate it behind `#if UNITY_EDITOR` and remove (or leave gated) before
merge.
- [x] **Hot-path collection access is optimized** — Cache `.Count`
(lists) / `.Length` (arrays) into a local `int` before the loop instead
of re-reading the property each iteration. Prefer `T[]` (with a separate
length int when the array is over-sized) over `List<T>` where the data
is hot — Unity's mono BCL doesn't expose
`CollectionsMarshal.AsSpan(List<T>)`, so a list can't be fed into
`Span<T>` / unsafe paths cleanly. Where the perf justifies it, drop into
`Span<T>` / `ref` locals / `Unsafe.As` / `unsafe` pointer code to skip
bounds checks and copies, and call out the invariants you're relying on
under **Notes** so reviewers can sanity-check them.
<!-- required-checks-end -->
## Testing details
Tick the platforms you actually tested on. Leave the rest unticked —
these are informational and do not block merge.
- [x] Windows
- [ ] Linux
- [ ] Android
- [ ] iOS
- [ ] macOS
Input / control mode coverage:
- [ ] Tested in VR (note headset under **Notes**)
- [ ] Tested in desktop / non-VR mode
- [ ] Tested with phone controls (mobile touch input)
- [x] N/A — change does not touch player/XR/input code
Where applicable, confirm these flows still work after your changes:
- [ ] Hot-switching (desktop ↔ VR mode swap at runtime)
- [ ] Avatar swapping
- [ ] Server swapping (joining / leaving / changing servers)
- [x] N/A — change does not touch any of the above
## Notes
This is almost entirely a native-plugin change under `Native~/`. The one
C# file it touches is `BasisMediaPlayerSecurity.cs` — the SSRF address
classifier, extended (in lockstep with the native `basis_io.c` guard) to
the full IANA "not globally reachable" special-use set. It has no
transform/component/hot-path/per-frame code, so the Unity-specific
required checks (transform access, Addressables, `GetComponent`,
`BasisEventDriver`, per-frame allocation/logging, camera driver, scene
discovery, jobification, collection access) still don't apply and are
ticked as N/A per the template.
**Verification** is via the repo's own native gates, run locally against
the real shipping source rather than a mock: `tools/media-fuzz` (all 10
targets build + run clean under AddressSanitizer +
UndefinedBehaviorSanitizer, and the pinned crash-repro replay gate
passes — including the two shift-UB repros the new RTSP/RTMP fuzzers
surfaced), and `tools/media-conformance` (demux output still matches
ffprobe on all synthetic fixtures, so the caps don't change valid-input
playback). Portable C and `basis_win_decode.cpp` compile clean, and both
native binaries are rebuilt from this source.
One behavioural change for testers: the native transports
(HLS/RTSP/RTMP) now enforce the non-global-unicast address block
themselves, so a `localhost` URL on those transports is refused even in
the Editor unless `BASIS_MEDIA_ALLOW_LOCAL` relaxes the native re-check
(it does not relax the top-level C# gate — a top-level RFC1918 URL stays
refused regardless). Documented in `TESTING.md`.
**Known residuals (deliberate, tracked as follow-ups — not
oversights):**
- **SSRF pre-check depth.** The host check closes literal-internal and
statically-private URLs (the common vector). It does *not* close active
DNS rebinding or an allowed URL that redirects to an internal host,
because the platform HTTP stacks (WinHTTP/JNI) re-resolve and follow
redirects. Fully closing those is a connect-by-pinned-IP change with
per-redirect re-validation and connected-peer verification at the
provider boundary — it needs on-device testing (a naive "reject all 3xx"
breaks legitimate CDN redirects), so it's scoped as its own follow-up.
- **Render-event ABA.** The liveness registry closes the
use-after-*free* of a closed engine. The narrow pointer-reuse edge (a
delayed event matching a *new* engine at the same address) is benign for
the C# binding's `RENDER_UPDATE`-only, idempotent usage; fully closing
it needs a generation-stamped handle in the event payload (a C# ABI
change) — follow-up.
- **RTSP/RTMP fuzz depth.** The new targets drive the buffer-taking
parsers directly (where the found bugs lived); full end-to-end session
fuzzing (scripted handshake) is a follow-up.32 files changed
Lines changed: 929 additions & 853 deletions
File tree
- Basis/Packages/com.basis.mediaplayer
- Native~
- android
- protocol
- unity
- windows
- Plugins
- Android/arm64-v8a
- Windows/x86_64
- Runtime/Core
- tools
- media-fuzz
- native
- testcases
- rtmp
- rtsp
- media-test-streams
- scripts
Lines changed: 17 additions & 9 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
508 | 508 | | |
509 | 509 | | |
510 | 510 | | |
| 511 | + | |
511 | 512 | | |
512 | 513 | | |
513 | 514 | | |
| |||
858 | 859 | | |
859 | 860 | | |
860 | 861 | | |
861 | | - | |
| 862 | + | |
| 863 | + | |
862 | 864 | | |
863 | 865 | | |
864 | 866 | | |
865 | | - | |
866 | | - | |
867 | | - | |
868 | | - | |
| 867 | + | |
| 868 | + | |
| 869 | + | |
| 870 | + | |
| 871 | + | |
| 872 | + | |
| 873 | + | |
| 874 | + | |
| 875 | + | |
869 | 876 | | |
870 | 877 | | |
871 | | - | |
| 878 | + | |
872 | 879 | | |
873 | 880 | | |
874 | 881 | | |
| |||
928 | 935 | | |
929 | 936 | | |
930 | 937 | | |
| 938 | + | |
931 | 939 | | |
932 | 940 | | |
933 | 941 | | |
934 | 942 | | |
935 | | - | |
| 943 | + | |
936 | 944 | | |
937 | | - | |
| 945 | + | |
938 | 946 | | |
939 | 947 | | |
940 | 948 | | |
941 | 949 | | |
942 | 950 | | |
943 | 951 | | |
944 | 952 | | |
945 | | - | |
| 953 | + | |
946 | 954 | | |
947 | 955 | | |
948 | 956 | | |
| |||
Lines changed: 45 additions & 21 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
96 | 96 | | |
97 | 97 | | |
98 | 98 | | |
99 | | - | |
| 99 | + | |
| 100 | + | |
100 | 101 | | |
101 | 102 | | |
102 | | - | |
| 103 | + | |
| 104 | + | |
103 | 105 | | |
104 | 106 | | |
105 | 107 | | |
| |||
407 | 409 | | |
408 | 410 | | |
409 | 411 | | |
410 | | - | |
| 412 | + | |
411 | 413 | | |
412 | 414 | | |
413 | 415 | | |
| |||
434 | 436 | | |
435 | 437 | | |
436 | 438 | | |
437 | | - | |
438 | | - | |
| 439 | + | |
| 440 | + | |
439 | 441 | | |
440 | 442 | | |
441 | 443 | | |
442 | 444 | | |
443 | 445 | | |
444 | 446 | | |
445 | | - | |
446 | | - | |
447 | | - | |
448 | | - | |
449 | | - | |
450 | | - | |
| 447 | + | |
| 448 | + | |
| 449 | + | |
| 450 | + | |
| 451 | + | |
| 452 | + | |
| 453 | + | |
| 454 | + | |
451 | 455 | | |
| 456 | + | |
452 | 457 | | |
453 | 458 | | |
454 | 459 | | |
| 460 | + | |
455 | 461 | | |
456 | 462 | | |
457 | 463 | | |
| |||
494 | 500 | | |
495 | 501 | | |
496 | 502 | | |
497 | | - | |
498 | | - | |
499 | | - | |
500 | | - | |
501 | 503 | | |
| 504 | + | |
| 505 | + | |
| 506 | + | |
| 507 | + | |
502 | 508 | | |
| 509 | + | |
503 | 510 | | |
504 | | - | |
| 511 | + | |
| 512 | + | |
| 513 | + | |
505 | 514 | | |
| 515 | + | |
| 516 | + | |
| 517 | + | |
| 518 | + | |
| 519 | + | |
| 520 | + | |
| 521 | + | |
506 | 522 | | |
| 523 | + | |
507 | 524 | | |
| 525 | + | |
| 526 | + | |
| 527 | + | |
508 | 528 | | |
509 | 529 | | |
510 | 530 | | |
| |||
520 | 540 | | |
521 | 541 | | |
522 | 542 | | |
523 | | - | |
| 543 | + | |
524 | 544 | | |
525 | 545 | | |
526 | 546 | | |
527 | 547 | | |
528 | 548 | | |
529 | 549 | | |
530 | | - | |
531 | | - | |
532 | | - | |
| 550 | + | |
| 551 | + | |
| 552 | + | |
| 553 | + | |
| 554 | + | |
| 555 | + | |
| 556 | + | |
533 | 557 | | |
534 | 558 | | |
535 | 559 | | |
| |||
572 | 596 | | |
573 | 597 | | |
574 | 598 | | |
575 | | - | |
| 599 | + | |
576 | 600 | | |
577 | 601 | | |
578 | 602 | | |
| |||
Lines changed: 80 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
227 | 227 | | |
228 | 228 | | |
229 | 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 | + | |
230 | 286 | | |
231 | 287 | | |
232 | 288 | | |
| |||
1177 | 1233 | | |
1178 | 1234 | | |
1179 | 1235 | | |
| 1236 | + | |
| 1237 | + | |
| 1238 | + | |
| 1239 | + | |
| 1240 | + | |
| 1241 | + | |
| 1242 | + | |
| 1243 | + | |
| 1244 | + | |
| 1245 | + | |
| 1246 | + | |
| 1247 | + | |
| 1248 | + | |
| 1249 | + | |
| 1250 | + | |
| 1251 | + | |
1180 | 1252 | | |
1181 | 1253 | | |
1182 | 1254 | | |
| |||
1195 | 1267 | | |
1196 | 1268 | | |
1197 | 1269 | | |
1198 | | - | |
1199 | | - | |
| 1270 | + | |
| 1271 | + | |
| 1272 | + | |
| 1273 | + | |
| 1274 | + | |
| 1275 | + | |
| 1276 | + | |
| 1277 | + | |
1200 | 1278 | | |
1201 | 1279 | | |
1202 | 1280 | | |
| |||
Lines changed: 6 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
228 | 228 | | |
229 | 229 | | |
230 | 230 | | |
| 231 | + | |
| 232 | + | |
| 233 | + | |
| 234 | + | |
| 235 | + | |
| 236 | + | |
231 | 237 | | |
232 | 238 | | |
233 | 239 | | |
| |||
0 commit comments