CWE-365 Switch语句中的竞争条件

Race Condition in Switch

结构: Simple

Abstraction: Base

状态: Draft

被利用可能性: Medium

基本描述

The code contains a switch statement in which the switched variable can be modified while the switch is still executing, resulting in unexpected behavior.

扩展描述

This issue is particularly important in the case of switch statements that involve fall-through style case statements - ie., those which do not end with break. If the variable being tested by the switch changes in the course of execution, this could change the intended logic of the switch so much that it places the process in a contradictory state and in some cases could even result in memory corruption.

相关缺陷

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

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

  • cwe_Nature: PeerOf cwe_CWE_ID: 364 cwe_View_ID: 1000

  • cwe_Nature: PeerOf cwe_CWE_ID: 366 cwe_View_ID: 1000

适用平台

Language: [{'cwe_Name': 'C', 'cwe_Prevalence': 'Undetermined'}, {'cwe_Name': 'C++', 'cwe_Prevalence': 'Undetermined'}, {'cwe_Name': 'Java', 'cwe_Prevalence': 'Undetermined'}, {'cwe_Name': 'C#', 'cwe_Prevalence': 'Undetermined'}]

常见的影响

范围 影响 注释
['Integrity', 'Other'] ['Alter Execution Logic', 'Unexpected State'] This weakness may lead to unexpected system state, resulting in unpredictable behavior.

可能的缓解方案

Implementation

策略:

Variables that may be subject to race conditions should be locked before the switch statement starts and only unlocked after the statement ends.

示例代码

This example has a switch statement that executes different code depending on the current time.

bad C

#include <sys/types.h>
#include <sys/stat.h>
int main(argc,argv){
struct stat *sb;
time_t timer;
lstat("bar.sh",sb);
printf("%d\n",sb->st_ctime);
switch(sb->st_ctime % 2){
case 0: printf("One option\n");
break;
case 1: printf("another option\n");
break;
default: printf("huh\n");
break;
}
return 0;
}

It seems that the default case of the switch statement should never be reached, as st_ctime % 2 should always be 0 or 1. However, if st_ctime % 2 is 1 when the first case is evaluated, the time may change and st_ctime % 2 may be equal to 0 when the second case is evaluated. The result is that neither case 1 or case 2 execute, and the default option is chosen.

分类映射

映射的分类名 ImNode ID Fit Mapped Node Name
CLASP Race condition in switch
Software Fault Patterns SFP19 Missing Lock

引用