вторник, 27 декабря 2016 г.

Packing and Unpacking Executable files and protection


http://wormholetravel.net/reverse.html
The last time we wrote a program that consisted of two files. Now we make the Reverse Engineering of multifile programs, try to pack them and unpack and see the code in IDA Pro and Ollydbg. The packing of executable files helps to protect them against reverse.
What is the packing of program.
Executable compression is any means of compressing an executable file and combining the compressed data with decompression code into a single executable. When this compressed executable is executed, the decompression code recreates the original code from the compressed code before executing it. In most cases this happens transparently so the compressed executable can be used in exactly the same way as the original. Executable compressors are often referred to as "runtime packers", "software packers", "software protectors" (or even "polymorphic packers" and "obfuscating tools"). A compressed executable can be considered a self-extracting archive, where compressed data is packaged along with the relevant decompression code in an executable file. Some compressed executables can be decompressed to reconstruct the original program file without being directly executed.

Most compressed executables decompress the original code in memory and most require slightly more memory to run (because they need to store the decompressor code, the compressed data and the decompressed code). Moreover, some compressed executables have additional requirements, such as those that write the decompressed executable to the file system before executing it.

So we have a program. hotel.exe


The code in C.
/* usehotel.c --the program allow to make order in hotel*/
/*compile together hotel.c*/
#include <windows.h>
#include <commctrl.h>
#include <stdio.h>
#include "resource.h"         /*defines constants declares functions*/
int main(void)
{
                int nights;
                double hotel_rate;
                int code;
                while ((code = menu()) != QUITE)
    {
                               switch (code)
                               {
                                               case 1 : hotel_rate = HOTEL1;
                                               break;
                                               case 2 : hotel_rate = HOTEL2;
                                               break;
                                               case 3 : hotel_rate = HOTEL3;
                                               break;
                                               case 4 : hotel_rate = HOTEL4;
                                               break;
                                               default: hotel_rate = 0.0;
                                               printf("Error! \n");
                                               break;
                               }
                                nights = getnights();
                                showprice(hotel_rate, nights);
                               }

                printf("Thank you for using our resourse and have good luck. \n");
                return 0;
                }
=====================================================================
/*hotel.c --- the functions to manage the hotel programm   "resource.h"           */
#include <stdio.h>
#define QUITE 5
#define HOTEL1 180.00
#define HOTEL2 225.00
#define HOTEL3 225.00
#define HOTEL4 355.00
#define DISCOUNT 0.95
#define STARS "********************************************"
int menu (void)
{
                int code, status;
                printf("\n%s%s\n", STARS, STARS);
                printf("Enter the digit dealing with chosen hotel: \n");
                printf("1) Fairfield Arms                                                  2) Hotel Olympic \n");
                printf("3) Chertworthy Plaza                                           4) The Stockton \n");
                printf("5) exit\n");
                printf("\n%s%s\n", STARS, STARS);
                while ((status = scanf("%d", &code)) != 1 || (code < 1 || code > 5))
                {
                               if (status != 1)
                                               scanf("%*s");                                      //noninteger input exclusion
                               printf("Enter the digit from 1 till 5. \n");
                }
                return code;
}
int getnights(void)                              //declare the function which does not accept anythng and returns
{                                                             //variable data integer getnights
                int nights;
                printf("How many nights do you want to book the room? ");
                while (scanf("%d", &nights) != 1)
                {
                               scanf("%*s");                                      //noninteger input exclusion
                               printf("Enter the digit as 2.  \n");
                }
                return nights;
}
void showprice(double rate, int nights)       //decraler the function which doesnt return anything, but accept
                                                                             //arguments double rate, int nights

{
                int n;
                double total = 0.0;
                double factor = 1.0;
for (n = 1; n <= nights; n++, factor *= DISCOUNT)
                               total += rate * factor;
                printf("The total summ is $%0.2f. \n", total);
}

Now we use LordPE to see the executable file inside.
Now we Open the Edit SectionHeaders the make the file writable or not.


Next, we pack executable file using upx307w program. Packing executable code use to protect against unauthorized copying and disassembling. Here we see the work of this program.

