sponsors

Monday, December 29, 2014

Keygenning With Delphi: Useful Delphi Functions and Tips

Hello and welcome to this short tutorial for keygenning in Delphi. A lot of beginners who are trying to learn keygenning often get stuck with questions about how to implement certain things or manipulate strings or characters in certain ways. In this tutorial, I will try to cover many of the things that were confusing to me and give you some tips on how to accomplish some of these tasks in a simple and effective manner.




Question 1: How do I get the numerical value of a character and a character value of a number?

A lot of licensing algorithms like to manipulate the numerical value of each character in a name individually in a mathematical operation. In order to do this in delphi, we can use the ord() function. Ord is short for ordinal. When a character is passed to this function, it will return the numerical value of the character. In this case we can implement myByte:=ord('A'); This sets myByte to 65 or $41 in hex. If you want to loop through an entire string and add all of the characters together we can do this:

var
I: Byte;
math: integer;
name: String;
Begin
name:='George';
math:=0;

For I := 1 to length(name) do
math:=math+ord(name[I]);

End;


In this example, we loop through the entire string and use 'name[I]' to get the character of the name at the current loop value. In Delphi, the first character is always character '1' unlike C++ where the first character is '0';
In order to get a character value of a number, we will use the chr() function. This allows us to pass a byte value to the function and get the character representation of it. If we execute myChar:=chr($41); this will set myChar = 'A'; Here is a code example.

CONST myVals: Array[0..3] of byte=($41,$42,$43,$44);
VAR
myStr: String;
I:byte;
Begin
myStr:=''; //Clears the Strings

for I := 0 to 3 do
myStr:=myStr+chr(myVals[I]); //Loops through myVals and converts the bytes to characters.
End; //In the end, myStr='ABCD'

Question 2: How do I work with hexadecimal values? How do I convert HexToInt? How do I convert an integer to a hex string?

Working with hexadecimal values in delphi is quite simple once you know how to do it. You are able to easily embed hexadecimal values in your code by simply adding a '$' sign before the value. With that said I:=$51; would be a simple way to put a hex numerical value in your code without having to convert it to decimal. If you are working with a hex string and you want to convert it to an integer, it is quite simple. The built-in delphi function strToInt can do it if you tell it that the string is a hex value. If you have the hex string value
of '5A223B4A', to convert it to hex, all you need to do is place a '$' at the beginning and pass it to the strToInt function. The '$' informs the function that this is a hex value. Therefore, the code I:=strToInt('$'+'5A223B4A') will convert the hex string to a numerical/integer value. If you have to do this with multiple values, you can simply create a small function such as this:

function hexToInt(hexStr: string): Integer;
begin
Result:=strToInt('$'; + hexStr);
end;

To convert an integer to a hex string, we need to use the built in intToHex function. This function takes two parameters. The first value is our numerical value or variable while the second is the length format. The length format tells the function what the minimum length you want the string to return. For example, if you wanted the length of the hex value to always be 8 or the equivalent of a 32 bit hex value, we will add a parameter of 8. This means that if the converted value is less than 8 characters, it will pad the value with zeros to get the desired length. However, if the converted value is greater than the length value, it will still output the correct value. That is because the length parameter only sets the minimum length, not the maximum. Therefore, if your code is intToHex($ffffffff, 4), it will output 'FFFFFFFF' where intToHex($ff, 4) will output '00FF'. Note that this function always returns uppercase hex strings.

Question 3: How do I generate a random letter/character from A-Z or a random hex value?

To generate a random letter or character between A-Z or a-z, we can do this numerically using the random function without needing to embed all 26 characters as a string. The characters A-Z have the numerical values of $41 to $5A while a-z have the numerical values of $61 to $7A. To generate a random uppercase character, we can do this:

VAR
myChar, myHexChar: Char;

Begin
myChar:= chr(byte(random(26)+$41)); //This generates a random Uppercase letter.
myChar:= chr(byte(random(26)+$61)); //This generates a random Lowercase letter.


For a random hex character, we can simply do this:

myHexChar:= intToHex(random($10), 1);//Creates a single hex character from '0-F'.
End;

Question 4: How do I work with Unicode String bytes?

Working with each each individual byte of a unicode string can be a little tricky in delphi, but can be accomplished with the use of pointers. In this code, we will create a byte pointer to our unicode string and use that pointer to read each byte individually. Since a unicode string represents each character with 2 bytes, we will need to get the length of our string and multiply it by 2 in order to get the length of the bytes. It this example, we will convert a unicode string to hex, byte by byte.

var
i,i2:integer;
pntr:pointer;
str2:string;

strU:unicodeString;
begin


str2:='';

strU:='ABCDEFG';
pntr:=(@strU[1]);
//This creates a pointer to our string.
   
