codeql icon indicating copy to clipboard operation
codeql copied to clipboard

Rewrite recommendations for the query `cpp/no-space-for-terminator`

Open rvermeulen opened this issue 1 year ago • 1 comments

This PR aims to improve the recommendations with the following changes:

  • Replace segmentation fault with crash that is platform agnostic (I think segmentation fault is not really a thing on Windows).
  • Replace security vulnerability with malicious code execution. This provides a range of issues, because a crash (previously segmentation fault) could also be considered a security vulnerability. Namely a DOS.
  • Removed the additional note on stack allocated arrays which seem confusing because we are always talking about buffers allocated on the heap.

rvermeulen avatar May 24 '24 23:05 rvermeulen

QHelp previews:

cpp/ql/src/Security/CWE/CWE-131/NoSpaceForZeroTerminator.qhelp

No space for zero terminator

This rule identifies calls to malloc that call strlen to determine the required buffer size, but do not allocate space for the zero terminator.

Recommendation

The highlighted code segment creates a buffer without ensuring it's large enough to accommodate the copied data. This leaves the code susceptible to a buffer overflow attack, which could lead to anything from program crashes to malicious code execution.

Increase the size of the buffer being allocated by one or replace malloc, strcpy pairs with a call to strdup

Example


void flawed_strdup(const char *input)
{
	char *copy;

	/* Fail to allocate space for terminating '\0' */
	copy = (char *)malloc(strlen(input));
	strcpy(copy, input);
	return copy;
}


References

github-actions[bot] avatar May 24 '24 23:05 github-actions[bot]

Removed the additional note on stack allocated arrays which seem confusing because we are always talking about buffers allocated on the heap.

This is not correct. alloca is also covered by this query. However, I'm fine with removing this remark.

jketema avatar May 27 '24 14:05 jketema