Skip to content

Commit

Permalink
Check for ELF damage (#1036)
Browse files Browse the repository at this point in the history
* Check if LOAD segments are within the file

* Separate segment checking into its own function, set loadable anyway
  • Loading branch information
HoundThe committed Nov 2, 2021
1 parent 59deef2 commit 122887a
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
7 changes: 7 additions & 0 deletions include/retdec/fileformat/file_format/elf/elf_format.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
namespace retdec {
namespace fileformat {

enum ElfLoaderError : std::uint32_t
{
LDR_ERROR_NONE = 0,
LDR_ERROR_SEGMENT_OUT_OF_FILE
};

/**
* ElfFormat - wrapper for parsing ELF files
*/
Expand Down Expand Up @@ -75,6 +81,7 @@ class ElfFormat : public FileFormat
const ELFIO::dynamic_section_accessor *elfDynamicTable,
const ELFIO::section *sec);
void loadSections();
void checkSegmentLoadable(const ELFIO::segment* seg);
void loadSegments();
void loadDynamicSegmentSection();
void loadInfoFromDynamicTables(DynamicTable &dynTab, ELFIO::section *sec);
Expand Down
11 changes: 4 additions & 7 deletions include/retdec/fileformat/file_format/file_format.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,10 @@ namespace fileformat {

struct LoaderErrorInfo
{
LoaderErrorInfo() : loaderErrorCode(0), loaderError(nullptr), loaderErrorUserFriendly(nullptr)
{}

std::uint32_t loaderErrorCode; // Loader error code, cast to uint32_t
const char * loaderError;
const char * loaderErrorUserFriendly;
bool isLoadableAnyway;
std::uint32_t loaderErrorCode = 0; // Loader error code, cast to uint32_t - 0 means OK
const char *loaderError = nullptr;
const char *loaderErrorUserFriendly = nullptr;
bool isLoadableAnyway = false;
};

/**
Expand Down
21 changes: 21 additions & 0 deletions src/fileformat/file_format/elf/elf_format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2062,6 +2062,25 @@ void ElfFormat::loadSections()
}
}

void ElfFormat::checkSegmentLoadable(const segment* seg)
{
if (!seg)
return;

auto filesize = seg->get_file_size();
auto fileoffset = seg->get_offset();
int segtype = seg->get_type();

// Check if LOAD segments are actually in the file
if (segtype == PT_LOAD && getFileLength() < fileoffset + filesize)
{
_ldrErrInfo.isLoadableAnyway = false;
_ldrErrInfo.loaderErrorCode = ElfLoaderError::LDR_ERROR_SEGMENT_OUT_OF_FILE;
_ldrErrInfo.loaderError = "LOAD Segment data is not within file bounds";
_ldrErrInfo.loaderErrorUserFriendly = "LOAD Segment data is not within file bounds";
}
}

/**
* Load information about segments
*/
Expand All @@ -2088,6 +2107,8 @@ void ElfFormat::loadSegments()
fSeg->setElfAlign(seg->get_align());
fSeg->load(this);
segments.push_back(fSeg);

checkSegmentLoadable(seg);
}
}

Expand Down

0 comments on commit 122887a

Please sign in to comment.