结构: Simple
Abstraction: Variant
状态: Draft
被利用可能性: High
The code calls sizeof() on a malloced pointer type, which always returns the wordsize/8. This can produce an unexpected result if the programmer intended to determine how much memory has been allocated.
The use of sizeof() on a pointer can sometimes generate useful information. An obvious case is to find out the wordsize on a platform. More often than not, the appearance of sizeof(pointer) indicates a bug.
cwe_Nature: ChildOf cwe_CWE_ID: 682 cwe_View_ID: 1000 cwe_Ordinal: Primary
cwe_Nature: CanPrecede cwe_CWE_ID: 131 cwe_View_ID: 1000
Language: [{'cwe_Name': 'C', 'cwe_Prevalence': 'Undetermined'}, {'cwe_Name': 'C++', 'cwe_Prevalence': 'Undetermined'}]
范围 | 影响 | 注释 |
---|---|---|
['Integrity', 'Confidentiality'] | ['Modify Memory', 'Read Memory'] | This error can often cause one to allocate a buffer that is much smaller than what is needed, leading to resultant weaknesses such as buffer overflows. |
策略:
Use expressions such as "sizeof(*pointer)" instead of "sizeof(pointer)", unless you intend to run sizeof() on a pointer type to gain some platform independence or if you are allocating a variable on the stack.
Care should be taken to ensure sizeof returns the size of the data structure itself, and not the size of the pointer to the data structure.
In this example, sizeof(foo) returns the size of the pointer.
bad C
In this example, sizeof(*foo) returns the size of the data structure and not the size of the pointer.
good C
This example defines a fixed username and password. The AuthenticateUser() function is intended to accept a username and a password from an untrusted user, and check to ensure that it matches the username and password. If the username and password match, AuthenticateUser() is intended to indicate that authentication succeeded.
bad
In AuthenticateUser(), because sizeof() is applied to a parameter with an array type, the sizeof() call might return 4 on many modern architectures. As a result, the strncmp() call only checks the first four characters of the input password, resulting in a partial comparison (CWE-187), leading to improper authentication (CWE-287).
Because of the partial comparison, any of these passwords would still cause authentication to succeed for the "admin" user:
attack
Because only 4 characters are checked, this significantly reduces the search space for an attacker, making brute force attacks more feasible.
The same problem also applies to the username, so values such as "adminXYZ" and "administrator" will succeed for the username.
映射的分类名 | ImNode ID | Fit | Mapped Node Name |
---|---|---|---|
CLASP | Use of sizeof() on a pointer type | ||
CERT C Secure Coding | ARR01-C | Do not apply the sizeof operator to a pointer when taking the size of an array | |
CERT C Secure Coding | MEM35-C | CWE More Abstract | Allocate sufficient memory for an object |
Software Fault Patterns | SFP10 | Incorrect Buffer Length Computation |