fix Size computation for allocation may overflow #381
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
fix the problem need to ensure that the size computation does not overflow. This can be achieved by validating the size of
hll.SparseData
before performing the arithmetic operation. Specifically, we should check iflen(hll.SparseData)
is within a safe range that guarantees no overflow will occur when multiplied byrecordValueBytes
.Performing calculations involving the size of potentially large strings or slices can result in an overflow (for signed integer types) or a wraparound (for unsigned types). An overflow causes the result of the calculation to become negative, while a wraparound results in a small (positive) number. This can cause further issues. If, the result is then used in an allocation, it will cause a runtime panic if it is negative, and allocate an unexpectedly small buffer otherwise.
POC
In the following example, assume that there is a function
encryptBuffer
that encrypts byte slices whose length must be padded to be a multiple of 16. The functionencryptValue
provides a convenience wrapper around this function: when passed an arbitrary value, it first encodes that value as JSON, pads the resulting byte slice, and then passes it toencryptBuffer
.When passed a value whose JSON encoding is close to the maximum value of type
int
in length, the computation ofsize
will overflow, producing a negative value. When that negative value is passed tomake
, a runtime panic will occur.To guard against this, the function should be improved to check the length of the JSON-encoded value. For example, here is a version of
encryptValue
that ensures the value is no larger than 64 MB, which fits comfortably within anint
and avoids the overflow:References
Integer overflow
Making slices, maps and channels
CWE-190