Improper String Length Checking

From Guidance Share

Jump to: navigation, search



Improper string length checking takes place when wide or multi-byte character strings are mistaken for standard character strings.

Applies To

  • Language: C, C++
  • Platform: All


The following example would be exploitable if any of the commented incorrect malloc calls were used.

#include <stdio.h>
#include <strings.h>
#include <wchar.h>
int main() { 
wchar_t wideString[] = L"The spazzy orange tiger jumped ” \ 
“over the tawny jaguar."; 
wchar_t *newString; 
printf("Strlen() output: %d\nWcslen() output: %d\n", 
strlen(wideString), wcslen(wideString)); 
/* Very wrong for obvious reasons // 
newString = (wchar_t *) malloc(strlen(wideString)); 
/* Wrong because wide characters aren't 1 byte long! // 
newString = (wchar_t *) malloc(wcslen(wideString)); 
/* correct! */ 
newString = (wchar_t *) malloc(wcslen(wideString) * 
/* ... */

The output from the printf() statement would be: Strlen() output: 0 Wcslen() output: 53


  • Access control: This flaw is exploited most frequently when it results in a buffer overflow condition, which leads to arbitrary code execution.
  • Availability: Even if the flaw remains unexploded, the probability that the process will crash due to the writing of data over arbitrary memory may result in a crash.


  • Failure to account for the differences in size between wide or mulit-byte characters and normal characters


  • Requirements specification: A language which is not subject to this flaw may be chosen.
  • Implementation: Ensure that if wide or multi-byte strings are in use that all functions which interact with these strings are wide and multi-byte character compatible, and that the maximum character size is taken into account when memory is allocated.
  • Build: Use of canary-style overflow prevention techniques at compile time may serve to complicate exploitation but cannot mitigate it fully; nor will this technique have any effect on process stability. This is not a complete mitigation technique.

Vulnerability Patterns

How Tos

Personal tools