Virus programming technology-5

Source: Internet
Author: User
Tags high cpu usage

Network shared resources are also organized in a tree. Non-leaf nodes are called containers. You need to search for containers until they reach the leaf node. The leaf node is the root path of the shared resources. Shared resources are generally divided into two types: Shared printing devices and shared folders. For searching shared network files, wnetopenenum and wnetenumresource are used for Recursive enumeration. For the function prototype and parameter meanings, see msdn. Use the following code enumshare. cpp to display the paths of all network drive Shared Folders:
  
# Include
# Include
# Pragma comment (Lib, "MIP. lib ")
  
Int enum_netshare (lpnetresource lpnr );
  
Void _ cdecl main (INT argc, char * argv [])
{
Enum_netshare (0 );
}
  
  
Int enum_netshare (lpnetresource lpnr)
{
Dword r, renum, usage;
Handle henum;
DWORD cbbuffer = 16384;
DWORD centries =-1;
Lpnetresource lpnrlocal; // pointer to the netresource Array Structure
Dword I;
  

R = wnetopenenum (resource_globalnet, // range: All Network Resources
Resourcetype_disk, // type: Only enumerative media can be stored
Resourceusage_all, // Usage Status: All
Lpnr, // null at the first call
& Henum); // network resource handle returned after the request is successful
  
If (R! = No_error ){
Printf ("wnetopenenum error.../N ");
Return false;
}

Lpnrlocal = (lpnetresource) malloc (cbbuffer );
If (lpnrlocal = NULL)
Return false;

Do
{
Zeromemory (lpnrlocal, cbbuffer );
  
Renum = wnetenumresource (henum,
& Centries, // return as many results as possible
Lpnrlocal, // lpnetresource
& Cbbuffer); // buffer size
If (renum = no_error ){
  
For (I = 0; I <centries; I ++ ){

Usage = lpnrlocal [I]. dwusage;

If (Usage & resourceusage_container ){

If (! Enum_netshare (& lpnrlocal [I])
Printf ("errors detected in Enum process.../N ");
} Else {
  
// Here, the virus can be called to traverse all the files in the shared folder.
// Enum_path (lpnrlocal [I]. lpremotename );
Printf ("find % s --> % s/n", lpnrlocal [I]. lplocalname,
Lpnrlocal [I]. lpremotename );
}
}
} Else if (renum! = Error_no_more_items ){
Printf ("wnetenumresource error.../N ");
Break;
}
} While (renum! = Error_no_more_items );
  
Free (void *) lpnrlocal );
  
R = wnetcloseenum (henum );

If (R! = No_error ){
Printf ("wnetcloseenum error.../N ");
Return false;
}
  
Return true;
}

The wnetopenenum 4th parameter is 0 at the beginning of traversal. When a shared container is found to be called recursively, this parameter is the netresource structure pointer of the shared container. From the netresource structure, we can find the lpremotename we are interested in. if the pointer is not 0, it indicates a valid shared container or shared folder.

Typedef struct _ netresource {
DWORD dwscope;
DWORD dwtype;
DWORD dwdisplaytype;
DWORD dwusage;
Lptstr lplocalname;
Lptstr lpremotename;
Lptstr lpcomment;
Lptstr lpprovider;
} Netresource;

After the problem of the starting directory is solved, you can use findfirstfile and findnextfile to traverse all the files and directories under these directories, the Traversal method can use the depth-first or breadth-first search algorithm, which is commonly used. The specific implementation method can be recursive search or non-recursive search. Recursive search requires stack space, which may result in stack space depletion and exceptions. However, this problem rarely occurs in real applications, but not in recursive search, but the code implementation is slightly complicated. In real-world applications, recursive traversal is the most used. When searching, you can specify the first parameter of findfirstfile *. * To search all files, determine whether the dwfileattributes member in the win32_find_data structure is a directory based on the search results. If the Member is a directory, continue to traverse the subdirectory, based on the file name Member in cfilename of win32_find_data, determine whether there is a file suffix to be infected to modify the infection action. The following code recursively searches a directory and all its subdirectories:

Void enum_path (char * cpath ){

Win32_find_data WFD;
Handle HFD;
Char cdir [max_path];
Char subdir [max_path];

Int R;

Getcurrentdirectory (max_path, cdir );
Setcurrentdirectory (cpath );

HFD = findfirstfile ("*. *", & WFD );

If (HFD! = Invalid_handle_value ){
Do {
If (WFD. dwfileattributes & file_attribute_directory ){
If (WFD. cfilename [0]! = '.'){
// Synthesize the complete path name
Sprintf (subdir, "% S // % s", cpath, WFD. cfilename );
// Recursively enumerate subdirectories
Enum_path (subdir );
}
} Else {

Printf ("% S/% s/n", cpath, WFD. cfilename );
// Determine whether to infect the relevant file based on the suffix.
}

} While (r = findnextfile (HFD, & WFD), R! = 0 );
}
Setcurrentdirectory (cdir );
}

