Decoding a simple crypted binary

37 views
Skip to first unread message

er4z0r

unread,
Apr 24, 2013, 6:40:42 PM4/24/13
to pef...@googlegroups.com
Hi,

I am trying to learn pefile by writing an unpacker/decrypter for a very simple crypter that basically just xors the whole .text section with an integer.

So far the only working code I have is this:

def decrypt_code_old(pe):

    text = locate_section(pe, ".text")

    textaddr = text.VirtualAddress

    #decrypt

    idx = 0

    while idx < text.Misc_VirtualSize:

        d = pe.get_word_at_rva(textaddr+idx)

        pe.set_word_at_rva(textaddr+idx, d ^ 23)

        idx += 1

But this is so terribly slow that I thought there must be another way. 

I have been trying get the whole section data, decode it and the set it back with pe.set_bytes but that always

failed because I could not get the decoded data in the right format for pe.set_bytes to accept it.

How cany I do this more efficient?

Ero Carrera

unread,
Apr 29, 2013, 5:22:57 AM4/29/13
to pef...@googlegroups.com
Hi there,

There are a few things that would speed it up. First you could get the
whole data for the section at once:
section_data = pe.get_data(text.VistualAddress, text.SizeOfRawData)

Then XOR all bytes into a list:
encoded_data_list = [chr(ord(byte)^xor_key) for byte in section_data]
The previous statement is a list comprehension, getting every
character's ordinal value, xor'ing it and making it a char again.

Then turn the data in a string by joining all the characters in the
list, this is much more efficient that going char by char:
encoded_data = "".join(encoded_data_list)

Then write the data at once:
pe.set_bytes_at_rva(text.VistualAddress, encoded_data)

Beware that in you code you are reading word and xor'ing with a byte
value. That will leave a byte of the two in the word untouched.
> --
> You received this message because you are subscribed to the Google Groups
> "pefile" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to pefile+un...@googlegroups.com.
> To post to this group, send email to pef...@googlegroups.com.
> Visit this group at http://groups.google.com/group/pefile?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

er4z0r

unread,
May 1, 2013, 4:41:34 AM5/1/13
to pef...@googlegroups.com
Hi Erro,

What a beautiful piece of code! That is exactly what I wanted to do but could not turn into working code :-)

thanks a lot! 
Reply all
Reply to author
Forward
0 new messages