Thursday, November 16, 2017

Creating Simple x64 Shellcode



Save this as shell.asm

global _start

_start:
    jmp short        shell_call    ; jump to call

shellcode:
    pop        rsi        ; Store address of "/bin/sh" in ESI
    xor        rax, rax    ; Zero
    mov byte    [rsi + 7],al    ; Null byte
    mov qword    [rsi + 8],rsi    ;
    mov qword    [rsi + 16],rax    ; Null pointer
    lea        rdi, [rsi]    ; Copy sh string into rdi
    lea        rsi, [rax]    ; Third execve (Null)
    lea        rdx, [eax]     ; Second execve arg (Null)
    xor        al, 0x3b    ; x64 execve syscall
    syscall

shell_call:
    call    shellcode    ; call shellcode and push db onto stack
    db    "/bin/sh"

Assemble the asm file with nasm:
nasm -f elf64 shell.asm -o shell.o

You can view the assembly code by dumping the object file with objdump:
objdump -D shell.o


You can test the functionality of the shellcode by linking the file into an executable.  Due to the way the ASM code is written,  I specified -N to make the .text section read/write:

ld -N -o shell shell.o



Monday, November 13, 2017

Malware Analysis: Re-writing a File Header (Magic Bytes)

Here are a couple of examples of how to re-write a file header.  Note: these are actual JPG's so the JFIF portion of the header will still be intact.  The point is the re-write of the first two bytes of the file.

Say, if you run into a situation where malware is downloaded as one file type, but subsequently rewritten on the target infection point for the sake of bypassing defense mechanisms.

In the first example, we use xxd to examine the first two bytes of a file.  In this case, the file is presented as a .JPG, but suppose it's actually an executable.  In order to analyze the file, we overwrite the header from its current state of ff d8 to 4d 5a.


Here, we've piped the 4d 5a bytes into dd, overwriting the first two bytes of the already-existing an.jpg file, specifying a byte size of 1 and a count of 2.  We can verify the over-write worked by re-running the xxd command to look at the first two bytes.

We can also use Python's print functionality:


In Powershell, the process is almost as simple.  First, read the file into a byte array with the system.io assembly, then overwrite the 0 and 1 position bytes and write the array back to disk. Verify with get-content that the ordinals returned are 77 and 90.  :