Fix arithmetic overflow on untrusted input #2
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.
I reported a similar bug to the original hashIds repo (that was never addressed). I discovered this repo and decided to test the same issue and it also exists here.
In it's current state, you cannot safely decode arbitrary untrusted user input (Imagine a user mistyping a url - which is how I originally discovered this in my app telemetry). I added a test case to this PR to demonstrate the problem and validate the fix. Here is an example:
By generating a squid of
Int64.max
and appending ana
to it, you create an id that when decoded overflows anInt64
. In swift, this will trigger an arithmetic overflow that will crash your program. It is impossible to validate a valid sqid before trying to decode it, so there is no valid way to sanitize user input which risks crashing your program.There are two ways to fix this:
This PR uses approach
2
because the decode function already throws, so it doesn't change the overall usability. (in the original hashids library, this required a bigger (api breaking change) because the original decode function did not throw.Solution
1
is also an option but will produce incorrect results. You can see that implementation in: cc4be61