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

================= Bug Report (1/1) ==================
## Source: GitHub Issue
## URL: https://github.com/opencv/opencv/issues/10541
## Description:
Issue: opencv/opencv#10541
Title: A heap based buffer overflow happens in cv::Jpeg2KDecoder::readComponent8u
State: closed
Created by: Epeius
Created at: 2018-01-07 13:02:37+00:00
Labels: bug, category: imgcodecs, category: vulnerability

Issue Body:
## System information (version)

- OpenCV 3.3.1
- Operating System / Platform => Ubuntu 16.04
- Compiler => clang++
- Compiled-executable: 32bits

## Detailed description

A heap-based buffer overflow happens in function `cv::Jpeg2KDecoder::readComponent8u` in grfmt_jpeg2000.cpp:343

The crash details as follows:

=================================================================
```
warning: component data type mismatch
=================================================================
==6293==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60900000c247 at pc 0x0000005ce1a3 bp 0x7fff71a94400 sp 0x7fff71a943f8
WRITE of size 1 at 0x60900000c247 thread T0
    #0 0x5ce1a2 in cv::Jpeg2KDecoder::readComponent8u(unsigned char*, void*, int, int, int, int, int) /home/opencv/fuzz/target/opencv-3.3.1/modules/imgcodecs/src/grfmt_jpeg2000.cpp:343:38
    #1 0x5cb417 in cv::Jpeg2KDecoder::readData(cv::Mat&) /home/opencv/fuzz/target/opencv-3.3.1/modules/imgcodecs/src/grfmt_jpeg2000.cpp:255:42
    #2 0x51d2c1 in cv::imread_(cv::String const&, int, int, cv::Mat*) /home/opencv/fuzz/target/opencv-3.3.1/modules/imgcodecs/src/loadsave.cpp:487:13
    #3 0x51a78c in cv::imread(cv::String const&, int) /home/opencv/fuzz/target/opencv-3.3.1/modules/imgcodecs/src/loadsave.cpp:638:5
    #4 0x50cf4f in main /home/opencv/fuzz/target/opencv-3.3.1/samples/cpp/example_cmake/test_png.cpp:46:25
    #5 0x7f1e5d14ef44 in __libc_start_main /build/eglibc-SvCtMH/eglibc-2.19/csu/libc-start.c:287
    #6 0x42f9f3 in _start (/home/opencv/test/target/12.7asan/opencv_afl-test+0x42f9f3)

0x60900000c247 is located 1 bytes to the right of 6-byte region [0x60900000c240,0x60900000c246)
allocated by thread T0 here:
    #0 0x4da835 in __interceptor_posix_memalign (/home/opencv/test/target/12.7asan/opencv_afl-test+0x4da835)
    #1 0x9b28c9 in cv::fastMalloc(unsigned long) /home/opencv/fuzz/target/opencv-3.3.1/modules/core/src/alloc.cpp:64:8
    #2 0xb8b0ca in cv::StdMatAllocator::allocate(int, int const*, int, void*, unsigned long*, int, cv::UMatUsageFlags) const /home/opencv/fuzz/target/opencv-3.3.1/modules/core/src/matrix.cpp:191:55
    #3 0xa924da in cv::Mat::create(int, int const*, int) /home/opencv/fuzz/target/opencv-3.3.1/modules/core/src/matrix.cpp:429:17
    #4 0x553b39 in cv::Mat::create(int, int, int) /home/opencv/fuzz/target/opencv-3.3.1/modules/core/include/opencv2/core/mat.inl.hpp:784:5
    #5 0x5c92e0 in cv::Jpeg2KDecoder::readData(cv::Mat&) /home/opencv/fuzz/target/opencv-3.3.1/modules/imgcodecs/src/grfmt_jpeg2000.cpp:171:9
    #6 0x51d2c1 in cv::imread_(cv::String const&, int, int, cv::Mat*) /home/opencv/fuzz/target/opencv-3.3.1/modules/imgcodecs/src/loadsave.cpp:487:13
    #7 0x51a78c in cv::imread(cv::String const&, int) /home/opencv/fuzz/target/opencv-3.3.1/modules/imgcodecs/src/loadsave.cpp:638:5
    #8 0x50cf4f in main /home/opencv/fuzz/target/opencv-3.3.1/samples/cpp/example_cmake/test_png.cpp:46:25
    #9 0x7f1e5d14ef44 in __libc_start_main /build/eglibc-SvCtMH/eglibc-2.19/csu/libc-start.c:287

SUMMARY: AddressSanitizer: heap-buffer-overflow /home/opencv/fuzz/target/opencv-3.3.1/modules/imgcodecs/src/grfmt_jpeg2000.cpp:343:38 in cv::Jpeg2KDecoder::readComponent8u(unsigned char*, void*, int, int, int, int, int)
Shadow bytes around the buggy address:
  0x0c127fff97f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c127fff9800: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c127fff9810: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c127fff9820: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c127fff9830: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
=>0x0c127fff9840: fa fa fa fa fa fa fa fa[06]fa fa fa fa fa fa fa
  0x0c127fff9850: fa fa fa fa fa fa fa fa 01 fa fa fa fa fa fa fa
  0x0c127fff9860: fa fa fa fa fa fa fa fa 00 00 04 fa fa fa fa fa
  0x0c127fff9870: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c127fff9880: fd fd fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c127fff9890: fd fa fa fa fa fa fa fa fa fa 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
  Heap right redzone:      fb
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack partial redzone:   f4
  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
==6293==ABORTING
```
=================================================================
## Steps to reproduce

Please refer to the following url for the testcases:
https://github.com/Epeius/NBPOC/tree/master/readComponent8u_heap_overflow


Comments:
Comment by carnil on 2018-01-08 20:38:19+00:00:
This issue has been assigned [CVE-2018-5268](https://github.com/opencv/opencv/issues/10541)

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 af4d6f34d8d05b0a9a0278728823272e49a63898
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;
}