WeSeong Log in
← Back to posts
Attracting; capturing

API Hooking, Packet Analysis

API Hooking, Packet Analysis

I. Overview

API Catching API A brief overview of "hooking" in Windows. API Let's examine what "it" is and what it encompasses. API This document introduces platforms related to "hooking," as well as process monitoring programs provided by Windows, and information about functions. API Example code with hooking capabilities in Python for Windows. API Let's briefly examine how this works. We'll analyze the structure of a packet. By creating a packet file, you'll find that it consists of a Global Header, followed by repeated Packet Headers and Data. I will introduce a method for analyzing the structure of the data link, network, and transport layer protocols, and extracting only the necessary information.



II. API Hooking

API Catching API (Hooking)is The essence of RV livingThis is referred to as "code injection." It involves inserting malicious code into a program or website to intercept data, modify the program's execution flow, or provide functionality that is different from the original. This is possible because... Infiltration of the processThis is because Windows uses APIs to access various functions and features within the operating system. For example, it allows users to turn on Bluetooth, access the file system, or change the date. Windows APIThis is a collection of functions that allow users to access these features. To access hardware, the kernel connects to each device's interface, and each shell in Windows represents a separate process that sends commands to the kernel. The reason that specific user programs (like Melon or a browser) can run smoothly in Windows is because they can utilize these processes. The Windows API is connected to these Windows processes.Because it is beneficial.


※ To elaborate further, in Windows, the "explorer" process, which is the primary parent process, uses the CreateProcessA function to create programs that users are using. It creates the processes. Once the process is created, the main thread begins to execute, and the main thread calls each child thread.

CreateProcessA function (processthreadsapi.h) - for Win32 applications

API hooking involves intercepting and modifying API calls made by a specific process to execute itself. Taking control by intercepting it in the middle.It possesses. API This allows me to manipulate the parameters or return values that are passed to the function, effectively canceling the function call or changing the process flow to one that I desire.


One well-known example that enables API hooking is Frida, which can be considered a type of platform for this purpose.

Operating Modes

This Frida tool is compatible with almost all operating systems and runs on the JavaScript language. For detailed instructions and functions, please refer to the website mentioned above.


* A helpful tip to remember: JavaScript has been instrumental in the remarkable development of the web, largely due to the development of the V8 engine, which made it possible to use the JavaScript language on virtually any website.


※ This article introduces a Microsoft program that tracks processes. While it can track all Windows processes, it cannot prevent or detect intrusions into multiple shells through API hooking. Specifically, A malicious program that changes the filename to display the process name correctly and then functions normally.There are quite a few of them. However, while they don't always provide complete information, examining additional details such as the actual process path and creation date can also be helpful. I plan to create a follow-up post with more detailed information.

Sysinternals - Sysinternals

I've included a simple example code.

var hook_createprocess = Module.getExportByName("kernel32.dll", "CreateProcessW");
Interceptor.attach(hook_createprocess, {
    onEnter(args) {
        var lpApplicationName = args[0];
        console.log(Memory.readByteArray(lpApplicationName, 4096));
        var applicationName = Memory.readUtf16String(lpApplicationName);
        console.log(applicationName);
        var lpCommandLine = args[1];
        console.log(Memory.readUtf16String(lpCommandLine));
    },
    onLeave(result) {
        //console.log(result);
    }
});

This code allows you to monitor the creation of processes in real-time by inserting it into the function that generates the processes.


Furthermore, let's explore how to use the Windows API through Python's file writing function to gain a better understanding of its application.

fd = open('경로\\aaaa.txt', 'w')
fd.writelines("12345abcde")
fd.close()

This code can be used to create a .txt file because of the Windows operating system's CreateFileA Functions and WriteFile This is because the functions can be called through the Windows API. Each function corresponds to a specific operation within the file system. Accessing the MFTIt allocates a random (empty or safe) location within the partition where the MFT will be stored. Specify the sectorand in that sector. Storing dataIt includes information such as the file's creation date, file name, and file location, which are relevant to the MFT (Master File Table). Recording various types of information.And it returns the functions that control this process. It's also referred to as "Handle," which can be thought of as simply an interface for manipulating these functions. The reason for returning them is quite obvious: they need to be released to free up memory.



Ⅲ. Packets

So far, I have studied the structures of PE, ZIP, and DISK (FAT, NTFS) files, and practiced using HxD to understand and modify their structures. Now, I want to further analyze the structure of network packets.


