CWE-467 在指针类型上使用sizeof()
Use of sizeof() on a Pointer Type
结构: 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. |
可能的缓解方案
Implementation
策略:
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
...
foo = (double )malloc(sizeof(foo));
In this example, sizeof(*foo) returns the size of the data structure and not the size of the pointer.
good C
...
foo = (double )malloc(sizeof(*foo));
例
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
/ Ignore CWE-259 (hard-coded password) and CWE-309 (use of password system for authentication) for this example. /
char username = "admin";
char pass = "password";
int AuthenticateUser(char inUser, char inPass) {
printf("Sizeof pass = %dn", sizeof(pass));
if (strncmp(username, inUser, sizeof(username))) {
return(AUTH_FAIL);
}
/ Because of CWE-467, the sizeof returns 4 on many platforms and architectures. /
if (! strncmp(pass, inPass, sizeof(pass))) {
return(AUTH_SUCCESS);
}
else {
return(AUTH_FAIL);
}
}
int main (int argc, char **argv)
{
if (argc ExitError("Usage: Provide a username and password");
}
authResult = AuthenticateUser(argv[1], argv[2]);
if (authResult != AUTH_SUCCESS) {
}
else {
}
}文章来源于互联网:scap中文网
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论