In just over 20 lines of C code, file traversal is implemented. The powerful functions of Win32 API not only provide convenience for developers, but also open the door for viruses. The implementation of Assembly is a little more complicated. Interested readers can refer to the enum_path section in elkern. The principle is the same. Due to the length, no compilation code is provided here.
Non-recursive search does not use stacks to store related information, but uses an explicitly allocated linked list or stack structure to store related information. An iterative loop is applied to achieve recursive traversal of the same function, the following is a simple implementation of using the linked list to process the sub-directory list in stack mode:

When using the assembly language, you need to manage the linked list and allocate and release the corresponding structure on your own. Therefore, it is cumbersome and the amount of code is a little large. Therefore, most viruses are searched recursively. It is worth noting that it is time-consuming to search for deep directories. To avoid high CPU usage for most viruses, sleep will be called to sleep after a certain number of files are searched, to avoid detection by sensitive users. The file search and infection module is usually run in a separate thread. After the virus obtains control, it creates the corresponding search and infection thread, and gives the master ready-to-use control to the original program.

* Modify and infect PE files

Now that you have been able to search for all files in disk and network shared files and want to implement parasitic operations, the next step is to infect the searched PE files. An important consideration for infecting PE is the location where the virus code is written to the PE file. Read/write files generally use Win32 API createfile, createfilemapping, mapviewoffile, and other APIs to map files in memory. This avoids the trouble of managing the buffer by yourself and thus is used by many viruses. To read and write files with read-only attributes, the virus first obtains and saves the attributes using getfileattributes before the operation, and then modifies the attributes of the file to writable using setfileattributes, restore the attribute value after infection.
  
Generally, there are several solutions to infect PE files:
  
A) Add a new section. Write the virus code to a new section, and modify the attribute values such as the file size in the section table and file header accordingly. Because a section is added at the end of the PE, it is easy to be noticed by users. In some cases, because the original PE Header does not have enough space to store the section table information of the new section, other data needs to be moved. In view of the above problems, there are not many pe viruses using this method.
B) attach it to the last section. Modify attribute values such as the size and attributes of the last section table and the file size in the file header. As more and more anti-virus software uses a tail scan method, many viruses also need to append random data after the virus code to escape this scan. This method is widely used by modern PE viruses.
C) written to the gaps reserved by unused sections in the PE file header. The size of the PE Header is generally 1024 bytes. The actual occupied part of a common PE file with 5-6 segments is generally about 600 bytes, and the remaining space of more than 400 bytes is available. Each section of the PE file is usually aligned by 512 bytes, but the actual data in the section is often not fully used by all the 512 bytes. The PE file alignment design was originally out of efficiency considerations, however, the gaps left behind the virus. The total length of the original PE file may not increase after the infection. Therefore, the CIH virus has been favored by virus authors since its first use of this technology.
D) overwrite some very useful data. For example, in the relocation table of an EXE file, because EXE generally does not need to be relocated, it can overwrite the relocated data without causing problems, to be safe, you can clear the corresponding items in the datadirectory array that indicates the relocation item in the file header. This method generally does not increase the length of the infected file. Therefore, this method is widely used by many viruses.
E) compress some data or code to save the space for storing the virus code, and then write the virus code into the space. Before running the program code, the virus first decompress the corresponding data or code, then, the control is handed over to the original program. This method generally does not increase the size of the infected file. However, there are many factors to consider and it is difficult to implement it. Not much is used.
  
Regardless of the method, it involves operations on the PE Header and the section table. First, let's study the modification of PE, that is to say, how to add the virus code so that the PE file is still a valid PE file and can still be loaded and executed by the system loader.
The attributes of each section in the PE file are described by a table item in the section table, and the section table follows image_nt_headers. Therefore, the starting offset of image_nt_headers is found from the dual-word at the file offset 0x3c, in addition, the size of image_nt_headers (248 bytes) is used to locate the starting position of the section table. Each table item is in the image_section_header structure:
Typedef struct _ image_section_header {
Byte name [image_sizeof_short_name]; // The name of the Section.
Union {
DWORD physicaladdress;
DWORD virtualsize; // the actual size of the byte Calculation
} MISC;
DWORD virtualaddress; // The starting virtual address of the node.
DWORD sizeofrawdata; // filealignment according to the file header
// Size after Alignment
DWORD pointertorawdata; // The offset pointing to the start of this section in the file
DWORD pointertorelocations;
DWORD pointertolinenumbers;
Word numberofrelocations;
Word numberoflinenumbers;
DWORD characteristics; // attributes of the Section
} Image_section_header, * pimage_section_header;

