Project: libxml2 (gnome/libxml2), language: c++
Vulnerability instance: libxml2.cve-2016-1833
Sanitizer: address

================= Bug Report (1/1) ==================
## Source: Chromium
## URL: https://bugs.chromium.org/p/project-zero/issues/detail?id=636
## Description:
The following crash due to a heap-based out-of-bounds memory read can be observed in an ASAN build of latest stable libxml2 (2.9.3, released 4 days ago), by feeding a malformed file to xmllint ("$ ./xmllint --html /path/to/file"):

--- cut ---
==26202==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x62100001c900 at pc 0x0000008073f9 bp 0x7ffd791c7f90 sp 0x7ffd791c7f88
READ of size 1 at 0x62100001c900 thread T0
    #0 0x8073f8 in htmlCurrentChar libxml2-2.9.3/HTMLparser.c:439:6
    #1 0x80ee62 in htmlParseCharDataInternal libxml2-2.9.3/HTMLparser.c:3011:8
    #2 0x821b85 in htmlParseCharData libxml2-2.9.3/HTMLparser.c:3061:5
    #3 0x7df875 in htmlParseContentInternal libxml2-2.9.3/HTMLparser.c:4634:3
    #4 0x7e2f0f in htmlParseDocument libxml2-2.9.3/HTMLparser.c:4769:5
    #5 0x802c55 in htmlDoRead libxml2-2.9.3/HTMLparser.c:6741:5
    #6 0x8030b6 in htmlReadFile libxml2-2.9.3/HTMLparser.c:6799:13
    #7 0x4f47a5 in parseAndPrintFile libxml2-2.9.3/xmllint.c:2248:8
    #8 0x4ebe8f in main libxml2-2.9.3/xmllint.c:3759:7

0x62100001c900 is located 0 bytes to the right of 4096-byte region [0x62100001b900,0x62100001c900)
allocated by thread T0 here:
    #0 0x4b8b68 in malloc llvm/projects/compiler-rt/lib/asan/asan_malloc_linux.cc:40
    #1 0xa01a0c in xmlBufCreate libxml2-2.9.3/buf.c:137:32
    #2 0x550aca in xmlSwitchInputEncodingInt libxml2-2.9.3/parserInternals.c:1205:34
    #3 0x54f5ce in xmlSwitchToEncodingInt libxml2-2.9.3/parserInternals.c:1281:12
    #4 0x54f278 in xmlSwitchEncoding libxml2-2.9.3/parserInternals.c:1101:11
    #5 0x808eea in htmlCurrentChar libxml2-2.9.3/HTMLparser.c:518:13
    #6 0x804a38 in htmlParseNameComplex libxml2-2.9.3/HTMLparser.c:2496:9
    #7 0x7cc29d in htmlParseName libxml2-2.9.3/HTMLparser.c:2483:12
    #8 0x7ec211 in htmlParseDocTypeDecl libxml2-2.9.3/HTMLparser.c:3424:12
    #9 0x7debf4 in htmlParseContentInternal libxml2-2.9.3/HTMLparser.c:4585:3
    #10 0x7e2f0f in htmlParseDocument libxml2-2.9.3/HTMLparser.c:4769:5
    #11 0x802c55 in htmlDoRead libxml2-2.9.3/HTMLparser.c:6741:5
    #12 0x8030b6 in htmlReadFile libxml2-2.9.3/HTMLparser.c:6799:13
    #13 0x4f47a5 in parseAndPrintFile libxml2-2.9.3/xmllint.c:2248:8
    #14 0x4ebe8f in main libxml2-2.9.3/xmllint.c:3759:7

SUMMARY: AddressSanitizer: heap-buffer-overflow libxml2-2.9.3/HTMLparser.c:439:6 in htmlCurrentChar
Shadow bytes around the buggy address:
  0x0c427fffb8d0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c427fffb8e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c427fffb8f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c427fffb900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0c427fffb910: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c427fffb920:[fa]fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c427fffb930: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c427fffb940: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c427fffb950: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c427fffb960: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0c427fffb970: 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
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==26202==ABORTING
--- cut ---

