how to directly read/write usb (disk) like winhex? - c++

My goal is to read /write usb.
First Must open and read usb low -level like 'program'
I used visual c++ with winAPI
below is my test code
char path[64];
sprintf(path,"\\\\.\\%c:",volume);//
/////MOST case, user's input is F or G ......
HANDLE usb;
usb=CreateFile(TEXT(path),
GENERIC_ALL,//
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, //serail I/O
NULL);
if(usb==INVALID_HANDLE_VALUE) cout<<"fail to createfile()"<<endl;
cout<<usb<<endl;
char buf[128];
DWORD dwBytesRead=0;
ReadFile(usb,buf,sizeof(buf),&dwBytesRead,NULL);
cout<<buf<<endl;
cout<<GetLastError()<<endl;
CloseHandle(usb);
I wonder CreateFile was correct And ReadFile
GetLastError() of ReadFile() was 87 that means Invalid Input...
what is the wrong??
I referenced MSDN many times...But any page doesn't solve this problem....
What Should I know? fix it?

Size of buffer must be equal to N * (sector size of drive) where N is DWORD value. Sector size can be received with DeviceIoControl(Handle, IOCTL_DISK_GET_DRIVE_GEOMETRY, ..., DISK_GEOMETRY, ...).

Related

Read/Write to unformatted SD Card on Windows

