30
Jan
2009
Jan
2009
Extracting binary resources in win32
Here is a useful snippet for extracting a binary resource from a compiled resource in a exe or dll. I haven\'t really seen any thing demonstrates how to do this exactly. So hopefully this helps someone. Maybe next time I will post the code to extract into memory and execute a PE file.
/** * Extracts a binary resource and write it to the specified output file. * * @param output_filename filename of the output file * @param resource_id resource id of object to extract from the resource file * * @author Jacob Hammack * */ void extract_resource(TCHAR *output_filename, int resource_id) { HGLOBAL resource_handle = NULL; HANDLE file_handle; HRSRC resource; TCHAR *resource_data; DWORD resource_size; DWORD bytes_written = 0; if(!(resource = FindResource(0, MAKEINTRESOURCE(resource_id), RT_RCDATA)) { return; } if(!(res_handle = LoadResource(NULL, resource))) { return; } resource_data = (TCHAR*) LockResource(resource_handle); resource_size = SizeofResource(NULL, resource); file_handle = CreateFile(output_filename, GENERIC_WRITE, FILE_SHARE_WRITE,0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(file_handle == INVALID_HANDLE_VALUE) { _tprintf(TEXT("[!] Unable to create file handle for writing temp data to disk.\n")); return; } while(bytes_written < resource_size) { if(FALSE == WriteFile(file_handle, resource_data + bytes_written, resource_size - bytes_written, &bytes_written, NULL)) { CloseHandle(file_handle); return; } } CloseHandle(file_handle); }