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

================= Bug Report (1/1) ==================
## Source: GitHub Issue
## URL: https://github.com/opencv/opencv/issues/9370
## Description:
Issue: opencv/opencv#9370
Title: AutoBuffer_heap_overflow in grfmt_pxm.cpp
State: closed
Created by: scdeny
Created at: 2017-08-15 06:14:56+00:00
Labels: bug, category: imgcodecs, category: vulnerability

Issue Body:
##### System information (version)
- OpenCV => 3.3
- Operating System / Platform => Ubuntu 16.04
- Compiler => g++

##### Detailed description
cv::imread("0.AutoBuffer_heap_overflow_poc") trigger the heap buffer overflow
OpenCV version from 2.2 to 3.3 affected

Root cause:
in modules/imgcodecs/src/grfmt_pxm.cpp
```
197:
    int  bit_depth = CV_ELEM_SIZE1(m_type)*8;
    int  src_pitch = (m_width*m_bpp*bit_depth/8 + 7)/8;
205:
    AutoBuffer<uchar> _src(src_pitch + 32);
    uchar* src = _src;
234:
                    for( x = 0; x < m_width; x++ )
                        src[x] = ReadNumber( m_strm, 1 ) != 0;
```

In my poc, the m_width is about 8x bigger than src_pitch, which cause the \_src buffer overflowed

```
(gdb) p src_pitch
$1 = 0xa2c3
(gdb) p m_width
$2 = 0x51615
(gdb) p m_bpp
$3 = 0x1
(gdb) p bit_depth
$4 = 0x8
```

##### Steps to reproduce
cv::imread("0.AutoBuffer_heap_overflow_poc")
poc is here:
https://github.com/scdeny/opencv_pocs/blob/master/0.AutoBuffer_heap_overflow_poc


#### Crash log
```
=================================================================
==18000==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x62e00000a6e3 at pc 0x7fffec9f24cc bp 0x7fffffffcd60 sp 0x7fffffffcd50
WRITE of size 1 at 0x62e00000a6e3 thread T0
    #0 0x7fffec9f24cb in cv::PxMDecoder::readData(cv::Mat&) /home/scdeny/github/opencv/modules/imgcodecs/src/grfmt_pxm.cpp:237
    #1 0x7fffec9739a6 in cv::imread_(cv::String const&, int, int, cv::Mat*) (/home/scdeny/github/opencv/debug_3.3_asan_noafl/lib/libopencv_imgcodecs.so.3.3+0x22c9a6)
    #2 0x7fffec974e33 in cv::imread(cv::String const&, int) (/home/scdeny/github/opencv/debug_3.3_asan_noafl/lib/libopencv_imgcodecs.so.3.3+0x22de33)
    #3 0x4040b4 in main cpp/opencv_fuzzer.cpp:56
    #4 0x7fffeb0dd82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
    #5 0x402f48 in _start (/home/scdeny/spoof_detection/bin/opencv_fuzzer_noafl_asan+0x402f48)

0x62e00000a6e3 is located 0 bytes to the right of 41699-byte region [0x62e000000400,0x62e00000a6e3)
allocated by thread T0 here:
    #0 0x7ffff6f036b2 in operator new[](unsigned long) (/usr/lib/x86_64-linux-gnu/libasan.so.2+0x996b2)
    #1 0x7fffec9b588e in cv::AutoBuffer<unsigned char, 1032ul>::allocate(unsigned long) /home/scdeny/github/opencv/modules/core/include/opencv2/core/utility.hpp:991
    #2 0x7fffec9739a6 in cv::imread_(cv::String const&, int, int, cv::Mat*) (/home/scdeny/github/opencv/debug_3.3_asan_noafl/lib/libopencv_imgcodecs.so.3.3+0x22c9a6)

SUMMARY: AddressSanitizer: heap-buffer-overflow /home/scdeny/github/opencv/modules/imgcodecs/src/grfmt_pxm.cpp:237 cv::PxMDecoder::readData(cv::Mat&)
Shadow bytes around the buggy address:
  0x0c5c7fff9480: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c5c7fff9490: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c5c7fff94a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c5c7fff94b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c5c7fff94c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c5c7fff94d0: 00 00 00 00 00 00 00 00 00 00 00 00[03]fa fa fa
  0x0c5c7fff94e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c5c7fff94f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c5c7fff9500: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c5c7fff9510: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c5c7fff9520: fa 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
==18000==ABORTING
```



Comments:
Comment by scdeny on 2017-08-16 00:35:18+00:00:
got [CVE-2017-12862](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-12862)

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