HyperDbg Debugger
Loading...
Searching...
No Matches
common.cpp File Reference

HyperDbg general functions for reading and converting and etc. More...

#include "pch.h"

Functions

BOOLEAN ConvertTokenToUInt64 (CommandToken TargetToken, PUINT64 Result)
 add ` between 64 bit values and convert them to string
std::string GetCaseSensitiveStringFromCommandToken (CommandToken TargetToken)
 Get case sensitive string from command token.
std::string GetLowerStringFromCommandToken (CommandToken TargetToken)
 Get lower case string from command token.
BOOLEAN CompareLowerCaseStrings (CommandToken TargetToken, const CHAR *StringToCompare)
 Compare lower case strings.
BOOLEAN IsTokenBracketString (CommandToken TargetToken)
 Is token bracket string.
BOOLEAN ConvertTokenToUInt32 (CommandToken TargetToken, PUINT32 Result)
 check and convert command token to a 32 bit unsigned integer
BOOLEAN HasEnding (string const &fullString, string const &ending)
 checks whether the string ends with a special string or not
BOOLEAN ValidateIP (const string &ip)
 Function to validate an IP address.
BOOLEAN VmxSupportDetection ()
 Detect whether the VMX is supported or not.
BOOL SetPrivilege (HANDLE Token, LPCTSTR Privilege, BOOL EnablePrivilege)
 SetPrivilege enables/disables process token privilege.
VOID Trim (std::string &s)
 trim from both ends and start of a string (in place)
std::string RemoveSpaces (std::string str)
 Remove all the spaces in a string.
BOOLEAN IsFileExistA (const CHAR *FileName)
 check if a file exist or not (ASCII)
BOOLEAN IsFileExistW (const WCHAR *FileName)
 check if a file exist or not (wide-char)
BOOLEAN IsEmptyString (CHAR *Text)
 Is empty character.
VOID GetConfigFilePath (PWCHAR ConfigPath)
 Get config path.
std::vector< std::string > ListDirectory (const std::string &Directory, const std::string &Extension)
 Create a list of special files in a directory.
VOID StringToWString (std::wstring &ws, const std::string &s)
 convert std::string to std::wstring
SIZE_T FindCaseInsensitive (std::string Input, std::string ToSearch, SIZE_T Pos)
 Find case insensitive sub string in a given substring.
SIZE_T FindCaseInsensitiveW (std::wstring Input, std::wstring ToSearch, SIZE_T Pos)
 Find case insensitive sub string in a given substring (unicode).
CHARConvertStringVectorToCharPointerArray (const std::string &s)
 Convert vector<string> to char*.
VOID CommonCpuidInstruction (UINT32 Func, UINT32 SubFunc, INT *CpuInfo)
 Get cpuid results.
UINT32 Getx86VirtualAddressWidth ()
 Get virtual address width for x86 processors.
BOOLEAN CheckCpuSupportRtm ()
 Check whether the processor supports RTM or not.
BOOLEAN CheckAddressCanonicality (UINT64 VAddr, PBOOLEAN IsKernelAddress)
 Checks if the address is canonical based on x86 processor's virtual address width or not.
BOOLEAN CheckAddressValidityUsingTsx (UINT64 Address)
 This function checks whether the address is valid or not using Intel TSX.
BOOLEAN CheckAccessValidityAndSafety (UINT64 TargetAddress, UINT32 Size)
 Check the safety to access the memory.
UINT32 Log2Ceil (UINT32 n)
 Function to compute log2Ceil.

Variables

BOOLEAN g_RtmSupport
 check for RTM support
UINT32 g_VirtualAddressWidth
 Virtual address width for x86 processors.

Detailed Description

HyperDbg general functions for reading and converting and etc.

Author
Sina Karvandi (sina@.nosp@m.hype.nosp@m.rdbg..nosp@m.org)
Version
0.1
Date
2020-05-27

Function Documentation

◆ CheckAccessValidityAndSafety()

BOOLEAN CheckAccessValidityAndSafety ( UINT64 TargetAddress,
UINT32 Size )

Check the safety to access the memory.

Parameters
TargetAddress
Size
Returns
BOOLEAN
1086{
1087 BOOLEAN IsKernelAddress;
1088 BOOLEAN Result = FALSE;
1089
1090 //
1091 // First, we check if the address is canonical based
1092 // on Intel processor's virtual address width
1093 //
1094 if (!CheckAddressCanonicality(TargetAddress, &IsKernelAddress))
1095 {
1096 //
1097 // No need for further check, address is invalid
1098 //
1099 return FALSE;
1100 }
1101
1102 //
1103 // We cannot check a kernel-mode address here in user-mode
1104 //
1105 if (IsKernelAddress)
1106 {
1107 return FALSE;
1108 }
1109
1110 //
1111 // We'll check address with TSX if it supports TSX RTM
1112 //
1113 if (g_RtmSupport)
1114 {
1115 //
1116 // *** The guest supports Intel TSX ***
1117 //
1118
1119 UINT64 AddressToCheck =
1120 (CHAR *)TargetAddress + Size - ((CHAR *)PAGE_ALIGN(TargetAddress));
1121
1122 if (AddressToCheck > PAGE_SIZE)
1123 {
1124 //
1125 // Address should be accessed in more than one page
1126 //
1127 UINT32 ReadSize = 0;
1128
1129 while (Size != 0)
1130 {
1131 ReadSize = (UINT32)((UINT64)PAGE_ALIGN(TargetAddress + PAGE_SIZE) - TargetAddress);
1132
1133 if (ReadSize == PAGE_SIZE && Size < PAGE_SIZE)
1134 {
1135 ReadSize = Size;
1136 }
1137
1138 if (!CheckAddressValidityUsingTsx(TargetAddress))
1139 {
1140 //
1141 // Address is not valid
1142 //
1143 return FALSE;
1144 }
1145
1146 /*
1147 ShowMessages("Addr From : %llx to Addr To : %llx | ReadSize : %llx\n",
1148 TargetAddress,
1149 TargetAddress + ReadSize,
1150 ReadSize);
1151 */
1152
1153 //
1154 // Apply the changes to the next addresses (if any)
1155 //
1156 Size = Size - ReadSize;
1157 TargetAddress = TargetAddress + ReadSize;
1158 }
1159 }
1160 else
1161 {
1162 if (!CheckAddressValidityUsingTsx(TargetAddress))
1163 {
1164 //
1165 // Address is not valid
1166 //
1167 return FALSE;
1168 }
1169 }
1170 }
1171 else
1172 {
1173 //
1174 // *** processor doesn't support RTM ***
1175 //
1176
1177 //
1178 // There is no way to perform this check! The below implementation doesn't satisfy
1179 // our needs for address checks, but we're not trying to ask kernel about it as
1180 // HyperDbg's script engine is not designed to be ran these functions in user-mode
1181 // so we left it unimplemented to avoid crashes in the main program
1182 //
1183 return FALSE;
1184
1185 //
1186 // Check if memory is safe and present
1187 //
1188
1189 UINT64 AddressToCheck =
1190 (CHAR *)TargetAddress + Size - ((CHAR *)PAGE_ALIGN(TargetAddress));
1191
1192 if (AddressToCheck > PAGE_SIZE)
1193 {
1194 //
1195 // Address should be accessed in more than one page
1196 //
1197 UINT32 ReadSize = 0;
1198
1199 while (Size != 0)
1200 {
1201 ReadSize = (UINT32)((UINT64)PAGE_ALIGN(TargetAddress + PAGE_SIZE) - TargetAddress);
1202
1203 if (ReadSize == PAGE_SIZE && Size < PAGE_SIZE)
1204 {
1205 ReadSize = Size;
1206 }
1207
1208 try
1209 {
1210 UINT64 ReadingTest = *((UINT64 *)TargetAddress);
1211 }
1212 catch (...)
1213 {
1214 //
1215 // Address is not valid
1216 //
1217 return FALSE;
1218 }
1219
1220 /*
1221 ShowMessages("Addr From : %llx to Addr To : %llx | ReadSize : %llx\n",
1222 TargetAddress,
1223 TargetAddress + ReadSize,
1224 ReadSize);
1225 */
1226
1227 //
1228 // Apply the changes to the next addresses (if any)
1229 //
1230 Size = Size - ReadSize;
1231 TargetAddress = TargetAddress + ReadSize;
1232 }
1233 }
1234 else
1235 {
1236 try
1237 {
1238 UINT64 ReadingTest = *((UINT64 *)TargetAddress);
1239 }
1240 catch (...)
1241 {
1242 //
1243 // Address is not valid
1244 //
1245 return FALSE;
1246 }
1247 }
1248 }
1249
1250 //
1251 // If we've reached here, the address was valid
1252 //
1253 return TRUE;
1254}
UCHAR BOOLEAN
Definition BasicTypes.h:35
#define TRUE
Definition BasicTypes.h:114
#define FALSE
Definition BasicTypes.h:113
unsigned int UINT32
Definition BasicTypes.h:54
char CHAR
Definition BasicTypes.h:33
BOOLEAN CheckAddressCanonicality(UINT64 VAddr, PBOOLEAN IsKernelAddress)
Checks if the address is canonical based on x86 processor's virtual address width or not.
Definition common.cpp:991
BOOLEAN CheckAddressValidityUsingTsx(UINT64 Address)
This function checks whether the address is valid or not using Intel TSX.
Definition common.cpp:1047
BOOLEAN g_RtmSupport
check for RTM support
Definition globals.h:44
#define PAGE_SIZE
Size of each page (4096 bytes).
Definition common.h:80
#define PAGE_ALIGN(Va)
Aligning a page.
Definition common.h:86

◆ CheckAddressCanonicality()

BOOLEAN CheckAddressCanonicality ( UINT64 VAddr,
PBOOLEAN IsKernelAddress )

Checks if the address is canonical based on x86 processor's virtual address width or not.

Parameters
VAddrvirtual address to check
IsKernelAddressFilled to show whether the address is a kernel address or user-address

IsKernelAddress wouldn't check for page attributes, it just checks the address convention in Windows

Returns
BOOLEAN
992{
993 UINT64 Addr = (UINT64)VAddr;
994 UINT64 MaxVirtualAddrLowHalf, MinVirtualAddressHighHalf;
995
996 //
997 // Get processor's address width for VA
998 //
999 UINT32 AddrWidth = g_VirtualAddressWidth;
1000
1001 //
1002 // get max address in lower-half canonical addr space
1003 // e.g. if width is 48, then 0x00007FFF_FFFFFFFF
1004 //
1005 MaxVirtualAddrLowHalf = ((UINT64)1ull << (AddrWidth - 1)) - 1;
1006
1007 //
1008 // get min address in higher-half canonical addr space
1009 // e.g., if width is 48, then 0xFFFF8000_00000000
1010 //
1011 MinVirtualAddressHighHalf = ~MaxVirtualAddrLowHalf;
1012
1013 //
1014 // Check to see if the address in a canonical address
1015 //
1016 if ((Addr > MaxVirtualAddrLowHalf) && (Addr < MinVirtualAddressHighHalf))
1017 {
1018 *IsKernelAddress = FALSE;
1019 return FALSE;
1020 }
1021
1022 //
1023 // Set whether it's a kernel address or not
1024 //
1025 if (MinVirtualAddressHighHalf < Addr)
1026 {
1027 *IsKernelAddress = TRUE;
1028 }
1029 else
1030 {
1031 *IsKernelAddress = FALSE;
1032 }
1033
1034 return TRUE;
1035}
UINT32 g_VirtualAddressWidth
Virtual address width for x86 processors.
Definition globals.h:50

◆ CheckAddressValidityUsingTsx()

BOOLEAN CheckAddressValidityUsingTsx ( UINT64 Address)

This function checks whether the address is valid or not using Intel TSX.

Parameters
AddressAddress to check
UINT32ProcId
Returns
BOOLEAN Returns true if the address is valid; otherwise, false
1048{
1049 UINT32 Status = 0;
1050 BOOLEAN Result = FALSE;
1051 CHAR TempContent;
1052
1053 if ((Status = _xbegin()) == _XBEGIN_STARTED)
1054 {
1055 //
1056 // Try to read the memory
1057 //
1058 TempContent = *(CHAR *)Address;
1059 _xend();
1060
1061 //
1062 // No error, address is valid
1063 //
1064 Result = TRUE;
1065 }
1066 else
1067 {
1068 //
1069 // Address is not valid, it aborts the tsx rtm
1070 //
1071 Result = FALSE;
1072 }
1073
1074 return Result;
1075}
#define _XBEGIN_STARTED
Intel TSX Constants.
Definition Common.h:61

◆ CheckCpuSupportRtm()

BOOLEAN CheckCpuSupportRtm ( )

Check whether the processor supports RTM or not.

Returns
BOOLEAN
951{
952 INT Regs1[4];
953 INT Regs2[4];
954 BOOLEAN Result;
955
956 //
957 // TSX is controlled via MSR_IA32_TSX_CTRL. However, support for this
958 // MSR is enumerated by ARCH_CAP_TSX_MSR bit in MSR_IA32_ARCH_CAPABILITIES.
959 //
960 // TSX control (aka MSR_IA32_TSX_CTRL) is only available after a
961 // microcode update on CPUs that have their MSR_IA32_ARCH_CAPABILITIES
962 // bit MDS_NO=1. CPUs with MDS_NO=0 are not planned to get
963 // MSR_IA32_TSX_CTRL support even after a microcode update. Thus,
964 // tsx= cmdline requests will do nothing on CPUs without
965 // MSR_IA32_TSX_CTRL support.
966 //
967
968 CommonCpuidInstruction(0, 0, Regs1);
969 CommonCpuidInstruction(7, 0, Regs2);
970
971 //
972 // Check RTM and MPX extensions in order to filter out TSX on Haswell CPUs
973 //
974 Result = Regs1[0] >= 0x7 && (Regs2[1] & 0x4800) == 0x4800;
975
976 return Result;
977}
int INT
Definition BasicTypes.h:43
VOID CommonCpuidInstruction(UINT32 Func, UINT32 SubFunc, INT *CpuInfo)
Get cpuid results.
Definition common.cpp:921

◆ CommonCpuidInstruction()

VOID CommonCpuidInstruction ( UINT32 Func,
UINT32 SubFunc,
INT * CpuInfo )

Get cpuid results.

Parameters
Func
SubFunc
CpuInfo
Returns
VOID
922{
923 CpuIdEx(CpuInfo, Func, SubFunc);
924}

◆ CompareLowerCaseStrings()

BOOLEAN CompareLowerCaseStrings ( CommandToken TargetToken,
const CHAR * StringToCompare )

Compare lower case strings.

Parameters
TargetTokenthe target command token
StringToComparethe string to compare
Returns
BOOLEAN shows whether text is equal or not
504{
505 //
506 // Extract the token type and value from the tuple
507 //
508 std::string TargetTokenValue = std::get<2>(TargetToken); // the second index is lower case
509
510 //
511 // Convert the token value to 64 bit unsigned integer
512 //
513 return _stricmp(TargetTokenValue.c_str(), StringToCompare) == 0;
514}

◆ ConvertStringVectorToCharPointerArray()

CHAR * ConvertStringVectorToCharPointerArray ( const std::string & s)

Convert vector<string> to char*.

use it like : std::transform(vs.begin(), vs.end(), std::back_inserter(vc), ConvertStringVectorToCharPointerArray); from: https://stackoverflow.com/questions/7048888/stdvectorstdstring-to-char-array

Parameters
s
Returns
CHAR*
906{
907 CHAR * Pc = new CHAR[s.size() + 1];
908 std::strcpy(Pc, s.c_str());
909 return Pc;
910}

◆ ConvertTokenToUInt32()

BOOLEAN ConvertTokenToUInt32 ( CommandToken TargetToken,
PUINT32 Result )

check and convert command token to a 32 bit unsigned integer

Parameters
TargetTokenthe target command token
Resultresult will be save to the pointer
Returns
BOOLEAN shows whether the conversion was successful or not
547{
548 //
549 // Extract the token type and value from the tuple
550 //
551 std::string TargetTokenValue = std::get<1>(TargetToken);
552
553 //
554 // Convert the token value to 32 bit unsigned integer
555 //
556 return ConvertStringToUInt32(TargetTokenValue, Result);
557}
BOOLEAN ConvertStringToUInt32(string TextToConvert, PUINT32 Result)

◆ ConvertTokenToUInt64()

BOOLEAN ConvertTokenToUInt64 ( CommandToken TargetToken,
PUINT64 Result )

add ` between 64 bit values and convert them to string