I2:=length(strU)*2;
//doubles the length to equal the length of its bytes.
for I := 1 to I2 do begin
str2:=str2+inttohex(byte(pntr^),2);
//This tells delphi to read the byte at the address of which our pointer points to. In this case, it is the address of our string.

inc(pbyte(pntr),1); // This will increment our pointer address to go to the next value in our string.
end;
//End loop

In the end, str2 will equal '4100420043004400450046004700'.


Question 5: How do I manipulate or obtain the individual bytes in an integer or cardinal?

As you may know, an integer value consists of 4 bytes. Some mathematical operations require us to manipulate an individual byte from this or extract it. Here are a few operations you can use to get the data you need.
If you are looking to access an individual byte other than the first, it is easiest to use the SHR function to move the bytes to the one that you need. The SHR function works at a binary level. A byte consists of 8 binary digits. In order to get to the next byte in the value, you would need to SHR by 8. Here are some examples of how to do so. We will use the hex value AABBCCDD to show you how to obtain each portion as a byte.

VAR
MyHex: Integer;
MyByte: Byte;
Begin
 myHex:=$AABBCCDD;

//let's get the $CC portion.
MyByte:=Byte(myHex SHR 8);// this moves the integer over by 8 binary digits and discards them from the right.
//In memory $AABBCCDD becomes $00AABBCC after the shift.


//let's get the $BB portion.
MyByte:=Byte(myHex SHR 16);// this moves the integer over by 16 binary digits and discards them.
//In memory $AABBCCDD becomes $0000AABB after the shift.
//let's get the $BB portion.
MyByte:=Byte(myHex SHR 24);// this moves the integer over by 24 binary digits and discards them.
//In memory $AABBCCDD becomes $000000AA after the shift.


In this next example, lets pretend we need to convert a value such as AABBCCDD to AA000000. While we could accomplish this with 2 shifts, it is easiest to use the and instruction. By doing $AABBCCDD and $FF000000, the result. The location of the F hex values will be the only portions remaining in the integer where the 0 values will be eliminated. Here are a few examples.

Var
int1,int2:Integer;
Begin
int1:=$AABBCCDD;
Int2:=int1 and $f0f0f0f0; //Int2=$A0B0C0D0
Int2:=int1 and $ff00;       //Int2=$0000CC00
End;

Question 6: How do I convert a float to hexadecimal?

 A very easy way to get the hexadecimal value of a float is to create a pointer to it and read it as a int64 value and use the format command to convert it to hexadecimal. Here is the approach I use:

VAR
flt: double;
I64: int64;
s:string;
Begin
flt:=12.45443563350
I64:=PInt64(@f1)^; //We get the address and read the value it contains as a int64 value.
s:=Format('%X', [I64]);//converts int64 to hex string;


This concludes this short entry on keygenning with delphi. If you have questions you would like to have answered, post them below and I will try to include them in my next tutorial. Until next time, happy reversing.


Saturday, December 20, 2014

Unpacking Jar2Exe 2.1: Extracting The Jar File At All 3 Protection Levels























Welcome to this extensive tutorial for unpacking Jar2Exe. Jar2Exe is a java executable wrapper which works by taking your original java archive, wrapping it into an executable, and executing it through a virtual environment using the jvm.dll provided with each java distribution. It also provides the ability to hide your archive and encrypt the class names making recovery difficult.  The goal of this tutorial is to demonstrate how to recover a jar file at the 3 different protection levels provided by Jar2Exe.

In this tutorial, I will be using the file SimpleApp.jar which is included with launch4j. You can protect it with the same settings to reverse along with me.

Tools Needed:
Resource Hacker
Winhex
Ollydbg 1.10+ MemoryDump 0.9 and  Olly Advanced or StrongOD Plugin(for advanced ctrl+g).
DJ Java Decompiler
7-Zip or Winrar

Jar2Exe Level 1: No Hiding, No Encryption:






















This is the default wrapping level which provides no protection to your java file. As you can see, the Hide class files and Encrypt and hide class files options are left unchecked. This level of protection simply takes your java archive/jar file, concatenates it to the end of the executable, and embeds its java files inside of it. This java archive can be recovered using a hex editor, just like we did with launch4j in the previous tutorial. To begin, we will open sample file called 'SimpleAppNoHide.exe' in winhex. To find the archive, scroll to the bottom of the file. Another option you can try other than scrolling is to search for the ascii string "serial "(with the space). This should take you directly to the archive, but I cannot guarantee that this approach will always be successful.

 Once you are here, the first occurrence of 'PK' labels the start of our archive. We can label this as our beginning of block:










Afterwards, we can scroll to the very last byte in the file and label it as our End of Block:












Once you have done so, right click the selected block and click Edit. In the new pane, go to Copy Block -> Into New File.























Afterwards, we can save it as a jar file. I used the name SimpleAppNoHide.jar:























