How to MODIFY an ELF file with Python - python-3.x

I am trying to modify an ELF file's .text segment using python.
I successfully acquired the .text field so then I can simply change the bit that I want. The thing is that pyelftools does not provide any way to generate an ELF file from the ELF object.
So what I tried is the following:
I've created a simple helloworld program in c, compiled it and got the a.out file. Then I used the pyelftools to disassemble it.

To change/edit any section of the ELF file I simply used pyelftools's ELFFile class methods to acquire the field's (i) offset and (ii) size. So then I know exactly where to look inside the binary file.
So after getting the values-margins of the field (A,B) I simply treated the file like a normal binary. The only thing I did is to do a file.seek(A) to move the file pointer to the specific section that I wish to modify.
def edit_elf_section(elf_object,original_file,section):
elf_section = elf_object.get_section_by_name(section)
# !! IMPORTANT !!
section_start = elf_section['sh_offset'] # NOT sh_addr. sh_addr is the logical address of the section
section_end = section_start + elf_section['sh_size']
original_file.seek(section_start)
# Write whatever you want to the file #
assert(original_file.tell() <= section_end) # You've written outside the section
To validate the results you can use the diff binary to see that the files are/aren't identical

Related

Extend section in Mach-O file

I am trying to extract libraries from the Dyld_shared_cache, and need to fix in external references.
For example, the pointers in the __DATA.__objc_selrefs section usually point to data outside the mach-o file, to fix that I would have to copy the corresponding c-string from the dyld and append it to the __TEXT.__objc_methname section.
Though from my understanding of the Mach-O file format, this extension of the __TEXT.__objc_methname would shift all the sections after it and would force me to fix all the offsets and pointers that reference them. Is there a way to add data to a section without breaking a lot of things?
Thanks!
Thanks to #Kamil.S for the idea about adding a new load command and section.
One way to achieve adding more data to a section is to create a duplicate segment and section and insert it before the __LINKEDIT segment.
Slide the __LINKEDIT segment so we have space to add the new section.
define the slide amount, this must be page-aligned, so I choose 0x4000.
add the slide amount to the relevant load commands, this includes but is not limited to:
__LINKEDIT segment (duh)
dyld_info_command
symtab_command
dysymtab_command
linkedit_data_commands
physically move the __LINKEDIT in the file.
duplicate the section and change the following1
size, should be the length of your new data.
addr, should be in the free space.
offset, should be in the free space.
duplicate the segment and change the following1
fileoff, should be the start of the free space.
vmaddr, should be the start of the free space.
filesize, anything as long as it is bigger than your data.
vmsize, must be identical to filesize.
nsects, change to reflect how many sections your adding.
cmdsize, change to reflect the size of the segment command and its section commands.
insert the duplicated segment and sections before the __LINKEDIT segment
update the mach_header
ncmds
sizeofcmds
physically write the extra data in the file.
you can optionally change the segname and sectname fields, though it isn't necessary. thanks Kamil.S!
UPDATE
After clarifing with OP that extension of __TEXT.__objc_methname would happen during Mach-O post processing of an existing executable I had a fresh look on the problem.
Another take would be to create a new load command LC_SEGMENT_64 with a new __TEXT_EXEC.__objc_methname segment / section entry (normally __TEXT_EXEC is used for some kernel stuff but essentially it's the same thing as __TEXT). Here's a quick POC to ilustrate the concept:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
printf("%lx",[NSObject new]);
}
return 0;
}
Compile like this:
gcc main.m -c -o main.o
ld main.o -rename_section __TEXT __objc_methname __TEXT_EXEC __objc_methname -lobjc -lc
Interestingly only ld up to High Sierra 10.14.6 generates __TEXT.__objc_methname, no trace of it on Catalina, it's done differently.
UPDATE2.
Playing around with it, I noticed execution rights for __TEXT segment (and __TEXT_EXEC for that matter) are not required for __objc_methname to work.
Even better specific segment & section names are not required:
I could pull off:
__DATA.__objc_methname
__DATA_CONST.__objc_methname
__ARBITRARY.__arbitrary
or in my case last __DATA section
__DATA.__objc_classrefs where the original the data got concatenated by the selector name.
It's all fine as long as a proper null terminated C-string with the selector name is there. If I intentionally break the "new\0" in hex editor or MachOView I'll get
"+[NSObject ne]: unrecognized selector sent to instance ..."
upon launching my POC executable so the value is used for sure.
So to sum __TEXT.__objc_methname section itself is likely some debugger hint made by the linker. The app runtime seems to only need selector names as char* anywhere in memory.

find address of PLT stub

