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

================= Bug Report (1/1) ==================
## Source: GitHub Issue
## URL: https://github.com/opencv/opencv/issues/15125
## Description:
Issue: opencv/opencv#15125
Title: out of bounds read in function cv::predictOrdered<cv::HaarEvaluator> 
State: closed
Created by: YourButterfly
Created at: 2019-07-23 03:32:04+00:00
Labels: 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


    An issue was discovered in opencv 4.1.0, there is an out of bounds read in function cv::predictOrdered<cv::HaarEvaluator> in cascadedetect.hpp, which leads to denial of service.

source

```c
 511                 double val = featureEvaluator(node.featureIdx);
 512                 idx = val < node.threshold ? node.left : node.right;
 513             }
 514             while( idx > 0 );
> 515             sum += \*bug=>*\  cascadeLeaves[leafOfs - idx];
 516             nodeOfs += weak.nodeCount;
 517             leafOfs += weak.nodeCount + 1;
 518         }
 519         if( sum < stage.threshold )
 520             return -si;
```

debug

```
In file: /home/pwd/SofterWare/opencv-4.1.0/modules/objdetect/src/cascadedetect.hpp
   510                 CascadeClassifierImpl::Data::DTreeNode& node = cascadeNodes[root + idx];
   511                 double val = featureEvaluator(node.featureIdx);
   512                 idx = val < node.threshold ? node.left : node.right;
   513             }
   514             while( idx > 0 );
 ► 515             sum += cascadeLeaves[leafOfs - idx];
   516             nodeOfs += weak.nodeCount;
   517             leafOfs += weak.nodeCount + 1;
   518         }
   519         if( sum < stage.threshold )
   520             return -si;
─────────────────────────────────────────────────────────────────────────────────────────────────────[ STACK ]─────────────────────────────────────────────────────────────────────────────────────────────────────
00:0000│ rsp  0x7fffc7ffe300 ◂— 0x8d80169006580d8
01:0008│      0x7fffc7ffe308 ◂— 0xbba5787f80000000
02:0010│      0x7fffc7ffe310 —▸ 0x7fffd53a5de0 ◂— 0xb1088000af4cb
03:0018│      0x7fffc7ffe318 ◂— 0xffedb5a100000003
04:0020│      0x7fffc7ffe320 ◂— 0xbf74af0fe0000000
05:0028│      0x7fffc7ffe328 —▸ 0x6b7b70 ◂— 0x0
06:0030│      0x7fffc7ffe330 ◂— 0x800000000000005d /* ']' */
07:0038│      0x7fffc7ffe338 —▸ 0x66f4a4 ◂— 0x100000000
───────────────────────────────────────────────────────────────────────────────────────────────────[ BACKTRACE ]───────────────────────────────────────────────────────────────────────────────────────────────────
 ► f 0     7ffff5e2c500
   f 1     7ffff5e2bb21
   f 2     7ffff5e3bd74
   f 3     7fffef87dc59
   f 4     7fffef87ea3b cv::ParallelJob::execute(bool)+603
   f 5     7fffef87e21a cv::WorkerThread::thread_body()+890
   f 6     7fffef880e05 cv::WorkerThread::thread_loop_wrapper(void*)+21
   f 7     7fffee3d46db start_thread+219
Program received signal SIGSEGV (fault address 0xfffffffe006630f8)
pwndbg> p cascadeLeaves 
$1 = (float *) 0x662e10
pwndbg> p leafOfs 
$2 = 186
pwndbg> p idx
$3 = -2147483648
```

bug report