The number of table items is determined by the numberofsections member of image_nt_headers. The ing between the memory virtual address and the address in the file can be converted from the starting virtual address in the section table and the location of the Section in the file. To add a section, you need to modify the array of the Section Table, add a table item in it, and then modify the number of numberofsections accordingly. It is worth noting that some existing section tables in PE files may be followed by other data, such as bound import data. In this case, you cannot simply add a Section Table item, you must move the data and modify the corresponding structure before adding a section. Otherwise, the PE file cannot be executed normally. Because many viruses are self-modified, the Section attribute is usually set to e000xxxx, indicating that the section can be read and written, otherwise, you need to call APIs such as virtualprotect at the beginning of the virus to dynamically modify the attributes of the Memory Page. The definition of the preceding section table also shows that the actual data of each section is aligned according to the filealignment in the file header. The size is generally 512, therefore, each section may have no more than 512 bytes of unused space (sizeofrawdata-virtualsize), which just gives the virus a chance. The famous CIH virus first adopted this technology, however, the problem is that the gap size of each section is not fixed. Therefore, you need to divide the virus code into several parts for storage and combine them through a piece of code during the runtime, the advantage is that if the virus code is small, you do not need to increase the size of the PE, which is more concealed. If the unused space of all sections is still insufficient for virus code, you can add a section or attach it to the last section. Attaching to the last section is relatively simple. You only need to modify the virtualsize of the last section in the section table and the sizeofrawdata Member after alignment by filealignment. Of course, if the file size is changed in all the above-mentioned modifications, the size of the sizeofimage value in the file header must be corrected, this value is the size of all sections and headers aligned by sectionalignment.
There are two problems worth noting here. The first problem is the processing of WFP (Windows File Protection) files. The WFP mechanism is a new mechanism to protect system files from Windows 2000, if the system finds that an important system file is changed, a dialog box is displayed to warn that the file has been replaced. Of course, there are multiple methods to bypass WFP protection, but for viruses, the simpler method is not to infect the system files in the WFP list. You can use SFC. the export function sfcisfileprotected of DLL determines whether a file is in the list. The first parameter of this API must be 0, and the second parameter is the file name to be determined, if a non-0 value is returned in the list, otherwise, 0 is returned.
Another problem is the PE File validation. Most PE files do not use the checksum field validation value in the file header. However, some PE files, such as key system service program files and driver files, must be correct, otherwise, the system loader rejects loading. The Checksum In the PE Header can be calculated using the export function checksummappedfile of imagehlp. dll. You can also calculate the checksummappedfile after clearing the field 0 using the following simple equivalent algorithm:
If the size of the PE file is an odd number of bytes, it is supplemented with 0, so that it is an even number of bytes. The Checksum field of the PE file header is cleared to 0, and then the ADC operation is performed in two bytes. Finally, the sum and the actual size of the file are calculated by the ADC operation to obtain the checksum value. The following cal_checksum process assumes that ESI has pointed to the PE file header, the checksum field of the file header has been cleared 0, and the CF flag has been reset:
; Call example:
; CLC
; Push pe_fileseize
; Call cal_checksum
Cal_checksum:
ADC bp, word [esi]; the initial ESI points to the file header, and EBX stores the file size
INC ESI
INC ESI
Loop cal_checksum
MoV EBX, [esp + 4]
The adc ebp, EBX, and EBP stores the PE checksum.
RET 4

In addition to the PE Header checksum, many programs also have verification modules, such as WinZip and WinRAR self-extracting files. If the files are infected, the files cannot be decompressed normally. Therefore, do not infect similar PE files.
The Code related to file modification in elkern is infected in infect. in ASM, the virus first tries to store its own code by using the gap between the PE Header and the section. If all gaps are still insufficient to store the virus code, it is appended to the last section, for more information about the code, see.
In fact, the code snippets that have completed the above functions are already a simple virus, whether written in assembly, C, or Python. However, these are far from all of the virus technologies. In the decades of fighting against viruses and viruses, with the advancement of anti-virus technology, the virus technology is also constantly improving, the memory resident infection technology, anti-analysis technology, EPO Technology, polymorphism technology, and Deformation Technology under Win32 have not been described for a long time. In any case, it is the content of the next article.
* Thinking and Prevention
Virus technology comes from programming practices, but it does not have to be used. It contains a lot of programming skills. If we are good at learning, many of these skills can be used to solve common programming problems. In addition, only by knowing ourselves and ourselves can we calmly respond to viruses, analyze their mechanisms, and find a better solution. As a user, understanding the virus mechanism is also very helpful for selecting appropriate Anti-Virus products and solutions.
Prevent viruses. from the user's point of view, in addition to using anti-virus software to regularly check viruses, it is also important to be alert when downloading or executing unknown programs with caution.
The virus is no longer simply a means to demonstrate superb programming skills, but has been given to other economic and sometimes political meanings by more and more fields. To prevent viruses, as a responsible programmer, do not write or spread viruses first. Everything starts from me.

* References
[1] The PE file format, luevelsmeyer
[2] Microsoft portable executable and common object file format specification, Microsoft Corp.
[3] an in-depth look into the Win32 portable executable file format, Matt pietrek
[4] 29A issue7

Author Profile
Wen Yujie, male, is currently engaged in network security work. The main research fields include malicious code, reverse engineering, artificial intelligence, compilation theory, and underlying security technology. He has translated Intel assembly language programming with Luo yunbin and co-authored Software Encryption technology insider.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.