* **Important Tip:** Although IPv6 was developed, IPv4 is still in use. The reason for this is: NATThis is because it allows for the distinction between public and private IP addresses, and also enhances security through port forwarding.



Source https://boanhack.tistory.com/172

PCAP File Signature

Now, let's delve into the structure of packets. For more detailed information, please refer to the blog post mentioned above. The first 24 bytes... Global HeaderThis is the default header that is typically included in .pcap files. Next, Packet HeaderThis is where the Packet Header and Packet DataThis pattern repeats continuously. If the Global Header is separated, it should be possible to distinguish between the Packet Header and the Data. The Packet Header consists of 16 bytes, and the length of the following Data is indicated as 12 to 15 bytes. In other words, the value obtained by adding the length of the header (16 bytes) to the length of the data represents the next packet. Of course, the initial value of the Global Header should be the sum of its individual components.


Now, we will begin to extract packet data from the data link, network, and transport layers.

[SK쉴더스 SeSAC, Dong-Seoul Branch, 1st Class]: 1. Network type, OSI 7-layer model, protocols (data link, network, transport layer)

[SK쉴더스 SeSAC, Dong-Seoul Branch] 2. Network Type, OSI 7-Layer Model, Protocols (Data Link, Network, Transport Layer)

For information on the protocols and header/data structures of the data link, network, and transport layers, please refer to the previous post. The first thing you'll find in Packet Data is: Ethernet This is information. It resides in the data link layer. MAC addressThis information explains the structure of a MAC address. The first 3 bytes represent the manufacturer, and the last 3 bytes are a unique identifier (serial number) assigned by the manufacturer. By default, a MAC address consists of 6 bytes, and in packet data Destination AddressIt comes first. Source AddressWhen the source address arrives later, if the destination address arrives first, we need to skip 6 bytes to find the destination address. This essentially means performing unnecessary operations.

[Network] Ethernet/TCP/IP Header Structure

As you can see in previous posts or on this blog, I have explained the detailed structure of an Ethernet header. However, a captured packet file does not contain the entire header structure. Therefore, you only need to extract the Destination Address, Source Address, and Type, which are 6 bytes, 6 bytes, and 2 bytes respectively.


MAC addresses are mapped to IP addresses.When searching for a MAC address associated with an IP address, a broadcast is sent. If the response received is within the same network range and includes the sender's IP address, the response includes the sender's MAC address. It immediately informs you without requiring an authentication code. This is how the ARP protocol works: it uses IP addresses to determine the corresponding MAC addresses. ARPConversely, if you know the MAC address, you can determine the IP address. RARPIt is said.


※ Regarding the ARP mentioned just now ARP SpoofingThere is a potential attack vector: exploiting the fact that the system immediately reveals the user's MAC address without requiring any authentication. This could be used to intercept network communication packets. SniffingThis can be observed through ARP requests. When a user requests a MAC address via ARP, the device reveals its own MAC address to the user and also to the server, allowing it to manipulate data in the middle. This type of attack is common in environments where multiple devices share the same network segment, such as in a coffee shop. Methods for defenseInstead of simply checking for unusual MAC addresses within the same network range (e.g., by using the `arp` command to see if there are duplicate MAC addresses) or dynamically mapping IP and MAC addresses to allow for changes, It should be designed in a way that prevents modification.


Useful information that can be obtained from dump packet files related to the IP protocol at the network layer includes: Time to Live, Protocol, IP address It has a back.

PCAP format, Header

For more detailed information, you might want to check out the blog post. Specifically, if you analyze only the IP protocol-related parts of a packet file using "Wireshark," you'll find that the "Time to Live" value is Version, Services, Total Length, Identification, Flags, Fragment OffsetThe information is available. If you want to check it, you can simply look at the number of bytes for each item without adding it to the total calculation. Since you want to know the "Time to Live" value directly, you can calculate the number of bytes before it, which reveals that it is 8 bytes. And The protocol starts with the next byte, and the source IP address occupies bytes 9 through 15, while the destination IP address occupies bytes 16 through 19.


※ Because the IP protocol section follows directly after the Ethernet protocol, it is necessary to start the calculation by adding 14 bytes (the length of the Ethernet protocol information) to ensure accuracy.


※ Regarding IP addresses Source AddressWow Destination AddressYou can determine whether an IP address is private or public by looking at it. Generally, if an IP address starts with 192.168.~, it is a private IP address. Otherwise, it is likely a public IP address.


