Skip to main content

HDD enumeration and info retreive - another way

In this part I tried to enumerate all physical hard disk drive (HDD) attached to the system and tried to query to those attached physical drive to get the disk information like Vendor ID, Product ID, Product Revision, Serial number etc.

In my last blog, I've tried to get physical hard disk drive count through volume map, but in this post, I tried get it through "SetupDiGetClassDevs" API. All the SetupDiXXX APIs are very powerful APIs. These APIs along with DeviceIoControl API helps to retrieve very useful information regarding devices. So, I'm not going to talk much on this rather let MSDN to speak about this APIs.

Let's see what are other information that we can get on HDD attached to the system through the usage of this API:

void printStorageDeviceProperty(UCHAR *outBuf, const DWORD returnedLength)
{
    PSTORAGE_DEVICE_DESCRIPTOR            devDesc;
    PUCHAR                              pUbuffer;

    devDesc = (PSTORAGE_DEVICE_DESCRIPTOR) outBuf;
           
    pUbuffer = (PUCHAR) outBuf;
    if ( devDesc->VendorIdOffset && pUbuffer[devDesc->VendorIdOffset] )
    {
        wprintf(L"Vendor ID       : " );
        for ( DWORD i = devDesc->VendorIdOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->ProductIdOffset && pUbuffer[devDesc->ProductIdOffset] )
    {
        wprintf(L"Product ID       : " );
        for ( DWORD i = devDesc->ProductIdOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->ProductRevisionOffset && pUbuffer[devDesc->ProductRevisionOffset] )
    {
        wprintf(L"Product Revision       : " );
        for ( DWORD i = devDesc->ProductRevisionOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }

    if ( devDesc->SerialNumberOffset && pUbuffer[devDesc->SerialNumberOffset] )
    {
        wprintf(L"Serial Number       : " );
        for ( DWORD i = devDesc->SerialNumberOffset; pUbuffer[i] != (UCHAR) NULL && i < returnedLength; i++ )
        {
            wprintf( L"%c", pUbuffer[i] );
        }
        wprintf(L"\n");
    }
   
    wprintf(L"Removable Media : %s\n", ((devDesc->RemovableMedia) ? L"Yes..." : L"No..."));
}

void printMediaType(HANDLE hDevice)
{
    PGET_MEDIA_TYPES MediaTypes = {0};
    BOOL    status = FALSE;
    UCHAR   buffer[2048];
    ULONG    returnedLength;

    status = DeviceIoControl(hDevice, IOCTL_STORAGE_GET_MEDIA_TYPES_EX, NULL, 0, buffer, sizeof(buffer), &returnedLength, FALSE);

    if (!status)
    {
        wprintf(L"IOCTL_STORAGE_GET_MEDIA_TYPES_EX failed with error code%d.\n\n", GetLastError());
        return;
    }

    MediaTypes = (PGET_MEDIA_TYPES) buffer;
    switch(MediaTypes->DeviceType)
    {
        case FILE_DEVICE_DISK:
            wprintf(L"Media Type: Device Disk\n");
            break;
        case FILE_DEVICE_DISK_FILE_SYSTEM:
            wprintf(L"Media Type: Device Disk File System\n");
            break;
        case FILE_DEVICE_FILE_SYSTEM:
            wprintf(L"Media Type: File Device File System\n");
            break;
        default:
            wprintf(L"Media Type: Unknown");
            break;
    }

    // Device Media Info
    for (DWORD i = 0; i < MediaTypes->MediaInfoCount; i++)
    {
        wprintf(L"Bytes/Sector:        %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.BytesPerSector);
        wprintf(L"No. of Cylinders: %I64d\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.Cylinders);
        // wprintf(L"Media Characteristics: %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.MediaCharacteristics);
        switch(MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.MediaType)
        {
        case FixedMedia:
            wprintf(L"Media Type:    FixedMedia\n");
            break;
        default:
            wprintf(L"Media Type:    Unknown...\n");
            break;
        }
        wprintf(L"No. of sides:        %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.NumberMediaSides);
        wprintf(L"Sectors/track:    %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.SectorsPerTrack);
        wprintf(L"Tracks/Cylinder:    %ld\n", MediaTypes->MediaInfo[i].DeviceSpecific.DiskInfo.TracksPerCylinder);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    HDEVINFO hDevInfo;
    SP_DEVINFO_DATA DeviceInfoData;
    DWORD i;

    // Create a HDEVINFO with all HDD present in system.
    hDevInfo = SetupDiGetClassDevs((LPGUID)&GUID_DEVINTERFACE_DISK,
       0, // Enumerator
       0, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE );

    if (hDevInfo == INVALID_HANDLE_VALUE)
    {
       return 1;
    }
   
    // Enumerate through all physical drive in Set.
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    for(i=0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
    {
        LPTSTR buffer = NULL;
        DWORD buffersize = 0;

        SP_DEVICE_INTERFACE_DATA                interfaceData;
        PSP_DEVICE_INTERFACE_DETAIL_DATA        interfaceDetailData = NULL;
        HANDLE                                    hDevice;
        BOOL                                    status;
        DWORD                                    interfaceDetailDataSize;
        DWORD                                    reqBufSize;
        DWORD                                    errorCode;

        interfaceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);

        status = SetupDiEnumDeviceInterfaces (
            hDevInfo,                    // Interface Device Info handle
            0,                            // Device Info data
            (LPGUID)&DiskClassGuid,        // Interface registered by driver
            i,                            // Member
            &interfaceData                // Device Interface Data
        );

        status = SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, NULL, 0, &reqBufSize, NULL);
        if(status == FALSE)
        {
            errorCode = GetLastError();
            if(errorCode != ERROR_INSUFFICIENT_BUFFER)
            {
                wprintf( L"SetupDiGetDeviceInterfaceDetail failed with error: %d\n", errorCode   );
                return FALSE;
            }
        }

        interfaceDetailDataSize = reqBufSize;
        interfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, reqBufSize);

        interfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);

        status = SetupDiGetDeviceInterfaceDetail(hDevInfo, &interfaceData, interfaceDetailData,
            interfaceDetailDataSize, &reqBufSize, NULL);

        if ( status == FALSE )
        {
            wprintf(L"Error in SetupDiGetDeviceInterfaceDetail failed with error: %d\n", GetLastError());
            return FALSE;
        }

        wprintf( L"Interface: %s\n", interfaceDetailData->DevicePath);

        hDevice = CreateFile(
                interfaceDetailData->DevicePath,    // device interface name
                GENERIC_READ | GENERIC_WRITE,       // dwDesiredAccess
                FILE_SHARE_READ | FILE_SHARE_WRITE, // dwShareMode
                NULL,                               // lpSecurityAttributes
                OPEN_EXISTING,                      // dwCreationDistribution
                0,                                  // dwFlagsAndAttributes
                NULL                                // hTemplateFile
                );

        if (interfaceDetailData)
            LocalFree(interfaceDetailData);

        if (hDevice == INVALID_HANDLE_VALUE)
        {
            wprintf(L"CreateFile failed with error: %d\n", GetLastError());
            return TRUE;
        }

        STORAGE_PROPERTY_QUERY                query;
        UCHAR                                outBuf[512];
        DWORD                                returnedLength;

       query.PropertyId = StorageDeviceProperty;
       query.QueryType = PropertyStandardQuery;
      
       status = DeviceIoControl( hDevice,               
                        IOCTL_STORAGE_QUERY_PROPERTY,
                        &query, sizeof( STORAGE_PROPERTY_QUERY ),
                        &outBuf, 512, &returnedLength, NULL
                        );

        if ( !status )
        {
            wprintf(L"IOCTL failed with error code: %d.\n\n", GetLastError() );
        }
        else
        {
            printStorageDeviceProperty(outBuf, returnedLength);
            printMediaType(hDevice);

            wprintf(L"\n\n");
        }

        if ( !CloseHandle(hDevice) )    
        {
            wprintf( L"Failed to close device.\n");
        }
    }    // End of for loop...

    if ( GetLastError() != NO_ERROR && GetLastError() != ERROR_NO_MORE_ITEMS )
    {
       return 1;
    }

    //  Cleanup
    SetupDiDestroyDeviceInfoList(hDevInfo);

    return 0;
}


The output looks like below:




Comments

Popular posts from this blog

Variadic template class to add numbers recursively during compilation

 The idea of having a class to add numbers (variable parameters) during compilation time recursively. Also wanted to restrict types to a single type while sending parameters to class member function. That said, if we mix int, float and double types to add function shall result in compilation error. How do we achieve this. The below is the code which actually helps to achieve this: <code> #include < fmt/format.h > template < typename T> class MyVarSumClass{     private :         T _sum = 0 ;     public :         template < typename ... TRest>         T add(T num, TRest... nums){             static_assert (std::conjunction<std::is_same<TRest, T>...>{}); /* Assert fails                if types are different */             _sum += num;             return add(nums...); // Next parameter packs gets picked recursively         }         // Base case         T add(T num){             _sum += num;             return _sum;         } }; int main() {     My

A simple approach to generate Fibonacci series via multi-threading

T his is a very simple approach taken to generate the Fibonacci series through multithreading. Here instead of a function, used a function object. The code is very simple and self-explanatory.  #include <iostream> #include <mutex> #include <thread> class Fib { public:     Fib() : _num0(1), _num1(1) {}     unsigned long operator()(); private:     unsigned long _num0, _num1;     std::mutex mu; }; unsigned long Fib::operator()() {     mu.lock(); // critical section, exclusive access to the below code by locking the mutex     unsigned long  temp = _num0;     _num0 = _num1;     _num1 = temp + _num0;     mu.unlock();     return temp; } int main() {     Fib f;          int i = 0;     unsigned long res = 0, res2= 0, res3 = 0;     std::cout << "Fibonacci series: ";     while (i <= 15) {         std::thread t1([&] { res = f(); }); // Capturing result to respective variable via lambda         std::thread t2([&] { res2 = f(); });         std::thread t3(

A concept to a product (Kimidori [ 黄緑]) - Part 2

In the previous part , we have seen KIMIDORI [ 黄緑] detect if a URL is malicious. In this part, we will see the details that KIMIDORI [ 黄緑] fetches out of the URL provided. As an example, provided a safe URL, https://www.azuresys.com/, and let's see what it brings out: As we can see, the link is safe and the link is active, which means we can just click on the link to open it on IE.  Now it's time to look into the URL report (still under development):  We have URLs IP, Location, and HTTP Status code. The Report part is a sliding window, the Show Report button shows as well as hides the report. Show / Hide Report is a toggle button. Let's see if we get the same details for any bad (phishing / malicious) URL: Took an URL example from a phishing link and tested it. The tool detected it as not a good link (Screen Shot Below) & link does not activate unlike a safe URL: Now let's see the report part for more details including domain registration details: It looks like it&