Reputation: 60577
How can you determine where a 32-bit ELF Linux binary ends, and additional data appended to the file begins? For example, some software will append data to the end of a file for extraction or execution, while being contained in a single binary. A self-extracting archive would be an example of such a file.
What I'm trying to do is similar to what Find out where PE file ends through PE header? asks, except for Linux ELF binaries, and not Windows PE binaries.
Note that in my case there is not a footer or any other data at the end to specify how large the payload is. Such data is specified where the ELF file end, just before the payload begins, but I would like to know how to programmatically find it without seeking for it and hoping it doesn't get a false-positive.
Upvotes: 2
Views: 2528
Reputation: 2363
The answer is different depending on the layout of the ELF headers. A binary compiled with or without debug symbols, and a binary that is completely stripped, may have sections in different orders. Sometimes the last ELF entry is the file header, and sometimes other sections, e.g. a .symtab section, appears later in the file.
uint32_t size;
Elf<size>_Ehrd* header = ...;
Elf<size>_Shdr* last_header = ...; // get the section with the highest offset
if(last_header->sh_offset < header->e_shoff)
size = header->e_shoff + header->e_shnum * header->e_shentsize;
else
size = last_section->sh_offset + last_section->sh_size;
You actually can in some cases overwrite sections that occur after the file header, and the program will still run. If you don't truncate the file, doing a strip
will still work. But readelf
can index into sections that have been overwritten or report that the file has been truncated.
Comparing the actual last section's offset in the calculation keeps the whole binary intact, not just the runnable part of it.
Upvotes: 1
Reputation: 1734
Maybe you could get the position of the section header table and time it with the amount of entries and the entry size? Not entirely sure but that's my best bet.
Upvotes: 4