Accordingly, if we open it through PEiD we will see how it is packaged and its other characteristics. We see that the executable file is packed UPX 0.89.6 - 1.02 / 1.05 - 2.09
Recall that is executable.
Executable (executable) module executable (English executable file.) - A file containing the program in the form in which it can be performed by a computer. Before the execution of the program is loaded into memory, and perform some preliminary tasks (setting environment, libraries download).
Typically, in an executable file data (information) stored in any format (e.g., ELF; see list.) And consist of several parts:

headlines;
instructions (code);

Portable Executable (PE, «portable executable") - a format executable files, object code and dynamic libraries used in 32-bit and 64-bit versions of Microsoft Windows operating system. PE format is a data structure that contains all the information necessary PE-loader to display the file in memory. The executable code includes references to bind dynamic link libraries, export and import of the table API functions, data management and data thread local storage (TLS). The family of operating systems Windows NT format is used for PE EXE, DLL, SYS (device driver) and other types of executable files.


The file is not encrypt.
 
Here we see in Section Viewer packed file. The code has become available to us.


Now, if we open the IDA Pro, we can see that the code is the UPX packed, and no information is available to us.


Now our code is protected.
Executable compression is also frequently used to deter reverse engineering or to obfuscate the contents of the executable (for example, to hide the presence of malware from antivirus scanners) by proprietary methods of compression and/or added encryption. Executable compression can be used to prevent direct disassembly, mask string literals and modify signatures. Although this does not eliminate the chance of reverse engineering.

And now, let the inverse problem and unpack program. Tool PEiD determined that the used packer UPX. Ok. Let's try to use FUU program (Faster Universal Unpacker). Download our packed hotel.exe file


Then we unpacked file is saved under a new name hotel1.exe
Save the new file hotel1.exe 


Open our new file hotel1.exe в Ollydbg


We find our code. 
 
We find our code in IDA Pro free. 


Here the code in Assembler. 



As our program was very simple, we can reverse the code and rewrite it and recompile the program.

 


And recompile the code to make the program. 



понедельник, 19 декабря 2016 г.

Multi-file compilation

http://wormholetravel.net/
Multi-file compilation

It happens that the code is spread over two files. Write code that characterizes the storage classes and conduct multi-file compilation as a demonstration.



We will use the open sourse IDE Code:Blocks and create the 32-bit GUI Application



The main.cpp will contain the code of parta.c file
The file partd.c will be contain in Resource section -> resource.h







After the compilation we get the result







суббота, 17 декабря 2016 г.

Storage Classes



FIVE CLASSES OF STORAGE:
- AUTOMATIC
- REGISTER
- STATIC
-> Static with a scope within the block
-> Static with an external binding
-> Static binding to vnutrinney

//VARIABLES IN BLOCK 1
#include <stdio.h>
int main()
{
int x = 30;
printf("x во внешнем блоке; %d по адресу %p \n", x, &x);
{
int x = 77;
printf("x во внутреннем блоке; %d по адресу %p \n", x, &x);
}
printf("x во внешнем блоке; %d по адресу %p \n", x, &x);
while (x++ < 33) //исходная переменная
{
int x = 100; //новая переменная х, скрывающая первую переменную х
x++;
printf("x в цикле while; %d по адресу %p \n", x, &x);
}
printf("x во внешнем блоке; %d по адресу %p \n", x, &x);
return 0;
}
ВЫВОД НА ЭКРАН
x во внешнем блоке; 30 по адресу 0xffffcc0c
x во внутреннем блоке; 77 по адресу 0xffffcc08
x во внешнем блоке; 30 по адресу 0xffffcc0c
x в цикле while; 101 по адресу 0xffffcc04
x в цикле while; 101 по адресу 0xffffcc04
x в цикле while; 101 по адресу 0xffffcc04
x во внешнем блоке; 34 по адресу 0xffffcc0c

//VARIABLES IN BLOCK 2
#include <stdio.h>
int main()
{
int n = 8;
printf(" первоначально n=%d по адресу %p \n", n, &n);
for (int n = 1; n < 3; n++)
printf("   цикл 1: n= %d по адресу %p \n", n, &n);
printf("   После цикла 1: n= %d по адресу %p \n", n, &n);
for (int n = 1; n < 3; n++)

{
printf("  индекс цикла 2 n = %d по адресу %p \n", n, &n);
int n = 6;
printf("  индекс цикла 2: n = %d по адресу %p \n", n, &n);
n++;
}
printf("        После цикла 2 n = %d по адресу %p \n", n, &n);

return 0;
}
ВЫВОД НА ЭКРАН
первоначально n=8 по адресу 0xffffcc0c
   цикл 1: n= 1 по адресу 0xffffcc08
   цикл 1: n= 2 по адресу 0xffffcc08
   После цикла 1: n= 8 по адресу 0xffffcc0c
  индекс цикла 2 n = 1 по адресу 0xffffcc04
  индекс цикла 2: n = 6 по адресу 0xffffcc00
  индекс цикла 2 n = 2 по адресу 0xffffcc04
  индекс цикла 2: n = 6 по адресу 0xffffcc00
        После цикла 2 n = 8 по адресу 0xffffcc0c

пятница, 9 декабря 2016 г.

About the function atoi(), strol()


// Convert the command line argument to a number
// Int argc -> from the argument count - the number of arguments
// Argv -> argument value - value arguments
// Atoi () from alphanumeric to integer - the transformation of alphanumeric values in an integer
// Strtol () is similar to atoi () works with numeral systems, the base having up to 36, in primenyayuschayaya
// Numbers as all the letters of the Latin alphabet to 'z'

Example 1
#include <stdio.h>
#include <string.h> //содержит прототипы строковых функций
int main()
{
    char login[100];
    printf("Enter Login:");
    scanf("%s", login);
    printf("Password: ");
    int i = atoi(login);
    for (i = 0; login[i] != '\0'; i++) //формирует пароль на основе логина
{
        printf("%d", login[i]);
    }
    printf("\n");
    return 0;
}
ВЫВОД НА ЭКРАН
Enter Login:cat
Password: 9997116 //десятичное число

Enter Login:businka
Password: 9811711510511010797 //десятичное число

Example 2
#include <stdio.h>
#include <string.h>
int main() 
{
    char login[100];
    printf("Enter Login:");
    scanf("%s", login);
    printf("Password: ");
    int i = strtol(login);
    for (i = 0; login[i] != '\0'; i++) //формирует пароль на основе логина 
{
        printf("%p", login[i]); //%p спецификатор вывода указателя адреса 
    }
    printf("\n");
    return 0;
}
ВЫВОД НА ЭКРАН
Enter Login:cat
Password: 0x630x610x74 //указатель на адрес 

Example 3
#include <stdio.h>
#include <string.h>
{
    char login[100];
    printf("Enter Login:");
    scanf("%s", login);
    printf("Password: ");
    int i = atoi(login);
    for (i = 0; login[i] != '\0'; i++) //формирует пароль на основе логина 
{
        printf("%x", login[i]); //%x спецификатор вывода шестнадцатиричное число 
    }
    printf("\n");
    return 0;
}

ВЫВОД НА ЭКРАН
Enter Login:cat
Password: 636174 //шестандцатиричное число 

Enter Login:Alisa
Password: 416c697361

Enter Login:Businka
Password: 427573696e6b61

Example 3
#include <stdio.h>
#include <string.h>
int main() 
{
    char login[100];
    printf("Enter Login:");
    scanf("%s", login);
    printf("Password: ");
    int i = atoi(login); //strtol() аналогично atoi() работает с системами счисления, имеющими основания вплоть до 36,
    for (i = 0; login[i] != '\0'; i++) //формирует пароль на основе логина 
{
        printf("%o", login[i]); //%о спецификатор вывода восьмиричное число 
    }
    printf("\n");
    return 0;
}

ВЫВОД НА ЭКРАН
Enter Login:Alisa
Password: 101154151163141 //восьмиричное число

/*Данный код на основани логина формирует пароль - кряк. Пароль - это переведенный символ в число*/
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char log[64];
    char pass[64];
    int i;
    int result;
printf("EnterLogin \n");
scanf("%s", log);

printf("EnterPassword \n");
scanf("%d", &pass);

int v3 = atoi(log); //atoi() от alphanumeric to integer - преобразование алфавитно-цифрового значения в целое число 
int v4 = atoi(pass);

if ( v3 == v4 )
{
for (i=0; log[i] !='\0'; i++) //пароль смещенные символы логина
{
if (log[i] != pass[i])
{
printf("%d IncorrectPas_0", v3); //%d спецификатор вывода целых десятичных чисел 
return 1;
}
}
    printf("%d PasswordIsCorr", v3);
result = 0;
}
else 
{
printf("%d IncorrectPassw", v3);
result = 1;
}
getchar();
getchar();
  return result;
}
ВЫВОД НА ЭКРАН
EnterLogin 
Alisa
EnterPassword 
6510810511597
PasswordIsCorr

