From 39f8614f17cd0a75dcf7739bde9b727ce3691296 Mon Sep 17 00:00:00 2001
From: alvaro <alvaro.felipe91@gmail.com>
Date: Mon, 3 Jul 2017 22:29:19 +0200
Subject: [PATCH] Added stream_size into section

This will allow to perform some security checks when reading size values
from ELF file

Fix crash e1ce7cecf01cf800397a4302854d9d76fa19763c
---
 elfio/elfio.hpp         |  9 +++------
 elfio/elfio_section.hpp | 17 ++++++++++++++++-
 2 files changed, 19 insertions(+), 7 deletions(-)

diff --git a/elfio/elfio.hpp b/elfio/elfio.hpp
index b5b9ed7..428d761 100644
--- a/elfio/elfio.hpp
+++ b/elfio/elfio.hpp
@@ -111,11 +111,9 @@ class elfio
     {
         clean();
 
-        unsigned char e_ident[EI_NIDENT];
-
-        // Read ELF file signature
-        stream.seekg( 0 );
-        stream.read( reinterpret_cast<char*>( &e_ident ), sizeof( e_ident ) );
+	unsigned char e_ident[EI_NIDENT];
+	// Read ELF file signature
+	stream.read( reinterpret_cast<char*>( &e_ident ), sizeof( e_ident ) );
 
         // Is it ELF file?
         if ( stream.gcount() != sizeof( e_ident ) ||
@@ -132,7 +130,6 @@ class elfio
         }
 
         convertor.setup( e_ident[EI_DATA] );
-
         header = create_header( e_ident[EI_CLASS], e_ident[EI_DATA] );
         if ( 0 == header ) {
             return false;
diff --git a/elfio/elfio_section.hpp b/elfio/elfio_section.hpp
index 99868ec..a226ba4 100644
--- a/elfio/elfio_section.hpp
+++ b/elfio/elfio_section.hpp
@@ -46,6 +46,16 @@ class section
     ELFIO_GET_SET_ACCESS_DECL( Elf_Xword,   size               );
     ELFIO_GET_SET_ACCESS_DECL( Elf_Word,    name_string_offset );
     ELFIO_GET_ACCESS_DECL    ( Elf64_Off,   offset             );
+    size_t stream_size;
+    const size_t get_stream_size() const 
+     {
+	return stream_size;
+     }
+
+    void set_stream_size(size_t value)
+     {
+	stream_size = value;
+     }
 
     virtual const char* get_data() const                                = 0;
     virtual void        set_data( const char* pData, Elf_Word size )    = 0;
@@ -224,11 +234,16 @@ class section_impl : public section
           std::streampos header_offset )
     {
         std::fill_n( reinterpret_cast<char*>( &header ), sizeof( header ), '\0' );
+
+	stream.seekg ( 0, stream.end );
+	set_stream_size ( stream.tellg() );
+
         stream.seekg( header_offset );
         stream.read( reinterpret_cast<char*>( &header ), sizeof( header ) );
 
+
         Elf_Xword size = get_size();
-        if ( 0 == data && SHT_NULL != get_type() && SHT_NOBITS != get_type() ) {
+        if ( 0 == data && SHT_NULL != get_type() && SHT_NOBITS != get_type() && size < get_stream_size()) {
             try {
                 data = new char[size];
             } catch (const std::bad_alloc&) {
-- 
GitLab