The crash was reported at https://bugzilla.gnome.org/show_bug.cgi?id=758606. Attached is an XML file which triggers the crash.

This bug is subject to a 90 day disclosure deadline. If 90 days elapse without a broadly available patch, then the bug report will automatically become visible to the public.

Build script:
#!/bin/bash
# Default build script template for C/C++ projects
set -eu

# Define configuration options
CONFIG_OPTS="--disable-shared"
CMAKE_OPTS="-DCMAKE_BUILD_TYPE=Debug"
MAKE_OPTS="-j$(nproc)"
BUILD_DIR="build"

# 1. Run build preparation scripts if they exist
for prep_script in buildconf autogen.sh bootstrap; do
  if [ -x "$prep_script" ]; then
    echo "Running $prep_script..."
    ./$prep_script
    break
  elif [ -f "$prep_script" ]; then
    echo "Found $prep_script but it's not executable, setting permissions..."
    chmod +x $prep_script
    ./$prep_script
    break
  fi
done

# 2. Handle different build systems
if [ -f "configure" ]; then
  echo "Found configure script, running with options: $CONFIG_OPTS"
  ./configure $CONFIG_OPTS

  echo "Building with make $MAKE_OPTS"
  make $MAKE_OPTS
elif [ -f "CMakeLists.txt" ]; then
  echo "Found CMakeLists.txt, using CMake build system"
  mkdir -p $BUILD_DIR
  cd $BUILD_DIR
  cmake $CMAKE_OPTS ..
  make $MAKE_OPTS
elif [ -f "Makefile" ] || [ -f "makefile" ]; then
  echo "Found Makefile, building with make $MAKE_OPTS"
  make $MAKE_OPTS
elif [ -f "meson.build" ]; then
  echo "Found meson.build, using Meson build system"
  mkdir -p $BUILD_DIR
  meson setup $BUILD_DIR .
  cd $BUILD_DIR
  ninja
elif [ -f "GNUmakefile" ]; then
  echo "Found GNUmakefile, building with make $MAKE_OPTS"
  make $MAKE_OPTS
elif [ -d ".git" ] && [ -f "Makefile.am" ]; then
  echo "Found Makefile.am, running autoreconf"
  autoreconf -i
  ./configure $CONFIG_OPTS
  make $MAKE_OPTS
else
  echo "WARNING: No recognized build system found!"
  echo "Trying generic approach:"
  
  # Try to detect common source patterns and compile them
  if ls *.c >/dev/null 2>&1 || ls *.cpp >/dev/null 2>&1 || ls *.cc >/dev/null 2>&1; then
    echo "Found C/C++ source files, attempting direct compilation"
    if ls *.cpp >/dev/null 2>&1 || ls *.cc >/dev/null 2>&1; then
      CXX=${CXX:-g++}
      echo "Compiling C++ sources with $CXX"
      $CXX -g -O1 -fsanitize=address -fno-omit-frame-pointer -o main *.cpp *.cc 2>/dev/null || true
    elif ls *.c >/dev/null 2>&1; then
      CC=${CC:-gcc}
      echo "Compiling C sources with $CC"
      $CC -g -O1 -fsanitize=address -fno-omit-frame-pointer -o main *.c 2>/dev/null || true
    fi
  fi
fi

Dockerfile:
FROM hwiwonlee/secb.base:latest
RUN apt-get update && case "$TARGETPLATFORM" in 'linux/arm64') EXTRA_PACKAGES='' ;; *)             EXTRA_PACKAGES='zlib1g-dev:i386 liblzma-dev:i386' ;; esac && apt-get install -y --no-install-recommends make autoconf libtool pkg-config zlib1g-dev liblzma-dev $EXTRA_PACKAGES
RUN apt-get install -y --no-install-recommends make autoconf libtool pkg-config zlib1g-dev liblzma-dev $EXTRA_PACKAGES
RUN git clone https://github.com/gnome/libxml2 libxml2
RUN git -C libxml2 checkout 502f6a6d08b08c04b3ddfb1cd21b2f699c1b7f5b
WORKDIR $SRC/libxml2
COPY build.sh $SRC/

