Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ELF: Adding segment makes unexecutable binaries #98

laxa opened this issue Sep 26, 2017 · 1 comment

ELF: Adding segment makes unexecutable binaries #98

laxa opened this issue Sep 26, 2017 · 1 comment


Copy link

laxa commented Sep 26, 2017

Tried to make a simple packer using lief, but it turns out I was never able to make a working binary while using lief.ELF.add_segment() function.

Reproduction steps are easy, just follow and at step Injecting the hook, lief failed to add the segment on debian unstable.

On some other tests, binaries were successfully written but could not be executed. This seems to happen when adding a segment to a static binary.

Here is a sample program:

#include <stdio.h>

int     main(void)
    puts("Hello World");
    return 0;


laxa:tmp.eJeAIIAtPd:14:23:41$ gcc hello_world.c -static
laxa:tmp.eJeAIIAtPd:14:24:00$ checksec --file a.out
[*] '/tmp/tmp.eJeAIIAtPd/a.out'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)

Then using the following lief script:

import lief

binary = lief.parse('a.out')

segment = lief.ELF.Segment()

segment           = lief.ELF.Segment()
segment.type      = lief.ELF.SEGMENT_TYPES.LOAD
segment.content   = [1, 2, 3]
segment.alignment = 8
segment           = binary.add_segment(segment, base=0xA0000000)


And doing that right after fails:

laxa:tmp.eJeAIIAtPd:14:24:31$ python 
laxa:tmp.eJeAIIAtPd:14:25:18$ chmod +x a.out.bin 
laxa:tmp.eJeAIIAtPd:14:25:23$ ./a.out.bin 
Segmentation fault
laxa:tmp.eJeAIIAtPd:14:25:25$ strace ./a.out.bin 
execve("./a.out.bin", ["./a.out.bin"], [/* 51 vars */]) = 0
--- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=0x400930} ---
+++ killed by SIGSEGV +++
Segmentation fault
Copy link

romainthomas commented Sep 26, 2017

I figured out where is the problem:

In fact when we add a segment in a static (or more generally not relocatable) binary, LIEF moves the program headers at the end of the binary. The assumption of the libc is false.

I suggest you to move to the HEAD version of LIEF (v0.8.0 is coming soon)
Here is the workaround

#!/usr/bin/env python
import lief
binary = lief.parse('hello')

segment = lief.ELF.Segment()
segment.type = lief.ELF.SEGMENT_TYPES.LOAD
segment.content = [1, 2, 3]
segment = binary.replace(segment, binary[lief.ELF.SEGMENT_TYPES.NOTE])


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet

No branches or pull requests

2 participants