Title: Rootkits and invisible software. Creating and revealing.
Copyright © by Hacking School – CSH Press. All Rights Reserved.
All rights reserved. This publication is protected by copyright. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without the prior consent of the publisher.
Company or product names mentioned herein are the trademarks or registered trademarks of their respective owners.
The author and the publisher have taken care to ensure the information in this publication is reliable and complete, but cannot assume responsibility for its use and for any related potential breach of patents or copyright. The author and the publisher cannot assume responsibility for any consequences or damage in connection with the use of the information in this publication.
This book and the software fragments included present techniques thanks to which both IT environment can be protected by its user as well as other systems can be attacked. The information serves general information purposes and it may be subject to change at any time.
Would like to draw your attention to the fact that this handbook, live training movies and software included can be used only to protect your IT environment. Conducting an attack on other IT system without the permission of its respective owner is penalized by the federal Computer Fraud and Abuse Act. If you live outside the United States, please refer to your local law.
“(a) Whoever— (1) having knowingly accessed a computer without authorization or exceeding authorized access, and by means of such conduct having obtained information that has been determined by the United States Government pursuant to an Executive order or statute to require protection against unauthorized disclosure for reasons of national defense or foreign relations, or any restricted data, as defined in paragraph y. of section 11 of the Atomic Energy Act of 1954, with reason to believe that such information so obtained could be used to the injury of the United States, or to the advantage of any foreign nation willfully communicates, delivers, transmits, or causes to be communicated, delivered, or transmitted, or attempts to communicate, deliver, transmit or cause to be communicated, delivered, or transmitted the same to any person not entitled to receive it, or willfully retains the same and fails to deliver it to the officer or employee of the United States entitled to receive it; (2) intentionally accesses a computer without authorization or exceeds authorized access, and thereby obtains— (A) information contained in a financial record of a financial institution, or of a card issuer as defined in section 1602 (n) of title 15, or contained in a file of a consumer reporting agency on a consumer, as such terms are defined in the Fair Credit Reporting Act (15 U.S.C. 1681 et seq.); (B) information from any department or agency of the United States; or (C) information from any protected computer; (3) intentionally, without authorization to access any nonpublic computer of a department or agency of the United States, accesses such a computer of that department or agency that is exclusively for the use of the Government of the United States or, in the case of a computer not exclusively for such use, is used by or for the Government of the United States and such conduct affects that use by or for the Government of the United States;
10 LEGAL INFORMATION
(4) knowingly and with intent to defraud, accesses a protected computer without authorization, or exceeds authorized access, and by means of such conduct furthers the intended fraud and obtains anything of value, unless the object of the fraud and the thing obtained consists only of the use of the computer and the value of such use is not more than $5,000 in any 1-year period; (5) (A) knowingly causes the transmission of a program, information, code, or command, and as a result of such conduct, intentionally causes damage without authorization, to a protected computer; (B) intentionally accesses a protected computer without authorization, and as a result of such conduct, recklessly causes damage; or (C) intentionally accesses a protected computer without authorization, and as a result of such conduct, causes damage and loss. (6) knowingly and with intent to defraud traffics (as defined in section 1029) in any password or similar information through which a computer may be accessed without authorization, if— (A) such trafficking affects interstate or foreign commerce; or (B) such computer is used by or for the Government of the United States; (7) with intent to extort from any person any money or other thing of value, transmits in interstate or foreign commerce any communication containing any— (A) threat to cause damage to a protected computer; (B) threat to obtain information from a protected computer without authorization or in excess of authorization or to impair the confidentiality of information obtained from a protected computer without authorization or by exceeding authorized access; or (C) demand or request for money or other thing of value in relation to damage to a protected computer, where such damage was caused to facilitate the extortion; shall be punished as provided in subsection (c) of this section.
(b) Whoever conspires to commit or attempts to commit an offense under subsection (a) of this section shall be punished as provided in subsection (c) of this section.
(c) The punishment for an offense under subsection (a) or (b) of this section is— (1) (A) a fine under this title or imprisonment for not more than ten years, or both, in the case of an offense under subsection (a)(1) of this section which does not occur after a conviction for another offense under this section, or an attempt to commit an offense punishable under this subparagraph; and (B) a fine under this title or imprisonment for not more than twenty years, or both, in the case of an offense under subsection (a)(1) of this section which occurs after a conviction for another offense under this section, or an attempt to commit an offense punishable under this subparagraph; (2) (A) except as provided in subparagraph (B), a fine under this title or imprisonment for not more than one year, or both, in the case of an offense under subsection (a)(2), (a)(3), or (a)(6) of this section which does not occur after a conviction for another offense under this section, or an attempt to commit an offense punishable under this subparagraph; (B) a fine under this title or imprisonment for not more than 5 years, or both, in the case of an offense under subsection (a)(2), or an attempt to commit an offense punishable under this subparagraph, if—
(i) the offense was committed for purposes of commercial advantage or private financial gain; (ii) the offense was committed in furtherance of any criminal or tortious act in violation of the Constitution or laws of the United States or of any State; or (iii) the value of the information obtained exceeds $5,000; and (C) a fine under this title or imprisonment for not more than ten years, or both, in the case of an offense under subsection (a)(2), (a)(3) or (a)(6) of this section which occurs after a conviction for another offense under this section, or an attempt to commit an offense punishable under this subparagraph;
(A) a fine under this title or imprisonment for not more than five years, or both, in the case of an offense under subsection (a)(4) or (a)(7) of this section which does not occur after a conviction for another offense under this section, or an attempt to commit an offense punishable under this subparagraph; and (B) a fine under this title or imprisonment for not more than ten years, or both, in the case of an offense under subsection (a)(4), or (a)(7) of this section which occurs after a conviction for another offense under this section, or an attempt to commit an offense punishable under this subparagraph;
(A) except as provided in subparagraphs (E) and (F), a fine under this title, imprisonment for not more than 5 years, or both, in the case of— (i) an offense under subsection (a)(5)(B), which does not occur after a conviction for another offense under this section, if the offense caused (or, in the case of an attempted offense, would, if completed, have caused)— (I) loss to 1 or more persons during any 1-year period (and, for purposes of an investigation, prosecution, or other proceeding brought by the United States only, loss resulting from a related course of conduct affecting 1 or more other protected computers) aggregating at least $5,000 in value; (II) the modification or impairment, or potential modification or impairment, of the medical examination, diagnosis, treatment, or care of 1 or more individuals; (III) physical injury to any person; (IV) a threat to public health or safety; (V) damage affecting a computer used by or for an entity of the United States Government in furtherance of the administration of justice, national defense, or national security; or (VI) damage affecting 10 or more protected computers during any 1-year period; or (ii) an attempt to commit an offense punishable under this subparagraph; (B) except as provided in subparagraphs (E) and (F), a fine under this title, imprisonment for not more than 10 years, or both, in the case of— (i) an offense under subsection (a)(5)(A), which does not occur after a conviction for another offense under this section, if the offense caused (or, in the case of an attempted offense, would, if completed, have caused) a harm provided in subclauses (I) through (VI) of subparagraph (A)(i); or (ii) an attempt to commit an offense punishable under this subparagraph; (C) except as provided in subparagraphs (E) and (F), a fine under this title, imprisonment for not more than 20 years, or both, in the case of—
12 LEGAL INFORMATION
(i) an offense or an attempt to commit an offense under subparagraphs (A) or (B) of subsection (a)(5) that occurs after a conviction for another offense under this section; or (ii) an attempt to commit an offense punishable under this subparagraph; (D) a fine under this title, imprisonment for not more than 10 years, or both, in the case of— (i) an offense or an attempt to commit an offense under subsection (a)(5)(C) that occurs after a conviction for another offense under this section; or (ii) an attempt to commit an offense punishable under this subparagraph; (E) if the offender attempts to cause or knowingly or recklessly causes serious bodily injury from conduct in violation of subsection (a)(5)(A), a fine under this title, imprisonment for not more than 20 years, or both; (F) if the offender attempts to cause or knowingly or recklessly causes death from conduct in violation of subsection (a)(5)(A), a fine under this title, imprisonment for any term of years or for life, or both; or (G) a fine under this title, imprisonment for not more than 1 year, or both, for— (i) any other offense under subsection (a)(5); or (ii) an attempt to commit an offense punishable under this subparagraph.
(d) (1) The United States Secret Service shall, in addition to any other agency having such authority, have the authority to investigate offenses under this section. (2) The Federal Bureau of Investigation shall have primary authority to investigate offenses under subsection (a)(1) for any cases involving espionage, foreign counterintelligence, information protected against unauthorized disclosure for reasons of national defense or foreign relations, or Restricted Data (as that term is defined in section 11y of the Atomic Energy Act of 1954 (42 U.S.C. 2014 (y)), except for offenses affecting the duties of the United States Secret Service pursuant to section 3056 (a) of this title. (3) Such authority shall be exercised in accordance with an agreement which shall be entered into by the Secretary of the Treasury and the Attorney General.
(e) As used in this section— (1) the term “computer” means an electronic, magnetic, optical, electrochemical, or other high speed data processing device performing logical, arithmetic, or storage functions, and includes any data storage facility or communications facility directly related to or operating in conjunction with such device, but such term does not include an automated typewriter or typesetter, a portable hand held calculator, or other similar device; (2) the term “protected computer” means a computer— (A) exclusively for the use of a financial institution or the United States Government, or, in the case of a computer not exclusively for such use, used by or for a financial institution or the United States Government and the conduct constituting the offense affects that use by or for the financial institution or the Government; or (B) which is used in or affecting interstate or foreign commerce or communication, including a computer located outside the United States that is used in a manner that affects interstate or foreign commerce or communication of the United States; (3) the term “State” includes the District of Columbia, the Commonwealth of Puerto Rico, and any other commonwealth, possession or territory of the United States; (4) the term “financial institution” means— (A) an institution, with deposits insured by the Federal Deposit Insurance Corporation;
(B) the Federal Reserve or a member of the Federal Reserve including any Federal Reserve Bank; (C) a credit union with accounts insured by the National Credit Union Administration; (D) a member of the Federal home loan bank system and any home loan bank; (E) any institution of the Farm Credit System under the Farm Credit Act of 1971; (F) a broker-dealer registered with the Securities and Exchange Commission pursuant to section 15 of the Securities Exchange Act of 1934; (G) the Securities Investor Protection Corporation; (H) a branch or agency of a foreign bank (as such terms are defined in paragraphs (1) and (3) of section 1(b) of the International Banking Act of 1978); and (I) an organization operating under section 25 orsection 25(a) of the Federal Reserve Act; (5) the term “financial record” means information derived from any record held by a financial institution pertaining to a customer’s relationship with the financial institution; (6) the term “exceeds authorized access” means to access a computer with authorization and to use such access to obtain or alter information in the computer that the accesser is not entitled so to obtain or alter; (7) the term “department of the United States” means the legislative or judicial branch of the Government or one of the executive departments enumerated in section 101 of title 5; (8) the term “damage” means any impairment to the integrity or availability of data, a program, a system, or information; (9) the term “government entity” includes the Government of the United States, any State or political subdivision of the United States, any foreign country, and any state, province, municipality, or other political subdivision of a foreign country; (10) the term “conviction” shall include a conviction under the law of any State for a crime punishable by imprisonment for more than 1 year, an element of which is unauthorized access, or exceeding authorized access, to a computer; (11) the term “loss” means any reasonable cost to any victim, including the cost of responding to an offense, conducting a damage assessment, and restoring the data, program, system, or information to its condition prior to the offense, and any revenue lost, cost incurred, or other consequential damages incurred because of interruption of service; and (12) the term “person” means any individual, firm, corporation, educational institution, financial institution, governmental entity, or legal or other entity.
(f) This section does not prohibit any lawfully authorized investigative, protective, or intelligence activity of a law enforcement agency of the United States, a State, or a political subdivision of a State, or of an intelligence agency of the United States.
(g) Any person who suffers damage or loss by reason of a violation of this section may maintain a civil action against the violator to obtain compensatory damages and injunctive relief or other equitable relief. A civil action for a violation of this section may be brought only if the conduct involves 1 of the factors set forth in subclauses(I), (II), (III), (IV), or (V) of subsection (c)(4)(A)(i). Damages for a violation involving only conduct described in subsection (c)(4)(A)(i)(I) are limited to economic damages. No action may be brought under this subsection unless such action is begun within 2 years of the date of the act complained of or the date of the discovery of the damage. No action may be brought under this subsection for the negligent design or manufacture of computer hardware, computer software, or firmware.
14 LEGAL INFORMATION
(h) The Attorney General and the Secretary of the Treasury shall report to the Congress annually, during the first 3 years following the date of the enactment of this subsection, concerning investigations and prosecutions under subsection (a)(5).
(i) (1) The court, in imposing sentence on any person convicted of a violation of this section, or convicted of conspiracy to violate this section, shall order, in addition to any other sentence imposed and irrespective of any provision of State law, that such person forfeit to the United States— (A) such person’s interest in any personal property that was used or intended to be used to commit or to facilitate the commission of such violation; and (B) any property, real or personal, constituting or derived from, any proceeds that such person obtained, directly or indirectly, as a result of such violation. (2) The criminal forfeiture of property under this subsection, any seizure and disposition thereof, and any judicial proceeding in relation thereto, shall be governed by the provisions of section 413 of the Comprehensive Drug Abuse Prevention and Control Act of 1970 (21 U.S.C. 853), except subsection (d) of that section.
(j) For purposes of subsection (i), the following shall be subject to forfeiture to the United States and no property right shall exist in them: (1) Any personal property used or intended to be used to commit or to facilitate the commission of any violation of this section, or a conspiracy to violate this section. (2) Any property, real or personal, which constitutes or is derived from proceeds traceable to any violation of this section, or a conspiracy to violate this section.”
While being an administrator and using the tools described in the handbook in order to protect your own IT environment, or gettin to know the hacking techniques presented, you always have to be sure that your actions are fully legal. The points below should be treated as examples, not as a full and complete list: § If you discover any new problem or lack of security in the tested environment, you have to inform the administrator. § You have to be really careful during the testing, any third person cannot be harmed by your actions. If you accidentally enter any other IT system during your tests, you have to cease them and inform the administrator. § All tests should have a complete documentation: the test, its aim, plan, people taking part in it. § The results of the tests should be kept away from any third person. § Tests conducted for any third person should be carried out only after obtaining a written permission. § Only testing environment should be used to conduct the tests.
15 Additional legal info can be found in the full text of the federal Computer Fraud and Abuse Act. Please note that the information stated herein is valid at the time of publication and it may be subject to change at any time.
Note re: antiviruses
Owing to the nature of this guide, the software included in the training contains implementations of techniques antivirus software commonly sees as unwanted or potentially harmful. Therefore, all alerts reporting malware or unwanted software being detected on the included disc are normal and constitute no risk to the user.
To be able to recreate the experiments in a proper way, it’s recommended you turn off your antivirus or real-time protection module temporarily. You can also allow selected items to run without putting them into quarantine
Intro and environment setup
New self-replicating malicious programs are built daily, and antiviruses daily release updates to protect systems against these attacks. So how can it be that when a virus infects your computer, the antivirus could fail to detect it even for months and months? This training aims to debunk the mistaken belief that good and up-to-date antivirus software can successfully shield you from all threats.
Virus and malware creators are every bit as hardworking as antivirus developers. The former want to discover the inner mechanisms of antiviruses, while the latter are on a constant lookout for how new viruses work. This training shows techniques you can use to write code that is undetectable even for the best antiviruses out there. Additionally, we will also show you how to cloak a program to make it stealthy. When you know the threat, you’ll also be able to train yourself how to detect items that are seemingly impossible to spot.
What is a rootkit?
A rootkit is not a threat itself since none of its functions are harmful for the user. A rootkit is a program or auxiliary module of another program that is intended to hide files, processes, Windows Registry entries, network connections and other items from users. To do this, a rootkit changes program or system library code to make them return false data (e.g., a process list that lacks a particular element). This guide covers rootkits written for the user mode (Ring3). We’ll leave out the kernel mode (Ring0) since newer Windows systems make it virtually impossible to modify the kernel and its structures.
18 MODULE 1. INTRO AND ENVIRONMENT SETUP Rootkit structure
Contrary to what you may think, the structure of a typical rootkit is very basic. A rootkit consists of an application that modifies the code of other processes and tracks whether new processes appear. It includes a set of system functions to change and a set of codes to replace the original function code excerpts.
Examples of rootkits
Bluepill: implemented by Joanna Rutkowska. This highly advanced rootkit makes use of virtualization. Very difficult to detect as it runs the operating system as a virtual machine controlled by the rootkit (using the AMD Pacifica virtualization technology). FU Rootkit: a kernel mode rootkit based on the DKOM (Direct Kernel Object Manipulation) technique. Can cloak a variety of elements without hooking. Vanquish Rootkit: a user mode rootkit using DLL injection and API hooking.
What you need to know to start
All codes presented in the book are written mostly in C++, a language that is flexible and easy-to-use for low-level functions, and therefore a good match for the task. The compiler we’ll use is Microsoft Visual C++ 2010 Express.
At least a passing knowledge of the assembly language will come in handy at the start as well. But if you don’t know this language, don’t worry: the next module features a short overview of what’s needed to know to write and understand basic programs.
Also highly useful is a knowledge of Windows internals, especially with regard to API routines and system libraries. If you don’t have it either, there’s no need to panic – the book includes critical information where needed.
Compatibility and current code version
The training videos for modules 1 to 9 have been made in the Microsoft Windows 7 32-bit version. Module 10, a summary of the training, contains implementations of all the methods and has been developed for the 64-bit operating system versions.
The methods in this training are universal. The guide’s sample programs have also been tested on the newest (at the time of writing) version of Windows, Microsoft Windows 8.x (32-bit for modules 1 to 9 and 64-bit for module 10). Note that almost all applications compiled for the 32-bit OS version should run in the 64-bit system without any need for adjustments. A few exceptions will require you to make changes to their codes: the how-to can be found in module 10.
A current archive containing sample codes and applications can be downloaded at: http://hackingschool.com/download/rtk_modules.zip. The archive will be brought up to date for all new OS versions released in the future.
“Rootkits: Subverting the Windows Kernel”: Greg Hoglund, James Butler. This resourceful book is exhaustive for kernel mode rootkits, but focused mostly on Windows XP.
“Windows NT/2000 Native API Reference”: Gary Nebbett. Descriptions of many undocumented Windows API services that haven’t changed a lot since the days of Windows NT.
20 MODULE 1. INTRO AND ENVIRONMENT SETUP Practice: video module transcript
Welcome to the first module of the training. We’ll learn how to use the applications used throughout this training. For instance, we’ll be using Microsoft Visual Studio 2010 in its Express version. We’ll also use the Olly Debugger in DeFixed version, which is a slightly modified version of the original Olly Debugger. Another tool which can come in handy is PEview. PEview is a program which shows us the headers of executable files and where we can see all the sections and imports specified in a binary file. We’ll also use Hexplorer, a hexadecimal editor.
Now let’s go on to discuss particular programs. The first application we’ll get acquainted with is Microsoft Visual Studio 2010. The environment can be downloaded from the Microsoft website. It’s one of the best C++ compilers available for the Microsoft Windows platform. The next application is Olly Debugger. Using it, we’ll be able to see the results of the operation of our program as well as check whether everything is performed as planned. The next application, as I’ve already mentioned, is PEview. It will be used to learn about the structure of a PE executable file. Using it, we’ll learn which imports and exports are used by a given application. Of course, it’s only a small part of the features of this program, but it’s precisely the one essential for us.
Another application is Hexplorer. It’s the editor we’ll use to edit binary files. We can use it to, for example, edit the character strings present in a binary file. We’ve briefly discussed the tools. Now let’s create a sample project in Microsoft Visual Studio. We run the compiler. In order to create a new project, we click File, New, and next Project. We’ll create a console application and place it in the Modules directory in subdirectory 1, because it’s the first module of our training. The project will be named TEST. We click Next… and Finish. The project creation is in progress. In the screen we can see all the files which compose our project. We also have a template. We start from changing the mode of compilation of our project to Release. Now let’s configure our project. We click Properties.
Next, we go to Configuration Properties, General and we choose Use MultiByte Character Set so that the strings we use are ANSI by default. Next, we click C/C++, choose Code Generation and click the Multi Threaded /MT option.
Then we hover over the Precompiled header and choose the option “Not using precompiled headers”. Finally, we click OK. After these changes, the project compiles without any problems, we just need to include the windows.h file which has all the WinApi functions declarations. In our program we’ll use one of them. We’ll need stdio headers in order to print the message in the console. We also have to remove _t prefixes. Let’s call a simple MessageBox which will display the message Hello World. The Hello World message should appear in
22 MODULE 1. INTRO AND ENVIRONMENT SETUP an upcoming window. Let’s also print Hello World in the window title and the console.
Let’s now compile the project using the F7 key. At the bottom of the window we can see that the compilation is already in progress. As we can see, everything went OK. Now we can start our program. We can see the console and the MessageBox window. The Hello World text, which we defined in the program, appeared as well.
For a moment, we might have caught a glimpse of the Hello World text in the console, after which the application closes due to the fact that the return instruction was executed. Now let’s have a look at our program in the debugger. It’s located in the directory Modules\1\Test\Release. We simply drag our program to the debugger. In the screen we can see all the instructions used
23 by the application. We can see, for instance, the loaded modules. There are quite a lot of them, but we’ll be mainly interested in libraries, such as kernel32, ntdll or kernelbase.
Let’s return to the code. What we see at the beginning of the code is the program prologue added by the compiler. In case of the Visual Studio compiler, the prologue always looks the same. We can go to the next instruction without entering the call using the F8 key. The next instruction is a jump. We press F7. We’re now in the place we’ve jumped to. What we can see here is a jump to the main function.
24 MODULE 1. INTRO AND ENVIRONMENT SETUP We can go to it by pressing the F4 key. It works as follows: the debugger places a breakpoint, a kind of trap for this instruction, and subsequently starts the program. We press F4 again and we are at the place the instruction is called. We press F7 to step inside this call. Here we get the code we’ve just created. We can find here the call of functions MessageBox and printf. We can also see the parameters entered in the code, but they are in the reverse order to the one declared in C++.
We press F8 to go to the next instruction. We can see that a new value appeared on the stack. It’s 0. The next instruction is PUSH, that is putting a number on the stack. This number is an address of the Hello string. We press F8 and see that the value 00B099B0 appeared on the stack. The Hello string is under this address and we see it in the preview. The next instruction is push Hello World. As we can see, it should be the address B899B000. If we look here, we’ll see that the Hello World string begins exactly at that location.
We press F8 and we see 00B099B8 on the stack. The values in the code and on the stack are different because encoding the message takes place in a Little endian bit order. It’s an encoding method where the most significant bit is stored at the end, with less significant bits at the beginning. Here we can see that B8 is at the beginning, even though it’s last on the stack.
When returning to our string, we can see that the 00B099B8 address indicates the Hello World string. We press F8 and we can see that the parameters on the stack, when looking from the top, are saved in the same order as in our C++ code. We press F8, so as not to step inside the function responsible for displaying the MessageBox. The MessageBox appeared. We press OK.
The next function we called was the printf function. As we can see, the Hello World message is placed on the stack, and right after it goes the format string. That means a string, and then Enter. We press F8. The difference between calling printf and MessageBox is that the MessageBox is a function of type STDcall and what we’ve put on the stack as parameters was removed from the stack automatically by the MessageBox function. Printf is a function of Pascal type; it’s characterised by the fact that if we put something on a stack, we have to remove it on our own. That’s what the ADD ESP,8 instruction is for.
ESP is a register which indicates the top of the stack, that is the value which will be removed from it first. If we add 8 to it, ESP will indicate 0018FB4C, that’s the address which was a stack top before we called the printf function. Now the return address is present on the stack. We could, for instance, change the return address, but we won’t do that because that would cause an incorrect closing of the program. We will see how to do so, just in case.
We click Modify and enter any value, for instance 28, and at this moment the program would jump to the address present on the stack when a RET instruction is executed. We’ll change it back to the previous value, so that the program doesn’t crash. Another instruction which will be performed by the
26 MODULE 1. INTRO AND ENVIRONMENT SETUP program is XOR EAX, EAX. We want the EAX to be set to 0 because XOR-ing two identical values always gives 0 as a result. We can see that in accordance with our assumptions, a 0 appeared in the EAX register.
However, before the RET instruction, we can change the value, for instance to 1. We press F7 to return and we can see that this value is removed from the stack. The value disappeared from the stack and we’re in the place indicated by the last address. Next, the values passed earlier to the main function are removed from the stack, that is the earlier EAX, argv and argc, together 12 bytes. 12 in hexadecimal notation is 0C. Next we see EBP – 20. EBP indicates the 0018FB90 address. Olly marks these fragments with frames. They are stack frames which appear the moment a function is called.
The EAX we’ve modified will be loaded to this address. 90 – 20, equals 70. Under this address we get 1. It’s an exit code from the main function, because the value the function returns is present in the EAX register. Later we can see a comparison and a jump.
We can see that the EAX register is put on the stack. It will be a parameter of the exit function, which will exit the program with code 1 because that’s the value we set before exiting the main function.
Now the exit from the program takes place. Let’s click the Play button. The program finished its execution and we get the message “Process terminated, exit code 1”. As we can see, the program exit code equalled 1. If we hadn’t modified anything in our code, the output code would equal 0. Now we’ll look at our code in PEview. As we’ve said before, this program can be used to preview application headers. The program consists of a standard DOS header, which tells us virtually nothing, but offers backward compatibility. From it, we only need an offset, which is a pointer to the next header. We can see that this offset value is E0 and the address indicates Image NT header.
28 MODULE 1. INTRO AND ENVIRONMENT SETUP
Before it, there is also a DOS stub, a code fragment which would run if we ran our program under DOS. Similarly to DOS header, it has to ensure a backward compatibility with 16-bit systems. We can see that NT header is located here. We’ll extend its structure. We see that it consists of a signature, based on which we can determine whether it’s a correct PE file. This signature is simply a PE text.
The next structure in the NT header is Image File header. Its fields include inter alia Machine, which determines the type of processor the application is for. Another value we’re interested in is Number of sections. It specifies the number of sections in the file. Here we’ve got 5 of them. In a moment we’ll discuss what a section is. The next field is Size of optional header. It’s the size of a subsequent structure in NT header. Then we have a Characteristic field which informs us about the file type. In this case it’s an executable file intended for 32-bit systems. It could just as well be an application for a 64-bit architecture. In such a situation, however, this field would have a slightly different value.
29 Another structure is Image optional header. From the fields we’re particularly interested in, we should mention Address of entry point, that is the address at which our program starts its execution. It’s a default base address which will be modified if a file is relocated. If a file has no relocation, the program will be automatically loaded to this address. Another important field is Size of image. Obviously, the field informs us about the file size. In this structure we’ll also be interested in the Data Directories array, which includes information about, for instance, import array, export array, as well as their sizes.
After the Image NT header there are headers of subsequent sections, one after another. Section is a file part which has its access rights. E.g. the first section is usually the code section. It has executing and reading rights and is also marked as the one containing the code. As we can see, the data section has reading and writing rights. Thanks to that we are able to write or read something from our variables, but not overwrite a code section too easily. Obviously, it can be bypassed and we will do so many times throughout this training, but we’ll talk about it later.
In each section we’re interested in the Virtual Size value, that is the size in the memory, RVA address, that is the location in the memory in relation to the base address, the size of the data in the file and the location within the file. The first section is the code section, the second section includes imports, the third one is the data section, the fourth one, in our case, is a section for storing resources, the fifth section includes relocations. As we can see, in this case the division is pretty logical and depends on the data we store in particular sections. In the first section we can just see the code. We can view it in a hexadecimal or a text form (also called ASCII).
30 MODULE 1. INTRO AND ENVIRONMENT SETUP
Let’s look into the rdata section, which is an import section. It includes an import array, which in turn has addresses of all the functions used in the program. We can see that the functions are pretty numerous, even though in our code we’ve only used functions MessageBox and printf. All the remaining functions are used by the program prologue and are automatically added during the compilation. We’ll talk more about the import section in one of the next modules, where we’ll insert the so-called hooks directly into the import section.
In the data section we can see that there are many zeroes, because many variables in our program are set to 0 as a default. Currently, there is only one resource in the resource section – manifest – automatically added by the compiler. There is also the relocation section. It’s used if the program has to be loaded under the base address other than the default, which is present in the Image Optional Header. Relocations are simply addresses of all the places in the code which must be appropriately modified.
That’s basically everything the PEview program offers. Now, we’ll view our application using the Hexplorer program. We see the preview of our program. The editor enables us to edit each byte. If we changed a single letter in the PE string, to T for instance, the program wouldn’t start due to an incorrect header of executable file. It would halt before executing the first code line. We can see it for ourselves. We click File, Save as and save the new program as test2. We have a modified application. We start it and we can see that the program simply closed because the header was incorrect. If we change the header back
31 to PE and save it, the program will start correctly. Even though it’s just a short string which doesn’t bring anything new to the program, we can’t modify it.
Using Hexplorer we can also browse all strings or search the contents for specific character strings. We click Find. In the program we’ve used for instance a Hello string. Let’s step into it. As we can see, the program localized it. We can modify it, for instance change it to Bye. For this purpose, we have to add 2 zeroes at the end. They have to be binary zeroes.
We save the modified version in the test2 file and launch it. As we can see, the window title was changed successfully. We press OK. Another feature offered by Hexplorer is casting other binary data to headers. Let’s choose Structures and PE header, because we know it’s a PE header. Now we see all the fields in this structure.
This way, we’ve reached the end of the software presentation. We’ve managed to discuss the basics which will come in handy when working with our training. Of course, during the subsequent modules we’ll get to know a range of other applications. I strongly invite you to the next module, where we will learn how to create our own shellcode. See you there.