T09 · Insecure Skill Coding Practices
Warning
- Location
- code.c:186
- Finding
- Undefined Behavior When Parsing an Empty Configuration Value<![CDATA[ ## Vulnerability Details **File Location**: `code.c`, lines 186–193 **Vulnerability Type**: Out-of-bounds pointer formation and undefined behavior **Risk Level**: Medium ### Vulnerable Code ```c char* eq = strchr(line, '='); if (eq) { *eq = '\0'; char* key = line; char* value = eq + 1; // Remove whitespace while (*value == ' ' || *value == '\t') value++; char* end = value + strlen(value) - 1; while (end > value && (*end == '\n' || *end == '\r' || *end == ' ')) *end-- = '\0'; ``` ### Technical Analysis When a configuration entry has an empty value and no trailing newline, such as `key=` at the end of a file, `value` points to an empty string and `strlen(value)` returns zero. The expression below consequently attempts to form a pointer one byte before the beginning of the `value` object: ```c char* end = value + strlen(value) - 1; ``` Forming this out-of-bounds pointer is undefined behavior under the C memory model, even if the following loop condition normally prevents it from being dereferenced. Compiler optimizations, runtime instrumentation, or platform-specific behavior may therefore produce unpredictable results. The same condition can occur after leading spaces or tabs are skipped if no other characters remain and the line has no newline terminator. ### Attack Path 1. An attacker gains control over a configuration file accepted by an application using this library. 2. The attacker places an empty assignment such as `key=` as the final line without a newline. 3. The application calls `config_load_file()` on that file. 4. The parser calculates `value + 0 - 1`, forming an invalid pointer. 5. The application encounters undefined, compiler-dependent behavior and may terminate, particularly under memory-safety instrumentation or hardened runtime environments. ### Impact Assessment The direct impact is availability loss or unpredictable configuration parsing in the process loading the malicious file. The flaw ...[truncated 275 chars]
- Remediation
- <![CDATA[ ## Remediation Suggestions Track the string length before calculating the final character position, and only index the string when the length is nonzero. For example: ```c while (*value == ' ' || *value == '\t') { value++; } size_t value_len = strlen(value); while (value_len > 0) { char last = value[value_len - 1]; if (last != '\n' && last != '\r' && last != ' ' && last != '\t') { break; } value[--value_len] = '\0'; } ``` Additionally: - Define and test the intended behavior for empty configuration values. - Add regression tests for `key=`, `key= `, empty final lines, and files both with and without trailing newlines. - Compile tests with AddressSanitizer and UndefinedBehaviorSanitizer. ]]>