Additional files:
filename: libxml2_xml_read_memory_fuzzer.cc
content: // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>
#include <stdint.h>

#include "libxml/parser.h"

void ignore (void* ctx, const char* msg, ...) {
  // Error handler to avoid spam of error messages from libxml parser.
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  xmlSetGenericErrorFunc(NULL, &ignore);

  if (auto doc = xmlReadMemory(reinterpret_cast<const char*>(data),
                               static_cast<int>(size), "noname.xml", NULL, 0)) {
    xmlFreeDoc(doc);
  }

  return 0;
}

filename: libxml2_xml_read_memory_fuzzer.options
content: [libfuzzer]
dict = xml.dict

filename: libxml2_xml_regexp_compile_fuzzer.cc
content: // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>
#include <stdint.h>

#include <algorithm>
#include <string>
#include <vector>

#include "libxml/parser.h"
#include "libxml/tree.h"
#include "libxml/xmlversion.h"


void ignore (void * ctx, const char * msg, ...) {
  // Error handler to avoid spam of error messages from libxml parser.
}


// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  xmlSetGenericErrorFunc(NULL, &ignore);

  std::vector<uint8_t> buffer(size + 1, 0);
  std::copy(data, data + size, buffer.data());

  xmlRegexpPtr x = xmlRegexpCompile(buffer.data());
  if (x)
    xmlRegFreeRegexp(x);

  return 0;
}

filename: libxml2_xml_regexp_compile_fuzzer.options
content: [libfuzzer]
dict = xml.dict

filename: target.yaml
content: homepage: "http://www.xmlsoft.org/"

filename: xml.dict
content: # Copyright 2016 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.
#
################################################################################
#
# AFL dictionary for XML
# ----------------------
#
# Several basic syntax elements and attributes, modeled on libxml2.
#
# Created by Michal Zalewski <lcamtuf@google.com>
#

attr_encoding=" encoding=\"1\""
attr_generic=" a=\"1\""
attr_href=" href=\"1\""
attr_standalone=" standalone=\"no\""
attr_version=" version=\"1\""
attr_xml_base=" xml:base=\"1\""
attr_xml_id=" xml:id=\"1\""
attr_xml_lang=" xml:lang=\"1\""
attr_xml_space=" xml:space=\"1\""
attr_xmlns=" xmlns=\"1\""

entity_builtin="&lt;"
entity_decimal="&#1;"
entity_external="&a;"
entity_hex="&#x1;"

string_any="ANY"
string_brackets="[]"
string_cdata="CDATA"
string_col_fallback=":fallback"
string_col_generic=":a"
string_col_include=":include"
string_dashes="--"
string_empty="EMPTY"
string_empty_dblquotes="\"\""
string_empty_quotes="''"
string_entities="ENTITIES"
string_entity="ENTITY"
string_fixed="#FIXED"
string_id="ID"
string_idref="IDREF"
string_idrefs="IDREFS"
string_implied="#IMPLIED"
string_nmtoken="NMTOKEN"
string_nmtokens="NMTOKENS"
string_notation="NOTATION"
string_parentheses="()"
string_pcdata="#PCDATA"
string_percent="%a"
string_public="PUBLIC"
string_required="#REQUIRED"
string_schema=":schema"
string_system="SYSTEM"
string_ucs4="UCS-4"
string_utf16="UTF-16"
string_utf8="UTF-8"
string_xmlns="xmlns:"

tag_attlist="<!ATTLIST"
tag_cdata="<![CDATA["
tag_close="</a>"
tag_doctype="<!DOCTYPE"
tag_element="<!ELEMENT"
tag_entity="<!ENTITY"
tag_ignore="<![IGNORE["
tag_include="<![INCLUDE["
tag_notation="<!NOTATION"
tag_open="<a>"
tag_open_close="<a />"
tag_open_exclamation="<!"
tag_open_q="<?"
tag_sq2_close="]]>"
tag_xml_q="<?xml?>"