VNX-704: File or content size narrowed from long with an unchecked cast
Reports Java casts to int, short, char or byte of a long file or content size (File.length(), Files.size(), FileChannel.size(), getContentLengthLong(), HttpEntity.getContentLength(), MultipartFile/ZipEntry getSize(), getFilePointer()), directly or through a long variable that is not bounds-checked first.
| Field | Value |
|---|---|
| Rule ID | VNX-704 |
| Severity | Low |
| SARIF level | note |
| Kind | sast |
| Languages | Java |
| CWE | CWE-704 |
| CAPEC | CAPEC-66 |
| ATT&CK | T1190 |
| CWSS vector | CWSS:1.0/TI:L/AP:RU/AL:S/IC:N/FC:LT/RP:RU/RL:S/AV:L/AS:N/IN:A/SC:A/BI:L/DI:H/EX:L/EC:N/P:L |
| Tags | incorrect-type-conversion narrowing-cast cwe-704 |
| Source | internal/sast/rules/vnx-704.rego |
Overview
VNX-704 maps to CWE-704: Incorrect Type Conversion or Cast. Java reports file, upload and response sizes as long. Casting one to int (or short, char, byte) silently wraps past the narrow type’s range: a file over 2 GB allocates a negative or tiny buffer, which throws NegativeArraySizeException or reads a truncated file, and a size limit checked after the cast is passed by a value that exceeds it.
The rule reports, in .java files:
(int)/(short)/(char)/(byte)applied directly toFile.length()(a receiver declaredFile/RandomAccessFilein the file, a receiver named likefile/srcFile, ornew File(...)),Files.size(...),getFilePointer(),getContentLengthLong(),contentLength(),getSize()andgetCompressedSize();- such a cast of a variable declared
longand assigned from one of those (or from a.length()/.size()call) in the 15 lines above.
Not reported: Math.toIntExact(...), a variable compared with Integer.MAX_VALUE or any limit between the assignment and the cast, casts of parenthesised arithmetic, casts of int-valued calls (String.length(), stream count(), Math.round), comments and string literals. Narrowing of Integer.parseInt/Long.parseLong results is VNX-192.
What Gets Flagged
byte[] buf = new byte[(int) file.length()]; // FLAGGED
byte[] out = new byte[(int) Files.size(p)]; // FLAGGED
return new byte[(int) upload.getSize()]; // FLAGGED
long size = source.length();
return new byte[(int) size]; // FLAGGED
What Is Not Flagged
return new byte[Math.toIntExact(file.length())];
long size = Files.size(p);
if (size > Integer.MAX_VALUE) {
throw new IllegalStateException("too large");
}
return new byte[(int) size];
Remediation
- Use
Math.toIntExact(...), which throws instead of wrapping. - Reject sizes above an explicit limit before converting, or stream the content instead of allocating one buffer for it.
References
Suppressing this rule
Put a nosec comment on the line, or on line 1 to cover the whole file. Use the comment marker of the file’s language (#, //, -- or ;):
# nosec vnx-704
// nosec vnx-704
Or record an ignore rule: vulnetix ignore add --rule vnx-704 --reason "...". See Suppressing findings.