[英]Windows C++ API: How do I read an entire binary file into a buffer?
我正在嘗試將任意長度的二進制文件的全部內容加載到字符數組中。 該數組的內容稍后將被復制到由VirtualAlloc
保留的 memory 位置。 到目前為止,這是我的代碼:
#include <windows.h>
#include <fileapi.h>
#include <tchar.h>
int __cdecl _tmain(int argc, TCHAR* argv[])
{
HANDLE payload;
if (argc != 2) {
_tprintf(TEXT("Usage: runp.exe [payload_file]\nExecutes the specified binary payload.\n"));
return 0;
}
_tprintf(TEXT("[*] Loading binary payload: %s\n"), argv[1]);
payload = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (payload == INVALID_HANDLE_VALUE) {
_tprintf(TEXT("[!] Could not open payload: %s\n"), argv[1]);
}
else {
DWORD size = GetFileSize(payload, NULL);
_tprintf(TEXT("[*] Payload found: %d bytes.\n"), size);
// TROUBLE STARTS HERE
LPDWORD bytes_read = 0;
char* buffer = new char[size + 1];
if (FALSE == ReadFile(payload, buffer, size, bytes_read, NULL)) {
_tprintf(TEXT("[!] Could not read payload!\n"));
}
else {
_tprintf(TEXT("[*] Payload read!\n"));
}
delete[] buffer;
// TROUBLE ENDS HERE
}
CloseHandle(payload);
return 0;
}
這是它如何失敗的示例:
PS C:\path\to\binary> echo "Demonstration file." > demo.file
PS C:\path\to\binary> .\runp.exe .\demo.file
[*] Loading binary payload: .\demo.file
[*] Payload found: 44 bytes.
[!] Could not read payload!
該程序正確檢測並識別二進制文件的大小,但我無法將文件的內容讀入我的自定義大小的緩沖區。
Windows 上的 C++ 不是我的母語。 Python 更適合我的速度,但我這里別無選擇。 任何幫助將非常感激。
在大家的幫助下,我能夠克服我在代碼中遇到的問題。 根據selbie的建議,我無法完全刪除所有TCHAR
內容,因為CreateFile
function 不會接受文件名的字符數組,也不會在不使用主要 function 的_tmain
格式的情況下進行編譯。 (同樣,Windows 上的 C++ 不是我的母語,所以無疑有更好的方法來實現這一點。)但我確實添加了\0
(空字節)來終止緩沖區內容。 我還納入了Retired Ninja和Mark Ransom建議的更改。 以下是應用這些更改后的代碼:
#include <windows.h>
#include <fileapi.h>
#include <stdio.h>
#include <tchar.h>
int __cdecl _tmain(int argc, TCHAR* argv[])
{
HANDLE payload;
if (argc != 2) {
printf("Usage: runp.exe [payload_file]\nExecutes the specified binary payload.\n");
return 0;
}
printf("[*] Loading binary payload: %ws\n", argv[1]);
payload = CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (payload == INVALID_HANDLE_VALUE) {
printf("[!] Could not open payload: %ws\n", argv[1]);
}
else {
DWORD size = GetFileSize(payload, NULL);
DWORD bytes_read = 0;
char* buffer = new char[size + 1];
if (FALSE == ReadFile(payload, buffer, size, &bytes_read, NULL)) {
printf("[!] Could not read payload!\n");
}
else {
buffer[bytes_read] = '\0';
printf("[*] %d bytes read.\n[*] File contents:\n\n%s\n", bytes_read, buffer);
}
delete[] buffer;
}
CloseHandle(payload);
return 0;
}
以下是該程序的實際演示:
C:\path\to\binary>echo Demonstration! > test.txt
C:\path\to\binary>type test.txt
Demonstration!
C:\path\to\binary>runp.exe test.txt
[*] Loading binary payload: test.txt
[*] 17 bytes read.
[*] File contents:
Demonstration!
再次感謝大家的有益建議!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.