```txt
AddressSanitizer:DEADLYSIGNAL
=================================================================
==9176==ERROR: AddressSanitizer: SEGV on unknown address 0x623e000443e8 (pc 0x7fc9fc661bfa bp 0x7fc9daee70b0 sp 0x7fc9daee6f80 T1)
==9176==The signal is caused by a READ memory access.
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
AddressSanitizer:DEADLYSIGNAL
    #0 0x7fc9fc661bf9 in int cv::predictOrdered<cv::HaarEvaluator>(cv::CascadeClassifierImpl&, cv::Ptr<cv::FeatureEvaluator>&, double&) /src/opencv/modules/objdetect/src/cascadedetect.hpp:515:17
    #1 0x7fc9fc65f736 in cv::CascadeClassifierImpl::runAt(cv::Ptr<cv::FeatureEvaluator>&, cv::Point_<int>, int, double&) /src/opencv/modules/objdetect/src/cascadedetect.cpp:962:20
    #2 0x7fc9fc692083 in cv::CascadeClassifierInvoker::operator()(cv::Range const&) const /src/opencv/modules/objdetect/src/cascadedetect.cpp:1029:46
    #3 0x7fc9f294b0c3 in (anonymous namespace)::ParallelLoopBodyWrapper::operator()(cv::Range const&) const /src/opencv/modules/core/src/parallel.cpp:343:17
    #4 0x7fc9f2d737e7 in cv::ParallelJob::execute(bool) /src/opencv/modules/core/src/parallel_impl.cpp:315:22
    #5 0x7fc9f2d7125b in cv::WorkerThread::thread_body() /src/opencv/modules/core/src/parallel_impl.cpp:415:24
    #6 0x7fc9f2d7f719 in cv::WorkerThread::thread_loop_wrapper(void*) /src/opencv/modules/core/src/parallel_impl.cpp:265:41
    #7 0x7fc9f15e46b9 in start_thread (/lib/x86_64-linux-gnu/libpthread.so.0+0x76b9)
    #8 0x7fc9f0cf841c in clone (/lib/x86_64-linux-gnu/libc.so.6+0x10741c)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /src/opencv/modules/objdetect/src/cascadedetect.hpp:515:17 in int cv::predictOrdered<cv::HaarEvaluator>(cv::CascadeClassifierImpl&, cv::Ptr<cv::FeatureEvaluator>&, double&)
Thread T1 created by T0 here:
    #0 0x43428d in __interceptor_pthread_create /work/llvm/projects/compiler-rt/lib/asan/asan_interceptors.cc:204
    #1 0x7fc9f2d79d58 in cv::WorkerThread::WorkerThread(cv::ThreadPool&, unsigned int) /src/opencv/modules/core/src/parallel_impl.cpp:227:15
    #2 0x7fc9f2d76240 in cv::ThreadPool::reconfigure_(unsigned int) /src/opencv/modules/core/src/parallel_impl.cpp:510:53
    #3 0x7fc9f2d7bb07 in cv::ThreadPool::run(cv::Range const&, cv::ParallelLoopBody const&, double) /src/opencv/modules/core/src/parallel_impl.cpp:548:9
    #4 0x7fc9f2949a99 in parallel_for_impl(cv::Range const&, cv::ParallelLoopBody const&, double) /src/opencv/modules/core/src/parallel.cpp:590:9
    #5 0x7fc9f2949a99 in cv::parallel_for_(cv::Range const&, cv::ParallelLoopBody const&, double) /src/opencv/modules/core/src/parallel.cpp:518
    #6 0x7fc9fc673269 in cv::CascadeClassifierImpl::detectMultiScaleNoGrouping(cv::_InputArray const&, std::vector<cv::Rect_<int>, std::allocator<cv::Rect_<int> > >&, std::vector<int, std::allocator<int> >&, std::vector<double, std::allocator<double> >&, double, cv::Size_<int>, cv::Size_<int>, bool) /src/opencv/modules/objdetect/src/cascadedetect.cpp:1346:9
    #7 0x7fc9fc677cb8 in cv::CascadeClassifierImpl::detectMultiScale(cv::_InputArray const&, std::vector<cv::Rect_<int>, std::allocator<cv::Rect_<int> > >&, std::vector<int, std::allocator<int> >&, std::vector<double, std::allocator<double> >&, double, int, int, cv::Size_<int>, cv::Size_<int>, bool) /src/opencv/modules/objdetect/src/cascadedetect.cpp:1365:5
    #8 0x7fc9fc6786ee in cv::CascadeClassifierImpl::detectMultiScale(cv::_InputArray const&, std::vector<cv::Rect_<int>, std::allocator<cv::Rect_<int> > >&, double, int, int, cv::Size_<int>, cv::Size_<int>) /src/opencv/modules/objdetect/src/cascadedetect.cpp:1386:5
    #9 0x7fc9fc686370 in cv::CascadeClassifier::detectMultiScale(cv::_InputArray const&, std::vector<cv::Rect_<int>, std::allocator<cv::Rect_<int> > >&, double, int, int, cv::Size_<int>, cv::Size_<int>) /src/opencv/modules/objdetect/src/cascadedetect.cpp:1659:9
    #10 0x51d4bc in main /work/funcs/classifier.cc:34:24
    #11 0x7fc9f0c1182f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)

==9176==ABORTING

```

others

    from fuzz project pwd-opencv-classifier-00
    crash name pwd-opencv-classifier-00-00000253-20190703.xml
    Auto-generated by pyspider at 2019-07-03 07:57:31

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


##### Steps to reproduce

commandline

    classifier /work/funcs/appname.bmp @@

 
[poc2.tar.gz](https://github.com/opencv/opencv/files/3420073/poc2.tar.gz)



Attachments:
https://github.com/opencv/opencv/files/3420073/poc2.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 7295983964044c280484469d73d6b8f59dbc5a4f
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;
}