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

================= Bug Report (1/2) ==================
## Source: Red Hat Bugzilla
## URL: https://bugzilla.redhat.com/show_bug.cgi?id=1752702
## Description:
Bugzilla ID: 1752702
Title: CVE-2019-16249 opencv: Out-of-bounds read in hal_baseline::v_load in core/hal/intrin_sse.hpp

Description
Pedro Sampaio 2019-09-17 03:13:58 UTC
OpenCV 4.1.1 has an out-of-bounds read in hal_baseline::v_load in core/hal/intrin_sse.hpp when called from computeSSDMeanNorm in modules/video/src/dis_flow.cpp.

Upstream issue:

https://github.com/opencv/opencv/issues/15481


Comments:
Comment 1
Pedro Sampaio 2019-09-17 03:14:11 UTC
Created opencv tracking bugs for this issue:

Affects: fedora-all [bug 1752703]

---

Comment 3
Mauro Matteo Cascella 2019-11-26 13:32:52 UTC
Upstream fix:
https://github.com/opencv/opencv/commit/cd7fa04985b10db5e66de542725d0da57f0d10b6

---

Comment 4
Mauro Matteo Cascella 2019-11-26 16:33:54 UTC
Statement:

This issue did not affect the versions of OpenCV as shipped with Red Hat Enterprise Linux 6, and 7 as they did not include support for DIS optflow algorithm.
This issue did not affect the versions of OpenCV as shipped with Red Hat Enterprise Linux 8 as DIS optflow algorithm did not include support for Single Instruction, Multiple Data (SIMD).

---

Comment 5
Mauro Matteo Cascella 2019-11-26 16:35:06 UTC
For the DIS optflow algorithm to be vulnerable the CV_SIMD128 macro has to be defined, as the vulnerable code in computeSSDMeanNorm function is conditionally compiled based on the value of that macro. Specifically, CV_SIMD128 is defined in the header file intrin_sse.hpp which, in turn, is included by intrin.hpp if SSE support is enabled. Despite the support of SSE, the version of OpenCV shipped with Red Hat Enterprise Linux 8 is not affected by this flaw due to the header file "opencv2/core/hal/intrin.hpp" not being included in the source file dis_flow.cpp.
 
The commit that removed the include statement from dis_flow.cpp is https://github.com/opencv/opencv_contrib/commit/64b3bbb6201b183db37ec3d6bc47c595c150b0d3. Please note that the commit refers to opencv_contrib repository, as optflow algorithm was an "extra" module under development. The optflow algorithm has been successively moved to the central OpenCV repository in release 4.0.0 (Pull Request https://github.com/opencv/opencv/pull/13084). The missing header has been reintroduced later with a fix in commit https://github.com/opencv/opencv/commit/c96850ba599ada02dad6bd1a4271ce8f4f20e246.

---

Comment 6
Mauro Matteo Cascella 2019-11-26 16:39:16 UTC
Function DISOpticalFlowImpl::PatchInverseSearch_ParBody::operator() in dis_flow.cpp wrongly computes the index of the uchar array I1_ptr. Consequently, a pointer to the last 12 bytes is passed as second argument to function computeSSDMeanNorm which reads 16 bytes from it through the HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION macro. This leads to a 4-byte out-of-bound read in v_load function defined in intrin_sse.hpp.

Upstream fix replaces the v_load() call in HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION macro with v_load_expand() which only reads 8 bytes from the pointer passed as argument.

================= Bug Report (2/2) ==================
## Source: GitHub Issue
## URL: https://github.com/opencv/opencv/issues/15481
## Description:
Issue: opencv/opencv#15481
Title: OOB: cv::WorkerThread::WorkerThread()
State: closed
Created by: RootUp
Created at: 2019-09-07 15:52:32+00:00
Labels: bug, category: video, category: vulnerability

Issue Body:
**Build type:** `Release`
**OpenCV version:** `4.1.2-pre`
**OS:** `Linux 4.15.0-62-generic #69-Ubuntu`
**OpenCV VCS version:** `4.1.1-217-g4de115c08`

I've complied opencv with clang enabling ASAN while fuzzing the opencv_test_video binary `crashes at cv::hal_baseline::v_load()` and `cv::computeSSDMeanNorm()`

