Web Application Security Guide/Truncation attacks, trimming attacks< Web Application Security Guide
Truncation attacks, trimming attacks
Truncating input can be problematic if the truncation affects comparisons (e.g. checking users against a blacklist before truncation, and then truncating the name to perform the login). SQL queries can be truncated if they exceed a certain length. This can be used to execute a query with significantly different meaning (e.g. cutting of a part of a
WHERE clause). Strings can also be automatically trimmed (leading/trailing whitespace removed), leading to the same vulnerabilities (e.g. checking the input "eviluser␣" against the blacklist, then logging in "eviluser"). SQL may do such trimming automatically.
To prevent this type of attack
- Avoid truncating input. Treat overlong input as an error instead.
- If truncation is necessary, ensure to check the value after truncation and use only the truncated value
- Make sure trimming does not occur or checks are done consistently
- Introduce length checks
- care about different lengths due to encoding
- Make sure SQL treats truncated queries as errors by setting an appropriate SQL MODE
Avoiding truncation makes sure no issues can arise. If truncation is applied, performing all necessary checks after the truncation and using only the truncated value is equivalent to receiving the value in truncated condition. The same rules apply for trimming. Length checks prevent unexpected truncation due to length limits. Encoding needs to be taken into account because the byte-lengths and character-lengths of a UTF-8 string may be different. Setting the SQL MODE so that truncation causes errors ensures that truncation cannot be abused to modify queries. However, the resulting errors can still cause queries to fail unexpectedly, which should be handled in a secure manner.