Warm tip: This article is reproduced from serverfault.com, please click

Receiving Segmentation fault when trying to execute injected code inside ELF binary

发布于 2020-11-28 11:05:49

I am currently working on an ELF-injector and my approach is standard: find code cave (long enough sequence of 0's), rewrite it with the instructions I want to execute and then jump back to the start of the original program to execute it as it normally would.

To actually execute code in the code cave I tried two different approaches, both of which result in sigsegv.

First one was changing entry point to the start of the code cave. The second one was "stealing" some of the first instructions from the original code and write jump to my code cave there and then after executing my injected code I would first execute stolen instructions and then jump to the instruction after the last stolen one in the original program.

I am also changing the access flags for the section, in which code cave resides.

Here are some screenshots of debugging the program in gdb:

Instructions at entry point - 0x555555556156 is the address of code cave

Instructions in the code cave - executing stolen ones and jumping back

Executing the code

And here are the flags for the section the code cave is in:

[19] 0x555555556058->0x555555556160 at 0x00002058: .eh_frame ALLOC LOAD READONLY CODE HAS_CONTENTS

EDIT: This is the Valgrind output, so the problem is actually with the permissions. How can I allow the code inside this section be executed?

enter image description here

Questioner
Nazar Pasternak
Viewed
0
Employed Russian 2020-11-29 01:02:41

I am also changing the access flags for the section, in which code cave resides.

Sections are not used at runtime, only segments are. Changing access flags on a section after the program is linked does exactly nothing.

You need to find a place for your cove in a segment with the right permissions.

P.S. You appear to be using objdump to examine contents of your ELF file.

Don't: it's entirely inadequate. Use readelf instead.