Parameters
Value
Returns
string */ string SeparateTo64BitValue(UINT64 Value) { ostringstream OstringStream; string Temp;

OstringStream << setw(16) << setfill('0') << hex << Value; Temp = OstringStream.str();

Temp.insert(8, 1, '`'); return Temp; }

/**

print bits and bytes for d* commands

Parameters
Size
Ptr
Returns
VOID */ VOID PrintBits(const UINT32 Size, const VOID * Ptr) { UCHAR * Buf = (UCHAR *)Ptr; UCHAR Byte; INT i, j;

for (i = Size - 1; i >= 0; i–) { for (j = 7; j >= 0; j–) { Byte = (Buf[i] >> j) & 1; ShowMessages("%u", Byte); } ShowMessages(" ", Byte); } }

/**

general replace all function

Parameters
str
from
to
Returns
VOID */ BOOL Replace(std::string & str, const std::string & from, const std::string & to) { SIZE_T StartPos = str.find(from); if (StartPos == std::string::npos) return FALSE; str.replace(StartPos, from.size(), to); return TRUE; }

/**

general replace all function

Parameters
str
from
to
Returns
VOID */ VOID ReplaceAll(string & str, const string & from, const string & to) { SIZE_T SartPos = 0;

if (from.empty()) return;

while ((SartPos = str.find(from, SartPos)) != std::string::npos) { str.replace(SartPos, from.length(), to); // // In case 'to' contains 'from', like replacing // 'x' with 'yx' // SartPos += to.length(); } }

/**

general split command

Parameters
starget string
csplitter (delimiter)
Returns
const vector<string> */ const vector<string> Split(const string & s, const CHAR & c) { string buff {""}; vector<string> v;

for (auto n : s) { if (n != c) buff += n; else if (n == c && !buff.empty()) { v.push_back(buff); buff.clear(); } } if (!buff.empty()) v.push_back(buff);

return v; }

/**

check if given string is a numeric string or not

Parameters
str
Returns
BOOLEAN */ BOOLEAN IsNumber(const string & str) { // // std::find_first_not_of searches the string for the first character // that does not match any of the characters specified in its arguments // return !str.empty() && (str.find_first_not_of("[0123456789]") == std::string::npos); }

/**

check whether the string is hex or not

Parameters
s
Returns
BOOLEAN */ BOOLEAN IsHexNotation(const string & s) { BOOLEAN IsAnyThing = FALSE;

for (auto & CptrChar : s) { IsAnyThing = TRUE;

if (!isxdigit(CptrChar)) { return FALSE; } } if (IsAnyThing) { return TRUE; } return FALSE; }

/**

check whether the string is decimal or not

Parameters
s
Returns
BOOLEAN */ BOOLEAN IsDecimalNotation(const string & s) { BOOLEAN IsAnyThing = FALSE;

for (auto & CptrChar : s) { IsAnyThing = TRUE;

if (!isdigit(CptrChar)) { return FALSE; } } if (IsAnyThing) { return TRUE; } return FALSE; }

/**

converts hex to bytes

Parameters
hex
Returns
vector<CHAR> */ vector<CHAR> HexToBytes(const string & hex) { vector<CHAR> Bytes;

for (UINT32 i = 0; i < hex.length(); i += 2) { std::string byteString = hex.substr(i, 2); CHAR Byte = (CHAR)strtol(byteString.c_str(), NULL, 16); Bytes.push_back(Byte); }

return Bytes; }

/**

check and convert string to a 64 bit unsigned integer and also check for special notations like 0x, 0n, etc.

Parameters
TextToConvertthe target string
Resultresult will be save to the pointer
Returns
BOOLEAN shows whether the conversion was successful or not */ BOOLEAN ConvertStringToUInt64(string TextToConvert, PUINT64 Result) { BOOLEAN IsDecimal = FALSE; // By default everything is hex

if (TextToConvert.rfind("0x", 0) == 0 || TextToConvert.rfind("0X", 0) == 0 || TextToConvert.rfind("\\x", 0) == 0 || TextToConvert.rfind("\\X", 0) == 0) { TextToConvert = TextToConvert.erase(0, 2); } else if (TextToConvert.rfind('x', 0) == 0 || TextToConvert.rfind('X', 0) == 0) { TextToConvert = TextToConvert.erase(0, 1); } else if (TextToConvert.rfind("0n", 0) == 0 || TextToConvert.rfind("0N", 0) == 0 || TextToConvert.rfind("\\n", 0) == 0 || TextToConvert.rfind("\\N", 0) == 0) { TextToConvert = TextToConvert.erase(0, 2); IsDecimal = TRUE; } else if (TextToConvert.rfind('n', 0) == 0 || TextToConvert.rfind('N', 0) == 0) { TextToConvert = TextToConvert.erase(0, 1); IsDecimal = TRUE; }

// // Remove '`' (if any)

TextToConvert.erase(remove(TextToConvert.begin(), TextToConvert.end(), '`'), TextToConvert.end());

if (IsDecimal) { if (!IsDecimalNotation(TextToConvert)) { // // Not decimal // return FALSE; } else { errno = 0; CHAR * Unparsed = NULL; const CHAR * S = TextToConvert.c_str(); const UINT64 N = strtoull(S, &Unparsed, 10);

if (errno || (!N && S == Unparsed)) { // fflush(stdout); // perror(s); return FALSE; }

*Result = N; return TRUE; } } else { // // It's not decimal // if (!IsHexNotation(TextToConvert)) { // // Not decimal and not hex! // return FALSE; } else { // // It's a hex number // const CHAR * Text = TextToConvert.c_str(); errno = 0; UINT64 ResultValue = strtoull(Text, NULL, 16);

*Result = ResultValue;

if (errno == EINVAL) { return FALSE; } else if (errno == ERANGE) { return TRUE; }

return TRUE; } } }

/**

check and convert string to a 32 bit unsigned it and also check for special notations like 0x etc.

Parameters
TextToConvertthe target string
Resultresult will be save to the pointer
Returns
BOOLEAN shows whether the conversion was successful or not */ BOOLEAN ConvertStringToUInt32(string TextToConvert, PUINT32 Result) { BOOLEAN IsDecimal = FALSE; // By default everything is hex

if (TextToConvert.rfind("0x", 0) == 0 || TextToConvert.rfind("0X", 0) == 0 || TextToConvert.rfind("\\x", 0) == 0 || TextToConvert.rfind("\\X", 0) == 0) { TextToConvert = TextToConvert.erase(0, 2); } else if (TextToConvert.rfind('x', 0) == 0 || TextToConvert.rfind('X', 0) == 0) { TextToConvert = TextToConvert.erase(0, 1); } else if (TextToConvert.rfind("0n", 0) == 0 || TextToConvert.rfind("0N", 0) == 0 || TextToConvert.rfind("\\n", 0) == 0 || TextToConvert.rfind("\\N", 0) == 0) { TextToConvert = TextToConvert.erase(0, 2); IsDecimal = TRUE; } else if (TextToConvert.rfind('n', 0) == 0 || TextToConvert.rfind('N', 0) == 0) { TextToConvert = TextToConvert.erase(0, 1); IsDecimal = TRUE; }

TextToConvert.erase(remove(TextToConvert.begin(), TextToConvert.end(), '`'), TextToConvert.end());

if (IsDecimal) { if (!IsDecimalNotation(TextToConvert)) { return FALSE; } else { try { INT I = std::stoi(TextToConvert); Result = I; return TRUE; } catch (std::invalid_argument const &) {

Bad input: std::invalid_argument thrown

            return FALSE;
        }
        catch (std::out_of_range const &)
        {

Integer overflow: std::out_of_range thrown

            return FALSE;
        }

        return FALSE;
    }
}
else
{

It's not decimal

    if (!IsHexNotation(TextToConvert))
    {
        return FALSE;
    }
    else
    {

It's hex number

        UINT32 TempResult;
        TempResult = stoi(TextToConvert, nullptr, 16);

Apply the results

         Result = TempResult;

        return TRUE;
    }
}

}

/**

check and convert command token to a 64 bit unsigned integer

Parameters
TargetTokenthe target command token
Resultresult will be save to the pointer
Returns
BOOLEAN shows whether the conversion was successful or not
448{
449 //
450 // Extract the token type and value from the tuple
451 //
452 std::string TargetTokenValue = std::get<1>(TargetToken);
453
454 //
455 // Convert the token value to 64 bit unsigned integer
456 //
457 return ConvertStringToUInt64(TargetTokenValue, Result);
458}
BOOLEAN ConvertStringToUInt64(string TextToConvert, PUINT64 Result)

◆ FindCaseInsensitive()

SIZE_T FindCaseInsensitive ( std::string Input,
std::string ToSearch,
SIZE_T Pos )

Find case insensitive sub string in a given substring.

Parameters
Input
ToSearch
Pos
Returns
SIZE_T
867{
868 // Convert complete given String to lower case
869 std::transform(Input.begin(), Input.end(), Input.begin(), ::tolower);
870 // Convert complete given Sub String to lower case
871 std::transform(ToSearch.begin(), ToSearch.end(), ToSearch.begin(), ::tolower);
872 // Find sub string in given string
873 return Input.find(ToSearch, Pos);
874}

◆ FindCaseInsensitiveW()

SIZE_T FindCaseInsensitiveW ( std::wstring Input,
std::wstring ToSearch,
SIZE_T Pos )

Find case insensitive sub string in a given substring (unicode).

Parameters
Input
ToSearch
Pos
Returns
SIZE_T
886{
887 // Convert complete given String to lower case
888 std::transform(Input.begin(), Input.end(), Input.begin(), ::tolower);
889 // Convert complete given Sub String to lower case
890 std::transform(ToSearch.begin(), ToSearch.end(), ToSearch.begin(), ::tolower);
891 // Find sub string in given string
892 return Input.find(ToSearch, Pos);
893}

◆ GetCaseSensitiveStringFromCommandToken()

std::string GetCaseSensitiveStringFromCommandToken ( CommandToken TargetToken)

Get case sensitive string from command token.

Parameters
TargetTokenthe target command token
Returns
string the string value of the token
468{
469 //
470 // Extract the token type and value from the tuple
471 //
472 std::string TargetTokenValue = std::get<1>(TargetToken); // the first index is case sensitive
473
474 return TargetTokenValue;
475}

◆ GetConfigFilePath()

VOID GetConfigFilePath ( PWCHAR ConfigPath)

Get config path.

Parameters
ConfigPath
793{
794 WCHAR CurrentPath[MAX_PATH] = {0};
795
796 //
797 // Get path file of current exe
798 //
799 GetModuleFileNameW(NULL, CurrentPath, MAX_PATH);
800
801 //
802 // Remove exe file name
803 //
804 PathRemoveFileSpecW(CurrentPath);
805
806 //
807 // Combine current exe path with config file name
808 //
809 PathCombineW(ConfigPath, CurrentPath, CONFIG_FILE_NAME);
810}
#define CONFIG_FILE_NAME
Config file name for HyperDbg.
Definition Definition.h:24

◆ GetLowerStringFromCommandToken()

std::string GetLowerStringFromCommandToken ( CommandToken TargetToken)

Get lower case string from command token.

Parameters
TargetTokenthe target command token
Returns
string the string value of the token
485{
486 //
487 // Extract the token type and value from the tuple
488 //
489 std::string TargetTokenValue = std::get<2>(TargetToken); // the second index is lower case
490
491 return TargetTokenValue;
492}

◆ Getx86VirtualAddressWidth()

UINT32 Getx86VirtualAddressWidth ( )

Get virtual address width for x86 processors.

Returns
UINT32
933{
934 INT Regs[4];
935
937
938 //
939 // Extracting bit 15:8 from eax register
940 //
941 return ((Regs[0] >> 8) & 0x0ff);
942}
#define CPUID_ADDR_WIDTH
Cpuid to get virtual address width.
Definition Constants.h:695

◆ HasEnding()

BOOLEAN HasEnding ( string const & fullString,
string const & ending )

checks whether the string ends with a special string or not

Parameters
fullString
ending
Returns
BOOLEAN if true then it shows that string ends with another string and if false then it shows that this string is not ended with the target string
570{
571 if (fullString.length() >= ending.length())
572 {
573 return (0 == fullString.compare(fullString.length() - ending.length(),
574 ending.length(),
575 ending));
576 }
577 else
578 {
579 return FALSE;
580 }
581}

◆ IsEmptyString()

BOOLEAN IsEmptyString ( CHAR * Text)

Is empty character.

Parameters
Text
766{
767 SIZE_T Len;
768
769 if (Text == NULL || Text[0] == '\0')
770 {
771 return TRUE;
772 }
773
774 Len = strlen(Text);
775 for (SIZE_T i = 0; i < Len; i++)
776 {
777 if (Text[i] != ' ' && Text[i] != '\t' && Text[i] != '\n')
778 {
779 return FALSE;
780 }
781 }
782
783 return TRUE;
784}

◆ IsFileExistA()

BOOLEAN IsFileExistA ( const CHAR * FileName)

check if a file exist or not (ASCII)

Parameters
FileNamepath of file
Returns
BOOLEAN shows whether the file exist or not
741{
742 struct stat buffer;
743 return (stat(FileName, &buffer) == 0);
744}

◆ IsFileExistW()

BOOLEAN IsFileExistW ( const WCHAR * FileName)

check if a file exist or not (wide-char)

Parameters
FileNamepath of file
Returns
BOOLEAN shows whether the file exist or not
754{
755 struct _stat64i32 buffer;
756 return (_wstat(FileName, &buffer) == 0);
757}

◆ IsTokenBracketString()

BOOLEAN IsTokenBracketString ( CommandToken TargetToken)

Is token bracket string.

Parameters
TargetTokenthe target command token
Returns
BOOLEAN shows whether the token is bracket string or not
525{
526 //
527 // Extract the token type and value from the tuple
528 //
529 CommandParsingTokenType TargetTokenValue = std::get<0>(TargetToken);
530
531 //
532 // Check if the token is a bracket string
533 //
534 return TargetTokenValue == CommandParsingTokenType::BracketString;
535}
CommandParsingTokenType
Command's parsing type (enum).
Definition commands.h:166
@ BracketString
Definition commands.h:170

◆ ListDirectory()

std::vector< std::string > ListDirectory ( const std::string & Directory,
const std::string & Extension )

Create a list of special files in a directory.

Parameters
Directory
Extension
Returns
std::vector<std::string>
821{
822 WIN32_FIND_DATAA FindData;
823 HANDLE Find = INVALID_HANDLE_VALUE;
824 std::string FullPath = Directory + "\\" + Extension;
825 std::vector<std::string> DirList;
826
827 Find = FindFirstFileA(FullPath.c_str(), &FindData);
828
829 if (Find == INVALID_HANDLE_VALUE)
830 throw std::runtime_error("invalid handle value! please check your path...");
831
832 while (FindNextFileA(Find, &FindData) != 0)
833 {
834 DirList.push_back(Directory + "\\" + std::string(FindData.cFileName));
835 }
836
837 FindClose(Find);
838
839 return DirList;
840}

◆ Log2Ceil()

UINT32 Log2Ceil ( UINT32 n)

Function to compute log2Ceil.

Parameters
n
Returns
UINT32
1264{
1265 if (n == 0)
1266 return 0; // log2Ceil(0) is undefined, returning 0 for safety.
1267
1268 n--; // Decrease by 1 to check if it is a power of 2
1269 UINT32 log2Floor = 0;
1270 while (n >>= 1)
1271 {
1272 log2Floor++;
1273 }
1274 return log2Floor + 1;
1275}

◆ RemoveSpaces()

std::string RemoveSpaces ( std::string str)

Remove all the spaces in a string.

Parameters
str
728{
729 str.erase(remove(str.begin(), str.end(), ' '), str.end());
730 return str;
731}

◆ SetPrivilege()

BOOL SetPrivilege ( HANDLE Token,
LPCTSTR Privilege,
BOOL EnablePrivilege )

SetPrivilege enables/disables process token privilege.

Parameters
Token
Privilege
EnablePrivilege
Returns
BOOL
647{
648 TOKEN_PRIVILEGES Tp;
649 LUID Luid;
650
651 if (!LookupPrivilegeValue(NULL, // lookup privilege on local system
652 Privilege, // privilege to lookup
653 &Luid)) // receives LUID of privilege
654 {
655 ShowMessages("err, in LookupPrivilegeValue (%x)\n", GetLastError());
656 return FALSE;
657 }
658
659 Tp.PrivilegeCount = 1;
660 Tp.Privileges[0].Luid = Luid;
661 if (EnablePrivilege)
662 Tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
663 else
664 Tp.Privileges[0].Attributes = 0;
665
666 //
667 // Enable the privilege or disable all privileges.
668 //
669 if (!AdjustTokenPrivileges(Token, FALSE, &Tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
670 {
671 ShowMessages("err, in AdjustTokenPrivileges (%x)\n", GetLastError());
672 return FALSE;
673 }
674
675 if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
676 {
677 ShowMessages("err, the token does not have the specified (debug) privilege (ACCESS DENIED!)\n");
678 ShowMessages("make sure to run it with administrator privileges\n");
679 return FALSE;
680 }
681
682 return TRUE;
683}

◆ StringToWString()

VOID StringToWString ( std::wstring & ws,
const std::string & s )

convert std::string to std::wstring

Parameters
ws
s
Returns
VOID
851{
852 std::wstring WsTmp(s.begin(), s.end());
853
854 ws = WsTmp;
855}

◆ Trim()

VOID Trim ( std::string & s)

trim from both ends and start of a string (in place)

Parameters
s
716{
717 ltrim(s);
718 rtrim(s);
719}

◆ ValidateIP()

BOOLEAN ValidateIP ( const string & ip)

Function to validate an IP address.

Parameters
ip
Returns
BOOLEAN
591{
592 //
593 // split the string into tokens
594 //
595 vector<string> list = Split(ip, '.');
596
597 //
598 // if token size is not equal to four
599 //
600 if (list.size() != 4)
601 return FALSE;
602
603 //
604 // validate each token
605 //
606 for (string str : list)
607 {
608 //
609 // verify that string is number or not and the numbers
610 // are in the valid range
611 //
612 if (!IsNumber(str) || stoi(str) > 255 || stoi(str) < 0)
613 return FALSE;
614 }
615
616 return TRUE;
617}
BOOLEAN IsNumber(const string &str)
const vector< string > Split(const string &s, const CHAR &c)

◆ VmxSupportDetection()

BOOLEAN VmxSupportDetection ( )

Detect whether the VMX is supported or not.

Returns
true if vmx is supported
false if vmx is not supported
627{
628 //
629 // Call assembly function
630 //
631 return AsmVmxSupportDetection();
632}
BOOLEAN AsmVmxSupportDetection()

Variable Documentation

◆ g_RtmSupport

BOOLEAN g_RtmSupport
extern

check for RTM support

◆ g_VirtualAddressWidth

UINT32 g_VirtualAddressWidth
extern

Virtual address width for x86 processors.