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

================= Bug Report (1/1) ==================
## Source: GitHub Issue
## URL: https://github.com/OpenCV/opencv/issues/15287
## Description:
Issue: OpenCV/opencv#15287
Title: Floating Point Exception in cv::HOGDescriptor::getDescriptorSize()
State: closed
Created by: YourButterfly
Created at: 2019-08-13 07:02:59+00:00
Labels: category: objdetect, 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 => 7.0.1

##### Detailed description

An issue was discovered in opencv 4.1.0. There is a FPE in cv::HOGDescriptor::getDescriptorSize.

DEBUG

```cpp
In file: opencv-4.1.0/modules/objdetect/src/hog.cpp
   88         blockSize.height % cellSize.height == 0);
   89     CV_Assert((winSize.width - blockSize.width) % blockStride.width == 0 &&
   90         (winSize.height - blockSize.height) % blockStride.height == 0 );
   91 
   92     return (size_t)nbins*
 ► 93         (blockSize.width/cellSize.width)*
   94         (blockSize.height/cellSize.height)*
   95         ((winSize.width - blockSize.width)/blockStride.width + 1)*
   96         ((winSize.height - blockSize.height)/blockStride.height + 1);
   97 }
   98 
pwndbg> p cellSize 
$2 = {
  width = 0, 
  height = 0
}

```

ASAN report
```txt
AddressSanitizer:DEADLYSIGNAL
=================================================================
==76303==ERROR: AddressSanitizer: FPE on unknown address 0x7f89dc67e495 (pc 0x7f89dc67e495 bp 0x7ffeedf44e90 sp 0x7ffeedf44d20 T0)
    #0 0x7f89dc67e494 in cv::HOGDescriptor::getDescriptorSize() const /home/pwd/fuzz/opencv/opencv-4.1.0/modules/objdetect/src/hog.cpp:93:25
    #1 0x7f89dc67f994 in cv::HOGDescriptor::checkDetectorSize() const /home/pwd/fuzz/opencv/opencv-4.1.0/modules/objdetect/src/hog.cpp:106:64
    #2 0x7f89dc67f994 in cv::HOGDescriptor::setSVMDetector(cv::_InputArray const&) /home/pwd/fuzz/opencv/opencv-4.1.0/modules/objdetect/src/hog.cpp:115
    #3 0x7f89dc683045 in cv::HOGDescriptor::read(cv::FileNode&) /home/pwd/fuzz/opencv/opencv-4.1.0/modules/objdetect/src/hog.cpp:168:9
    #4 0x7f89dc689eb2 in cv::HOGDescriptor::load(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) /home/pwd/fuzz/opencv/opencv-4.1.0/modules/objdetect/src/hog.cpp:200:12
    #5 0x518fb0 in cv::HOGDescriptor::HOGDescriptor(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) /home/pwd/fuzz/opencv/opencv-4.1.0/installed-asan/include/opencv4/opencv2/objdetect.hpp:421:9
    #6 0x518fb0 in main /home/pwd/fuzz/opencv/opencv-4.1.0/mytests/hog.cc:17
    #7 0x7f89d149db96 in __libc_start_main /build/glibc-OTsEL5/glibc-2.27/csu/../csu/libc-start.c:310
    #8 0x41b909 in _start (/home/pwd/fuzz/opencv/opencv-4.1.0/mytests/hog+0x41b909)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: FPE /home/pwd/fuzz/opencv/opencv-4.1.0/modules/objdetect/src/hog.cpp:93:25 in cv::HOGDescriptor::getDescriptorSize() const
==76303==ABORTING

```

##### Steps to reproduce

<!-- to add code example fence it with triple backticks and optional file extension
    ```.cpp
    // C++ code example
    ```
 or attach as .txt or .zip file
-->

```shell
./hog timg.jpeg getDescriptorSize__FPE
```
[hog-vuln.tar.gz](https://github.com/opencv/opencv/files/3495664/hog-vuln.tar.gz)




Comments:
Comment by nluedtke on 2019-09-09 11:14:49+00:00:
This was assigned [CVE-2019-15939.](https://nvd.nist.gov/vuln/detail/CVE-2019-15939)

Attachments:
https://github.com/opencv/opencv/files/3495664/hog-vuln.tar.gz

Build script:
#!/bin/bash -eu
# Minimized build script with only core build commands
set -eu
mkdir -p opencv/build
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=$WORK \
  -DBUILD_SHARED_LIBS=OFF -DOPENCV_GENERATE_PKGCONFIG=ON \
  -DOPENCV_GENERATE_PKGCONFIG=ON -DOPENCV_FORCE_3RDPARTY_BUILD=ON ..
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 00171ca935d945ec9831d67ff0ef020f078cd19a
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;
}