CWE-120 未进行输入大小检查的缓冲区拷贝(传统缓冲区溢出)

Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')

结构: Simple

Abstraction: Base

状态: Incomplete

被利用可能性: High

基本描述

The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.

扩展描述

A buffer overflow condition exists when a program attempts to put more data in a buffer than it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a buffer. The simplest type of error, and the most common cause of buffer overflows, is the "classic" case in which the program copies the buffer without restricting how much is copied. Other variants exist, but the existence of a classic overflow strongly suggests that the programmer is not considering even the most basic of security protections.

相关缺陷

  • cwe_Nature: ChildOf cwe_CWE_ID: 119 cwe_View_ID: 1000 cwe_Ordinal: Primary

  • cwe_Nature: ChildOf cwe_CWE_ID: 119 cwe_View_ID: 1003 cwe_Ordinal: Primary

  • cwe_Nature: ChildOf cwe_CWE_ID: 119 cwe_View_ID: 699 cwe_Ordinal: Primary

  • cwe_Nature: CanPrecede cwe_CWE_ID: 123 cwe_View_ID: 1000

  • cwe_Nature: ChildOf cwe_CWE_ID: 20 cwe_View_ID: 700 cwe_Ordinal: Primary

适用平台

Language: [{'cwe_Name': 'C', 'cwe_Prevalence': 'Undetermined'}, {'cwe_Name': 'C++', 'cwe_Prevalence': 'Undetermined'}, {'cwe_Class': 'Assembly', 'cwe_Prevalence': 'Undetermined'}]

常见的影响

范围 影响 注释
['Integrity', 'Confidentiality', 'Availability'] Execute Unauthorized Code or Commands Buffer overflows often can be used to execute arbitrary code, which is usually outside the scope of a program's implicit security policy. This can often be used to subvert any other security service.
Availability ['DoS: Crash, Exit, or Restart', 'DoS: Resource Consumption (CPU)'] Buffer overflows generally lead to crashes. Other attacks leading to lack of availability are possible, including putting the program into an infinite loop.

检测方法

DM-1 Automated Static Analysis

This weakness can often be detected using automated static analysis tools. Many modern tools use data flow analysis or constraint-based techniques to minimize the number of false positives.

Automated static analysis generally does not account for environmental considerations when reporting out-of-bounds memory operations. This can make it difficult for users to determine which warnings should be investigated first. For example, an analysis tool might report buffer overflows that originate from command line arguments in a program that is not expected to run with setuid or other special privileges.

Detection techniques for buffer-related errors are more mature than for most other weakness types.

DM-2 Automated Dynamic Analysis

This weakness can be detected using dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.

DM-9 Manual Analysis

Manual analysis can be useful for finding this weakness, but it might not achieve desired code coverage within limited time constraints. This becomes difficult for weaknesses that must be considered for all inputs, since the attack surface can be too large.

Automated Static Analysis - Binary or Bytecode

According to SOAR, the following detection techniques may be useful:

Highly cost effective:
  • Bytecode Weakness Analysis - including disassembler + source code weakness analysis
  • Binary Weakness Analysis - including disassembler + source code weakness analysis

Manual Static Analysis - Binary or Bytecode

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:
  • Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies

Dynamic Analysis with Automated Results Interpretation

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:
  • Web Application Scanner
  • Web Services Scanner
  • Database Scanners

Dynamic Analysis with Manual Results Interpretation

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:
  • Fuzz Tester
  • Framework-based Fuzzer

Manual Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:
  • Focused Manual Spotcheck - Focused manual analysis of source
  • Manual Source Code Review (not inspections)

Automated Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Highly cost effective:
  • Source code Weakness Analyzer
  • Context-configured Source Code Weakness Analyzer

Architecture or Design Review

According to SOAR, the following detection techniques may be useful:

Highly cost effective:
  • Formal Methods / Correct-By-Construction
Cost effective for partial coverage:
  • Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)

可能的缓解方案

MIT-3 Requirements

策略: Language Selection

Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer. Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.

MIT-4.1 Architecture and Design

策略: Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.

MIT-10 Build and Compilation

策略: Compilation or Build Hardening

Run or compile the software using features or extensions that automatically provide a protection mechanism that mitigates or eliminates buffer overflows. For example, certain compilers and extensions provide automatic buffer overflow detection mechanisms that are built into the compiled code. Examples include the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice.

MIT-9 Implementation

策略: Consider adhering to the following rules when allocating and managing an application's memory:

MIT-5 Implementation

策略: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

MIT-15 Architecture and Design

策略:

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

MIT-11 Operation

策略: Environment Hardening

Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64].

MIT-12 Operation

策略: Environment Hardening

Use a CPU and operating system that offers Data Execution Protection (NX) or its equivalent [REF-60] [REF-61].

['Build and Compilation', 'Operation']

策略:

