Use of dangerous function¶
ID: cpp/dangerous-function-overflowKind: problemSecurity severity: 10.0Severity: errorPrecision: very-highTags: - reliability - security - external/cwe/cwe-242 - external/cwe/cwe-676Query suites: - cpp-code-scanning.qls - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This rule finds calls to thegets function, which is dangerous and should not be used. SeeRelated rules below for rules that identify other dangerous functions.
Thegets function is one of the vulnerabilities exploited by the Internet Worm of 1988, one of the first computer worms to spread through the Internet. Thegets function provides no way to limit the amount of data that is read and stored, so without prior knowledge of the input it is impossible to use it safely with any size of buffer.
Recommendation¶
Replace calls togets withfgets, specifying the maximum length to copy. This will prevent the buffer overflow.
Example¶
The following example gets a string from standard input in two ways:
#define BUFFERSIZE (1024)// BAD: using getsvoidecho_bad(){charbuffer[BUFFERSIZE];gets(buffer);printf("Input was: '%s'\n",buffer);}// GOOD: using fgetsvoidecho_good(){charbuffer[BUFFERSIZE];fgets(buffer,BUFFERSIZE,stdin);printf("Input was: '%s'\n",buffer);}
The first version usesgets and will overflow if the input is longer than the buffer. The second version of the code usesfgets and will not overflow, because the amount of data written is limited by the length parameter.
Related rules¶
Other dangerous functions identified by CWE-676 (”Use of Potentially Dangerous Function”) includestrcpy andstrcat. Use of these functions is highlighted by rules for the following CWEs:
References¶
Wikipedia:Morris worm.
E. Spafford.The Internet Worm Program: An Analysis. Purdue Technical Report CSD-TR-823,(online), 1988.
Common Weakness Enumeration:CWE-242.
Common Weakness Enumeration:CWE-676.