I am working on Linux X86_64.
I have a need to determine the address of a specific PLT entry in an ELF file given the name of the dynamic function that the entry represents.
I can figure out the file offset from the address, but I need to be able to determine the address.
If I disassemble the ELF file using objdump -D -z elffile I see that objdump uses symbolic names for each entry in the PLT. (Where does objdump obtain the relationship between these addresses and the symbol names?)
example:
0000000000000041a2b0 fileno#plt:
If I use objdump -T elffile | grep fileno I get something like this:
0000000000000 DF *UND* 00000000000000000 GLIBC_2.2.5 fileno
What I need to be able to do from "C" is find the PLT entry in the ELF file for a specific dynamic function and obtain the address.
The background is that I am patching an existing ELF file and need to redirect a function call to a different dynamic function. I have manually patched an ELF file using addresses gathered from objdump disassembly and proven that this will work for my specific application, I just need to be able to do it from a program. I am hoping not to have to crawl through objdump disassembler code to figure out how it gets the PLT entry symbols and addresses.
I figured this out:
You have to parse the relocation table in the rela.plt section.
Those entries contain a string table index that can be used to lookup the function name by indexing into the dynamic symbol section. Each entry in the dynamic symbol section contains a dynamic string table offset that can be used to pull out the function name. When you find the corresponding function, the index into the relocation table (+1) corresponds to the index into the .plt section for the functions PLT entry. So to calculate the address for a specific entry it is just: .plt.sec address + ((relocation_index + 1) * .plt entry size)
This method works for x86.
It does not work for PPC which has a completely different format for the .plt section. If anyone has any info on doing this for PPC please post.

Why the "SIZEOF_HEADERS" in ld script is 0?

