Access violation on `jmp` to appended segment - windows

So I've used CFF Explorer to add a code section to an .exe file. I've set the section characteristics to 0x60000020 (executable, readable, contains code) and created some dummy code there using IDA.
However, when I injected a jmp to that code from the original .text segment, all I got was an access violation. I used IDA to patch the binary, so it generated offsets for me, but it seems to be right:
jmp far ptr 6:75D100h
The resulting opcode looks right too:
EA 00 D1 75 00 06 00
But as soon as I hit that jump - "The instruction referenced memory at 0xFFFFFFFF, memory can't be read". I've experimented a bit with offsets to no avail; The appended segment seems to be properly loaded in memory.
Would be grateful for any hint to what I am missing here:)

Just to mark this as answered - the solution, as proposed by #Jester and #RossRidge, was to drop the jmp far. Using
jmp near ptr 75D100h
fixed everything. Have to say IDA's behavior can be somewhat wierd.

Related

Why do these `const int main=0xc3` (or other number) programs return 252 on OS X?

I heard about the "shortest C program that results in an illegal instruction": const main=6; for x86-64 over on codegolf.SE and it got me curious what would happen if I put different numbers there.
Now I guess this has to do with what is or isn't a valid x86-64 instruction (durr) but specifically I'd like to know what the different results mean.
const main=0 through 2 give bus error.
const main=3 gives a segfault.
6 and 7 give illegal instruction.
I get various bus errors and segfaults and illegal instructions up until
const main=194 which didn't give me an interrupt at all (at least not that got through to my python script that was generating these little programs).
There are a few other numbers that also do not lead to exceptions/interrupts and thus to Unix signals. I checked the return code of a couple and the return code was 252. I don't know why or what that means or how it got there.
204 got me a "trace trap". This is 0xcc which I know is the int3 interrupt - that's fun! (241/0xf1 also gets me this)
Anyway, it keeps going and it's obviously mostly bus errors and segfaults and a few illegal instructions here and there and the occasional... does whatever it does and then returns with 252...
I googled around some opcodes but I don't really know what I am doing or where to look to be honest. I haven't even looked at all my outputs yet just been scrolling through. I understand that a segfault is invalid access to valid memory and a bus error is access to invalid memory and I plan to look at the patterns of the numbers and work out where these are happening and why. But the 252 thing has me a bit stumped.
#!/usr/bin/env python3
import os
import subprocess
import time
import signal
os.mkdir("testc")
try:
os.chdir("testc")
except:
print("Could not change directory, exiting.")
for i in range(0, 65536):
filename = "test" + str(i) + ".c"
f = open(filename, "w")
f.write("const main=" + str(i) + ";")
f.close()
outname = "test" + str(i)
subprocess.Popen(["gcc", filename, "-o", outname], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(1)
err = subprocess.Popen("./" + outname, shell=True)
result = None
while result is None:
result = err.poll()
r = result
if result == -11:
r = "segfault"
if result == -10:
r = "bus error"
if result == -4:
r = "illegal instruction"
if result == -5:
print = "trap"
print("const main=" + str(hex(i)) + " : " + r)
This produces a C program in testc/test20.c like
const int main=20;
Then compiles it with gcc and runs it. (And sleeps for 1 second before trying the next number.)
There were no expectations. I just wanted to see what happened.
int main = 194 is c2 00 00 00, which decodes as ret 0
Whatever called main must have left 252 in the low byte of RAX. (The calling convention says that RAX is the return-value register, but it's not an arg-passing register so on function entry it holds whatever tmp garbage your caller was using it for.)
See the bottom of the answer for a theory on why you get SIGBUS for 2 but SIGSEGV for 3: I think RAX is a valid pointer on entry to main (by chance of what the dynamic linker had there), 03 00 add eax, [rax] destroys it but 02 00 add al, [rax] doesn't, and then execution either faults on the 00 00 add [rax], al from the next 2 bytes of main, or runs the 00 00 instruction and then falls off the end of a page.
Update from #MichaelPetch: RAX is pointing to main (in the read-only TEXT segment), and stores to read-only pages also SIGBUS. So 00 00 add [rax], al will SIGBUS for that reason if RAX is still pointing there.
(Beware that this answer has some wrong guesses and wasn't fully rewritten every time I got new info from #SWilliams or #MichaelPetch. The bullet points about what kinds of #PF cause which signal are up to date, and I've tried to at least add a correction after things that weren't quite accurate. I think there's some value to the wrong theories, as an illustration of others kinds of things that might have happened, so I'm leaving it all in here.)
Your Python program fails on my Linux machine once it gets to c2 00 00 00 ret imm16, the first one that returns successfully. (On Linux, the .rodata section ends up after .text in the TEXT segment, so there's nothing for main to fall into.)
...
const main=0xc0 : segfault
const main=0xc1 : segfault
Traceback (most recent call last):
File "./opcode-test.py", line 34, in <module>
print("const main=" + str(hex(i)) + " : " + r)
TypeError: must be str, not int
Doesn't python have an equivalent of strsignal(3) to map signals to standard text strings like "Illegal instruction"? (Like strerror but for signal codes instead of errno values?)
Most x86 instructions are multiple bytes long. x86 is little-endian, so you're mostly looking at
?? 00 00 00 90 90 90 ... or for larger integers ?? ?? 00 00 90 90 90 90 ..., assuming your linker fills bytes between functions with 0x90 nop like GNU ld on Linux does.
These byte sequences might decode to one or more valid instructions before you hit the NOPs and fall through to whatever CRT function the linker puts after main. If you get there without faulting, and without offsetting the stack pointer, you've entered the function with a valid return address on the stack (main's caller, another CRT function) exactly like if main tail-called it.
Presumably that function returns 252 (or some wider value whose low byte is 252). Returning from main leads to clean process exit, making an exit system call with main's return value.
This fall-through tailcall is like if main ended with return next_function(argc, argv);.
Correction (without rewriting the whole answer, sorry)
Since main=194 is the first one that worked, I think you're not actually getting fall-through, probably only C2 ret imm16 and C3 ret are leading to a clean exit. And for c2, it has to be followed by 2 00 bytes, or else it'll break the stack for main's caller.
Or those instructions with a prefix that doesn't do anything, or a harmless one-byte instruction. e.g. 90 nop / c3 ret or 90 nop / c2 00 00 ret 0. Or 91 xchg eax, ecx, etc. could actually give you a different return value, swapping EAX with another register. (x86 dedicates opcodes 90 .. 97 to xchg-with-EAX, because on original 8086 AX was more "special", without instructions like movsx to sign-extend into other registers. And without 2 operand imul.
Other harmless one-byte instructions include 99 cdq and 98 cwde, but not push or pop (because changing RSP would make it not point at the return address). Some one-byte flag set/clear instructions are f9 stc, fd std, but not fb sti (that's privileged, unlike the carry flag and direction flag).
Harmless prefixes are 0x40..4f REX prefixes, 0xf2/f3REP, and0x66and0x67` operand-size and address size. Also any segment-override prefixes might also be harmless.
I just tested main=0xc366 and main=0xc367 and yes they both exit cleanly. GDB decodes 66 c3 as retw (operand-size prefix) and 67 c3 as addr32 ret (address size prefix), but both still pop a 64-bit return address, and don't truncate the stack pointer either. (I took out the -no-pie I'd been using, so RIP was outside the low 32 bits along with RSP).
Note that 00 is the opcode for add [r/m8], r8, so 00 00 decodes as add [rax], al.
To get past those 00 bytes and get to the "nop sled" the linker inserts as padding, you need the opcode (and modrm byte if the opcode uses one) to encode the start of a longer instruction, like 0xb8 mov eax, imm32 which is 5 bytes long, and consumes the next 4 bytes after the 0xb8. In fact there are short-form mov-immediate encodings for every register, so 0xb8 + 0..7 will all get you past the gap. Except for mov esp, imm32, which will lead to a crash once you get to the next function because it stepped on the stack pointer.
One of the early ones is 05, the short-form (no modrm) opcode for add eax, imm32. Most original-8086 ALU instructions have a special AX,imm16 / EAX,imm32 short form, instead of the op r/m32, imm32 or imm8 form that uses a ModRM byte to encode the destination operand. (And the bits of the /r field in ModRM as extra opcode bits.)
See Tips for golfing in x86/x64 machine code for more about AL / EAX / RAX short form encodings, and one byte instructions.
For manually decoding x86 machine code, see Intel's manuals, especially the vol.2 manual which details the instruction encoding formats, and has an opcode table at the end. (See links in the x86 tag wiki). For just an opcode map, see http://ref.x86asm.net/coder64.html.
Use a disassembler or debugger to see what's in your executables
But really, use a disassembler like objdump -drwC -Mintel. Or llvm-objdump. Find main in the output, and look at what you get. (Or use GDB, because labels in the middle of an instruction throw off the disassembler.)
Use objdump -rwC -Mintel -D -j .rodata -j .text testc/test194 to get output like this, disassembling the .text and .rodata sections as code:
testc/test194: file format elf64-x86-64
Disassembly of section .text:
0000000000400540 <__libc_csu_init>:
400540: 41 57 push r15
400542: 49 89 d7 mov r15,rdx
...
4005a4: c3 ret
4005a5: 90 nop
4005a6: 66 2e 0f 1f 84 00 00 00 00 00 nop WORD PTR cs:[rax+rax*1+0x0]
00000000004005b0 <__libc_csu_fini>:
4005b0: c3 ret
Disassembly of section .rodata:
00000000004005c0 <_IO_stdin_used>: ;;;; This is actually data!
4005c0: 01 00 add DWORD PTR [rax],eax
4005c2: 02 00 add al,BYTE PTR [rax]
00000000004005c4 <main>:
4005c4: c2 00 00 ret 0x0
... ; objdump elided the last 0, not me. It literally put ...
(I modified your python script to add the -no-pie gcc option, which is why my disassembly has absolute addresses, instead of just small addresses relative to the start of the file = 0. I wondered if that might put main somewhere it could fall through, but it didn't.)
Notice there's only a small gap between .text and .rodata. They're part of the same ELF segment (in the ELF program headers that the OS's program loader looks at), so they're part of the same mapping, no unmapped pages between them. If we're lucky, the intervening bytes are even filled with 0x90 nop instead of 00. Actually, something filled the gap between __libc_csu_init and __libc_csu_fini with long NOPs. Maybe that was from the assembler if they were in the same source file.
main is of course in .rodata because you declared it in C as a read-only global (static storage), like const int main = 6;. I you used const int main __attribute__((section(".text"))) = 123, you could get main in the normal .text section. On my system, it ends up right before __libc_csu_init.
But labels interrupt disassembly; the disassembler thinks it must have been wrong and restarts decoding from the label. So in GDB on testc/test5 (with set disassembly-flavor intel and layout reg, then using the start command to stop at the start of main), I'll get
|0x40053c <main> add eax,0x41000000 │
│0x400541 <__libc_csu_init+1> push rdi │
│0x400542 <__libc_csu_init+2> mov r15,rdx
But from objdump -drwC -Mintel (disassembing only the .text section is the default for -d, and I used the GNU C attribute to put main there so my program could work the way yours does), I get:
000000000040053c <main>:
40053c: 05 00 00 00 ....
0000000000400540 <__libc_csu_init>:
400540: 41 57 push r15
400542: 49 89 d7 mov r15,rdx
Notice that the .... on the same line as the 05 00 00 00 indicates that decoding didn't get to the end of an instruction.
And since main isn't aligned by 16 here, it's right up against the start of __libc_csu_init. So the add eax, imm32 consumes the REX.W prefix (41) from push r15, making it decode as push rdi if reached by falling through from main instead of by a call to the __libc_csu_init label.
The above output was from Linux. Your OS X system would be different
OS X puts most of the CRT startup code in libc, not statically linked into the executable with main.
Or maybe there isn't anything for your main to fall through into
If there was, main=5 would have worked, but you say the first non-crashing result was with main=194, which is an actual ret.
If nothing before c3 ret or c2 00 00 ret 0 returned, then probably there's nothing to fall into after main, or the gap isn't padded with repeated 90 nop to form a "nop sled" that will execute ok if decoding starts anywhere in the middle of it. (e.g. after an earlier instruction consumes the trailing 0 bytes at the end of the dword int main, and some of the padding bytes.)
I understand that a segfault is invalid access to valid memory and a bus error is access to invalid memory
No, that simplified description is backwards. Usually you get a segfault for trying to access an unmapped page, on all Unixes. But you get a bus error for some kinds of invalid access (even on valid addresses).
Solaris on SPARC gives you a bus error for misaligned word loads/stores to valid memory.
On x86-64 Linux, you only get SIGBUS for really weird stuff. See Debugging SIGBUS on x86 Linux. Non-canonical stack pointer leading to a #SS exception, reading past the end of a mmaped file that was truncated. Also if you enable x86 alignment checking (AC flag), but nobody does that because library funcs like memcpy use unaligned loads/stores, and compiler code-gen assumes that unaligned integer loads/stores are safe.
IDK what hardware exceptions *BSD maps to SIGBUS, but I'd assume that regular out-of-bounds access, like NULL-pointer dereference, would SIGSEGV. That's pretty standard.
#MichaelPetch says in comments that on OS X
#PF (page fault hardware exception) from code-fetch cases the kernel to deliver SIGBUS
#PF from a data load/store to an unmapped page results in SIGSEGV.
#PF from a store to a read-only page results in SIGBUS. (And this is what's happening after 02 00 add al, [rax], in the 00 00 add [rax], al that forms the 2nd byte of main. The rest of this answer doesn't take this into account.)
(Of course this is after checking if the page-fault was due a difference between the hardware page table and the logical process memory map, e.g. from lazy mapping, copy-on-write, or pages paged out to disk.)
So if your int main is landing at the very end of an unmapped page, 05 add eax,imm32 would read one extra byte past the end of the dword holding int main (.long 5 in GAS syntax asm). That would go into the next page and SIGBUS. (Your last comment indicates it does SIGBUS.)
A theory for what's going on with the first few values:
You report:
a bus error for main = 02 00 add al, [rax] / `00 00 add [rax], al
but a segfault for main = 03 00 add eax, [rax] / 00 00 add [rax], al.
We know the low byte of RAX is 252, so if RAX holds a valid pointer value, it's 4-byte aligned. So if loading a byte from [rax] works, so does loading a dword.
So probably the memory-source add is succeeding, and modifying AL, the low byte of RAX (byte operand size) probably still leaving RAX a valid pointer.** Then if the rest of the page containing main is filled with 00 00 add [rax], al instructions (or just the one inside main itself), those will succeed (without further modifying RAX) until execution falls off into an unmapped page, as long as RAX is still a valid pointer after running whatever main decoded to.
Actually, the memory-destination add itself faults and raises SIGBUS.
03 00 add eax, [rax] writes EAX, and thus truncates RAX to 32-bit. (writing a 32-bit register implicitly zero-extends into the full 64-bit register, unlike writing low 8 or 16 partial registers.) This definitely gives you an invalid pointer, because OS X maps static code/data outside the low 32 bits of virtual address space.
So the following 00 00 add [rax], al will definitely fault from trying to write an out-of-bounds address, causing a #PF that raises SIGSEGV.
There's probably just the one 00 00 from the last two bytes of main before the end of a page. Otherwise 05 add eax, imm32 would segfault from truncating RAX and then running 00 00 add [rax], al. For it to SIGBUS, it must code-fetch into an unmapped page without decoding any memory-access instructions after that.
There are certainly other plausible explanations for what you're seeing, but I think this explains all your observations so far; without more data we can't disprove it. Obviously the easiest thing would be to fire up GDB or whatever other debugger and just start / si and watch what happens.

Hex file and disassembly discrepancy

I have parsed hex files for the purpose of bootloading before. This is my first time with a hex file generated using Microchip's XC32 tool chain. Right away I noticed what appears to be a discrepancy between the hex file and the disassembly.
The first 3 lines of the hex file:
:020000040000fa
:020000041d00dd
:10000000030000100000000040f3060000000000a4
From the listing file:
9d000000 <_reset>:
9d000000: 10000003 b 9d000010 <__reset_switch_isa>
9d000004: 00000000 nop
9d000008 <__reset_micromips_isa>:
9d000008: f340 0006 jalx 9d000018 <_startup>
9d00000c: 0000 0000 nop
Notice that address 9d000008 looks like it should contain 0x06 in the listing file. However, the hex file seems to indicate 0x40 at this location. The following 3 bytes are also not in the expected order.
:10 0000 00 03 00 00 10 00 00 00 00 40 f3 06 00 00 00 00 00 a4
When I look though the file other records are as expected, but the bytes pertaining to this jalx instruction word seem to be out of order. Can someone set me straight?
Thanks!
UPDATE:
Another perplexing data point. If I flash the hex file into the part using the debugger (not using my bootloader). Then if I view the execution memory and disassembly listing, I see the following:
Address Instruction Disassembly
1D00_0000 10000003 BEQ ZERO, ZERO, 0x1D000010
1D00_0004 00000000 NOP
1D00_0008 0006F340 SLL S8, A2, 13
1D00_000C 00000000 NOP
When the IDE reinterprets the code that it programmed in, it now shows a SLL instruction not a JALX. This is compiler generated startup code so I cannot be sure what it should be. The byte order matches the hex file not the listing file, so the Microchip tools interpret the hex file as I would but this does not match the listing file.
I posted this question on the microchip.com forum and a couple users there provided the answer.
Basically the JALX instruction in the listing file excerpt is formatted in microMIPS not MIPS32. So there is not actually a discrepancy between the listing file and the hex file. The hex file is interpreted with each byte written into ascending address locations as I was attempting to do. However, viewing the disassembly as I did in the update does no interpret the instructions as microMIPS, so the disassembly for that instruction is incorrect when viewed through the IDE. When the JALX is executed, a flag in the CPU informs the processor to treat this instruction as mircoMIPS.
For more information, see the excellent responses I received at:
http://www.microchip.com/forums/FindPost/986740
It looks like the listing is using Little Endian for those 16-bit values. If that were meant to be a 32-bit value, the 0x06 would come first.
As long as that's the case, there's not really a problem.

How to use int3( VEH or SEH )

Know I want to replace function prologue with jmp to jump to my allocate zone(VirtualAllocateEx). But function prologue just have 3 bytes, and jmp have 5 bytes.
like this:
55 `push ebp`
8B EC `mov ebp, esp`
833D C4354200 02 `cmp dword ptr ds:[4235C4],2`
E9 AD00000000 `jmp` 00140000 // replace above three instructions
If I want to use jmp to cover function prologue, the third instruction after function prologue must be covered.
So know I want to use int3 to replace function prologue to to jump to my allocate zone or any address, how can I do it?
I try to use VEH or SEH to do so, but I can't figure out how to make it.
You need to write the original code (the one you quoted) on another memory location (just allocate something).
Write it while saving some space for the additional OpCodes (your custom new code).
It doesn't have to fit exactly as you're allowed to fill the unused bytes with NOP (0x90 if I'm not mistaken).
Now, jump to this code from the original code.
I've been doing this stuff when I was making game trainers years ago.. Works very well.
On thing to note: Your reWritten code should, at the end, jump back to the original place to continue the code flow.
Let me know if it's unclear.

What are segfault rip/rsp numbers and how to use them

When my linux application crashes, it produces a line in the logs something like:
segfault at 0000000 rip 00003f32a823 rsp 000123ade323 error 4
What are those rip and rsp addresses? How do I use them to pinpoint the problem? Do they correspond to something in the objdump or readelf outputs? Are they useful if my program gets its symbols stripped out (to a separate file, which can be used using gdb)?
Well the rip pointer tells you the instruction that caused the crash. You need to look it up in a map file.
In the map file you will have a list of functions and their starting address. When you load the application it is loaded to a base address. The rip pointer - the base address gives you the map file address. If you then search through the map file for a function that starts at an address slightly lower than your rip pointer and is followed, in the list, by a function with a higher address you have located the function that crashed.
From there you need to try and identify what went wrong in your code. Its not much fun but it, at least, gives you a starting point.
Edit: The "segfault at" bit is telling you, i'd wager, that you have dereferenced a NULL pointer. The rsp is the current stack pointer. Alas its probably not all that useful. With a memory dump you "may" be able to figure out more accurately where you'd got to in the function but it can be really hard to work out, exactly, where you are in an optimised build
I got the error, too. When I saw:
probe.out[28503]: segfault at 0000000000000180 rip 00000000004450c0 rsp 00007fff4d508178 error 4
probe.out is an app which using libavformat (ffmpeg). I disassembled it.
objdump -d probe.out
The rip is where the instruction will run:
00000000004450c0 <ff_rtp_queued_packet_time>:
4450c0: 48 8b 97 80 01 00 00 mov 0x180(%rdi),%rdx
44d25d: e8 5e 7e ff ff callq 4450c0 <ff_rtp_queued_packet_time>
finally, I found the app crashed in the function ff_rtp_queued_packet_time.
PS. sometimes the address doesn't exactly match, but it is almost there.

x86 assember - illegal opcode 0xff /7 under Windows

I'm currently developing an x86 disassembler, and I started disassembling a win32 PE file. Most of the disassembled code looks good, however there are some occurences of the illegal 0xff /7 opcode (/7 means reg=111, 0xff is the opcode group inc/dec/call/callf/jmp/jmpf/push/illegal with operand r/m 16/32). The first guess was, that /7 is the pop instruction, but it is encoded with 0x8f /0. I've checked this against the official Intel Architecture Software Developer’s Manual Volume 2: Instruction Set Reference - so I'm not just missleaded.
Example disassembly: (S0000O0040683a is a lable being jumped to by another instruction)
S0000O0040683a: inc edi ; 0000:0040683a ff c7
test dword ptr [eax+0xff],edi ; 0000:0040683c 85 78 ff
0xff/7 edi ; 0000:0040683f ff ff
BTW: gdb disassembles this equally (except the bug 0xff not yielding -1 in my disassembly):
(gdb) disassemble 0x0040683a 0x00406840
Dump of assembler code from 0x40683a to 0x406840:
0x0040683a: inc %edi
0x0040683c: test %edi,0xffffffff(%eax)
0x0040683f: (bad)
End of assembler dump.
So the question is: Is there any default handler in the illegal opcode exception handler of Windows, which implements any functionality in this illegal opcode, and if yes: What happends there?
Regards, Bodo
After many many additional hours getting my disassembler to produce the output in the exact same syntax than gdb does, I could diff over the two versions. This revealed a rather awkward bug in my disassember: I forgot to take into account, that the 0x0f 0x8x jump instruction have a TWO byte opcode (plus the rel16/32 operand). So each 0x0f 0x8x jump target was off by one leading to code which is not reachable in reality. After fixing this bug, no 0xff/7 opcodes are disassembled any longer.
Thanks go to everyone answering to my question (and commenting that answers as well) and thus at least trying to help me.
Visual Studio disassembles this to the following:
00417000 FF C7 inc edi
00417002 85 78 FF test dword ptr [eax-1],edi
00417005 ?? db ffh
00417006 FF 00 inc dword ptr [eax]
Obviously, a general protection fault happens at 00417002 because eax does not point to anything meaningful, but even if I nop it out (90 90 90) it throws an illegal opcode exception at 00417005 (it does not get handled by the kernel). I'm pretty sure that this is some sort of data and not executable code.
To answer your question, Windows will close the application with the exception code 0xC000001D STATUS_ILLEGAL_INSTRUCTION. The dialog will match the dialog used for any other application crashes, whether it offers a debugger or to send an error report.
Regarding the provided code, it would appear to have either been assembled incorrectly (encoding a greater than 8-bit displacement) or is actually data (as suggested by others already).
It looks like 0xFFFFFFFF has been inserted instead of 0xFF for the test instruction, probably in error?
85 = test r/m32, and 78 is the byte for parameters [eax+disp8], edi, with the disp8 to follow which should just be 0xFF (-1) but as a 32-bit signed integer this is 0xFFFFFFFF.
So I am assuming that you have 85 78 FF FF FF FF where it should be 85 B8 FF FF FF FF for a 32-bit displacement or 85 78 FF for the 8-bit displacement? If this is the case the next byte in the code should be 0xFF...
Of course, as suggested already, this could just be data, and don't forget that data can be stored in PE files and there is no strong guarantee of any particular structure. You can actually insert code or user defined data into some of the MZ or PE header fields if you are agressively optimising to decrease the .exe size.
EDIT: as per the comments below I'd also recommend using an executable where you already know exactly what the expected disassembled code should be.

Resources