使用PhysicalDrive0直接写入磁盘

时间:2017-12-18 23:23:23

标签: c windows permissions filesystems raw-disk

我尝试使用以下代码直接写入磁盘上的偏移量(我在虚拟机中运行它,但仍然如此):

int main()
{
    OVERLAPPED overlapped;


    char DataBuffer[] = "AAAAAAA";
    HANDLE dHandle = CreateFile(_T("\\\\.\\PhysicalDrive0"),
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_FLAG_NO_BUFFERING,
        NULL
    );

    // LOCK DISK
    int err;
    DWORD stuff = 0;
    if (!DeviceIoControl
    (
        dHandle,
        FSCTL_LOCK_VOLUME,
        NULL,
        0,
        NULL,
        0,
        &stuff,
        NULL
    ))
    {
        err = GetLastError();
        fprintf(stderr, "Error %u locking volume.\n", err);
        return err;
    }


    DWORD lpBytesReturned;
    if (!DeviceIoControl(
        dHandle,            // handle to a volume
        (DWORD)FSCTL_DISMOUNT_VOLUME,   // dwIoControlCode
        NULL,                        // lpInBuffer
        0,                           // nInBufferSize
        NULL,                        // lpOutBuffer
        0,                           // nOutBufferSize
        &lpBytesReturned,   // number of bytes returned
        NULL  // OVERLAPPED structure
    )) {
        err = GetLastError();
        fprintf(stderr, "Error %u dismount volume.\n", err);
        return err;
    }


    printf("Handle is : %d\n", dHandle);
    int set_res = SetFilePointer(dHandle, 791908352, NULL, FILE_BEGIN);
    if (set_res == INVALID_SET_FILE_POINTER) {
        printf("invalid set_file pointer\n");
        printf("Last error was : %d\n", GetLastError());

    }
    DWORD written = 0;
    int res2 = WriteFile(dHandle, DataBuffer, 4096, &written, NULL);
    if (!res2) {
        printf("Last error was : %d\n", GetLastError());
        printf("Written : %d", written);
    }
    printf("Written : %d", written);

    return 0;

当我运行以下代码时,我得到:

5 (0x5)
Access is denied.

尝试WriteFile后。 我以管理员身份运行该程序。 我知道偏移是有效的,因为我可以从该偏移中读取相关数据。

我知道为什么会得到它?我怎么能让它发挥作用?

0 个答案:

没有答案