Project: matio (tbeu/matio), language: c++
Vulnerability instance: matio.cve-2019-20017
Sanitizer: address

================= Bug Report (1/1) ==================
## Source: GitHub Issue
## URL: https://github.com/tbeu/matio/issues/127
## Description:
Issue: tbeu/matio#127
Title: There is a stack-based buffer overflow in the Mat_VarReadNextInfo5 function of mat5.c(at 4915)
State: closed
Created by: gutiniao
Created at: 2019-11-07 03:14:45+00:00

Issue Body:
A crafted input will lead to crash in mat5.c at matio 1.5.17.
Triggered by
./matdump POC

Poc
[001-stackover-Mat_VarReadNextInfo5_mat54915](https://github.com/gutiniao/afltest/blob/master/001-stackover-Mat_VarReadNextInfo5_mat54915)

The ASAN information is as follows:

```
./matdump 001-stackover-Mat_VarReadNextInfo5_mat54915 
InflateRankDims: inflate returned data error
=================================================================
==31427==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffcc32c92d0 at pc 0x7fcd463809a6 bp 0x7ffcc32c90c0 sp 0x7ffcc32c90b0
READ of size 4 at 0x7ffcc32c92d0 thread T0
    #0 0x7fcd463809a5 in Mat_VarReadNextInfo5 /home/matio_asan/src/mat5.c:4915
    #1 0x7fcd4639746b in Mat_VarReadNextInfo /home/matio_asan/src/mat.c:2342
    #2 0x408126 in main /home/matio_asan/tools/matdump.c:944
    #3 0x7fcd45b7282f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
    #4 0x401b58 in _start (/usr/local/matio_asan/bin/matdump+0x401b58)

Address 0x7ffcc32c92d0 is located in stack of thread T0 at offset 416 in frame
    #0 0x7fcd4637fc54 in Mat_VarReadNextInfo5 /home/matio_asan/src/mat5.c:4788

  This frame has 6 object(s):
    [32, 36) 'data_type'
    [96, 100) 'nBytes'
    [160, 168) 'dims'
    [224, 232) 'size'
    [288, 312) 'buf'
    [352, 416) 'uncomp_buf' <== Memory access at offset 416 overflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
      (longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-overflow /home/matio_asan/src/mat5.c:4915 Mat_VarReadNextInfo5
Shadow bytes around the buggy address:
  0x100018651200: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x100018651210: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x100018651220: 00 00 00 00 00 00 f1 f1 f1 f1 04 f4 f4 f4 f2 f2
  0x100018651230: f2 f2 04 f4 f4 f4 f2 f2 f2 f2 00 f4 f4 f4 f2 f2
  0x100018651240: f2 f2 00 f4 f4 f4 f2 f2 f2 f2 00 00 00 f4 f2 f2
=>0x100018651250: f2 f2 00 00 00 00 00 00 00 00[f3]f3 f3 f3 f3 f3
  0x100018651260: f3 f3 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x100018651270: 00 00 00 00 00 00 00 00 f1 f1 f1 f1 00 f4 f4 f4
  0x100018651280: f2 f2 f2 f2 00 04 f4 f4 f3 f3 f3 f3 00 00 00 00
  0x100018651290: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x1000186512a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
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
==31427==ABORTING
```
about code (4915):

```
    if ( mat->byteswap ) {
                        for ( j = 0; j < matvar->rank; j++ )
                            matvar->dims[j] = Mat_uint32Swap(dims + j);
                    } else {
                        for ( j = 0; j < matvar->rank; j++ )
----------------->   matvar->dims[j] = dims[j];
                    }
```




Comments:
Comment by tbeu on 2019-11-09 08:27:46+00:00:
No need to report fuzzing issues since matio is on [OSS-Fuzz](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&q=proj%3Amatio&can=1) with still about 40 open issues.

Instead of v1.5.17, please rerun the test against current master and reopen if the issue is still reproducible.

---

Comment by gutiniao on 2019-11-11 07:09:53+00:00:
> No need to report fuzzing issues since matio is on [OSS-Fuzz](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&q=proj%3Amatio&can=1) with still about 40 open issues.
> 
> Instead of v1.5.17, please rerun the test against current master and reopen if the issue is still reproducible.

Yes, I just use 'git clone' to fetch the current master of the matio,the issue is still reproducible.
![image](https://user-images.githubusercontent.com/57210135/68567760-c8dfc300-0494-11ea-829a-7f361925ac9c.png)

![image](https://user-images.githubusercontent.com/57210135/68567735-bd8c9780-0494-11ea-9ddd-1cc56b939ec1.png)
i 'm sure the issue is different from the fuzzing issues on OSS-fuzz.

---

Comment by tbeu on 2019-11-11 21:18:08+00:00:
I cannot reproduce.

---

Comment by gutiniao on 2019-11-12 06:22:00+00:00:
> I cannot reproduce.

Your fixs about [issue 128](https://github.com/tbeu/matio/issues/128) and [issue 129](https://github.com/tbeu/matio/issues/129) have solve the problem . but there is a new [issue](https://github.com/tbeu/matio/issues/131)

---

Comment by carnil on 2019-12-27 08:42:46+00:00:
CVE-2019-20017 has been assigned for this issue.

Build script:
#!/bin/bash -eu
# Minimized build script with only core build commands
set -eu
./autogen.sh
./configure
make -j$(nproc)
make install -j$(nproc)

Dockerfile:
FROM hwiwonlee/secb.base:latest
RUN apt-get update && apt-get install -y make autoconf automake libtool
RUN git clone https://github.com/tbeu/matio matio
RUN git -C matio checkout 64f793668e09216029447990702c145403d14375
WORKDIR $SRC/matio
COPY build.sh $SRC/

Additional files:
filename: fuzzer_temp_file.h
content: // Copyright 2019 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: matio_fuzzer.cc
content: // Copyright 2019 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.

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>

#include "fuzzer_temp_file.h"
#include "matio.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  FuzzerTemporaryFile temp_file(data, size);

  mat_t* matfd = Mat_Open(temp_file.filename(), MAT_ACC_RDONLY);
  if (matfd == nullptr) {
    return 0;
  }
  // TODO(https://github.com/google/oss-fuzz/pull/2761): use more complicated APIs
  // such as Mat_VarReadDataAll, Mat_VarReadDataLinear, Mat_VarReadNext, etc. 
  Mat_Close(matfd);

  return 0;
}