T09 · Insecure Skill Coding Practices
Warning
- Location
- code.c:192
- Finding
- Undefined Behavior When Parsing an Empty Configuration Value<![CDATA[ ## Vulnerability Details **File Location**: `code.c:192-193` **Vulnerability Type**: Out-of-bounds pointer arithmetic / undefined behavior **Risk Level**: Medium ### Vulnerable Code ```c char* end = value + strlen(value) - 1; while (end > value && (*end == '\n' || *end == '\r' || *end == ' ')) *end-- = '\0'; ``` ### Technical Analysis When the configuration value is empty, `strlen(value)` returns zero. The expression used to initialize `end` then attempts to construct a pointer one byte before the beginning of `value`: ```c value + 0 - 1 ``` Constructing and subsequently comparing this out-of-bounds pointer is undefined behavior under the C language rules. An empty value can occur when a configuration file ends with `key=` without a trailing newline. The loop's `end > value` condition may appear to prevent dereferencing the invalid pointer, but the relational comparison itself is not a reliable safeguard after an invalid pointer has been constructed. Compiler optimization and platform behavior may therefore produce unpredictable results. ### Attack Path 1. An attacker obtains the ability to supply or modify a file processed by `config_load_file()`. 2. The attacker makes the final file content an assignment with no value and no trailing newline, for example: ```text server.host= ``` 3. `strchr()` finds the equals sign, and `value` points to the terminating null byte. 4. `strlen(value)` returns zero. 5. The parser constructs `value - 1`, invoking undefined behavior. 6. Depending on the compiler and runtime environment, the consuming process may crash or behave unpredictably. ### Impact Assessment The demonstrated impact is primarily loss of availability in a process that loads attacker-controlled configuration files. This flaw does not directly grant additional operating-system privileges, disclose secrets, or execute attacker-supplied commands. Its scope is limited to applications embedding this configuration manager, but it may re ...[truncated 93 chars]
- Remediation
- <![CDATA[ ## Remediation Suggestions Use length-based trimming without ever constructing a pointer before the buffer: ```c size_t value_len = strlen(value); while (value_len > 0 && (value[value_len - 1] == '\n' || value[value_len - 1] == '\r' || value[value_len - 1] == ' ')) { value[--value_len] = '\0'; } ``` Additional hardening should include: - Add tests for `key=`, `key=\n`, whitespace-only values, and files without a final newline. - Define explicitly whether empty values are valid strings or malformed entries. - If empty values are invalid, reject the line and return a parse error rather than continuing silently. - Compile and test with AddressSanitizer and UndefinedBehaviorSanitizer. ]]>
