Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Possibly wrong buffer size in string copy

ID: cpp/bad-strncpy-sizeKind: problemSecurity severity: 9.3Severity: warningPrecision: mediumTags:   - reliability   - correctness   - security   - external/cwe/cwe-676   - external/cwe/cwe-119   - external/cwe/cwe-251Query suites:   - cpp-security-extended.qls   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

The standard library functionstrncpy copies a source string to a destination buffer. The third argument defines the maximum number of characters to copy and should be less than or equal to the size of the destination buffer. Calls of the formstrncpy(dest,src,strlen(src)) orstrncpy(dest,src,sizeof(src)) incorrectly set the third argument to the size of the source buffer. Executing a call of this type may cause a buffer overflow. Buffer overflows can lead to anything from a segmentation fault to a security vulnerability.

Recommendation

Check the highlighted function calls carefully, and ensure that the size parameter is derived from the size of the destination buffer, not the source buffer.

Example

In the following examples, the size of the source buffer is incorrectly used as a parameter tostrncpy:

charsrc[256];chardest1[128];...strncpy(dest1,src,sizeof(src));// wrong: size of dest should be usedchar*dest2=(char*)malloc(sz1+sz2+sz3);strncpy(dest2,src,strlen(src));// wrong: size of dest should be used

The corrected version uses the size of the destination buffer, or a variable containing the size of the destination buffer as the size parameter tostrncpy:

charsrc[256];chardest1[128];...strncpy(dest1,src,sizeof(dest1));// correctsize_tdestSize=sz1+sz2+sz3;char*dest2=(char*)malloc(destSize);strncpy(dest2,src,destSize);// correct

References

  • cplusplus.com:strncpy.

  • I. Gerg.An Overview and Example of the Buffer-Overflow Exploit. IANewsletter vol 7 no 4. 2005.

  • M. Donaldson.Inside the Buffer Overflow Attack: Mechanism, Method & Prevention. SANS Institute InfoSec Reading Room. 2002.

  • Common Weakness Enumeration:CWE-676.

  • Common Weakness Enumeration:CWE-119.

  • Common Weakness Enumeration:CWE-251.


[8]ページ先頭

©2009-2025 Movatter.jp