// PELF_FILE_WRITE_ROUTINE static NTSTATUS NTAPI LogfpWriteFile(IN PEVTLOGFILE LogFile, IN PLARGE_INTEGER FileOffset, IN PVOID Buffer, IN SIZE_T Length, OUT PSIZE_T WrittenLength OPTIONAL) { NTSTATUS Status; PLOGFILE pLogFile = (PLOGFILE)LogFile; IO_STATUS_BLOCK IoStatusBlock; if (WrittenLength) *WrittenLength = 0; Status = NtWriteFile(pLogFile->FileHandle, NULL, NULL, NULL, &IoStatusBlock, Buffer, Length, FileOffset, NULL); if (WrittenLength) *WrittenLength = IoStatusBlock.Information; return Status; }
BOOL WINAPI WriteConsole( IN HANDLE hConsoleOutput, IN const VOID *lpBuffer, IN DWORD nNumberOfCharsToWrite, OUT LPDWORD lpNumberOfCharsWritten, IN LPVOID lpReserved) { IO_STATUS_BLOCK IoStatusBlock; NTSTATUS Status; Status = NtWriteFile(hConsoleOutput, NULL, NULL, NULL, &IoStatusBlock, (PVOID)lpBuffer, nNumberOfCharsToWrite, NULL, NULL); if (!NT_SUCCESS(Status)) return FALSE; *lpNumberOfCharsWritten = IoStatusBlock.Information; return TRUE; }
BOOLEAN WriteSector( HANDLE Handle, ULONG Offset, PVOID Buffer ) { IO_STATUS_BLOCK IoStatusBlock; LARGE_INTEGER ByteOffset; ByteOffset.HighPart = 0; ByteOffset.LowPart = Offset; if( !NT_SUCCESS(NtWriteFile( Handle, NULL, NULL, NULL, &IoStatusBlock, Buffer, SectorSize, &ByteOffset, NULL )) ) { return FALSE; } return TRUE; }
DWORD IHFAPI OutputConsole(LPWSTR str) { if (live) if (str) { int t, len, sum; BYTE buffer[0x80]; BYTE *buff; len = wcslen(str) << 1; t = swprintf((LPWSTR)(buffer + 8),L"%d: ",current_process_id) << 1; sum = len + t + 8; if (sum > 0x80) { buff = new BYTE[sum]; memcpy(buff + 8, buffer + 8, t); } else buff = buffer; *(DWORD*)buff = IHF_NOTIFICATION; //cmd *(DWORD*)(buff + 4) = IHF_NOTIFICATION_TEXT; //console memcpy(buff + t + 8, str, len); IO_STATUS_BLOCK ios; NtWriteFile(hPipe,0,0,0,&ios,buff,sum,0,0); if (buff!=buffer) delete buff; return len; } return 0; }
// AndyScull - for compatibility with VNR code DWORD IHFAPI ConsoleOutput(LPSTR str) { if (live) if (str) { int t, len, sum, slen; slen = strlen(str) + 1; len = MultiByteToWideChar(CP_ACP, 0, str, slen, 0, 0); wchar_t* wstr = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, str, slen, wstr, len); BYTE buffer[0x80]; BYTE *buff; len = wcslen(wstr) << 1; t = swprintf((LPWSTR)(buffer + 8),L"%d: ",current_process_id) << 1; sum = len + t + 8; if (sum > 0x80) { buff = new BYTE[sum]; memcpy(buff + 8, buffer + 8, t); } else buff = buffer; *(DWORD*)buff = IHF_NOTIFICATION; //cmd *(DWORD*)(buff + 4) = IHF_NOTIFICATION_TEXT; //console memcpy(buff + t + 8, wstr, len); IO_STATUS_BLOCK ios; NtWriteFile(hPipe,0,0,0,&ios,buff,sum,0,0); if (buff!=buffer) delete buff; delete wstr; return len; } return 0; }
/* * @implemented */ BOOL WINAPI WriteFileEx(IN HANDLE hFile, IN LPCVOID lpBuffer, IN DWORD nNumberOfBytesToWrite OPTIONAL, IN LPOVERLAPPED lpOverlapped, IN LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) { LARGE_INTEGER Offset; NTSTATUS Status; Offset.u.LowPart = lpOverlapped->Offset; Offset.u.HighPart = lpOverlapped->OffsetHigh; lpOverlapped->Internal = STATUS_PENDING; Status = NtWriteFile(hFile, NULL, ApcRoutine, lpCompletionRoutine, (PIO_STATUS_BLOCK)lpOverlapped, (PVOID)lpBuffer, nNumberOfBytesToWrite, &Offset, NULL); if (!NT_SUCCESS(Status)) { BaseSetLastNTError(Status); return FALSE; } return TRUE; }
BOOLEAN WriteTest( IN HANDLE Handle ) { IO_STATUS_BLOCK ioStatusBlock; NTSTATUS status; static ULONG messageNumber = 0; messageNumber++; sprintf( Buffer, "Sending message number %d\n", messageNumber); status = NtWriteFile ( Handle, 0L, NULL, NULL, &ioStatusBlock, Buffer, MESSAGE_SIZE, NULL, NULL); printf ("Write status = %lx\n", status ); if (NT_SUCCESS(status)) { status = NtWaitForSingleObject( Handle, TRUE, NULL ); printf( "NtWaitForSingleObject returns %lx\n", status ); status = ioStatusBlock.Status; } printf( "NtWriteFileFinalStatus returns %lx\n", status ); return ( (BOOLEAN)NT_SUCCESS( status ) ); }
static NTSTATUS Fat12WriteBootSector(IN HANDLE FileHandle, IN PFAT16_BOOT_SECTOR BootSector, IN OUT PFORMAT_CONTEXT Context) { IO_STATUS_BLOCK IoStatusBlock; NTSTATUS Status; PFAT16_BOOT_SECTOR NewBootSector; LARGE_INTEGER FileOffset; /* Allocate buffer for new bootsector */ NewBootSector = (PFAT16_BOOT_SECTOR)RtlAllocateHeap(RtlGetProcessHeap (), 0, BootSector->BytesPerSector); if (NewBootSector == NULL) return STATUS_INSUFFICIENT_RESOURCES; /* Zero the new bootsector */ RtlZeroMemory(NewBootSector, BootSector->BytesPerSector); /* Copy FAT16 BPB to new bootsector */ memcpy(&NewBootSector->OEMName[0], &BootSector->OEMName[0], FIELD_OFFSET(FAT16_BOOT_SECTOR, Res2) - FIELD_OFFSET(FAT16_BOOT_SECTOR, OEMName)); /* FAT16 BPB length (up to (not including) Res2) */ /* Write the boot sector signature */ NewBootSector->Signature1 = 0xAA550000; /* Write sector 0 */ FileOffset.QuadPart = 0ULL; Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, NewBootSector, BootSector->BytesPerSector, &FileOffset, NULL); if (!NT_SUCCESS(Status)) { DPRINT("NtWriteFile() failed (Status %lx)\n", Status); goto done; } UpdateProgress(Context, 1); done: /* Free the buffer */ RtlFreeHeap(RtlGetProcessHeap(), 0, NewBootSector); return Status; }
void RequestRefreshProfile() { if (live) { BYTE buffer[0x80]; *(DWORD*)buffer=-1; *(DWORD*)(buffer+4)=1; *(DWORD*)(buffer+8)=0; IO_STATUS_BLOCK ios; NtWriteFile(hPipe,0,0,0,&ios,buffer,HEADER_SIZE,0,0); } }
static NTSTATUS Fat32WriteFsInfo(IN HANDLE FileHandle, IN PFAT32_BOOT_SECTOR BootSector, IN OUT PFORMAT_CONTEXT Context) { IO_STATUS_BLOCK IoStatusBlock; NTSTATUS Status; PFAT32_FSINFO FsInfo; LARGE_INTEGER FileOffset; /* Allocate buffer for new sector */ FsInfo = (PFAT32_FSINFO)RtlAllocateHeap(RtlGetProcessHeap(), 0, BootSector->BytesPerSector); if (FsInfo == NULL) return STATUS_INSUFFICIENT_RESOURCES; /* Zero the new sector */ memset(FsInfo, 0, BootSector->BytesPerSector); FsInfo->LeadSig = 0x41615252; FsInfo->StrucSig = 0x61417272; FsInfo->FreeCount = 0xffffffff; FsInfo->NextFree = 0xffffffff; FsInfo->TrailSig = 0xaa550000; /* Write sector */ FileOffset.QuadPart = BootSector->FSInfoSector * BootSector->BytesPerSector; Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, FsInfo, BootSector->BytesPerSector, &FileOffset, NULL); if (!NT_SUCCESS(Status)) { DPRINT("NtWriteFile() failed (Status %lx)\n", Status); RtlFreeHeap(RtlGetProcessHeap(), 0, FsInfo); return Status; } UpdateProgress(Context, 1); /* Free the new sector buffer */ RtlFreeHeap(RtlGetProcessHeap(), 0, FsInfo); return Status; }
DWORD IHFAPI NotifyHookInsert(DWORD addr) { if (live) { BYTE buffer[0x10]; *(DWORD*)buffer=IHF_NOTIFICATION; *(DWORD*)(buffer+4)=IHF_NOTIFICATION_NEWHOOK; *(DWORD*)(buffer+8)=addr; *(DWORD*)(buffer+0xc)=0; IO_STATUS_BLOCK ios; NtWriteFile(hPipe,0,0,0,&ios,buffer,0x10,0,0); } return 0; }
IHFSERVICE DWORD IHFAPI IHF_ModifyHook(DWORD pid, HookParam* hp) { SendParam sp; HANDLE hModify,hCmd; hCmd = GetCmdHandleByPID(pid); if (hCmd == 0) return -1; hModify = IthCreateEvent(L"ITH_MODIFY_HOOK"); sp.type = IHF_COMMAND_MODIFY_HOOK; sp.hp = *hp; IO_STATUS_BLOCK ios; if (NT_SUCCESS(NtWriteFile(hCmd, 0,0,0, &ios, &sp, sizeof(SendParam), 0, 0))) NtWaitForSingleObject(hModify, 0, 0); NtClose(hModify); man -> RemoveSingleHook(pid, sp.hp.addr); return 0; }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Reads or writes specified number of sectors from/to specified buffer. // static BOOL DirectIo( PWCHAR Drive, // drive name to read/write sectors from/to PCHAR Buffer, // bufer to store the data ULONG Length, // size of the buffer ULONG LBASector, // starting LBA sector ULONG Count, // number of sectors to read/write ULONG Flags // variouse operation flags ) { BOOL Ret = FALSE; HANDLE hDrive; NTSTATUS ntStatus; OBJECT_ATTRIBUTES oa = {0}; UNICODE_STRING us; IO_STATUS_BLOCK IoStatus = {0}; LARGE_INTEGER FilePos = {0}; HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); RtlInitUnicodeString(&us, Drive); InitializeObjectAttributes(&oa, &us, OBJ_CASE_INSENSITIVE, NULL, NULL); if ((Count * BIOS_DEFAULT_SECTOR_SIZE) <= Length) { ntStatus = NtCreateFile(&hDrive, GENERIC_WRITE | GENERIC_READ, &oa, &IoStatus, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, 0, NULL, 0); if (NT_SUCCESS(ntStatus)) { FilePos.QuadPart = ((ULONGLONG)LBASector * BIOS_DEFAULT_SECTOR_SIZE); if (Flags & SCSI_IO_WRITE_SECTOR) ntStatus = NtWriteFile(hDrive, hEvent, NULL, NULL, &IoStatus, Buffer, (Count*BIOS_DEFAULT_SECTOR_SIZE), &FilePos, NULL); else ntStatus = NtReadFile(hDrive, hEvent, NULL, NULL, &IoStatus, Buffer, (Count*BIOS_DEFAULT_SECTOR_SIZE), &FilePos, NULL); if (ntStatus == STATUS_PENDING) WaitForSingleObject(hEvent, INFINITE); NtClose(hDrive); if (NT_SUCCESS(IoStatus.Status)) Ret = TRUE; } // if (hDrive != INVALID_HANDLE_VALUE) } // if ((Count * BIOS_DEFAULT_SECTOR_SIZE) <= Length) return(Ret); }
IHFSERVICE DWORD IHFAPI IHF_RemoveHook(DWORD pid, DWORD addr) { HANDLE hRemoved,hCmd; hCmd = GetCmdHandleByPID(pid); if (hCmd == 0) return -1; hRemoved = IthCreateEvent(L"ITH_REMOVE_HOOK"); SendParam sp = {}; IO_STATUS_BLOCK ios; sp.type = IHF_COMMAND_REMOVE_HOOK; sp.hp.addr = addr; //cmdq -> AddRequest(sp, pid); NtWriteFile(hCmd, 0,0,0, &ios, &sp, sizeof(SendParam),0,0); NtWaitForSingleObject(hRemoved, 0, 0); NtClose(hRemoved); man -> RemoveSingleHook(pid, sp.hp.addr); return 0; }
int json_object_to_file_ext(wchar_t *filename, struct json_object *obj, int flags) { NTSTATUS status; HANDLE fileHandle; IO_STATUS_BLOCK isb; PSTR json_str; if (!(json_str = json_object_to_json_string_ext(obj, flags))) return -1; status = PhCreateFileWin32( &fileHandle, filename, FILE_GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT ); if (!NT_SUCCESS(status)) return -1; status = NtWriteFile( fileHandle, NULL, NULL, NULL, &isb, json_str, (ULONG)strlen(json_str), NULL, NULL ); if (!NT_SUCCESS(status)) { NtClose(fileHandle); return -1; } NtClose(fileHandle); return 0; }
IHFSERVICE DWORD IHFAPI IHF_ActiveDetachProcess(DWORD pid) { DWORD module, engine, dwWrite; HANDLE hProc, hThread, hCmd; IO_STATUS_BLOCK ios; //man->LockHookman(); ProcessRecord* pr = man->GetProcessRecord(pid); hCmd = man->GetCmdHandleByPID(pid); if (pr == 0 || hCmd == 0) return FALSE; //hProc = pr->process_handle; //This handle may be closed(thus invalid) during the detach process. NtDuplicateObject(NtCurrentProcess(), pr->process_handle, NtCurrentProcess(), &hProc, 0, 0, DUPLICATE_SAME_ACCESS); //Make a copy of the process handle. module = pr->module_register; if (module == 0) return FALSE; engine = pr->engine_register; engine &= ~0xFF; SendParam sp = {}; sp.type = 4; NtWriteFile(hCmd, 0,0,0, &ios, &sp, sizeof(SendParam),0,0); //cmdq->AddRequest(sp, pid); dwWrite = 0x1000; hThread = IthCreateThread(LdrUnloadDll, engine, hProc); if (hThread == 0 || hThread == INVALID_HANDLE_VALUE) return FALSE; NtWaitForSingleObject(hThread, 0, 0); NtClose(hThread); hThread = IthCreateThread(LdrUnloadDll, module, hProc); if (hThread == 0 || hThread == INVALID_HANDLE_VALUE) return FALSE; NtWaitForSingleObject(hThread, 0, 0); //man->UnlockHookman(); THREAD_BASIC_INFORMATION info; NtQueryInformationThread(hThread, ThreadBasicInformation, &info, sizeof(info), 0); NtClose(hThread); NtSetEvent(hPipeExist, 0); FreeThreadStart(hProc); NtClose(hProc); dwWrite = 0x1000; return info.ExitStatus; }
int main() { wcscpy(path+4,GetModulePath()); LPWSTR p=path; while (*p) p++; while (*p!=L'\\') p--; p--; while (*p!=L'\\') p--; p++; wcscpy(p,L"version.h"); UNICODE_STRING us; RtlInitUnicodeString(&us,path); OBJECT_ATTRIBUTES oa={sizeof(oa),0,&us,OBJ_CASE_INSENSITIVE,0,0}; HANDLE hFile; IO_STATUS_BLOCK isb; if (!NT_SUCCESS(NtCreateFile(&hFile, FILE_SHARE_READ|FILE_WRITE_DATA|FILE_READ_ATTRIBUTES|SYNCHRONIZE ,&oa,&isb,0,0,FILE_SHARE_READ,FILE_OPEN_IF, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,0,0))) return 1; FILE_BASIC_INFORMATION basic; NtQueryInformationFile(hFile,&isb,&basic,sizeof(basic),FileBasicInformation); int l=strlen(buffer); char* ptr; ptr=buffer+l; LARGE_INTEGER current_time; TIME_FIELDS tf,ctf; NtQuerySystemTime(¤t_time); current_time.QuadPart-=GetTimeBias()->QuadPart; RtlTimeToTimeFields(¤t_time,&tf); RtlTimeToTimeFields(&basic.LastWriteTime,&ctf); if (ctf.wDay!=tf.wDay||ctf.wMonth!=tf.wMonth||ctf.wYear!=tf.wYear){ l+=sprintf(ptr,"%.4d.%.2d.%.2d)\\r\\n\";",tf.wYear,tf.wMonth,tf.wDay); NtWriteFile(hFile,0,0,0,&isb,buffer,l,0,0); } NtClose(hFile); return 0; //IthCloseSystemService(); }
int XWriteFile( int handle, void *buffer, unsigned int numberOfBytesToWrite, unsigned int *numberOfBytesWritten) { IO_STATUS_BLOCK ioStatusBlock; NTSTATUS status; #ifdef DEBUG debugPrint("XWriteFile handle=%08x numberOfBytesToWrite=%08x\n", handle, numberOfBytesToWrite); #endif if(numberOfBytesWritten) *numberOfBytesWritten = 0; status = NtWriteFile( (void*)handle, NULL, NULL, NULL, &ioStatusBlock, buffer, numberOfBytesToWrite, NULL); if (status == STATUS_PENDING) status = NtWaitForSingleObject((void*)handle, FALSE, NULL); if (!NT_SUCCESS(status)) return RtlNtStatusToDosError(status); else { if (numberOfBytesWritten) *numberOfBytesWritten = (unsigned int)ioStatusBlock.Information; return STATUS_SUCCESS; } }
IHFSERVICE DWORD IHFAPI IHF_InsertHook(DWORD pid, HookParam* hp, LPWSTR name) { InsertHookStruct s; HANDLE hCmd = man->GetCmdHandleByPID(pid); if (hCmd == 0) return -1; { s.sp.type = IHF_COMMAND_NEW_HOOK; s.sp.hp = *hp; DWORD len; if (name) len = wcslen(name) << 1; else len = 0; if (len >= IHS_BUFF_SIZE - 2) len = IHS_BUFF_SIZE - 2; memcpy(s.name_buffer, name, len); s.name_buffer[len] = 0; s.name_buffer[len + 1] = 0; IO_STATUS_BLOCK ios; NtWriteFile(hCmd, 0,0,0, &ios, &s, IHS_SIZE, 0, 0); } //memcpy(&sp.hp,hp,sizeof(HookParam)); //cmdq->AddRequest(sp, pid); return 0; }
static NTSTATUS LogfInitializeNew(PLOGFILE LogFile, ULONG ulMaxSize, ULONG ulRetention) { IO_STATUS_BLOCK IoStatusBlock; EVENTLOGEOF EofRec; NTSTATUS Status; ZeroMemory(&LogFile->Header, sizeof(EVENTLOGHEADER)); SetFilePointer(LogFile->hFile, 0, NULL, FILE_BEGIN); SetEndOfFile(LogFile->hFile); LogFile->Header.HeaderSize = sizeof(EVENTLOGHEADER); LogFile->Header.Signature = LOGFILE_SIGNATURE; LogFile->Header.MajorVersion = MAJORVER; LogFile->Header.MinorVersion = MINORVER; LogFile->Header.StartOffset = sizeof(EVENTLOGHEADER); LogFile->Header.EndOffset = sizeof(EVENTLOGHEADER); LogFile->Header.CurrentRecordNumber = 1; LogFile->Header.OldestRecordNumber = 1; LogFile->Header.MaxSize = ulMaxSize; LogFile->Header.Flags = 0; LogFile->Header.Retention = ulRetention; LogFile->Header.EndHeaderSize = sizeof(EVENTLOGHEADER); Status = NtWriteFile(LogFile->hFile, NULL, NULL, NULL, &IoStatusBlock, &LogFile->Header, sizeof(EVENTLOGHEADER), NULL, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("NtWriteFile failed (Status 0x%08lx)\n", Status); return Status; } EofRec.RecordSizeBeginning = sizeof(EVENTLOGEOF); EofRec.Ones = 0x11111111; EofRec.Twos = 0x22222222; EofRec.Threes = 0x33333333; EofRec.Fours = 0x44444444; EofRec.BeginRecord = LogFile->Header.StartOffset; EofRec.EndRecord = LogFile->Header.EndOffset; EofRec.CurrentRecordNumber = LogFile->Header.CurrentRecordNumber; EofRec.OldestRecordNumber = LogFile->Header.OldestRecordNumber; EofRec.RecordSizeEnd = sizeof(EVENTLOGEOF); Status = NtWriteFile(LogFile->hFile, NULL, NULL, NULL, &IoStatusBlock, &EofRec, sizeof(EVENTLOGEOF), NULL, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("NtWriteFile failed (Status 0x%08lx)\n", Status); return Status; } Status = NtFlushBuffersFile(LogFile->hFile, &IoStatusBlock); if (!NT_SUCCESS(Status)) { DPRINT1("NtFlushBuffersFile failed (Status 0x%08lx)\n", Status); return Status; } return STATUS_SUCCESS; }
NTSTATUS LogfBackupFile(PLOGFILE LogFile, PUNICODE_STRING BackupFileName) { OBJECT_ATTRIBUTES ObjectAttributes; IO_STATUS_BLOCK IoStatusBlock; EVENTLOGHEADER Header; EVENTLOGEOF EofRec; HANDLE FileHandle = NULL; ULONG i; LARGE_INTEGER FileOffset; NTSTATUS Status; PUCHAR Buffer = NULL; DWORD dwOffset, dwRead, dwRecSize; DPRINT1("LogfBackupFile(%p, %wZ)\n", LogFile, BackupFileName); /* Lock the log file shared */ RtlAcquireResourceShared(&LogFile->Lock, TRUE); InitializeObjectAttributes(&ObjectAttributes, BackupFileName, OBJ_CASE_INSENSITIVE, NULL, NULL); Status = NtCreateFile(&FileHandle, GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, &ObjectAttributes, &IoStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE, FILE_WRITE_THROUGH | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (!NT_SUCCESS(Status)) { DPRINT("Can't create backup file %wZ (Status: 0x%08lx)\n", BackupFileName, Status); goto Done; } /* Initialize the (dirty) log file header */ Header.HeaderSize = sizeof(EVENTLOGHEADER); Header.Signature = LOGFILE_SIGNATURE; Header.MajorVersion = MAJORVER; Header.MinorVersion = MINORVER; Header.StartOffset = sizeof(EVENTLOGHEADER); Header.EndOffset = sizeof(EVENTLOGHEADER); Header.CurrentRecordNumber = 1; Header.OldestRecordNumber = 1; Header.MaxSize = LogFile->Header.MaxSize; Header.Flags = ELF_LOGFILE_HEADER_DIRTY; Header.Retention = LogFile->Header.Retention; Header.EndHeaderSize = sizeof(EVENTLOGHEADER); /* Write the (dirty) log file header */ Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, &Header, sizeof(EVENTLOGHEADER), NULL, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("Failed to write the log file header (Status: 0x%08lx)\n", Status); goto Done; } for (i = LogFile->Header.OldestRecordNumber; i < LogFile->Header.CurrentRecordNumber; i++) { dwOffset = LogfOffsetByNumber(LogFile, i); if (dwOffset == 0) break; if (SetFilePointer(LogFile->hFile, dwOffset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { DPRINT1("SetFilePointer() failed!\n"); goto Done; } if (!ReadFile(LogFile->hFile, &dwRecSize, sizeof(DWORD), &dwRead, NULL)) { DPRINT1("ReadFile() failed!\n"); goto Done; } if (SetFilePointer(LogFile->hFile, dwOffset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { DPRINT1("SetFilePointer() failed!\n"); goto Done; } Buffer = HeapAlloc(MyHeap, 0, dwRecSize); if (Buffer == NULL) { DPRINT1("HeapAlloc() failed!\n"); goto Done; } if (!ReadFile(LogFile->hFile, Buffer, dwRecSize, &dwRead, NULL)) { DPRINT1("ReadFile() failed!\n"); goto Done; } /* Write the event record */ Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, Buffer, dwRecSize, NULL, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("NtWriteFile() failed! (Status: 0x%08lx)\n", Status); goto Done; } /* Update the header information */ Header.EndOffset += dwRecSize; /* Free the buffer */ HeapFree(MyHeap, 0, Buffer); Buffer = NULL; } /* Initialize the EOF record */ EofRec.RecordSizeBeginning = sizeof(EVENTLOGEOF); EofRec.Ones = 0x11111111; EofRec.Twos = 0x22222222; EofRec.Threes = 0x33333333; EofRec.Fours = 0x44444444; EofRec.BeginRecord = sizeof(EVENTLOGHEADER); EofRec.EndRecord = Header.EndOffset; EofRec.CurrentRecordNumber = LogFile->Header.CurrentRecordNumber; EofRec.OldestRecordNumber = LogFile->Header.OldestRecordNumber; EofRec.RecordSizeEnd = sizeof(EVENTLOGEOF); /* Write the EOF record */ Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, &EofRec, sizeof(EVENTLOGEOF), NULL, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("NtWriteFile() failed!\n"); goto Done; } /* Update the header information */ Header.CurrentRecordNumber = LogFile->Header.CurrentRecordNumber; Header.OldestRecordNumber = LogFile->Header.OldestRecordNumber; Header.MaxSize = Header.EndOffset + sizeof(EVENTLOGEOF); Header.Flags = 0; /* Write the (clean) log file header */ FileOffset.QuadPart = 0; Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, &Header, sizeof(EVENTLOGHEADER), &FileOffset, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("NtWriteFile() failed! (Status: 0x%08lx)\n", Status); } Done: /* Free the buffer */ if (Buffer != NULL) HeapFree(MyHeap, 0, Buffer); /* Close the backup file */ if (FileHandle != NULL) NtClose(FileHandle); /* Unlock the log file */ RtlReleaseResource(&LogFile->Lock); return Status; }
VOID Create( IN PCHAR FileName, IN ULONG FileTime, IN ULONG FileCount ) { NTSTATUS Status; HANDLE FileHandle; OBJECT_ATTRIBUTES ObjectAttributes; STRING NameString; IO_STATUS_BLOCK IoStatus; LARGE_INTEGER AllocationSize; LARGE_INTEGER ByteOffset; ULONG Count; ULONG Pattern[3]; // // Get the filename // simprintf("Create ", 0); simprintf(FileName, 0); simprintf("\n", 0); // // Create the new file // AllocationSize = LiFromUlong( FileCount * 4 ); RtlInitString( &NameString, FileName ); InitializeObjectAttributes( &ObjectAttributes, &NameString, 0, NULL, NULL ); if (!NT_SUCCESS(Status = NtCreateFile( &FileHandle, FILE_WRITE_DATA | SYNCHRONIZE, &ObjectAttributes, &IoStatus, &AllocationSize, FILE_ATTRIBUTE_NORMAL, 0L, FILE_SUPERSEDE, WriteThrough, (PVOID)NULL, 0L ))) { CreateFileError( Status , FileName ); return; } // // The main loop writes out the test pattern our test pattern // is <FileTime> <FileSize> <Count> where count is the current // iteration count for the current test pattern output. // Pattern[0] = FileTime; Pattern[1] = FileCount; for (Count = 0; Count < FileCount; Count += 1) { Pattern[2] = Count; ByteOffset = LiFromUlong( Count * 3 * 4 ); if (!NT_SUCCESS(Status = NtWriteFile( FileHandle, (HANDLE)NULL, (PIO_APC_ROUTINE)NULL, (PVOID)NULL, &IoStatus, Pattern, 3 * 4, &ByteOffset, (PULONG) NULL ))) { WriteFileError( Status ); return; } if (!NT_SUCCESS(Status = NtWaitForSingleObject(FileHandle, TRUE, NULL))) { WaitForSingleObjectError( Status ); return; } // // check how the write turned out // CheckIoStatus( &IoStatus, 3 * 4, FALSE ); if (!NT_SUCCESS(IoStatus.Status)) { IoStatusError( IoStatus.Status ); break; } } // // Now close the file // if (!NT_SUCCESS(Status = NtClose( FileHandle ))) { CloseError( Status ); } // // And return to our caller // return; }
NTSTATUS IniCacheSave( PINICACHE Cache, PWCHAR FileName) { UNICODE_STRING Name; PINICACHESECTION Section; PINICACHEKEY Key; ULONG BufferSize; PCHAR Buffer; PCHAR Ptr; ULONG Len; NTSTATUS Status; OBJECT_ATTRIBUTES ObjectAttributes; IO_STATUS_BLOCK IoStatusBlock; LARGE_INTEGER Offset; HANDLE FileHandle; /* Calculate required buffer size */ BufferSize = 0; Section = Cache->FirstSection; while (Section != NULL) { BufferSize += (Section->Name ? wcslen(Section->Name) : 0) + 4; /* "[]\r\n" */ Key = Section->FirstKey; while (Key != NULL) { BufferSize += wcslen(Key->Name) + (Key->Data ? wcslen(Key->Data) : 0) + 3; /* "=\r\n" */ Key = Key->Next; } Section = Section->Next; if (Section != NULL) BufferSize += 2; /* extra "\r\n" at end of each section */ } BufferSize++; /* Null-terminator */ DPRINT("BufferSize: %lu\n", BufferSize); /* Allocate file buffer */ Buffer = (CHAR*)RtlAllocateHeap(ProcessHeap, 0, BufferSize); if (Buffer == NULL) { DPRINT1("RtlAllocateHeap() failed\n"); return STATUS_INSUFFICIENT_RESOURCES; } RtlZeroMemory(Buffer, BufferSize); /* Fill file buffer */ Ptr = Buffer; Section = Cache->FirstSection; while (Section != NULL) { Len = sprintf(Ptr, "[%S]\r\n", Section->Name); Ptr += Len; Key = Section->FirstKey; while (Key != NULL) { Len = sprintf(Ptr, "%S=%S\r\n", Key->Name, Key->Data); Ptr += Len; Key = Key->Next; } Section = Section->Next; if (Section != NULL) { Len = sprintf(Ptr, "\r\n"); Ptr += Len; } } /* Create ini file */ RtlInitUnicodeString(&Name, FileName); InitializeObjectAttributes(&ObjectAttributes, &Name, 0, NULL, NULL); Status = NtCreateFile(&FileHandle, GENERIC_WRITE | SYNCHRONIZE, &ObjectAttributes, &IoStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_SUPERSEDE, FILE_SYNCHRONOUS_IO_NONALERT | FILE_SEQUENTIAL_ONLY, NULL, 0); if (!NT_SUCCESS(Status)) { DPRINT("NtCreateFile() failed (Status %lx)\n", Status); RtlFreeHeap(ProcessHeap, 0, Buffer); return Status; } Offset.QuadPart = 0LL; Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, Buffer, BufferSize, &Offset, NULL); if (!NT_SUCCESS(Status)) { DPRINT("NtWriteFile() failed (Status %lx)\n", Status); NtClose(FileHandle); RtlFreeHeap(ProcessHeap, 0, Buffer); return Status; } NtClose(FileHandle); RtlFreeHeap(ProcessHeap, 0, Buffer); return STATUS_SUCCESS; }
NTSTATUS SetupCopyFile( PWCHAR SourceFileName, PWCHAR DestinationFileName) { OBJECT_ATTRIBUTES ObjectAttributes; HANDLE FileHandleSource; HANDLE FileHandleDest; static IO_STATUS_BLOCK IoStatusBlock; FILE_STANDARD_INFORMATION FileStandard; FILE_BASIC_INFORMATION FileBasic; ULONG RegionSize; UNICODE_STRING FileName; NTSTATUS Status; PVOID SourceFileMap = 0; HANDLE SourceFileSection; SIZE_T SourceSectionSize = 0; LARGE_INTEGER ByteOffset; #ifdef __REACTOS__ RtlInitUnicodeString(&FileName, SourceFileName); InitializeObjectAttributes(&ObjectAttributes, &FileName, OBJ_CASE_INSENSITIVE, NULL, NULL); Status = NtOpenFile(&FileHandleSource, GENERIC_READ, &ObjectAttributes, &IoStatusBlock, FILE_SHARE_READ, FILE_SEQUENTIAL_ONLY); if (!NT_SUCCESS(Status)) { DPRINT1("NtOpenFile failed: %x, %wZ\n", Status, &FileName); goto done; } #else FileHandleSource = CreateFileW(SourceFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (FileHandleSource == INVALID_HANDLE_VALUE) { Status = STATUS_UNSUCCESSFUL; goto done; } #endif Status = NtQueryInformationFile(FileHandleSource, &IoStatusBlock, &FileStandard, sizeof(FILE_STANDARD_INFORMATION), FileStandardInformation); if (!NT_SUCCESS(Status)) { DPRINT1("NtQueryInformationFile failed: %x\n", Status); goto closesrc; } Status = NtQueryInformationFile(FileHandleSource, &IoStatusBlock,&FileBasic, sizeof(FILE_BASIC_INFORMATION), FileBasicInformation); if (!NT_SUCCESS(Status)) { DPRINT1("NtQueryInformationFile failed: %x\n", Status); goto closesrc; } Status = NtCreateSection(&SourceFileSection, SECTION_MAP_READ, NULL, NULL, PAGE_READONLY, SEC_COMMIT, FileHandleSource); if (!NT_SUCCESS(Status)) { DPRINT1("NtCreateSection failed: %x, %S\n", Status, SourceFileName); goto closesrc; } Status = NtMapViewOfSection(SourceFileSection, NtCurrentProcess(), &SourceFileMap, 0, 0, NULL, &SourceSectionSize, ViewUnmap, 0, PAGE_READONLY ); if (!NT_SUCCESS(Status)) { DPRINT1("NtMapViewOfSection failed: %x, %S\n", Status, SourceFileName); goto closesrcsec; } RtlInitUnicodeString(&FileName, DestinationFileName); InitializeObjectAttributes(&ObjectAttributes, &FileName, OBJ_CASE_INSENSITIVE, NULL, NULL); Status = NtCreateFile(&FileHandleDest, GENERIC_WRITE | SYNCHRONIZE, &ObjectAttributes, &IoStatusBlock, NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_OVERWRITE_IF, FILE_NO_INTERMEDIATE_BUFFERING | FILE_SEQUENTIAL_ONLY | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (!NT_SUCCESS(Status)) { DPRINT1("NtCreateFile failed: %x\n", Status); goto unmapsrcsec; } RegionSize = (ULONG)PAGE_ROUND_UP(FileStandard.EndOfFile.u.LowPart); IoStatusBlock.Status = 0; ByteOffset.QuadPart = 0; Status = NtWriteFile(FileHandleDest, NULL, NULL, NULL, &IoStatusBlock, SourceFileMap, RegionSize, &ByteOffset, NULL); if (!NT_SUCCESS(Status)) { DPRINT1("NtWriteFile failed: %x:%x, iosb: %p src: %p, size: %x\n", Status, IoStatusBlock.Status, &IoStatusBlock, SourceFileMap, RegionSize); goto closedest; } /* Copy file date/time from source file */ Status = NtSetInformationFile(FileHandleDest, &IoStatusBlock, &FileBasic, sizeof(FILE_BASIC_INFORMATION), FileBasicInformation); if (!NT_SUCCESS(Status)) { DPRINT1("NtSetInformationFile failed: %x\n", Status); goto closedest; } /* shorten the file back to it's real size after completing the write */ Status = NtSetInformationFile(FileHandleDest, &IoStatusBlock, &FileStandard.EndOfFile, sizeof(FILE_END_OF_FILE_INFORMATION), FileEndOfFileInformation); if (!NT_SUCCESS(Status)) { DPRINT1("NtSetInformationFile failed: %x\n", Status); } closedest: NtClose(FileHandleDest); unmapsrcsec: NtUnmapViewOfSection(NtCurrentProcess(), SourceFileMap); closesrcsec: NtClose(SourceFileSection); closesrc: NtClose(FileHandleSource); done: return Status; }
NTSTATUS dumpEatEntriesToDefFile(PVOID pEatEntryList, ULONGLONG listBufferSize, PUCHAR pModuleName){ OBJECT_ATTRIBUTES defFileAttr; UNICODE_STRING uDefFileName; IO_STATUS_BLOCK ioSb; NTSTATUS status, fatalStatus = STATUS_CLUSTER_NETINTERFACE_EXISTS; PCHAR pDefPreamble = NULL; ///Keep it simple. We can't allocate less than 4 kB using NtXxx funcs anyway, ///so just allocate 4 kB although we never will need that much. ULONGLONG defPreambleSize = PAGE_SIZE; HANDLE hDefFile = NULL; HANDLE hParentDir = NULL; ///Quite some ugly hacking... char szDefPreamblePart[] = { 0x0D, 0x0A, 0x0D, 0x0A, 'E', 'X', 'P', 'O', 'R', 'T', 'S', 0x0D, 0x0A, 0x0 }; status = NtAllocateVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, 0, &defPreambleSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (status) return status; status = RtlStringCbPrintfA(pDefPreamble, defPreambleSize, "LIBRARY %s%s", pModuleName, szDefPreamblePart); if (status){ fatalStatus = NtFreeVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, &defPreambleSize, MEM_RELEASE); if (fatalStatus) mydie(status, fatalStatus); return status; } status = RtlStringCbLengthA(pDefPreamble, defPreambleSize, &defPreambleSize); if (status){ fatalStatus = NtFreeVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, &defPreambleSize, MEM_RELEASE); if (fatalStatus) mydie(status, fatalStatus); return status; } hParentDir = NtCurrentPeb()->ProcessParameters->CurrentDirectory.Handle; RtlInitUnicodeString(&uDefFileName, L"exports.def"); InitializeObjectAttributes(&defFileAttr, &uDefFileName, OBJ_CASE_INSENSITIVE, hParentDir, NULL); status = NtCreateFile(&hDefFile, FILE_ALL_ACCESS | SYNCHRONIZE, &defFileAttr, &ioSb, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_SUPERSEDE, FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE, NULL, 0); if (status){ fatalStatus = NtFreeVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, &defPreambleSize, MEM_RELEASE); if (fatalStatus) mydie(status, fatalStatus); return status; } status = NtWriteFile(hDefFile, NULL, NULL, NULL, &ioSb, pDefPreamble, (ULONG)defPreambleSize, NULL, NULL); if (!status) status = NtWriteFile(hDefFile, NULL, NULL, NULL, &ioSb, pEatEntryList, (ULONG)listBufferSize, NULL, NULL); fatalStatus = NtClose(hDefFile); if (fatalStatus) mydie(status, fatalStatus); fatalStatus = NtFreeVirtualMemory(INVALID_HANDLE_VALUE, &pDefPreamble, &defPreambleSize, MEM_RELEASE); if (fatalStatus) mydie(status, fatalStatus); return status; }
static NTSTATUS DownloadUpdateThreadStart( __in PVOID Parameter ) { PPH_STRING downloadUrlPath = NULL; HANDLE tempFileHandle = NULL; HINTERNET hInitialize = NULL, hConnection = NULL, hRequest = NULL; NTSTATUS status = STATUS_UNSUCCESSFUL; HWND hwndDlg = (HWND)Parameter; Button_Enable(GetDlgItem(hwndDlg, IDC_DOWNLOAD), FALSE); SetDlgItemText(hwndDlg, IDC_STATUS, L"Initializing"); // Reset the progress state on Vista and above. if (WindowsVersion > WINDOWS_XP) SendDlgItemMessage(hwndDlg, IDC_PROGRESS, PBM_SETSTATE, PBST_NORMAL, 0L); if (!ConnectionAvailable()) return status; __try { // Get temp dir. WCHAR tempPathString[MAX_PATH]; DWORD tempPathLength = GetTempPath(MAX_PATH, tempPathString); if (tempPathLength == 0 || tempPathLength > MAX_PATH) { LogEvent(hwndDlg, PhFormatString(L"CreateFile failed (%d)", GetLastError())); __leave; } // create the download path string. downloadUrlPath = PhFormatString( L"/projects/processhacker/files/processhacker2/processhacker-%u.%u-setup.exe/download?use_mirror=autoselect", /* ?use_mirror=waix" */ UpdateData.MajorVersion, UpdateData.MinorVersion ); // Append the tempath to our string: %TEMP%processhacker-%u.%u-setup.exe // Example: C:\\Users\\dmex\\AppData\\Temp\\processhacker-2.10-setup.exe SetupFilePath = PhFormatString( L"%sprocesshacker-%u.%u-setup.exe", tempPathString, UpdateData.MajorVersion, UpdateData.MinorVersion ); // Create output file status = PhCreateFileWin32( &tempFileHandle, SetupFilePath->Buffer, FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | FILE_ATTRIBUTE_TEMPORARY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT ); if (!NT_SUCCESS(status)) { LogEvent(hwndDlg, PhFormatString(L"PhCreateFileWin32 failed (%s)", ((PPH_STRING)PHA_DEREFERENCE(PhGetNtMessage(status)))->Buffer)); __leave; } { // Create a user agent string. PPH_STRING phVersion = PhGetPhVersion(); PPH_STRING userAgent = PhConcatStrings2(L"PH Updater v", phVersion->Buffer); // Initialize the wininet library. if (!(hInitialize = InternetOpen( userAgent->Buffer, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ))) { LogEvent(hwndDlg, PhFormatString(L"Updater: (InitializeConnection) InternetOpen failed (%d)", GetLastError())); PhDereferenceObject(userAgent); PhDereferenceObject(phVersion); __leave; } PhDereferenceObject(userAgent); PhDereferenceObject(phVersion); } // Connect to the server. if (!(hConnection = InternetConnect( hInitialize, L"sourceforge.net", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0))) { LogEvent(hwndDlg, PhFormatString(L"InternetConnect failed (%d)", GetLastError())); __leave; } // Open the HTTP request. if (!(hRequest = HttpOpenRequest( hConnection, NULL, downloadUrlPath->Buffer, NULL, NULL, NULL, INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RESYNCHRONIZE, 0 ))) { LogEvent(hwndDlg, PhFormatString(L"HttpOpenRequest failed (%d)", GetLastError())); __leave; } SetDlgItemText(hwndDlg, IDC_STATUS, L"Connecting"); // Send the HTTP request. if (!HttpSendRequest(hRequest, NULL, 0, NULL, 0)) { LogEvent(hwndDlg, PhFormatString(L"HttpSendRequest failed (%d)", GetLastError())); // Enable the 'Retry' button. Button_Enable(GetDlgItem(hwndDlg, IDC_DOWNLOAD), TRUE); SetDlgItemText(hwndDlg, IDC_DOWNLOAD, L"Retry"); // Reset the state and let user retry the download. PhUpdaterState = Download; } else { BYTE hashBuffer[20]; DWORD contentLengthSize = sizeof(DWORD); PH_HASH_CONTEXT hashContext; // Initialize hash algorithm. PhInitializeHash(&hashContext, Sha1HashAlgorithm); if (!HttpQueryInfoW(hRequest, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &contentLength, &contentLengthSize, 0)) { // No content length...impossible to calculate % complete... // we can read the data, BUT in this instance Sourceforge always returns the content length // so instead we'll exit here instead of downloading the file. LogEvent(hwndDlg, PhFormatString(L"HttpQueryInfo failed (%d)", GetLastError())); __leave; } else { BYTE buffer[PAGE_SIZE]; DWORD bytesRead = 0, startTick = 0; IO_STATUS_BLOCK isb; // Zero the buffer. ZeroMemory(buffer, PAGE_SIZE); // Reset the counters. bytesDownloaded = 0, timeTransferred = 0, LastUpdateTime = 0; IsUpdating = FALSE; // Start the clock. startTick = GetTickCount(); timeTransferred = startTick; // Download the data. while (InternetReadFile(hRequest, buffer, PAGE_SIZE, &bytesRead)) { // If we get zero bytes, the file was uploaded or there was an error. if (bytesRead == 0) break; // If window closed and thread handle was closed, just dispose and exit. // (This also skips error checking/prompts and updating the disposed UI) if (!DownloadThreadHandle) __leave; // Update the hash of bytes we downloaded. PhUpdateHash(&hashContext, buffer, bytesRead); // Write the downloaded bytes to disk. status = NtWriteFile( tempFileHandle, NULL, NULL, NULL, &isb, buffer, bytesRead, NULL, NULL ); if (!NT_SUCCESS(status)) { PPH_STRING message = PhGetNtMessage(status); LogEvent(hwndDlg, PhFormatString(L"NtWriteFile failed (%s)", message->Buffer)); PhDereferenceObject(message); break; } // Check dwBytesRead are the same dwBytesWritten length returned by WriteFile. if (bytesRead != isb.Information) { PPH_STRING message = PhGetNtMessage(status); LogEvent(hwndDlg, PhFormatString(L"NtWriteFile failed (%s)", message->Buffer)); PhDereferenceObject(message); break; } // Update our total bytes downloaded PhAcquireQueuedLockExclusive(&Lock); bytesDownloaded += (DWORD)isb.Information; PhReleaseQueuedLockExclusive(&Lock); AsyncUpdate(); } // Check if we downloaded the entire file. assert(bytesDownloaded == contentLength); // Compute our hash result. if (PhFinalHash(&hashContext, &hashBuffer, 20, NULL)) { // Allocate our hash string, hex the final hash result in our hashBuffer. PPH_STRING hexString = PhBufferToHexString(hashBuffer, 20); if (PhEqualString(hexString, UpdateData.Hash, TRUE)) { // If PH is not elevated, set the UAC shield for the install button as the setup requires elevation. if (!PhElevated) SendMessage(GetDlgItem(hwndDlg, IDC_DOWNLOAD), BCM_SETSHIELD, 0, TRUE); // Set the download result, don't include hash status since it succeeded. //SetDlgItemText(hwndDlg, IDC_STATUS, L"Download Complete"); // Set button text for next action Button_SetText(GetDlgItem(hwndDlg, IDC_DOWNLOAD), L"Install"); // Enable the Install button Button_Enable(GetDlgItem(hwndDlg, IDC_DOWNLOAD), TRUE); // Hash succeeded, set state as ready to install. PhUpdaterState = Install; } else { if (WindowsVersion > WINDOWS_XP) SendDlgItemMessage(hwndDlg, IDC_PROGRESS, PBM_SETSTATE, PBST_ERROR, 0L); SetDlgItemText(hwndDlg, IDC_STATUS, L"Download complete, SHA1 Hash failed."); // Set button text for next action Button_SetText(GetDlgItem(hwndDlg, IDC_DOWNLOAD), L"Retry"); // Enable the Install button Button_Enable(GetDlgItem(hwndDlg, IDC_DOWNLOAD), TRUE); // Hash failed, reset state to downloading so user can redownload the file. PhUpdaterState = Download; } PhDereferenceObject(hexString); } else { //SetDlgItemText(hwndDlg, IDC_STATUS, L"PhFinalHash failed"); // Show fancy Red progressbar if hash failed on Vista and above. if (WindowsVersion > WINDOWS_XP) SendDlgItemMessage(hwndDlg, IDC_PROGRESS, PBM_SETSTATE, PBST_ERROR, 0L); } } } status = STATUS_SUCCESS; } __finally { if (hInitialize) { InternetCloseHandle(hInitialize); hInitialize = NULL; } if (hConnection) { InternetCloseHandle(hConnection); hConnection = NULL; } if (hRequest) { InternetCloseHandle(hRequest); hRequest = NULL; } if (tempFileHandle) { NtClose(tempFileHandle); tempFileHandle = NULL; } if (downloadUrlPath) { PhDereferenceObject(downloadUrlPath); downloadUrlPath = NULL; } } return status; }
static NTSTATUS Fat32WriteRootDirectory(IN HANDLE FileHandle, IN PFAT32_BOOT_SECTOR BootSector, IN OUT PFORMAT_CONTEXT Context) { IO_STATUS_BLOCK IoStatusBlock; NTSTATUS Status; PUCHAR Buffer; LARGE_INTEGER FileOffset; ULONGLONG FirstDataSector; ULONGLONG FirstRootDirSector; /* Allocate buffer for the cluster */ Buffer = (PUCHAR)RtlAllocateHeap(RtlGetProcessHeap(), 0, BootSector->SectorsPerCluster * BootSector->BytesPerSector); if (Buffer == NULL) return STATUS_INSUFFICIENT_RESOURCES; /* Zero the buffer */ memset(Buffer, 0, BootSector->SectorsPerCluster * BootSector->BytesPerSector); DPRINT("BootSector->ReservedSectors = %lu\n", BootSector->ReservedSectors); DPRINT("BootSector->FATSectors32 = %lu\n", BootSector->FATSectors32); DPRINT("BootSector->RootCluster = %lu\n", BootSector->RootCluster); DPRINT("BootSector->SectorsPerCluster = %lu\n", BootSector->SectorsPerCluster); /* Write cluster */ FirstDataSector = BootSector->ReservedSectors + (BootSector->FATCount * BootSector->FATSectors32) + 0 /* RootDirSectors */; DPRINT("FirstDataSector = %lu\n", FirstDataSector); FirstRootDirSector = ((BootSector->RootCluster - 2) * BootSector->SectorsPerCluster) + FirstDataSector; FileOffset.QuadPart = FirstRootDirSector * BootSector->BytesPerSector; DPRINT("FirstRootDirSector = %lu\n", FirstRootDirSector); DPRINT("FileOffset = %lu\n", FileOffset.QuadPart); Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, Buffer, BootSector->SectorsPerCluster * BootSector->BytesPerSector, &FileOffset, NULL); if (!NT_SUCCESS(Status)) { DPRINT("NtWriteFile() failed (Status %lx)\n", Status); RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer); return Status; } UpdateProgress(Context, (ULONG)BootSector->SectorsPerCluster); /* Free the buffer */ RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer); return Status; }
/* * @implemented */ BOOL WINAPI WriteFile(IN HANDLE hFile, IN LPCVOID lpBuffer, IN DWORD nNumberOfBytesToWrite OPTIONAL, OUT LPDWORD lpNumberOfBytesWritten OPTIONAL, IN LPOVERLAPPED lpOverlapped OPTIONAL) { NTSTATUS Status; TRACE("WriteFile(hFile %p)\n", hFile); if (lpNumberOfBytesWritten != NULL) *lpNumberOfBytesWritten = 0; hFile = TranslateStdHandle(hFile); if (IsConsoleHandle(hFile)) { return WriteConsoleA(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); } if (lpOverlapped != NULL) { LARGE_INTEGER Offset; PVOID ApcContext; Offset.u.LowPart = lpOverlapped->Offset; Offset.u.HighPart = lpOverlapped->OffsetHigh; lpOverlapped->Internal = STATUS_PENDING; ApcContext = (((ULONG_PTR)lpOverlapped->hEvent & 0x1) ? NULL : lpOverlapped); Status = NtWriteFile(hFile, lpOverlapped->hEvent, NULL, ApcContext, (PIO_STATUS_BLOCK)lpOverlapped, (PVOID)lpBuffer, nNumberOfBytesToWrite, &Offset, NULL); /* return FALSE in case of failure and pending operations! */ if (!NT_SUCCESS(Status) || Status == STATUS_PENDING) { BaseSetLastNTError(Status); return FALSE; } if (lpNumberOfBytesWritten != NULL) *lpNumberOfBytesWritten = lpOverlapped->InternalHigh; } else { IO_STATUS_BLOCK Iosb; Status = NtWriteFile(hFile, NULL, NULL, NULL, &Iosb, (PVOID)lpBuffer, nNumberOfBytesToWrite, NULL, NULL); /* Wait in case operation is pending */ if (Status == STATUS_PENDING) { Status = NtWaitForSingleObject(hFile, FALSE, NULL); if (NT_SUCCESS(Status)) Status = Iosb.Status; } if (NT_SUCCESS(Status)) { /* * lpNumberOfBytesWritten must not be NULL here, in fact Win doesn't * check that case either and crashes (only after the operation * completed). */ *lpNumberOfBytesWritten = Iosb.Information; } else { BaseSetLastNTError(Status); return FALSE; } } TRACE("WriteFile() succeeded\n"); return TRUE; }
DWORD WINAPI WaitForPipe(LPVOID lpThreadParameter) //Dynamic detect ITH main module status. { int i; TextHook *man; struct { DWORD pid; TextHook *man; DWORD module; DWORD engine; } u; HANDLE hMutex,hPipeExist; //swprintf(engine_event,L"ITH_ENGINE_%d",current_process_id); swprintf(detach_mutex,L"ITH_DETACH_%d",current_process_id); //swprintf(lose_event,L"ITH_LOSEPIPE_%d",current_process_id); //hEngine=IthCreateEvent(engine_event); //NtWaitForSingleObject(hEngine,0,0); //NtClose(hEngine); while (engine_base == 0) NtDelayExecution(0, &wait_time); //LoadEngine(L"ITH_Engine.dll"); u.module=module_base; u.pid=current_process_id; u.man=hookman; u.engine=engine_base; hPipeExist=IthOpenEvent(exist); IO_STATUS_BLOCK ios; //hLose=IthCreateEvent(lose_event,0,0); if (hPipeExist!=INVALID_HANDLE_VALUE) while (running) { hPipe=INVALID_HANDLE_VALUE; hCommand=INVALID_HANDLE_VALUE; while (NtWaitForSingleObject(hPipeExist,0,&wait_time)==WAIT_TIMEOUT) if (!running) goto _release; hMutex=IthCreateMutex(mutex,0); NtWaitForSingleObject(hMutex,0,0); while (hPipe==INVALID_HANDLE_VALUE|| hCommand==INVALID_HANDLE_VALUE) { NtDelayExecution(0,&sleep_time); if (hPipe==INVALID_HANDLE_VALUE) hPipe=IthOpenPipe(recv_pipe,GENERIC_WRITE); if (hCommand==INVALID_HANDLE_VALUE) hCommand=IthOpenPipe(command,GENERIC_READ); } //NtClearEvent(hLose); NtWriteFile(hPipe,0,0,0,&ios,&u,16,0,0); live=true; for (man=hookman,i=0;i<current_hook;man++) if (man->RecoverHook()) i++; OutputConsole(dll_name); OutputConsole(L"Pipe connected."); //OutputDWORD(tree->Count()); NtReleaseMutant(hMutex,0); NtClose(hMutex); if (!hook_inserted && engine_base) { hook_inserted=true; IdentifyEngine(); } hDetach=IthCreateMutex(detach_mutex,1); while (running&&NtWaitForSingleObject(hPipeExist,0,&sleep_time)==WAIT_OBJECT_0) NtDelayExecution(0,&sleep_time); live=false; for (man=hookman,i=0;i<current_hook;man++) if (man->RemoveHook()) i++; if (!running) { NtWriteFile(hPipe,0,0,0,&ios,man,4,0,0); IthReleaseMutex(hDetach); } NtClose(hDetach); NtClose(hPipe); } _release: //NtClose(hLose); NtClose(hPipeExist); return 0; }
static NTSTATUS Fat32WipeSectors( IN HANDLE FileHandle, IN PFAT32_BOOT_SECTOR BootSector, IN OUT PFORMAT_CONTEXT Context) { IO_STATUS_BLOCK IoStatusBlock; PUCHAR Buffer; LARGE_INTEGER FileOffset; ULONGLONG Sector; ULONG Length; NTSTATUS Status; /* Allocate buffer for the cluster */ Buffer = (PUCHAR)RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, BootSector->SectorsPerCluster * BootSector->BytesPerSector); if (Buffer == NULL) return STATUS_INSUFFICIENT_RESOURCES; Sector = 0; Length = BootSector->SectorsPerCluster * BootSector->BytesPerSector; while (Sector + BootSector->SectorsPerCluster < BootSector->SectorsHuge) { FileOffset.QuadPart = Sector * BootSector->BytesPerSector; Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, Buffer, Length, &FileOffset, NULL); if (!NT_SUCCESS(Status)) { DPRINT("NtWriteFile() failed (Status %lx)\n", Status); goto done; } UpdateProgress(Context, (ULONG)BootSector->SectorsPerCluster); Sector += BootSector->SectorsPerCluster; } if (Sector + BootSector->SectorsPerCluster > BootSector->SectorsHuge) { DPRINT("Remaining sectors %lu\n", BootSector->SectorsHuge - Sector); FileOffset.QuadPart = Sector * BootSector->BytesPerSector; Length = (BootSector->SectorsHuge - Sector) * BootSector->BytesPerSector; Status = NtWriteFile(FileHandle, NULL, NULL, NULL, &IoStatusBlock, Buffer, Length, &FileOffset, NULL); if (!NT_SUCCESS(Status)) { DPRINT("NtWriteFile() failed (Status %lx)\n", Status); goto done; } UpdateProgress(Context, BootSector->SectorsHuge - Sector); } done: /* Free the buffer */ RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer); return Status; }