EnterLogin 
c
EnterPassword 
118
IncorrectPas_0

EnterLogin 
v
EnterPassword 
118
PasswordIsCorr

Example 4
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char num1[80], num2[80];
printf("Enter first number: ");
gets(num1);
printf("Enter second number: ");
gets(num2);
printf("The sum is: %d", atoi(num1)+atoi(num2));
return 0;
}
ВЫВОД НА ЭКРАН
Enter first number: 12
Enter second number: 12
The sum is: 24

Enter first number: 9
Enter second number: 3
The sum is: 12

воскресенье, 4 декабря 2016 г.

Cracks me, writing keygen

http://wormholetravel.net/
In this part we'll start analysis Cracks,where the serial number is variable and is calculated on the basis of the name, which we are introducing.
Let's start with a search for the correct serial number in Ckacks. Open it in OllyDbg.

Make Run.
We are located at the entry point into the program.

See which API-functions are used for the entered serial number

Let's try to establish BP for this function to stop at the place where it will read the name and serial number.


After pressing the OK ourselves on api-functions and parameters are visible in the stack.
The buffer, which stores the entered text, starting with 4001287, look through the DUMP, that there is - right click and FOLLOW IN DUMP on line, which provides information on the buffer.
There's nothing here, because the API-function is not performed, so that perform DEBUG-EXECUTE TILL RETURN, and when the RET is exerted on, press the F7, to return to the program.


