1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-29 23:33:05 +04:00

Merge pull request #28620 from mvanhorn:osc/28619-fix-yaml-parsekey-empty-key-oob

core: fix heap-buffer-overflow in YAML parseKey for empty keys #28620

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake

### Description

Fixes https://github.com/opencv/opencv/issues/28619

Moves the "empty key" check before the backward do-while scan in `YAMLParser::parseKey()`.

**Problem:** When parsing a YAML mapping with an empty key (e.g. `: 10` at column 0), `endptr == ptr` after the forward scan finds `:`. The do-while loop `do c = *--endptr; while(c == ' ')` always executes at least once, so it decrements `endptr` to `ptr-1` and reads one byte before the heap allocation (ASan: heap-buffer-overflow READ of size 1).

**Fix:** Check `endptr == ptr` before entering the backward loop. If the key is empty, raise `CV_PARSE_ERROR_CPP("An empty key")` immediately without the OOB read.

This contribution was developed with AI assistance (Claude Code).
This commit is contained in:
Matt Van Horn
2026-03-12 00:37:24 -07:00
committed by GitHub
parent 1a3e1e05b7
commit 8e1fa1bbdc
2 changed files with 18 additions and 2 deletions
+3 -2
View File
@@ -432,12 +432,13 @@ public:
CV_PARSE_ERROR_CPP( "Missing \':\'" );
saveptr = endptr + 1;
if( endptr == ptr )
CV_PARSE_ERROR_CPP( "An empty key" );
do c = *--endptr;
while( c == ' ' );
++endptr;
if( endptr == ptr )
CV_PARSE_ERROR_CPP( "An empty key" );
value_placeholder = fs->addNode(map_node, std::string(ptr, endptr - ptr), FileNode::NONE);
ptr = saveptr;
+15
View File
@@ -1673,6 +1673,21 @@ TEST(Core_InputOutput, FileStorage_free_file_after_exception)
ASSERT_EQ(0, std::remove(fileName.c_str()));
}
TEST(Core_InputOutput, FileStorage_YAML_empty_key)
{
const std::string fileName = cv::tempfile("FileStorage_YAML_empty_key_test.yml");
const std::string content = "%YAML:1.0\n---\nkey1: value1\n: 10\n";
std::fstream testFile;
testFile.open(fileName.c_str(), std::fstream::out);
if(!testFile.is_open()) FAIL();
testFile << content;
testFile.close();
EXPECT_THROW(FileStorage(fileName, FileStorage::READ), cv::Exception);
ASSERT_EQ(0, std::remove(fileName.c_str()));
}
TEST(Core_InputOutput, FileStorage_write_to_sequence)
{
const std::vector<std::string> formatExts = { ".yml", ".json", ".xml" };