The transport layer is TCPWow UDPThese are divided into two categories. Therefore, when calculating, it's necessary to determine whether it's TCP or UDP. This is done while extracting the IP protocol from the network layer, as mentioned above. Protocol You might have encountered this before. When you convert a hexadecimal value to decimal, you get 17 and 6. These numbers indicate whether the data is being transmitted using TCP or UDP. TCP uses port 6, while UDP uses port 17.Therefore, we can analyze the structure by dividing it based on this value.


Let's start by looking at TCP. The key information to understand here is: Source/Destination Port, Sequence/Acknowledgment Number, Flags, Payload (raw data)Once we have obtained the IP protocol data (a total of 20 bytes), Source/Destination Port: Each port uses 2 bytes.and then, we can determine Each sequence/acknowledgment number is 4 bytes long.The flags require a small calculation. You need to extract only one byte from the 2 bytes following the Acknowledgment Number. & You can determine this by performing the calculation. 0b00100000 & The calculation results in an "Urgent Flag" value. If the value is 0, it means there was no request. If the value is 1, it indicates that a request was received. Specifically: * 0b00010000: Acknowledgment value * 0b00001000: Push value * 0b00000100: Reset value * 0b00000010: Syn value * 0b00000001: Fin valueOnce we have these 6 flag values, we can proceed to obtain the payload. However, the payload typically starts after the 20-byte TCP header, and it might be missing, so filtering is necessary. If the payload is present, Before the header and data of the next packet appear (i.e., before the data for the next packet is received). Simply extract it.


※ Provides information about the TCP connection status FlagsThe values obtained during the 3-way handshake process provide us with useful information. Urgentis Urgent requestThis means Okayis Completedwhich means Pressis Immediately transmit the received data to the application layer.This means... Resetis After forcibly disconnecting, ignore any remaining data requested. Synis Request for connectionThis refers to [specific term/concept], and finally, EndThis signifies a normal connection termination. By monitoring packets related to this SYN request and blocking them, you can enhance security.


Let's examine the connection process using Syn and Ack, and sequence numbers. Initially, the client initiates a connection to a specific server. When requesting a Syn, use a random sequence number.It sends the data. The server receives the data. The value obtained by adding 1 to the sequence number, and the acknowledgment number.I am sending it back. The client is Send the value obtained by adding 1 to the received Acknowledgment (Ack) number as the Sequence (Seq) number, and generate a new random Ack number.Ultimately, the connection is established through the exchange of Syn and Ack. Understanding the concepts of Syn and Ack allows you to target the intended recipient. Port scanningThis allows you to perform the action without leaving a trace in the TCP logs. First, verify that the server is running.This is the process: first, a SYN request is sent, and then an ACK response is received, immediately terminating the connection. A method of not sending an "Acknowledgement (Ack) request" after the final connection is established.This process consists of several steps. Strictly speaking, this process involves: TCP Half-Open Scan (Stealth Scan)This is referred to as "stealth scanning." One of the key reasons why these TCP information packets are important is that they allow for the proactive blocking of port or flag requests using firewalls, thus preventing unauthorized access.


※ The payload data for TCP is Web communication packets (the content portion of HTTP's Get and Post methods), which represent the actual data being transmitted.They are filled with.


If we continue with UDP, then in UDP: Source/Destination Port and UDP PayloadThe only thing that needs to be extracted is the MAC address. This is significantly simpler than working with TCP. Similarly, once you move past the IP protocol in the network layer, The source/destination port each occupies 2 bytes.Simply calculate the total length, including the UDP header and the data (payload). LengthWhen sending data over UDP, the payload length needs to be reduced by -8 based on this value. This is because there are two port numbers and length/checksum information, each taking up 2 bytes, before the UDP payload. Total: 8 bytesThis is because the Source/Destination Port is defined at the beginning and each takes up 2 bytes. The UDP payload starts 8 bytes after the "Length" field.Once you extract the relevant information, you should be able to obtain the information you need.


※ When sending a query over UDP, the port number to use is 53. UDP is typically used to obtain the IP address of the destination DNS (Domain Name Server), and there are two types: forward and reverse. Forward... www.google.com and The goal is to find the corresponding IP address for a given hostname, and "reverse DNS" refers to the process of finding the hostname associated with a specific IP address (e.g., 192.168.0.10)The task is to find the host's name, based solely on the information provided.



Review

During the last Friday of this week, I worked on writing code in Python to analyze packet files. By coding the structures in Python and figuring out how to extract them, I found that it became easier to understand. Starting next week, I anticipate incorporating mobile devices, so it's important to thoroughly understand the structures I learned this week.