We see that in the buffer kept my name, to continue to make the appropriate operations and create the correct key for it. If we want to make the crack, we must examine the algorithm that runs the program for the calculation of the key name, but for now just let the program generate it and try to see where it is compared with the serial number entered by us.

We meet the same API-function for the second time. It uses the new buffer to fit the entered serial number. Let's see it through the dump.

Note the dates of bytes, right click - BREAKPOINT - MEMORY ON ACCESS, and RUN.

We see that there was a stop where the program reads the first byte of the wrong serial number, and moves it to the BL. Press F7.


BL - Base Law
The BL is 39 - the value of the first byte. We needed to catch what the program does with it and, if possible, write down any math program over it commits.
Here is checking out whether it is zero, and if so - it is the end of the line and will exit the loop.

Since zero is not equal to the first byte, the transition does not take place and get to the SUB BL, 30.

After 30 has been subtracted, remaining 9 BL. On the next line, EDI is multiplied by EAX.

These registers are initialized to the following values: at the beginning of the procedure was placed in EAX 0A, EDI and before entering the loop is equated to zero via XOR EDI, EDI instructions.

By pressing the F7, as we know, based on the definition IMUL instructions with two operands, in this case, they will be multiplied by taking into account the sign, and the result stored in the first operand, ie, in EDI.

Thus, EDI is still zero, which became the result of the previous operation. Then there is the addition of EDI with the value in EBX.

As a result, EDI is still 9, but on the next line, the statement is executed INC ESI, which increases the ESI, to then return to the beginning of the loop and read the next byte incorrect registration number.












It is enough to set a breakpoint on the way out of the cycle and press F9 when the stop occurs, we see what is EDI.
If you double-click on EDI.
Meaning EDI - a hexadecimal value in the second field, see it in the decimal number system, and this value corresponds to the serial number entered by me, ie, after exiting the cycle EDI provides serial in hex.
Those. summarizing briefly: If you type the word 98989898, it will be transformed into a decimal number 98989898 or hexadecimal 5E6774A.
On the next line, EDI xor'itsya 1234.
We see that coming through the RET, we were at the EAX comparison with EBX, ie where there is a transition, decisive, correct or not the serial number

And we see that compared to the calculated value in the EBX with EAX, which contains 5447.
Since EAX is determined by the program, and EBX - is calculated, it is obvious that, since my serial number is incorrect, then the values ​​of these registers will not be equal.
If EBX would be equal to EAX, the program would have made the right move, so we need to analyze why there registers inequality.
EBX = (hex value of the wrong serial number) XOR 1234.
I need to EBX was equal to EAX, then check for equality will give the desired result
If EAX = EBX
Replace EBX on EAX, ie that they are equal.
EAX = (hex value of a correct serial number) XOR 1234
Under this condition, entered serial number is correct.
Reformulate.
EAX XOR = 1234 (hex value of a correct serial number)
And since there EAX value (5447), we can replace it EAX.
5447 XOR 1234 = (hexadecimal value right seriynika)
If the count result of XOR operation:
4673 = (hexadecimal value right seriynika)
If 4673 - a hexadecimal value, then the corresponding decimal, to be administered will be:
Decimal value -> 18035