```c
==14389==ERROR: AddressSanitizer: unknown-crash on address 0x61500000c9c4 at pc 0x7f24d2ff6a40 bp 0x7f24aa6c4ac0 sp 0x7f24aa6c4ab0
READ of size 16 at 0x61500000c9c4 thread T7
    #0 0x7f24d2ff6a3f in _mm_loadu_si128(long long __vector(2) const*) /usr/lib/gcc/x86_64-linux-gnu/7/include/emmintrin.h:703
    #1 0x7f24d2ff6a3f in cv::hal_baseline::v_load(unsigned char const*) /home/input0/opencv/modules/core/include/opencv2/core/hal/intrin_sse.hpp:1348
    #2 0x7f24d2ff6a3f in cv::computeSSDMeanNorm(unsigned char*, unsigned char*, int, int, float, float, float, float, int) /home/input0/opencv/modules/video/src/dis_flow.cpp:738
    #3 0x7f24d2ff927f in cv::DISOpticalFlowImpl::PatchInverseSearch_ParBody::operator()(cv::Range const&) const /home/input0/opencv/modules/video/src/dis_flow.cpp:887
    #4 0x7f24cc0d860e in operator() /home/input0/opencv/modules/core/src/parallel.cpp:323
    #5 0x7f24cc0de621 in cv::ParallelJob::execute(bool) /home/input0/opencv/modules/core/src/parallel_impl.cpp:315
    #6 0x7f24cc0f3dd5 in cv::WorkerThread::thread_body() /home/input0/opencv/modules/core/src/parallel_impl.cpp:415
    #7 0x7f24cc0f5660 in cv::WorkerThread::thread_loop_wrapper(void*) /home/input0/opencv/modules/core/src/parallel_impl.cpp:265
    #8 0x7f24d2a8c6da in start_thread (/lib/x86_64-linux-gnu/libpthread.so.0+0x76da)
    #9 0x7f24ca52e88e in __clone (/lib/x86_64-linux-gnu/libc.so.6+0x12188e)

0x61500000c9d0 is located 0 bytes to the right of 400-byte region [0x61500000c840,0x61500000c9d0)
allocated by thread T0 here:
    #0 0x7f24d35127a0 in posix_memalign (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdf7a0)
    #1 0x7f24cb2ffdc0 in cv::fastMalloc(unsigned long) /home/input0/opencv/modules/core/src/alloc.cpp:93

Thread T7 created by T0 here:
    #0 0x7f24d346ad2f in __interceptor_pthread_create (/usr/lib/x86_64-linux-gnu/libasan.so.4+0x37d2f)
    #1 0x7f24cc0e9aa3 in cv::WorkerThread::WorkerThread(cv::ThreadPool&, unsigned int) /home/input0/opencv/modules/core/src/parallel_impl.cpp:227
    #2 0x7fffb7dfd58f  (<unknown module>)

SUMMARY: AddressSanitizer: unknown-crash /usr/lib/gcc/x86_64-linux-gnu/7/include/emmintrin.h:703 in _mm_loadu_si128(long long __vector(2) const*)
Shadow bytes around the buggy address:
  0x0c2a7fff98e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c2a7fff98f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 fa
  0x0c2a7fff9900: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
  0x0c2a7fff9910: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c2a7fff9920: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c2a7fff9930: 00 00 00 00 00 00 00 00[00]00 fa fa fa fa fa fa
  0x0c2a7fff9940: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c2a7fff9950: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
  0x0c2a7fff9960: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c2a7fff9970: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c2a7fff9980: 00 00 00 00 00 00 00 00 00 00 fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==14389==
```


Comments:
Comment by mshabunin on 2019-09-17 11:01:23+00:00:
https://nvd.nist.gov/vuln/detail/CVE-2019-16249

---

Comment by alalek on 2019-09-17 13:57:21+00:00:
> fuzzing the opencv_test_video

There is no fuzzing in regular OpenCV tests, so there is no special reproducer input data.

Only address sanitizer is working.
One of failed test is:
- DenseOpticalFlow_DIS.InvalidImgSize_CoarsestLevelLessThanFinestLevel

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 693877212d34f2d5e3bbf29287aa1db2d07d4d6d
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;
}