Most mitigating technologies at the compiler or OS level to date address only a subset of buffer overflow problems and rarely provide complete protection against even that subset. It is good practice to implement strategies to increase the workload of an attacker, such as leaving the attacker to guess an unknown value that changes every program execution.

MIT-13 Implementation

策略:

Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.

MIT-21 Architecture and Design

策略: Enforcement by Conversion

When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.

MIT-17 ['Architecture and Design', 'Operation']

策略: Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

MIT-22 ['Architecture and Design', 'Operation']

策略: Sandbox or Jail

Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software. OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations. This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise. Be careful to avoid CWE-243 and other weaknesses related to jails.

示例代码

The following code asks the user to enter their last name and then attempts to store the value entered in the last_name array.

bad C

char last_name[20];
printf ("Enter your last name: ");
scanf ("%s", last_name);

The problem with the code above is that it does not restrict or limit the size of the name entered by the user. If the user enters "Very_very_long_last_name" which is 24 characters long, then a buffer overflow will occur since the array can only hold 20 characters total.

The following code attempts to create a local copy of a buffer to perform some manipulations to the data.

bad C

void manipulate_string(char* string){
char buf[24];
strcpy(buf, string);
...
}

However, the programmer does not ensure that the size of the data pointed to by string will fit in the local buffer and blindly copies the data with the potentially dangerous strcpy() function. This may result in a buffer overflow condition if an attacker can influence the contents of the string parameter.

The excerpt below calls the gets() function in C, which is inherently unsafe.

bad C

char buf[24];
printf("Please enter your name and press <Enter>\n");
gets(buf);
...
}

However, the programmer uses the function gets() which is inherently unsafe because it blindly copies all input from STDIN to the buffer without restricting how much is copied. This allows the user to provide a string that is larger than the buffer size, resulting in an overflow condition.

In the following example, a server accepts connections from a client and processes the client request. After accepting a client connection, the program will obtain client information using the gethostbyaddr method, copy the hostname of the client that connected to a local variable and output the hostname of the client to a log file.

bad C

...
struct hostent clienthp;
char hostname[MAX_LEN];

// create server socket, bind to server address and listen on socket
...

// accept client connections and process requests
int count = 0;
for (count = 0; count < MAX_CONNECTIONS; count++) {

int clientlen = sizeof(struct sockaddr_in);
int clientsocket = accept(serversocket, (struct sockaddr
)&clientaddr, &clientlen);

if (clientsocket >= 0) {
clienthp = gethostbyaddr((char*) &clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);
strcpy(hostname, clienthp->h_name);
logOutput("Accepted client connection from host ", hostname);

// process client request
...
close(clientsocket);
}
}
close(serversocket);

...

However, the hostname of the client that connected may be longer than the allocated size for the local hostname variable. This will result in a buffer overflow when copying the client hostname to the local variable using the strcpy method.

分析过的案例

标识 说明 链接
CVE-2000-1094 buffer overflow using command with long argument https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2000-1094
CVE-1999-0046 buffer overflow in local program using long environment variable https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-1999-0046
CVE-2002-1337 buffer overflow in comment characters, when product increments a counter for a ">" but does not decrement for "<" https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1337
CVE-2003-0595 By replacing a valid cookie value with an extremely long string of characters, an attacker may overflow the application's buffers. https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2003-0595
CVE-2001-0191 By replacing a valid cookie value with an extremely long string of characters, an attacker may overflow the application's buffers. https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2001-0191

Notes

Relationship At the code level, stack-based and heap-based overflows do not differ significantly, so there usually is not a need to distinguish them. From the attacker perspective, they can be quite different, since different techniques are required to exploit them. Terminology Many issues that are now called "buffer overflows" are substantively different than the "classic" overflow, including entirely different bug types that rely on overflow exploit techniques, such as integer signedness errors, integer overflows, and format string bugs. This imprecise terminology can make it difficult to determine which variant is being reported.

分类映射

映射的分类名 ImNode ID Fit Mapped Node Name
PLOVER Unbounded Transfer ('classic overflow')
7 Pernicious Kingdoms Buffer Overflow
CLASP Buffer overflow
OWASP Top Ten 2004 A1 CWE More Specific Unvalidated Input
OWASP Top Ten 2004 A5 CWE More Specific Buffer Overflows
CERT C Secure Coding STR31-C Exact Guarantee that storage for strings has sufficient space for character data and the null terminator
WASC 7 Buffer Overflow
Software Fault Patterns SFP8 Faulty Buffer Access
OMG ASCSM ASCSM-CWE-120
OMG ASCRM ASCRM-CWE-120

相关攻击模式

  • CAPEC-10
  • CAPEC-100
  • CAPEC-14
  • CAPEC-24
  • CAPEC-42
  • CAPEC-44
  • CAPEC-45
  • CAPEC-46
  • CAPEC-47
  • CAPEC-67
  • CAPEC-8
  • CAPEC-9
  • CAPEC-92

引用