CWE-1341
Description
The product attempts to close or release a resource or handle more than once, without any successful open between the close operations.
Note that while the implementation for most (if not all) resource reservation allocations involve a unique identifier/pointer/symbolic reference, then if this identifier is reused, checking the identifier for resource closure may result in a false state of openness and closing of the wrong resource. For this reason, reuse of identifiers is discouraged.
Consequences
Depending on the type of resource and the expected API behavior, this could lead to memory corruption, data corruption, or execution path corruption.
Mitigations
Change the code's logic so that the resource is only closed once. This might require simplifying or refactoring. This fix can be simple to do in small code blocks, but more difficult when multiple closes are buried within complex conditionals.
It can be effective to implement a flag that is (1) set when the resource is opened, (2) cleared when it is closed, and (3) checked before closing. This approach can be useful when there are disparate cases in which closes must be performed. However, flag-tracking can increase code complexity and requires diligent compliance by the programmer.
When closing a resource, set the resource's associated variable to NULL or equivalent value for the given language. Some APIs will ignore this null value without causing errors. For other APIs, this can lead to application crashes or exceptions, which may still be preferable to corrupting an unintended resource such as memory or data.
Detection
For commonly-used APIs and resource types, automated tools often have signatures that can spot this issue.
Some compiler instrumentation tools such as AddressSanitizer (ASan) can indirectly detect some instances of this weakness.