Mona the Monad
Mona the Monad

Reputation: 2435

Get start and end of a section

Foreword

There already exist questions like this one, but the ones I have found so far were either specific to a given toolchain (this solution works with GCC, but not with Clang), or specific to a given format (this one is specific to Mach-O). I tagged ELF in this question merely out of familiarity, but I'm trying to figure out as "portable" a solution as reasonably possible, for other platforms. Anything that can be done with GCC and GCC-compatible toolchains (like MinGW and Clang) would suffice for me.

Problem

I have an ELF section containing a collection of relocatable "gadgets" that are to be copied/injected into something that can execute them. They are completely relocatable in that the raw bytes of the section can be copied verbatim (e.g. by memcpy) to any [correctly aligned] memory location, with little to no relocation processing (done by the injector). The problem is that I don't have a portable way of determining the size of such a section. I could "cheat" a little by using --section-start, and outright determine a start address, but that feels a little hacky, and I still wouldn't have a way to get the section's end/size.

Overview

Most of the gadgets in the section are written in assembly, so the section itself is declared there. No languages were tagged because I'm trying to be portable with this and get it working for various architectures/platforms. I have separate assembly sources for each (e.g. ARM, AArch64, x86_64, etc).

   ; The injector won't be running this code, so no need to be executable.
   ; Relocations (if any) will be done by the injector.
   .section gadgets, "a", @progbits
   ...

The more "heavy duty" code is written in C and compiled in via a section attribute.

__attribute__((section("gadgets")))
void do_totally_innocent_things();

Alternatives

I technically don't need to make use of sections like this at all. I could instead figure out the ends of each function in the gadget, and then copy those however I like. I figured using a section would be a more straightforward way to go about it, to keep everything in one modular relocatable bundle.

Upvotes: 0

Views: 1158

Answers (1)

bitflip
bitflip

Reputation: 21

I'm not sure if you considered this or this is out of picture but you could read the elf headers. This would be sort of 'universal' as you can do the same thing with Mach-O binaries

So for example: Creating 3 integer variables inside the 'custom_sect' section

These would add up to 12 or 0xC bytes which if we read the headers we can confirm: Size with readelf

and here is how a section is represented in the ELF executables: ELF section representation

So each section will have its own size property which you can just read out

Upvotes: 0

Related Questions