Repository navigation
video: fix DISOpticalFlow heap-buffer-overflow with patch_size > border_size - #29715
Conversation
…er_size
DISOpticalFlowImpl pads I1 of every pyramid level with a fixed 16
pixel border (border_size), while PatchInverseSearch clamps a patch's
sample position to:
i_lower_limit = bsz - psz + 1.0f; // bsz = border_size, psz = patch_size
i_upper_limit = bsz + dis->h - 1.0f;
i.e. a patch may be placed up to patch_size - 1 pixels outside of the
image. computeSSD()/computeSSDMeanNorm() then read patch_size (+1 for
bilinear interpolation) rows/columns starting at that clamped
position, which stays inside the padded buffer only while
patch_size <= border_size. patch_size is user-settable via
setPatchSize() with no upper bound relative to the hardcoded
border_size, so setPatchSize() past 16 -- or a temporal-candidate flow
large enough to push the clamped search against its limit -- reads
past the end of I1s_ext (confirmed via AddressSanitizer,
heap-buffer-overflow in computeSSDMeanNorm).
Fix: size the border to whichever is larger, exactly once, at the top
of prepareBuffers() (where every I1s_ext[i] already gets freshly
created/padded on every calc() call, so this doesn't need any
additional cache-invalidation logic). The needed inequality
(border_size >= patch_size) is independent of image size, so this is
sufficient at every pyramid level uniformly. ocl_prepareBuffers() does
not need the equivalent change: calc()'s CV_OCL_RUN gate only takes
the OpenCL path when patch_size == 8, which is always within the
hardcoded border, so that path can never reach this overflow.
A prior attempt at this exact fix (PR opencv#29600) was closed by a
maintainer, who ran its own added regression test and got the same
ASan heap-buffer-overflow again ("the patch is not efficient"). I
could not reproduce that failure: I reproduced the original overflow
on unfixed 5.x (byte-for-byte the same crash site/allocator stack as
both the original issue report and opencv#29600's own ASan trace), then
applied the same one-line fix and ran opencv#29600's own added test 20x
plus a new 40-trial randomized stress test (patch_size 9-48 -- above
and below border_size=16 -- varying image size, patch_stride, flow
magnitude up to 120px, and a same-instance second calc() call to
exercise buffer re-use across a patch-size change) under
AddressSanitizer with zero failures. I don't have an explanation for
the discrepancy (possibly a stale incremental build on the original
report's end, since I hit and had to work around exactly that kind of
false "no work to do" build-cache issue myself while reproducing this)
-- flagging this openly rather than asserting certainty either way.
Verified locally:
- Built an ASan+UBSan-style instrumented Debug configuration
(-fsanitize=address, core+imgproc+features+flann+video+ts) separate
from the Release build used for the rest of today's changes,
specifically to reproduce and verify this memory-safety class of bug
properly rather than relying on a Release build where an
out-of-bounds read often silently returns garbage instead of
crashing.
- Confirmed the crash reproduces on unfixed 5.x, and is gone with the
fix, under both the exact regression_20185_patch_larger_than_border
test and the new randomized regression_20185_stress test (40
trials), both passing cleanly under ASan.
- Re-verified both new tests pass in the standard Release build_verify
configuration used for the rest of today's PRs.
- Full opencv_test_video suite (both ASan and Release): no failures
attributable to this change; all failures present are pre-existing,
needing opencv_extra test data (tracking/ECC/optical-flow reference
videos and images) not configured in this scoped build.
|
@asmorkalov please review the PR and start the workflow passing. I have made all the checks and passes it is clean .able to merge. Thank you. |
|
The original issue says that the bug is reproducible with particular images only, but not random pixels. With random pixels the issue is visible with ASAN, so we can treat it as suitable reproducer. |
|
Please re-target the PR to 4.x branch, the issue is reproducible there too. |
|
@Thebinary110 Friendly reminder. |
|
@asmorkalov yes working on it was stuck with something else will resolve it today itself. |
- border_size is object state that persists across calc() calls; per review, growing it based on the current patch_size made "the next frames processed with border_size > 16" -- correct in that prepareBuffers() recomputes it fresh every call so it doesn't actually leak stale values across frames, but still the wrong place to put a per-call derived quantity. Reverted that change entirely; border_size stays the constant 16 it always was. Instead, fixed this at the point that actually needs to respect the border: PatchInverseSearch_ParBody's i/j_lower_limit and i/j_upper_limit, which clamp how far a patch search may be pushed outside the image. These now also account for the read window (patch_size, plus 1 for bilinear interpolation) needing to stay inside the *existing* padded buffer, rather than assuming patch_size <= border_size always holds. For patch_size <= border_size (the common case, e.g. the default of 8) the bounds are algebraically identical to the originals -- verified no test/behavior change for default settings. - Replaced the local, explicitly-seeded RNG in both new tests with theRNG(), which the test system already seeds per-test. - Removed the comments duplicating what's in the PR description. While re-verifying under the same ASan setup used originally, the stress test's initial patch_stride range (independent of patch_size) surfaced a second, unrelated heap-buffer-overflow in precomputeStructureTensor(): its buffer-allocation size (cur_cols / patch_stride) and its usage formula (1 + (w - patch_size) / patch_stride) can disagree once patch_stride is comparable to or larger than the *effective* patch_size (which autoSelectPatchSizeAndScales can silently reduce for a given image size, independent of what setPatchSize() was called with). This is a real, separate, pre-existing bug, but out of scope for opencv#20185 -- constrained the stress test's patch_stride to a small fixed value (matching every built-in preset, all of which keep stride well below patch_size) instead of trying to fix it here. Re-verified with the same rigor as the original PR: ASan build, 20185_patch_larger_than_border and 20185_stress passing cleanly across 10 repeated runs plus a full opencv_test_video pass (no failures beyond the same pre-existing missing-opencv_extra-data ones as before); Release build_verify shows the same.
|
Pushed a commit addressing all review comments:
One thing worth flagging: while re-verifying under ASan with the new approach, the stress test's original (patch_size-independent) `patch_stride` range surfaced a second, unrelated heap-buffer-overflow in `precomputeStructureTensor()` -- its buffer-allocation formula (`cur_cols / patch_stride`) and its usage formula (`1 + (w - patch_size) / patch_stride`) can disagree once `patch_stride` is comparable to or larger than the effective `patch_size` (which `autoSelectPatchSizeAndScales()` can silently reduce for a given image size, independent of what `setPatchSize()` was called with). This looks like a real, separate, pre-existing bug -- I constrained the stress test's `patch_stride` to stay well below `patch_size` (matching every built-in preset) to keep this PR scoped to #20185, rather than trying to fix it here. Happy to file a separate issue for it if that's useful. Re-verified with the same ASan setup as before: both regression tests pass cleanly across 10 repeated runs, plus a full `opencv_test_video` pass (no failures beyond the same pre-existing missing-`opencv_extra`-data ones present before this PR). |
|
Re: retargeting to 4.x -- this branch descends from 5.x, and the two branches have diverged too far (module reorg etc.) for a literal base-branch change to produce a reviewable diff (~2M lines). Opened a separate PR instead with the same two commits cherry-picked cleanly onto 4.x's current tip: #29853. Verified there the same way as here -- reproduced the crash on pristine 4.x with ASan, confirmed it's fixed, full opencv_test_video pass. |
…erflow video: fix DISOpticalFlow heap-buffer-overflow with patch_size > border_size - #29853 Fixes #20185. 4.x companion to #29715. @asmorkalov asked to retarget #29715 to 4.x since the issue reproduces there too, but that PR's branch descends from 5.x, so literally changing its base produces an unreviewable ~2M-line diff (the two branches have diverged far beyond this module). Opening a separate PR instead: same two commits, cherry-picked cleanly onto 4.x's current tip with zero conflicts (`modules/video/src/dis_flow.cpp` is byte-for-byte identical between the branches apart from this fix). ### What / why See #29715 for the full writeup. Summary: `DISOpticalFlowImpl` pads `I1` with a fixed 16px border, while `PatchInverseSearch`'s search-position clamp lets a patch be placed up to `patch_size - 1` px outside the image -- safe only while `patch_size <= border_size`. Since `patch_size` is user-settable with no upper bound relative to the hardcoded border, `setPatchSize()` past 16 (or a large-enough temporal-candidate flow) reads past the end of the padded buffer (confirmed via AddressSanitizer). Fix (per review on #29715): rather than growing the persistent `border_size` object field to match `patch_size` (which a reviewer correctly flagged as the wrong place for a per-call derived quantity), the search clamp itself (`i/j_lower_limit`, `i/j_upper_limit` in `PatchInverseSearch_ParBody`) now accounts for the read window needing to stay inside the *existing* padded buffer. For `patch_size <= border_size` (every built-in preset) the bounds are algebraically identical to the originals -- `border_size` itself is untouched. ### Testing Verified this reproduces identically on 4.x: built an ASan-instrumented Debug configuration (`core+imgproc+imgcodecs+features2d+flann+video+ts`), confirmed the crash reproduces on pristine 4.x (same crash site as the original report), confirmed it's gone with this fix, and ran the new `regression_20185_patch_larger_than_border` / `regression_20185_stress` tests (5 repeated runs) plus the full `opencv_test_video` suite -- no failures attributable to this change (everything else failing needs `opencv_extra` test data not configured in this scoped build). ### PR checklist - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on code under GPL or another incompatible license. - [x] The PR is proposed to the proper branch (4.x, per maintainer request on #29715). - [x] Accuracy tests included (see above). - [x] No public API/behavior change, so no documentation or sample updates needed.
|
@Thebinary110 Please synchronize the changes with 4.x patch and I'll merge it. |
|
@Thebinary110 Friendly reminder. |
The stress test ran DIS 40 times per invocation for little added coverage beyond the existing targeted regression test; dropping it per review. Also condensed the clamp-bounds comment in PatchInverseSearch_ParBody down to its essential rationale.
|
@asmorkalov yeah I am was looking for any discrepancies in 4.x version. pushing the changes review , allow the tests and merge. and also now since I have contributed well enough to proof you can assign me tasks to solve or any :feature to work on. I will be more than happy to work on it. |
|
@asmorkalov Synced -- cherry-picked the same follow-up commit from #29853 onto this branch (drop the stress test, trim the clamp-bounds comment). Verified under the same ASan setup as before: both files are now byte-identical to #29853's current state, and the remaining regression test passes cleanly. |
|
@asmorkalov |
Fixes #20185.
What
DISOpticalFlowImplpadsI1of every pyramid level with a fixed 16 pixel border (border_size), whilePatchInverseSearchclamps a patch's sample position to:i.e. a patch may be placed up to
patch_size - 1pixels outside of the image.computeSSD()/computeSSDMeanNorm()then readpatch_size(+1 for bilinear interpolation) rows/columns starting at that clamped position, which stays inside the padded buffer only whilepatch_size <= border_size.patch_sizeis user-settable viasetPatchSize()with no upper bound relative to the hardcodedborder_size-- sosetPatchSize()past 16, or a temporal-candidate flow large enough to push the clamped search against its limit, reads past the end ofI1s_ext(confirmed via AddressSanitizer: heap-buffer-overflow incomputeSSDMeanNorm).Fix
Size the border to whichever is larger, exactly once, at the top of
prepareBuffers()(where everyI1s_ext[i]already gets freshly created/padded on everycalc()call, so this doesn't need any additional cache-invalidation logic):border_size = max(16, patch_size);The needed inequality (
border_size >= patch_size) is independent of image size, so this is sufficient at every pyramid level uniformly.ocl_prepareBuffers()does not need the equivalent change:calc()'sCV_OCL_RUNgate only takes the OpenCL path whenpatch_size == 8exactly, which is always within the hardcoded border, so that path can never reach this overflow.On the prior attempt
A prior attempt at this exact fix (#29600) was closed by @asmorkalov, who ran its own added regression test and got the same ASan heap-buffer-overflow again ("the patch is not efficient"). I want to be upfront about this rather than just re-submitting the same-looking diff: I could not reproduce that failure. I reproduced the original overflow on unfixed 5.x (same crash site / allocator stack as both the original issue report and #29600's own ASan trace), then applied the same one-line fix and ran #29600's own added test 20x plus a new 40-trial randomized stress test (
patch_size9-48 -- spanning above and belowborder_size=16-- varying image size,patch_stride, flow magnitude up to 120px, and a same-instance secondcalc()call to exercise buffer re-use across a patch-size change) under AddressSanitizer, with zero failures. I don't have a confirmed explanation for the discrepancy -- possibly a stale incremental build on the original attempt's end, since I hit and had to work around exactly that kind of false "no work to do" ninja build-cache issue myself while setting up this reproduction. Flagging this openly rather than asserting certainty either way -- happy to dig further if CI or review surfaces a case this doesn't cover.Testing
Verified locally with a dedicated ASan-instrumented Debug build (
-fsanitize=address, separate from the Release build used to verify the rest of today's changes), specifically because an out-of-bounds read like this often just silently returns garbage in a Release build instead of crashing:regression_20185_patch_larger_than_border(from video: fix out-of-bounds read in DISOpticalFlow with patch_size larger than the border #20185 🤖🤖🤖 #29600, included here) and a newregression_20185_stresstest (40 randomized trials) -- both passing cleanly under ASan.opencv_test_videosuite (both ASan and Release): no failures attributable to this change; everything else failing needsopencv_extratest data (tracking/ECC/optical-flow reference videos/images) not configured in this scoped build.PR checklist