After XOR:
0 = 0 0
0 1 = 1
0 1 = 1
1 1 = 0

5678h = 101011001111000
1234h = 1001000110100
5447h = 101010001000111

5447h XOR 1234h = 4673h


4673h = 100011001110011 = 18035


How is the number of a name for comparison:
1) the name of the characters are converted to uppercase
2) the name of all the character codes are added
3) found the number XORitsya with constant 5678h

// KEYGEN TO CRACKS_ME Password variable quantity
// Main () function with the argument of
// Int argc -> from the argument count - the number of arguments
// Argv -> argument value - value arguments
/ * Generally speaking, stdin is used to read from the console (as is known, is the keyboard console + display), and
stdout and stderr - write to the console. In the role of pointers stdin stream file, stdout, and sdterr can be used in any function,
where the type FILE * variable is used. For example, you can write about such a call for input from the console line: fgets (); * /

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#define BSIZE 100

int main(int argc, char *argv[])  //командная строка, int argc -> от argument count - кол-во  аргументов
                                                  //argv -> argument value - значения аргументов
{
   char name[BSIZE];                                                    //инициализация переменных
   int serial;
   int i, x, y;
   int keynumber;

   if (argc == 2) {                                               //int argc -> от argument count - количество аргументов
               strcpy(name, argv[1]);            // strcpy() для копирования из строки временного файла в пост.место
   }
   else if (argc == 1) {
               fprintf(stderr, "Enter a name: ");                                            // stderr - для записи на консоль
                           scanf("%s", name);
   }
   else {
               fprintf(stderr, "Usage: crackme_kg name \n");                                  // stderr - для записи на консоль
                           fprintf(stderr, " crackme \n");
                                      return 1;
   }

   printf("nName: %s \n", name);

               // make a key number
               keynumber = 0;
   for (i = 0; i != strlen(name); i++) {                              //strlen() функция перевода в строчный вид
               if (name[i] < 0x041) {
                           break;
               }
               else if (name[i] < 0x05a) {
                           continue;
               }
               else {
                           name[i] = toupper(name[i]);
                           keynumber += name[i];
               }
   }

   keynumber ^= 0x05678;                                                                   //xor     edi, 5678h     
   serial = keynumber ^ 0x01234;                                                                     //xor     edi, 1234h

   printf("Serial: %d \n", serial);

   getchar();
   getchar();
  
               return 0;
}

ВЫВОД НА ЭКРАН
Enter the name: angelina
name: angelina
Serial: 18035

Enter a name: Busina
nName: Busina

Serial: 17868

//KEYGEN НА CRACKS_ME Пароль величина переменная

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define BSIZE 100

int main (int argc, char *argv[])

{
char name[BSIZE];
char serial[BSIZE];
char key[BSIZE];
char *HardCoded = "HardCoded";
int i, r, c;

if (argc == 2) {
strcpy(name, argv[1]);
}
else if (argc == 1) {
fprintf(stderr, "Enter a name: ");
scanf("%s", name);
}
else {
fprintf(stderr, "Usage: splish name \n");
fprintf(stderr, " splish \n");
return 1;
}

for (i = 0; i != strlen(name); i++)
{
r = name[i] % 10;
r ^= i;
r += 2;
if (r >= 10) {
r -= 10;
}
key[i] = r;
}

for (i = 0; i != strlen(name); i++) {
for (c = 'A'; ; c++) {
if (key[i] == (c%10))
{
serial[i] = c;
break;
}
}
}
serial[i] = '\0';

printf("nHard Corded: %s \n", HardCoded);
printf("Name: %s \n", name);
printf("Serial: %s \n", serial);

return 0;
}
ВЫВОД НА ЭКРАН
Enter a name: angelina
nHard Corded: HardCoded
Name: angelina
Serial: EIIJJHDH

Enter a name: Businka
nHard Corded: HardCoded
Name: Businka

Serial: DDEDBJI