Enumerations in C++ come in two forms: scoped enumerations, where the underlying type is fixed, and unscoped enumerations where the underlying type is may or may not be fixed. The range of values that can be represented by either form of enumeration may include enumerator values not specified by the enumeration itself. The range of valid enumeration values for an enumeration type is defined by the C++ Standard, [dcl.enum], paragraph 8 [ISO/IEC 14882-2014]:
...
Code Block | ||||
---|---|---|---|---|
| ||||
enum class enum_type {
E_A,
E_B,
E_C
};
void f(int int_var) {
enum_type enum_var = static_cast<enum_type>(int_var);
} |
Compliant Solution (Fixed Unscoped Enumeration)
Similar to the previous compliant solution, this compliant solution uses an unscoped enumeration, but provides a fixed underlying type of type int
, allowing any value from the parameter to be converted into a valid enumeration value:
Code Block | ||||
---|---|---|---|---|
| ||||
enum enum_type : int { E_A, E_B, E_C }; void f(int int_var) { enum_type enum_var = static_cast<enum_type>(int_var); } |
While similar to the previous compliant solution, the previous compliant solution differs from the noncompliant code example in the way the enumerator values are expressed in code and what implicit conversions are allowed. The previous compliant solution requires a nested name specifier to identify the enumerator (e.g., enum_type::E_A
), and will not implicitly convert the enumerator value to int
. As with the noncompliant code example, this compliant solution does not allow a nested name specifier and will implicitly convert the enumerator value to int
.
Risk Assessment
Unexpected behavior can lead to a buffer overflow and the execution of arbitrary code by an attacker. This is most likely if the program in one case checks the value correctly and then fails to do so later. Such a situation could allow an attacker to avoid verification of a buffer's length, and so on.
...