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

================= Bug Report (1/1) ==================
## Source: GitHub Issue
## URL: https://github.com/opencv/opencv/issues/9371
## Description:
Issue: opencv/opencv#9371
Title: Integer overflow in PxMDecoder::readData
State: closed
Created by: scdeny
Created at: 2017-08-15 06:18:34+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
integer overflow in PxMDecoder::readData
/home/scdeny/github/opencv/modules/imgcodecs/src/grfmt_pxm.cpp:199:29: runtime error: signed integer overflow: 1166948579 * 24 cannot be represented in type 'int'
/home/scdeny/github/opencv/modules/imgcodecs/src/grfmt_pxm.cpp:199:35: runtime error: signed integer overflow: -2058005176 * 8 cannot be represented in type 'int'
/home/scdeny/github/opencv/modules/imgcodecs/src/grfmt_pxm.cpp:201:26: runtime error: signed integer overflow: 1166948579 * 3 cannot be represented in type 'int'

/home/scdeny/github/opencv/modules/imgcodecs/src/grfmt_pxm.cpp
bool  PxMDecoder::readData( Mat& img )
199:
    int  src_pitch = (m_width*m_bpp*bit_depth/8 + 7)/8;
    int  nch = CV_MAT_CN(m_type);
    int  width3 = m_width*nch;

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

##### Crash log
```
==28529==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7ffc9ad1dd72 at pc 0x7fffec9a1501 bp 0x7fffffffcce0 sp 0x7fffffffccd0
READ of size 1 at 0x7ffc9ad1dd72 thread T0
    #0 0x7fffec9a1500 in icvCvt_BGR2RGB_8u_C3R(unsigned char const*, int, unsigned char*, int, CvSize) /home/scdeny/github/opencv/modules/imgcodecs/src/utils.cpp:223
    #1 0x7fffec9f466e in cv::PxMDecoder::readData(cv::Mat&) /home/scdeny/github/opencv/modules/imgcodecs/src/grfmt_pxm.cpp:322
    #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)
    #3 0x7fffec974e33 in cv::imread(cv::String const&, int) (/home/scdeny/github/opencv/debug_3.3_asan_noafl/lib/libopencv_imgcodecs.so.3.3+0x22de33)
    #4 0x4040b4 in main cpp/opencv_fuzzer.cpp:56
    #5 0x7fffeb0dd82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
    #6 0x402f48 in _start (/home/scdeny/spoof_detection/bin/opencv_fuzzer_noafl_asan+0x402f48)

0x7ffc9ad1dd72 is located 0 bytes to the right of 22369650-byte region [0x7ffc997c8800,0x7ffc9ad1dd72)
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/utils.cpp:223 icvCvt_BGR2RGB_8u_C3R(unsigned char const*, int, unsigned char*, int, CvSize)
Shadow bytes around the buggy address:
  0x10001359bb50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x10001359bb60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x10001359bb70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x10001359bb80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x10001359bb90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x10001359bba0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00[02]fa
  0x10001359bbb0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x10001359bbc0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x10001359bbd0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x10001359bbe0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x10001359bbf0: 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
==28529==ABORTING
```



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

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