I am trying to read/write to an SD card that is unformatted and I am having issues. I am using the windows API to open a handle to the SD card and read/write to it, however I get various errors depending on my approach.
Below is me trying to access the SD card by volume label:
HANDLE sdCardHandle = CreateFile("\\\\.\\E:", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(sdCardHandle == INVALID_HANDLE_VALUE)
{
CloseHandle(sdCardHandle);
return;
}
// I have also tried using VirtualAlloc() to get a sector aligned buffer
unit8_t buffer[512] = { 0 };
DWORD bytesWritten = 0;
if(WriteFile(sdCardHandle, buffer, 512, &bytesWritten, NULL) != TRUE)
{
DWORD lastError = GetLastError();
CloseHandle(sdCardHandle);
return;
}
However the WriteFile fails and the last error is 87 which is invalid parameter. I have tried locking the volume and also unmounting the volume before writing also and it failed.
The next attempt was to try and write to the physical drive instead by running the following in administrator mode:
HANDLE sdCardHandle = CreateFile("\\\\.\\PhysicalDrive1", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(sdCardHandle == INVALID_HANDLE_VALUE)
{
CloseHandle(sdCardHandle);
return;
}
// I have also tried using VirtualAlloc() to get a sector aligned buffer
unit8_t buffer[512] = { 0 };
DWORD bytesWritten = 0;
if(WriteFile(sdCardHandle, buffer, 512, &bytesWritten, NULL) != TRUE)
{
DWORD lastError = GetLastError();
CloseHandle(sdCardHandle);
return;
}
Which also fails but return error 23 which is a bad CRC error. I have also tried unmounting and locking the volume first but nothing changed. If there is any thing else I need to do or try please let me know.
Thank you everyone for all of your help and suggestions. It turns out I was doing the operation correct the entire time. However the SD card reader was causing the error. The issue I believe is that BitDefender might not be allowing the read/write operations to go out to the physical disk. I instead used a USB adapter that shows the SD card as USB drive and my read/write works! Hopefully this helps anyone having a similar issue.
from CreateFile
Volume handles can be opened as noncached at the discretion of the
particular file system, even when the noncached option is not
specified in CreateFile. You should assume that all Microsoft file
systems open volume handles as noncached. The restrictions on
noncached I/O for files also apply to volumes.
so we need assume that FILE_FLAG_NO_BUFFERING (FILE_NO_INTERMEDIATE_BUFFERING) will be used:
Specifying this flag places the following restrictions on the caller's
parameters to other ZwXxxFile routines.
Any optional ByteOffset passed to NtReadFile or NtWriteFile must be a multiple of the sector size.
The Length passed to NtReadFile or NtWriteFile must be an integral of the sector size. Note that specifying a read operation to
a buffer whose length is exactly the sector size might result in a
lesser number of significant bytes being transferred to that buffer
if the end of the file was reached during the transfer.
Buffers must be aligned in accordance with the alignment requirement of the underlying device. To obtain this information,
call NtCreateFile to get a handle for the file object that
represents the physical device, and pass that handle to NtQueryInformationFile. For a list of the system's FILE_XXX_ALIGNMENT values, see DEVICE_OBJECT.
note, that here - Alignment and File Access Requirements was wrong information:
File access buffer addresses for read and write operations should be
physical sector-aligned, which means aligned on addresses in memory
that are integer multiples of the volume's physical sector size.
Depending on the disk, this requirement may not be enforced.
this is false - buffer addresses for read and write operations must not be physical sector-aligned. it must be aligned in accordance with the alignment requirement of the underlying device. this is absolute different things.
we can get this align from FILE_ALIGNMENT_INFO (win 8+) or by using FILE_ALIGNMENT_INFORMATION via NtQueryInformationFile with FileAlignmentInformation
in your current code you hardcode buffer size to 512. however sector size of device can be bigger size.
// I have also tried using VirtualAlloc() to get a sector aligned
buffer
how i say - you not need sector aligned buffer (usual device align 2-4 bytes). but you need buffer integral of the sector size. so before read data - you need first query sector size and device align required
HANDLE sdCardHandle = CreateFile(L"\\\\.\\PhysicalDrive1", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (sdCardHandle != INVALID_HANDLE_VALUE)
{
FILE_ALIGNMENT_INFO fai;
if (GetFileInformationByHandleEx(sdCardHandle, FileAlignmentInfo, &fai, sizeof(fai)))
{
ULONG BytesReturned;
STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR saad;
STORAGE_PROPERTY_QUERY spq = { StorageAccessAlignmentProperty, PropertyStandardQuery };
if (DeviceIoControl(sdCardHandle, IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), &saad, sizeof(saad), &BytesReturned, 0))
{
if (PBYTE pb = new BYTE[saad.BytesPerPhysicalSector + fai.AlignmentRequirement])
{
PBYTE buf = (PBYTE)(((ULONG_PTR)pb + fai.AlignmentRequirement) & ~(ULONG_PTR)fai.AlignmentRequirement);
if (ReadFile(sdCardHandle, buf, saad.BytesPerPhysicalSector, &BytesReturned, 0))
{
__nop();
}
else
{
GetLastError();//RtlGetLastNtStatus();
}
delete [] pb;
}
}
}
CloseHandle(sdCardHandle);
}
also as separate note - when you use OPEN_EXISTING - any file attributes is ignored (it used only when you create new file). as result use FILE_ATTRIBUTE_NORMAL - senseless (but not error - simply will be ignored)

Using WriteFile to fill up a cluster

I want to use Writefile to fill up then end of every file until it reaches the end of its last cluster. Then I want to delete what I wrote and repeat the process(attempting to get rid data that might have been there).
I have a 2 issues:
WriteFile gives me an error: ERROR_INVALID_PARAMETER
Depending on the type of file, WriteFile() gives me different results
So for the first issue I realized that the parameter nNumberOfBytesToWrite in the WriteFile() has to be a multiple of bytes per sector(my case is 512 bytes). Is this a limitation of the function or am I doing something wrong?
In my second issue, I'm using two dummy files(.txt and .html) on an external hard drive to write random data to. In the case of the .txt file, the data is written to the end of the file which is what I need. However, the .html file just writes to the beginning of the file and replaces any data that was already there.
Here are some code snippets relevant to my issue:
hFile = CreateFile(result,
GENERIC_READ | GENERIC_WRITE |FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0);
if (hFile == INVALID_HANDLE_VALUE) {
cout << "File does not exist" << endl;
CloseHandle(hFile);
}
DWORD dwBytesWritten;
char * wfileBuff = new char[512];
memset (wfileBuff,'0',512);
returnz = SetFilePointer(hFile, 0,NULL,FILE_END);
if(returnz ==0){
cout<<"Error: "<<GetLastError()<<endl;
};
LockFile(hFile, returnz, 0, 512, 0)
returnz =WriteFile(hFile, wfileBuff, 512, &dwBytesWritten, NULL);
if(returnz ==0){
cout<<"Error: "<<GetLastError()<<endl;
}
UnlockFile(hFile, returnz, 0, 512, 0);
cout<<dwBytesWritten<<endl<<endl;
I am using static numbers at the moment just to test out the functions. Is there anyway I can always write to the the end of the file no matter what type of file? I also tried SetFilePointer(hFile, 0,(fileSize - slackSpace + 1),FILE_BEGIN); but that didn't work.
You need to heed the information in the documentation concerning FILE_FLAG_NO_BUFFERING. Specifically this section:
As previously discussed, an application must meet certain requirements
when working with files opened with FILE_FLAG_NO_BUFFERING. The
following specifics apply:
File access sizes, including the optional file offset in the OVERLAPPED structure, if specified, must be for a number of bytes that
is an integer multiple of the volume sector size. For example, if the
sector size is 512 bytes, an application can request reads and writes
of 512, 1,024, 1,536, or 2,048 bytes, but not of 335, 981, or 7,171
bytes.
File access buffer addresses for read and write operations should be physical sector-aligned, which means aligned on addresses in memory
that are integer multiples of the volume's physical sector size.
Depending on the disk, this requirement may not be enforced.

Reading data off of a cluster

I need help reading data off of the last cluster of a file using CreateFile() and then using ReadFile(). First I'm stuck with a zero result for my ReadFile() because I think I have incorrect permissions set up in CreateFile().
/**********CreateFile for volume ********/
HANDLE hDevice = INVALID_HANDLE_VALUE;
hDevice = CreateFile(L"\\\\.\\C:",
0,
FILE_SHARE_READ |
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
wcout << "error at hDevice at CreateFile "<< endl;
system("pause");
}
/******* Read file from the volume *********/
DWORD nRead;
TCHAR buff[4096];
if (BOOL fileFromVol = ReadFile(
hDevice,
buff,
4096,
&nRead,
NULL
) == 0) {
cout << "Error with fileFromVol" << "\n\n";
system("pause");
}
Next, I have all the cluster information and file information I need (file size, last cluster location of the file,# of clusters on disk, cluster size,etc). How do I set the pointer on the volume to start at a specfied cluster location so I can read/write data from it?
The main problem is that you specify 0 for dwDesiredAccess. In order to read the data you should specify FILE_READ_DATA.
On top of that I seriously question the use of TCHAR. That's appropriate for text when you need to support Windows 9x. On top of not needing to support Windows 9x, the data is not text. Your buffer should be of type unsigned char.
Obviously you need the buffer to be a multiple of the cluster size. You've hard coded 4096, but the real code should surely query the cluster size.
When either of these API calls fail, they indicate a failure reason in the last error value. You can obtain that by calling GetLastError. When your ReadFile fails it will return ERROR_ACCESS_DENIED.
You can seek in the volume by calling SetFilePointerEx. Again, you will need to seek to multiples of the cluster size.
LARGE_INTEGER dist;
dist.QuadPart = ClusterNum * ClusterSize;
BOOL res = SetFilePointerEx(hFile, dist, nullptr, FILE_BEGIN);
if (!res)
// handle error
If you are reading sequentially that there's no need to set the file pointer. The call to ReadFile will advance it automatically.
When doing random-access I/O, just don't mess with the file pointer stored in the file handle at all. Instead, use an OVERLAPPED structure and specify the location for each and every I/O operation.
This works even for synchronous I/O (if the file is opened without FILE_FLAG_OVERLAPPED).
Of course, as David mentioned you will get ERROR_ACCESS_DENIED if you perform operations using a file handle opened without sufficient access.

Read bytes of hard drive

Using the hex editor HxDen one can read (and edit) the bytes on the hard drive or a USB key or the RAM. That is, one can read/change the first byte on the hard disk.
I understand how to read the bytes from a file using C++, but I was wondering how one might do this for the hard disk.
To make it simple, given a positive integer n, how can I read byte number n on the hard drive using C++? (I would like to do C++, but if there is an easier way, I would like to hear about that.)
I am using MinGW on Windows 7 if that matters.
It is documented in the MSDN Library article for CreateFile, section "Physical Disks and Volumes". This code worked well to directly read the C: drive:
HANDLE hdisk = CreateFile(L"\\\\.\\C:",
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
0, NULL);
if (hdisk == INVALID_HANDLE_VALUE) {
int err = GetLastError();
// report error...
return -err;
}
LARGE_INTEGER position = { 0 };
BOOL ok = SetFilePointerEx(hdisk, position, nullptr, FILE_BEGIN);
assert(ok);
BYTE buf[65536];
DWORD read;
ok = ReadFile(hdisk, buf, 65536, &read, nullptr);
assert(ok);
// etc..
Admin privileges are required, you must run your program elevated on Win7 or you'll get error 5 (Access denied).

Faster method for exporting embedded data

For some reasons, i'm using the method described here: http://geekswithblogs.net/TechTwaddle/archive/2009/10/16/how-to-embed-an-exe-inside-another-exe-as-a.aspx
It starts off from the first byte of the embedded file and goes through 4.234.925 bytes one by one! It takes approximately 40 seconds to finish.
Is there any other methods for copying an embedded file to the hard-disk? (I maybe wrong here but i think the embedded file is read from the memory)
Thanks.
Once you know the location and size of the embedded exe , then you can do it in one write.
LPBYTE pbExtract; // the pointer to the data to extract
UINT cbExtract; // the size of the data to extract.
HANDLE hf;
hf = CreateFile("filename.exe", // file name
GENERIC_WRITE, // open for writing
0, // no share
NULL, // no security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no template
if (INVALID_HANDLE_VALUE != hf)
{
DWORD cbWrote;
WriteFile(hf, pbExtract, cbExtract, &cbWrote, NULL);
CloseHandle(hf);
}
As the man says, write more of the file (or the whole thing) per WriteFile call. A WriteFile call per byte is going to be ridiculously slow yes.