Once we are finished, the program will run correctly, but to be tidy, we need to delete the extra files that Jar2Exe added to our archive. Let's open the archive in 7-zip or winrar(whichever you fancy).







Once it is opened, you can see that Jar2Exe adds an additional directory called 'com'. While some other java applications may use this directory, Jar2Exe adds an additional subdirectory called regexlab.









After entering the com directory, we see that regexlab is the only subdirectory it contains, meaning that the entire com folder is unused and can simply be deleted from the archive, let's go ahead and delete it:













After confirming the deletion, we can close the archive and run the jar file.





























If you did everything correctly, the application should run without problems and our work is finished.

Jar2Exe Level 2: Hidden Archive:





















With the level 2 protection, Jar2Exe takes our java archive, encrypts it, and adds it as an RCData entry in the resource directory. To find the offset of the encrypted archive, we need to open our executable which I named 'SimpleAppHide.exe' in a resource editor. For this, I prefer resource hacker:














Above, we have located the encrypted data in the "RCData" section of the resource table. In this case, our offset is 46398h. Keep a note of this and open the application in Ollydbg. Once you have it opened, go to the hex dump section and go to the offset above:
















Once you arrive at the offset, right click the byte and add a Hardware Breakpoint On Access -> Byte:





















Now, let's run the program and wait for the break to occur. We should arrive here:









This loop will decrypt our archive byte for byte. Let's toggle a breakpoint on the instruction after the loop. In this example, the instruction is 00401BE3 > CMP DWOR PTR SS:[ESP+18],EBP. Run the program now and let the decryption complete. Once we break here, the register EAX will contain the location where our decrypted jar file is located and ECX contains its size. Using this information, we are ready to dump the file from memory. To do this, I found a very simple plugin called Memory Dump. It allows you to simply specify a memory address and size to dump those bytes to disk. Let's open the plugin:














To begin, check the field which says End Address / Lenght. This will allow us to enter the length value. Set the Start Address to the value in EAX and the lenght(length) equal to the value in ECX. In my case, the address is 296810 and the size is 11EC. Once you have entered these values, we are ready to dump this to disk.





























A limitation of this tool is that you can only save the file with a .dmp extension, but we can easily rename it once we are finished. Simply save it  with the name you fancy. In this case I named it as SimpleApp3Hide.dmp for easy recognition.





After a quick renaming, the file is ready to run.





























Jar2Exe Level 3: Hidden Archive + Encrypted Class Names:


This is the strongest protection offered by Jar2Exe. First, it changes all of the class file names to gibberish. Second, it encrypts and hides the files just like the level 2 protection. While we can recover the archive with a similar method as in Level 2, we need to take an additional step to repair the class names.

To begin, let's open the application "SimpleAppEncrypt.exe" in a resource editor just as before to acquire the offset of the encrypted RCData:
















Our offset in this case is 49398h. Let's note that and open the application in Ollydbg and follow the offset.










Once we arrive at the offset, place a hardware breakpoint on access-> byte just like before.

































Run the program an wait for the breakpoint. We should arrive at the following code:






































This is the new decryption routine. The instruction 0040ACED-> MOV BYTE PTR DS:[ECX],AL will move each decrypted byte to their new memory location.





According to the code, the address of the memory location where our file is decrypted to can be found at the stack pointer [ESP+18].








The value at ESP+1C contains the size of the memory region. This can be verified by checking the decrement value of the loop.







This code verifies that ESP+1C is the value decremented. ESP+1c is moved to EAX, decremented, and then moved back.

At our current location where the hardware breakpoint landed us, the values at ESP +18 and ESP+1C are the ones we need for our dump. Please note them and target a breakpoint on the instruction outside of the loop.







Once you break here, we are ready to make a dump of the file. But first, I would like to show you the encrypted strings in our archive to give you a glimpse of how jar2exe encrypts them:
























As you can see here, the names of our classes and manifest files have been completely obfuscated. As a result, we need to recover these names manually. The way that jar2exe gets the original names for the class is to read them directly from the class file itself. I will show you a simple approach to doing this once we dump the archive.

Now since I am finished digressing, let's dump the file just like before.














In my case, the location of the decrypted file is at 296858 and its length is 1284. We are ready to dump:




















Now that we have saved the file, let's rename change the extension to .jar and prepare to extract the contents.




Please note that due to the encryption employed on the names, the file will not run until we correct the classes. Let's extract the contents to a new folder so we can begin repairing.












Once we have extracted the files, let's open the new directory and see the files.




As we can see here, the file names are complete gibberish. The randomly named directories will typically not contain a file and can be deleted. The rest of the files will be the original class and manifest files. To begin the recovery, I like to first identify which file is the manifest. We can usually assume that the manifest will be the smallest file contained in the archive. The manifest.mf file tells the java runtime which file contains the main() class. Without it, the runtime would not know how to execute the code. Let's find the smallest file and open it in a text editor.















