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); } }
/****************************************************************** * ENV_CopyStartupInformation (internal) * * Creates the STARTUPINFO information from the ntdll information */ void ENV_CopyStartupInformation(void) { RTL_USER_PROCESS_PARAMETERS* rupp; ANSI_STRING ansi; RtlAcquirePebLock(); rupp = NtCurrentTeb()->Peb->ProcessParameters; startup_infoW.cb = sizeof(startup_infoW); startup_infoW.lpReserved = NULL; startup_infoW.lpDesktop = rupp->Desktop.Buffer; startup_infoW.lpTitle = rupp->WindowTitle.Buffer; startup_infoW.dwX = rupp->dwX; startup_infoW.dwY = rupp->dwY; startup_infoW.dwXSize = rupp->dwXSize; startup_infoW.dwYSize = rupp->dwYSize; startup_infoW.dwXCountChars = rupp->dwXCountChars; startup_infoW.dwYCountChars = rupp->dwYCountChars; startup_infoW.dwFillAttribute = rupp->dwFillAttribute; startup_infoW.dwFlags = rupp->dwFlags; startup_infoW.wShowWindow = rupp->wShowWindow; startup_infoW.cbReserved2 = rupp->RuntimeInfo.MaximumLength; startup_infoW.lpReserved2 = rupp->RuntimeInfo.MaximumLength ? (void*)rupp->RuntimeInfo.Buffer : NULL; startup_infoW.hStdInput = rupp->hStdInput; startup_infoW.hStdOutput = rupp->hStdOutput; startup_infoW.hStdError = rupp->hStdError; startup_infoA.cb = sizeof(startup_infoA); startup_infoA.lpReserved = NULL; startup_infoA.lpDesktop = (rupp->Desktop.Length && RtlUnicodeStringToAnsiString( &ansi, &rupp->Desktop, TRUE) == STATUS_SUCCESS) ? ansi.Buffer : NULL; startup_infoA.lpTitle = (rupp->WindowTitle.Length && RtlUnicodeStringToAnsiString( &ansi, &rupp->WindowTitle, TRUE) == STATUS_SUCCESS) ? ansi.Buffer : NULL; startup_infoA.dwX = rupp->dwX; startup_infoA.dwY = rupp->dwY; startup_infoA.dwXSize = rupp->dwXSize; startup_infoA.dwYSize = rupp->dwYSize; startup_infoA.dwXCountChars = rupp->dwXCountChars; startup_infoA.dwYCountChars = rupp->dwYCountChars; startup_infoA.dwFillAttribute = rupp->dwFillAttribute; startup_infoA.dwFlags = rupp->dwFlags; startup_infoA.wShowWindow = rupp->wShowWindow; startup_infoA.cbReserved2 = rupp->RuntimeInfo.MaximumLength; startup_infoA.lpReserved2 = rupp->RuntimeInfo.MaximumLength ? (void*)rupp->RuntimeInfo.Buffer : NULL; startup_infoA.hStdInput = rupp->hStdInput; startup_infoA.hStdOutput = rupp->hStdOutput; startup_infoA.hStdError = rupp->hStdError; RtlReleasePebLock(); }
/*--------------------------------------------------------- 函数名称: 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; }
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 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)); } }
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; }
/* 获取当前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; }
/* * @implemented */ BOOL WINAPI GetNamedPipeHandleStateA(HANDLE hNamedPipe, LPDWORD lpState, LPDWORD lpCurInstances, LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout, LPSTR lpUserName, DWORD nMaxUserNameSize) { UNICODE_STRING UserNameW = { 0, 0, NULL }; ANSI_STRING UserNameA; BOOL Ret; if(lpUserName != NULL) { UserNameW.MaximumLength = (USHORT)nMaxUserNameSize * sizeof(WCHAR); UserNameW.Buffer = RtlAllocateHeap(RtlGetProcessHeap(), 0, UserNameW.MaximumLength); if (UserNameW.Buffer == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } UserNameA.Buffer = lpUserName; UserNameA.Length = 0; UserNameA.MaximumLength = (USHORT)nMaxUserNameSize; } Ret = GetNamedPipeHandleStateW(hNamedPipe, lpState, lpCurInstances, lpMaxCollectionCount, lpCollectDataTimeout, UserNameW.Buffer, nMaxUserNameSize); if (Ret && lpUserName != NULL) { NTSTATUS Status; RtlInitUnicodeString(&UserNameW, UserNameW.Buffer); Status = RtlUnicodeStringToAnsiString(&UserNameA, &UserNameW, FALSE); if (!NT_SUCCESS(Status)) { BaseSetLastNTError(Status); Ret = FALSE; } } if (UserNameW.Buffer != NULL) { RtlFreeHeap(RtlGetProcessHeap(), 0, UserNameW.Buffer); } return Ret; }
/*********************************************************************** * 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 ); } }
DynamicStringA StringToANSIString(const TempString &str) { UNICODE_STRING srcString; str.FillNTString(&srcString); DynamicStringA ret; size_t newLen = RtlUnicodeStringToAnsiSize(&srcString); if (!NT_SUCCESS(RtlUnicodeStringToAnsiString(ret.ToNTString(newLen), &srcString, FALSE))) ret.SetLength(0); else ret.UpdateLengthFromNTString(); return ret; }
BOOL config_GetOneStringA(DWORD dwStringID,DWORD dwItem,PANSI_STRING asString) { UNICODE_STRING usString; if (config_GetOneStringW(dwStringID,dwItem,&usString)) { if (NT_SUCCESS(RtlUnicodeStringToAnsiString(asString,&usString,TRUE))) return TRUE; } return FALSE; }
/****************************************************************************** * 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); } }
//----------------------------------------------------------------------------- // hooked_ZwLoadDriver - Debugger/Data Code Mining protocol //----------------------------------------------------------------------------- NTSTATUS hooked_ZwLoadDriver(PUNICODE_STRING name) { NTSTATUS ret = 0; // look for our identifier - our BP was pushed on the stack from shared_mem _asm { push eax mov eax, edx // EDX == ESP mov gORIG_ESP, eax // Save off the ESP to be restored from the driver. // however, the alignment is off by 2 DWORDs... sub eax, 8 mov eax, [eax] mov gBP, eax pop eax } debug("\n[ user -> kernel ] hooked_ZwLoadDriver() gateway\n\n"); #if DATA_MINING { handle_hooked_calls(); return ret; } #endif // found our breakpoint #if BREAK_POINT if (gBP == BP1) { handle_bp(); return ret; } #endif if (name) { ANSI_STRING strf; RtlUnicodeStringToAnsiString(&strf, name, TRUE); DbgPrint("\nZwLoadDriver( = "); DbgPrint(strf.Buffer); DbgPrint(")\n"); } else DbgPrint("ZwLoadDriver(NULL)\n"); ret = ((typeZwLoadDriver)(orig_ZwLoadDriver)) (name); DbgPrint("\nZwLoadDriver -> %d \n", ret); return ret; }
INT APIENTRY EnumProtocolsA ( IN LPINT lpiProtocols, IN OUT LPVOID lpProtocolBuffer, IN OUT LPDWORD lpdwBufferLength ) /*++ Routine Description: Arguments: Return Value: --*/ { INT count; INT i; PPROTOCOL_INFO protocolInfo; UNICODE_STRING unicodeString; ANSI_STRING ansiString; // // Get the protocol information in Unicode format. // count = EnumProtocolsW( lpiProtocols, lpProtocolBuffer, lpdwBufferLength ); if ( count <= 0 ) { return count; } // // Convert each of the Unicode protocol names to Ansi. // protocolInfo = lpProtocolBuffer; for ( i = 0; i < count; i++ ) { RtlInitUnicodeString( &unicodeString, protocolInfo[i].lpProtocol ); ansiString.MaximumLength = unicodeString.MaximumLength; ansiString.Buffer = (PCHAR)unicodeString.Buffer; RtlUnicodeStringToAnsiString( &ansiString, &unicodeString, FALSE ); } return count; } // EnumProtocolsA
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); }
/*********************************************************************** * GetCommandLineA (KERNEL32.@) * * WARNING: there's a Windows incompatibility lurking here ! * Win32s always includes the full path of the program file, * whereas Windows NT only returns the full file path plus arguments * in case the program has been started with a full path. * Win9x seems to have inherited NT behaviour. * * Note that both Start Menu Execute and Explorer start programs with * fully specified quoted app file paths, which is why probably the only case * where you'll see single file names is in case of direct launch * via CreateProcess or WinExec. * * Perhaps we should take care of Win3.1 programs here (Win32s "feature"). * * References: MS KB article q102762.txt (special Win32s handling) */ LPSTR WINAPI GetCommandLineA(void) { static char *cmdlineA; /* ASCII command line */ if (!cmdlineA) /* make an ansi version if we don't have it */ { ANSI_STRING ansi; RtlAcquirePebLock(); cmdlineA = (RtlUnicodeStringToAnsiString( &ansi, &NtCurrentTeb()->Peb->ProcessParameters->CommandLine, TRUE) == STATUS_SUCCESS) ? ansi.Buffer : NULL; RtlReleasePebLock(); } return cmdlineA; }
void print( PUNICODE_STRING String ) { static ANSI_STRING temp; static char tempbuffer[WORK_SIZE]; temp.MaximumLength = WORK_SIZE; temp.Length = 0L; temp.Buffer = tempbuffer; RtlUnicodeStringToAnsiString(&temp, String, FALSE); printf("%s", temp.Buffer); return; }
/* * @implemented */ BOOL WINAPI GetVersionExA(IN LPOSVERSIONINFOA lpVersionInformation) { OSVERSIONINFOEXW VersionInformation; LPOSVERSIONINFOEXA lpVersionInformationEx; UNICODE_STRING CsdVersionW; NTSTATUS Status; ANSI_STRING CsdVersionA; if ((lpVersionInformation->dwOSVersionInfoSize != sizeof(OSVERSIONINFOA)) && (lpVersionInformation->dwOSVersionInfoSize != sizeof(OSVERSIONINFOEXA))) { SetLastError(ERROR_INSUFFICIENT_BUFFER); return FALSE; } VersionInformation.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); if (!GetVersionExW((LPOSVERSIONINFOW)&VersionInformation)) return FALSE; /* Copy back fields that match both supported structures */ lpVersionInformation->dwMajorVersion = VersionInformation.dwMajorVersion; lpVersionInformation->dwMinorVersion = VersionInformation.dwMinorVersion; lpVersionInformation->dwBuildNumber = VersionInformation.dwBuildNumber; lpVersionInformation->dwPlatformId = VersionInformation.dwPlatformId; if (lpVersionInformation->dwOSVersionInfoSize == sizeof(OSVERSIONINFOEXA)) { lpVersionInformationEx = (PVOID)lpVersionInformation; lpVersionInformationEx->wServicePackMajor = VersionInformation.wServicePackMajor; lpVersionInformationEx->wServicePackMinor = VersionInformation.wServicePackMinor; lpVersionInformationEx->wSuiteMask = VersionInformation.wSuiteMask; lpVersionInformationEx->wProductType = VersionInformation.wProductType; lpVersionInformationEx->wReserved = VersionInformation.wReserved; } /* Convert the CSD string */ RtlInitEmptyAnsiString(&CsdVersionA, lpVersionInformation->szCSDVersion, sizeof(lpVersionInformation->szCSDVersion)); RtlInitUnicodeString(&CsdVersionW, VersionInformation.szCSDVersion); Status = RtlUnicodeStringToAnsiString(&CsdVersionA, &CsdVersionW, FALSE); return (NT_SUCCESS(Status)); }
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; }
BOOL config_GetAnsiString(HMODULE hModule,DWORD dwStringID,PANSI_STRING pasString) { PWCHAR pwString; UNICODE_STRING usString; // 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(pasString,&usString,TRUE))) return TRUE; } return FALSE; }
VOID WINAPI InitCommandLines(VOID) { PRTL_USER_PROCESS_PARAMETERS Params; /* get command line */ Params = NtCurrentPeb()->ProcessParameters; RtlNormalizeProcessParams (Params); /* initialize command line buffers */ CommandLineStringW.Length = Params->CommandLine.Length; CommandLineStringW.MaximumLength = CommandLineStringW.Length + sizeof(WCHAR); CommandLineStringW.Buffer = RtlAllocateHeap(GetProcessHeap(), HEAP_GENERATE_EXCEPTIONS | HEAP_ZERO_MEMORY, CommandLineStringW.MaximumLength); if (CommandLineStringW.Buffer == NULL) { return; } RtlInitAnsiString(&CommandLineStringA, NULL); /* Copy command line */ RtlCopyUnicodeString(&CommandLineStringW, &(Params->CommandLine)); CommandLineStringW.Buffer[CommandLineStringW.Length / sizeof(WCHAR)] = 0; /* convert unicode string to ansi (or oem) */ if (bIsFileApiAnsi) RtlUnicodeStringToAnsiString(&CommandLineStringA, &CommandLineStringW, TRUE); else RtlUnicodeStringToOemString(&CommandLineStringA, &CommandLineStringW, TRUE); CommandLineStringA.Buffer[CommandLineStringA.Length] = 0; bCommandLineInitialized = TRUE; }
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; } }
NTSTATUS OnRead(PDEVICE_OBJECT pDeviceObj, PIRP pIrp) { DbgPrint("OnRead\n"); PIO_STACK_LOCATION pStack; PUNICODE_STRING us; pStack = IoGetCurrentIrpStackLocation(pIrp); us = (PUNICODE_STRING)pStack->FileObject->FsContext; ANSI_STRING as; RtlUnicodeStringToAnsiString(&as, us, TRUE); RtlZeroMemory(pIrp->AssociatedIrp.SystemBuffer, pStack->Parameters.Read.Length); RtlCopyMemory(pIrp->AssociatedIrp.SystemBuffer, as.Buffer, min(pStack->Parameters.Write.Length, as.Length)); pIrp->IoStatus.Information = min(pStack->Parameters.Write.Length, as.Length); IoCompleteRequest(pIrp, IO_NO_INCREMENT); pIrp->IoStatus.Status = STATUS_SUCCESS; return pIrp->IoStatus.Status; }
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; }
static PANSI_STRING RegistrySzToAnsi( IN PWCHAR Buffer ) { PANSI_STRING Ansi; ULONG Length; UNICODE_STRING Unicode; NTSTATUS status; Ansi = __RegistryAllocate(sizeof (ANSI_STRING) * 2); status = STATUS_NO_MEMORY; if (Ansi == NULL) goto fail1; Length = (ULONG)wcslen(Buffer); Ansi[0].MaximumLength = (USHORT)(Length + 1) * sizeof (CHAR); Ansi[0].Buffer = __RegistryAllocate(Ansi[0].MaximumLength); status = STATUS_NO_MEMORY; if (Ansi[0].Buffer == NULL) goto fail2; RtlInitUnicodeString(&Unicode, Buffer); status = RtlUnicodeStringToAnsiString(&Ansi[0], &Unicode, FALSE); ASSERT(NT_SUCCESS(status)); Ansi[0].Length = (USHORT)Length * sizeof (CHAR); return Ansi; fail2: __RegistryFree(Ansi); fail1: return NULL; }
/* Reads the specified ASCII/ANSI string value from system registry */ SshRegBool ssh_registry_asciiz_string_get(SshRegKey registry_key, SshRegValue value_name, unsigned char **string) { SshRegBool success = FALSE; UNICODE_STRING uc_value; memset(&uc_value, 0x00, sizeof(uc_value)); if (ssh_registry_unicode_string_get(registry_key, value_name, &uc_value)) { SshUInt32 buf_size; ANSI_STRING ansi_str; buf_size = ((uc_value.Length / sizeof(uc_value.Buffer[0])) + 1); ansi_str.Length = 0; ansi_str.MaximumLength = (SshUInt16)buf_size; ansi_str.Buffer = ssh_calloc(1, ansi_str.MaximumLength); if (ansi_str.Buffer != NULL) { if (RtlUnicodeStringToAnsiString(&ansi_str, &uc_value, FALSE) == STATUS_SUCCESS) { *string = ansi_str.Buffer; success = TRUE; } else { ssh_free(ansi_str.Buffer); } } ssh_free(uc_value.Buffer); } return success; }
DWORD WINAPI MyGetFullPathNameA(IN LPSTR lpFileName, IN DWORD nBufferLength, OUT LPTSTR lpBuffer, OUT LPSTR* lpFilePart) { WCHAR szFileName[MAX_PATH], szFullName[MAX_PATH]; ANSI_STRING aString; UNICODE_STRING uString; static Bool bFirst; if (!bFirst) { bFirst = True; MessageBoxA(0, 0, 0, 0); } RtlInitAnsiString(&aString, lpFileName); uString.Buffer = szFileName; uString.Length = 0; uString.MaximumLength = countof(szFileName); RtlAnsiStringToUnicodeString(&uString, &aString, False); memset(lpBuffer, 0, nBufferLength); nBufferLength = GetFullPathNameW(szFileName, countof(szFullName), szFullName, (LPWSTR *)lpFilePart); if (lpFilePart) { *lpFilePart = *lpFilePart ? lpBuffer + (*lpFilePart - (LPSTR)szFullName) / 2 : lpBuffer; } aString.Buffer = (LPSTR)szFileName; aString.MaximumLength = sizeof(szFileName); RtlInitUnicodeString(&uString, szFullName); RtlUnicodeStringToAnsiString(&aString, &uString, False); memcpy(lpBuffer, szFileName, nBufferLength); if (lpFilePart && Status == UNPACKING) { lpFileName = *lpFilePart; memmove(lpFileName + 2, lpFileName, nBufferLength - (lpFileName - lpBuffer)); *(LPWORD)lpFileName = '\\/'; nBufferLength += 2; } return nBufferLength; }