Repository navigation
Fix out-of-bounds read in pointInPolygon on an unbounded bounding box - #115035
Conversation
…nding box
calcGridAttributes validated the derived grid scales for finiteness but tested
the bounding-box span only for equality with zero. Since 1 / +-inf is +-0.0,
which is finite, an infinite span passed that validation. contains() then
computed (x + x_shift) * x_scale as inf * 0.0 = NaN; NaN compares false against
both the < 0 and > grid_size range guards, static_cast<int>(NaN) yields INT_MIN,
and getCellIndex signed-overflows before indexing a 64-element cells vector.
Classify the span where it is computed instead: a non-positive span (zero, or
the inverse box boost::geometry::envelope leaves for an empty geometry) means
the polygon has no interior, and a non-finite span is rejected with
BAD_ARGUMENTS. This is the only writer of cell_width, cell_height, x_scale and
y_scale, so every reader is covered at once, and no NaN can reach getCellIndex:
with a finite positive span, inf * positive_finite is +-inf, which the existing
range guard already catches.
The predicate is <= 0 rather than !(span > 0) because the two differ only for
NaN. A NaN span already throws BAD_ARGUMENTS today, and !(span > 0) is true for
NaN, which would have turned that into a silent 0.
Four carriers, each measured against pristine HEAD and the patched binary:
- a polygon with vertices at +-DBL_MAX aborts on default settings (this is
what the targeted AST fuzzer found; parseRing's mulOverflow guard does not
stop it because the vertices have y == 0, so the product is 0);
- an empty ring aborts under validate_polygons = 0;
- an empty ring inside a multipolygon trips a boost R-tree assertion,
"Indexable is invalid", from the inverse-box envelope;
- an unbounded span on the y axis does not abort but returns wrong results:
for the triangle (0,-DBL_MAX),(1,DBL_MAX),(2,0) it answers 1 at (1,-1e308),
(1.5,1e308) and (0.5,1e308), where scaling y by 1/DBL_MAX, an affine map
that preserves inside/outside, proves the answer is 0.
Wide but finite polygons keep their results, pinned by non-regression rows.
Three existing tests are extended, each verified to fail before this change;
two of them fail by the server dying, which is the defect itself. The
01940_point_in_polygon_ubsan expectation changes from 0 to BAD_ARGUMENTS: its
polygon has an inf vertex, the same query already throws on default settings
because only validate_polygons = 0 reaches the grid at all, and its 0 came from
the -inf query point hitting the isFinite guard rather than from grid
arithmetic. That matches 04318_polygon_dict_nan_inf_coordinates, which rejects
infinite polygon coordinates.
Issue ClickHouse#11375 reported the same assertion at the same line in 2020 and was fixed
by adding the NaN point guard; that repro still returns 0. This defect arrives
through the span instead, which the point guard does not cover.
Found by the AST fuzzer (amd_debug, targeted), STID 2501-4c25:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112930&sha=27e32067e2142071df32a1cd106e533e54ae645e&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding in round 1,
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20260816-190300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260816-174300 |
|
Workflow [PR], commit [58f6131] Summary: ✅
AI ReviewSummaryThis PR hardens the constant-polygon grid builder in Findings❌ Blockers
Tests
Final VerdictChanges requested: the grid-side fix looks correct, but the constant-polygon parser still has undefined behavior on the same LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · Uncovered code |
|
cc @nikitamikhaylov @rschu1ze, could you review this? pointInPolygon built its lookup grid after checking only that the derived scales were finite, but 1 / +-inf is +-0.0 and passes that check, so a polygon spanning +-DBL_MAX produced a NaN grid coordinate, an INT_MIN cell index, and an out-of-bounds read of cells (an abort in hardened and sanitizer builds, wrong results otherwise); the span itself is now validated where it is computed. |
| } | ||
|
|
||
| /// 1 / +-inf is +-0.0, which is finite: the scales below would pass their own check. | ||
| if (!isFinite(cell_width) || !isFinite(cell_height)) |
There was a problem hiding this comment.
load still goes through parseConstPolygon before it constructs PointInPolygonWithGrid, so the exact +-DBL_MAX repro from the PR body reaches parseRing first. That code still does static_cast<Int64>(x_data[i]) / static_cast<Int64>(y_data[i]) inside mulOverflow (src/Functions/pointInPolygon.cpp:721), and those conversions are already out of range for +-1.7976931348623157e308.
So this new guard fixes the downstream contains OOB once a Polygon object exists, but it does not make the motivating input well-defined end-to-end: the parser can still enter undefined behavior before BAD_ARGUMENTS is thrown. Can we reject these coordinates before the Int64 cast, or replace that precheck with one that does not rely on out-of-range integral conversion?
There was a problem hiding this comment.
All three citations check out: load calls parseConstPolygon before constructing the impl, the static_cast<Int64> at pointInPolygon.cpp:721 is real, and +-DBL_MAX is outside Int64 range, so that conversion is UB. I reproduced the conversion standalone under -fsanitize=undefined.
I am not changing it here, for three measured reasons.
Pre-existing and untouched. This PR's source change is +7/-1 in PolygonUtils.h alone. pointInPolygon.cpp has 0 hunks.
Deliberately ignorelisted since 2021. tests/ubsan_ignorelist.txt:17 carries src:*/Functions/pointInPolygon.cpp under the comment "Some value is outside the range of representable values of type 'long' on user-provided data inside boost::geometry - ignore" (339c12f), wired in at cmake/sanitize.cmake:129,139. There is no live signal either: over 180 days CIDB has 0 rows citing pointInPolygon.cpp next to "runtime error" (control: 970 "runtime error" rows overall) and 0 float-cast-overflow reports anywhere.
The suggested precheck would reject queries that work today. INT64_MAX is 9.22e18, so a cast-range check excludes most of the double range, and polygons above it currently give correct answers. Every coordinate below is out of Int64 range, and these return 1, 0, 1:
SELECT pointInPolygon((1e19, 0.5), [(0., 0.), (2e19, 0.), (2e19, 1.), (0., 1.)]); -- inside
SELECT pointInPolygon((3e19, 0.5), [(0., 0.), (2e19, 0.), (2e19, 1.), (0., 1.)]); -- outside
SELECT pointInPolygon((1e199, 0.5), [(0., 0.), (1e200, 0.), (1e200, 1.), (0., 1.)]);Rejecting out-of-Int64-range coordinates turns all three into errors, including the inside/outside pair that discriminates correctly today. The cast result is also discarded: only the overflow flag is read, and the vertex stored is the raw Float64 pair.
On the end-to-end point: the motivating input is well-defined in observable behaviour after this change. On the two binaries built from this branch, the repro aborts with vector[] index out of bounds before, and returns Code: 36 ... bounding box is unbounded after. Making that precheck range-correct is a fair separate change, but it moves the accepted coordinate domain and does not belong in a P0 out-of-bounds fix.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 22 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 58f6131CI is fully finished on this head and it is clean: 177 check-runs, 160 success / 17 skipped,
Those four CIDB rows are historical, not open. All predate the label being applied; both jobs then The three regression tests ran on this head with 0 failures: Session id: cron:our-pr-ci-monitor:20260817-020000 |
84d3205
Related: #11375
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed an out-of-bounds read in
pointInPolygonwith a constant polygon whose bounding box is unbounded, for example when a coordinate reaches+-DBL_MAX. Such a polygon is now rejected withBAD_ARGUMENTS, and a polygon with an empty ring is treated as having no interior. Previously the query could return a wrong result, or abort the server in builds with hardening or sanitizers enabled.Description
SELECT pointInPolygon((1e308, 1.), [(-1.7976931348623157e308, 0.), (1.7976931348623157e308, 0.), (0., 2.)])reads a
cellselement out of range, on default settings and with no elevated privileges. Withlibc++ hardening or a sanitizer it aborts (
vector[] index out of bounds); otherwise it switcheson a garbage cell type. Found by the targeted AST fuzzer:
report
(the carrier PR is unrelated to this code).
Root cause.
calcGridAttributesvalidated the derived scales for finiteness but tested thebounding-box span only for
== 0.1 / +-infis+-0.0, which is finite, so an infinite spanpassed validation;
containsthen computedinf * 0.0 = NaN, which compared false against bothrange guards,
static_cast<int>(NaN)gaveINT_MIN, and the cell index overflowed.Change. Classify the span where it is computed: non-positive means no interior
(
has_empty_bound), non-finite is rejected withBAD_ARGUMENTS. Six lines in the only writer ofthe grid scales, so every reader is covered at once.
<= 0rather than!(span > 0)keeps a NaNspan throwing, as it does today.
Scope. Only the preprocessed grid used for constant polygons is changed. A non-constant
polygon column takes the on-the-fly ray-casting path, which builds no grid and cannot reach this
out-of-bounds read; it does lose precision on an unbounded span (
inf/infin the edge formula),a separate pre-existing issue deliberately left alone here.
Validation. Measured against pristine HEAD. Three carriers stop aborting: the wide polygon
above, an empty ring, and an empty ring inside a multipolygon (which tripped a boost R-tree
assertion). A fourth, an unbounded span on the y axis, silently returned wrong answers (
1where an affine analogue proves
0). Wide but finite polygons (1e200) keep their results.3 existing tests extended, each verified to fail before the change; the
polygonsuite is green.Behavior matrix (pristine HEAD vs this PR)
01940_point_in_polygon_ubsanchanges expectation from0toBAD_ARGUMENTS: its polygon hasan
infvertex, so the span is now rejected beforecontainsruns, where its0came from thequery point guard. That guard stays covered by
00500_point_in_polygon_nan.(1e308,1.)vs[(-M,0.),(M,0.),(0.,2.)]BAD_ARGUMENTSBAD_ARGUMENTSvalidate_polygons=00[[[]]]multipolygonvalidate_polygons=00[(0.,-M),(1.,M),(2.,0.)],(1.,-1e308)validate_polygons=01(wrong)BAD_ARGUMENTS[(inf,0.),(inf,0.1),(inf,0.2)]validate_polygons=0BAD_ARGUMENTSBAD_ARGUMENTS1e200span,(0.,1.)/(1e199,0.5)1/11/1validate_polygons=00000M = 1.7976931348623157e308.Version info
26.8.1.1524(included in26.8and later)