As you can see, we have identified our manifest file. This file should be renamed to 'MANIFEST.MF' and placed in a subdirectory called 'META-INF'. Remember that these names are case sensitive and must be typed in all uppercase.















To continue with the rest of the files, let's add a '.class' extension to each of them and open them in your favorite java decompiler. You can read these names with a hex editor if you fancy, but a decompiler makes it a little cleaner. Let's begin with the largest file which is 4kb. I will open it in DJ Java Decompiler.















As we can see here, we have identified the name of this class file as SimpleApp which according to the manifest, contains our main() procedure. The name of the package this file resides in is 'net.sf.launch4j.example'. The dots between these words represent a subdirectory. That means that this class belongs in a folder hierarchy of net/sf/launch4j/example. Let's rename this to class file to 'SimpleApp.class', create the directory hierarchy listed above, and place this file in it.



Now that we have completed this, we just need to go back and follow the same steps for the rest of the files. Please remember that every name is case sensitive. Once you have recovered each of them and placed them into the correct directory(there is only one directory), it should look like this:









Now that we are done, it is time to recreate the jar file. A jar file is simply a zip archive under a different extension. All we need to do is go back to the directory that contains our two folders named 'net' and 'META-INF' and add them to a zip archive.

















Now, we simply change the extension of the zip archive to jar and it is ready to run.




Now let's see the finished result:





























I hope that you have learned a few things from this tutorial and have walked away with some new knowledge. If something in this tutorial is not clear, please feel free to post a comment and I will try to explain it further. Until next time, happy reversing.

Sunday, December 14, 2014

Unpacking Launch4j 3.5: Extracting The Jar File


Unpacking Launch4j 3.5: Extracting The Jar File:

Welcome to this short tutorial for unpacking Launch4j. Launch4j is a Java executable wrapper for Windows which makes the process of deploying a Java application on windows a little less arduous. It bundles the Java application with all of its command line arguments into a single executable and passes itself directly to the java runtime or "java.exe" upon execution. The goal of this tutorial is to show you how to recover/extract/unpack the original jar file and retrieve the command line arguments from the executable. While most protection detecting utilities do not detect launch4j, it is quite easy to identify this wrapper by using string references to find the string 'Launch4j'.

The application we will be working with is the demo project included with Launch4j called SimpleApp. It is located in the Launch4j installation directory in the folder '%Launch4j%\demo\SimpleApp\'. To begin, we will open our file 'SimpleApp.exe' in LordPE and click the sections button. This window will allow us to determine the Raw Offset and size of the resource section which usually has the name '.rsrc'.   

 As we can see in the picture, the raw offset is '6000h' and its raw size is '1C00h'. The jar file is always located directly after the end of the last section and spans all the way until the end of the file, so '6000h + 1C00h= 7C00h'. This means that 7C00h is the raw offset of the Jar file. Let's open the application up in winhex to verify.


As you can see here, we have reached the beginning of the Jar archive which is indicated by the 'PK' file type identifier. As stated above, the end of the archive will be the last byte in our file. In order to make sure we select everything correctly, we need to mark this offset as the 'beginning of block' through the right click menu.


Once you have done this, we can simply scroll to the last offset and mark it as the 'end of block'. 


This will automatically select all of the bytes in our archive and allow us to extract and save them as another file. To do this, right click the selection and click the 'Edit' button.











From here, another menu will appear. Go to the option 'Copy Block' and in the sub-menu, click 'Into New File'.























Afterwards, a save dialog will appear. In this example, I decided to name the file 'SimpleApp2.jar'.

























After clicking save, let's run our extracted file and see the results.





















As you can see, our extraction was successful and the file runs correctly, so our work is done. 

While this file runs correctly as is, in some cases, the author may pass additional command line arguments to the java runtime. If we do not recover these parameters, some applications may not run correctly.  To do so, we can open the original file in ollydbg and set a breakpoint on the API CreateProcessA. After running the application, we will shortly break here and we can read the arguments off of the stack. Below, we can look at the following example from another target.








In this example, we can can see that application is passing the parameters -Xms256M and -Xmx800M which tells the application the minimum and maximum ram amount to allocate to the process. Without these parameters, the application may not have the ram it requires to perform certain tasks. That is why it is crucial to recover these parameters to insure that the extracted jar will work correctly. 

Another approach to recovering these parameters would be to search for them with a resource editor. While this approach may not be as reliable as the one above, it may be best when working with malicious code.



















In this example, I was able to find the parameters stored in the RC Data directory of the resource table. 

I hope that you were able to walk away with some new knowledge. If there is something that you are not quite able to grasp or understand, please feel free to post your questions or comments below. Until next time, happy reversing.