Project: opencv (opencv/opencv), language: c++
Vulnerability instance: opencv.cve-2019-14493
Sanitizer: address

================= Bug Report (1/1) ==================
## Source: GitHub Issue
## URL: https://github.com/opencv/opencv/issues/15127
## Description:
Issue: opencv/opencv#15127
Title: null-pointer-dereference in function cv::XMLParser::parse 
State: closed
Created by: YourButterfly
Created at: 2019-07-23 03:36:46+00:00
Labels: bug, category: core, category: vulnerability

Issue Body:
<!--
If you have a question rather than reporting a bug please go to http://answers.opencv.org where you get much faster responses.
If you need further assistance please read [How To Contribute](https://github.com/opencv/opencv/wiki/How_to_contribute).

Please:

* Read the documentation to test with the latest developer build.
* Check if other person has already created the same issue to avoid duplicates. You can comment on it if there already is an issue.
* Try to be as detailed as possible in your report.
* Report only one problem per created issue.


This is a template helping you to create an issue which can be processed as quickly as possible. This is the bug reporting section for the OpenCV library.
-->

##### System information (version)
<!-- Example
- OpenCV => 3.1
- Operating System / Platform => Windows 64 Bit
- Compiler => Visual Studio 2015
-->

- OpenCV => 4.1.0
- Operating System / Platform => Ubuntu 18.04 LTS
- Compiler => clang-7

##### Detailed description

description

    An issue was discovered in opencv 4.1.0, There is a null-pointer-dereference in function cv::XMLParser::parse at persistence_xml.cpp:795-17.

source

```c
 791         while( ptr && *ptr != '\0' )
 792         {
 793             ptr = skipSpaces( ptr, 0 );
 794 
> 795             if( *p \*bug=>*\ tr != '\0' )
 796             {
 797                 ptr = parseTag( ptr, key, type_name, tag_type );
 798                 if( tag_type != CV_XML_OPENING_TAG || key != "opencv_storage" )
 799                     CV_PARSE_ERROR_CPP( "<opencv_storage> tag is missing" );
 800                 FileNode root = fs->addNode(root_collection, std::string(), FileNode::MAP, 0);

```

bug report

```txt
AddressSanitizer:DEADLYSIGNAL
=================================================================
==8688==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x7fe7b7de5554 bp 0x7ffc4b0ef9b0 sp 0x7ffc4b0ef500 T0)
==8688==The signal is caused by a READ memory access.
==8688==Hint: address points to the zero page.
    #0 0x7fe7b7de5553 in cv::XMLParser::parse(char*) /src/opencv/modules/core/src/persistence_xml.cpp:795:17
    #1 0x7fe7b767cf11 in cv::FileStorage::Impl::open(char const*, int, char const*) /src/opencv/modules/core/src/persistence.cpp:765:34
    #2 0x7fe7b76740ef in cv::FileStorage::FileStorage(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) /src/opencv/modules/core/src/persistence.cpp:1775:18
    #3 0x7fe7c1bafe0d in cv::CascadeClassifierImpl::load(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) /src/opencv/modules/objdetect/src/cascadedetect.cpp:911:17
    #4 0x7fe7c1bd606e in cv::CascadeClassifier::load(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) /src/opencv/modules/objdetect/src/cascadedetect.cpp:1596:13
    #5 0x51d296 in main /work/funcs/classifier.cc:24:29
    #6 0x7fe7b616582f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
    #7 0x41bcc8 in _start (/src/aflbuild/installed/bin/classifier+0x41bcc8)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /src/opencv/modules/core/src/persistence_xml.cpp:795:17 in cv::XMLParser::parse(char*)
==8688==ABORTING

```

others

    from fuzz project pwd-opencv-classifier-00
    crash name pwd-opencv-classifier-00-00000208-20190627.xml
    Auto-generated by pyspider at 2019-06-27 21:14:17

    please send email to  teamseri0us360@gmail.com if you have any questions.


##### Steps to reproduce

commandline

    classifier /work/funcs/appname.bmp @@

[poc3.tar.gz](https://github.com/opencv/opencv/files/3420081/poc3.tar.gz)




Attachments:
https://github.com/opencv/opencv/files/3420081/poc3.tar.gz

Build script:
#!/bin/bash -eu
# Minimized build script with only core build commands
set -eu
mkdir -p $build_dir
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=$install_dir \
  -DBUILD_SHARED_LIBS=OFF -DOPENCV_GENERATE_PKGCONFIG=ON \
  -DOPENCV_GENERATE_PKGCONFIG=ON -DOPENCV_FORCE_3RDPARTY_BUILD=ON \
  -DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DBUILD_opencv_apps=OFF \
  $SRC/opencv
make -j$(nproc)
make install -j$(nproc)

Dockerfile:
FROM hwiwonlee/secb.base:latest
RUN apt-get update && apt-get install -y build-essential cmake pkg-config
RUN git clone https://github.com/opencv/opencv opencv
RUN git -C opencv checkout d7744aca0278db9004824c3bf5aadef880405c51
WORKDIR $SRC/opencv
COPY build.sh $SRC/

Additional files:
filename: fuzzer_temp_file.h
content: // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Adapter utility from fuzzer input to a temporary file, for fuzzing APIs that
// require a file instead of an input buffer.

#ifndef FUZZER_TEMP_FILE_H_
#define FUZZER_TEMP_FILE_H_

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

// Pure-C interface for creating and cleaning up temporary files.

static char* fuzzer_get_tmpfile(const uint8_t* data, size_t size) {
  char* filename_buffer = strdup("/tmp/generate_temporary_file.XXXXXX");
  if (!filename_buffer) {
    perror("Failed to allocate file name buffer.");
    abort();
  }
  const int file_descriptor = mkstemp(filename_buffer);
  if (file_descriptor < 0) {
    perror("Failed to make temporary file.");
    abort();
  }
  FILE* file = fdopen(file_descriptor, "wb");
  if (!file) {
    perror("Failed to open file descriptor.");
    close(file_descriptor);
    abort();
  }
  const size_t bytes_written = fwrite(data, sizeof(uint8_t), size, file);
  if (bytes_written < size) {
    close(file_descriptor);
    fprintf(stderr, "Failed to write all bytes to file (%zu out of %zu)",
            bytes_written, size);
    abort();
  }
  fclose(file);
  return filename_buffer;
}

static void fuzzer_release_tmpfile(char* filename) {
  if (unlink(filename) != 0) {
    perror("WARNING: Failed to delete temporary file.");
  }
  free(filename);
}

// C++ RAII object for creating temporary files.

#ifdef __cplusplus
class FuzzerTemporaryFile {
 public:
  FuzzerTemporaryFile(const uint8_t* data, size_t size)
      : filename_(fuzzer_get_tmpfile(data, size)) {}

  ~FuzzerTemporaryFile() { fuzzer_release_tmpfile(filename_); }

  const char* filename() const { return filename_; }

 private:
  char* filename_;
};
#endif

#endif  // FUZZER_TEMP_FILE_H_

filename: imdecode_fuzzer.cc
content: #include <opencv2/opencv.hpp>
#include <opencv2/imgcodecs/legacy/constants_c.h>

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  std::vector<uint8_t> image_data = {data, data + size};
  // TODO: Try other image types than CV_8UC1.
  cv::Mat data_matrix =
      cv::Mat(1, image_data.size(), CV_8UC1, image_data.data());
  try {
    cv::Mat decoded_matrix = cv::imdecode(data_matrix, CV_LOAD_IMAGE_UNCHANGED);
  } catch (cv::Exception e) {
    // Do nothing.
  }
  return 0;
}


filename: imread_fuzzer.cc
content: #include <cstddef>
#include <cstdint>
#include <unistd.h>

#include <opencv2/opencv.hpp>
#include "fuzzer_temp_file.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  const FuzzerTemporaryFile file(data, size);
  try {
    cv::Mat matrix = cv::imread(file.filename());
  } catch (cv::Exception e) {
    // Do nothing.
  }
  return 0;
}