-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisksn_ioctl.cpp
77 lines (64 loc) · 1.96 KB
/
disksn_ioctl.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "disksn_ioctl.h"
#include "log.h"
#include "mangler.h"
#include <windows.h>
int get_disk_sn_ioctl(std::string& sn) {
HANDLE hDevice = INVALID_HANDLE_VALUE;
STORAGE_PROPERTY_QUERY spq {};
STORAGE_DESCRIPTOR_HEADER sdh {};
BYTE *buffer = NULL;
STORAGE_DEVICE_DESCRIPTOR *desc = NULL;
DWORD dw_ret = 0;
int ret = -1;
sn = "1000001";
hDevice = CreateFile(L"\\\\.\\PhysicalDrive0", 0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == NULL || hDevice == INVALID_HANDLE_VALUE) {
DWORD last_error = GetLastError();
Log::print_error_code(L"Cannot open PhysicalDrive0.", last_error);
goto cleanup;
}
spq.PropertyId = StorageDeviceProperty;
spq.QueryType = PropertyStandardQuery;
if (!DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
&spq, sizeof(spq), &sdh, sizeof(sdh),
&dw_ret, NULL))
{
DWORD last_error = GetLastError();
Log::print_error_code(L"Cannot query PhysicalDrive properties using DeviceIoControl.", last_error);
goto cleanup;
}
buffer = new BYTE[sdh.Size];
ZeroMemory(buffer, sdh.Size);
if (!DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
&spq, sizeof(spq), buffer,sdh.Size,
&dw_ret, NULL))
{
DWORD last_error = GetLastError();
Log::print_error_code(L"Cannot query PhysicalDrive properties using DeviceIoControl.", last_error);
goto cleanup;
}
desc = (STORAGE_DEVICE_DESCRIPTOR*) buffer;
if (desc->SerialNumberOffset == 0) {
sn = "1000001";
Log::print(L"Cannot find serial number for PhysicalDrive0.");
goto cleanup;
}
sn = ((LPCSTR)desc) + desc->SerialNumberOffset;
detect_and_decode_hex(sn);
if (check_zero_serial_number(sn)) {
sn = "1001001";
goto cleanup;
}
mangle_serial_number(sn);
ret = 0;
cleanup:
if (buffer) {
delete[] buffer;
}
if (hDevice != NULL && hDevice != INVALID_HANDLE_VALUE) {
CloseHandle(hDevice);
}
return ret;
}