Below is some snippet from my ld script:
Output format:
OUTPUT_FORMAT("elf32-i386", "elf32-i386",
"elf32-i386")
OUTPUT_ARCH(i386)
Memory layout:
MEMORY
{
CFLASH (xri) : ORIGIN = 0x20000000, LENGTH = 0x1000
(...omitted...)
}
REGION_ALIAS("CODE", CFLASH)
Sections layout:
SECTIONS
{
PROVIDE (__executable_start = SEGMENT_START("text-segment", ORIGIN(CODE)));
. = SEGMENT_START("text-segment", ORIGIN(CODE)) + SIZEOF_HEADERS; <=== PLACE 1
(...omitted...)
.startup_bsp :
{
KEEP (*(.startup_bsp))
. = ALIGN (., 0x4);
} >CODE =0xF4F4F4F4
(...omitted...)
As I understand, the location counter "." stands for the VMA. At PLACE 1, the VMA should have been set to 0x20000000 + SIZEOF_HEADERS.
But as I dumped the section headers from the generated ELF file, I see this:
So the VMA and LMA are still 0x20000000, where is the SIZEOF_HEADERS??? I think it should be the ELF file header size but it seems to be 0. Why?
According to here:
SIZEOF_HEADERS
Return the size in bytes of the output file's headers. This is information which appears at the start of the output file. You can use
this number when setting the start address of the first section, if
you choose, to facilitate paging.
When producing an ELF output file, if the linker script uses the SIZEOF_HEADERS builtin function, the linker must compute the number of
program headers before it has determined all the section addresses and
sizes. If the linker later discovers that it needs additional program
headers, it will report an error `not enough room for program
headers'. To avoid this error, you must avoid using the SIZEOF_HEADERS
function, or you must rework your linker script to avoid forcing the
linker to use additional program headers, or you must define the
program headers yourself using the PHDRS command (see PHDRS).
So far, I guess it is the >CODE that overrides the VMA calculated from the location counter .. The .startup_bsp section is appended to the CODE memory region.
And since it is the first section for CODE region, it occupies the starting address of that region.

Include binary file in as86/bin86

I have written a bit of code in i8086 assembler that is supposed to put a 80x25 image into the VRAM and show it on screen.
entry start
start:
mov di,#0xb800 ; Point ES:DI at VRAM
mov es,di
mov di,#0x0000
mov si,#image ; And DS:SI at Image
mov cx,#0x03e8 ; Image is 1000 bytes
mov bl,#0x20 ; Print spaces
; How BX is used:
; |XXXX XXXX XXXXXXXX|
; ^^^^^^^^^ BL contains ascii whitespace
; ^^^^ BH higher 4 bits contain background color
; ^^^^ BH lower 4 bits contain unused foreground color
img_loop:
seg ds ; Load color
mov bh,[si]
seg es ; Write a whitespace and color to VRAM
mov [di],bx
add di,#2 ; Advance one 'pixel'
sal bh,#4 ; Shift the unused lower 4-bits so that they become background color for the 2nd pixel
seg es
mov [di],bx
add di,#2
add si,#1
sub cx,#1 ; Repeat until 1 KiB is read
jnz img_loop
endless:
jmp endless
image:
GET splash.bin
The problem is that I cannot get the as86 assembler to include the binary data from the image file. I have looked at the the man page but I could not find anything that works.
If I try to build above code it gives me no error, but the output file produced by the linker is only 44 bytes in size, so clearly it did not bother to put in the 1000 byte image.
Can anybody help me with that? What am I doing wrong?
I am not certain that this will help you, as I have never tried it for 8086 code. But you might be able to make it work.
The objcopy program can convert binary objects to various different formats. Like this example from the man objcopy page:
objcopy -I binary -O <output_format> -B <architecture> \
--rename-section .data=.rodata,alloc,load,readonly,data,contents \
<input_binary_file> <output_object_file>
So from that you'd have an object file with your <input_binary_file> in a section named .rodata. But you could name it whatever you wanted. Then use a linker to link your machine code to the image data.
The symbol names are created for you too. Also from the man page:
-B
--binary-architecture=bfdarch
Useful when transforming a architecture-less input file into an object file. In this case the output architecture can be set to
bfdarch. This option will be ignored if the input file has a known
bfdarch. You can access this binary data inside a program by
referencing the special symbols that are created by the conversion
process. These symbols are called _binary_objfile_start,
_binary_objfile_end and _binary_objfile_size. e.g. you can transform a picture file into an object file and then access it in your code using
these symbols.
If your whole code is pure code (no executable headers, no relocation...) you can just manually concatenate the image at the end of the code (and of course remove GET splash.bin). In Linux for example you can do cat code-binary image-binary > final-binary.
Thank you everybody else trying to help me. Unfortunately I did not get the objcopy to work (maybe I am just too stupid, who knows) and while I actually used cat at first, I had to include multiple binary files soon, which should still be accessible via labels in my assembler code, so that was not a solution either.
What I ended up doing was the following: You reserve the exact amount of bytes in your assembler source code directly after the label you wanna put in your binary file, i.e.:
splash_img:
.SPACE 1000
snake_pit:
.SPACE 2000
Then you assemble your source code creating a symbol table by adding the -s option, i.e. -s snake.symbol to your call to as86. The linker call does not change. Now you have a binary file that has a bunch of zeroes at the position you wanna have your binary data, and you have a symbol table that should look similar to this:
0 00000762 ---R- snake_pit
0 0000037A ---R- splash_img
All you gotta do now is get a program to override the binary file created by the linker with your binary include file starting at the addresses found in the symbol table. It is up to you how you wanna do it, there are a lot of ways, I ended up writing a small C program that does this.
Then I just call ./as86_binin snake snake.symbols splash_img splash.bin and it copies the binary include into my linked assembler program.
I am sorry for answering my own question now, but I felt like this is the best way to do it. It is quite unfortunate bin86 doesn't have a simple binary include macro on its own. If anybody else runs into this problem in the future, I hope this will help you.

file command generating 'invalid argument'

I have a perl script that traverses a set of directories and when it hits one of them it blows up with an Invalid Argument and I want to be able to programmatically skip it. I thought I could start by finding out the file type with the file command but it too blows up like this:
$ file /sys/devices/virtual/net/br-ex/speed
/sys/devices/virtual/net/br-ex/speed: ERROR: cannot read `/sys/devices/virtual/net/br-ex/speed' (Invalid argument)
If I print out the mode of the file with the perl or python stat function it tells me 33060 but I'm not sure what all the bits mean and I'm hoping a particular one would tell me not to try to look inside. Any suggestions?
To understand the stats number you got, you need to convert the number to octal (in python oct(...)).
Then you'll see that 33060 interprets to 100444. You're interested only in the last three digits (444). The first digit is file owner permissions, the second is group and the third is everyone else.
You can look at each of the numbers (in your case all are 4) as 3 binary bits in this order:
read-write-execute.
Since in your case owner, group & other has 4, it is translated (for all of them) to 100 (in binary) which means that only the read bit is on for all three - meaning that all three can only read the file.
As far as file permissions go, you should have been successful reading /sys/devices/virtual/net/br-ex/speed.
There are two reasons for the read to fail:
- Either speed is a directory, (directories require execute permissions to read inside).
- Or it's a special file - which can be tested using the -f flag in perl or bash, or using os.path.isfile(...) in python.
Anyhow, you can use the following links to filter files & directories according to their permissions in the 3 languages you mentioned:
ways to test permissions in perl.
ways to test permissions in python.
ways to test permissions in bash.
Not related to this particular case, but I hit the same error when I ran it on a malicious ELF (Linux executable) file. In that case it was because the program headers of the ELF was intentionally corrupted. Looking at the source code for file command, this is clear as it checks the ELF headers and bails out with the same error in case the headers are corrupted:
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) <
CAST(ssize_t, xph_sizeof)) {
file_badread(ms);
return -1;
}
TLDR; The file command checks not only the magic bytes, but it also performs other checks to validate a file type.

Resources