id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
25,941
1-2-perm-strings.cpp
mandliya_algorithms_and_data_structures/cracking_the_coding_interview_problems/1-2-perm-strings.cpp
/* * Cracking the coding interview edition 6 * Given two strings, determine if one is permutation of other. */ #include <iostream> #include <cstring> #include <quickSort.h> #include <string> /* * Function: arePermutations * Args: string1, string2 * return: true or false * assumption: ASCII char set */ bool arePermutations( const std::string str1, const std::string str2 ) { int len1 = str1.length(); int len2 = str2.length(); if ( len1 != len2 ) { return false; } int seen[128] = { 0 }; for ( int i = 0; i < len1; ++i ) { seen[ int(str1[i]) ]++; seen[ int(str2[i]) ]--; } for ( int i = 0; i < 128; ++i ) { if ( seen[i] != 0 ) { return false; } } return true; } /* * Function: arePermutations2 * Args: string1, string2 * return: true or false * assumption: ASCII char set */ bool arePermutations2( const std::string str1, const std::string str2 ) { int len1 = str1.length(); int len2 = str2.length(); if ( len1 != len2 ) { return false; } char *cstr1 = new char[ len1 + 1 ]; std::strcpy( cstr1, str1.c_str() ); char *cstr2 = new char[ len2 + 1 ]; std::strcpy( cstr2, str2.c_str() ); algo::quickSort( cstr1, 0, len1); algo::quickSort( cstr2, 0, len1); for (int i = 0; i < len1; ++i ) { if ( cstr1[i] != cstr2[i] ) return false; } return true; } int main() { std::string str1("abc"); std::string str2("cba"); std::string str3("abcd"); std::string str4("cbad"); std::string str5("cbcd"); if ( arePermutations( str1, str2 ) ) { std::cout << str1 << " and " << str2 << " are permutations of each other\n"; } else { std::cout << str1 << " and " << str2 << " are not permutations of each other\n"; } if ( arePermutations2( str3, str4 ) ) { std::cout << str3 << " and " << str4 << " are permutations of each other\n"; } else { std::cout << str3 << " and " << str4 << " are not permutations of each other\n"; } if ( arePermutations( str2, str4 ) ) { std::cout << str2 << " and " << str4 << " are permutations of each other\n"; } else { std::cout << str2 << " and " << str4 << " are not permutations of each other\n"; } if ( arePermutations2( str4, str5 ) ) { std::cout << str4 << " and " << str5 << " are permutations of each other\n"; } else { std::cout << str4 << " and " << str5 << " are not permutations of each other\n"; } return 0; }
2,582
C++
.cpp
87
24.655172
88
0.560373
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,948
orders_order.cpp
mandliya_algorithms_and_data_structures/greedy_problems/orders_order.cpp
/* * John is taking orders. * The ith order is placed by the ith customer at ti time and it takes di time to procees. * What is the order in which the customers will get their orders? * * Input * On the first line you will get n, the number of orders. * Then n lines will follow. On the (i+1)th line, you will get ti and di separated by a single space. * * Output * Print the order ( as single space separated integers ) in which the burger customers get their orders. * If two customers get the order at the same time, * then print the smallest numbered order first.(remember, the customers are numbered 1 to n). * * Approach : * By greedy approach, we can conclude the customer who ordered first and his order duration is smaller will get his order first. * So we will sort the orders based on time at which order was taken, + duration it will take to fulfill that order. */ #include <iostream> #include <algorithm> using namespace std; struct order { int index; int time; int duration; }; bool compareFunc(order & o1, order & o2) { if ( (o1.time + o1.duration) < (o2.time + o2.duration) ) { return true; } else if ( o1.time + o1.duration == o2.time + o2.duration ) { if (o1.index < o2.index) { return true; } } return false; } int main() { int N; cin >> N ; order * orders = new order[N]; for (int i = 0; i < N; ++i) { orders[i].index = i+1; cin >> orders[i].time; cin >> orders[i].duration; } sort(orders, orders+N, compareFunc); for( int i = 0; i < N; ++i) { std::cout << orders[i].index << " "; } std::cout << std::endl; return 0; }
1,694
C++
.cpp
52
28.596154
129
0.646915
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,949
two_arrays.cpp
mandliya_algorithms_and_data_structures/greedy_problems/two_arrays.cpp
/** * Given two array A and B * Is there an permutation A', B' possible of A and B, such that, A'i+B'i ≥ K for all i, * where A'i denotes the ith element in the array A' and B'i denotes ith element in the array B'. * * Input: The first line contains two integers, N and K. * The second line contains N space separated integers, denoting array A. * The third line describes array B in a same format. * * Output: YES or NO * * Solution Approach : * Greedy Algorithm. * sort one of the arrays in ascending order and the other in descending order and * then for every i, check if the condition (A[i] + B[i] >= k ) holds true or not * for each of the array indices i. It can be deduced that if the condition fails on the sorted arrays, * then there exists no permutation of A and B such that the condition holds good. */ #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int N, K; cin >> N >> K; int * A = new int[N]; int * B = new int[N]; for ( int i = 0; i < N; ++i) { cin >> A[i]; } for(int i = 0; i < N; ++i) { cin >> B[i]; } sort(A, A + N); sort(B, B + N, std::greater<int>()); //decreasing order sort int j; for( j = 0; j < N; ++j ) { if (A[j] + B[j] < K) { std::cout << "NO" << std::endl; break; } } if ( j == N ) { std::cout << "YES" << std::endl; } return 0; }
1,377
C++
.cpp
47
26.87234
102
0.629239
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,950
huffman_coding.cpp
mandliya_algorithms_and_data_structures/greedy_problems/huffman_coding.cpp
/** * Huffman Encoding: * Huffman coding compresses data by using fewer bits to encode more frequently * occurring characters so that not all characters are encoded with 8 bits. * It is a way to assign binary codes to symbols that reduces the overall number of bits * used to encode a typical string of those symbols. * For example, if you use letters as symbols and have details of the frequency of occurrence * of those letters in typical strings, then you could just encode each letter with a fixed number of bits, * such as in ASCII codes. You can do better than this by encoding more frequently occurring letters such as e and a, * with smaller bit strings; and less frequently occurring letters such as q and x with longer bit strings. * More details: https://www.cs.duke.edu/csed/poop/huff/info/ */ #include <iostream> #include <queue> #include <vector> struct HeapNode { char data; unsigned int frequency; HeapNode *left; HeapNode *right; HeapNode(char d, unsigned int fr) : data {d}, frequency {fr}, left {nullptr}, right {nullptr} {} }; // We need a comparator for comparing two nodes. struct compare { bool operator() (HeapNode* node1, HeapNode* node2) { return (node1->frequency > node2->frequency); } }; void generateHuffmanCodeUtil(HeapNode* root, std::string str) { if (!root) return; if (root->data != '$') { std::cout << root->data << " : " << str << std::endl; } generateHuffmanCodeUtil(root->left, str + '0'); generateHuffmanCodeUtil(root->right, str + '1'); } void generateHuffmanCode(std::string data, std::vector<int> frequencies) { HeapNode *left, *right, *top; // Create a minimum heap based on frequency and inserts all characters in it. // std::priority_queue<HeapNode*, std::vector<HeapNode*>, compare> minHeap; unsigned int size = frequencies.size(); for (unsigned int i = 0; i < size; ++i) { minHeap.push(new HeapNode(data[i], frequencies[i])); } while (minHeap.size() != 1) { // Get two minimum nodes from heap. left = minHeap.top(); minHeap.pop(); right = minHeap.top(); minHeap.pop(); // Combine the above two nodes (their frequecies) to generate a // new node.Make these two nodes as left and right children of this new node. // Add this node to the min heap, also assign in '$' as data. (character for internal nodes) // top = new HeapNode('$', left->frequency + right->frequency); top->left = left; top->right = right; minHeap.push(top); } // We are done generating the tree, lets print it. // generateHuffmanCodeUtil(minHeap.top(), ""); } int main() { std::string data{"abcdef"}; std::vector<int> frequencies = { 5, 9, 12, 13, 16, 45 }; generateHuffmanCode(data, frequencies); return 0; }
3,045
C++
.cpp
85
29.882353
118
0.646054
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,951
squareSum.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/squareSum.cpp
/** * Given an array A of n elements, find three indices i, j and k such that A[i]^2 + A[j]^2 = A[K]^2 * O(n2) time complexity and O(1) space complexity */ #include <iostream> #include <vector> #include <algorithm> std::vector<int> squareSum( std::vector<int> & arr ) { std::vector<int> indices{ -1, -1, -1 }; if ( arr.size() < 3 ) { return indices; } std::sort(arr.begin(), arr.end()); for ( size_t i = 0; i < arr.size(); ++i ) { arr[i] = arr[i] * arr[i]; } for ( size_t k = arr.size()-1; k >= 2; k-- ) { size_t i = 0; size_t j = k-1; while ( i < j ) { if ( arr[i] + arr[j] == arr[k] ) { indices[0] = i; indices[1] = j; indices[2] = k; return indices; } if ( arr[i] + arr[j] < arr[k] ) { i++; } else { j--; } } } return indices; } void printVec( std::vector<int> & vec ) { for ( auto v : vec ) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::vector<int> vec{ 1, 2, 3, 4, 5, 6, 7 }; std::cout << "Vec:"; printVec( vec ); std::cout << "Indices i,j and k in above vector which forms A[i]^2 + A[j]^2 = A[k]^2 : "; std::vector<int> indices = squareSum(vec); printVec(indices); return 0; }
1,190
C++
.cpp
50
21.16
99
0.548102
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,952
testBubble.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testBubble.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <bubbleSort.h> #include <generic.h> using namespace std; bool isSorted(int myData[], int size){ for(int i = 0; i < size - 1; i++){ if(myData[i] > myData[i+1]) return false; } return true; } TEST_CASE("Compute bubble sort with small list"){ int small_lyst[] = { 6, 5, 4, 100, 1, 3 }; algo::bubbleSort(small_lyst, 0, 6); REQUIRE( isSorted(small_lyst, 6) == true ); } TEST_CASE("Compute bubble sort with big list"){ const int LENGTH = 1000; int lyst[LENGTH]; for(int i = 0; i < LENGTH; i++){ lyst[i] = LENGTH - i; } algo::bubbleSort(lyst, 0, LENGTH); REQUIRE( isSorted(lyst, 1000) == true ); }
713
C++
.cpp
26
23.884615
49
0.622807
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,953
testFixPoint.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testFixPoint.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <vector> using namespace std; int binarySearchFixedPoint( const std::vector<int> & arr) { int high = arr.size() -1; int low = 0; while ( low <= high ) { int mid = (low + high)/2; if ( arr[mid] == mid ) { return mid; } else if ( mid > arr[mid] ) { low = mid + 1; } else { high = mid - 1; } } return -1; } TEST_CASE("Compute fixed point with small list"){ vector<int> vec {-1, 0, 2, 2, 1000, 10000}; REQUIRE( binarySearchFixedPoint(vec) == 2 ); } TEST_CASE("Compute not finding fixed point with small list"){ vector<int> vec {100, 3333, 10000}; REQUIRE( binarySearchFixedPoint(vec) == -1 ); } TEST_CASE("Compute finding fixed point with big list"){ vector<int> vec; for(int i = 0; i < 100; i++){ vec.push_back(i + 1); } vec.push_back(100); for(int i = 101; i < 1000; i++){ vec.push_back(i + 1); } REQUIRE( binarySearchFixedPoint(vec) == 100 ); }
961
C++
.cpp
38
22.684211
61
0.631121
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,954
testClosestPair.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testClosestPair.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <vector> #include <utility> #include <limits> #include <cmath> using namespace std; std::pair<int,int> closestPair( std::vector<int> & vec1, std::vector<int> & vec2, int x ) { int left = 0; int right = vec2.size() - 1; int minDiff = std::numeric_limits<int>::max(); int leftRes, rightRes; while (left < vec1.size() && right >= 0 ) { int diff = std::abs(vec1[left] + vec2[right] - x); if ( diff < minDiff ) { minDiff = diff; leftRes = left; rightRes = right; } if ( vec1[left] + vec2[right] > x ) { --right; } else { ++left; } } return std::make_pair(vec1[leftRes], vec2[rightRes]); } TEST_CASE("Closest pairs in small list"){ vector<int> l_first {0, 50, 100}; vector<int> l_second {15, 30, 45}; pair<int,int> myPair = closestPair(l_first, l_second, 75); pair<int,int> pear = closestPair(l_first, l_second, 132); REQUIRE( myPair.first == 50 ); REQUIRE( myPair.second == 30 ); REQUIRE( pear.first == 100 ); REQUIRE( pear.second == 30 ); } TEST_CASE("Closest pairs in bigger lists"){ vector<int> l_first {0, 50, 100, 150, 200, 250, 300, 321, 350}; vector<int> l_second {122, 123, 3423, 3451, 4444, 5555, 7777, 99999, 100000}; pair<int,int> myPair = closestPair(l_first, l_second, 3602); pair<int,int> pear = closestPair(l_first, l_second, 3523); REQUIRE( myPair.first == 150 ); REQUIRE( myPair.second == 3451 ); REQUIRE( pear.first == 100 ); REQUIRE( pear.second == 3423 ); } TEST_CASE("Closest pairs in lists of different size"){ vector<int> l_first {0, 50, 100}; vector<int> l_second {122, 123, 3423, 3451, 4444, 5555, 7777, 99999, 100000}; pair<int,int> myPair = closestPair(l_first, l_second, 5657); pair<int,int> pear = closestPair(l_first, l_second, 201); REQUIRE( myPair.first == 100 ); REQUIRE( myPair.second == 5555 ); REQUIRE( pear.first == 100 ); REQUIRE( pear.second == 122 ); }
1,933
C++
.cpp
57
31.350877
91
0.657051
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,955
heapSort.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/heapSort.cpp
#include<iostream> using namespace std; void maxHeapify(int*, int, int); void buildHeap(int*, int); void heapsort(int*, int); int main() { int arr[] = { 4,2,3,1,5,6,8,}; heapsort(arr, sizeof(arr) / sizeof(int)); for (int i = 0; i < sizeof(arr) / sizeof(int); i++) { cout << arr[i] << " "; } return 0; } void maxHeapify(int* arr, int n, int i) { if (i > n / 2 - 1) { //if index of element is greater than i/2 it is in the last level of the heap. no need to call maxHeapify for it. return; } if (arr[i] > arr[2 * i] && arr[i] > arr[(2 * i) + 1]) { //heap property already satisfied. return; } int maxInx = i, temp; while (i <= (n / 2 - 1)) { //finding the index of the largest child of i. if (arr[2 * i + 1] > arr[i] && (2 * i + 1) < n) { maxInx = 2 * i + 1; } if (arr[(2 * i) + 2] > arr[maxInx] && (2 * i + 2) < n) { maxInx = (2 * i) + 2; } //if no change occurs. then return. if (i == maxInx) { return; } //having obtained the index of the largest node swap it with i. //swapping arr[i] with arr[maxInx] temp = arr[maxInx]; arr[maxInx] = arr[i]; arr[i] = temp; i = maxInx; } } void buildHeap(int* arr, int n) { //start calling from the last parent in the heap(n/2) and go upto the root node. //start from the last parent instead of root because here the loop invacriant is that heap condition is //satisfied for all nodes other than the one for which it is called. which would not be true when it is //called for the root node of the array when the array is compeletely random. //refer to CORMEN for more details. for (int i = (n / 2 - 1); i >= 0; i--) { maxHeapify(arr, n, i); } } void heapsort(int* arr, int n) { buildHeap(arr, n); int temp; while (n > 0) { //after the heap is built take the element a[0], swap it with the last element, discard it and call maxheapify //for the root element temp = arr[n - 1]; arr[n - 1] = arr[0]; arr[0] = temp; n--; maxHeapify(arr, n, 0); } }
1,981
C++
.cpp
64
28.390625
115
0.626119
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,956
testFOBS.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testFOBS.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <iostream> #include <vector> #include <algorithm> int firstOccurrenceBinarySearch( const std::vector<int> & vec, int key ) { int high = vec.size() - 1; int low = 0; int firstOccurrance = -1; while ( low <= high ) { int mid = (high + low) / 2; if ( key < vec[mid] ) { high = mid - 1; } else if ( key > vec[mid]) { low = mid + 1; } else { firstOccurrance = mid; high = mid - 1 ; } } return firstOccurrance; } TEST_CASE("Find key 1"){ std::vector<int> arr1{ 8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1 }; sort(arr1.begin(), arr1.end()); REQUIRE( firstOccurrenceBinarySearch(arr1, 20) == 5 ); } TEST_CASE("Find key 2"){ std::vector<int> arr1{1, 1, 1, 2, 3, 4, 4, 5, 234, 234, 234, 234}; REQUIRE( firstOccurrenceBinarySearch(arr1, 234) == 8 ); } TEST_CASE("Find key 3"){ std::vector<int> arr1{1, 1, 1, 2, 3, 4, 4, 5, 234, 234, 234, 234}; REQUIRE( firstOccurrenceBinarySearch(arr1, 124415) == -1 ); } TEST_CASE("Find key 4"){ std::vector<int> arr1{1, 5, 324}; REQUIRE( firstOccurrenceBinarySearch(arr1, -123) == -1 ); }
1,156
C++
.cpp
40
25.75
73
0.610961
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,957
testFindMax.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testFindMax.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <iostream> #include <vector> int findMaximum(std::vector<int> & arr, int low, int high) { // subset has only one element if ( high == low ) { return arr[low]; } //subset has 2 elements if ( high - low == 1 ) { return arr[high] > arr[low] ? arr[high] : arr[low]; } int mid = ( high + low )/2; if ( arr[mid-1] > arr[mid] ) { return findMaximum(arr, low, mid-1); } else { return findMaximum(arr, mid+1, high); } } TEST_CASE("Find max 1"){ std::vector<int> arr1{ 8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1 }; REQUIRE( findMaximum( arr1, 0, arr1.size()-1 ) == 500 ); } TEST_CASE("Find max 2"){ std::vector<int> arr2{1, 3, 50, 10, 9, 7, 6}; REQUIRE( findMaximum( arr2, 0, arr2.size()-1 ) == 50 ); } TEST_CASE("Find max 3"){ std::vector<int> arr3{10, 20, 30, 40, 50}; REQUIRE( findMaximum( arr3, 0, arr3.size()-1 ) == 50 ); } TEST_CASE("Find max 4"){ std::vector<int> arr4{120, 100, 80, 20, 0}; REQUIRE( findMaximum( arr4, 0, arr4.size()-1 ) == 120 ); }
1,033
C++
.cpp
36
26.861111
69
0.620342
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,958
firstRepeatingElement.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/firstRepeatingElement.cpp
/* * Find the first repeating element in an array of integers * Given an array of integers, find the first repeating element in it. * We need to find the element that occurs more than once and whose index of first occurrence is smallest. * Examples: * * Input: arr[] = {10, 5, 3, 4, 3, 5, 6} * Output: 5 [5 is the first element that repeats] * * Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10} * Output: 6 [6 is the first element that repeats] */ #include <iostream> #include <vector> #include <unordered_set> #include <limits> int firstRepeating(std::vector<int> & arr) { std::unordered_set<int> arrSet; int min = -1; int arrSize = (int) arr.size(); for ( int i = arrSize -1; i >= 0; i--) { if ( arrSet.find(arr[i]) != arrSet.end()) { min = i; } else { arrSet.insert(arr[i]); } } if ( min != -1 ) { return arr[min]; } else { return std::numeric_limits<int>::min(); } } void printArray( std::vector<int> & arr ) { std::cout << "Array :"; for (auto a : arr) { std::cout << a << " "; } std::cout << std::endl; } int main() { std::vector<int> arr{6, 10, 5, 4, 9, 120, 4, 6, 10}; printArray(arr); std::cout << "First repeating element in above array is:" << firstRepeating(arr) << std::endl; std::vector<int> arr2 {10, 5, 3, 4, 3, 5, 6}; printArray(arr2); std::cout << "First repeating element in above array is:" << firstRepeating(arr2) << std::endl; return 0; }
1,417
C++
.cpp
49
26.77551
106
0.633824
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,959
commonIn3Arrays.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/commonIn3Arrays.cpp
#include <iostream> #include <vector> void printCommonElements(const std::vector<int>& vec1, const std::vector<int>& vec2, const std::vector<int>& vec3) { std::vector<int>::const_iterator it1 = vec1.begin(); std::vector<int>::const_iterator it2 = vec2.begin(); std::vector<int>::const_iterator it3 = vec3.begin(); while (it1 != vec1.end() && it2 != vec2.end() && it3 != vec3.end()) { if (*it1 == *it2 && *it2 == *it3) { std::cout << *it1 << " "; it1++; it2++; it3++; } else if (*it1 < *it2) { ++it1; } else if (*it2 < *it3) { ++it2; } else { ++it3; } } std::cout << std::endl; } int main() { std::vector<int> vec1 {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; std::vector<int> vec2 {3, 6, 9, 12, 15, 18, 21}; std::vector<int> vec3 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; printCommonElements(vec1, vec2, vec3); return 0; }
1,129
C++
.cpp
41
19.658537
98
0.456642
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,960
testCommon.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testCommon.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <vector> using namespace std; vector<int> commonElements(const std::vector<int>& vec1, const std::vector<int>& vec2, const std::vector<int>& vec3) { std::vector<int>::const_iterator it1 = vec1.begin(); std::vector<int>::const_iterator it2 = vec2.begin(); std::vector<int>::const_iterator it3 = vec3.begin(); vector<int> vec4; while (it1 != vec1.end() && it2 != vec2.end() && it3 != vec3.end()) { if (*it1 == *it2 && *it2 == *it3) { std::cout << *it1 << " "; vec4.push_back(*it1); it1++; it2++; it3++; } else if (*it1 < *it2) { ++it1; } else if (*it2 < *it3) { ++it2; } else { ++it3; } } return vec4; } TEST_CASE("Closest one common in small arrays"){ vector<int> l_first {0, 15, 50, 100}; vector<int> l_second {15, 30, 45}; vector<int> l_third {1, 2, 3, 15}; vector<int> mine = commonElements(l_first, l_second, l_third); REQUIRE( mine.size() == 1 ); REQUIRE( mine.at(0) == 15 ); } TEST_CASE("Closest common in larger arrays"){ vector<int> l_first {0, 15, 50, 100, 150, 200, 250, 300, 350}; vector<int> l_second {15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 200, 210, 225, 240}; vector<int> l_third {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210}; vector<int> mine = commonElements(l_first, l_second, l_third); REQUIRE( mine.size() == 2 ); REQUIRE( mine.at(0) == 150 ); REQUIRE( mine.at(1) == 200 ); }
1,649
C++
.cpp
52
26.326923
118
0.555556
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,962
closest_nums.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/closest_nums.cpp
/* Given a list of unsorted integers, A={a1,a2,…,aN}, Find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all. Input: N= Number of elements, followed by N elements. Output: Output the pairs of elements with the smallest difference. If there are multiple pairs, output all of them in ascending order, all on the same line (consecutively) with just a single space between each pair of numbers. If there's a number which lies in two pair, print it two times Example: Input : 4 5 4 3 2 Output: 2 3 3 4 4 5 */ #include <iostream> #include <vector> #include <algorithm> #include <climits> using namespace std; int main() { int N; vector<int> vec; cin >> N; int x; for ( int i = 0; i < N; ++i) { cin >> x; vec.push_back(x); } sort(vec.begin(), vec.end()); int mindiff = INT_MAX; for( size_t i = 0; i < vec.size()-1; ++i){ if (vec[i+1]-vec[i] < mindiff) { mindiff = vec[i+1]-vec[i]; } } for( size_t i =0; i < vec.size()-1; ++i ) { if (vec[i+1]-vec[i] == mindiff) { std::cout << vec[i] << " " << vec[i+1] << " "; } } std::cout << std::endl; return 0; }
1,268
C++
.cpp
38
28.368421
289
0.599511
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,964
findClosestPairToZero.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/findClosestPairToZero.cpp
/** * An Array of integers is given, both +ve and -ve. You need to find the two elements such that their sum is closest to zero. * Example: * vec : { 1, 60, -10, 70, -80, 85 } * * output: -80, 85 * * If no such pair exists return a { 0, 0 } pair * */ #include <iostream> #include <vector> #include <algorithm> #include <utility> #include <limits> std::pair<int, int> pairSumClosestToZero( std::vector<int> & vec ) { std::pair<int, int> minPair( 0, 0 ); if ( vec.size() < 2 ) { return minPair; } size_t minLeft = 0, minRight = vec.size()-1; size_t left = 0, right = vec.size() -1; int minSum = std::numeric_limits<int>::max(); std::sort( vec.begin(), vec.end() ); while( left < right ) { int sum = vec[left] + vec[right]; if ( std::abs(minSum) > std::abs(sum) ) { minSum = sum; minLeft = left; minRight = right; } if ( sum > 0 ) { --right; } else { ++left; } } minPair.first = vec[minLeft]; minPair.second = vec[minRight]; return minPair; } int main() { std::vector<int> vec{ 1, 60, -10, 70, -80, 85 }; std::cout << "Vec: "; for ( auto v : vec ) { std::cout << v << " "; } std::pair<int, int> minPair = pairSumClosestToZero(vec); std::cout << "Pair whose sum is closes to 0 in above vector is: (" << minPair.first << ", " << minPair.second << ")" << std::endl; return 0; }
1,344
C++
.cpp
52
23.480769
125
0.607782
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,965
testClosestZero.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testClosestZero.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <vector> #include <algorithm> #include <utility> #include <limits> using namespace std; std::pair<int, int> pairSumClosestToZero( std::vector<int> & vec ) { std::pair<int, int> minPair( 0, 0 ); if ( vec.size() < 2 ) { return minPair; } size_t minLeft = 0, minRight = vec.size()-1; size_t left = 0, right = vec.size() -1; int minSum = std::numeric_limits<int>::max(); std::sort( vec.begin(), vec.end() ); while( left < right ) { int sum = vec[left] + vec[right]; if ( std::abs(minSum) > std::abs(sum) ) { minSum = sum; minLeft = left; minRight = right; } if ( sum > 0 ) { --right; } else { ++left; } } minPair.first = vec[minLeft]; minPair.second = vec[minRight]; return minPair; } TEST_CASE("Closest pairs to zero test 1"){ vector<int> lyst { 2, -100, -80, 2, 4, 300, 74}; pair<int,int> mine = pairSumClosestToZero(lyst); REQUIRE( mine.first == 2 ); REQUIRE( mine.second == 2 ); } TEST_CASE("Closest pairs to zero test 2"){ vector<int> lyst { -10123, -3414, 3, -34664, 10023, 6526, 47324, 100, 2351, 37345, 12576, 12356}; pair<int,int> mine = pairSumClosestToZero(lyst); REQUIRE( mine.first == -10123 ); REQUIRE( mine.second == 10023 ); } TEST_CASE("Closest pairs to zero on huge array"){ vector<int> lyst; for(int i = 20000; i < 20100; i++){ lyst.push_back(i); } lyst.push_back(-5); lyst.push_back(7); pair<int,int> mine = pairSumClosestToZero(lyst); REQUIRE( mine.first == -5 ); REQUIRE( mine.second == 7 ); }
1,544
C++
.cpp
56
25.214286
98
0.65
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,967
testFRE.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testFRE.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <vector> #include <unordered_set> #include <limits> using namespace std; int firstRepeating(std::vector<int> & arr) { std::unordered_set<int> arrSet; int min = -1; int arrSize = (int) arr.size(); for ( int i = arrSize -1; i >= 0; i--) { if ( arrSet.find(arr[i]) != arrSet.end()) { min = i; } else { arrSet.insert(arr[i]); } } if ( min != -1 ) { return arr[min]; } else { return std::numeric_limits<int>::min(); } } TEST_CASE("Find first repeat 1"){ vector<int> arr1{234, 453465, 234, 6345, 14123, 624, 44, 34, 26, 7345 }; REQUIRE( firstRepeating(arr1) == 234 ); } TEST_CASE("Find first repeat 2"){ vector<int> arr1{234, 453465, 6345, 14123, 624, 44, 34, 26, 7345 }; int theLimit = std::numeric_limits<int>::min(); REQUIRE( firstRepeating(arr1) == theLimit ); } TEST_CASE("Find first repeat 3"){ vector<int> arr1; for(int i = 0; i < 1000; i++){ if(i == 44){ arr1.push_back(44); } arr1.push_back(i); } REQUIRE( firstRepeating(arr1) == 44 ); }
1,043
C++
.cpp
42
22.738095
73
0.642929
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,968
find_pairs_with_sum.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/find_pairs_with_sum.cpp
/* * Problem: * Given an unsorted array of integers, find a pair with given sum in it. * For example, * Input: * arr = [8, 7, 2, 5, 3, 1] * sum = 10 * * Output: * Pair found at index 0 and 2 (8 + 2) * OR * Pair found at index 1 and 4 (7 + 3) */ #include <iostream> #include <vector> #include <unordered_map> void printPairWithSum(const std::vector<int>& arr, const int sum) { std::unordered_map<int, int> hashMap; bool found = false; for (unsigned int i = 0; i < arr.size(); ++i) { // We need to check if pair(arr[i], sum-arr[i]) already // exists in the map // if (hashMap.find(sum-arr[i]) != hashMap.end()) { std::cout << "Found pair with sum: " << sum << " with values (" << sum-arr[i] << " ," << arr[i] << ") at indices (" << hashMap[sum-arr[i]] << " ," << i << ")" << std::endl; found = true; } hashMap[arr[i]] = i; } if (!found) std::cout << "Pair not found\n"; } int main() { std::vector<int> arr {8, 7, 2, 5, 3, 1}; printPairWithSum(arr, 10); return 0; }
1,193
C++
.cpp
43
21.418605
74
0.502191
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,969
missingNumber2.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/missingNumber2.cpp
/** * Find the missing number in Arithmetic Progression * Examples: * Input: arr[] = {2, 4, 8, 10, 12, 14} * Output: 6 * * Input: arr[] = {1, 6, 11, 16, 21, 31}; * Output: 26 */ #include <iostream> #include <vector> #include <limits> int findMissingUtil( std::vector<int> & vec, int diff) { size_t low = 0; size_t high = vec.size() - 1; while ( low < high ) { size_t mid = ( low + high ) / 2; //check if the missing element just after mid index is missing. if ( mid < vec.size() - 1 && vec[mid + 1] - vec[mid] != diff ) { return vec[mid] + diff; } // the element just before mid is missing. if ( mid > 0 && vec[mid-1] - vec[mid] != diff ) { return vec[mid - 1] + diff; } //the sub array before mid is following AP if ( vec[mid] == vec[0] + diff * mid ) { low = mid + 1; } else { high = mid - 1; } } return std::numeric_limits<int>::max(); } void printVec( std::vector<int> & vec ) { std::cout << "Vec: "; for ( auto v : vec ) { std::cout << v << " "; } std::cout << std::endl; } int missingNumber( std::vector<int> & vec ) { int diff = (vec[vec.size() - 1] - vec[0])/(vec.size()); return findMissingUtil( vec, diff ); } int main() { std::vector<int> vec{ 2, 4, 8, 10, 12, 14 }; printVec(vec); std::cout << "Missing number in above arithmetic progression is : " << missingNumber(vec) << std::endl; return 0; }
1,384
C++
.cpp
52
24.230769
68
0.59139
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,970
testClosestNums.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/testClosestNums.cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <iostream> #include <vector> #include <algorithm> #include <climits> using namespace std; TEST_CASE("Compute mindiff 1"){ vector<int> small_lyst; small_lyst.push_back(2); small_lyst.push_back(6); small_lyst.push_back(234); small_lyst.push_back(734); small_lyst.push_back(25687); small_lyst.push_back(1); sort(small_lyst.begin(), small_lyst.end()); int mindiff = INT_MAX; int mySizem = static_cast<int>(small_lyst.size() - 1); for( int i = 0; i < mySizem; i++){ if (small_lyst[i+1]-small_lyst[i] < mindiff) { mindiff = small_lyst[i+1]-small_lyst[i]; } } vector<int> newList; for( int i =0; i < mySizem; i++ ) { if (small_lyst[i+1]-small_lyst[i] == mindiff) { newList.push_back(small_lyst[i]); newList.push_back(small_lyst[i+1]); } } REQUIRE( newList.size() == 2 ); REQUIRE( newList.at(0) == 1 ); REQUIRE( newList.at(1) == 2 ); }
976
C++
.cpp
34
25
55
0.634328
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,971
fixedPoint.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/fixedPoint.cpp
/** * Given a sorted array of numbers, determine if there exists a fixed point, if so return index, or return -1. Fixed point in array is when i = arr[i]. */ #include<iostream> #include<vector> int binarySearchFixedPoint( const std::vector<int> & arr) { int high = arr.size() -1; int low = 0; while ( low <= high ) { int mid = (low + high)/2; if ( arr[mid] == mid ) { return mid; } else if ( mid > arr[mid] ) { low = mid + 1; } else { high = mid - 1; } } return -1; } void printVec( std::vector<int> & vec ) { std::cout << "VEC:"; for ( auto & v : vec ) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::vector<int> vec { -10, -1, 0, 3, 10, 11, 30, 50, 100 }; printVec(vec); int fixedPoint = binarySearchFixedPoint(vec); if (fixedPoint != -1) { std::cout << "Above vector has a fixed point at index(0 indexed): " << fixedPoint << std::endl; } else { std::cout << "Above vector has no fixed point\n"; } return 0; }
982
C++
.cpp
38
23.605263
151
0.608511
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,972
first_occurrence_binary_search.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/first_occurrence_binary_search.cpp
/** * Given a sorted array, and a number. * User binary search to find the number, and return the index.If number occurrs multiple times * return the first index. If number does not exist, return -1. */ #include <iostream> #include <vector> int firstOccurrenceBinarySearch( const std::vector<int> & vec, int key ) { int high = vec.size() - 1; int low = 0; int firstOccurrance = -1; while ( low <= high ) { int mid = (high + low) / 2; if ( key < vec[mid] ) { high = mid - 1; } else if ( key > vec[mid]) { low = mid + 1; } else { firstOccurrance = mid; high = mid - 1 ; } } return firstOccurrance; } void printVec( const std::vector<int> & vec) { for ( auto & i : vec ) { std::cout << i << " "; } std::cout << std::endl; } int main() { std::vector<int> vec{ 1, 1, 1, 1, 2, 2, 3, 3, 3 }; std::cout << "Contents of vector:\n"; printVec(vec); std::cout << "First Occurrence of 1 in the vector is at index : " << firstOccurrenceBinarySearch(vec, 1) << std::endl; return 0; }
1,099
C++
.cpp
41
22.731707
96
0.582146
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,973
missingNumbers.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/missingNumbers.cpp
/** * Problem Statement * * Numeros, the Artist, had two lists A and B, such that B was a permutation of A. * Numeros was very proud of these lists. Unfortunately, while transporting them from one exhibition to another, some numbers were left out of A. * Can you find the missing numbers? * * Notes * * If a number occurs multiple times in the lists, you must ensure that the frequency of that number in both lists is the same. * If that is not the case, then it is also a missing number. * You have to print all the missing numbers in ascending order. * Print each missing number once, even if it is missing multiple times. * The difference between maximum and minimum number in B is less than or equal to 100. * Input Format * There will be four lines of input: * * n - the size of the first list * This is followed by n space-separated integers that make up the first list. * m - the size of the second list * This is followed by m space-separated integers that make up the second list. * * Output Format * Output the missing numbers in ascending order. */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main() { long n,m; cin >> n; long *list1 = new long[n]; for (long i = 0; i < n; ++i) { cin >> list1[i]; } cin >> m; long *list2 = new long[m]; for (long i = 0; i < m; ++i) { cin >> list2[i]; } unordered_map<long,long> hash; for (long i = 0; i < m; ++i) { hash[list2[i]]++; } for (long i = 0; i < n; ++i) { hash[list1[i]]--; } unordered_map<long,long>::iterator it; vector<long> results; for (it = hash.begin(); it != hash.end(); ++it){ if ( it->second > 0) { results.push_back(it->first); } } sort(results.begin(), results.end()); vector<long>::iterator i; for (i = results.begin(); i != results.end(); ++i){ cout << *i << " "; } return 0; }
2,034
C++
.cpp
65
27.4
145
0.639695
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,974
minLengthUnsortedArray.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/minLengthUnsortedArray.cpp
/** * Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted. * Examples: * 1) If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between the indexes 3 and 8. * * 2) If the input array is [0, 1, 15, 25, 6, 7, 30, 40, 50], your program should be able to find that the subarray lies between the indexes 2 and 5. */ #include <iostream> #include <vector> #include <utility> std::pair<size_t, size_t> minLengthSubarray( std::vector<int> arr ) { //step 1: scan from left to right, find first element which is greater than next element size_t start = 0; for ( start = 0; start < arr.size() - 1; ++start ) { if ( arr[start] > arr[start+1] ) { break; } } if ( start == arr.size() - 1 ) { return std::make_pair(0,0); } //step 2: scan from right to left, and find first element(from right) //which is smaller than element before it( on left) size_t end; for ( end = arr.size() - 1; end > 0; --end ) { if ( arr[end] < arr[end-1] ) { break; } } // find minimum and maximum element in arr[start..end] int min = arr[start], max = arr[start]; for ( size_t i = start + 1; i <= end; ++i ) { if ( arr[i] > max ) { max = arr[i]; } if ( arr[i] < min ) { min = arr[i]; } } // find the first element bigger than min in subarry arr[0..start-1], and // change the start index to that element index for ( size_t i = 0; i < start; ++i ) { if ( arr[i] > min ) { start = i; break; } } // similarly find first element from right which is smaller than max, and // change the end index to that element index for ( size_t i = arr.size() - 1; i >= end+1 ; --i ) { if ( arr[i] < max ) { end = i; break; } } return std::make_pair( start, end ); } void printVec( std::vector<int> & vec, size_t begin, size_t end ) { for ( size_t i = begin; i <= end; ++i ) { std::cout << vec[i] << " "; } std::cout << std::endl; } int main() { std::vector<int> vec1{10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60}; std::pair<size_t, size_t> subArrayIndices = minLengthSubarray(vec1); std::cout << "Array:"; printVec( vec1, 0, vec1.size() - 1 ); size_t start = subArrayIndices.first; size_t end = subArrayIndices.second; if ( start == 0 && end == 0 ) { std::cout << "Above array is already sorted\n"; } else { std::cout << "Min length subarray in above array which needs to be sorted to sort above array completely is : "; printVec(vec1, start, end); } std::vector<int> vec2 { 0, 1, 15, 25, 6, 7, 30, 40, 50 }; subArrayIndices = minLengthSubarray(vec2); std::cout << "Array:"; printVec( vec2, 0, vec2.size() - 1 ); start = subArrayIndices.first; end = subArrayIndices.second; if ( start == 0 && end == 0 ) { std::cout << "Above array is already sorted\n"; } else { std::cout << "Min length subarray in above array which needs to be sorted to sort above array completely is : "; printVec(vec2, start, end); } return 0; }
3,065
C++
.cpp
90
31.588889
161
0.63535
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,977
closestPairSorted.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/closestPairSorted.cpp
/** * Find the closest pair from two sorted arrays * Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array. * We are given two arrays ar1[0…m-1] and ar2[0..n-1] and a number x, we need to find the pair ar1[i] + ar2[j] such that absolute value of (ar1[i] + ar2[j] – x) is minimum. * Input: ar1[] = {1, 4, 5, 7}; * ar2[] = {10, 20, 30, 40}; * x = 32 * Output: 1 and 30 * * Input: ar1[] = {1, 4, 5, 7}; * ar2[] = {10, 20, 30, 40}; * x = 50 * Output: 7 and 40 */ #include <iostream> #include <vector> #include <utility> #include <limits> #include <cmath> std::pair<int,int> closestPair( std::vector<int> & vec1, std::vector<int> & vec2, int x ) { int left = 0; int right = vec2.size() - 1; int minDiff = std::numeric_limits<int>::max(); int leftRes, rightRes; while (left < vec1.size() && right >= 0 ) { int diff = std::abs(vec1[left] + vec2[right] - x); if ( diff < minDiff ) { minDiff = diff; leftRes = left; rightRes = right; } if ( vec1[left] + vec2[right] > x ) { --right; } else { ++left; } } return std::make_pair(vec1[leftRes], vec2[rightRes]); } void printVec( std::vector<int> & vec ) { for ( auto v : vec ) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::vector<int> vec1 {1, 4, 5, 7}; std::vector<int> vec2 {10, 20, 30, 40}; std::cout << "Vec1: "; printVec(vec1); std::cout << "Vec2: "; printVec(vec2); int x = 32; std::cout << "x : " << x << std::endl; std::pair<int,int> result = closestPair(vec1, vec2, x); std::cout << "The closest pair from the above two sorted vectors to " << x << " is " << "(" << result.first << ", " << result.second << ")" << std::endl; std::vector<int> vec3 {1, 4, 5, 7}; std::vector<int> vec4 {10, 20, 30, 40}; std::cout << "Vec3: "; printVec(vec3); std::cout << "Vec4: "; printVec(vec4); x = 50; std::cout << "x : " << x << std::endl; std::pair<int,int> result2 = closestPair(vec3, vec4, x); std::cout << "The closest pair from the above two sorted vectors to " << x << " is " << "(" << result2.first << ", " << result2.second << ")" << std::endl; return 0; }
2,244
C++
.cpp
70
29.742857
172
0.574596
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,978
move_zeros.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/move_zeros.cpp
/* * Given a vector containing numbers, move all the 0s in the vector to the end. * example: * vec = [1, 0, 4, 5, 3, 0, 7, 8, 0, 10] * output = [1, 4, 5, 3, 7, 8, 10, 0, 0, 0] * * Idea is to move non-zero elements sequentially to next available position starting from 0. * After all elements in the array are processed, we fill all remaining indexes by 0. */ #include <iostream> #include <vector> void moveZeros(std::vector<int>& vec) { unsigned int j = 0; unsigned int size = vec.size(); for (unsigned int i = 0; i < size; ++i) { if (vec[i] != 0) vec[j++] = vec[i]; } while(j < size) { vec[j++] = 0; } } void printVector(const std::vector<int>& vec) { std::cout << "Vector contents: "; for (auto x:vec) { std::cout << x << " "; } std::cout << std::endl; } int main() { std::vector<int> vec {1, 0, 4, 5, 3, 0, 7, 8, 0, 10}; printVector(vec); std::cout << "Moving zeros to the back..\n"; moveZeros(vec); printVector(vec); return 0; }
1,106
C++
.cpp
43
20.697674
94
0.55038
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,979
findMaximum.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/findMaximum.cpp
/** * Find the maximum element in an array which is first increasing and then decreasing. * Input: arr[] = {8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1} * Output: 500 * * Also consider cases like * Input: arr[] = {10, 20, 30, 40, 50} * Output: 50 * * Input: arr[] = {120, 100, 80, 20, 0} * Output: 120 */ #include <iostream> #include <vector> int findMaximum(std::vector<int> & arr, int low, int high) { // subset has only one element if ( high == low ) { return arr[low]; } //subset has 2 elements if ( high - low == 1 ) { return arr[high] > arr[low] ? arr[high] : arr[low]; } int mid = ( high + low )/2; if ( arr[mid-1] > arr[mid] ) { return findMaximum(arr, low, mid-1); } else { return findMaximum(arr, mid+1, high); } } void printVec( std::vector<int> & arr ) { std::cout << "Arr:"; for ( auto & a : arr ) { std::cout << a << " "; } std::cout << std::endl; } int main() { std::vector<int> arr1{ 8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1 }; printVec(arr1); std::cout << "Max in above arr:" << findMaximum( arr1, 0, arr1.size()-1 ) << std::endl; std::vector<int> arr2{1, 3, 50, 10, 9, 7, 6}; printVec(arr2); std::cout << "Max in above arr:" << findMaximum( arr2, 0, arr2.size()-1 ) << std::endl; std::vector<int> arr3{10, 20, 30, 40, 50}; printVec(arr3); std::cout << "Max in above arr:" << findMaximum( arr3, 0, arr3.size()-1 ) << std::endl; std::vector<int> arr4{120, 100, 80, 20, 0}; printVec(arr4); std::cout << "Max in above arr:" << findMaximum( arr4, 0, arr4.size()-1 ) << std::endl; return 0; }
1,567
C++
.cpp
52
27.961538
88
0.599867
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,980
peak_element.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/peak_element.cpp
/* * Given an array, find peak element in it. A peak element is an element that is greater than its neighbors. * For example, * * Input : [8, 9, 10, 2, 5, 6] * Output: The peak element is 10 * Input : [8, 9, 10, 12, 15] * Output: The peak element is 15 * Input : [10, 8, 6, 5, 3, 2] * Output: The peak element is 10 */ #include <iostream> int findPeak(int arr[], int n, int low, int high) { // mid point // int mid = (low + high) / 2; // check if mid element is peak // if ((mid == 0 || arr[mid-1] <= arr[mid]) && (mid == n-1 || arr[mid+1] <= arr[mid])) { return mid; } // if left neighbour of mid is greater than mid element // then peak would be in left array. if (mid - 1 >= 0 && arr[mid-1] > arr[mid]) { return findPeak(arr, n, low, mid-1); } // search the right side otherwise. // return findPeak(arr, n, mid+1, high); } int main() { int arr[] = {10, 20, 30, 25, 15}; int n = sizeof(arr) / sizeof(arr[0]); int peakIndex = findPeak(arr, n, 0, n-1); std::cout << "The peak element of the array is:" << arr[peakIndex] << std::endl; return 0; }
1,231
C++
.cpp
43
23.325581
109
0.547395
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,981
smallest_missing.cpp
mandliya_algorithms_and_data_structures/sort_search_problems/smallest_missing.cpp
/* * Given a sorted array of distinct non-negative integers, find smallest missing element in it. * For example, * Input: A[] = [0, 1, 2, 6, 9, 11, 15] * Output: The smallest missing element is 3 * Input: A[] = [1, 2, 3, 4, 6, 9, 11, 15] * Output: The smallest missing element is 0 * Input: A[] = [0, 1, 2, 3, 4, 5, 6] * Output: The smallest missing element is 7 */ #include <iostream> #include <vector> int missingElement(const std::vector<int>& arr, int low, int high) { if (low > high) { return low; } int mid = low + (high - low)/2; // if mid index matches the with the mid element, then smallest // missing element lies on the right of the mid. if (arr[mid] == mid) { return missingElement(arr, mid + 1, high); } else { return missingElement(arr, low, mid - 1); } } void print(const std::vector<int>& arr) { std::cout << "Contents of array:" << std::endl; for (auto i : arr) { std::cout << i << " "; } std::cout << std::endl; } int main() { std::vector<int> arr{0, 1, 2, 3, 4, 6, 7}; print(arr); int low = 0; int high = arr.size() -1; std::cout << "Smallest missing element in array is :" << missingElement(arr, low, high) << std::endl; return 0; }
1,366
C++
.cpp
49
22.55102
96
0.565251
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,983
pow.cpp
mandliya_algorithms_and_data_structures/math_problems/pow.cpp
/* * A simple divide and conquer approach to calculate pow(x,y) */ #include <iostream> double pow( double x, int y ) { //base case if ( y == 0 ) { return 1; } double temp = pow(x, y/2); if ( y % 2 == 0 ) { return temp * temp; } else { if ( y > 0 ) { return x * temp * temp; } else { return ( temp * temp ) / x; } } } int main() { std::cout << "Program to calculate power y to the base x\n"; double x; int y; std::cout << "Enter base : "; std::cin >> x; std::cout << "Enter power(int + or -) : "; std::cin >> y; std::cout << "Power " << y << " to the base " << x << " is: "; std::cout << pow(x, y) << std::endl; return 0; }
664
C++
.cpp
34
17.382353
63
0.544728
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,984
gcd.cpp
mandliya_algorithms_and_data_structures/math_problems/gcd.cpp
/** * Given two numbers, determine the greatest common divisior of the two numbers. */ #include <iostream> int gcd1( int a, int b ) { while( b > 0 ) { int temp = a % b; a = b; b = temp; } return a; } int gcd2( int a, int b ) { if ( b == 0 ) return a; if ( a == 0 ) return b; return gcd2(b, a % b); } int gcd3( int a, int b ) { if ( a == 0 ) return b; if ( b == 0 ) return a; while ( a != b ) { if ( a > b ) { a = a-b; } else { b = b-a; } } return a; } int gcd4 ( int a, int b ) { if ( a == 0 ) return b; if ( b == 0 ) return a; if ( a == b ) return a; if ( a > b ) return gcd4(b, a-b); else return gcd4(a, b-a); } int main() { int a, b; std::cout << "Enter number 1 : "; std::cin >> a; std::cout << "Enter number 2 : "; std::cin >> b; std::cout << "GCD of " << a << " and " << b << " is " << gcd1(a,b) << std::endl; std::cout << "GCD of " << a << " and " << b << " is " << gcd2(a,b) << std::endl; std::cout << "GCD of " << a << " and " << b << " is " << gcd3(a,b) << std::endl; std::cout << "GCD of " << a << " and " << b << " is " << gcd4(a,b) << std::endl; return 0; }
1,374
C++
.cpp
53
19.245283
82
0.397858
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
25,985
factorial_of_large_num.cpp
mandliya_algorithms_and_data_structures/math_problems/factorial_of_large_num.cpp
/** * Factorial of a very large number, say 100. It would be of 158 digits long. We will store the result in a vector. * We can do this by doing normal multiplication algorithm, however we will store digits in an array. * let's just take an example of normal multiplication of 189 to 10, output would be 1890. * so step store digits of 189 in a vector in reverse order. * result[] = { 9, 8, 1 } * m = 10 * prod = 1 * carry = 0 * i = 0 --> prod = result[0] * m + carry = 9 * 10 + 0 = 90 * result[0] = 0 , carry = 9 * * i = 1 --> prod = result[1] * m + carry = 8 * 10 + 9 = 89 * result[1] = 9, carry = 8 * * i = 2 --> prod = result[2] * m + carry = 1 * 10 + 8 = 18 * result[2] = 8, carry = 1 * * result[3] = carry = 1 * * result = { 0, 9, 8, 1 } * */ #include <iostream> #include <vector> #include <algorithm> // look at above example to understand this function void multiply( std::vector<int> & result, int m ) { int carry = 0; for (unsigned int i = 0; i < result.size(); ++i ) { int prod = result[i] * m + carry; result[i] = prod % 10; carry = prod / 10; } while( carry ) { result.push_back(carry % 10 ); carry /= 10; } } std::vector<int> factorial( int n ) { std::vector<int> result{ 1 }; for ( int i = 2; i <= n; ++i ) { multiply(result, i); } return result; } void print_num( std::vector<int> & vec ) { for(std::vector<int>::reverse_iterator it = vec.rbegin(); it != vec.rend(); ++it) { std::cout << *it; } std::cout << std::endl; } int main() { std::cout << "Program for calculating large number factorial\n"; std::cout << "Enter a number:"; int n; std::cin >> n; std::vector<int> res = factorial(n); print_num(res); return 0; }
1,826
C++
.cpp
66
23.787879
115
0.569222
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,986
lowest_possible_number.cpp
mandliya_algorithms_and_data_structures/math_problems/lowest_possible_number.cpp
/* * Problem: * Given a string representation of a number, remove n characters * from the string such that number representation is lowest possible. * * Example: * Input: * str = "4325043", n = 3 * Output: * "2043" * * Input: * str = "765028321", n = 5 * Output: * "0221" * * Input: * str = "12345", n = 6 * Output: * 0 * * Input: * str = "12345", n = 0 * Output: * 12345 */ #include <iostream> void build_lowest_number(const std::string& num, std::string& result, int n) { // If 0 characters are left to remove, append everything to result. if (n == 0) { result.append(num); return; } int len = num.length(); // If there are more characters to remove than string length. // remove nothing and return, last example above. if (n >= len) { return; } // Now, we will find the minimum digit in n+1 characters. // Since we need to remove, smallest of n+1 digits should be // part of final string. int min_index = 0; for (int i = 1; i <= n; ++i) { if (num[i] < num[min_index]) { min_index = i; } } result.push_back(num[min_index]); std::string remaining_num = num.substr(min_index + 1, len - min_index); build_lowest_number(remaining_num, result, n-min_index); } int main() { std::string num_string{"4325043"}; std::string result; std::cout << "Number: " << num_string << std::endl; std::cout << "After removing 5 characters, smallest possible number:" << std::endl; build_lowest_number(num_string, result, 3); std::cout << result << std::endl; return 0; }
1,658
C++
.cpp
66
20.984848
73
0.604548
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,988
string_permutations.cpp
mandliya_algorithms_and_data_structures/math_problems/string_permutations.cpp
/* * Problem: Print all the permutations of a string. * * Details: Permutation is "arrangement number" or "order". So problem is given a string, how many strings can we produce by rearranging them. * * Example: Permutations of ABC are ABC, ACB, BCA, BAC, CAB, CBA * * Approach: Lets take a backtracking approach. We select one letter, then recursively permute the remaining letters. * At each step of permutation process, the given set will have two parts, a part we have already processed and the part we are yet to process. * So, at ith step we exchange the i’th value with the value being chosen at that stage. * */ #include <iostream> #include <cstring> /* * Helper routine to swap pointers */ void swap( char *a, char *b ) { char temp = *a; *a = *b; *b = temp; } /* * Function : Permute * Arg 1: c string * Arg 2: starting index of the string. * Arg 3: ending index of the string/ */ void permute(char *str, int l, int r) { if (l == r) { std::cout << str << std::endl; } for (int i = l; i <= r; ++i) { swap( (str + l), (str + i) ); permute(str, l+1, r); swap( (str + l), (str + i) ); } } int main() { char str[] = "abc"; std::cout << "Permutations of the string " << str << " are :\n"; permute(str, 0, std::strlen(str)-1); return 0; }
1,372
C++
.cpp
49
24.755102
153
0.619879
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,989
phone_digits.cpp
mandliya_algorithms_and_data_structures/math_problems/phone_digits.cpp
/** * Given a normal keypad. * _________________________ * | 1 | 2 | 3 | * | | abc | def | * _________________________ * | 4 | 5 | 6 | * | ghi | jkl | mno | * ________________________ * | 7 | 8 | 9 | * | pqrs | tuv | wxyz | * _________________________ * * and a n digit number, list all the words which are possible by pressing these n digits. * example * 234 - adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi * cdg cdh cdi ceg ceh cei cfg cfh cfi */ #include <iostream> #include <string> #include <unordered_map> #include <sstream> #include <vector> std::unordered_map<char, std::string> table{ { '0', "" }, { '1', "" }, { '2', "abc"}, { '3', "def"}, { '4', "ghi"}, { '5', "jkl"}, { '6', "mno"}, { '7', "pqrs"}, { '8', "tuv"}, { '9', "wxyz"} }; void get_words( std::string input, unsigned int curr_digit, std::string & curr_str, std::vector<std::string> & output) { if ( curr_digit == input.size()) { output.push_back(curr_str); return; } std::string curr_alphas{ table[input[curr_digit]] }; for( unsigned int i = 0; i < curr_alphas.size(); ++i ) { curr_str[curr_digit] = curr_alphas[i]; get_words( input, curr_digit + 1, curr_str, output); if (curr_alphas[i] == '0' || curr_alphas[i] == '1') { return; } } } int main() { std::string input; std::cout << "Enter a number:"; std::cin >> input; std::vector<std::string> output; std::string curr_string(input.size(), ' '); get_words(input, 0, curr_string, output); for ( auto & word : output ) { std::cout << word << std::endl; } return 0; }
2,145
C++
.cpp
62
24.419355
90
0.398941
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,990
stackDemo.cpp
mandliya_algorithms_and_data_structures/stack_problems/stackDemo.cpp
#include <iostream> #include <stack.h> int main() { algo::Stack<double> st{10}; for ( int i = 0; i < 10; ++i) { st.push( i ); } st.print(); while (!st.empty()) { std::cout << st.top() << " "; st.pop(); } while (st.size() > 0) { std::cout << st.top() << " "; st.pop(); } std::cout << std::endl; return 0; }
388
C++
.cpp
20
14.3
37
0.434426
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
25,994
list.h
mandliya_algorithms_and_data_structures/include/list.h
#ifndef LIST_H #define LIST_H #include "generic.h" namespace algo { template <typename Object> class List { private: class ListNode { public: ListNode( const Object & obj = Object{ }, ListNode *pNext = nullptr, ListNode *pPrev = nullptr ) : element{ obj }, next { pNext }, prev { pPrev } { } ListNode( const Object && obj, ListNode *pNext = nullptr, ListNode *pPrev = nullptr ) : element( std::move( obj ) ), next ( pNext ), prev ( pPrev ) { } private: Object element; ListNode* next; ListNode* prev; friend class List<Object>; }; //end of class ListNode public: class const_iterator { public: const_iterator( ) : current{ nullptr } { } const Object& operator* ( ) const { return retrieve( ); } const_iterator& operator++ ( ) { current = current->next; return *this; } const_iterator operator++ ( int ) { const_iterator old = *this; ++ ( *this ); return old; } const_iterator & operator-- ( ) { current = current->prev; return *this; } const_iterator operator-- ( int ) { const_iterator old = *this; --( *this ); return old; } bool operator== ( const const_iterator& rhs ) const { return ( current == rhs.current ); } bool operator!= ( const const_iterator& rhs ) const { return ( current != rhs.current ); } protected: ListNode *current; Object& retrieve ( ) const { return current->element; } const_iterator( ListNode *p ) : current{ p } { } friend class List<Object>; }; //end of class const_iterator class iterator : public const_iterator { public: iterator( ) { } Object & operator*( ) { return const_iterator::retrieve( ); } const Object & operator*( ) const { return const_iterator::operator*( ); } iterator & operator++( ) { this->current = this->current->next; return *this; } iterator operator++ ( int ) { iterator old = *this; ++ ( *this ); return old; } iterator & operator--( ) { this->current = this->current->prev; return *this; } iterator operator-- ( int ) { iterator old = *this; -- ( *this ); return old; } protected: iterator( ListNode* node ) : const_iterator { node } { } friend class List<Object>; }; //end of class iterator public: List( ) { initialize( ); } ~List( ) { clear( ); delete _head; delete _tail; } List( const List& rhs ) { initialize( ); for (auto & elem : rhs ) { push_back( elem ); } } List ( List && rhs ) : _size( rhs._size ), _head( rhs._head ), _tail( rhs._tail ) { rhs._size = 0; rhs._head = rhs._tail = nullptr; } List& operator= ( const List & rhs ) { List copy = rhs; algo::swap( copy, *this ); return *this; } List& operator= ( List && rhs ) { algo::swap( _size, rhs._size ); algo::swap( _head, rhs._head ); algo::swap( _tail, rhs._tail ); return *this; } iterator begin( ) { return iterator( _head->next ); } const_iterator begin( ) const { return const_iterator( _head->next ); } iterator end( ) { return iterator( _tail ); } const_iterator end( ) const { return const_iterator( _tail ); } int size( ) const { return _size; } bool empty( ) const { return ( _size == 0 ); } void clear( ) { while ( !empty( ) ) pop_front( ); } Object& front( ) { return (*begin( ) ); } const Object& front( ) const { return (*begin( ) ); } Object& back( ) { return (*--end( ) ); } const Object& back( ) const { return (*--end( ) ); } void push_front( const Object& obj ) { insert( obj, begin( ) ); } void push_front( Object && obj ) { insert( std::move( obj ), begin( ) ); } void push_back( const Object & obj ) { insert( obj, end( ) ); } void push_back ( Object && obj ) { insert( std::move( obj ), end( ) ); } void pop_front( ) { erase( begin( ) ); } void pop_back( ) { erase( --end( ) ); } iterator insert( const Object & obj, iterator it ) { ListNode *currNode = it.current; ListNode *newNode = new ListNode{ obj, currNode, currNode->prev }; currNode->prev->next = newNode; currNode->prev = newNode; ++_size; return iterator( newNode ); } iterator erase( iterator it ) { ListNode* currNode = it.current; iterator returnItr( currNode->next ); currNode->prev->next = currNode->next; currNode->next->prev = currNode->prev; delete currNode; --_size; return returnItr; } iterator erase( iterator from, iterator to ) { for( iterator it = from; it != to; ) { it = erase( it ); } return to; } private: int _size; ListNode *_head; ListNode *_tail; void initialize( ) { _size = 0; _head = new ListNode; _tail = new ListNode; _head->next = _tail; _tail->prev = _head; } }; //end of class List } //end of namespace algo #endif
8,573
C++
.h
257
15.929961
89
0.340275
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,995
bubbleSort.h
mandliya_algorithms_and_data_structures/include/bubbleSort.h
/*** * _ __ ___ _ * | |/ /___ ___ _ __ / __|__ _| |_ __ * | ' </ -_) -_) '_ \ | (__/ _` | | ' \ * |_|\_\___\___| .__/ \___\__,_|_|_|_|_| * |_| * _ * __ _ _ _ __| | * / _` | ' \/ _` | * \__,_|_||_\__,_| * * _ _ _ _ _ _ * | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___ * | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-< * |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/ * |___/ * Yeah! Ravi let's do it! */ #ifndef BUBBLE_SORT_H #define BUBBLE_SORT_H #include "generic.h" namespace algo { template <typename T> static void bubbleSort(T list[], int start, int end) { bool swapped; do { swapped = false; for (int i = start + 1; i <= end; ++i) { if (list[i-1] > list[i]) { swapped = true; swap(list[i-1], list[i]); } } } while (swapped); } } //end of namespace algo #endif
1,706
C++
.h
38
25.789474
74
0.151023
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,996
queue.h
mandliya_algorithms_and_data_structures/include/queue.h
/*** * _ __ ___ _ * | |/ /___ ___ _ __ / __|__ _| |_ __ * | ' </ -_) -_) '_ \ | (__/ _` | | ' \ * |_|\_\___\___| .__/ \___\__,_|_|_|_|_| * |_| * _ * __ _ _ _ __| | * / _` | ' \/ _` | * \__,_|_||_\__,_| * * _ _ _ _ _ _ * | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___ * | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-< * |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/ * |___/ * Yeah! Ravi let's do it! */ #ifndef QUEUE_H #define QUEUE_H #include <exception> namespace algo { const int defaultQueueCapacity = 500; template <typename T> class Queue { public: Queue( int capacity = defaultQueueCapacity ) : _capacity { capacity }, _count { 0 }, _head { 0 }, _tail { -1 }, _elements { new T[_capacity] } { } bool empty() const { return ( _count == 0 ); } int count() const { return _count; } int capacity() const { return _capacity; } void pop() { if (empty()) { return; } else { --_count; ++_head; if ( _head == _capacity ) { _head = 0; } } } bool push( const T & obj ) { if ( _count == _capacity ) { return false; } else { ++_count; ++_tail; if ( _tail == _capacity ) { _tail = 0; } _elements[_tail] = obj; return true; } } const T & front() const { if ( empty() ) throw empty_queue_exception; return _elements[_head]; } private: class EmptyQueueException : public std::exception { virtual const char * what() const throw() { return "Queue is empty"; } } empty_queue_exception; int _capacity; int _count; int _head; int _tail; T * _elements; Queue( const Queue & ); Queue & operator= ( const Queue & ); }; //end of class queue } //end of namespace algo #endif //end of QUEUE_H
3,649
C++
.h
96
18.020833
79
0.215781
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,997
pUnitTest.h
mandliya_algorithms_and_data_structures/include/pUnitTest.h
// pUnitTest.h // A simple unit test class #ifndef __PSTRING_UTEST__ #define __PSTRING_UTEST__ #include <cstdio> #define _UTest_VERSION "1.0.0" const static char * __ut_pstr = "pass"; const static char * __ut_fstr = "fail"; class UTest { unsigned long int _pass_count = 0; unsigned long int _fail_count = 0; bool _summary_flag = false; const char * _test_str = nullptr; UTest( UTest & ); // no copy constructor UTest operator = ( UTest & ); // no assignment operator UTest(){} // no default constructor public: static const char * version() { return _UTest_VERSION; } UTest( const char * ); void init ( const char * ); bool summary ( bool flag ) { return _summary_flag = flag; } bool summary ( ) { return _summary_flag; } unsigned long int pass_count() const { return _pass_count; } unsigned long int fail_count() const { return _fail_count; } void test ( const char * description, const int flag ); void report() const; }; #endif /* defined(__PSTRING_UTEST__) */
1,089
C++
.h
28
35.285714
65
0.622624
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,998
generic.h
mandliya_algorithms_and_data_structures/include/generic.h
/*** * _ __ ___ _ * | |/ /___ ___ _ __ / __|__ _| |_ __ * | ' </ -_) -_) '_ \ | (__/ _` | | ' \ * |_|\_\___\___| .__/ \___\__,_|_|_|_|_| * |_| * _ * __ _ _ _ __| | * / _` | ' \/ _` | * \__,_|_||_\__,_| * * _ _ _ _ _ _ * | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___ * | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-< * |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/ * |___/ * Yeah! Ravi let's do it! */ #ifndef GENERIC_H #define GENERIC_H #include <iostream> #include <random> #include <sstream> #include <string> template<typename T> T MAX(T a, T b) { return ((a > b) ? a : b); } template<typename T> T MIN(T a, T b) { return ((a < b) ? a : b); } namespace algo { // swap two elements template <typename T> static inline void swap(T &a, T &b) { T _temp(std::move(a)); a = std::move(b); b = std::move(_temp); } //Print the list of T template <typename T> static inline void printList(T *list, int count) { for (int i = 0; i < count; ++i) { std::cout << list[i] << " "; } std::cout<< std::endl; } //generate a random int between min and max static inline int random_range(const int min, const int max) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> distribution(min, max); return distribution(mt); } //generate a random double between min and max static inline double random_range(const double min, const double max) { // std::random_device rd; // std::mt19937 mt(rd()); std::uniform_real_distribution<double> distribution(min, max); std::default_random_engine re; return distribution(re); } //convert an int to string std::string intToString( int num ) { std::stringstream ss; ss << num; return ss.str(); } } //end of namespace algo #endif //end of generic.h
2,730
C++
.h
75
24.973333
75
0.339137
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,999
double_linked_list.h
mandliya_algorithms_and_data_structures/include/double_linked_list.h
/** * A linux kernel like implementation of double linked list. */ #ifndef _DOUBLE_LINKED_LIST_H_ #define _DOUBLE_LINKED_LIST_H_ struct list_head { struct list_head * next; struct list_head * prev; }; /** * Following two macros are for initializing an empty list. */ #define LIST_HEAD_INIT(name) { &(name), &(name) } #define LIST_HEAD(name) \ struct list_head name = LIST_HEAD(name) static inline void INIT_LIST_HEAD( struct list_head * list ) { list->next = list; list->prev = list; } /** * Insert a new entry between two known consecutive entries. * This is for internal use only as we know consecutive list entries * and where we want to insert the newNode between prevNode and * nextNode in list */ static inline void __list_add( struct list_head *newNode, struct list_head *prevNode, struct list_head *nextNode) { prevNode->next = newNode; newNode->prev = prevNode; newNode->next = nextNode; nextNode->prev = newNode; } /** * list_add - Add a new entry * @param newNode [new entry to be added in list] * @param head [list head to add it after] * @return [none] * Insert a new entry after specified head * This is good for implementation of a stack */ static inline void list_add( struct list_head * newNode, struct list_head * head) { __list_add( newNode, head, head->next ); } /** * list_add_tail [Add a new entry to the tail] * @param newNode [new entry to be added] * @param head [list add to add it before] * * Insert a new entry before specified head * This is good for implementation of queue. */ static inline void list_add_tail( struct list_head * newNode, struct list_head * head) { __list_add( newNode, head->prev, head ); } /** * Delete an entry between prevNode and nextNode by making prevNode/nextNode * pointing to each other * This is only used for internal list manipulation when we * know prevNode/nextNode entries already */ static inline void __list_del( struct list_head * prevNode, struct list_head * nextNode) { prevNode->next = nextNode; nextNode->prev = prevNode; } /** * Deletes an entry from the list * @param entry [Entry to be deleted] */ static inline void list_del( struct list_head * entry ) { __list_del(entry->prev, entry->next); entry->prev = nullptr; entry->next = nullptr; } static inline void __list_del_entry( struct list_head * entry) { __list_del( entry->prev, entry->next ); } /** * Replace @oldNode with @newNode in the list * @param oldNode [Node to be replaced] * @param newNode [This node replaces the oldNode] */ static inline void list_replace( struct list_head * oldNode, struct list_head * newNode) { newNode->next = oldNode->next; newNode->prev = oldNode->prev; oldNode->prev->next = newNode; oldNode->next->prev = newNode; } static inline void list_replace_init( struct list_head * oldList, struct list_head * newList) { list_replace( oldList, newList ); INIT_LIST_HEAD( oldList ); } /** * Deletes the entry from the list and reinitialize it * @param entry [node to be deleted and reinitialized] */ static inline void list_del_init( struct list_head * entry ) { __list_del( entry->prev, entry->next ); INIT_LIST_HEAD( entry ); } /** * list_move - deletes from one list and adds as another's head * @param list [the entry to move] * @param head [the head that will precede our entry] */ static inline void list_move( struct list_head * list, struct list_head * head) { __list_del_entry( list ); list_add( list, head ); } /** * list_move_tail- deletes from one list and adds as another's tail * @param list [the entry to move] * @param head [the head that will follow our entry] */ static inline void list_move_tail( struct list_head * list, struct list_head * head) { __list_del_entry( list ); list_add_tail( list, head ); } /** * list_is_last - Determines if @entry node is the last in the list * @param entry [Node to be checked if it is last] * @param head [the head of the list] * @return [ true if entry is last false otherwise] */ static inline bool list_is_last( const struct list_head * entry, const struct list_head * head ) { return ( entry->next == head ); } /** * list_is_empty - Verifies if the list is empty * @param head [the list to be tested` * @return - returns true if list is empty, otherwise false */ static inline bool list_is_empty( const struct list_head * head ) { return ( head->next == head ); } /** * list_is_empty_careful - tests whether list is empty and not being modified i.e. * checks that no other cpu is in process of modifying next or prev * @param head [the list to be tested] * @return [returns true if list is empty and not being modified] */ static inline bool list_is_empty_careful( const struct list_head * head) { struct list_head * nextNode = head->next; return ( nextNode == head ) && ( nextNode == head->prev ); } /** * list_rotate_left - Rotate the list to left (1,2,3,4)-->(2,3,4,1) * @param head head of the list */ static inline void list_rotate_left( struct list_head * head ) { struct list_head * first; if ( !list_is_empty(head) ) { first = head->next; list_move_tail( first, head ); } } /** * [list_is_singular - check if list contain just one entry * @param head [head of the list] * @return [return true if list has just one entry false otherwise] */ static inline bool list_is_singular( const struct list_head * head) { return (!list_is_empty(head) && ( head->next == head->prev )); } /** * Internal function to join two list at position between prev and next * @param list [new list] * @param prev [new list to be added after this] * @param next [new list to be added before this] */ static inline void __list_splice( const struct list_head * list, struct list_head * prev, struct list_head * next) { struct list_head * first = list->next; struct list_head * last = list->prev; first->prev = prev; prev->next = first; last->next = next; next->prev = last; } /** * list-splice Join two lists * @param list [The new list to be added] * @param head [The entry where you want to add the new list in current list] */ static inline void list_splice( const struct list_head * list, struct list_head * head ) { if( !list_is_empty(list) ) { __list_splice(list, head, head->next); } } /** * list_splice_init : join two lists and reinitialise the emptied list. * @param list [The new list to be adeed] * @param head [The entry where you want to add the new list in current list] */ static inline void list_splice_init( struct list_head * list, struct list_head * head) { if( !list_is_empty(list) ) { __list_splice(list, head, head->next); INIT_LIST_HEAD(list); } } /** * list_entry - get the struct for this entry * @param ptr [the &struct list_head pointer] * @param ptrtype [the pointer to the type of struct this was embedded in] * @param member [the name of the list_struct within the struct.] */ #define list_entry(ptr, ptrtype, member) \ (reinterpret_cast<ptrtype>( (char *)(ptr) - (char *)(&(reinterpret_cast<ptrtype>(1)->member)) + 1)) /** * [list_for_each] -- Iterate over a list * @param pos [the &struct list_head to use as a loop counter.] * @param head [the head for your list.] */ #define list_for_each(pos, head) \ for(pos = (head)->next; pos != (head); \ pos = pos->next) /** * [list_for_each_prev] -- Iterate over a list in reverse * @param pos [the &struct list_head to use as a loop counter.] * @param head [the head for your list.] */ #define list_for_each_prev(pos, head) \ for (pos = (head)->prev; pos != (head); \ pos = pos->prev) /** * list_for_each_safe - iterate over a list safe against removal of list entry * @pos: the &struct list_head to use as a loop counter. * @n: another &struct list_head to use as temporary storage * @head: the head for your list. */ #define list_for_each_safe(pos, n, head) \ for (pos = (head)->next, n = pos->next; pos != (head); \ pos = n, n = pos->next) /** * list_for_each_entry - iterate over a list of given type * @param pos [The pointer to use as loop counter] * @param head [The head of your list] * @param member [the name of the list_struct within the struct.] */ #define list_for_each_entry(pos, head, member) \ for (pos = list_entry((head)->next, decltype(pos), member); \ &pos->member != (head); \ pos = list_entry(pos->member.next, decltype(pos), member)) /** * Move a node to the front */ static inline void list_mtf(struct list_head *entry, struct list_head *head) { if (entry->prev == head) return; __list_del(entry->prev, entry->next); __list_add(entry, head, head->next); } /** * Move a node ahead one position */ static inline void list_mao(struct list_head *entry, struct list_head * head) { // if the entry in the 1st position if (entry->prev == head) return; struct list_head * prev = entry->prev; __list_del(entry->prev, entry->next); __list_add(entry, prev->prev, prev); } #endif
9,683
C++
.h
292
29.184932
101
0.642109
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,002
quickSort.h
mandliya_algorithms_and_data_structures/include/quickSort.h
/*** * _ __ ___ _ * | |/ /___ ___ _ __ / __|__ _| |_ __ * | ' </ -_) -_) '_ \ | (__/ _` | | ' \ * |_|\_\___\___| .__/ \___\__,_|_|_|_|_| * |_| * _ * __ _ _ _ __| | * / _` | ' \/ _` | * \__,_|_||_\__,_| * * _ _ _ _ _ _ * | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___ * | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-< * |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/ * |___/ * Yeah! Ravi let's do it! */ #ifndef QUICK_SORT_H #define QUICK_SORT_H #include <generic.h> namespace algo { //Partition routine for quicksort template <typename T> static int __partition(T list[], int start, int end) { int pivotIndex = random_range(start, end); T pivot = list[pivotIndex]; //Swapping pivot element with element at start swap(list[start], list[pivotIndex]); int i = start + 1; int j = end; while (i <= j) { while ((i <= end) && (list[i] <= pivot)) { ++i; } while ((j >= start) && (list[j] > pivot)) { --j; } if (i < j) { swap(list[i], list[j]); } } swap(list[start], list[j]); return j; } //quickSort Routine template <typename T> static void quickSort(T list[], int start, int end) { if (start < end) { int pivotIndex = __partition<T>(list, start, end); quickSort(list, start, pivotIndex - 1); quickSort(list, pivotIndex + 1, end); } } }//end of namespace algo #endif //end of quickSort.h
2,450
C++
.h
58
25.431034
74
0.250739
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,003
binarySearchTree.h
mandliya_algorithms_and_data_structures/include/binarySearchTree.h
#ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include <iostream> namespace algo { template <typename T> class BinarySearchTree { private: struct BinaryNode { T element; BinaryNode *left; BinaryNode *right; BinaryNode( const T & obj = T(), BinaryNode *lptr = nullptr, BinaryNode *rptr = nullptr ) : element{ obj }, left { lptr }, right { rptr } { } BinaryNode( T && obj, BinaryNode *lptr, BinaryNode *rptr ) : element{ std::move(obj) }, left{ lptr }, right{ rptr } { } }; // end of struct BinaryNode public: BinarySearchTree(); BinarySearchTree( const BinarySearchTree& rhs ); BinarySearchTree( BinarySearchTree && rhs ); BinarySearchTree & operator= ( const BinarySearchTree & rhs ); BinarySearchTree & operator= ( BinarySearchTree && rhs ); ~BinarySearchTree( ); const T & findMin() const; const T & findMax() const; bool contains( const T & obj ) const; bool empty( ) const; void printTree(std::ostream & out = std::cout) const; void clear() const; void insert( const T & obj ); void insert( T && obj ); void remove( const T & obj ); const int height() const; void prettyPrint( ) const; BinaryNode * getRoot() const; void mirror(); private: BinaryNode *root; const T & __findMin( BinaryNode *node ) const; const T & __findMax( BinaryNode *node ) const; bool __contains( BinaryNode *node, const T & obj ) const; void __insert( BinaryNode * & node, const T & obj ); void __insert( BinaryNode * & node, T && obj ); void __remove( BinaryNode *node, const T & obj ); void __clear( BinaryNode *node ) const; void __printTree( BinaryNode *node, std::ostream& out ) const; BinaryNode * __copy( BinaryNode *node ); void __prettyPrint( BinaryNode *node, int indent = 0, std::ostream & out = std::cout) const; const int __height( BinaryNode * node ); void __mirror( BinaryNode * & node ); }; // end of class BinarySearchTree } // end of namespace algo //for more clarity, functions are defined in below file #include "impl/binarySearchTree.impl.h" #endif
2,649
C++
.h
60
31.683333
104
0.532352
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,004
pstring.h
mandliya_algorithms_and_data_structures/include/pstring.h
/** * A string library for practice. * by Ravi Mandliya */ #ifndef __ALG_PSTRING_LIB #define __ALG_PSTRING_LIB #include <cstdlib> #include <cstring> #include <iostream> namespace algo { static int const _PSTRING_MAX_LEN = 65535; static const char * _PSTRING_VERSION = "1.0.0"; static const size_t npos = -1; class String { char * _str = nullptr; size_t _str_len = 0; //data allocation and dellocation void _alloc_cstr( size_t sz ); //alloc memory for _str void _reset(); //for resetting data void _swap( String & s ); //mem function swap. void _copy_str( const char * s ); //alloc and copy. //private utility functions bool _have_value() const; size_t _char_find( const char & match , size_t pos = 0) const; void _char_replace( const char & match_char, const char & replace_char ); public: String(); //default constructor String( const char * c ); //cstr constructor String( const String & s ); //copy constructor String( String && s ) noexcept; //move constructor ~String(); //destructor const char * c_str() const; //getter //operators String & operator = ( String s ); //copy and swap assignmment for move and copy assignment. String & operator += ( const String & s ); //concatenation for string String & operator += ( const char * s ); //concatenation for literals const char operator [] ( const size_t index ) const; //subscript operator //comparison operator bool operator == ( const String & s ) const; bool operator != ( const String & s ) const; bool operator >= ( const String & s ) const; bool operator > ( const String & s ) const; bool operator <= ( const String & s ) const; bool operator < ( const String & s ) const; // conversion operators operator const char * () const; // c-string type //utility methods size_t length() const { return _str_len; } size_t size() const { return _str_len; } String lower() const; String upper() const; const char & back() const; const char & front() const; String substr(size_t pos = 0, size_t len = npos) const; static const char * version() { return _PSTRING_VERSION; } //find and replace utility functions size_t find( const String & str, size_t pos = 0) const; size_t find( const char * s, size_t pos = 0 ) const; size_t find( char c, size_t pos = 0) const; String replace( size_t pos, size_t len, const char * str ); String replace( size_t pos, size_t len, const String & str ); //compare int compare (const String& str) const noexcept; int compare (const char * str) const; }; String operator + ( const String & lhs, const String & rhs ); String operator + ( const String & lhs, const char * rhs ); } #endif
3,183
C++
.h
70
40.642857
115
0.57226
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,005
stack.h
mandliya_algorithms_and_data_structures/include/stack.h
/*** * _ __ ___ _ * | |/ /___ ___ _ __ / __|__ _| |_ __ * | ' </ -_) -_) '_ \ | (__/ _` | | ' \ * |_|\_\___\___| .__/ \___\__,_|_|_|_|_| * |_| * _ * __ _ _ _ __| | * / _` | ' \/ _` | * \__,_|_||_\__,_| * * _ _ _ _ _ _ * | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___ * | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-< * |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/ * |___/ * Yeah! Ravi let's do it! */ #ifndef STACK_H #define STACK_H #include <iostream> #include <exception> #include <cstdint> namespace algo { const uint32_t defaultCapacity = 500; template <typename T = uintptr_t> class Stack { public: Stack( uint32_t capacity = defaultCapacity ) : _capacity{ capacity }, _size{ 0 }, _elements{ new T[_capacity] } { } Stack( const Stack & st ) : _capacity{ st.capacity }, _size{ st._size }, _elements{ new T[_capacity] } { for(uint32_t i = 0; i < _capacity; ++i) { _elements[i] = st._elements[i]; } } bool empty() { return (_size == 0 ); } void pop() { if (empty()) return; _size--; } void push( const T & obj ) { if ( _size == _capacity ) throw stack_out_of_bound_exception; _elements[_size++] = obj; } const T & top() { if (empty()) throw stack_empty_exception; return _elements[_size - 1]; } uint32_t size() { return _size; } void print(std::ostream & out = std::cout) { for (int i = _size - 1; i >= 0; --i) { out << _elements[i] << " "; } out << std::endl; } private: uint32_t _capacity; uint32_t _size; T * _elements; Stack & operator=(const Stack & st); class StackEmptyException : public std::exception { virtual const char * what() const throw() { return "Stack is empty"; } } stack_empty_exception; class StackOutofBoundException : public std::exception { virtual const char * what() const throw() { return "Stack Index out of bound"; } } stack_out_of_bound_exception ; }; // end of class stack } // end of namespace algo #endif
3,522
C++
.h
91
22.021978
92
0.284526
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,006
graph.h
mandliya_algorithms_and_data_structures/include/graph.h
#ifndef _GRAPH_H #define _GRAPH_H #include <vector> #include <queue> namespace algo { template <class dataType> // Type of data vertex will hold class Graph { int numOfVertices; // number of vertices. struct Vertex; // forward declaration of vertex structure struct Node { // linkedlist for mapping edges in the graph Vertex * vertexPtr; // points to the vertex to which the edge is adjecent Node * next; // points to the next edge belonging to same vertex }; enum visitedState{ // Enum representing visited state of vertex WHITE, // not yet visited GRAY, // being visited BLACK // visited }; struct Vertex { visitedState state; // state of vertex, visited/being visited/done dataType data; // the template data Node * list; // Pointer to all edges (linkedlist) }; std::vector<Vertex> vertices; // vector of all vertices. //private methods Node * getNode( Vertex * ); // allocate and initialize a newnode for the adj list. void insertAtEnd( Node * & , Vertex * ); // insert at the end of adjacency list of vertex. void deleteAllAfter( Node * ); // delete the adjacency list of the vertex. void depth_first_traversal_util(Vertex * ); // Private utility function for DFS public: Graph() = default; // Default constructor Graph(std::vector<dataType> &); // Constructor which takes vector of vertex data void setEdge(dataType, dataType); // For setting a edge of graph void display() const; // Print current config of the graph. void breadth_first_search(dataType); // Breadth first traversal of the graph void depth_first_search(dataType); // Depth first traversal of the graph ~Graph(); }; //end of class Graph template <typename dataType> typename Graph<dataType>::Node * algo::Graph<dataType>::getNode(Vertex * v) // allocate and initialize a newnode for the adj list. { Node * newNode = new Node; newNode->vertexPtr = v; newNode->next = nullptr; return newNode; } template <typename dataType> void Graph<dataType>::insertAtEnd( Node * & node, Vertex * v) // insert at the end of adjacency list of vertex. { Node *newNode = getNode(v); if ( node == nullptr ) { node = newNode; } else { Node * temp = node; while( temp->next != nullptr ) { temp = temp->next; } temp->next = newNode; } } template <typename dataType> void Graph<dataType>::deleteAllAfter( Node * node ) // delete the adjacency list of the vertex. { Node * nextNode; while( node != nullptr ) { nextNode = node->next; delete(node); node = nextNode; } } template <typename dataType> Graph<dataType>::Graph(std::vector<dataType> & values) // Non default constructor, takes a vector of vertices data : numOfVertices(values.size()), vertices(numOfVertices) { for ( int i = 0; i < numOfVertices; ++i ) { vertices[i].data = values[i]; vertices[i].list = nullptr; vertices[i].state = WHITE; } } template <typename dataType> void Graph<dataType>::setEdge(dataType data1, dataType data2) // Setting individual edge of the graph. { for (int i = 0; i < numOfVertices; ++i) { if (vertices[i].data == data1) { for ( int j = 0; j < numOfVertices; ++j) { if (vertices[j].data == data2) { insertAtEnd(vertices[i].list, &vertices[j]); break; } } break; } } } template <typename dataType> void Graph<dataType>::display() const // Prints the current config of the graph { Node * node; for ( int i = 0; i < numOfVertices; ++i ) { std::cout << "Vertex:" << vertices[i].data << " "; std::cout << "Connections: "; node = vertices[i].list; while( node != nullptr ) { std::cout << node->vertexPtr->data << " "; node = node->next; } std::cout << std::endl; } } template <typename dataType> void Graph<dataType>::breadth_first_search(dataType startElem) // Breadth first traversal of the graph { //mark all vertices as not visited, i.e. state = WHITE for ( int i = 0; i < numOfVertices; ++i ) { vertices[i].state = WHITE; } // search for the vertex containing start element Vertex * startVertex = nullptr; for ( int i = 0; i < numOfVertices; ++i ) { if ( vertices[i].data == startElem ) { startVertex = &vertices[i]; break; } } //Return if start vertex not found if ( startVertex == nullptr ) { return; } //Create a queue for traversing breadth wise. std::queue<Vertex *> vertexQueue; //mark the first vertex as being processed startVertex->state = GRAY; //push the first vertex vertexQueue.push(startVertex); Vertex * currVertex = nullptr; while( !vertexQueue.empty() ) { currVertex = vertexQueue.front(); vertexQueue.pop(); currVertex->state = BLACK; std::cout << currVertex->data << " "; Node * adjVertex = currVertex->list; while( adjVertex != nullptr ) { if ( adjVertex->vertexPtr->state == WHITE ) { adjVertex->vertexPtr->state = GRAY; vertexQueue.push(adjVertex->vertexPtr); } adjVertex = adjVertex->next; } } std::cout << std::endl; } template <typename dataType> void Graph<dataType>::depth_first_traversal_util(Vertex * v) // Depth first search private utility function { v->state = GRAY; std::cout << v->data << " "; Node * node = v->list; while( node != nullptr ) { if (node->vertexPtr->state == WHITE) { depth_first_traversal_util(node->vertexPtr); } node = node->next; } v->state = BLACK; } template <typename dataType> void Graph<dataType>::depth_first_search(dataType startElem) // Public function for depth first traversal { for( int i = 0; i < numOfVertices; ++i ) { vertices[i].state = WHITE; } for ( int i = 0; i < numOfVertices; ++i) { if (vertices[i].data == startElem) { depth_first_traversal_util(&vertices[i]); break; } } std::cout << std::endl; } template <typename dataType> Graph<dataType>::~Graph() { for( int i = 0; i < numOfVertices; ++i ) { deleteAllAfter(vertices[i].list); } } } //end of namespace algo #endif
7,332
C++
.h
191
32.874346
129
0.549698
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,007
heap_sort.h
mandliya_algorithms_and_data_structures/include/heap_sort.h
#ifndef HEAP_SORT #define HEAP_SORT #include <generic.h> #include <cassert> namespace algo { template <typename T> static void __sift_down(T list[], int low, int high) { int root = low; while( (root * 2 + 1) <= high ) { int left_child = root * 2 + 1; int right_child = left_child + 1; int swpIdx = root; //if root is less than left child. if ( list[root] < list[left_child] ) { swpIdx = left_child; } // if right child exists and bigger if ( (right_child <= high) && list[swpIdx] < list[right_child] ) { swpIdx = right_child; } if ( swpIdx != root ) { algo::swap( list[swpIdx], list[root] ); } else { break; } //keep going down swpIdx = root; } } template <typename T> static void __heapify(T list[], int low, int high) { int mid = (high - low - 1)/2; while( mid >=0 ) { __sift_down(list, mid, high); --mid; } } template <typename T> static void heap_sort(T list[], int size) { assert(list); assert(size > 0); //heapify the list __heapify(list, 0, size-1); int high = size - 1; while ( high > 0 ) { algo::swap(list[high], list[0]); --high; __heapify(list, 0, high); } } } #endif
1,477
C++
.h
52
19.75
76
0.482004
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,008
selectionSort.h
mandliya_algorithms_and_data_structures/include/selectionSort.h
/*** * _ __ ___ _ * | |/ /___ ___ _ __ / __|__ _| |_ __ * | ' </ -_) -_) '_ \ | (__/ _` | | ' \ * |_|\_\___\___| .__/ \___\__,_|_|_|_|_| * |_| * _ * __ _ _ _ __| | * / _` | ' \/ _` | * \__,_|_||_\__,_| * * _ _ _ _ _ _ * | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___ * | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-< * |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/ * |___/ * Yeah! Ravi let's do it! */ #ifndef SELECTION_SORT_H #define SELECTION_SORT_H #include <cassert> namespace algo { template <typename T> static void selectionSort( T list[ ], int start, int end ) { assert( start <= end ); int i, j, minIndex; for ( i = start; i <= end - 1; ++i ) { //let us assume element at start index is smallest minIndex = i; for ( j = start + 1; j <= end; ++j ) { if ( list[j] < list[minIndex] ) { minIndex = j; } } //swap the min element with the element at current position if ( minIndex != i ) { swap( list[i], list[minIndex] ); } } } } //end of namespace algo #endif
1,991
C++
.h
43
27.372093
75
0.196271
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,009
binarySearchTree.impl.h
mandliya_algorithms_and_data_structures/include/impl/binarySearchTree.impl.h
#ifndef BINARY_SEARCH_TREE_IMPL_H #define BINARY_SEARCH_TREE_IMPL_H #include <stdexcept> #include <generic.h> //for pretty printing tree #include <iomanip> #include <deque> namespace algo { // default constructor template <typename T> BinarySearchTree<T>::BinarySearchTree( ) : root{ nullptr } { } // copy constructor template<typename T> BinarySearchTree<T>::BinarySearchTree( const BinarySearchTree & rhs ) : root { nullptr } { root = __copy( rhs.root ); } // move constructor template<typename T> BinarySearchTree<T>::BinarySearchTree( BinarySearchTree && rhs ) : root { rhs.root } { rhs.root = nullptr; } //copy assignment template<typename T> BinarySearchTree<T> & BinarySearchTree<T>::operator= ( const BinarySearchTree & rhs ) { BinarySearchTree copy = rhs; algo::swap( *this, copy ); return *this; } // move assignment template<typename T> BinarySearchTree<T> & BinarySearchTree<T>::operator= ( BinarySearchTree && rhs ) { swap( root, rhs.root ); return *this; } // destructor template<typename T> BinarySearchTree<T>::~BinarySearchTree( ) { clear(); } // Smallest item in Tree template <typename T> const T & BinarySearchTree<T>::findMin() const { if ( empty() ) throw std::underflow_error("Empty Tree"); return __findMin( root )->element; } // Largest item in Tree template <typename T> const T & BinarySearchTree<T>::findMax() const { if ( empty() ) throw std::underflow_error("Empty Tree"); return __findMax( root )->element; } // does tree contain obj template <typename T> bool BinarySearchTree<T>::contains( const T & obj ) const { return __contains( root, obj ); } // isTreeEmpty template <typename T> bool BinarySearchTree<T>::empty( ) const { return ( root == nullptr ); } // print the content of tree in sorted order template <typename T> void BinarySearchTree<T>::printTree(std::ostream & out ) const { if ( empty( ) ) { std::cout << "Empty Tree\n"; } else { __printTree( root, out ); } } // clear the tree template <typename T> void BinarySearchTree<T>::clear() const { __clear( root ); } // insert element to tree, duplicates ignored template <typename T> void BinarySearchTree<T>::insert( const T & obj ) { __insert( root, obj ); } // move insert element to tree, duplicates ignored template <typename T> void BinarySearchTree<T>::insert( T && obj ) { __insert( root, std::move( obj ) ); } // remove element from tree template <typename T> void BinarySearchTree<T>::remove( const T & obj ) { __remove( root, obj ); } //get the height of tree template <typename T> const int BinarySearchTree<T>::height() const { return __height(root); } //pretty print the tree template <typename T> void BinarySearchTree<T>::prettyPrint( ) const { __prettyPrint(root); } template<typename T> typename BinarySearchTree<T>::BinaryNode* BinarySearchTree<T>::getRoot( ) const { return root; } template <typename T> const T & BinarySearchTree<T>::__findMin( BinaryNode *node ) const { if ( node == nullptr ) return nullptr; else if ( node->left == nullptr ) return node; else return __findMin( node->left ); } template <typename T> const T & BinarySearchTree<T>::__findMax( BinaryNode *node ) const { if ( node == nullptr ) return nullptr; else if ( node->right == nullptr ) return node; else return __findMax( node->right ); } template <typename T> bool BinarySearchTree<T>::__contains( BinaryNode *node, const T & obj ) const { if ( node == nullptr ) return false; else if ( obj < node->element ) return __contains( node->left, obj ); else if ( obj > node->element ) return __contains( node->right, obj ); else return true; } template <typename T> void BinarySearchTree<T>::__insert( BinaryNode * & node, const T & obj ) { if ( node == nullptr ) { node = new BinaryNode( obj, nullptr, nullptr ); } else if ( obj < node->element ) { __insert( node->left, obj ); } else if ( obj > node->element ) { __insert( node->right, obj ); } else { //ignore case of duplicate } } template <typename T> void BinarySearchTree<T>::__insert( BinaryNode * & node, T && obj ) { if ( node == nullptr ) { node = new BinaryNode( std::move( obj ), nullptr, nullptr ); return; } BinaryNode * currNode = node; bool flag = true; while (flag) { if ( currNode->element > obj ) { if ( currNode->left == nullptr ) { currNode->left = new BinaryNode( std::move( obj ), nullptr, nullptr ); flag = false; } else { currNode = currNode->left; } } else if (currNode->element < obj ) { if (currNode->right == nullptr) { currNode->right = new BinaryNode( std::move( obj ), nullptr, nullptr ); flag = false; } else { currNode = currNode->right; } } else { flag = false; //case of duplicate } } } template <typename T> void BinarySearchTree<T>::__remove( BinaryNode *node, const T & obj ) { if ( node == nullptr ) { return; } if ( obj < node->element ) { __remove( node->left, obj ); } else if ( obj > node->element ) { __remove( node->right, obj ); } else { if ( node->left != nullptr && node->right != nullptr ) { node->element = __findMin(node->right)->element; __remove( node->right, node->element); } else { BinaryNode *oldNode = node; node = ( node->left != nullptr ) ? node->left : node->right; delete oldNode; } } } template <typename T> void BinarySearchTree<T>::__clear( BinaryNode *node ) const { if ( node != nullptr ) { __clear( node->left ); __clear( node->right ); delete node; } } template <typename T> void BinarySearchTree<T>::__printTree( BinaryNode *node, std::ostream& out ) const { if ( node != nullptr ) { __printTree( node->left, out ); out << node->element << " "; __printTree( node->right, out ); } } template <typename T> typename BinarySearchTree<T>::BinaryNode* BinarySearchTree<T>::__copy( BinaryNode *node ) { if ( node == nullptr ) { return nullptr; } return new BinaryNode( node->element, __copy( node->left ), __copy( node->right) ); } template <typename T> void BinarySearchTree<T>::__prettyPrint( BinaryNode *node, int indent, std::ostream & out ) const { if ( node != nullptr ) { if ( node->right != nullptr ) __prettyPrint( node->right, indent + 4, out); if ( indent ) out << std::setw(indent) << ' '; if ( node->right != nullptr ) out<<" /\n" << std::setw(indent) << ' '; out << node->element << std::endl; if ( node->left != nullptr ) { out << std::setw(indent) << ' ' <<" \\\n"; __prettyPrint (node->left, indent + 4, out); } } } //private function to get tree height template <typename T> const int BinarySearchTree<T>::__height( BinaryNode * node ) { if ( node == nullptr ) { return 0; } int leftHeight = __height( node->left ); int rightHeight = __height( node->right ); return ( ( leftHeight > rightHeight ) ? leftHeight + 1 : rightHeight + 1 ); } template <typename T> void BinarySearchTree<T>::mirror( ) { __mirror(root); } template <typename T> void BinarySearchTree<T>::__mirror(BinaryNode * & node) { if (node != nullptr) { __mirror(node->left); __mirror(node->right); swap(node->left, node->right); } } } //end of namespace algo #endif //end of BINARY_SEARCH_TREE_IMPL
9,135
C++
.h
294
22.414966
101
0.528902
mandliya/algorithms_and_data_structures
5,894
1,319
168
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,010
ATAIdentifyDump.cpp
LordNoteworthy_al-khaser/Tools/ATAIdentifyDump/ATAIdentifyDump.cpp
#include "pch.h" int main() { printf("Dumping data for all disks.\n"); printf("\n"); for (int driveNumber = 0; driveNumber < 16; driveNumber++) { char deviceNameBuffer[64] = { 0 }; sprintf_s(deviceNameBuffer, "\\\\.\\PhysicalDrive%d", driveNumber); HANDLE diskHandle = CreateFileA( deviceNameBuffer, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, 0, 0 ); if (diskHandle == INVALID_HANDLE_VALUE) { printf("====================\n"); printf("ERROR: Failed to open handle to %s. Last error: %d\n", deviceNameBuffer, GetLastError()); printf("====================\n"); continue; } const unsigned int IdentifyBufferSize = 512; const BYTE IdentifyCommandID = 0xEC; unsigned char Buffer[IdentifyBufferSize + sizeof(ATA_PASS_THROUGH_EX)] = { 0 }; ATA_PASS_THROUGH_EX & pte = *reinterpret_cast<ATA_PASS_THROUGH_EX*>(Buffer); pte.Length = sizeof(pte); pte.TimeOutValue = 10; pte.DataTransferLength = 512; pte.DataBufferOffset = sizeof(ATA_PASS_THROUGH_EX); IDEREGS* regs = (IDEREGS*)pte.CurrentTaskFile; regs->bCommandReg = IdentifyCommandID; regs->bSectorCountReg = 1; pte.AtaFlags = ATA_FLAGS_DATA_IN | ATA_FLAGS_DRDY_REQUIRED; DWORD br = 0; BOOL ioctlSuccess = DeviceIoControl( diskHandle, IOCTL_ATA_PASS_THROUGH, &pte, sizeof(Buffer), &pte, sizeof(Buffer), &br, 0 ); if (!ioctlSuccess) { printf("====================\n"); printf("ATA pass through IOCTL failed for drive %s. Last error: %d\n", deviceNameBuffer, GetLastError()); printf("====================\n"); CloseHandle(diskHandle); continue; } IDENTIFY_DEVICE_DATA *idd = reinterpret_cast<IDENTIFY_DEVICE_DATA*>(Buffer + sizeof(ATA_PASS_THROUGH_EX)); printf("\n"); printf("====================\n"); printf("BEGIN IDENTIFY_DEVICE_DATA for %s\n", deviceNameBuffer); printf("====================\n"); printf("GeneralConfiguration.Reserved1 = %hu\n", idd->GeneralConfiguration.Reserved1); printf("GeneralConfiguration.Retired3 = %hu\n", idd->GeneralConfiguration.Retired3); printf("GeneralConfiguration.ResponseIncomplete = %hu\n", idd->GeneralConfiguration.ResponseIncomplete); printf("GeneralConfiguration.Retired2 = %hu\n", idd->GeneralConfiguration.Retired2); printf("GeneralConfiguration.FixedDevice = %hu\n", idd->GeneralConfiguration.FixedDevice); printf("GeneralConfiguration.RemovableMedia = %hu\n", idd->GeneralConfiguration.RemovableMedia); printf("GeneralConfiguration.Retired1 = %hu\n", idd->GeneralConfiguration.Retired1); printf("GeneralConfiguration.DeviceType = %hu\n", idd->GeneralConfiguration.DeviceType); printf("NumCylinders = %hu\n", idd->NumCylinders); printf("ReservedWord2 = %hu\n", idd->ReservedWord2); printf("NumHeads = %hu\n", idd->NumHeads); printf("Retired1[0] = %hu\n", idd->Retired1[0]); printf("Retired1[1] = %hu\n", idd->Retired1[1]); printf("NumSectorsPerTrack = %hu\n", idd->NumSectorsPerTrack); printf("VendorUnique1[0] = %hu\n", idd->VendorUnique1[0]); printf("VendorUnique1[1] = %hu\n", idd->VendorUnique1[1]); printf("VendorUnique1[2] = %hu\n", idd->VendorUnique1[2]); printf("SerialNumber = \"%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\"\n", idd->SerialNumber[1], idd->SerialNumber[0], idd->SerialNumber[3], idd->SerialNumber[2], idd->SerialNumber[5], idd->SerialNumber[4], idd->SerialNumber[7], idd->SerialNumber[6], idd->SerialNumber[9], idd->SerialNumber[8], idd->SerialNumber[11], idd->SerialNumber[10], idd->SerialNumber[13], idd->SerialNumber[12], idd->SerialNumber[15], idd->SerialNumber[14], idd->SerialNumber[17], idd->SerialNumber[16], idd->SerialNumber[19], idd->SerialNumber[18]); printf("Retired2[0] = %hu\n", idd->Retired2[0]); printf("Retired2[1] = %hu\n", idd->Retired2[1]); printf("Obsolete1 = %hu\n", idd->Obsolete1); printf("FirmwareRevision = \"%c%c%c%c%c%c%c%c\"\n", idd->FirmwareRevision[1], idd->FirmwareRevision[0], idd->FirmwareRevision[3], idd->FirmwareRevision[2], idd->FirmwareRevision[5], idd->FirmwareRevision[4], idd->FirmwareRevision[7], idd->FirmwareRevision[6]); printf("ModelNumber = \"%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\"\n", idd->ModelNumber[1], idd->ModelNumber[0], idd->ModelNumber[3], idd->ModelNumber[2], idd->ModelNumber[5], idd->ModelNumber[4], idd->ModelNumber[7], idd->ModelNumber[6], idd->ModelNumber[9], idd->ModelNumber[8], idd->ModelNumber[11], idd->ModelNumber[10], idd->ModelNumber[13], idd->ModelNumber[12], idd->ModelNumber[15], idd->ModelNumber[14], idd->ModelNumber[17], idd->ModelNumber[16], idd->ModelNumber[19], idd->ModelNumber[18], idd->ModelNumber[21], idd->ModelNumber[20], idd->ModelNumber[23], idd->ModelNumber[22], idd->ModelNumber[25], idd->ModelNumber[24], idd->ModelNumber[27], idd->ModelNumber[26], idd->ModelNumber[29], idd->ModelNumber[28], idd->ModelNumber[31], idd->ModelNumber[30], idd->ModelNumber[33], idd->ModelNumber[32], idd->ModelNumber[35], idd->ModelNumber[34], idd->ModelNumber[37], idd->ModelNumber[36], idd->ModelNumber[39], idd->ModelNumber[38]); printf("MaximumBlockTransfer = %d\n", idd->MaximumBlockTransfer); printf("VendorUnique2 = %d\n", idd->VendorUnique2); printf("ReservedWord48 = %hu\n", idd->ReservedWord48); printf("Capabilities.ReservedByte49 = %d\n", idd->Capabilities.ReservedByte49); printf("Capabilities.DmaSupported = %d\n", idd->Capabilities.DmaSupported); printf("Capabilities.LbaSupported = %d\n", idd->Capabilities.LbaSupported); printf("Capabilities.IordyDisable = %d\n", idd->Capabilities.IordyDisable); printf("Capabilities.IordySupported = %d\n", idd->Capabilities.IordySupported); printf("Capabilities.Reserved1 = %d\n", idd->Capabilities.Reserved1); printf("Capabilities.StandybyTimerSupport = %d\n", idd->Capabilities.StandybyTimerSupport); printf("Capabilities.Reserved2 = %d\n", idd->Capabilities.Reserved2); printf("Capabilities.ReservedWord50 = %hu\n", idd->Capabilities.ReservedWord50); printf("ObsoleteWords51[0] = %hu\n", idd->ObsoleteWords51[0]); printf("ObsoleteWords51[1] = %hu\n", idd->ObsoleteWords51[1]); printf("TranslationFieldsValid = %hu\n", idd->TranslationFieldsValid); printf("Reserved3 = %hu\n", idd->Reserved3); printf("NumberOfCurrentCylinders = %hu\n", idd->NumberOfCurrentCylinders); printf("NumberOfCurrentHeads = %hu\n", idd->NumberOfCurrentHeads); printf("CurrentSectorsPerTrack = %hu\n", idd->CurrentSectorsPerTrack); printf("CurrentSectorCapacity = %lu\n", idd->CurrentSectorCapacity); printf("CurrentMultiSectorSetting = %d\n", idd->CurrentMultiSectorSetting); printf("MultiSectorSettingValid = %d\n", idd->MultiSectorSettingValid); printf("ReservedByte59 = %d\n", idd->ReservedByte59); printf("UserAddressableSectors = %lu\n", idd->UserAddressableSectors); printf("ObsoleteWord62 = %hu\n", idd->ObsoleteWord62); printf("MultiWordDMASupport = %hu\n", idd->MultiWordDMASupport); printf("MultiWordDMAActive = %hu\n", idd->MultiWordDMAActive); printf("AdvancedPIOModes = %hu\n", idd->AdvancedPIOModes); printf("ReservedByte64 = %hu\n", idd->ReservedByte64); printf("MinimumMWXferCycleTime = %hu\n", idd->MinimumMWXferCycleTime); printf("RecommendedMWXferCycleTime = %hu\n", idd->RecommendedMWXferCycleTime); printf("MinimumPIOCycleTime = %hu\n", idd->MinimumPIOCycleTime); printf("MinimumPIOCycleTimeIORDY = %hu\n", idd->MinimumPIOCycleTimeIORDY); printf("ReservedWords69[0] = %hu\n", idd->ReservedWords69[0]); printf("ReservedWords69[1] = %hu\n", idd->ReservedWords69[1]); printf("ReservedWords69[2] = %hu\n", idd->ReservedWords69[2]); printf("ReservedWords69[3] = %hu\n", idd->ReservedWords69[3]); printf("ReservedWords69[4] = %hu\n", idd->ReservedWords69[4]); printf("ReservedWords69[5] = %hu\n", idd->ReservedWords69[5]); printf("QueueDepth = %hu\n", idd->QueueDepth); printf("ReservedWord75 = %hu\n", idd->ReservedWord75); printf("ReservedWords76[0] = %hu\n", idd->ReservedWords76[0]); printf("ReservedWords76[1] = %hu\n", idd->ReservedWords76[1]); printf("ReservedWords76[2] = %hu\n", idd->ReservedWords76[2]); printf("ReservedWords76[3] = %hu\n", idd->ReservedWords76[3]); printf("MajorRevision = %hu\n", idd->MajorRevision); printf("MinorRevision = %hu\n", idd->MinorRevision); printf("CommandSetSupport.SmartCommands = %hu\n", idd->CommandSetSupport.SmartCommands); printf("CommandSetSupport.SecurityMode = %hu\n", idd->CommandSetSupport.SecurityMode); printf("CommandSetSupport.RemovableMediaFeature = %hu\n", idd->CommandSetSupport.RemovableMediaFeature); printf("CommandSetSupport.PowerManagement = %hu\n", idd->CommandSetSupport.PowerManagement); printf("CommandSetSupport.Reserved1 = %hu\n", idd->CommandSetSupport.Reserved1); printf("CommandSetSupport.WriteCache = %hu\n", idd->CommandSetSupport.WriteCache); printf("CommandSetSupport.LookAhead = %hu\n", idd->CommandSetSupport.LookAhead); printf("CommandSetSupport.ReleaseInterrupt = %hu\n", idd->CommandSetSupport.ReleaseInterrupt); printf("CommandSetSupport.ServiceInterrupt = %hu\n", idd->CommandSetSupport.ServiceInterrupt); printf("CommandSetSupport.DeviceReset = %hu\n", idd->CommandSetSupport.DeviceReset); printf("CommandSetSupport.HostProtectedArea = %hu\n", idd->CommandSetSupport.HostProtectedArea); printf("CommandSetSupport.Obsolete1 = %hu\n", idd->CommandSetSupport.Obsolete1); printf("CommandSetSupport.WriteBuffer = %hu\n", idd->CommandSetSupport.WriteBuffer); printf("CommandSetSupport.ReadBuffer = %hu\n", idd->CommandSetSupport.ReadBuffer); printf("CommandSetSupport.Nop = %hu\n", idd->CommandSetSupport.Nop); printf("CommandSetSupport.Obsolete2 = %hu\n", idd->CommandSetSupport.Obsolete2); printf("CommandSetSupport.DownloadMicrocode = %hu\n", idd->CommandSetSupport.DownloadMicrocode); printf("CommandSetSupport.DmaQueued = %hu\n", idd->CommandSetSupport.DmaQueued); printf("CommandSetSupport.Cfa = %hu\n", idd->CommandSetSupport.Cfa); printf("CommandSetSupport.AdvancedPm = %hu\n", idd->CommandSetSupport.AdvancedPm); printf("CommandSetSupport.Msn = %hu\n", idd->CommandSetSupport.Msn); printf("CommandSetSupport.PowerUpInStandby = %hu\n", idd->CommandSetSupport.PowerUpInStandby); printf("CommandSetSupport.ManualPowerUp = %hu\n", idd->CommandSetSupport.ManualPowerUp); printf("CommandSetSupport.Reserved2 = %hu\n", idd->CommandSetSupport.Reserved2); printf("CommandSetSupport.SetMax = %hu\n", idd->CommandSetSupport.SetMax); printf("CommandSetSupport.Acoustics = %hu\n", idd->CommandSetSupport.Acoustics); printf("CommandSetSupport.BigLba = %hu\n", idd->CommandSetSupport.BigLba); printf("CommandSetSupport.DeviceConfigOverlay = %hu\n", idd->CommandSetSupport.DeviceConfigOverlay); printf("CommandSetSupport.FlushCache = %hu\n", idd->CommandSetSupport.FlushCache); printf("CommandSetSupport.FlushCacheExt = %hu\n", idd->CommandSetSupport.FlushCacheExt); printf("CommandSetSupport.Resrved3 = %hu\n", idd->CommandSetSupport.Resrved3); printf("CommandSetSupport.SmartErrorLog = %hu\n", idd->CommandSetSupport.SmartErrorLog); printf("CommandSetSupport.SmartSelfTest = %hu\n", idd->CommandSetSupport.SmartSelfTest); printf("CommandSetSupport.MediaSerialNumber = %hu\n", idd->CommandSetSupport.MediaSerialNumber); printf("CommandSetSupport.MediaCardPassThrough = %hu\n", idd->CommandSetSupport.MediaCardPassThrough); printf("CommandSetSupport.StreamingFeature = %hu\n", idd->CommandSetSupport.StreamingFeature); printf("CommandSetSupport.GpLogging = %hu\n", idd->CommandSetSupport.GpLogging); printf("CommandSetSupport.WriteFua = %hu\n", idd->CommandSetSupport.WriteFua); printf("CommandSetSupport.WriteQueuedFua = %hu\n", idd->CommandSetSupport.WriteQueuedFua); printf("CommandSetSupport.WWN64Bit = %hu\n", idd->CommandSetSupport.WWN64Bit); printf("CommandSetSupport.URGReadStream = %hu\n", idd->CommandSetSupport.URGReadStream); printf("CommandSetSupport.URGWriteStream = %hu\n", idd->CommandSetSupport.URGWriteStream); printf("CommandSetSupport.ReservedForTechReport = %hu\n", idd->CommandSetSupport.ReservedForTechReport); printf("CommandSetSupport.IdleWithUnloadFeature = %hu\n", idd->CommandSetSupport.IdleWithUnloadFeature); printf("CommandSetSupport.Reserved4 = %hu\n", idd->CommandSetSupport.Reserved4); printf("CommandSetActive.SmartCommands = %hu\n", idd->CommandSetActive.SmartCommands); printf("CommandSetActive.SecurityMode = %hu\n", idd->CommandSetActive.SecurityMode); printf("CommandSetActive.RemovableMediaFeature = %hu\n", idd->CommandSetActive.RemovableMediaFeature); printf("CommandSetActive.PowerManagement = %hu\n", idd->CommandSetActive.PowerManagement); printf("CommandSetActive.Reserved1 = %hu\n", idd->CommandSetActive.Reserved1); printf("CommandSetActive.WriteCache = %hu\n", idd->CommandSetActive.WriteCache); printf("CommandSetActive.LookAhead = %hu\n", idd->CommandSetActive.LookAhead); printf("CommandSetActive.ReleaseInterrupt = %hu\n", idd->CommandSetActive.ReleaseInterrupt); printf("CommandSetActive.ServiceInterrupt = %hu\n", idd->CommandSetActive.ServiceInterrupt); printf("CommandSetActive.DeviceReset = %hu\n", idd->CommandSetActive.DeviceReset); printf("CommandSetActive.HostProtectedArea = %hu\n", idd->CommandSetActive.HostProtectedArea); printf("CommandSetActive.Obsolete1 = %hu\n", idd->CommandSetActive.Obsolete1); printf("CommandSetActive.WriteBuffer = %hu\n", idd->CommandSetActive.WriteBuffer); printf("CommandSetActive.ReadBuffer = %hu\n", idd->CommandSetActive.ReadBuffer); printf("CommandSetActive.Nop = %hu\n", idd->CommandSetActive.Nop); printf("CommandSetActive.Obsolete2 = %hu\n", idd->CommandSetActive.Obsolete2); printf("CommandSetActive.DownloadMicrocode = %hu\n", idd->CommandSetActive.DownloadMicrocode); printf("CommandSetActive.DmaQueued = %hu\n", idd->CommandSetActive.DmaQueued); printf("CommandSetActive.Cfa = %hu\n", idd->CommandSetActive.Cfa); printf("CommandSetActive.AdvancedPm = %hu\n", idd->CommandSetActive.AdvancedPm); printf("CommandSetActive.Msn = %hu\n", idd->CommandSetActive.Msn); printf("CommandSetActive.PowerUpInStandby = %hu\n", idd->CommandSetActive.PowerUpInStandby); printf("CommandSetActive.ManualPowerUp = %hu\n", idd->CommandSetActive.ManualPowerUp); printf("CommandSetActive.Reserved2 = %hu\n", idd->CommandSetActive.Reserved2); printf("CommandSetActive.SetMax = %hu\n", idd->CommandSetActive.SetMax); printf("CommandSetActive.Acoustics = %hu\n", idd->CommandSetActive.Acoustics); printf("CommandSetActive.BigLba = %hu\n", idd->CommandSetActive.BigLba); printf("CommandSetActive.DeviceConfigOverlay = %hu\n", idd->CommandSetActive.DeviceConfigOverlay); printf("CommandSetActive.FlushCache = %hu\n", idd->CommandSetActive.FlushCache); printf("CommandSetActive.FlushCacheExt = %hu\n", idd->CommandSetActive.FlushCacheExt); printf("CommandSetActive.Resrved3 = %hu\n", idd->CommandSetActive.Resrved3); printf("CommandSetActive.SmartErrorLog = %hu\n", idd->CommandSetActive.SmartErrorLog); printf("CommandSetActive.SmartSelfTest = %hu\n", idd->CommandSetActive.SmartSelfTest); printf("CommandSetActive.MediaSerialNumber = %hu\n", idd->CommandSetActive.MediaSerialNumber); printf("CommandSetActive.MediaCardPassThrough = %hu\n", idd->CommandSetActive.MediaCardPassThrough); printf("CommandSetActive.StreamingFeature = %hu\n", idd->CommandSetActive.StreamingFeature); printf("CommandSetActive.GpLogging = %hu\n", idd->CommandSetActive.GpLogging); printf("CommandSetActive.WriteFua = %hu\n", idd->CommandSetActive.WriteFua); printf("CommandSetActive.WriteQueuedFua = %hu\n", idd->CommandSetActive.WriteQueuedFua); printf("CommandSetActive.WWN64Bit = %hu\n", idd->CommandSetActive.WWN64Bit); printf("CommandSetActive.URGReadStream = %hu\n", idd->CommandSetActive.URGReadStream); printf("CommandSetActive.URGWriteStream = %hu\n", idd->CommandSetActive.URGWriteStream); printf("CommandSetActive.ReservedForTechReport = %hu\n", idd->CommandSetActive.ReservedForTechReport); printf("CommandSetActive.IdleWithUnloadFeature = %hu\n", idd->CommandSetActive.IdleWithUnloadFeature); printf("CommandSetActive.Reserved4 = %hu\n", idd->CommandSetActive.Reserved4); printf("UltraDMASupport = %hu\n", idd->UltraDMASupport); printf("UltraDMAActive = %hu\n", idd->UltraDMAActive); printf("ReservedWord89[0] = %hu\n", idd->ReservedWord89[0]); printf("ReservedWord89[1] = %hu\n", idd->ReservedWord89[1]); printf("ReservedWord89[2] = %hu\n", idd->ReservedWord89[2]); printf("ReservedWord89[3] = %hu\n", idd->ReservedWord89[3]); printf("HardwareResetResult = %hu\n", idd->HardwareResetResult); printf("CurrentAcousticValue = %hu\n", idd->CurrentAcousticValue); printf("RecommendedAcousticValue = %hu\n", idd->RecommendedAcousticValue); printf("ReservedWord95[0] = %hu\n", idd->ReservedWord95[0]); printf("ReservedWord95[1] = %hu\n", idd->ReservedWord95[1]); printf("ReservedWord95[2] = %hu\n", idd->ReservedWord95[2]); printf("ReservedWord95[3] = %hu\n", idd->ReservedWord95[3]); printf("ReservedWord95[4] = %hu\n", idd->ReservedWord95[4]); printf("Max48BitLBA[0] = %lu\n", idd->Max48BitLBA[0]); printf("Max48BitLBA[1] = %lu\n", idd->Max48BitLBA[1]); printf("StreamingTransferTime = %hu\n", idd->StreamingTransferTime); printf("ReservedWord105 = %hu\n", idd->ReservedWord105); printf("PhysicalLogicalSectorSize.LogicalSectorsPerPhysicalSector = %hu\n", idd->PhysicalLogicalSectorSize.LogicalSectorsPerPhysicalSector); printf("PhysicalLogicalSectorSize.Reserved0 = %hu\n", idd->PhysicalLogicalSectorSize.Reserved0); printf("PhysicalLogicalSectorSize.LogicalSectorLongerThan256Words = %hu\n", idd->PhysicalLogicalSectorSize.LogicalSectorLongerThan256Words); printf("PhysicalLogicalSectorSize.MultipleLogicalSectorsPerPhysicalSector = %hu\n", idd->PhysicalLogicalSectorSize.MultipleLogicalSectorsPerPhysicalSector); printf("PhysicalLogicalSectorSize.Reserved1 = %hu\n", idd->PhysicalLogicalSectorSize.Reserved1); printf("InterSeekDelay = %hu\n", idd->InterSeekDelay); printf("WorldWideName[0] = %hu\n", idd->WorldWideName[0]); printf("WorldWideName[1] = %hu\n", idd->WorldWideName[1]); printf("WorldWideName[2] = %hu\n", idd->WorldWideName[2]); printf("WorldWideName[3] = %hu\n", idd->WorldWideName[3]); printf("ReservedForWorldWideName128[0] = %hu\n", idd->ReservedForWorldWideName128[0]); printf("ReservedForWorldWideName128[1] = %hu\n", idd->ReservedForWorldWideName128[1]); printf("ReservedForWorldWideName128[2] = %hu\n", idd->ReservedForWorldWideName128[2]); printf("ReservedForWorldWideName128[3] = %hu\n", idd->ReservedForWorldWideName128[3]); printf("ReservedForTlcTechnicalReport = %hu\n", idd->ReservedForTlcTechnicalReport); printf("WordsPerLogicalSector[0] = %hu\n", idd->WordsPerLogicalSector[0]); printf("WordsPerLogicalSector[1] = %hu\n", idd->WordsPerLogicalSector[1]); printf("CommandSetSupportExt.ReservedForDrqTechnicalReport = %hu\n", idd->CommandSetSupportExt.ReservedForDrqTechnicalReport); printf("CommandSetSupportExt.WriteReadVerifySupported = %hu\n", idd->CommandSetSupportExt.WriteReadVerifySupported); printf("CommandSetSupportExt.Reserved01 = %hu\n", idd->CommandSetSupportExt.Reserved01); printf("CommandSetSupportExt.Reserved1 = %hu\n", idd->CommandSetSupportExt.Reserved1); printf("CommandSetActiveExt.ReservedForDrqTechnicalReport = %hu\n", idd->CommandSetActiveExt.ReservedForDrqTechnicalReport); printf("CommandSetActiveExt.WriteReadVerifyEnabled = %hu\n", idd->CommandSetActiveExt.WriteReadVerifyEnabled); printf("CommandSetActiveExt.Reserved01 = %hu\n", idd->CommandSetActiveExt.Reserved01); printf("CommandSetActiveExt.Reserved1 = %hu\n", idd->CommandSetActiveExt.Reserved1); printf("ReservedForExpandedSupportandActive[0] = %hu\n", idd->ReservedForExpandedSupportandActive[0]); printf("ReservedForExpandedSupportandActive[1] = %hu\n", idd->ReservedForExpandedSupportandActive[1]); printf("ReservedForExpandedSupportandActive[2] = %hu\n", idd->ReservedForExpandedSupportandActive[2]); printf("ReservedForExpandedSupportandActive[3] = %hu\n", idd->ReservedForExpandedSupportandActive[3]); printf("ReservedForExpandedSupportandActive[4] = %hu\n", idd->ReservedForExpandedSupportandActive[4]); printf("ReservedForExpandedSupportandActive[5] = %hu\n", idd->ReservedForExpandedSupportandActive[5]); printf("MsnSupport = %hu\n", idd->MsnSupport); printf("ReservedWord1274 = %hu\n", idd->ReservedWord1274); printf("SecurityStatus.SecuritySupported = %hu\n", idd->SecurityStatus.SecuritySupported); printf("SecurityStatus.SecurityEnabled = %hu\n", idd->SecurityStatus.SecurityEnabled); printf("SecurityStatus.SecurityLocked = %hu\n", idd->SecurityStatus.SecurityLocked); printf("SecurityStatus.SecurityFrozen = %hu\n", idd->SecurityStatus.SecurityFrozen); printf("SecurityStatus.SecurityCountExpired = %hu\n", idd->SecurityStatus.SecurityCountExpired); printf("SecurityStatus.EnhancedSecurityEraseSupported = %hu\n", idd->SecurityStatus.EnhancedSecurityEraseSupported); printf("SecurityStatus.Reserved0 = %hu\n", idd->SecurityStatus.Reserved0); printf("SecurityStatus.SecurityLevel = %hu\n", idd->SecurityStatus.SecurityLevel); printf("SecurityStatus.Reserved1 = %hu\n", idd->SecurityStatus.Reserved1); printf("ReservedWord129[0] = %hu\n", idd->ReservedWord129[0]); printf("ReservedWord129[1] = %hu\n", idd->ReservedWord129[1]); printf("ReservedWord129[2] = %hu\n", idd->ReservedWord129[2]); printf("ReservedWord129[3] = %hu\n", idd->ReservedWord129[3]); printf("ReservedWord129[4] = %hu\n", idd->ReservedWord129[4]); printf("ReservedWord129[5] = %hu\n", idd->ReservedWord129[5]); printf("ReservedWord129[6] = %hu\n", idd->ReservedWord129[6]); printf("ReservedWord129[7] = %hu\n", idd->ReservedWord129[7]); printf("ReservedWord129[8] = %hu\n", idd->ReservedWord129[8]); printf("ReservedWord129[9] = %hu\n", idd->ReservedWord129[9]); printf("ReservedWord129[10] = %hu\n", idd->ReservedWord129[10]); printf("ReservedWord129[11] = %hu\n", idd->ReservedWord129[11]); printf("ReservedWord129[12] = %hu\n", idd->ReservedWord129[12]); printf("ReservedWord129[13] = %hu\n", idd->ReservedWord129[13]); printf("ReservedWord129[14] = %hu\n", idd->ReservedWord129[14]); printf("ReservedWord129[15] = %hu\n", idd->ReservedWord129[15]); printf("ReservedWord129[16] = %hu\n", idd->ReservedWord129[16]); printf("ReservedWord129[17] = %hu\n", idd->ReservedWord129[17]); printf("ReservedWord129[18] = %hu\n", idd->ReservedWord129[18]); printf("ReservedWord129[19] = %hu\n", idd->ReservedWord129[19]); printf("ReservedWord129[20] = %hu\n", idd->ReservedWord129[20]); printf("ReservedWord129[21] = %hu\n", idd->ReservedWord129[21]); printf("ReservedWord129[22] = %hu\n", idd->ReservedWord129[22]); printf("ReservedWord129[23] = %hu\n", idd->ReservedWord129[23]); printf("ReservedWord129[24] = %hu\n", idd->ReservedWord129[24]); printf("ReservedWord129[25] = %hu\n", idd->ReservedWord129[25]); printf("ReservedWord129[26] = %hu\n", idd->ReservedWord129[26]); printf("ReservedWord129[27] = %hu\n", idd->ReservedWord129[27]); printf("ReservedWord129[28] = %hu\n", idd->ReservedWord129[28]); printf("ReservedWord129[29] = %hu\n", idd->ReservedWord129[29]); printf("ReservedWord129[30] = %hu\n", idd->ReservedWord129[30]); printf("CfaPowerModel.MaximumCurrentInMA2 = %hu\n", idd->CfaPowerModel.MaximumCurrentInMA2); printf("CfaPowerModel.CfaPowerMode1Disabled = %hu\n", idd->CfaPowerModel.CfaPowerMode1Disabled); printf("CfaPowerModel.CfaPowerMode1Required = %hu\n", idd->CfaPowerModel.CfaPowerMode1Required); printf("CfaPowerModel.Reserved0 = %hu\n", idd->CfaPowerModel.Reserved0); printf("CfaPowerModel.Word160Supported = %hu\n", idd->CfaPowerModel.Word160Supported); printf("ReservedForCfaWord161[0] = %hu\n", idd->ReservedForCfaWord161[0]); printf("ReservedForCfaWord161[1] = %hu\n", idd->ReservedForCfaWord161[1]); printf("ReservedForCfaWord161[2] = %hu\n", idd->ReservedForCfaWord161[2]); printf("ReservedForCfaWord161[3] = %hu\n", idd->ReservedForCfaWord161[3]); printf("ReservedForCfaWord161[4] = %hu\n", idd->ReservedForCfaWord161[4]); printf("ReservedForCfaWord161[5] = %hu\n", idd->ReservedForCfaWord161[5]); printf("ReservedForCfaWord161[6] = %hu\n", idd->ReservedForCfaWord161[6]); printf("ReservedForCfaWord161[7] = %hu\n", idd->ReservedForCfaWord161[7]); printf("DataSetManagementFeature.SupportsTrim = %hu\n", idd->DataSetManagementFeature.SupportsTrim); printf("DataSetManagementFeature.Reserved0 = %hu\n", idd->DataSetManagementFeature.Reserved0); printf("ReservedForCfaWord170[0] = %hu\n", idd->ReservedForCfaWord170[0]); printf("ReservedForCfaWord170[1] = %hu\n", idd->ReservedForCfaWord170[1]); printf("ReservedForCfaWord170[2] = %hu\n", idd->ReservedForCfaWord170[2]); printf("ReservedForCfaWord170[3] = %hu\n", idd->ReservedForCfaWord170[3]); printf("ReservedForCfaWord170[4] = %hu\n", idd->ReservedForCfaWord170[4]); printf("ReservedForCfaWord170[5] = %hu\n", idd->ReservedForCfaWord170[5]); printf("CurrentMediaSerialNumber[0] = %hu\n", idd->CurrentMediaSerialNumber[0]); printf("CurrentMediaSerialNumber[1] = %hu\n", idd->CurrentMediaSerialNumber[1]); printf("CurrentMediaSerialNumber[2] = %hu\n", idd->CurrentMediaSerialNumber[2]); printf("CurrentMediaSerialNumber[3] = %hu\n", idd->CurrentMediaSerialNumber[3]); printf("CurrentMediaSerialNumber[4] = %hu\n", idd->CurrentMediaSerialNumber[4]); printf("CurrentMediaSerialNumber[5] = %hu\n", idd->CurrentMediaSerialNumber[5]); printf("CurrentMediaSerialNumber[6] = %hu\n", idd->CurrentMediaSerialNumber[6]); printf("CurrentMediaSerialNumber[7] = %hu\n", idd->CurrentMediaSerialNumber[7]); printf("CurrentMediaSerialNumber[8] = %hu\n", idd->CurrentMediaSerialNumber[8]); printf("CurrentMediaSerialNumber[9] = %hu\n", idd->CurrentMediaSerialNumber[9]); printf("CurrentMediaSerialNumber[10] = %hu\n", idd->CurrentMediaSerialNumber[10]); printf("CurrentMediaSerialNumber[11] = %hu\n", idd->CurrentMediaSerialNumber[11]); printf("CurrentMediaSerialNumber[12] = %hu\n", idd->CurrentMediaSerialNumber[12]); printf("CurrentMediaSerialNumber[13] = %hu\n", idd->CurrentMediaSerialNumber[13]); printf("CurrentMediaSerialNumber[14] = %hu\n", idd->CurrentMediaSerialNumber[14]); printf("CurrentMediaSerialNumber[15] = %hu\n", idd->CurrentMediaSerialNumber[15]); printf("CurrentMediaSerialNumber[16] = %hu\n", idd->CurrentMediaSerialNumber[16]); printf("CurrentMediaSerialNumber[17] = %hu\n", idd->CurrentMediaSerialNumber[17]); printf("CurrentMediaSerialNumber[18] = %hu\n", idd->CurrentMediaSerialNumber[18]); printf("CurrentMediaSerialNumber[19] = %hu\n", idd->CurrentMediaSerialNumber[19]); printf("CurrentMediaSerialNumber[20] = %hu\n", idd->CurrentMediaSerialNumber[20]); printf("CurrentMediaSerialNumber[21] = %hu\n", idd->CurrentMediaSerialNumber[21]); printf("CurrentMediaSerialNumber[22] = %hu\n", idd->CurrentMediaSerialNumber[22]); printf("CurrentMediaSerialNumber[23] = %hu\n", idd->CurrentMediaSerialNumber[23]); printf("CurrentMediaSerialNumber[24] = %hu\n", idd->CurrentMediaSerialNumber[24]); printf("CurrentMediaSerialNumber[25] = %hu\n", idd->CurrentMediaSerialNumber[25]); printf("CurrentMediaSerialNumber[26] = %hu\n", idd->CurrentMediaSerialNumber[26]); printf("CurrentMediaSerialNumber[27] = %hu\n", idd->CurrentMediaSerialNumber[27]); printf("CurrentMediaSerialNumber[28] = %hu\n", idd->CurrentMediaSerialNumber[28]); printf("CurrentMediaSerialNumber[29] = %hu\n", idd->CurrentMediaSerialNumber[29]); printf("ReservedWord206 = %hu\n", idd->ReservedWord206); printf("ReservedWord207[0] = %hu\n", idd->ReservedWord207[0]); printf("ReservedWord207[1] = %hu\n", idd->ReservedWord207[1]); printf("BlockAlignment.AlignmentOfLogicalWithinPhysical = %hu\n", idd->BlockAlignment.AlignmentOfLogicalWithinPhysical); printf("BlockAlignment.Word209Supported = %hu\n", idd->BlockAlignment.Word209Supported); printf("BlockAlignment.Reserved0 = %hu\n", idd->BlockAlignment.Reserved0); printf("WriteReadVerifySectorCountMode3Only[0] = %hu\n", idd->WriteReadVerifySectorCountMode3Only[0]); printf("WriteReadVerifySectorCountMode3Only[1] = %hu\n", idd->WriteReadVerifySectorCountMode3Only[1]); printf("WriteReadVerifySectorCountMode2Only[0] = %hu\n", idd->WriteReadVerifySectorCountMode2Only[0]); printf("WriteReadVerifySectorCountMode2Only[1] = %hu\n", idd->WriteReadVerifySectorCountMode2Only[1]); printf("NVCacheCapabilities.NVCachePowerModeEnabled = %hu\n", idd->NVCacheCapabilities.NVCachePowerModeEnabled); printf("NVCacheCapabilities.Reserved0 = %hu\n", idd->NVCacheCapabilities.Reserved0); printf("NVCacheCapabilities.NVCacheFeatureSetEnabled = %hu\n", idd->NVCacheCapabilities.NVCacheFeatureSetEnabled); printf("NVCacheCapabilities.Reserved1 = %hu\n", idd->NVCacheCapabilities.Reserved1); printf("NVCacheCapabilities.NVCachePowerModeVersion = %hu\n", idd->NVCacheCapabilities.NVCachePowerModeVersion); printf("NVCacheCapabilities.NVCacheFeatureSetVersion = %hu\n", idd->NVCacheCapabilities.NVCacheFeatureSetVersion); printf("NVCacheSizeLSW = %hu\n", idd->NVCacheSizeLSW); printf("NVCacheSizeMSW = %hu\n", idd->NVCacheSizeMSW); printf("NominalMediaRotationRate = %hu\n", idd->NominalMediaRotationRate); printf("ReservedWord218 = %hu\n", idd->ReservedWord218); printf("NVCacheOptions.NVCacheEstimatedTimeToSpinUpInSeconds = %d\n", idd->NVCacheOptions.NVCacheEstimatedTimeToSpinUpInSeconds); printf("NVCacheOptions.Reserved = %d\n", idd->NVCacheOptions.Reserved); printf("ReservedWord220[0] = %hu\n", idd->ReservedWord220[0]); printf("ReservedWord220[1] = %hu\n", idd->ReservedWord220[1]); printf("ReservedWord220[2] = %hu\n", idd->ReservedWord220[2]); printf("ReservedWord220[3] = %hu\n", idd->ReservedWord220[3]); printf("ReservedWord220[4] = %hu\n", idd->ReservedWord220[4]); printf("ReservedWord220[5] = %hu\n", idd->ReservedWord220[5]); printf("ReservedWord220[6] = %hu\n", idd->ReservedWord220[6]); printf("ReservedWord220[7] = %hu\n", idd->ReservedWord220[7]); printf("ReservedWord220[8] = %hu\n", idd->ReservedWord220[8]); printf("ReservedWord220[9] = %hu\n", idd->ReservedWord220[9]); printf("ReservedWord220[10] = %hu\n", idd->ReservedWord220[10]); printf("ReservedWord220[11] = %hu\n", idd->ReservedWord220[11]); printf("ReservedWord220[12] = %hu\n", idd->ReservedWord220[12]); printf("ReservedWord220[13] = %hu\n", idd->ReservedWord220[13]); printf("ReservedWord220[14] = %hu\n", idd->ReservedWord220[14]); printf("ReservedWord220[15] = %hu\n", idd->ReservedWord220[15]); printf("ReservedWord220[16] = %hu\n", idd->ReservedWord220[16]); printf("ReservedWord220[17] = %hu\n", idd->ReservedWord220[17]); printf("ReservedWord220[18] = %hu\n", idd->ReservedWord220[18]); printf("ReservedWord220[19] = %hu\n", idd->ReservedWord220[19]); printf("ReservedWord220[20] = %hu\n", idd->ReservedWord220[20]); printf("ReservedWord220[21] = %hu\n", idd->ReservedWord220[21]); printf("ReservedWord220[22] = %hu\n", idd->ReservedWord220[22]); printf("ReservedWord220[23] = %hu\n", idd->ReservedWord220[23]); printf("ReservedWord220[24] = %hu\n", idd->ReservedWord220[24]); printf("ReservedWord220[25] = %hu\n", idd->ReservedWord220[25]); printf("ReservedWord220[26] = %hu\n", idd->ReservedWord220[26]); printf("ReservedWord220[27] = %hu\n", idd->ReservedWord220[27]); printf("ReservedWord220[28] = %hu\n", idd->ReservedWord220[28]); printf("ReservedWord220[29] = %hu\n", idd->ReservedWord220[29]); printf("ReservedWord220[30] = %hu\n", idd->ReservedWord220[30]); printf("ReservedWord220[31] = %hu\n", idd->ReservedWord220[31]); printf("ReservedWord220[32] = %hu\n", idd->ReservedWord220[32]); printf("ReservedWord220[33] = %hu\n", idd->ReservedWord220[33]); printf("ReservedWord220[34] = %hu\n", idd->ReservedWord220[34]); printf("Signature = %hu\n", idd->Signature); printf("CheckSum = %hu\n", idd->CheckSum); printf("====================\n"); printf("END IDENTIFY_DEVICE_DATA for %s\n", deviceNameBuffer); printf("====================\n"); printf("\n"); CloseHandle(diskHandle); } return 0; }
32,223
C++
.cpp
430
71.886047
983
0.750165
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,011
Al-khaser.cpp
LordNoteworthy_al-khaser/al-khaser/Al-khaser.cpp
// al-khaser.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" BOOL ENABLE_TLS_CHECKS = FALSE; BOOL ENABLE_DEBUG_CHECKS = FALSE; BOOL ENABLE_INJECTION_CHECKS = FALSE; BOOL ENABLE_GEN_SANDBOX_CHECKS = FALSE; BOOL ENABLE_VBOX_CHECKS = FALSE; BOOL ENABLE_VMWARE_CHECKS = FALSE; BOOL ENABLE_VPC_CHECKS = FALSE; BOOL ENABLE_QEMU_CHECKS = FALSE; BOOL ENABLE_KVM_CHECKS = FALSE; BOOL ENABLE_XEN_CHECKS = FALSE; BOOL ENABLE_WINE_CHECKS = FALSE; BOOL ENABLE_PARALLELS_CHECKS = FALSE; BOOL ENABLE_HYPERV_CHECKS = FALSE; BOOL ENABLE_CODE_INJECTIONS = FALSE; BOOL ENABLE_TIMING_ATTACKS = FALSE; BOOL ENABLE_DUMPING_CHECK = FALSE; BOOL ENABLE_ANALYSIS_TOOLS_CHECK = FALSE; BOOL ENABLE_ANTI_DISASSM_CHECKS = FALSE; void EnableDefaultChecks() { ENABLE_TLS_CHECKS = TRUE; ENABLE_DEBUG_CHECKS = TRUE; ENABLE_INJECTION_CHECKS = TRUE; ENABLE_GEN_SANDBOX_CHECKS = TRUE; ENABLE_VBOX_CHECKS = TRUE; ENABLE_VMWARE_CHECKS = TRUE; ENABLE_VPC_CHECKS = TRUE; ENABLE_QEMU_CHECKS = TRUE; ENABLE_KVM_CHECKS = TRUE; ENABLE_XEN_CHECKS = TRUE; ENABLE_WINE_CHECKS = TRUE; ENABLE_PARALLELS_CHECKS = TRUE; ENABLE_HYPERV_CHECKS = TRUE; ENABLE_TIMING_ATTACKS = TRUE; ENABLE_DUMPING_CHECK = TRUE; ENABLE_ANALYSIS_TOOLS_CHECK = TRUE; ENABLE_ANTI_DISASSM_CHECKS = TRUE; } void EnableChecks(std::string checkType) { if (checkType == "TLS") ENABLE_TLS_CHECKS = TRUE; else if (checkType == "DEBUG") ENABLE_DEBUG_CHECKS = TRUE; else if (checkType == "INJECTION") ENABLE_INJECTION_CHECKS = TRUE; else if (checkType == "GEN_SANDBOX") ENABLE_GEN_SANDBOX_CHECKS = TRUE; else if (checkType == "VBOX") ENABLE_VBOX_CHECKS = TRUE; else if (checkType == "VMWARE") ENABLE_VMWARE_CHECKS = TRUE; else if (checkType == "VPC") ENABLE_VPC_CHECKS = TRUE; else if (checkType == "QEMU") ENABLE_QEMU_CHECKS = TRUE; else if (checkType == "KVM") ENABLE_KVM_CHECKS = TRUE; else if (checkType == "XEN") ENABLE_XEN_CHECKS = TRUE; else if (checkType == "WINE") ENABLE_WINE_CHECKS = TRUE; else if (checkType == "PARALLELS") ENABLE_PARALLELS_CHECKS = TRUE; else if (checkType == "HYPERV") ENABLE_HYPERV_CHECKS = TRUE; else if (checkType == "CODE_INJECTIONS") ENABLE_CODE_INJECTIONS = TRUE; else if (checkType == "TIMING_ATTACKS") ENABLE_TIMING_ATTACKS = TRUE; else if (checkType == "DUMPING_CHECK") ENABLE_DUMPING_CHECK = TRUE; else if (checkType == "ANALYSIS_TOOLS") ENABLE_ANALYSIS_TOOLS_CHECK = TRUE; else if (checkType == "ANTI_DISASSM") ENABLE_ANTI_DISASSM_CHECKS = TRUE; } int main(int argc, char* argv[]) { /* enable functions */ if (argc > 1) { for (int i = 1; i < argc; i += 2) { if (strcmp(argv[i], "--check") == 0 && (i + 1 < argc)) { EnableChecks(argv[i + 1]); } } } else { EnableDefaultChecks(); } /* Resize the console window for better visibility */ resize_console_window(); /* Display general informations */ _tprintf(_T("[al-khaser version 0.82]")); print_category(TEXT("Initialisation")); API::Init(); print_os(); API::PrintAvailabilityReport(); /* Are we running under WoW64 */ if (IsWoW64()) _tprintf(_T("Process is running under WOW64\n\n")); if (ENABLE_DEBUG_CHECKS) PageExceptionInitialEnum(); /* TLS checks */ if (ENABLE_TLS_CHECKS) { print_category(TEXT("TLS Callbacks")); exec_check(&TLSCallbackProcess, TEXT("TLS process attach callback ")); exec_check(&TLSCallbackThread, TEXT("TLS thread attach callback ")); } /* Debugger Detection */ if (ENABLE_DEBUG_CHECKS) { print_category(TEXT("Debugger Detection")); exec_check(&IsDebuggerPresentAPI, TEXT("Checking IsDebuggerPresent API ")); exec_check(&IsDebuggerPresentPEB, TEXT("Checking PEB.BeingDebugged ")); exec_check(&CheckRemoteDebuggerPresentAPI, TEXT("Checking CheckRemoteDebuggerPresent API ")); exec_check(&NtGlobalFlag, TEXT("Checking PEB.NtGlobalFlag ")); exec_check(&HeapFlags, TEXT("Checking ProcessHeap.Flags ")); exec_check(&HeapForceFlags, TEXT("Checking ProcessHeap.ForceFlags ")); exec_check(&LowFragmentationHeap, TEXT("Checking Low Fragmentation Heap")); exec_check(&NtQueryInformationProcess_ProcessDebugPort, TEXT("Checking NtQueryInformationProcess with ProcessDebugPort ")); exec_check(&NtQueryInformationProcess_ProcessDebugFlags, TEXT("Checking NtQueryInformationProcess with ProcessDebugFlags ")); exec_check(&NtQueryInformationProcess_ProcessDebugObject, TEXT("Checking NtQueryInformationProcess with ProcessDebugObject ")); exec_check(&WUDF_IsAnyDebuggerPresent, TEXT("Checking WudfIsAnyDebuggerPresent API ")); exec_check(&WUDF_IsKernelDebuggerPresent, TEXT("Checking WudfIsKernelDebuggerPresent API ")); exec_check(&WUDF_IsUserDebuggerPresent, TEXT("Checking WudfIsUserDebuggerPresent API ")); exec_check(&NtSetInformationThread_ThreadHideFromDebugger, TEXT("Checking NtSetInformationThread with ThreadHideFromDebugger ")); exec_check(&CloseHandle_InvalideHandle, TEXT("Checking CloseHandle with an invalide handle ")); exec_check(&NtSystemDebugControl_Command, TEXT("Checking NtSystemDebugControl")); exec_check(&UnhandledExcepFilterTest, TEXT("Checking UnhandledExcepFilterTest ")); exec_check(&OutputDebugStringAPI, TEXT("Checking OutputDebugString ")); exec_check(&HardwareBreakpoints, TEXT("Checking Hardware Breakpoints ")); exec_check(&SoftwareBreakpoints, TEXT("Checking Software Breakpoints ")); exec_check(&Interrupt_0x2d, TEXT("Checking Interupt 0x2d ")); exec_check(&Interrupt_3, TEXT("Checking Interupt 1 ")); exec_check(&TrapFlag, TEXT("Checking trap flag")); exec_check(&MemoryBreakpoints_PageGuard, TEXT("Checking Memory Breakpoints PAGE GUARD ")); exec_check(&IsParentExplorerExe, TEXT("Checking If Parent Process is explorer.exe ")); exec_check(&CanOpenCsrss, TEXT("Checking SeDebugPrivilege ")); exec_check(&NtQueryObject_ObjectTypeInformation, TEXT("Checking NtQueryObject with ObjectTypeInformation ")); exec_check(&NtQueryObject_ObjectAllTypesInformation, TEXT("Checking NtQueryObject with ObjectAllTypesInformation ")); exec_check(&NtYieldExecutionAPI, TEXT("Checking NtYieldExecution ")); exec_check(&SetHandleInformatiom_ProtectedHandle, TEXT("Checking CloseHandle protected handle trick ")); exec_check(&NtQuerySystemInformation_SystemKernelDebuggerInformation, TEXT("Checking NtQuerySystemInformation with SystemKernelDebuggerInformation ")); exec_check(&SharedUserData_KernelDebugger, TEXT("Checking SharedUserData->KdDebuggerEnabled ")); exec_check(&ProcessJob, TEXT("Checking if process is in a job ")); exec_check(&VirtualAlloc_WriteWatch_BufferOnly, TEXT("Checking VirtualAlloc write watch (buffer only) ")); exec_check(&VirtualAlloc_WriteWatch_APICalls, TEXT("Checking VirtualAlloc write watch (API calls) ")); exec_check(&VirtualAlloc_WriteWatch_IsDebuggerPresent, TEXT("Checking VirtualAlloc write watch (IsDebuggerPresent) ")); exec_check(&VirtualAlloc_WriteWatch_CodeWrite, TEXT("Checking VirtualAlloc write watch (code write) ")); exec_check(&PageExceptionBreakpointCheck, TEXT("Checking for page exception breakpoints ")); exec_check(&ModuleBoundsHookCheck, TEXT("Checking for API hooks outside module bounds ")); } if (ENABLE_INJECTION_CHECKS) { print_category(TEXT("DLL Injection Detection")); exec_check(&ScanForModules_EnumProcessModulesEx_32bit, TEXT("Enumerating modules with EnumProcessModulesEx [32-bit] ")); exec_check(&ScanForModules_EnumProcessModulesEx_64bit, TEXT("Enumerating modules with EnumProcessModulesEx [64-bit] ")); exec_check(&ScanForModules_EnumProcessModulesEx_All, TEXT("Enumerating modules with EnumProcessModulesEx [ALL] ")); exec_check(&ScanForModules_ToolHelp32, TEXT("Enumerating modules with ToolHelp32 ")); exec_check(&ScanForModules_LdrEnumerateLoadedModules, TEXT("Enumerating the process LDR via LdrEnumerateLoadedModules ")); exec_check(&ScanForModules_LDR_Direct, TEXT("Enumerating the process LDR directly ")); exec_check(&ScanForModules_MemoryWalk_GMI, TEXT("Walking process memory with GetModuleInformation ")); exec_check(&ScanForModules_MemoryWalk_Hidden, TEXT("Walking process memory for hidden modules ")); exec_check(&ScanForModules_DotNetModuleStructures, TEXT("Walking process memory for .NET module structures ")); } /* Generic sandbox detection */ if (ENABLE_GEN_SANDBOX_CHECKS) { print_category(TEXT("Generic Sandboxe/VM Detection")); loaded_dlls(); known_file_names(); known_usernames(); known_hostnames(); other_known_sandbox_environment_checks(); exec_check(&NumberOfProcessors, TEXT("Checking Number of processors in machine ")); exec_check(&idt_trick, TEXT("Checking Interupt Descriptor Table location ")); exec_check(&ldt_trick, TEXT("Checking Local Descriptor Table location ")); exec_check(&gdt_trick, TEXT("Checking Global Descriptor Table location ")); exec_check(&str_trick, TEXT("Checking Store Task Register ")); exec_check(&number_cores_wmi, TEXT("Checking Number of cores in machine using WMI ")); exec_check(&disk_size_wmi, TEXT("Checking hard disk size using WMI ")); exec_check(&dizk_size_deviceiocontrol, TEXT("Checking hard disk size using DeviceIoControl ")); exec_check(&setupdi_diskdrive, TEXT("Checking SetupDi_diskdrive ")); exec_check(&mouse_movement, TEXT("Checking mouse movement ")); exec_check(&lack_user_input, TEXT("Checking lack of user input ")); exec_check(&memory_space, TEXT("Checking memory space using GlobalMemoryStatusEx ")); exec_check(&disk_size_getdiskfreespace, TEXT("Checking disk size using GetDiskFreeSpaceEx ")); exec_check(&cpuid_is_hypervisor, TEXT("Checking if CPU hypervisor field is set using cpuid(0x1)")); exec_check(&cpuid_hypervisor_vendor, TEXT("Checking hypervisor vendor using cpuid(0x40000000)")); exec_check(&accelerated_sleep, TEXT("Check if time has been accelerated ")); exec_check(&VMDriverServices, TEXT("VM Driver Services ")); exec_check(&serial_number_bios_wmi, TEXT("Checking SerialNumber from BIOS using WMI ")); exec_check(&model_computer_system_wmi, TEXT("Checking Model from ComputerSystem using WMI ")); exec_check(&manufacturer_computer_system_wmi, TEXT("Checking Manufacturer from ComputerSystem using WMI ")); exec_check(&current_temperature_acpi_wmi, TEXT("Checking Current Temperature using WMI ")); exec_check(&process_id_processor_wmi, TEXT("Checking ProcessId using WMI ")); exec_check(&power_capabilities, TEXT("Checking power capabilities ")); exec_check(&cpu_fan_wmi, TEXT("Checking CPU fan using WMI ")); exec_check(&query_license_value, TEXT("Checking NtQueryLicenseValue with Kernel-VMDetection-Private ")); exec_check(&cachememory_wmi, TEXT("Checking Win32_CacheMemory with WMI ")); exec_check(&physicalmemory_wmi, TEXT("Checking Win32_PhysicalMemory with WMI ")); exec_check(&memorydevice_wmi, TEXT("Checking Win32_MemoryDevice with WMI ")); exec_check(&memoryarray_wmi, TEXT("Checking Win32_MemoryArray with WMI ")); exec_check(&voltageprobe_wmi, TEXT("Checking Win32_VoltageProbe with WMI ")); exec_check(&portconnector_wmi, TEXT("Checking Win32_PortConnector with WMI ")); exec_check(&smbiosmemory_wmi, TEXT("Checking Win32_SMBIOSMemory with WMI ")); exec_check(&perfctrs_thermalzoneinfo_wmi, TEXT("Checking ThermalZoneInfo performance counters with WMI ")); exec_check(&cim_memory_wmi, TEXT("Checking CIM_Memory with WMI ")); exec_check(&cim_sensor_wmi, TEXT("Checking CIM_Sensor with WMI ")); exec_check(&cim_numericsensor_wmi, TEXT("Checking CIM_NumericSensor with WMI ")); exec_check(&cim_temperaturesensor_wmi, TEXT("Checking CIM_TemperatureSensor with WMI ")); exec_check(&cim_voltagesensor_wmi, TEXT("Checking CIM_VoltageSensor with WMI ")); exec_check(&cim_physicalconnector_wmi, TEXT("Checking CIM_PhysicalConnector with WMI ")); exec_check(&cim_slot_wmi, TEXT("Checking CIM_Slot with WMI ")); exec_check(&pirated_windows, TEXT("Checking if Windows is Genuine ")); exec_check(&registry_services_disk_enum, TEXT("Checking Services\\Disk\\Enum entries for VM strings ")); exec_check(&registry_disk_enum, TEXT("Checking Enum\\IDE and Enum\\SCSI entries for VM strings ")); exec_check(&number_SMBIOS_tables, TEXT("Checking SMBIOS tables ")); } /* VirtualBox Detection */ if (ENABLE_VBOX_CHECKS) { print_category(TEXT("VirtualBox Detection")); vbox_reg_key_value(); exec_check(&vbox_dir, TEXT("Checking VirtualBox Guest Additions directory ")); vbox_files(); vbox_reg_keys(); exec_check(&vbox_check_mac, TEXT("Checking Mac Address start with 08:00:27 ")); exec_check(&hybridanalysismacdetect, TEXT("Checking MAC address (Hybrid Analysis) ")); vbox_devices(); exec_check(&vbox_window_class, TEXT("Checking VBoxTrayToolWndClass / VBoxTrayToolWnd ")); exec_check(&vbox_network_share, TEXT("Checking VirtualBox Shared Folders network provider ")); vbox_processes(); exec_check(&vbox_pnpentity_pcideviceid_wmi, TEXT("Checking Win32_PnPDevice DeviceId from WMI for VBox PCI device ")); exec_check(&vbox_pnpentity_controllers_wmi, TEXT("Checking Win32_PnPDevice Name from WMI for VBox controller hardware ")); exec_check(&vbox_pnpentity_vboxname_wmi, TEXT("Checking Win32_PnPDevice Name from WMI for VBOX names ")); exec_check(&vbox_bus_wmi, TEXT("Checking Win32_Bus from WMI ")); exec_check(&vbox_baseboard_wmi, TEXT("Checking Win32_BaseBoard from WMI ")); exec_check(&vbox_mac_wmi, TEXT("Checking MAC address from WMI ")); exec_check(&vbox_eventlogfile_wmi, TEXT("Checking NTEventLog from WMI ")); exec_check(&vbox_firmware_SMBIOS, TEXT("Checking SMBIOS firmware ")); exec_check(&vbox_firmware_ACPI, TEXT("Checking ACPI tables ")); } /* VMWare Detection */ if (ENABLE_VMWARE_CHECKS) { print_category(TEXT("VMWare Detection")); vmware_reg_key_value(); vmware_reg_keys(); vmware_files(); vmware_mac(); exec_check(&vmware_adapter_name, TEXT("Checking VMWare network adapter name ")); vmware_devices(); exec_check(&vmware_dir, TEXT("Checking VMWare directory ")); exec_check(&vmware_firmware_SMBIOS, TEXT("Checking SMBIOS firmware ")); exec_check(&vmware_firmware_ACPI, TEXT("Checking ACPI tables ")); } /* Virtual PC Detection */ if (ENABLE_VPC_CHECKS) { print_category(TEXT("Virtual PC Detection")); virtual_pc_process(); virtual_pc_reg_keys(); } /* QEMU Detection */ if (ENABLE_QEMU_CHECKS) { print_category(TEXT("QEMU Detection")); qemu_reg_key_value(); qemu_processes(); qemu_dir(); exec_check(&qemu_firmware_SMBIOS, TEXT("Checking SMBIOS firmware ")); exec_check(&qemu_firmware_ACPI, TEXT("Checking ACPI tables ")); } /* Xen Detection */ if (ENABLE_XEN_CHECKS) { print_category(TEXT("Xen Detection")); xen_process(); exec_check(&xen_check_mac, TEXT("Checking Mac Address start with 08:16:3E ")); } /* KVM Detection */ if (ENABLE_KVM_CHECKS) { print_category(TEXT("Xen Detection")); kvm_files(); kvm_reg_keys(); exec_check(&kvm_dir, TEXT("Checking KVM virio directory ")); } /* Wine Detection */ if (ENABLE_WINE_CHECKS) { print_category(TEXT("Wine Detection")); exec_check(&wine_exports, TEXT("Checking Wine via dll exports ")); wine_reg_keys(); } /* Paralles Detection */ if (ENABLE_PARALLELS_CHECKS) { print_category(TEXT("Paralles Detection")); parallels_process(); exec_check(&parallels_check_mac, TEXT("Checking Mac Address start with 00:1C:42 ")); } if (ENABLE_HYPERV_CHECKS) { print_category(TEXT("Hyper-V Detection")); exec_check(&check_hyperv_driver_objects, TEXT("Checking for Hyper-V driver objects ")); exec_check(&check_hyperv_global_objects, TEXT("Checking for Hyper-V global objects ")); } /* Code injections techniques */ if (ENABLE_CODE_INJECTIONS) { CreateRemoteThread_Injection(); SetWindowsHooksEx_Injection(); NtCreateThreadEx_Injection(); RtlCreateUserThread_Injection(); QueueUserAPC_Injection(); GetSetThreadContext_Injection(); } /* Timing Attacks */ if (ENABLE_TIMING_ATTACKS) { print_category(TEXT("Timing-attacks")); UINT delayInSeconds = 600U; UINT delayInMillis = delayInSeconds * 1000U; printf("\n[*] Delay value is set to %u minutes ...\n", delayInSeconds / 60); exec_check(timing_NtDelayexecution, delayInMillis, TEXT("Performing a sleep using NtDelayExecution ...")); exec_check(timing_sleep_loop, delayInMillis, TEXT("Performing a sleep() in a loop ...")); exec_check(timing_SetTimer, delayInMillis, TEXT("Delaying execution using SetTimer ...")); exec_check(timing_timeSetEvent, delayInMillis, TEXT("Delaying execution using timeSetEvent ...")); exec_check(timing_WaitForSingleObject, delayInMillis, TEXT("Delaying execution using WaitForSingleObject ...")); exec_check(timing_WaitForMultipleObjects, delayInMillis, TEXT("Delaying execution using WaitForMultipleObjects ...")); exec_check(timing_IcmpSendEcho, delayInMillis, TEXT("Delaying execution using IcmpSendEcho ...")); exec_check(timing_CreateWaitableTimer, delayInMillis, TEXT("Delaying execution using CreateWaitableTimer ...")); exec_check(timing_CreateTimerQueueTimer, delayInMillis, TEXT("Delaying execution using CreateTimerQueueTimer ...")); exec_check(&rdtsc_diff_locky, TEXT("Checking RDTSC Locky trick ")); exec_check(&rdtsc_diff_vmexit, TEXT("Checking RDTSC which force a VM Exit (cpuid) ")); } /* Malware analysis tools */ if (ENABLE_ANALYSIS_TOOLS_CHECK) { print_category(TEXT("Analysis-tools")); analysis_tools_process(); } /* Anti disassembler tricks */ if (ENABLE_ANTI_DISASSM_CHECKS) { _tprintf(_T("Begin AntiDisassmConstantCondition\n")); AntiDisassmConstantCondition(); _tprintf(_T("Begin AntiDisassmAsmJmpSameTarget\n")); AntiDisassmAsmJmpSameTarget(); _tprintf(_T("Begin AntiDisassmImpossibleDiasassm\n")); AntiDisassmImpossibleDiasassm(); _tprintf(_T("Begin AntiDisassmFunctionPointer\n")); AntiDisassmFunctionPointer(); _tprintf(_T("Begin AntiDisassmReturnPointerAbuse\n")); AntiDisassmReturnPointerAbuse(); #ifndef _WIN64 _tprintf(_T("Begin AntiDisassmSEHMisuse\n")); AntiDisassmSEHMisuse(); #endif } /* Anti Dumping */ if (ENABLE_DUMPING_CHECK) { print_category(TEXT("Anti Dumping")); ErasePEHeaderFromMemory(); SizeOfImage(); } _tprintf(_T("\n\nAnalysis done, I hope you didn't get red flags :)")); getchar(); return 0; }
18,602
C++
.cpp
339
51.126844
155
0.739814
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,013
timing.cpp
LordNoteworthy_al-khaser/al-khaser/TimingAttacks/timing.cpp
#include "pch.h" #include "timing.h" /* Timing attacks or sleepy malwares are used to bypass sandboxed in general Every system which run in a timeout is vulnerable to this types of attacks */ BOOL timing_NtDelayexecution(UINT delayInMillis) { // In this example, I will demonstrate NtDelayExecution because it is the lowest user mode // api to delay execution Sleep -> SleepEx -> NtDelayExecution. LARGE_INTEGER DelayInterval; LONGLONG llDelay = delayInMillis * 10000LL; DelayInterval.QuadPart = -llDelay; if (!API::IsAvailable(API_IDENTIFIER::API_NtDelayExecution)) return TRUE; // TODO: make this a warning (NtDelayExecution should always exist) auto NtDelayExecution = static_cast<pNtDelayExecution>(API::GetAPI(API_IDENTIFIER::API_NtDelayExecution)); NtDelayExecution(FALSE, &DelayInterval); return FALSE; } BOOL bProcessed = FALSE; VOID CALLBACK TimerProc(HWND hwnd, UINT message, UINT_PTR iTimerID, DWORD dwTime) { // Malicious code is place here .... bProcessed = TRUE; } BOOL timing_SetTimer(UINT delayInMillis) { MSG Msg; UINT_PTR iTimerID; // Set our timer without window handle iTimerID = SetTimer(NULL, 0, delayInMillis, TimerProc); if (iTimerID == NULL) return TRUE; // Because we are running in a console app, we should get the messages from // the queue and check if msg is WM_TIMER while (GetMessage(&Msg, NULL, 0, 0) & !bProcessed) { TranslateMessage(&Msg); DispatchMessage(&Msg); } // Kill the timer KillTimer(NULL, iTimerID); return FALSE; } VOID CALLBACK TimerFunction(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) { bProcessed = TRUE; } BOOL timing_timeSetEvent(UINT delayInMillis) { // Some vars UINT uResolution; TIMECAPS tc; MMRESULT idEvent; // We can obtain this minimum value by calling timeGetDevCaps(&tc, sizeof(TIMECAPS)); uResolution = min(max(tc.wPeriodMin, 0), tc.wPeriodMax); // Create the timer idEvent = timeSetEvent( delayInMillis, uResolution, TimerFunction, 0, TIME_ONESHOT); if (idEvent == NULL) return TRUE; while (!bProcessed){ // wait until uor function finish } // destroy the timer timeKillEvent(idEvent); // reset the timer timeEndPeriod(uResolution); return FALSE; } BOOL timing_WaitForSingleObject(UINT delayInMillis) { HANDLE hEvent; // Create a nonsignaled event hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (hEvent == NULL) { print_last_error(_T("CreateEvent")); return TRUE; } // Wait until timeout DWORD x = WaitForSingleObject(hEvent, delayInMillis); // Malicious code goes here return FALSE; } BOOL timing_WaitForMultipleObjects(UINT delayInMillis) { HANDLE hThread; HANDLE ghEvents[2]; DWORD i, dwEvent, dwThreadID; // Create two event objects for (i = 0; i < 2; i++) { ghEvents[i] = CreateEvent( NULL, // default security attributes FALSE, // auto-reset event object FALSE, // initial state is nonsignaled NULL); // unnamed object if (ghEvents[i] == NULL) { print_last_error(_T("CreateEvent")); return TRUE; } } dwEvent = WaitForMultipleObjects( 2, // number of objects in array ghEvents, // array of objects FALSE, // wait for any object delayInMillis); // delay in milliseconds return FALSE; } BOOL timing_sleep_loop (UINT delayInMillis) { /* This trick is about performing a low number of seconds to sleep but in a loop, the reason behind that sandboxes tries to avoid patching such sleeps because it could lead to race conditions and also because it is just negliable. However, when you do it in a loop, you can make it efficiant to cuz the sandboxe to reach its timeout. */ int delayInMillis_divided = delayInMillis / 1000; /* Example: we want to sleep 300 seeconds, then we can sleep 0.3s for 1000 times which is like: 300 seconds = 5 minues */ for (int i = 0; i < 1000; i++) { Sleep(delayInMillis_divided); } // Malicious code goes here return FALSE; } /* RDSTC is a famous x86 instruction to count the number of cycle since reset. This can be used to detect the VM. Thanks to Forcepoint for blog article. */ #define LODWORD(_qw) ((DWORD)(_qw)) BOOL rdtsc_diff_locky() { ULONGLONG tsc1; ULONGLONG tsc2; ULONGLONG tsc3; DWORD i = 0; // Try this 10 times in case of small fluctuations for (i = 0; i < 10; i++) { tsc1 = __rdtsc(); // Waste some cycles - should be faster than CloseHandle on bare metal GetProcessHeap(); tsc2 = __rdtsc(); // Waste some cycles - slightly longer than GetProcessHeap() on bare metal CloseHandle(0); tsc3 = __rdtsc(); // Did it take at least 10 times more CPU cycles to perform CloseHandle than it took to perform GetProcessHeap()? if ((LODWORD(tsc3) - LODWORD(tsc2)) / (LODWORD(tsc2) - LODWORD(tsc1)) >= 10) return FALSE; } // We consistently saw a small ratio of difference between GetProcessHeap and CloseHandle execution times // so we're probably in a VM! return TRUE; } /* CPUID is an instruction which cauz a VM Exit to the VMM, this little overhead can show the presence of a hypervisor */ BOOL rdtsc_diff_vmexit() { ULONGLONG tsc1 = 0; ULONGLONG tsc2 = 0; ULONGLONG avg = 0; INT cpuInfo[4] = {}; // Try this 10 times in case of small fluctuations for (INT i = 0; i < 10; i++) { tsc1 = __rdtsc(); __cpuid(cpuInfo, 0); tsc2 = __rdtsc(); // Get the delta of the two RDTSC avg += (tsc2 - tsc1); } // We repeated the process 10 times so we make sure our check is as much reliable as we can avg = avg / 10; return (avg < 1000 && avg > 0) ? FALSE : TRUE; } /* Another timinig attack using the API IcmpSendEcho which takes a TimeOut in milliseconds as a parameter, to wait for IPv4 ICMP packets replies. First time observed: http://blog.talosintelligence.com/2017/09/avast-distributes-malware.html */ BOOL timing_IcmpSendEcho(UINT delayInMillis) { HANDLE hIcmpFile; unsigned long DestinationAddress = INADDR_NONE; char SendData[32] = "Data Buffer"; LPVOID ReplyBuffer = NULL; DWORD ReplySize = 0; const char ipaddr[] = "224.0.0.0"; hIcmpFile = IcmpCreateFile(); if (hIcmpFile == INVALID_HANDLE_VALUE) { printf("\tUnable to open handle.\n"); printf("IcmpCreatefile returned error: %u\n", GetLastError()); return TRUE; } // // Size of ICMP_ECHO_REPLY + size of send data + 8 extra bytes for ICMP error message // ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData) + 8; ReplyBuffer = (VOID*)malloc(ReplySize); if (ReplyBuffer == NULL) { IcmpCloseHandle(hIcmpFile); printf("\tUnable to allocate memory\n"); return TRUE; } IcmpSendEcho(hIcmpFile, DestinationAddress, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, delayInMillis); IcmpCloseHandle(hIcmpFile); free(ReplyBuffer); return FALSE; } /* Timing attack using waitable timers. Test fails if any of the calls return an error state. */ BOOL timing_CreateWaitableTimer(UINT delayInMillis) { HANDLE hTimer; LARGE_INTEGER dueTime; BOOL bResult = FALSE; dueTime.QuadPart = delayInMillis * -10000LL; hTimer = CreateWaitableTimer(NULL, TRUE, NULL); if (hTimer == NULL) { return TRUE; } if (SetWaitableTimer(hTimer, &dueTime, 0, NULL, NULL, FALSE) == FALSE) { bResult = TRUE; } else { if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0) { bResult = TRUE; } } CancelWaitableTimer(hTimer); CloseHandle(hTimer); return bResult; } HANDLE g_hEventCTQT = NULL; /* Timing attack using CreateTimerQueueTimer. Test fails if any of the calls return an error state. */ BOOL timing_CreateTimerQueueTimer(UINT delayInMillis) { HANDLE hTimerQueue; HANDLE hTimerQueueTimer = NULL; BOOL bResult = FALSE; g_hEventCTQT = CreateEvent(NULL, FALSE, FALSE, NULL); if (g_hEventCTQT == NULL) return FALSE; hTimerQueue = CreateTimerQueue(); if (hTimerQueue == NULL) { return TRUE; } if (CreateTimerQueueTimer( &hTimerQueueTimer, hTimerQueue, &CallbackCTQT, reinterpret_cast<PVOID>(0xDEADBEEFULL), delayInMillis, 0, WT_EXECUTEDEFAULT) == FALSE) { bResult = TRUE; } else { // idea here is to wait only 10x the expected delay time // if the wait expires before the timer comes back, we fail the test if (WaitForSingleObject(g_hEventCTQT, delayInMillis * 10) != WAIT_OBJECT_0) { bResult = FALSE; } } // Delete all timers in the timer queue. DeleteTimerQueueEx(hTimerQueue, NULL); CloseHandle(g_hEventCTQT); return bResult; } VOID CALLBACK CallbackCTQT(PVOID lParam, BOOLEAN TimerOrWaitFired) { if (TimerOrWaitFired == TRUE && lParam == reinterpret_cast<PVOID>(0xDEADBEEFULL)) { SetEvent(g_hEventCTQT); } }
8,583
C++
.cpp
293
26.931741
118
0.742077
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,014
NtQueryInformationProcess_ProcessDebugPort.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtQueryInformationProcess_ProcessDebugPort.cpp
#include "pch.h" #include "NtQueryInformationProcess_ProcessDebugPort.h" /* Instead of calling CheckRemoteDebuggerPresent an individual could also make directly the call to NtQueryInformationProcess process theirself. */ BOOL NtQueryInformationProcess_ProcessDebugPort () { auto NtQueryInfoProcess = static_cast<pNtQueryInformationProcess>(API::GetAPI(API_IDENTIFIER::API_NtQueryInformationProcess)); // ProcessDebugPort const int ProcessDbgPort = 7; // Other Vars NTSTATUS Status; #if defined (ENV64BIT) DWORD dProcessInformationLength = sizeof(ULONG) * 2; DWORD64 IsRemotePresent = 0; #elif defined(ENV32BIT) DWORD dProcessInformationLength = sizeof(ULONG); DWORD32 IsRemotePresent = 0; #endif Status = NtQueryInfoProcess(GetCurrentProcess(), ProcessDbgPort, &IsRemotePresent, dProcessInformationLength, NULL); if(Status == 0x00000000 && IsRemotePresent != 0) return TRUE; else return FALSE; }
926
C++
.cpp
26
33.461538
127
0.81982
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,015
SharedUserData_KernelDebugger.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/SharedUserData_KernelDebugger.cpp
#include "pch.h" #include "SharedUserData_KernelDebugger.h" /* NtQuerySystemInformation can be used to detect the presence of a kernel debugger. However, the same information can be obtained from user mode with no system calls at all. This is done by reading from the KUSER_SHARED_DATA struct, which is has a fixed user mode address of 0x7FFE0000 in all versions of Windows in both 32 and 64 bit. In kernel mode it is located at 0xFFDF0000 (32 bit) or 0xFFFFF78000000000 (64 bit). Detailed information about KUSER_SHARED_DATA can be found here: http://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kuser_shared_data.htm */ BOOL SharedUserData_KernelDebugger() { // The fixed user mode address of KUSER_SHARED_DATA const ULONG_PTR UserSharedData = 0x7FFE0000; // UserSharedData->KdDebuggerEnabled is a BOOLEAN according to ntddk.h, which gives the false impression that it is // either true or false. However, this field is actually a set of bit flags, and is only zero if no debugger is present. const UCHAR KdDebuggerEnabledByte = *(UCHAR*)(UserSharedData + 0x2D4); // 0x2D4 = the offset of the field // Extract the flags. // The meaning of these is the same as in NtQuerySystemInformation(SystemKernelDebuggerInformation). // Normally if a debugger is attached, KdDebuggerEnabled is true, KdDebuggerNotPresent is false and the byte is 0x3. const BOOLEAN KdDebuggerEnabled = (KdDebuggerEnabledByte & 0x1) == 0x1; const BOOLEAN KdDebuggerNotPresent = (KdDebuggerEnabledByte & 0x2) == 0; if (KdDebuggerEnabled || !KdDebuggerNotPresent) return TRUE; return FALSE; }
1,597
C++
.cpp
25
62.04
150
0.796166
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,017
SeDebugPrivilege.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/SeDebugPrivilege.cpp
#include "pch.h" #include "SeDebugPrivilege.h" /* If we're being debugged and the process has SeDebugPrivileges privileges then OpenProcess call will be successful. This requires administrator privilege ! In Windows XP, Vista and 7, calling OpenProcess with PROCESS_ALL_ACCESS will fait even with SeDebugPrivilege enabled, That's why I used PROCESS_QUERY_LIMITED_INFORMATION */ DWORD GetCsrssProcessId() { if (API::IsAvailable(API_IDENTIFIER::API_CsrGetProcessId)) { auto CsrGetProcessId = static_cast<pCsrGetId>(API::GetAPI(API_IDENTIFIER::API_CsrGetProcessId)); return CsrGetProcessId(); } else return GetProcessIdFromName(_T("csrss.exe")); } BOOL CanOpenCsrss() { HANDLE hCsrss = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, GetCsrssProcessId()); if (hCsrss != NULL) { CloseHandle(hCsrss); return TRUE; } else return FALSE; }
868
C++
.cpp
29
27.896552
117
0.790865
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,018
NtQuerySystemInformation_SystemKernelDebuggerInformation.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtQuerySystemInformation_SystemKernelDebuggerInformation.cpp
#include "pch.h" #include "NtQuerySystemInformation_SystemKernelDebuggerInformation.h" /* When NtQuerySystemInformation is called with the SystemKernelDebuggerInformation class, the function will return a SYSTEM_KERNEL_DEBUGGER_INFORMATION struct which will reveal the presence of a kernel debugger. */ BOOL NtQuerySystemInformation_SystemKernelDebuggerInformation() { // SystemKernelDebuggerInformation const int SystemKernelDebuggerInformation = 0x23; // The debugger information struct SYSTEM_KERNEL_DEBUGGER_INFORMATION KdDebuggerInfo; auto NtQuerySystemInformation = static_cast<pNtQuerySystemInformation>(API::GetAPI(API_IDENTIFIER::API_NtQuerySystemInformation)); // Call NtQuerySystemInformation NTSTATUS Status = NtQuerySystemInformation(SystemKernelDebuggerInformation, &KdDebuggerInfo, sizeof(SYSTEM_KERNEL_DEBUGGER_INFORMATION), NULL); if (Status >= 0) { // KernelDebuggerEnabled almost always implies !KernelDebuggerNotPresent. KernelDebuggerNotPresent can sometimes // change if the debugger is temporarily disconnected, but either of these means a debugger is enabled. if (KdDebuggerInfo.KernelDebuggerEnabled || !KdDebuggerInfo.KernelDebuggerNotPresent) return TRUE; } return FALSE; }
1,230
C++
.cpp
24
49.041667
144
0.844167
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,019
TrapFlag.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/TrapFlag.cpp
#include "pch.h" #include "TrapFlag.h" /* This technique is similar to exceptions based debugger detections. You enable the trap flag in the current process and check whether an exception is raised or not. If an exception is not raised, you can assume that a debugger has “swallowed” the exception for us, and that the program is being traced. The beauty of this approach is that it detects every debugger, user mode or kernel mode, because they all use the trap flag for tracing a program. Vectored Exception Handling is used here because SEH is an anti-debug trick in itself. */ static BOOL SwallowedException = TRUE; static LONG CALLBACK VectoredHandler( _In_ PEXCEPTION_POINTERS ExceptionInfo ) { SwallowedException = FALSE; if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) return EXCEPTION_CONTINUE_EXECUTION; return EXCEPTION_CONTINUE_SEARCH; } BOOL TrapFlag() { PVOID Handle = AddVectoredExceptionHandler(1, VectoredHandler); SwallowedException = TRUE; #ifdef _WIN64 UINT64 eflags = __readeflags(); #else UINT eflags = __readeflags(); #endif // Set the trap flag eflags |= 0x100; __writeeflags(eflags); RemoveVectoredExceptionHandler(Handle); return SwallowedException; }
1,251
C++
.cpp
38
30.763158
76
0.798826
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,020
PageExceptionBreakpointCheck.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/PageExceptionBreakpointCheck.cpp
#include "pch.h" #ifdef _DEBUG #define OutputDebugStringDbgOnly(S) OutputDebugString(S) #else #define OutputDebugStringDbgOnly(S) do {} while(0); #endif std::vector<PVOID> executablePages = {}; void PageExceptionInitialEnum() { SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); size_t pageSize = sysInfo.dwPageSize; HMODULE hMainModule; MODULEINFO moduleInfo; MEMORY_BASIC_INFORMATION memInfo = { 0 }; // Get the main module handle from an address stored within it (pointer to this method) if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)PageExceptionBreakpointCheck, &hMainModule)) { // Get information about the main module (we want to know the size of it) if (GetModuleInformation(GetCurrentProcess(), hMainModule, &moduleInfo, sizeof(MODULEINFO))) { // cast the module to a pointer unsigned char* module = static_cast<unsigned char*>(moduleInfo.lpBaseOfDll); for (size_t ofs = 0; ofs < moduleInfo.SizeOfImage; ofs += pageSize) { if (VirtualQuery(module + ofs, &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) >= sizeof(MEMORY_BASIC_INFORMATION)) { if ((memInfo.Protect & PAGE_EXECUTE) == PAGE_EXECUTE || (memInfo.Protect & PAGE_EXECUTE_READ) == PAGE_EXECUTE_READ || (memInfo.Protect & PAGE_EXECUTE_WRITECOPY) == PAGE_EXECUTE_WRITECOPY || (memInfo.Protect & PAGE_EXECUTE_READWRITE) == PAGE_EXECUTE_READWRITE) { executablePages.push_back(module + ofs); } } } } } } BOOL PageExceptionBreakpointCheck() { SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); size_t pageSize = sysInfo.dwPageSize; HMODULE hMainModule; MODULEINFO moduleInfo; MEMORY_BASIC_INFORMATION memInfo = { 0 }; wchar_t buffer[512]; // first we check if any of the pages are executable+guard or noaccess // Get the main module handle from an address stored within it (pointer to this method) if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)PageExceptionBreakpointCheck, &hMainModule)) { // Get information about the main module (we want to know the size of it) if (GetModuleInformation(GetCurrentProcess(), hMainModule, &moduleInfo, sizeof(MODULEINFO))) { // cast the module to a pointer unsigned char* module = static_cast<unsigned char*>(moduleInfo.lpBaseOfDll); for (size_t ofs = 0; ofs < moduleInfo.SizeOfImage; ofs += pageSize) { SecureZeroMemory(buffer, 512); wsprintf(buffer, L"Scanning %p... ", module + ofs); OutputDebugStringDbgOnly(buffer); if (VirtualQuery(module + ofs, &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) >= sizeof(MEMORY_BASIC_INFORMATION)) { if (memInfo.AllocationProtect == 0) OutputDebugStringDbgOnly(L"^ AllocationProtect is zero. Potential shenanigans."); if (memInfo.Protect == 0) OutputDebugStringDbgOnly(L"^ Protect is zero. Potential shenanigans."); if ((memInfo.Protect & PAGE_EXECUTE) == PAGE_EXECUTE || (memInfo.Protect & PAGE_EXECUTE_READ) == PAGE_EXECUTE_READ || (memInfo.Protect & PAGE_EXECUTE_WRITECOPY) == PAGE_EXECUTE_WRITECOPY || (memInfo.Protect & PAGE_EXECUTE_READWRITE) == PAGE_EXECUTE_READWRITE) { // this is an executable page OutputDebugStringDbgOnly(L"^ is executable."); if ((memInfo.Protect & PAGE_GUARD) == PAGE_GUARD || (memInfo.AllocationProtect & PAGE_GUARD) == PAGE_GUARD) { // this is an executable guard page, page exception debugging detected OutputDebugStringDbgOnly(L"^ is guard page !!!!!!"); return TRUE; } } if ((memInfo.Protect & PAGE_NOACCESS) == PAGE_NOACCESS) { // this is a NOACCESS page, which shouldn't exist here (alternative way to set page exception BPs) OutputDebugStringDbgOnly(L"^ is NOACCESS !!!!!!!"); return TRUE; } } else OutputDebugStringDbgOnly(L"^ FAILED!"); } } OutputDebugStringDbgOnly(L"Moving on to delta check..."); for (PVOID page : executablePages) { SecureZeroMemory(buffer, 512); wsprintf(buffer, L"Scanning delta for %p... ", page); OutputDebugStringDbgOnly(buffer); if (VirtualQuery(page, &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) >= sizeof(MEMORY_BASIC_INFORMATION)) { if (memInfo.AllocationProtect == 0) OutputDebugStringDbgOnly(L"^ AllocationProtect is zero. Potential shenanigans."); if (memInfo.Protect == 0) OutputDebugStringDbgOnly(L"^ Protect is zero. Potential shenanigans."); if (!((memInfo.Protect & PAGE_EXECUTE) == PAGE_EXECUTE || (memInfo.Protect & PAGE_EXECUTE_READ) == PAGE_EXECUTE_READ || (memInfo.Protect & PAGE_EXECUTE_WRITECOPY) == PAGE_EXECUTE_WRITECOPY || (memInfo.Protect & PAGE_EXECUTE_READWRITE) == PAGE_EXECUTE_READWRITE)) { // page was executable, now isn't! OutputDebugStringDbgOnly(L"^ was executable, now isn't !!!!!!"); return TRUE; } } } } return FALSE; }
4,884
C++
.cpp
119
36.689076
116
0.710282
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,021
CloseHandle_InvalidHandle.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/CloseHandle_InvalidHandle.cpp
#include "pch.h" /* APIs making use of the ZwClose syscall (such as CloseHandle, indirectly) can be used to detect a debugger. When a process is debugged, calling ZwClose with an invalid handle will generate a STATUS_INVALID_HANDLE (0xC0000008) exception. As with all anti-debugs that rely on information made directly available. */ BOOL NtClose_InvalideHandle() { auto NtClose_ = static_cast<pNtClose>(API::GetAPI(API_IDENTIFIER::API_NtClose)); __try { NtClose_(reinterpret_cast<HANDLE>(0x99999999ULL)); } __except (EXCEPTION_EXECUTE_HANDLER) { return TRUE; } return FALSE; } BOOL CloseHandle_InvalideHandle() { // Let's try first with user mode API: CloseHandle __try { CloseHandle(reinterpret_cast<HANDLE>(0x99999999ULL)); } __except (EXCEPTION_EXECUTE_HANDLER) { return TRUE; } // Direct call to NtClose to bypass user mode hooks if (NtClose_InvalideHandle()) return TRUE; else return FALSE; }
942
C++
.cpp
33
26.212121
85
0.761958
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,022
WriteWatch.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/WriteWatch.cpp
#include "pch.h" #include "WriteWatch.h" /* * This check uses the MEM_WRITE_WATCH feature of VirtualAlloc to test for additional memory writes by debuggers, sandboxing, etc. * There are a few ways that we can exploit this: * (1) Allocate a buffer, write it once, get the count, see if it's >1 * (2) Allocate a buffer, pass it to an API where we know the buffer isn't touched (e.g. call with invalid parameter) and see if the count is >0 * (3) Allocate a buffer, use it to store a result of a call we care about (e.g. IsDebuggerPresent) and see if the memory was hit exactly once * (4) Allocate an executable buffer, copy a debug check routine to it, run the check, see if any writes were performed after ours. * * Reference: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366887.aspx * GetWriteWatch: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366573.aspx * */ BOOL VirtualAlloc_WriteWatch_BufferOnly() { ULONG_PTR hitCount; DWORD granularity; BOOL result = FALSE; PVOID* addresses = static_cast<PVOID*>(VirtualAlloc(NULL, 4096 * sizeof(PVOID), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (addresses == NULL) { printf("VirtualAlloc failed. Last error: %u\n", GetLastError()); return result; } int* buffer = static_cast<int*>(VirtualAlloc(NULL, 4096 * 4096, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)); if (buffer == NULL) { VirtualFree(addresses, 0, MEM_RELEASE); printf("VirtualAlloc failed. Last error: %u\n", GetLastError()); return result; } // read the buffer once buffer[0] = 1234; hitCount = 4096; if (GetWriteWatch(0, buffer, 4096, addresses, &hitCount, &granularity) != 0) { printf("GetWriteWatch failed. Last error: %u\n", GetLastError()); result = FALSE; } else { // should only have one read here result = hitCount != 1; } VirtualFree(addresses, 0, MEM_RELEASE); VirtualFree(buffer, 0, MEM_RELEASE); return result; } BOOL VirtualAlloc_WriteWatch_APICalls() { ULONG_PTR hitCount; DWORD granularity; BOOL result = FALSE, error = FALSE; PVOID* addresses = static_cast<PVOID*>(VirtualAlloc(NULL, 4096 * sizeof(PVOID), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (addresses == NULL) { printf("VirtualAlloc failed. Last error: %u\n", GetLastError()); return result; } int* buffer = static_cast<int*>(VirtualAlloc(NULL, 4096 * 4096, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)); if (buffer == NULL) { VirtualFree(addresses, 0, MEM_RELEASE); printf("VirtualAlloc failed. Last error: %u\n", GetLastError()); return result; } // make a bunch of calls where buffer *can* be written to, but isn't actually touched due to invalid parameters. // this can catch out API hooks whose return-by-parameter behaviour is different to that of regular APIs if (GlobalGetAtomName(INVALID_ATOM, (LPTSTR)buffer, 1) != FALSE) { printf("GlobalGetAtomName succeeded when it should've failed... not sure what happened!\n"); result = FALSE; error = TRUE; } if (GetEnvironmentVariable(L"%ThisIsAnInvalidEnvironmentVariableName?[]<>@\\;*!-{}#:/~%", (LPWSTR)buffer, 4096*4096) != FALSE) { printf("GetEnvironmentVariable succeeded when it should've failed... not sure what happened!\n"); result = FALSE; error = TRUE; } if (GetBinaryType(L"%ThisIsAnInvalidFileName?[]<>@\\;*!-{}#:/~%", (LPDWORD)buffer) != FALSE) { printf("GetBinaryType succeeded when it should've failed... not sure what happened!\n"); result = FALSE; error = TRUE; } if (HeapQueryInformation(0, (HEAP_INFORMATION_CLASS)69, buffer, 4096, NULL) != FALSE) { printf("HeapQueryInformation succeeded when it should've failed... not sure what happened!\n"); result = FALSE; error = TRUE; } if (ReadProcessMemory(INVALID_HANDLE_VALUE, (LPCVOID)0x69696969, buffer, 4096, NULL) != FALSE) { printf("ReadProcessMemory succeeded when it should've failed... not sure what happened!\n"); result = FALSE; error = TRUE; } if (GetThreadContext(INVALID_HANDLE_VALUE, (LPCONTEXT)buffer) != FALSE) { printf("GetThreadContext succeeded when it should've failed... not sure what happened!\n"); result = FALSE; error = TRUE; } if (GetWriteWatch(0, &VirtualAlloc_WriteWatch_APICalls, 0, NULL, NULL, (PULONG)buffer) == 0) { printf("GetWriteWatch succeeded when it should've failed... not sure what happened!\n"); result = FALSE; error = TRUE; } if (error == FALSE) { // APIs failed as they should have! :) hitCount = 4096; if (GetWriteWatch(0, buffer, 4096, addresses, &hitCount, &granularity) != 0) { printf("GetWriteWatch failed. Last error: %u\n", GetLastError()); result = FALSE; } else { // should have zero reads here because GlobalGetAtomName doesn't probe the buffer until other checks have succeeded // if there's an API hook or debugger in here it'll probably try to probe the buffer, which will be caught here result = hitCount != 0; } } else { printf("Write watch API check skipped, ignore the result as it is inconclusive.\n"); } VirtualFree(addresses, 0, MEM_RELEASE); VirtualFree(buffer, 0, MEM_RELEASE); return result; } BOOL VirtualAlloc_WriteWatch_IsDebuggerPresent() { ULONG_PTR hitCount; DWORD granularity; BOOL result = FALSE; PVOID* addresses = static_cast<PVOID*>(VirtualAlloc(NULL, 4096 * sizeof(PVOID), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (addresses == NULL) { printf("VirtualAlloc failed. Last error: %u\n", GetLastError()); return result; } int* buffer = static_cast<int*>(VirtualAlloc(NULL, 4096 * 4096, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)); if (buffer == NULL) { VirtualFree(addresses, 0, MEM_RELEASE); printf("VirtualAlloc failed. Last error: %u\n", GetLastError()); return result; } buffer[0] = IsDebuggerPresent(); hitCount = 4096; if (GetWriteWatch(0, buffer, 4096, addresses, &hitCount, &granularity) != 0) { printf("GetWriteWatch failed. Last error: %u\n", GetLastError()); result = FALSE; } else { // should only have one write here result = (hitCount != 1) | (buffer[0] == TRUE); } VirtualFree(addresses, 0, MEM_RELEASE); VirtualFree(buffer, 0, MEM_RELEASE); return result; } BOOL VirtualAlloc_WriteWatch_CodeWrite() { ULONG_PTR hitCount; DWORD granularity; BOOL result = FALSE; PVOID* addresses = static_cast<PVOID*>(VirtualAlloc(NULL, 4096 * sizeof(PVOID), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (addresses == NULL) { printf("VirtualAlloc failed. Last error: %u\n", GetLastError()); return result; } byte* buffer = static_cast<byte*>(VirtualAlloc(NULL, 4096 * 4096, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_EXECUTE_READWRITE)); if (buffer == NULL) { VirtualFree(addresses, 0, MEM_RELEASE); printf("VirtualAlloc failed. Last error: %u\n", GetLastError()); return result; } // construct a call to isDebuggerPresent in assembly ULONG_PTR isDebuggerPresentAddr = (ULONG_PTR)&IsDebuggerPresent; #ifndef _WIN32 #ifndef _WIN64 #error Architecture must be WIN32 or WIN64 #endif #endif #if _WIN64 /* * 64-bit * 0: 51 push rcx 1: 48 b9 ef cd ab 90 78 56 34 12 movabs rcx, 0x1234567890abcdef b: ff d1 call rcx d: 59 pop rcx e: c3 ret */ int pos = 0; buffer[pos++] = 0x51; // push rcx buffer[pos++] = 0x48; // movabs rcx, ... buffer[pos++] = 0xB9; // ^ ... int offset = 0; for (int n = 0; n < 8; n++) { buffer[pos++] = (isDebuggerPresentAddr >> offset) & 0xFF; offset += 8; } buffer[pos++] = 0xFF; // call rcx buffer[pos++] = 0xD1; // ^ buffer[pos++] = 0x59; // pop rcx buffer[pos ] = 0xC3; // ret #else /* * 32-bit * 0: 51 push ecx 1: b9 78 56 34 12 mov ecx, 0x12345678 6: ff d1 call ecx 8: 59 pop ecx 9: c3 ret */ int pos = 0; buffer[pos++] = 0x51; // push ecx buffer[pos++] = 0xB9; // mov ecx, ... int offset = 0; for (int n = 0; n < 4; n++) { buffer[pos++] = (isDebuggerPresentAddr >> offset) & 0xFF; offset += 8; } buffer[pos++] = 0xFF; // call ecx buffer[pos++] = 0xD1; // ^ buffer[pos++] = 0x59; // pop ecx buffer[pos] = 0xC3; // ret #endif ResetWriteWatch(buffer, 4096 * 4096); // cool, now exec the code BOOL(*foo)(VOID) = (BOOL(*)(VOID))buffer; if (foo() == TRUE) { result = TRUE; } if (result == FALSE) { hitCount = 4096; if (GetWriteWatch(0, buffer, 4096, addresses, &hitCount, &granularity) != 0) { printf("GetWriteWatch failed. Last error: %u\n", GetLastError()); result = FALSE; } else { result = hitCount != 0; } } VirtualFree(addresses, 0, MEM_RELEASE); VirtualFree(buffer, 0, MEM_RELEASE); return result; }
8,803
C++
.cpp
258
31.662791
145
0.683561
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,023
ParentProcess.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/ParentProcess.cpp
#include "pch.h" #include "ParentProcess.h" #define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING #include <experimental/filesystem> DWORD GetExplorerPIDbyShellWindow() { DWORD dwProcessId = 0; // Get the PID of explorer by its windows handle GetWindowThreadProcessId(GetShellWindow(), &dwProcessId); return dwProcessId; } DWORD GetParentProcessId() { auto NtQueryInfoProcess = static_cast<pNtQueryInformationProcess>(API::GetAPI(API_IDENTIFIER::API_NtQueryInformationProcess)); NTSTATUS Status = 0; ALK_PROCESS_BASIC_INFORMATION pbi; SecureZeroMemory(&pbi, sizeof(ALK_PROCESS_BASIC_INFORMATION)); const UINT ProcessBasicInformation = 0; Status = NtQueryInfoProcess(GetCurrentProcess(), ProcessBasicInformation, (PVOID)&pbi, sizeof(ALK_PROCESS_BASIC_INFORMATION), 0); if (Status != 0) { return 0; } else { return (DWORD)pbi.ParentProcessId; } } BOOL IsParentExplorerExe() { // this check will throw a false positive if you're running an alternative shell. DWORD parentPid = GetParentProcessId(); bool parentPidEqualsExplorerPid = false; if (parentPid > 0) { // first check HANDLE hParent = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, parentPid); if (hParent != INVALID_HANDLE_VALUE) { WCHAR winDir[MAX_PATH]; WCHAR parentProcessPath[MAX_PATH]; if (GetModuleFileNameExW(hParent, NULL, parentProcessPath, MAX_PATH) && GetWindowsDirectory(winDir, MAX_PATH)) { CloseHandle(hParent); // get path to X:\Windows\explorer.exe auto expectedPath = std::experimental::filesystem::path(winDir); expectedPath = expectedPath.append("explorer.exe"); // get path to parent process auto actualPath = std::experimental::filesystem::path(parentProcessPath); // if the paths are equivalent, no detection. return std::experimental::filesystem::equivalent(expectedPath, actualPath) ? FALSE : TRUE; } CloseHandle(hParent); } // if the first check couldn't be completed, fall back to the shell window approach. // this check is less ideal because it throws false positives if you have explorer process isolation enabled (i.e. one process per explorer window) DWORD explorerPid = GetExplorerPIDbyShellWindow(); if (explorerPid > 0) { if (parentPid != explorerPid) { return TRUE; } } } return FALSE; }
2,324
C++
.cpp
67
31.731343
149
0.765074
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,026
ScanForModules.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/ScanForModules.cpp
#include "pch.h" #define NUMCHARS(a) (sizeof(a)/sizeof(*a)) static HRESULT NormalizeNTPathOld(wchar_t* pszPath, size_t nMax) // Normalizes the path returned by GetProcessImageFileName { wchar_t* pszSlash = wcschr(&pszPath[1], '\\'); if (pszSlash) pszSlash = wcschr(pszSlash + 1, '\\'); if (!pszSlash) return E_FAIL; wchar_t cSave = *pszSlash; *pszSlash = 0; wchar_t szNTPath[_MAX_PATH]; wchar_t szDrive[_MAX_PATH] = L"A:"; // We'll need to query the NT device names for the drives to find a match with pszPath for (wchar_t cDrive = 'A'; cDrive < 'Z'; ++cDrive) { szDrive[0] = cDrive; szNTPath[0] = 0; if (0 != QueryDosDevice(szDrive, szNTPath, NUMCHARS(szNTPath)) && 0 == _wcsicmp(szNTPath, pszPath)) { // Match wcscat_s(szDrive, NUMCHARS(szDrive), L"\\"); wcscat_s(szDrive, NUMCHARS(szDrive), pszSlash + 1); wcscpy_s(pszPath, nMax, szDrive); return S_OK; } } *pszSlash = cSave; return E_FAIL; } static HRESULT NormalizeNTPath(TCHAR* pszPath, size_t nMax) // Normalizes the path returned by GetProcessImageFileName { TCHAR* pszSlash = StrChr(&pszPath[1], '\\'); if (pszSlash) pszSlash = StrChr(pszSlash + 1, '\\'); if (!pszSlash) return E_FAIL; TCHAR cSave = *pszSlash; *pszSlash = 0; TCHAR szNTPath[_MAX_PATH]; TCHAR szDrive[_MAX_PATH] = L"A:"; // We'll need to query the NT device names for the drives to find a match with pszPath for (TCHAR cDrive = 'A'; cDrive < 'Z'; ++cDrive) { szDrive[0] = cDrive; szNTPath[0] = 0; if (0 != QueryDosDevice(szDrive, szNTPath, NUMCHARS(szNTPath)) && 0 == StrCmpI(szNTPath, pszPath)) { // Match StringCbCat(szDrive, NUMCHARS(szDrive), _T("\\")); StringCbCat(szDrive, NUMCHARS(szDrive), pszSlash + 1); StringCbCopy(pszPath, nMax, szDrive); return S_OK; } } *pszSlash = cSave; return E_FAIL; } bool IsGlobalizationNls(TCHAR* filename) { // exclude this nls // consider removing this hack with proper implementation of memory scan PCTSTR ret = StrStrI(filename, _T("\\Windows\\Globalization\\Sorting\\SortDefault.nls")); return (ret != NULL); } bool IsBadLibrary(TCHAR* filename, DWORD filenameLength) { TCHAR systemDrive[MAX_PATH]; TCHAR systemDriveDevice[MAX_PATH]; TCHAR systemRootPath[MAX_PATH]; TCHAR exePath[MAX_PATH]; TCHAR normalisedPath[MAX_PATH]; if (IsGlobalizationNls(filename)) return false; StringCbCopy(normalisedPath, MAX_PATH, filename); NormalizeNTPath(normalisedPath, MAX_PATH); size_t normalisedPathLength = 0; StringCbLength(normalisedPath, MAX_PATH, &normalisedPathLength); if (filenameLength == INVALID_FILE_SIZE) { size_t filenameActualLength = 0; StringCbLength(filename, MAX_PATH, &filenameActualLength); filenameLength = (DWORD)filenameActualLength; } GetSystemDirectory(systemRootPath, MAX_PATH); #ifdef _X86_ TCHAR syswow64Path[MAX_PATH]; SHGetFolderPath (NULL, CSIDL_SYSTEMX86, NULL, 0, syswow64Path); StringCbCat(syswow64Path, MAX_PATH, _T("\\")); size_t syswow64PathLength = 0; StringCbLength(syswow64Path, MAX_PATH, &syswow64PathLength); #endif size_t exePathLength = GetProcessImageFileName(GetCurrentProcess(), exePath, MAX_PATH); NormalizeNTPath(exePath, MAX_PATH); StringCbLength(exePath, MAX_PATH, &exePathLength); if (GetEnvironmentVariable(_T("SystemDrive"), systemDrive, MAX_PATH) > 0) { if (QueryDosDeviceW(systemDrive, systemDriveDevice, MAX_PATH) > 0) { StringCbCat(systemDriveDevice, MAX_PATH, _T("\\Windows\\System32\\")); size_t systemDriveDevicelength = 0; StringCbLength(systemDriveDevice, MAX_PATH, &systemDriveDevicelength); //printf("systemDriveDevice: %S (%d)\n", systemDriveDevice, systemDriveDevicelength); if (StrNCmpI(systemDriveDevice, filename, (int)(min(systemDriveDevicelength, filenameLength) / sizeof(TCHAR)) ) == 0) { // path matched the NT file path return false; } StringCbCat(systemRootPath, MAX_PATH, _T("\\")); size_t systemRootPathLength = 0; StringCbLength(systemRootPath, MAX_PATH, &systemRootPathLength); //printf("systemRootPath: %S (%d)\n", systemRootPath, systemRootPathLength); if (StrNCmpI(systemRootPath, normalisedPath, (int)(min(systemRootPathLength, normalisedPathLength) / sizeof(TCHAR)) ) == 0) { // path matched the regular system path return false; } #ifdef _X86_ if (IsWoW64() && StrNCmpI(syswow64Path, normalisedPath, (int)(min(syswow64PathLength, normalisedPathLength) / sizeof(TCHAR)) ) == 0) { // path matched the wow64 system path return false; } #endif if (StrCmpI(exePath, normalisedPath) == 0) { // path matched the executable path return false; } } } return true; } BOOL ScanForModules_EnumProcessModulesEx_Internal(DWORD moduleFlag) { //printf("EnumProcessModulesEx()\n"); HMODULE* moduleList; HMODULE* tmp; DWORD currentSize = 1024 * sizeof(HMODULE); DWORD requiredSize = 0; bool anyBadLibs = false; // the EnumProcessModulesEx API was moved from psapi.dll into kernel32.dll for Windows 7, then back out afterwards. // check for availability of either. if (!API::IsAvailable(API_EnumProcessModulesEx_PSAPI) && !API::IsAvailable(API_EnumProcessModulesEx_Kernel)) { // neither available return FALSE; } // API is available in one of the two libraries, use whichever is available. pEnumProcessModulesEx fnEnumProcessModulesEx; if (API::IsAvailable(API_EnumProcessModulesEx_PSAPI)) { fnEnumProcessModulesEx = static_cast<pEnumProcessModulesEx>(API::GetAPI(API_IDENTIFIER::API_EnumProcessModulesEx_PSAPI)); } else { fnEnumProcessModulesEx = static_cast<pEnumProcessModulesEx>(API::GetAPI(API_IDENTIFIER::API_EnumProcessModulesEx_Kernel)); } moduleList = static_cast<HMODULE*>(calloc(1024, sizeof(HMODULE))); if (moduleList) { if (fnEnumProcessModulesEx(GetCurrentProcess(), moduleList, currentSize, &requiredSize, moduleFlag)) { bool success = true; if (requiredSize > currentSize) { currentSize = requiredSize; tmp = static_cast<HMODULE*>(realloc(moduleList, currentSize)); if (tmp) { moduleList = tmp; if (fnEnumProcessModulesEx(GetCurrentProcess(), moduleList, currentSize, &requiredSize, moduleFlag) == FALSE) { success = false; } } else { success = false; //realloc failed } } if (success) { DWORD count = requiredSize / sizeof(HMODULE); TCHAR moduleName[MAX_PATH]; for (DWORD i = 0; i < count; i++) { DWORD len; if ((len = GetModuleFileNameEx(GetCurrentProcess(), moduleList[i], moduleName, MAX_PATH)) > 0) { bool isBad = IsBadLibrary(moduleName, len); if (isBad) printf(" [!] Injected library: %S\n", moduleName); anyBadLibs |= isBad; } } } } free(moduleList); } return anyBadLibs ? TRUE : FALSE; } BOOL ScanForModules_EnumProcessModulesEx_32bit() { return ScanForModules_EnumProcessModulesEx_Internal(LIST_MODULES_32BIT); } BOOL ScanForModules_EnumProcessModulesEx_64bit() { return ScanForModules_EnumProcessModulesEx_Internal(LIST_MODULES_64BIT); } BOOL ScanForModules_EnumProcessModulesEx_All() { return ScanForModules_EnumProcessModulesEx_Internal(LIST_MODULES_ALL); } BOOL ScanForModules_MemoryWalk_GMI() { // TODO: Convert this to the new enumerate_memory() API for speed! MEMORY_BASIC_INFORMATION memInfo = { 0 }; HMODULE moduleHandle = 0; TCHAR moduleName[MAX_PATH]; MODULEINFO moduleInfo = { 0 }; auto memoryRegions = enumerate_memory(); bool anyBadLibs = false; for (PMEMORY_BASIC_INFORMATION region : *memoryRegions) { if (region->State == MEM_FREE) { delete region; continue; } PBYTE addr = static_cast<PBYTE>(region->BaseAddress); PBYTE regionEnd = addr + region->RegionSize; //printf("Scanning %p - %p ...\n", addr, regionEnd); while(addr < regionEnd) { bool skippedForward = false; if (VirtualQuery(addr, &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) >= sizeof(MEMORY_BASIC_INFORMATION)) { if (memInfo.State != MEM_FREE) { if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (TCHAR*)addr, &moduleHandle)) { SecureZeroMemory(moduleName, MAX_PATH * sizeof(TCHAR)); DWORD len = GetModuleFileName(moduleHandle, moduleName, MAX_PATH); //printf(" [!] %p: %S\n", addr, moduleName); bool isBad = IsBadLibrary(moduleName, len); if (isBad) printf(" [!] Injected library: %S\n", moduleName); anyBadLibs |= isBad; if (GetModuleInformation(GetCurrentProcess(), moduleHandle, &moduleInfo, sizeof(MODULEINFO))) { size_t moduleSizeRoundedUp = (moduleInfo.SizeOfImage + 1); moduleSizeRoundedUp += 4096 - (moduleSizeRoundedUp % 4096); PBYTE nextPos = static_cast<PBYTE>(moduleInfo.lpBaseOfDll) + moduleSizeRoundedUp; if (nextPos > addr) { //printf(" -> Moving from %x to %x\n", addr, nextPos); addr = nextPos; skippedForward = true; } } } } } if (!skippedForward) addr += 4096; } delete region; } delete memoryRegions; return anyBadLibs ? TRUE : FALSE; } BOOL ScanForModules_MemoryWalk_Hidden() { HMODULE moduleHandle = 0; TCHAR moduleName[MAX_PATH]; auto memoryRegions = enumerate_memory(); bool anyBadLibs = false; bool firstPrint = true; for (PMEMORY_BASIC_INFORMATION region : *memoryRegions) { if (region->State == MEM_FREE) { delete region; continue; } PBYTE addr = static_cast<PBYTE>(region->BaseAddress); PBYTE regionEnd = addr + region->RegionSize; //printf("Scanning %p - %p ...\n", addr, regionEnd); while (addr < regionEnd) { bool skippedForward = false; if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (TCHAR*)addr, &moduleHandle) == FALSE) { // not a known module if ((region->State & MEM_COMMIT) == MEM_COMMIT && ((region->Protect == PAGE_READONLY) || (region->Protect == PAGE_READWRITE) || (region->Protect == PAGE_EXECUTE_READ) || (region->Protect == PAGE_EXECUTE_READWRITE) || (region->Protect == PAGE_EXECUTE_WRITECOPY))) { auto moduleData = static_cast<PBYTE>(region->BaseAddress); if (moduleData[0] == 'M' && moduleData[1] == 'Z') { if (firstPrint) { firstPrint = false; printf("\n\n"); if (IsWoW64()) { printf(" [!] Running on WoW64, there will be false positives due to wow64 DLLs.\n"); } } printf(" [!] Executable at %p\n", region->BaseAddress); anyBadLibs = true; } } } else { MODULEINFO modInfo = { 0 }; if (GetModuleInformation(GetCurrentProcess(), moduleHandle, &modInfo, sizeof(MODULEINFO))) { size_t moduleSizeRoundedUp = (modInfo.SizeOfImage + 1); moduleSizeRoundedUp += 4096 - (moduleSizeRoundedUp % 4096); PBYTE nextPos = static_cast<PBYTE>(modInfo.lpBaseOfDll) + moduleSizeRoundedUp; if (nextPos > addr) { //printf(" -> Moving from %x to %x\n", addr, nextPos); addr = nextPos; skippedForward = true; } } } SecureZeroMemory(moduleName, sizeof(TCHAR)*MAX_PATH); DWORD len; if ((len = GetMappedFileName(GetCurrentProcess(), region->AllocationBase, moduleName, MAX_PATH)) > 0) { bool isBad = IsBadLibrary(moduleName, len); if (isBad) printf(" [!] Injected library: %S\n", moduleName); anyBadLibs |= isBad; // mapped files take up a whole region, so just skip to the end of the region addr = regionEnd; skippedForward = true; } if (!skippedForward) addr += 4096; } delete region; } delete memoryRegions; return anyBadLibs ? TRUE : FALSE; } BOOL ScanForModules_DotNetModuleStructures() { HMODULE moduleHandle = 0; TCHAR moduleName[MAX_PATH]; auto memoryRegions = enumerate_memory(); bool anyBadLibs = false; /* This works because the .NET runtime loads structures into memory that describe modules. This happens even if the module is loaded dynamically, from memory. If al-khaser were a .NET application we'd need to apply some additional checks on the results, but since it isn't then we can just report every .NET module we find. This check is quite effective because it catches pretty much any kind of .NET injection, even if the injector uses tricks like messing with PE headers or patching EWT. */ bool firstPrint = true; for (PMEMORY_BASIC_INFORMATION region : *memoryRegions) { if (region->State == MEM_FREE || region->Type == MEM_MAPPED || region->Type == MEM_IMAGE) { //printf("region %p skipped for being free, mapped, or image.\n", region->BaseAddress); delete region; continue; } if ((region->State & MEM_COMMIT) == MEM_COMMIT && region->Protect == PAGE_READWRITE && region->AllocationProtect == PAGE_READWRITE) { uint64_t* addr = static_cast<uint64_t*>(region->BaseAddress); uint64_t* regionEnd = addr + (region->RegionSize / sizeof(uint64_t)); // check first qword at region base address. should be zero. if (*addr == 0) { // find the pattern of QWORDs we want (0, 0, 0, 0, 0, 0, pointer, length, 1, 2, 0, 2, 0, 2, 0) while (addr < regionEnd - 32) { uint64_t* ptr = addr; bool sixZeroes = true; for (int i = 0; i < 6; i++) { sixZeroes &= *(ptr++) == 0; } if (sixZeroes) { //printf("got six zeroes at %p\n", ptr); uint64_t stringPtrVal = *ptr; PCWSTR stringPtr = reinterpret_cast<PCWSTR>(*ptr); ptr++; uint64_t stringLen = *ptr; ptr++; if (*ptr++ == 1 && *ptr++ == 2 && *ptr++ == 0 && *ptr++ == 2 && *ptr++ == 0 && *ptr++ == 2 && *ptr++ == 0) { // pattern matches, check string addr if ((stringPtrVal & 0xFFFFFFFF00000000ULL) == ((uint64_t)ptr & 0xFFFFFFFF00000000ULL)) { // check string length is sane if (stringLen < MAX_PATH * sizeof(wchar_t)) { // ok, we're sure it's the right structure. report it. if (firstPrint) { printf("\n\n"); } printf(" [!] Found module: %S (structure address %p)\n", stringPtr, stringPtr); anyBadLibs = true; } } } } addr++; } } } delete region; } delete memoryRegions; return anyBadLibs ? TRUE : FALSE; } std::vector<LDR_DATA_TABLE_ENTRY*>* WalkLDR(PPEB_LDR_DATA ldrData) { auto entryList = new std::vector<LDR_DATA_TABLE_ENTRY*>(); LIST_ENTRY* head = ldrData->InMemoryOrderModuleList.Flink; LIST_ENTRY* node = head; do { LDR_DATA_TABLE_ENTRY ldrEntry = { 0 }; LDR_DATA_TABLE_ENTRY* pLdrEntry = CONTAINING_RECORD(node, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks); if (attempt_to_read_memory(pLdrEntry, &ldrEntry, sizeof(ldrEntry))) { entryList->push_back(new LDR_DATA_TABLE_ENTRY(ldrEntry)); node = ldrEntry.InMemoryOrderLinks.Flink; } else { printf(" [!] Error reading entry.\n"); break; } } while (node != head); entryList->pop_back(); return entryList; } std::vector<LDR_DATA_TABLE_ENTRY64*>* WalkLDR(PPEB_LDR_DATA64 ldrData) { auto entryList = new std::vector<LDR_DATA_TABLE_ENTRY64*>(); LIST_ENTRY64 head; if (!attempt_to_read_memory_wow64(&head, sizeof(LIST_ENTRY64), ldrData->InMemoryOrderModuleList.Flink)) { printf(" [!] Error reading list head.\n"); } ULONGLONG nodeAddr = ldrData->InMemoryOrderModuleList.Flink; LIST_ENTRY64 node = head; LDR_DATA_TABLE_ENTRY64 ldrEntry = { 0 }; do { if (attempt_to_read_memory_wow64(&ldrEntry, sizeof(LDR_DATA_TABLE_ENTRY64), nodeAddr - sizeof(LIST_ENTRY64))) { entryList->push_back(new LDR_DATA_TABLE_ENTRY64(ldrEntry)); if (!attempt_to_read_memory_wow64(&node, sizeof(LIST_ENTRY64), ldrEntry.InMemoryOrderLinks.Flink)) { break; } nodeAddr = ldrEntry.InMemoryOrderLinks.Flink; } else { break; } } while (nodeAddr != ldrData->InMemoryOrderModuleList.Flink); entryList->pop_back(); return entryList; } BOOL ScanForModules_LDR_Direct() { PROCESS_BASIC_INFORMATION pbi = { 0 }; THREAD_BASIC_INFORMATION tbi = { 0 }; //printf("MemoryWalk_LDR()\n"); bool anyBadLibs = false; auto NtQueryInformationProcess = static_cast<pNtQueryInformationProcess>(API::GetAPI(API_IDENTIFIER::API_NtQueryInformationProcess)); NTSTATUS status = NtQueryInformationProcess(GetCurrentProcess(), ProcessBasicInformation, &pbi, sizeof(pbi), nullptr); if (status != 0) { printf("Failed to get process information. Status: %d\n", status); } else { if (pbi.PebBaseAddress != nullptr) { PPEB peb = pbi.PebBaseAddress; if (peb->Ldr != nullptr) { PPEB_LDR_DATA ldrData = peb->Ldr; auto ldrEntries = WalkLDR(ldrData); for (LDR_DATA_TABLE_ENTRY* ldrEntry : *ldrEntries) { //printf(" -> %S\n", ldrEntry->FullDllName.Buffer); bool isBad = IsBadLibrary(ldrEntry->FullDllName.Buffer, ldrEntry->FullDllName.Length); if (isBad) printf(" [!] Injected library: %S\n", ldrEntry->FullDllName.Buffer); anyBadLibs |= isBad; delete ldrEntry; } delete ldrEntries; } if (IsWoW64()) { PPEB64 peb64 = reinterpret_cast<PPEB64>(GetPeb64()); PEB_LDR_DATA64 ldrData = { 0 }; if (peb64 && attempt_to_read_memory_wow64(&ldrData, sizeof(PEB_LDR_DATA64), peb64->Ldr)) { auto ldrEntries = WalkLDR(&ldrData); for (LDR_DATA_TABLE_ENTRY64* ldrEntry : *ldrEntries) { WCHAR* dllNameBuffer = new WCHAR[ldrEntry->FullDllName.Length + 1]; SecureZeroMemory(dllNameBuffer, (ldrEntry->FullDllName.Length + 1) * sizeof(WCHAR)); if (attempt_to_read_memory_wow64(dllNameBuffer, ldrEntry->FullDllName.Length * sizeof(WCHAR), ldrEntry->FullDllName.Buffer)) { //printf(" -> %S\n", dllNameBuffer); bool isBad = IsBadLibrary(dllNameBuffer, ldrEntry->FullDllName.Length); if (isBad) printf(" [!] Injected library (WOW64): %S\n", dllNameBuffer); anyBadLibs |= isBad; } else { printf(" [!] Failed to read module name at %llx.\n", reinterpret_cast<ULONGLONG>(ldrEntry->FullDllName.Buffer)); } delete [] dllNameBuffer; delete ldrEntry; } delete ldrEntries; } } } } return anyBadLibs ? TRUE : FALSE; } VOID NTAPI LdrEnumCallback(_In_ PLDR_DATA_TABLE_ENTRY ModuleInformation, _In_ PVOID Parameter, _Out_ BOOLEAN *Stop) { // add ldr entry to table from param auto ldtEntries = static_cast<std::vector<LDR_DATA_TABLE_ENTRY>*>(Parameter); ldtEntries->push_back(LDR_DATA_TABLE_ENTRY(*ModuleInformation)); Stop = FALSE; } BOOL ScanForModules_LdrEnumerateLoadedModules() { if (!API::IsAvailable(API_IDENTIFIER::API_LdrEnumerateLoadedModules)) return FALSE; auto LdrEnumerateLoadedModules = static_cast<pLdrEnumerateLoadedModules>(API::GetAPI(API_IDENTIFIER::API_LdrEnumerateLoadedModules)); auto ldrEntries = new std::vector<LDR_DATA_TABLE_ENTRY>(); NTSTATUS status; if ((status = LdrEnumerateLoadedModules(FALSE, &LdrEnumCallback, ldrEntries)) != 0) { printf("LdrEnumerateLoadedModules failed. Status: %x\n", status); delete ldrEntries; return FALSE; } bool anyBadEntries = false; for (LDR_DATA_TABLE_ENTRY ldrEntry : *ldrEntries) { bool isBad = IsBadLibrary(ldrEntry.FullDllName.Buffer, ldrEntry.FullDllName.Length); anyBadEntries |= isBad; } delete ldrEntries; return anyBadEntries ? TRUE : FALSE; } BOOL ScanForModules_ToolHelp32() { bool anyBadLibs = false; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, GetCurrentProcessId()); //printf("Snapshot: %p\n", snapshot); if (snapshot == INVALID_HANDLE_VALUE) { printf("Failed to get snapshot. Last error: %u\n", GetLastError()); } else { MODULEENTRY32 module = { 0 }; module.dwSize = sizeof(MODULEENTRY32); if (Module32First(snapshot, &module) != FALSE) { do { bool isBad = IsBadLibrary(module.szExePath, INVALID_FILE_SIZE); if (isBad) printf(" [!] Injected library: %S\n", module.szExePath); anyBadLibs |= isBad; //printf(" [!] %S\n", module.szModule); } while (Module32Next(snapshot, &module) != FALSE); } else { printf("Failed to get first module. Last error: %u\n", GetLastError()); } CloseHandle(snapshot); } return anyBadLibs ? TRUE : FALSE; }
20,274
C++
.cpp
608
29.4375
168
0.694574
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,027
NtQueryInformationProcess_ProcessDebugObject.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtQueryInformationProcess_ProcessDebugObject.cpp
#include "pch.h" #include "NtQueryInformationProcess_ProcessDebugObject.h" /* This function uses NtQuerySystemInformation to try to retrieve a handle to the current process's debug object handle. If the function is successful it'll return true which means we're being debugged or it'll return false if it fails the process isn't being debugged */ BOOL NtQueryInformationProcess_ProcessDebugObject() { // ProcessDebugObjectHandle const int ProcessDebugObjectHandle = 0x1e; auto NtQueryInfoProcess = static_cast<pNtQueryInformationProcess>(API::GetAPI(API_IDENTIFIER::API_NtQueryInformationProcess)); // Other Vars NTSTATUS Status; HANDLE hDebugObject = NULL; #if defined (ENV64BIT) DWORD dProcessInformationLength = sizeof(ULONG) * 2; DWORD64 IsRemotePresent = 0; #elif defined(ENV32BIT) DWORD dProcessInformationLength = sizeof(ULONG); DWORD32 IsRemotePresent = 0; #endif // Regular check Status = NtQueryInfoProcess(GetCurrentProcess(), ProcessDebugObjectHandle, &hDebugObject, dProcessInformationLength, NULL); if (Status != STATUS_PORT_NOT_SET) return TRUE; if (hDebugObject != NULL) return TRUE; // Check with overlapping return length and debug object handle buffers to find anti-anti-debuggers Status = NtQueryInfoProcess(GetCurrentProcess(), ProcessDebugObjectHandle, &hDebugObject, dProcessInformationLength, (PULONG)&hDebugObject); if (Status != STATUS_PORT_NOT_SET) return TRUE; if (hDebugObject == NULL) return TRUE; // Handle incorrectly zeroed if ((ULONG)(ULONG_PTR)hDebugObject != dProcessInformationLength) return TRUE; // Return length incorrectly overwritten return FALSE; }
1,634
C++
.cpp
38
40.921053
141
0.810095
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,028
NtQueryObject_ObjectTypeInformation.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtQueryObject_ObjectTypeInformation.cpp
#include "pch.h" #include "NtQueryObject_ObjectInformation.h" /* Windows XP introduced a "debug object". When a debugging session begins, a debug object is created, and a handle is associated with it. Using the ntdll NtQueryObject() function with class: ObjectTypeInformation. ObjectTypeInformation will return the type information of the supplied handle. */ BOOL NtQueryObject_ObjectTypeInformation() { //NOTE this check now only detects if NtQueryObject is hooked to set ObjectInformation->TotalNumberOfObjects = 0 // We have to import the function auto NtQueryObject = static_cast<pNtQueryObject>(API::GetAPI(API_IDENTIFIER::API_NtQueryObject)); auto NtCreateDebugObject = static_cast<pNtCreateDebugObject>(API::GetAPI(API_IDENTIFIER::API_NtCreateDebugObject)); // Some vars HANDLE DebugObjectHandle; OBJECT_ATTRIBUTES ObjectAttributes; InitializeObjectAttributes(&ObjectAttributes, 0, 0, 0, 0); BYTE memory[0x1000] = { 0 }; POBJECT_TYPE_INFORMATION ObjectInformation = (POBJECT_TYPE_INFORMATION)memory; NTSTATUS Status; NtCreateDebugObject(&DebugObjectHandle, DEBUG_ALL_ACCESS, &ObjectAttributes, FALSE); if (API::IsAvailable(API_IDENTIFIER::API_NtQueryObject)) { Status = NtQueryObject(DebugObjectHandle, ObjectTypeInformation, ObjectInformation, sizeof(memory), 0); // Make sure to not screw up later checks CloseHandle(DebugObjectHandle); if (Status >= 0) { if (ObjectInformation->TotalNumberOfObjects == 0) return TRUE; //There should be at least one object (we just created it). else return FALSE; } else { //NOTE: this should actually never happen on a valid handle (so this check can be bypassed by failing NtQueryObject) return FALSE; } } else return FALSE; }
1,747
C++
.cpp
42
38.833333
119
0.787448
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,029
ProcessJob.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/ProcessJob.cpp
#include "pch.h" #include "ProcessJob.h" /* * ProcessJob - Contributed by Graham Sutherland (https://github.com/gsuberland) * * Checks whether the process is part of a job object and, if so, any non-whitelisted processes are part of that job. * * Debuggers and other analysis applications usually place processes inside a job so that child processes will exit * when the parent process exits. * You can observe this with Visual Studio by running al-khaser with Debug -> Start Without Debugging. * */ BOOL ProcessJob() { BOOL foundProblem = FALSE; DWORD jobProcessStructSize = sizeof(JOBOBJECT_BASIC_PROCESS_ID_LIST) + sizeof(ULONG_PTR) * 1024; JOBOBJECT_BASIC_PROCESS_ID_LIST* jobProcessIdList = static_cast<JOBOBJECT_BASIC_PROCESS_ID_LIST*>(malloc(jobProcessStructSize)); if (jobProcessIdList) { SecureZeroMemory(jobProcessIdList, jobProcessStructSize); jobProcessIdList->NumberOfProcessIdsInList = 1024; if (QueryInformationJobObject(NULL, JobObjectBasicProcessIdList, jobProcessIdList, jobProcessStructSize, NULL)) { int ok_processes = 0; for (DWORD i = 0; i < jobProcessIdList->NumberOfAssignedProcesses; i++) { ULONG_PTR processId = jobProcessIdList->ProcessIdList[i]; // is this the current process? if so that's ok if (processId == (ULONG_PTR)GetCurrentProcessId()) { ok_processes++; } else { // find the process name for this job process HANDLE hJobProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)processId); if (hJobProcess != NULL) { const int processNameBufferSize = 4096; LPTSTR processName = static_cast<LPTSTR>(malloc(sizeof(TCHAR) * processNameBufferSize)); if (processName) { SecureZeroMemory(processName, sizeof(TCHAR) * processNameBufferSize); if (GetProcessImageFileName(hJobProcess, processName, processNameBufferSize) > 0) { String pnStr(processName); // ignore conhost.exe (this hosts the al-khaser executable in a console) if (pnStr.find(String(L"\\Windows\\System32\\conhost.exe")) != std::string::npos) { ok_processes++; } } free(processName); } CloseHandle(hJobProcess); } } } // if we found other processes in the job other than the current process and conhost, report a problem foundProblem = ok_processes != jobProcessIdList->NumberOfAssignedProcesses; } free(jobProcessIdList); } return foundProblem; }
2,488
C++
.cpp
63
34.714286
129
0.724481
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,030
IsDebuggerPresent.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/IsDebuggerPresent.cpp
#include "pch.h" #include "IsDebuggerPresent.h" BOOL IsDebuggerPresentAPI ( VOID ) /*++ Routine Description: Calls the IsDebuggerPresent() API. This function is part of the Win32 Debugging API and it returns TRUE if a user mode debugger is present. Internally, it simply returns the value of the PEB->BeingDebugged flag. Arguments: None Return Value: TRUE - if debugger was detected FALSE - otherwise --*/ { return IsDebuggerPresent(); }
455
C++
.cpp
21
19.857143
64
0.791569
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,032
NtSetInformationThread_ThreadHideFromDebugger.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtSetInformationThread_ThreadHideFromDebugger.cpp
#include "pch.h" #include "NtSetInformationThread_ThreadHideFromDebugger.h" /* Calling NtSetInformationThread will attempt with ThreadInformationClass set to x11 (ThreadHideFromDebugger) to hide a thread from the debugger, Passing NULL for hThread will cause the function to hide the thread the function is running in. Also, the function returns false on failure and true on success. When the function is called, the thread will continue to run but a debugger will no longer receive any events related to that thread. These checks also look for hooks on the NtSetInformationThread API that try to block ThreadHideFromDebugger. */ #ifndef STATUS_INFO_LENGTH_MISMATCH #define STATUS_INFO_LENGTH_MISMATCH ((DWORD)0xC0000004L) #endif #ifndef STATUS_DATATYPE_MISALIGNMENT #define STATUS_DATATYPE_MISALIGNMENT ((DWORD)0x80000002L) #endif BOOL NtSetInformationThread_ThreadHideFromDebugger() { // this is needed because the bool data type can be at unaligned memory locations, whereas the NtQueryInformationThread API expects 32-bit aligned pointers. struct AlignedBool { alignas(4) bool Value; }; // ThreadHideFromDebugger const int ThreadHideFromDebugger = 0x11; auto NtSetInformationThread = static_cast<pNtSetInformationThread>(API::GetAPI(API_IDENTIFIER::API_NtSetInformationThread)); auto NtQueryInformationThread = static_cast<pNtQueryInformationThread>(API::GetAPI(API_IDENTIFIER::API_NtQueryInformationThread)); NTSTATUS Status; bool doQITcheck = false; // only do the QueryInformationThread check if we're on Vista and the API is available. // this is because the ThreadHideFromDebugger class can only be queried from Vista onwards. if (API::IsAvailable(API_IDENTIFIER::API_NtQueryInformationThread)) { doQITcheck = IsWindowsVistaOrGreater(); } AlignedBool isThreadHidden; isThreadHidden.Value = false; // First issue a bogus call with an incorrect length parameter. If it succeeds, we know NtSetInformationThread was hooked. Status = NtSetInformationThread(GetCurrentThread(), ThreadHideFromDebugger, &isThreadHidden, 12345); if (Status == 0) return TRUE; // Next try again but give it a bogus thread handle. If it succeeds, again we know NtSetInformationThread was hooked. Status = NtSetInformationThread((HANDLE)0xFFFF, ThreadHideFromDebugger, NULL, 0); if (Status == 0) return TRUE; // Now try a legitimate call. Status = NtSetInformationThread(GetCurrentThread(), ThreadHideFromDebugger, NULL, 0); if (Status == 0) { if (doQITcheck) { // note: the ThreadHideFromDebugger query expects a bool (1 byte), not a BOOL (4 bytes) // if a BOOL is used, the kernel returns 0xC0000004 (STATUS_INFO_LENGTH_MISMATCH) because BOOL is typedef int. // first do a legitimate call. this should succeed or return an error such as access denied. Status = NtQueryInformationThread(GetCurrentThread(), ThreadHideFromDebugger, &isThreadHidden.Value, sizeof(bool), NULL); // this shouldn't happen, because we used the correct length. this will only happen if a buggy hook mistakenly expects a BOOL rather than a bool. if (Status == STATUS_INFO_LENGTH_MISMATCH) { // we found a buggy hook that expects some size other than 1 return TRUE; } // if the legitimate call succeeded, continue with additional bogus API call checks if (Status == 0) { AlignedBool bogusIsThreadHidden; bogusIsThreadHidden.Value = false; // now do a bogus call with the wrong size. this will catch buggy hooks that accept BOOL (4 bytes) or just don't have any size checks Status = NtQueryInformationThread(GetCurrentThread(), ThreadHideFromDebugger, &bogusIsThreadHidden.Value, sizeof(BOOL), NULL); if (Status != STATUS_INFO_LENGTH_MISMATCH) { // we found a buggy hook that allows for incorrect size values return TRUE; } // NtQueryInformationThread explicitly requires the ThreadInformation pointer to be aligned. as such, it should reject unaligned pointers. // hooks are almost certainly guaranteed to not retain this behaviour, so it's a very nice way to catch them out. const size_t UnalignedCheckCount = 8; bool bogusUnalignedValues[UnalignedCheckCount]; int alignmentErrorCount = 0; #if _WIN64 // on 64-bit, up to two elements in the array should be aligned. const size_t MaxAlignmentCheckSuccessCount = 2; #else // on 32-bit, there should be either two or four aligned elements (unsure how WoW64 affects this, so I'm just gonna assume 2 or 4 are ok) const size_t MaxAlignmentCheckSuccessCount = 4; #endif for (size_t i = 0; i < UnalignedCheckCount; i++) { Status = NtQueryInformationThread(GetCurrentThread(), ThreadHideFromDebugger, &(bogusUnalignedValues[i]), sizeof(BOOL), NULL); if (Status == STATUS_DATATYPE_MISALIGNMENT) { alignmentErrorCount++; } } // if there weren't enough alignment errors, we know that the API must be hooked and not checking alignment properly! if (UnalignedCheckCount - MaxAlignmentCheckSuccessCount > alignmentErrorCount) { return TRUE; } // the legitimate call was successful, and the bogus call was unsuccessful, so return false (no detection) if the HideFromDebugger flag was properly set. // if the HideFromDebugger flag was not set, i.e. the NtSetInformationThread call lied to us about being successful, then return true (debugger/hook detected) return isThreadHidden.Value ? FALSE : TRUE; } } } else { // call failed, should've succeeded return TRUE; } // we didn't find any hooks. return FALSE; }
5,571
C++
.cpp
111
46.801802
162
0.772769
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,033
NtYieldExecution.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtYieldExecution.cpp
#include "pch.h" #include "NtYieldExecution.h" /* The ntdll function NtYieldExecution or its kernel32 equivalent SwitchToThread function allows the current thread to offer to give up the rest of its time slice, and allow the next scheduled thread to execute. If no threads are scheduled to execute (or when the system is busy in particular ways and will not allow a switch to occur), then the ntdll NtYieldExecution() function returns the STATUS_NO_YIELD_PERFORMED (0x40000024) status, which causes the kernel32 SwitchToThread() function to return a zero. When an application is being debugged, the act of single-stepping through the code causes debug events and often results in no yield being allowed. However, this is a hopelessly unreliable method for detecting a debugger because it will also detect the presence of a thread that is running with high priority. */ BOOL NtYieldExecutionAPI() { //NOTE: this check is unreliable, don't actually use this in a real environment auto NtYieldExecution = static_cast<pNtYieldExecution>(API::GetAPI(API_IDENTIFIER::API_NtYieldExecution)); INT iDebugged = 0; for (int i = 0; i < 0x20; i++) { Sleep(0xf); if (NtYieldExecution() != STATUS_NO_YIELD_PERFORMED) iDebugged++; } if (iDebugged <= 3) return FALSE; else return TRUE; }
1,302
C++
.cpp
28
44.392857
132
0.788599
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,036
SetHandleInformation_API.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/SetHandleInformation_API.cpp
#include "pch.h" #include "SetHandleInformation_API.h" BOOL SetHandleInformatiom_ProtectedHandle() { /* some vars */ HANDLE hMutex; /* Create a mutex so we can get a handle */ hMutex = CreateMutex(NULL, FALSE, _T("Random name")); if (hMutex) { /* Protect our handle */ SetHandleInformation(hMutex, HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAG_PROTECT_FROM_CLOSE); __try { /* Then, let's try close it */ CloseHandle(hMutex); } __except (EXCEPTION_EXECUTE_HANDLER) { return TRUE; } } return FALSE; }
537
C++
.cpp
21
22.666667
95
0.708333
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,038
LowFragmentationHeap.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/LowFragmentationHeap.cpp
#include "pch.h" #include "LowFragmentationHeap.h" BOOL LowFragmentationHeap( VOID ) /*++ Routine Description: Originally found by Souhail Hammou: http://rce4fun.blogspot.com/2014/02/anti-debugging-trick-checking-for-low.html Under a debugger, the process does not have a Low Fragmentation Heap (LFH) The routine simply checks whether the nt!_HEAP.FrontEndHeap is NULL. Arguments: None Return Value: TRUE - if debugger was detected FALSE - otherwise --*/ { PINT_PTR FrontEndHeap = NULL; // Get the default process heap. HANDLE hHeap = GetProcessHeap(); // The FrontEndHeap offset of the _HEAP structure // is found on different locations depending of the OS. if (IsWindowsVista() || IsWindows7()) { #if defined (ENV64BIT) FrontEndHeap = (PINT_PTR)((CHAR*)hHeap + 0x178); #elif defined(ENV32BIT) FrontEndHeap = (PINT_PTR)((CHAR*)hHeap + 0xd4); #endif } if (IsWindows8or8PointOne()) { #if defined (ENV64BIT) FrontEndHeap = (PINT_PTR)((CHAR*)hHeap + 0x170); #elif defined(ENV32BIT) FrontEndHeap = (PINT_PTR)((CHAR*)hHeap + 0xd0); #endif } // In Windows 10. the offset changes very often. // Ignoring it from now. if (FrontEndHeap && *FrontEndHeap == NULL) { return TRUE; } return FALSE; }
1,234
C++
.cpp
45
25.355556
79
0.746803
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,039
SoftwareBreakpoints.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/SoftwareBreakpoints.cpp
#include "pch.h" #include "SoftwareBreakpoints.h" /* Software breakpoints aka INT 3 represented in the IA-32 instruction set with the opcode CC (0xCC). Given a memory addresse and size, it is relatively simple to scan for the byte 0xCC -> if(pTmp[i] == 0xCC) An obfuscated method would be to check if our memory byte xored with 0x55 is equal 0x99 for example ... */ VOID My_Critical_Function() { int a = 1; int b = 2; int c = a + b; _tprintf(_T("I am critical function, you should protect against int3 bps %d"), c); } VOID Myfunction_Adresss_Next() { My_Critical_Function(); /* There is no guaranteed way of determining the size of a function at run time(and little reason to do so) however if you assume that the linker located functions that are adjacent in the source code sequentially in memory, then the following may give an indication of the size of a function Critical_Function by using : int Critical_Function_length = (int)Myfunction_Adresss_Next - (int)Critical_Function Works only if you compile the file in Release mode. */ }; BOOL SoftwareBreakpoints() { //NOTE this check might not work on x64 because of alignment 0xCC bytes size_t sSizeToCheck = (size_t)(Myfunction_Adresss_Next)-(size_t)(My_Critical_Function); PUCHAR Critical_Function = (PUCHAR)My_Critical_Function; for (size_t i = 0; i < sSizeToCheck; i++) { if (Critical_Function[i] == 0xCC) // Adding another level of indirection : 0xCC xor 0x55 = 0x99 return TRUE; } return FALSE; }
1,489
C++
.cpp
36
39.472222
117
0.753633
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,040
BeingDebugged.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/BeingDebugged.cpp
#include "pch.h" #include "BeingDebugged.h" BOOL IsDebuggerPresentPEB( VOID ) /*++ Routine Description: Checks if the BeingDebugged flag is set in the Process Environment Block (PEB). This is effectively the same code that IsDebuggerPresent() executes internally. The PEB pointer is fetched from DWORD FS:[0x30] on x86_32 and QWORD GS:[0x60] on x86_64. Arguments: None Return Value: TRUE - if debugger was detected FALSE - otherwise --*/ { #if defined (ENV64BIT) PPEB pPeb = (PPEB)__readgsqword(0x60); #elif defined(ENV32BIT) PPEB pPeb = (PPEB)__readfsdword(0x30); #endif return pPeb->BeingDebugged == 1; }
628
C++
.cpp
25
23.28
89
0.77027
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,042
NtQueryObject_AllTypesInformation.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtQueryObject_AllTypesInformation.cpp
#include "pch.h" #include "NtQueryObject_ObjectInformation.h" /* Windows XP introduced a "debug object". When a debugging session begins, a debug object is created, and a handle is associated with it. Using the ntdll NtQueryObject() function with class: ObjectAllTypesInformation. ObjectAllTypesInformation (3) will return a list with all existing object type, we should iterate over objects to locate "DebugObject". Todo: Support for Win10 */ BOOL NtQueryObject_ObjectAllTypesInformation() { //NOTE this check is unreliable, a debugger present on the system doesn't mean it's attached to you auto NtQueryObject = static_cast<pNtQueryObject>(API::GetAPI(API_IDENTIFIER::API_NtQueryObject)); // Some vars ULONG size; PVOID pMemory = NULL; POBJECT_ALL_INFORMATION pObjectAllInfo = NULL; NTSTATUS Status; // Get the size of the information needed Status = NtQueryObject(NULL, 3, &size, sizeof(ULONG), &size); // Alocate memory for the list pMemory = VirtualAlloc(NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (pMemory == NULL) return FALSE; // Now we can actually retrieve the list Status = NtQueryObject((HANDLE)-1, 3, pMemory, size, NULL); // Status != STATUS_SUCCESS if (Status != 0x00000000) { VirtualFree(pMemory, 0, MEM_RELEASE); return FALSE; } // We have the information we need pObjectAllInfo = (POBJECT_ALL_INFORMATION)pMemory; UCHAR *pObjInfoLocation = (UCHAR*)pObjectAllInfo->ObjectTypeInformation; ULONG NumObjects = pObjectAllInfo->NumberOfObjects; for (UINT i = 0; i < NumObjects; i++) { POBJECT_TYPE_INFORMATION pObjectTypeInfo = (POBJECT_TYPE_INFORMATION)pObjInfoLocation; // The debug object will always be present if (StrCmp(_T("DebugObject"), pObjectTypeInfo->TypeName.Buffer) == 0) { // Are there any objects? if (pObjectTypeInfo->TotalNumberOfObjects > 0) { VirtualFree(pMemory, 0, MEM_RELEASE); return TRUE; } else { VirtualFree(pMemory, 0, MEM_RELEASE); return FALSE; } } // Get the address of the current entries // string so we can find the end pObjInfoLocation = (unsigned char*)pObjectTypeInfo->TypeName.Buffer; // Add the size pObjInfoLocation += pObjectTypeInfo->TypeName.MaximumLength; // Skip the trailing null and alignment bytes ULONG_PTR tmp = ((ULONG_PTR)pObjInfoLocation) & -(int)sizeof(void*); // Not pretty but it works if ((ULONG_PTR)tmp != (ULONG_PTR)pObjInfoLocation) tmp += sizeof(void*); pObjInfoLocation = ((unsigned char*)tmp); } VirtualFree(pMemory, 0, MEM_RELEASE); return FALSE; }
2,563
C++
.cpp
68
34.882353
116
0.750808
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,043
NtSystemDebugControl.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtSystemDebugControl.cpp
#include "pch.h" BOOL NtSystemDebugControl_Command() { auto NtSystemDebugControl_ = static_cast<pNtSystemDebugControl>(API::GetAPI(API_IDENTIFIER::API_NtSystemDebugControl)); auto status = NtSystemDebugControl_(SYSDBG_COMMAND::SysDbgCheckLowMemory, 0, 0, 0, 0, 0); const auto STATUS_DEBUGGER_INACTIVE = 0xC0000354L; const auto STATUS_ACCESS_DENIED = 0xC0000022L; if (status == STATUS_DEBUGGER_INACTIVE) { return FALSE; } else { // kernel debugger found if (status != STATUS_ACCESS_DENIED) { // usermode debugger too } return TRUE; } }
557
C++
.cpp
16
32.4375
120
0.758813
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,044
NtQueryInformationProcess_ProcessDebugFlags.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtQueryInformationProcess_ProcessDebugFlags.cpp
#include "pch.h" #include "NtQueryInformationProcess_ProcessDebugFlags.h" /* When NtQueryProcessInformation is called with the ProcessDebugFlags class, the function will return the inverse of EPROCESS->NoDebugInherit, which means that if a debugger is present, then this function will return FALSE if the process is being debugged. */ BOOL NtQueryInformationProcess_ProcessDebugFlags() { // ProcessDebugFlags const int ProcessDebugFlags = 0x1f; auto NtQueryInfoProcess = static_cast<pNtQueryInformationProcess>(API::GetAPI(API_IDENTIFIER::API_NtQueryInformationProcess)); // Other Vars NTSTATUS Status; DWORD NoDebugInherit = 0; Status = NtQueryInfoProcess(GetCurrentProcess(), ProcessDebugFlags, &NoDebugInherit, sizeof(DWORD), NULL); if (Status == 0x00000000 && NoDebugInherit == 0) return TRUE; else return FALSE; }
852
C++
.cpp
20
40
140
0.801453
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,045
WUDF_IsDebuggerPresent.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/WUDF_IsDebuggerPresent.cpp
#include "pch.h" #include "WUDF_IsDebuggerPresent.h" BOOL WUDF_IsAnyDebuggerPresent() { if (API::IsAvailable(API_IDENTIFIER::API_WudfIsAnyDebuggerPresent)) { auto WudfIsAnyDebuggerPresent = static_cast<pWudfIsAnyDebuggerPresent>(API::GetAPI(API_IDENTIFIER::API_WudfIsAnyDebuggerPresent)); return WudfIsAnyDebuggerPresent() == 0 ? FALSE : TRUE; } else return FALSE; } BOOL WUDF_IsKernelDebuggerPresent() { if (API::IsAvailable(API_IDENTIFIER::API_WudfIsKernelDebuggerPresent)) { auto WudfIsKernelDebuggerPresent = static_cast<pWudfIsKernelDebuggerPresent>(API::GetAPI(API_IDENTIFIER::API_WudfIsKernelDebuggerPresent)); return WudfIsKernelDebuggerPresent() == 0 ? FALSE : TRUE; } else return FALSE; } BOOL WUDF_IsUserDebuggerPresent() { if (API::IsAvailable(API_IDENTIFIER::API_WudfIsUserDebuggerPresent)) { auto WudfIsUserDebuggerPresent = static_cast<pWudfIsKernelDebuggerPresent>(API::GetAPI(API_IDENTIFIER::API_WudfIsUserDebuggerPresent)); return WudfIsUserDebuggerPresent() == 0 ? FALSE : TRUE; } else return FALSE; }
1,054
C++
.cpp
32
30.90625
141
0.803729
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,048
HardwareBreakpoints.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/HardwareBreakpoints.cpp
#include "pch.h" #include "HardwareBreakpoints.h" /* Hardware breakpoints are a technology implemented by Intel in their processor architecture, and are controlled by the use of special registers known as Dr0-Dr7. Dr0 through Dr3 are 32 bit registers that hold the address of the breakpoint . */ BOOL HardwareBreakpoints() { BOOL bResult = FALSE; // This structure is key to the function and is the // medium for detection and removal PCONTEXT ctx = PCONTEXT(VirtualAlloc(NULL, sizeof(CONTEXT), MEM_COMMIT, PAGE_READWRITE)); if (ctx) { SecureZeroMemory(ctx, sizeof(CONTEXT)); // The CONTEXT structure is an in/out parameter therefore we have // to set the flags so Get/SetThreadContext knows what to set or get. ctx->ContextFlags = CONTEXT_DEBUG_REGISTERS; // Get the registers if (GetThreadContext(GetCurrentThread(), ctx)) { // Now we can check for hardware breakpoints, its not // necessary to check Dr6 and Dr7, however feel free to if (ctx->Dr0 != 0 || ctx->Dr1 != 0 || ctx->Dr2 != 0 || ctx->Dr3 != 0) bResult = TRUE; } VirtualFree(ctx, 0, MEM_RELEASE); } return bResult; }
1,129
C++
.cpp
29
36.206897
91
0.738051
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,049
TLS_callbacks.cpp
LordNoteworthy_al-khaser/al-khaser/AntiDebug/TLS_callbacks.cpp
#include "pch.h" #include "TLS_callbacks.h" // The Thread Local Storage (TLS) callback is called before the execution of the EntryPoint of the application // Malware takes advantages to perform anti-debug and anti-vm checks. // There could be more than one callback, and sometimes, inside one call back, one can create one in the fly. volatile bool has_run = false; VOID WINAPI tls_callback(PVOID hModule, DWORD dwReason, PVOID pContext) { if (!has_run) { has_run = true; tls_callback_thread_event = CreateEvent(NULL, FALSE, FALSE, NULL); tls_callback_process_event = CreateEvent(NULL, FALSE, FALSE, NULL); } if (dwReason == DLL_THREAD_ATTACH) { OutputDebugString(L"TLS callback: thread attach"); tls_callback_thread_data = 0xDEADBEEF; SetEvent(tls_callback_thread_event); } if (dwReason == DLL_PROCESS_ATTACH) { OutputDebugString(L"TLS callback: process attach"); tls_callback_process_data = 0xDEADBEEF; SetEvent(tls_callback_process_event); } } DWORD WINAPI TLSCallbackDummyThread( _In_ LPVOID lpParameter ) { OutputDebugString(L"TLS callback: dummy thread launched"); return 0; } BOOL TLSCallbackThread() { const int BLOWN = 1000; if (CreateThread(NULL, 0, &TLSCallbackDummyThread, NULL, 0, NULL) == NULL) { OutputDebugString(L"TLS callback: couldn't start dummy thread"); } int fuse = 0; while (tls_callback_thread_event == NULL && ++fuse != BLOWN) { SwitchToThread(); } if (fuse >= BLOWN) { OutputDebugString(L"TLSCallbackThread timeout on event creation."); return TRUE; } DWORD waitStatus = WaitForSingleObject(tls_callback_thread_event, 5000); if (waitStatus != WAIT_OBJECT_0) { if (waitStatus == WAIT_FAILED) OutputDebugString(L"TLSCallbackThread wait failed."); else if (waitStatus == WAIT_ABANDONED) OutputDebugString(L"TLSCallbackThread wait abandoned."); else OutputDebugString(L"TLSCallbackThread timeout on event wait."); return TRUE; } if (tls_callback_thread_data != 0xDEADBEEF) OutputDebugString(L"TLSCallbackThread data did not match."); else OutputDebugString(L"All seems fine for TLSCallbackThread."); return tls_callback_thread_data == 0xDEADBEEF ? FALSE : TRUE; } BOOL TLSCallbackProcess() { const int BLOWN = 1000; int fuse = 0; while (tls_callback_process_event == NULL && ++fuse != BLOWN) { SwitchToThread(); } if (fuse >= BLOWN) { OutputDebugString(L"TLSCallbackProcess timeout on event creation."); return TRUE; } DWORD waitStatus = WaitForSingleObject(tls_callback_process_event, 5000); if (waitStatus != WAIT_OBJECT_0) { if (waitStatus == WAIT_FAILED) OutputDebugString(L"TLSCallbackProcess wait failed."); else if (waitStatus == WAIT_ABANDONED) OutputDebugString(L"TLSCallbackProcess wait abandoned."); else OutputDebugString(L"TLSCallbackProcess timeout on event wait."); return TRUE; } if (tls_callback_process_data != 0xDEADBEEF) OutputDebugString(L"TLSCallbackProcess data did not match."); else OutputDebugString(L"All seems fine for TLSCallbackProcess."); return tls_callback_process_data == 0xDEADBEEF ? FALSE : TRUE; } #ifdef _WIN64 #pragma comment (linker, "/INCLUDE:_tls_used") #pragma comment (linker, "/INCLUDE:tls_callback_func") #else #pragma comment (linker, "/INCLUDE:__tls_used") #pragma comment (linker, "/INCLUDE:_tls_callback_func") #endif #ifdef _WIN64 #pragma const_seg(".CRT$XLF") EXTERN_C const #else #pragma data_seg(".CRT$XLF") EXTERN_C #endif PIMAGE_TLS_CALLBACK tls_callback_func = tls_callback; #ifdef _WIN64 #pragma const_seg() #else #pragma data_seg() #endif //_WIN64
3,575
C++
.cpp
112
29.625
110
0.753417
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,051
QueueUserAPC.cpp
LordNoteworthy_al-khaser/al-khaser/CodeInjection/QueueUserAPC.cpp
#include "pch.h" #include "QueueUserAPC.h" // // Check whatever InjectedDLL.dll was loaded, because this dll // does not provide any other way of caller notification. // BOOL IsDllInjected(DWORD dwProcessId, LPTSTR DllName) { BOOL bFound = FALSE; HANDLE hSnapshot; hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessId); if (hSnapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32 me32; me32.dwSize = sizeof(MODULEENTRY32); if (Module32First(hSnapshot, &me32)) { do { if (StrCmpI(me32.szModule, DllName) == 0) { bFound = TRUE; break; } } while (Module32Next(hSnapshot, &me32)); } CloseHandle(hSnapshot); } return bFound; } BOOL QueueUserAPC_Injection() { TCHAR lpDllName[] = _T("InjectedDLL.dll"); TCHAR lpDllPath[MAX_PATH]; HANDLE hThreadSnapshot = INVALID_HANDLE_VALUE; DWORD dwTargetProcessId, dwCurrentProcessId = GetCurrentProcessId(); HANDLE hProcess = NULL; HANDLE hThread = NULL; HMODULE hKernel32; FARPROC LoadLibraryAddress; LPVOID lpBaseAddress = NULL; BOOL bStatus = FALSE; /* Get Process ID from Process name */ // // calc used because it has multiple threads and some of them maybe alertable. // dwTargetProcessId = GetProcessIdFromName(_T("calc.exe")); if (dwTargetProcessId == 0) dwTargetProcessId = GetProcessIdFromName(_T("win32calc.exe"));//w10 classic calc if (dwTargetProcessId == 0) { print_last_error(_T("GetProcessIdFromName")); return FALSE; } /* Obtain a hmodule of kernel32 */ hKernel32 = GetModuleHandle(_T("kernel32.dll")); if (hKernel32 == NULL) { print_last_error(_T("GetModuleHandle")); return FALSE; } /* Get LoadLibrary address */ _tprintf(_T("\t[+] Looking for LoadLibrary in kernel32\n")); LoadLibraryAddress = GetProcAddress(hKernel32, "LoadLibraryW"); if (LoadLibraryAddress == NULL) { print_last_error(_T("GetProcAddress")); return FALSE; } _tprintf(_T("\t[+] Found at 0x%p\n"), LoadLibraryAddress); _tprintf(_T("\t[+] Getting proc id: %u\n"), dwTargetProcessId); /* Obtain a handle the process */ hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwTargetProcessId); if (hProcess == NULL) { print_last_error(_T("OpenProcess")); return FALSE; } do { // not a loop /* Get the full path of the dll */ GetFullPathName(lpDllName, MAX_PATH, lpDllPath, NULL); _tprintf(_T("\t[+] Full DLL Path: %s\n"), lpDllPath); // The maximum size of the string buffer. SIZE_T WriteBufferSize = _tcslen(lpDllPath) * sizeof(TCHAR); /* Allocate memory into the remote process */ _tprintf(_T("\t[+] Allocating space for the path of the DLL\n")); lpBaseAddress = VirtualAllocEx(hProcess, NULL, WriteBufferSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (lpBaseAddress == NULL) { print_last_error(_T("VirtualAllocEx")); break; } /* Write to the remote process */ printf("\t[+] Writing into the current process space at 0x%p\n", lpBaseAddress); if (!WriteProcessMemory(hProcess, lpBaseAddress, lpDllPath, WriteBufferSize, NULL)) { print_last_error(_T("WriteProcessMemory")); break; } hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hThreadSnapshot == INVALID_HANDLE_VALUE) break; THREADENTRY32 te32; te32.dwSize = sizeof(THREADENTRY32); // // Brute force threads to find suitable alertable thread for APC injection (if any). // if (Thread32First(hThreadSnapshot, &te32)) { do { if (te32.th32OwnerProcessID == dwTargetProcessId) { hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID); if (hThread) { if (QueueUserAPC((PAPCFUNC)LoadLibraryAddress, hThread, (ULONG_PTR)lpBaseAddress)) { if (IsDllInjected(dwTargetProcessId, lpDllName)) { bStatus = TRUE; } } CloseHandle(hThread); } } // dll injected - leave if (bStatus) { _tprintf(_T("\t[+] Dll has been injected successfully ...\n")); break; } } while (Thread32Next(hThreadSnapshot, &te32)); } } while (FALSE); // not a loop // // Cleanup. // if (hThreadSnapshot != INVALID_HANDLE_VALUE) CloseHandle(hThreadSnapshot); if (lpBaseAddress) { VirtualFreeEx(hProcess, lpBaseAddress, 0, MEM_RELEASE); } CloseHandle(hProcess); return bStatus; }
4,248
C++
.cpp
128
29.859375
108
0.71327
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,053
SetWindowsHooksEx.cpp
LordNoteworthy_al-khaser/al-khaser/CodeInjection/SetWindowsHooksEx.cpp
#include "pch.h" #include "SetWindowsHooksEx.h" BOOL SetWindowsHooksEx_Injection() { TCHAR lpDllName[] = _T("InjectedDLL.dll"); TCHAR lpDllPath[MAX_PATH]; HOOKPROC myFunctionAddress; HMODULE hOurDll; DWORD dwProcessId, dwThreadId; HHOOK hHook; /* Get Process ID from Process name */ dwProcessId = GetProcessIdFromName(_T("notepad.exe")); if (dwProcessId == NULL) return FALSE; _tprintf(_T("\t[+] Getting proc id: %u\n"), dwProcessId); /* Get thread id from process id */ dwThreadId = GetMainThreadId(dwProcessId); if (dwThreadId == NULL) return FALSE; _tprintf(_T("\t[+] Getting main thread id of proc id: %u\n"), dwThreadId); /* Get the full path of the dll to be injected */ GetFullPathName(lpDllName, MAX_PATH, lpDllPath, NULL); _tprintf(_T("\t[+] Full DLL Path: %s\n"), lpDllPath); /* Obtain a handle to our injected dll */ hOurDll = LoadLibrary(lpDllPath); if (hOurDll == NULL) { print_last_error(_T("LoadLibrary")); return FALSE; } /* Get 'MyProc' address */ _tprintf(_T("\t[+] Looking for 'MyProc' in our dll\n")); myFunctionAddress = (HOOKPROC)GetProcAddress(hOurDll, "MyProc"); if (myFunctionAddress == NULL) { print_last_error(_T("GetProcAddress")); return FALSE; } _tprintf(_T("\t[+] Found at 0x%p\n"), myFunctionAddress); /* Injection happens here */ hHook = SetWindowsHookEx(WH_KEYBOARD, myFunctionAddress, hOurDll, dwThreadId); if (hHook == NULL) { print_last_error(_T("SetWindowsHookEx")); return FALSE; } /* Unhook */ _tprintf(_T("SetWindowsHookEx created successfully ...\n")); /* When we want to remove the hook */ // UnhookWindowsHookEx(hHook); return TRUE; }
1,645
C++
.cpp
49
31.22449
79
0.708781
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,054
GetSetThreadContext.cpp
LordNoteworthy_al-khaser/al-khaser/CodeInjection/GetSetThreadContext.cpp
#include "pch.h" #include "GetSetThreadContext.h" BOOL GetSetThreadContext_Injection() { #ifdef _WIN64 return TRUE; //TODO implement this on x64 #else TCHAR lpApplicationName[] = _T("C:\\Windows\\System32\\svchost.exe"); TCHAR lpApplicationName2[] = _T("C:\\masm32\\examples\\dialogs_later\\basic\\basicdlg.exe"); BOOL bResult = FALSE; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInfo; PCONTEXT pContext = NULL; HANDLE hFile = INVALID_HANDLE_VALUE; SecureZeroMemory(&StartupInfo, sizeof(STARTUPINFO)); SecureZeroMemory(&ProcessInfo, sizeof(PPROCESS_INFORMATION)); do { /* not a loop */ // Create the hollowed process in suspended mode if (!CreateProcess(lpApplicationName, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &StartupInfo, &ProcessInfo)) { print_last_error(_T("CreateProcess")); break; } // Allocate space for context structure LPVOID pTargetImageBase = NULL; pContext = PCONTEXT(VirtualAlloc(NULL, sizeof(CONTEXT), MEM_COMMIT, PAGE_READWRITE)); if (pContext == NULL) { print_last_error(_T("VirtualAlloc")); break; } // Get the thread context of target pContext->ContextFlags = CONTEXT_FULL; if (!GetThreadContext(ProcessInfo.hThread, pContext)) { print_last_error(_T("GetThreadContext")); break; } // Read the image base address of target ReadProcessMemory(ProcessInfo.hProcess, LPCVOID(pContext->Ebx + 8), pTargetImageBase, 4, NULL); // Opening source image hFile = CreateFile(lpApplicationName2, GENERIC_READ, NULL, NULL, OPEN_ALWAYS, NULL, NULL); if (hFile == INVALID_HANDLE_VALUE) { print_last_error(_T("CreateFile")); break; } // Reading the file DWORD dwSize = GetFileSize(hFile, 0); DWORD dwBytesRead; PBYTE pBuffer = static_cast<PBYTE>(MALLOC(dwSize)); if (pBuffer == NULL) { print_last_error(_T("HeapAlloc")); break; } else { SecureZeroMemory(pBuffer, dwSize); ReadFile(hFile, pBuffer, dwSize, &dwBytesRead, 0); PIMAGE_SECTION_HEADER pImageSectionHeader; PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)pBuffer; if (pDosHeader->e_magic == IMAGE_DOS_SIGNATURE) { PIMAGE_NT_HEADERS32 pNTHeaders = PIMAGE_NT_HEADERS(DWORD(pBuffer) + pDosHeader->e_lfanew); if (pNTHeaders->Signature == IMAGE_NT_SIGNATURE) { if (DWORD(pTargetImageBase) == pNTHeaders->OptionalHeader.ImageBase) { pNtUnmapViewOfSection NtUnmapViewOfSection; NtUnmapViewOfSection = (pNtUnmapViewOfSection)(GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtUnmapViewOfSection")); NtUnmapViewOfSection(ProcessInfo.hProcess, pTargetImageBase); } LPVOID pImageBase; pImageBase = VirtualAllocEx(ProcessInfo.hProcess, LPVOID(pNTHeaders->OptionalHeader.ImageBase), pNTHeaders->OptionalHeader.SizeOfImage, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (pImageBase == NULL) { print_last_error(_T("VirtualAllocEx")); break; } else { WriteProcessMemory(ProcessInfo.hProcess, pImageBase, pBuffer, pNTHeaders->OptionalHeader.SizeOfHeaders, NULL); for (int Count = 0; Count < pNTHeaders->FileHeader.NumberOfSections; Count++) { pImageSectionHeader = PIMAGE_SECTION_HEADER(DWORD(pBuffer) + pDosHeader->e_lfanew + 248 + (Count * 40)); WriteProcessMemory(ProcessInfo.hProcess, LPVOID(DWORD(pImageBase) + pImageSectionHeader->VirtualAddress), LPVOID(DWORD(pBuffer) + pImageSectionHeader->PointerToRawData), pImageSectionHeader->SizeOfRawData, NULL); } WriteProcessMemory(ProcessInfo.hProcess, LPVOID(pContext->Ebx + 8), LPVOID(&pNTHeaders->OptionalHeader.ImageBase), 4, NULL); pContext->Eax = DWORD(pImageBase) + pNTHeaders->OptionalHeader.AddressOfEntryPoint; SetThreadContext(ProcessInfo.hThread, LPCONTEXT(pContext)); LONG dwRet; dwRet = ResumeThread(ProcessInfo.hThread); bResult = (dwRet != -1); } } } FREE(pBuffer); } } while (FALSE); /* not a loop */ /* Cleanup */ if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread); if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess); if (pContext) VirtualFree(pContext, 0, MEM_RELEASE); if (hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); return bResult; #endif }
4,254
C++
.cpp
104
36.625
130
0.731441
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,056
InjectedDLL.cpp
LordNoteworthy_al-khaser/al-khaser/CodeInjection/InjectedDLL/InjectedDLL.cpp
#include "stdafx.h" #include "InjectedDLL.h" LRESULT CALLBACK MyProc(INT code, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK MyProc(INT code, WPARAM wParam, LPARAM lParam) { //here goes our code TCHAR str[MAX_PATH] = _T(""); _stprintf(str, _T("[Al-khaser] - Injected from process: %d"), GetCurrentProcessId()); OutputDebugString(str); return CallNextHookEx(NULL, code, wParam, lParam); //this is needed to let other applications set other hooks on this target } BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: OutputDebugString(_T("[Al-khaser] - DLL is attached")); break; case DLL_PROCESS_DETACH: OutputDebugString(_T("[Al-khaser] - DLL is detached")); break; case DLL_THREAD_ATTACH: OutputDebugString(_T("[Al-khaser] - Thread is atached")); break; case DLL_THREAD_DETACH: OutputDebugString(_T("[Al-khaser] - Thread is detached")); break; } /* Returns TRUE on success, FALSE on failure */ return TRUE; }
1,032
C++
.cpp
31
30.645161
126
0.730111
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,057
process.cpp
LordNoteworthy_al-khaser/al-khaser/AntiAnalysis/process.cpp
#include "pch.h" #pragma once #include "process.h" /* Check for process list */ VOID analysis_tools_process() { const TCHAR *szProcesses[] = { _T("ollydbg.exe"), // OllyDebug debugger _T("ollyice.exe"), // OllyICE debugger _T("ProcessHacker.exe"), // Process Hacker _T("tcpview.exe"), // Part of Sysinternals Suite _T("autoruns.exe"), // Part of Sysinternals Suite _T("autorunsc.exe"), // Part of Sysinternals Suite _T("filemon.exe"), // Part of Sysinternals Suite _T("procmon.exe"), // Part of Sysinternals Suite _T("regmon.exe"), // Part of Sysinternals Suite _T("procexp.exe"), // Part of Sysinternals Suite _T("idaq.exe"), // IDA Pro Interactive Disassembler _T("idaq64.exe"), // IDA Pro Interactive Disassembler _T("ImmunityDebugger.exe"), // ImmunityDebugger _T("Wireshark.exe"), // Wireshark packet sniffer _T("dumpcap.exe"), // Network traffic dump tool _T("HookExplorer.exe"), // Find various types of runtime hooks _T("ImportREC.exe"), // Import Reconstructor _T("PETools.exe"), // PE Tool _T("LordPE.exe"), // LordPE _T("SysInspector.exe"), // ESET SysInspector _T("proc_analyzer.exe"), // Part of SysAnalyzer iDefense _T("sysAnalyzer.exe"), // Part of SysAnalyzer iDefense _T("sniff_hit.exe"), // Part of SysAnalyzer iDefense _T("windbg.exe"), // Microsoft WinDbg _T("joeboxcontrol.exe"), // Part of Joe Sandbox _T("joeboxserver.exe"), // Part of Joe Sandbox _T("ResourceHacker.exe"), // Resource Hacker _T("x32dbg.exe"), // x32dbg _T("x64dbg.exe"), // x64dbg _T("Fiddler.exe"), // Fiddler _T("httpdebugger.exe"), // Http Debugger _T("cheatengine-i386.exe"), // Cheat Engine _T("cheatengine-x86_64.exe"), // Cheat Engine _T("cheatengine-x86_64-SSE4-AVX2.exe"), // Cheat Engine _T("frida-helper-32.exe"), // Frida _T("frida-helper-64.exe"), // Frida }; WORD iLength = sizeof(szProcesses) / sizeof(szProcesses[0]); for (int i = 0; i < iLength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking process of malware analysis tool: %s "), szProcesses[i]); if (GetProcessIdFromName(szProcesses[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } }
2,350
C++
.cpp
57
38.561404
118
0.630131
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,058
VMWare.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/VMWare.cpp
#include "pch.h" #include "VMWare.h" /* Check against VMWare registry key values */ VOID vmware_reg_key_value() { /* Array of strings of blacklisted registry key values */ const TCHAR *szEntries[][3] = { { _T("HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 0\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0"), _T("Identifier"), _T("VMWARE") }, { _T("HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 1\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0"), _T("Identifier"), _T("VMWARE") }, { _T("HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 2\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0"), _T("Identifier"), _T("VMWARE") }, { _T("SYSTEM\\ControlSet001\\Control\\SystemInformation"), _T("SystemManufacturer"), _T("VMWARE") }, { _T("SYSTEM\\ControlSet001\\Control\\SystemInformation"), _T("SystemProductName"), _T("VMWARE") }, }; WORD dwLength = sizeof(szEntries) / sizeof(szEntries[0]); for (int i = 0; i < dwLength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking reg key %s"), szEntries[i][0]); if (Is_RegKeyValueExists(HKEY_LOCAL_MACHINE, szEntries[i][0], szEntries[i][1], szEntries[i][2])) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check against VMWare registry keys */ VOID vmware_reg_keys() { /* Array of strings of blacklisted registry keys */ const TCHAR* szKeys[] = { _T("SOFTWARE\\VMware, Inc.\\VMware Tools"), }; WORD dwlength = sizeof(szKeys) / sizeof(szKeys[0]); /* Check one by one */ for (int i = 0; i < dwlength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking reg key %s "), szKeys[i]); if (Is_RegKeyExists(HKEY_LOCAL_MACHINE, szKeys[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check against VMWare blacklisted files */ VOID vmware_files() { /* Array of strings of blacklisted paths */ const TCHAR* szPaths[] = { _T("System32\\drivers\\vmnet.sys"), _T("System32\\drivers\\vmmouse.sys"), _T("System32\\drivers\\vmusb.sys"), _T("System32\\drivers\\vm3dmp.sys"), _T("System32\\drivers\\vmci.sys"), _T("System32\\drivers\\vmhgfs.sys"), _T("System32\\drivers\\vmmemctl.sys"), _T("System32\\drivers\\vmx86.sys"), _T("System32\\drivers\\vmrawdsk.sys"), _T("System32\\drivers\\vmusbmouse.sys"), _T("System32\\drivers\\vmkdb.sys"), _T("System32\\drivers\\vmnetuserif.sys"), _T("System32\\drivers\\vmnetadapter.sys"), }; /* Getting Windows Directory */ WORD dwlength = sizeof(szPaths) / sizeof(szPaths[0]); TCHAR szWinDir[MAX_PATH] = _T(""); TCHAR szPath[MAX_PATH] = _T(""); PVOID OldValue = NULL; GetWindowsDirectory(szWinDir, MAX_PATH); if (IsWoW64()) { Wow64DisableWow64FsRedirection(&OldValue); } /* Check one by one */ for (int i = 0; i < dwlength; i++) { PathCombine(szPath, szWinDir, szPaths[i]); TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking file %s "), szPath); if (is_FileExists(szPath)) print_results(TRUE, msg); else print_results(FALSE, msg); } if (IsWoW64()) { Wow64RevertWow64FsRedirection(&OldValue); } } /* Check against VMWare blacklisted directories */ BOOL vmware_dir() { TCHAR szProgramFile[MAX_PATH]; TCHAR szPath[MAX_PATH] = _T(""); TCHAR szTarget[MAX_PATH] = _T("VMWare\\"); if (IsWoW64()) ExpandEnvironmentStrings(_T("%ProgramW6432%"), szProgramFile, ARRAYSIZE(szProgramFile)); else SHGetSpecialFolderPath(NULL, szProgramFile, CSIDL_PROGRAM_FILES, FALSE); PathCombine(szPath, szProgramFile, szTarget); return is_DirectoryExists(szPath); } /* Check VMWare NIC MAC addresses */ VOID vmware_mac() { /* VMWre blacklisted mac adr */ const TCHAR *szMac[][2] = { { _T("\x00\x05\x69"), _T("00:05:69") }, // VMWare, Inc. { _T("\x00\x0C\x29"), _T("00:0c:29") }, // VMWare, Inc. { _T("\x00\x1C\x14"), _T("00:1C:14") }, // VMWare, Inc. { _T("\x00\x50\x56"), _T("00:50:56") }, // VMWare, Inc. }; WORD dwLength = sizeof(szMac) / sizeof(szMac[0]); /* Check one by one */ for (int i = 0; i < dwLength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking MAC starting with %s"), szMac[i][1]); if (check_mac_addr(szMac[i][0])) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check against VMWare adapter name */ BOOL vmware_adapter_name() { const TCHAR* szAdapterName = _T("VMWare"); if (check_adapter_name(szAdapterName)) return TRUE; else return FALSE; } /* Check against VMWare pseaudo-devices */ VOID vmware_devices() { const TCHAR *devices[] = { _T("\\\\.\\HGFS"), _T("\\\\.\\vmci"), }; WORD iLength = sizeof(devices) / sizeof(devices[0]); for (int i = 0; i < iLength; i++) { HANDLE hFile = CreateFile(devices[i], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking device %s "), devices[i]); if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); print_results(TRUE, msg); } else print_results(FALSE, msg); } } /* Check for process list */ VOID vmware_processes() { const TCHAR *szProcesses[] = { _T("vmtoolsd.exe"), _T("vmwaretray.exe"), _T("vmwareuser.exe"), _T("VGAuthService.exe"), _T("vmacthlp.exe"), }; WORD iLength = sizeof(szProcesses) / sizeof(szProcesses[0]); for (int i = 0; i < iLength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking VWware process %s "), szProcesses[i]); if (GetProcessIdFromName(szProcesses[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check for SMBIOS firmware */ BOOL vmware_firmware_SMBIOS() { BOOL result = FALSE; const DWORD Signature = static_cast<DWORD>('RSMB'); DWORD smbiosSize = 0; PBYTE smbios = get_system_firmware(static_cast<DWORD>('RSMB'), 0x0000, &smbiosSize); if (smbios != NULL) { PBYTE vmwareString = (PBYTE)"VMware"; size_t vmwwareStringLen = 6; if (find_str_in_data(vmwareString, vmwwareStringLen, smbios, smbiosSize)) { result = TRUE; } free(smbios); } return result; } /* Check for ACPI firmware */ BOOL vmware_firmware_ACPI() { BOOL result = FALSE; PDWORD tableNames = static_cast<PDWORD>(malloc(4096)); if (tableNames == NULL) return FALSE; SecureZeroMemory(tableNames, 4096); DWORD tableSize = enum_system_firmware_tables(static_cast<DWORD>('ACPI'), tableNames, 4096); // API not available if (tableSize == -1) return FALSE; DWORD tableCount = tableSize / 4; if (tableSize < 4 || tableCount == 0) { result = TRUE; } else { for (DWORD i = 0; i < tableCount; i++) { DWORD tableSize = 0; PBYTE table = get_system_firmware(static_cast<DWORD>('ACPI'), tableNames[i], &tableSize); if (table) { PBYTE vmwareString = (PBYTE)"VMWARE"; size_t vmwwareStringLen = 6; if (find_str_in_data(vmwareString, vmwwareStringLen, table, tableSize)) { result = TRUE; } free(table); } } } free(tableNames); return result; }
7,016
C++
.cpp
246
26.02439
127
0.669099
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,059
Parallels.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/Parallels.cpp
#include "pch.h" #include "Parallels.h" /* Check for process list */ VOID parallels_process() { const TCHAR *szProcesses[] = { _T("prl_cc.exe"), _T("prl_tools.exe"), }; WORD iLength = sizeof(szProcesses) / sizeof(szProcesses[0]); for (int i = 0; i < iLength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking Parallels processes: %s"), szProcesses[i]); if (GetProcessIdFromName(szProcesses[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check Parallels NIC MAC address */ BOOL parallels_check_mac() { // Parallels, Inc. return check_mac_addr(_T("\x00\x1C\x42")); }
662
C++
.cpp
30
19.966667
104
0.672524
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,060
KVM.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/KVM.cpp
#include "pch.h" /* Check against kvm registry keys */ VOID kvm_reg_keys() { /* Array of strings of blacklisted registry keys */ const TCHAR* szKeys[] = { _T("SYSTEM\\ControlSet001\\Services\\vioscsi"), _T("SYSTEM\\ControlSet001\\Services\\viostor"), _T("SYSTEM\\ControlSet001\\Services\\VirtIO-FS Service"), _T("SYSTEM\\ControlSet001\\Services\\VirtioSerial"), _T("SYSTEM\\ControlSet001\\Services\\BALLOON"), _T("SYSTEM\\ControlSet001\\Services\\BalloonService"), _T("SYSTEM\\ControlSet001\\Services\\netkvm"), }; WORD dwlength = sizeof(szKeys) / sizeof(szKeys[0]); /* Check one by one */ for (int i = 0; i < dwlength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking reg key %s "), szKeys[i]); if (Is_RegKeyExists(HKEY_LOCAL_MACHINE, szKeys[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check against kvm blacklisted files */ VOID kvm_files() { /* Array of strings of blacklisted paths */ const TCHAR* szPaths[] = { _T("System32\\drivers\\balloon.sys"), _T("System32\\drivers\\netkvm.sys"), _T("System32\\drivers\\pvpanic.sys"), _T("System32\\drivers\\viofs.sys"), _T("System32\\drivers\\viogpudo.sys"), _T("System32\\drivers\\vioinput.sys"), _T("System32\\drivers\\viorng.sys"), _T("System32\\drivers\\vioscsi.sys"), _T("System32\\drivers\\vioser.sys"), _T("System32\\drivers\\viostor.sys"), }; /* Getting Windows Directory */ WORD dwlength = sizeof(szPaths) / sizeof(szPaths[0]); TCHAR szWinDir[MAX_PATH] = _T(""); TCHAR szPath[MAX_PATH] = _T(""); PVOID OldValue = NULL; GetWindowsDirectory(szWinDir, MAX_PATH); if (IsWoW64()) { Wow64DisableWow64FsRedirection(&OldValue); } /* Check one by one */ for (int i = 0; i < dwlength; i++) { PathCombine(szPath, szWinDir, szPaths[i]); TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking file %s "), szPath); if (is_FileExists(szPath)) print_results(TRUE, msg); else print_results(FALSE, msg); } if (IsWoW64()) { Wow64RevertWow64FsRedirection(&OldValue); } } /* Check against kvm blacklisted directories */ BOOL kvm_dir() { TCHAR szProgramFile[MAX_PATH]; TCHAR szPath[MAX_PATH] = _T(""); TCHAR szTarget[MAX_PATH] = _T("Virtio-Win\\"); if (IsWoW64()) ExpandEnvironmentStrings(_T("%ProgramW6432%"), szProgramFile, ARRAYSIZE(szProgramFile)); else SHGetSpecialFolderPath(NULL, szProgramFile, CSIDL_PROGRAM_FILES, FALSE); PathCombine(szPath, szProgramFile, szTarget); return is_DirectoryExists(szPath); }
2,562
C++
.cpp
85
27.741176
90
0.693463
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,061
Wine.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/Wine.cpp
#include "pch.h" #include "Wine.h" /* Check against Wine export dlls */ BOOL wine_exports() { /* Some vars */ HMODULE hKernel32; /* Get kernel32 module handle */ hKernel32 = GetModuleHandle(_T("kernel32.dll")); if (hKernel32 == NULL) { print_last_error(_T("GetModuleHandle")); return FALSE; } /* Check if wine_get_unix_file_name is exported by this dll */ if (GetProcAddress(hKernel32, "wine_get_unix_file_name") == NULL) return FALSE; else return TRUE; } /* Check against Wine registry keys */ VOID wine_reg_keys() { /* Array of strings of blacklisted registry keys */ const TCHAR* szKeys[] = { _T("SOFTWARE\\Wine") }; WORD dwlength = sizeof(szKeys) / sizeof(szKeys[0]); /* Check one by one */ for (int i = 0; i < dwlength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking reg key %s "), szKeys[i]); if (Is_RegKeyExists(HKEY_CURRENT_USER, szKeys[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } }
1,004
C++
.cpp
42
21.761905
87
0.678534
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,062
Generic.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/Generic.cpp
#include "pch.h" #include "Generic.h" /* Check if the DLL is loaded in the context of the process */ VOID loaded_dlls() { /* Some vars */ HMODULE hDll; /* Array of strings of blacklisted dlls */ CONST TCHAR* szDlls[] = { _T("avghookx.dll"), // AVG _T("avghooka.dll"), // AVG _T("snxhk.dll"), // Avast _T("sbiedll.dll"), // Sandboxie _T("dbghelp.dll"), // WindBG _T("api_log.dll"), // iDefense Lab _T("dir_watch.dll"), // iDefense Lab _T("pstorec.dll"), // SunBelt Sandbox _T("vmcheck.dll"), // Virtual PC _T("wpespy.dll"), // WPE Pro _T("cmdvrt64.dll"), // Comodo Container _T("cmdvrt32.dll"), // Comodo Container }; WORD dwlength = sizeof(szDlls) / sizeof(szDlls[0]); for (int i = 0; i < dwlength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking if process loaded modules contains: %s "), szDlls[i]); /* Check if process loaded modules contains the blacklisted dll */ hDll = GetModuleHandle(szDlls[i]); if (hDll == NULL) print_results(FALSE, msg); else print_results(TRUE, msg); } } /* Check if the file name contains any of the following strings. This is likely an automated malware sandbox. */ VOID known_file_names() { /* Array of strings of filenames seen in sandboxes */ CONST TCHAR* szFilenames[] = { _T("sample.exe"), _T("bot.exe"), _T("sandbox.exe"), _T("malware.exe"), _T("test.exe"), _T("klavme.exe"), _T("myapp.exe"), _T("testapp.exe"), }; #if defined (ENV64BIT) PPEB pPeb = (PPEB)__readgsqword(0x60); #elif defined(ENV32BIT) PPEB pPeb = (PPEB)__readfsdword(0x30); #endif if (!pPeb->ProcessParameters->ImagePathName.Buffer) { return; } // Get the file name from path/ WCHAR* szFileName = PathFindFileNameW(pPeb->ProcessParameters->ImagePathName.Buffer); TCHAR msg[256] = _T(""); WORD dwlength = sizeof(szFilenames) / sizeof(szFilenames[0]); for (int i = 0; i < dwlength; i++) { _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking if process file name contains: %s "), szFilenames[i]); /* Check if file name matches any blacklisted filenames */ if (StrCmpIW(szFilenames[i], szFileName) != 0) print_results(FALSE, msg); else print_results(TRUE, msg); } // Some malware do check if the file name is a known hash (like md5 or sha1) PathRemoveExtensionW(szFileName); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking if process file name looks like a hash: %s "), szFileName); if ( (wcslen(szFileName) == 32 || wcslen(szFileName) == 40 || wcslen(szFileName) == 64) && IsHexString(szFileName)) print_results(TRUE, msg); else print_results(FALSE, msg); } static TCHAR * get_username() { TCHAR *username; DWORD nSize = (UNLEN + 1); username = (TCHAR *) malloc(nSize * sizeof(TCHAR)); if (!username) { return NULL; } if (0 == GetUserName(username, &nSize)) { free(username); return NULL; } return username; } /* Check for usernames associated with sandboxes */ VOID known_usernames() { /* Array of strings of usernames seen in sandboxes */ CONST TCHAR* szUsernames[] = { /* Checked for by Gootkit * https://www.sentinelone.com/blog/gootkit-banking-trojan-deep-dive-anti-analysis-features/ */ _T("CurrentUser"), _T("Sandbox"), /* Checked for by ostap * https://www.bromium.com/deobfuscating-ostap-trickbots-javascript-downloader/ */ _T("Emily"), _T("HAPUBWS"), _T("Hong Lee"), _T("IT-ADMIN"), _T("Johnson"), /* Lastline Sandbox */ _T("Miller"), /* Lastline Sandbox */ _T("milozs"), _T("Peter Wilson"), _T("timmy"), _T("user"), /* Checked for by Betabot (not including ones from above) * https://www.bromium.com/deobfuscating-ostap-trickbots-javascript-downloader/ */ _T("sand box"), _T("malware"), _T("maltest"), _T("test user"), /* Checked for by Satan (not including ones from above) * https://cofense.com/satan/ */ _T("virus"), /* Checked for by Emotet (not including ones from above) * https://blog.trendmicro.com/trendlabs-security-intelligence/new-emotet-hijacks-windows-api-evades-sandbox-analysis/ */ _T("John Doe"), /* VirusTotal Cuckoofork Sandbox */ }; TCHAR *username; if (NULL == (username = get_username())) { return; } TCHAR msg[256]; WORD dwlength = sizeof(szUsernames) / sizeof(szUsernames[0]); for (int i = 0; i < dwlength; i++) { _stprintf_s(msg, sizeof(msg) / sizeof(msg[0]), _T("Checking if username matches : %s "), szUsernames[i]); /* Do a case-insensitive search for all entries in szHostnames */ BOOL matched = FALSE; if (0 == _tcsicmp(szUsernames[i], username)) { matched = TRUE; } print_results(matched, msg); } free(username); } static TCHAR * get_netbios_hostname() { TCHAR *hostname; DWORD nSize = (MAX_COMPUTERNAME_LENGTH + 1); hostname = (TCHAR *) malloc(nSize * sizeof(TCHAR)); if (!hostname) { return NULL; } if (0 == GetComputerName(hostname, &nSize)) { free(hostname); return NULL; } return hostname; } static TCHAR * get_dns_hostname() { TCHAR *hostname; DWORD nSize = 0; GetComputerNameEx(ComputerNameDnsHostname, NULL, &nSize); hostname = (TCHAR *) malloc((nSize + 1) * sizeof(TCHAR)); if (!hostname) { return NULL; } if (0 == GetComputerNameEx(ComputerNameDnsHostname, hostname, &nSize)) { free(hostname); return NULL; } return hostname; } /* Check for hostnames associated with sandboxes */ VOID known_hostnames() { /* Array of strings of hostnames seen in sandboxes */ CONST TCHAR* szHostnames[] = { /* Checked for by Gootkit * https://www.sentinelone.com/blog/gootkit-banking-trojan-deep-dive-anti-analysis-features/ */ _T("SANDBOX"), _T("7SILVIA"), /* Checked for by ostap * https://www.bromium.com/deobfuscating-ostap-trickbots-javascript-downloader/ */ _T("HANSPETER-PC"), _T("JOHN-PC"), _T("MUELLER-PC"), _T("WIN7-TRAPS"), /* Checked for by Shifu (not including ones from above) * https://www.mcafee.com/blogs/other-blogs/mcafee-labs/japanese-banking-trojan-shifu-combines-malware-tools */ _T("FORTINET"), /* Checked for by Emotet (not including ones from above) * https://blog.trendmicro.com/trendlabs-security-intelligence/new-emotet-hijacks-windows-api-evades-sandbox-analysis/ */ _T("TEQUILABOOMBOOM"), /* VirusTotal Cuckoofork Sandbox */ }; TCHAR *NetBIOSHostName; TCHAR *DNSHostName; if (NULL == (NetBIOSHostName = get_netbios_hostname())) { return; } if (NULL == (DNSHostName = get_dns_hostname())) { free(NetBIOSHostName); return; } TCHAR msg[256]; WORD dwlength = sizeof(szHostnames) / sizeof(szHostnames[0]); for (int i = 0; i < dwlength; i++) { _stprintf_s(msg, sizeof(msg) / sizeof(msg[0]), _T("Checking if hostname matches : %s "), szHostnames[i]); /* Do a case-insensitive search for all entries in szHostnames */ BOOL matched = FALSE; if (0 == _tcsicmp(szHostnames[i], NetBIOSHostName)) { matched = TRUE; } else if (0 == _tcsicmp(szHostnames[i], DNSHostName)) { matched = TRUE; } print_results(matched, msg); } free(NetBIOSHostName); free(DNSHostName); } /* Check for a combination of environmental conditions, replicating what malware could/has used to detect that it's running in a sandbox. */ VOID other_known_sandbox_environment_checks() { TCHAR *NetBIOSHostName; TCHAR *DNSHostName; TCHAR *username; BOOL matched; if (NULL == (username = get_username())) { return; } if (NULL == (NetBIOSHostName = get_netbios_hostname())) { free(username); return; } if (NULL == (DNSHostName = get_dns_hostname())) { free(username); free(NetBIOSHostName); return; } /* From Emotet * https://blog.trendmicro.com/trendlabs-security-intelligence/new-emotet-hijacks-windows-api-evades-sandbox-analysis/ */ matched = FALSE; if ((0 == StrCmp(username, _T("Wilber"))) && ((0 == StrCmpNI(NetBIOSHostName, _T("SC"), 2)) || (0 == StrCmpNI(NetBIOSHostName, _T("SW"), 2)))) { matched = TRUE; } print_results(matched, (TCHAR *)_T("Checking whether username is 'Wilber' and NetBIOS name starts with 'SC' or 'SW' ")); matched = FALSE; if ((0 == StrCmp(username, _T("admin"))) && (0 == StrCmp(NetBIOSHostName, _T("SystemIT")))) { matched = TRUE; } print_results(matched, (TCHAR *)_T("Checking whether username is 'admin' and NetBIOS name is 'SystemIT' ")); matched = FALSE; if ((0 == StrCmp(username, _T("admin"))) && (0 == StrCmp(DNSHostName, _T("KLONE_X64-PC")))) { matched = TRUE; } print_results(matched, (TCHAR *) _T("Checking whether username is 'admin' and DNS hostname is 'KLONE_X64-PC' ")); matched = FALSE; if ((0 == StrCmp(username, _T("John"))) && (is_FileExists((TCHAR *)_T("C:\\take_screenshot.ps1"))) && (is_FileExists((TCHAR *)_T("C:\\loaddll.exe")))) { matched = TRUE; } print_results(matched, (TCHAR *)_T("Checking whether username is 'John' and two sandbox files exist ")); matched = FALSE; if ((is_FileExists((TCHAR *)_T("C:\\email.doc"))) && (is_FileExists((TCHAR *)_T("C:\\email.htm"))) && (is_FileExists((TCHAR *)_T("C:\\123\\email.doc"))) && (is_FileExists((TCHAR *)_T("C:\\123\\email.docx")))) { matched = TRUE; } print_results(matched, (TCHAR *)_T("Checking whether four known sandbox 'email' file paths exist ")); matched = FALSE; if ((is_FileExists((TCHAR *)_T("C:\\a\\foobar.bmp"))) && (is_FileExists((TCHAR *)_T("C:\\a\\foobar.doc"))) && (is_FileExists((TCHAR *)_T("C:\\a\\foobar.gif")))) { matched = TRUE; } print_results(matched, (TCHAR *)_T("Checking whether three known sandbox 'foobar' files exist ")); free(username); free(NetBIOSHostName); free(DNSHostName); } /* Detect Hybrid Analysis with mac vendor */ BOOL hybridanalysismacdetect() { return check_mac_addr(_T("\x0A\x00\x27")); } /* Number of Processors in VM */ BOOL NumberOfProcessors() { #if defined (ENV64BIT) PULONG ulNumberProcessors = (PULONG)(__readgsqword(0x60) + 0xB8); #elif defined(ENV32BIT) PULONG ulNumberProcessors = (PULONG)(__readfsdword(0x30) + 0x64); #endif if (*ulNumberProcessors < 2) return TRUE; else return FALSE; } /* This trick involves looking at pointers to critical operating system tables that are typically relocated on a virtual machine. One such table is the Interrupt Descriptor Table (IDT), which tells the system where various operating system interrupt handlers are located in memory. On real machines, the IDT is located lower in memory than it is on guest (i.e., virtual) machines PS: Does not seem to work on newer version of VMWare Workstation (Tested on v12) */ BOOL idt_trick() { UINT idt_base = get_idt_base(); if ((idt_base >> 24) == 0xff) return TRUE; else return FALSE; } /* Same for Local Descriptor Table (LDT) */ BOOL ldt_trick() { UINT ldt_base = get_ldt_base(); if (ldt_base == 0xdead0000) return FALSE; else return TRUE; // VMWare detected } /* Same for Global Descriptor Table (GDT) */ BOOL gdt_trick() { UINT gdt_base = get_gdt_base(); if ((gdt_base >> 24) == 0xff) return TRUE; // VMWare detected else return FALSE; } /* The instruction STR (Store Task Register) stores the selector segment of the TR register (Task Register) in the specified operand (memory or other general purpose register). All x86 processors can manage tasks in the same way as an operating system would do it. That is, keeping the task state and recovering it when that task is executed again. All the states of a task are kept in its TSS; there is one TSS per task. How can we know which is the TSS associated to the execution task? Using STR instruction, due to the fact that the selector segment that was brought back points into the TSS of the present task. In all the tests that were done, the value brought back by STR from within a virtual machine was different to the obtained from a native system, so apparently, it can be used as a another mechanism of a unique instruction in assembler to detect virtual machines. */ BOOL str_trick() { UCHAR mem[4] = { 0, 0, 0, 0 }; #if defined (ENV32BIT) __asm str mem; #endif if ((mem[0] == 0x00) && (mem[1] == 0x40)) return TRUE; // VMWare detected else return FALSE; } /* Check number of cores using WMI */ BOOL number_cores_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_Processor")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; // Iterate over our enumator while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; // Get the value of the Name property hRes = pclsObj->Get(_T("NumberOfCores"), 0, &vtProp, 0, 0); if (SUCCEEDED(hRes)) { if (V_VT(&vtProp) != VT_NULL) { // Do our comparaison if (vtProp.uintVal < 2) { bFound = TRUE; } // release the current result object VariantClear(&vtProp); } } // release class object pclsObj->Release(); // break from while if (bFound) break; } // Cleanup pEnumerator->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); } } return bFound; } /* Filter for removable disk, CD-ROM, network drive or RAM disk */ BOOL checkDriveType(IWbemClassObject* pclsObj) { if (!pclsObj) return FALSE; BOOL res = FALSE; VARIANT vtDriveType; HRESULT hResDriveType; hResDriveType = pclsObj->Get(_T("DriveType"), 0, &vtDriveType, NULL, 0); if (SUCCEEDED(hResDriveType) && V_VT(&vtDriveType) != VT_NULL) { if (vtDriveType.uintVal == 2 // removable disk (USB) || vtDriveType.uintVal == 4 // network drive || vtDriveType.uintVal == 5 // CD-ROM || vtDriveType.uintVal == 6 // RAM disk ) { res = TRUE; } VariantClear(&vtDriveType); } return res; } /* Check hard disk size using WMI */ BOOL disk_size_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; UINT64 minHardDiskSize = (80ULL * (1024ULL * (1024ULL * (1024ULL)))); // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_LogicalDisk")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; // Iterate over our enumator while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; // Don`t check removable disk, network drive CD-ROM and RAM disk if (checkDriveType(pclsObj)) { pclsObj->Release(); continue; } // Get the value of the Name property hRes = pclsObj->Get(_T("Size"), 0, &vtProp, NULL, 0); if (SUCCEEDED(hRes)) { if (V_VT(&vtProp) != VT_NULL) { // convert disk size string to bytes errno = 0; unsigned long long diskSizeBytes = _tcstoui64_l(vtProp.bstrVal, NULL, 10, _get_current_locale()); // do the check only if we successfuly got the disk size if (errno == 0) { // Do our comparison if (diskSizeBytes < minHardDiskSize) { // Less than 80GB bFound = TRUE; } } // release the current result object VariantClear(&vtProp); } } // release class object pclsObj->Release(); // break from while if (bFound) break; } // Cleanup pEnumerator->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); } } return bFound; } /* DeviceIoControl works with disks directly rather than partitions (GetDiskFreeSpaceEx) We can send IOCTL_DISK_GET_LENGTH_INFO code to get the raw byte size of the physical disk */ BOOL dizk_size_deviceiocontrol() { HANDLE hDevice = INVALID_HANDLE_VALUE; BOOL bResult = FALSE; GET_LENGTH_INFORMATION size = { 0 }; DWORD lpBytesReturned = 0; LONGLONG minHardDiskSize = (80LL * (1024LL * (1024LL * (1024LL)))); LARGE_INTEGER totalDiskSize; totalDiskSize.QuadPart = 0LL; // This technique requires admin priviliege starting from Windows Vista if (!IsElevated() && IsWindowsVistaOrGreater()) return FALSE; // This code tries to get the physical disk(s) associated with the drive that Windows is on. // This is not always C:\ or PhysicalDrive0 so we need to do some work to account for multi-disk volumes. // By default we fall back to PhysicalDrive0 if any of this fails. bool defaultToDrive0 = true; // get the Windows system directory wchar_t winDirBuffer[MAX_PATH]; SecureZeroMemory(winDirBuffer, MAX_PATH); UINT winDirLen = GetSystemWindowsDirectory(winDirBuffer, MAX_PATH); if (winDirLen) { // get the drive number (0-25 for A-Z) associated with the directory int driveNumber = PathGetDriveNumber(winDirBuffer); if (driveNumber >= 0) { // convert the drive number to a root path (e.g. C:\) wchar_t driveRootPathBuffer[MAX_PATH]; SecureZeroMemory(driveRootPathBuffer, MAX_PATH); wnsprintf(driveRootPathBuffer, MAX_PATH, _T("\\\\.\\%C:"), _T('A') + driveNumber); // open a handle to the volume HANDLE hVolume = CreateFile( driveRootPathBuffer, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (hVolume != INVALID_HANDLE_VALUE) { DWORD extentSize = 8192; //256 VOLUME_DISK_EXTENTS entries PVOLUME_DISK_EXTENTS diskExtents = NULL; diskExtents = static_cast<PVOLUME_DISK_EXTENTS>(LocalAlloc(LPTR, extentSize)); if (diskExtents) { DWORD dummy = 0; BOOL extentsIoctlOK = DeviceIoControl(hVolume, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, diskExtents, extentSize, &dummy, NULL); if (extentsIoctlOK && diskExtents->NumberOfDiskExtents > 0) { // loop through disks associated with this drive // we want to sum the disk wchar_t physicalPathBuffer[MAX_PATH]; for (DWORD i = 0; i < diskExtents->NumberOfDiskExtents; i++) { if (wnsprintf(physicalPathBuffer, MAX_PATH, _T("\\\\.\\PhysicalDrive%u"), diskExtents->Extents[i].DiskNumber) > 0) { // open the physical disk hDevice = CreateFile( physicalPathBuffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hDevice != INVALID_HANDLE_VALUE) { // fetch the size info bResult = DeviceIoControl( hDevice, // device to be queried IOCTL_DISK_GET_LENGTH_INFO, // operation to perform NULL, 0, // no input buffer &size, sizeof(GET_LENGTH_INFORMATION), &lpBytesReturned, // bytes returned (LPOVERLAPPED)NULL); // synchronous I/O if (bResult) { // add size :) totalDiskSize.QuadPart += size.Length.QuadPart; // we've been successful so far, so let's say it's fine defaultToDrive0 = false; } else { // failed IOCTL call defaultToDrive0 = true; } CloseHandle(hDevice); if (!bResult) break; } else { // failed to open the drive defaultToDrive0 = true; break; } } else { // failed to construct the path string for some reason defaultToDrive0 = true; break; } } } LocalFree(diskExtents); } CloseHandle(hVolume); } } } // for some reason we couldn't enumerate the disks associated with the system drive // so we'll just check PhysicalDrive0 as a backup if (defaultToDrive0) { hDevice = CreateFile(_T("\\\\.\\PhysicalDrive0"), GENERIC_READ, // no access to the drive FILE_SHARE_READ, // share mode NULL, // default security attributes OPEN_EXISTING, // disposition 0, // file attributes NULL); // do not copy file attributes if (hDevice != INVALID_HANDLE_VALUE) { if (DeviceIoControl( hDevice, // device to be queried IOCTL_DISK_GET_LENGTH_INFO, // operation to perform NULL, 0, // no input buffer &size, sizeof(GET_LENGTH_INFORMATION), &lpBytesReturned, // bytes returned (LPOVERLAPPED)NULL)) // synchronous I/O { totalDiskSize.QuadPart = size.Length.QuadPart; } CloseHandle(hDevice); } } if (totalDiskSize.QuadPart < minHardDiskSize) // 80GB bResult = TRUE; else bResult = FALSE; return bResult; } BOOL setupdi_diskdrive() { HDEVINFO hDevInfo; SP_DEVINFO_DATA DeviceInfoData; DWORD i; BOOL bFound = FALSE; // Create a HDEVINFO with all present devices. hDevInfo = SetupDiGetClassDevs((LPGUID)&GUID_DEVCLASS_DISKDRIVE, 0, // Enumerator 0, DIGCF_PRESENT); if (hDevInfo == INVALID_HANDLE_VALUE) return FALSE; // Enumerate through all devices in Set. DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); /* Init some vars */ DWORD dwPropertyRegDataType; LPTSTR buffer = NULL; DWORD dwSize = 0; for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++) { while (!SetupDiGetDeviceRegistryProperty(hDevInfo, &DeviceInfoData, SPDRP_HARDWAREID, &dwPropertyRegDataType, (PBYTE)buffer, dwSize, &dwSize)) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // Change the buffer size. if (buffer)LocalFree(buffer); // Double the size to avoid problems on // W2k MBCS systems per KB 888609. buffer = (LPTSTR)LocalAlloc(LPTR, dwSize * 2); if (buffer == NULL) break; } else break; } if (buffer) { // Do our comparison if ((StrStrI(buffer, _T("vbox")) != NULL) || (StrStrI(buffer, _T("vmware")) != NULL) || (StrStrI(buffer, _T("qemu")) != NULL) || (StrStrI(buffer, _T("virtual")) != NULL)) { bFound = TRUE; break; } } } if (buffer) LocalFree(buffer); // Cleanup SetupDiDestroyDeviceInfoList(hDevInfo); if (GetLastError() != NO_ERROR && GetLastError() != ERROR_NO_MORE_ITEMS) return FALSE; return bFound; } /* Check if there is any mouse movement in the sandbox. */ BOOL mouse_movement() { POINT positionA = {}; POINT positionB = {}; /* Retrieve the position of the mouse cursor, in screen coordinates */ GetCursorPos(&positionA); /* Wait a moment */ Sleep(5000); /* Retrieve the poition gain */ GetCursorPos(&positionB); if ((positionA.x == positionB.x) && (positionA.y == positionB.y)) /* Probably a sandbox, because mouse position did not change. */ return TRUE; else return FALSE; } /* Check for the lack of user input. This version is slightly different from the original: https://www.lastline.com/labsblog/malware-evasion-techniques/ It does not run inside an infinite loop (preventing al-khaser to get stuck) */ BOOL lack_user_input() { int correct_idle_time_counter = 0; DWORD current_tick_count = 0, idle_time = 0; LASTINPUTINFO last_input_info; // Contains the time of the last input last_input_info.cbSize = sizeof(LASTINPUTINFO); for (int i = 0; i < 128; ++i) { Sleep(0xb); // Retrieves the time of the last input event if (GetLastInputInfo(&last_input_info)) { current_tick_count = GetTickCount(); if (current_tick_count < last_input_info.dwTime) // impossible case unless GetTickCount is manipulated return TRUE; if (current_tick_count - last_input_info.dwTime < 100) { correct_idle_time_counter++; if (correct_idle_time_counter >= 10) return FALSE; } } else // GetLastInputInfo must not fail return TRUE; } return TRUE; } /* Check if the machine have enough memory space, usually VM get a small ammount, one reason if because several VMs are running on the same servers so they can run more tasks at the same time. */ BOOL memory_space() { DWORDLONG ullMinRam = (1024LL * (1024LL * (1024LL * 1LL))); // 1GB MEMORYSTATUSEX statex = { 0 }; statex.dwLength = sizeof(statex); GlobalMemoryStatusEx(&statex); return (statex.ullTotalPhys < ullMinRam) ? TRUE : FALSE; } /* This trick consists of getting information about total amount of space. This can be used to expose a sandbox. */ BOOL disk_size_getdiskfreespace() { ULONGLONG minHardDiskSize = (80ULL * (1024ULL * (1024ULL * (1024ULL)))); LPCWSTR pszDrive = NULL; BOOL bStatus = FALSE; // 64 bits integer, low and high bytes ULARGE_INTEGER totalNumberOfBytes; // If the function succeeds, the return value is nonzero. If the function fails, the return value is 0 (zero). bStatus = GetDiskFreeSpaceEx(pszDrive, NULL, &totalNumberOfBytes, NULL); if (bStatus) { if (totalNumberOfBytes.QuadPart < minHardDiskSize) // 80GB return TRUE; } return FALSE;; } /* Sleep and check if time have been accelerated */ BOOL accelerated_sleep() { DWORD dwStart = 0, dwEnd = 0, dwDiff = 0; DWORD dwMillisecondsToSleep = 60 * 1000; /* Retrieves the number of milliseconds that have elapsed since the system was started */ dwStart = GetTickCount(); /* Let's sleep 1 minute so Sandbox is interested to patch that */ Sleep(dwMillisecondsToSleep); /* Do it again */ dwEnd = GetTickCount(); /* If the Sleep function was patched*/ dwDiff = dwEnd - dwStart; if (dwDiff > dwMillisecondsToSleep - 1000) // substracted 1s just to be sure return FALSE; else return TRUE; } /* The CPUID instruction is a processor supplementary instruction (its name derived from CPU IDentification) for the x86 architecture allowing software to discover details of the processor. By calling CPUID with EAX =1, The 31bit of ECX register if set will reveal the precense of a hypervisor. */ BOOL cpuid_is_hypervisor() { INT CPUInfo[4] = { -1 }; /* Query hypervisor precense using CPUID (EAX=1), BIT 31 in ECX */ __cpuid(CPUInfo, 1); if ((CPUInfo[2] >> 31) & 1) return TRUE; else return FALSE; } /* If HV presence confirmed then it is good to know which type of hypervisor we have When CPUID is called with EAX=0x40000000, cpuid return the hypervisor signature. */ BOOL cpuid_hypervisor_vendor() { INT CPUInfo[4] = { -1 }; CHAR szHypervisorVendor[0x40]; WCHAR *pwszConverted; BOOL bResult = FALSE; const TCHAR* szBlacklistedHypervisors[] = { _T("KVMKVMKVM\0\0\0"), /* KVM */ _T("Microsoft Hv"), /* Microsoft Hyper-V or Windows Virtual PC */ _T("VMwareVMware"), /* VMware */ _T("XenVMMXenVMM"), /* Xen */ _T("prl hyperv "), /* Parallels */ _T("VBoxVBoxVBox"), /* VirtualBox */ }; WORD dwlength = sizeof(szBlacklistedHypervisors) / sizeof(szBlacklistedHypervisors[0]); // __cpuid with an InfoType argument of 0 returns the number of // valid Ids in CPUInfo[0] and the CPU identification string in // the other three array elements. The CPU identification string is // not in linear order. The code below arranges the information // in a human readable form. __cpuid(CPUInfo, 0x40000000); memset(szHypervisorVendor, 0, sizeof(szHypervisorVendor)); memcpy(szHypervisorVendor, CPUInfo + 1, 12); for (int i = 0; i < dwlength; i++) { pwszConverted = ascii_to_wide_str(szHypervisorVendor); if (pwszConverted) { bResult = (_tcscmp(pwszConverted, szBlacklistedHypervisors[i]) == 0); free(pwszConverted); if (bResult) return TRUE; } } return FALSE; } /* Check SerialNumber devices using WMI */ BOOL serial_number_bios_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_BIOS")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; // Get the value of the Name property hRes = pclsObj->Get(_T("SerialNumber"), 0, &vtProp, 0, 0); if (SUCCEEDED(hRes)) { if (vtProp.vt == VT_BSTR) { // Do our comparison if ( (StrStrI(vtProp.bstrVal, _T("VMWare")) != 0) || (wcscmp(vtProp.bstrVal, _T("0")) == 0) || // VBox (serial is just "0") (StrStrI(vtProp.bstrVal, _T("Xen")) != 0) || (StrStrI(vtProp.bstrVal, _T("Virtual")) != 0) || (StrStrI(vtProp.bstrVal, _T("A M I")) != 0) ) { VariantClear(&vtProp); pclsObj->Release(); bFound = TRUE; break; } } VariantClear(&vtProp); } // release the current result object pclsObj->Release(); } // Cleanup pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); } } return bFound; } /* Check Model from ComputerSystem using WMI */ BOOL model_computer_system_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_ComputerSystem")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; // Get the value of the Name property hRes = pclsObj->Get(_T("Model"), 0, &vtProp, 0, 0); if (SUCCEEDED(hRes)) { if (vtProp.vt == VT_BSTR) { // Do our comparison if ( (StrStrI(vtProp.bstrVal, _T("VirtualBox")) != 0) || (StrStrI(vtProp.bstrVal, _T("HVM domU")) != 0) || //Xen (StrStrI(vtProp.bstrVal, _T("VMWare")) != 0) ) { VariantClear(&vtProp); pclsObj->Release(); bFound = TRUE; break; } } VariantClear(&vtProp); } // release the current result object pclsObj->Release(); } // Cleanup pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); } } return bFound; } /* Check Manufacturer from ComputerSystem using WMI */ BOOL manufacturer_computer_system_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_ComputerSystem")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; // Get the value of the Name property hRes = pclsObj->Get(_T("Manufacturer"), 0, &vtProp, 0, 0); if (SUCCEEDED(hRes)) { if (vtProp.vt == VT_BSTR) { // Do our comparison if ( (StrStrI(vtProp.bstrVal, _T("VMWare")) != 0) || (StrStrI(vtProp.bstrVal, _T("Xen")) != 0) || (StrStrI(vtProp.bstrVal, _T("innotek GmbH")) != 0) || // Vbox (StrStrI(vtProp.bstrVal, _T("QEMU")) != 0) ) { VariantClear(&vtProp); pclsObj->Release(); bFound = TRUE; break; } } VariantClear(&vtProp); } // release the current result object pclsObj->Release(); } // Cleanup pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); } } return bFound; } /* Check Current Temperature using WMI, this requires admin privileges In my tests, it works against vbox, vmware, kvm and xen. */ BOOL current_temperature_acpi_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; // This technique required admin priviliege if (!IsElevated()) return FALSE; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("root\\WMI")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM MSAcpi_ThermalZoneTemperature")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { bFound = TRUE; break; } // Get the value of the Name property hRes = pclsObj->Get(_T("CurrentTemperature"), 0, &vtProp, 0, 0); if (SUCCEEDED(hRes)) { VariantClear(&vtProp); pclsObj->Release(); break; } // release the current result object VariantClear(&vtProp); pclsObj->Release(); } // Cleanup pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); } } return bFound; } /* Check ProcessId from Win32_Processor using WMI KVM, XEN anv VMWare seems to return something, VBOX return NULL */ BOOL process_id_processor_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_Processor")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; // Get the value of the Name property hRes = pclsObj->Get(_T("ProcessorId"), 0, &vtProp, 0, 0); if (SUCCEEDED(hRes)) { // Do our comparison if (vtProp.bstrVal == NULL) { bFound = TRUE; } } // release the current result object VariantClear(&vtProp); pclsObj->Release(); // break from while if (bFound) break; } // Cleanup pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); } } return bFound; } /* Check what power states are enabled. Most VMs don't support S1-S4 power states whereas most hardware does, and thermal control is usually not found either. This has been tested on VirtualBox and Hyper-V, as well as a physical desktop and laptop. */ BOOL power_capabilities() { SYSTEM_POWER_CAPABILITIES powerCaps; BOOL bFound = FALSE; if (GetPwrCapabilities(&powerCaps) == TRUE) { if ((powerCaps.SystemS1 | powerCaps.SystemS2 | powerCaps.SystemS3 | powerCaps.SystemS4) == FALSE) { bFound = (powerCaps.ThermalControl == FALSE); } } return bFound; } /* According to MSDN, this query should return a class that provides statistics on the CPU fan. Win32/OilRig checks to see if the result of this query returned a class with more than 0 elements, which would most likely be true in a non-virtual environment. */ BOOL cpu_fan_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; ULONG uObjCount = 0; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_Fan")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { break; } else { uObjCount++; pclsObj->Release(); } } // Cleanup pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); } } if (uObjCount == 0) bFound = TRUE; return bFound; } /* Check Caption from VideoController using WMI */ BOOL caption_video_controller_wmi() { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; BOOL bFound = FALSE; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_VideoController")); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; VARIANT vtProp; while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; // Get the value of the Name property hRes = pclsObj->Get(_T("Caption"), 0, &vtProp, 0, 0); if (SUCCEEDED(hRes)) { if (vtProp.vt == VT_BSTR) { // Do our comparison if ( (StrStrI(vtProp.bstrVal, _T("Hyper-V")) != 0) || (StrStrI(vtProp.bstrVal, _T("VMWare")) != 0) ) { VariantClear(&vtProp); pclsObj->Release(); bFound = TRUE; break; } } VariantClear(&vtProp); } // release the current result object pclsObj->Release(); } // Cleanup pSvc->Release(); pLoc->Release(); pEnumerator->Release(); CoUninitialize(); } } return bFound; } /* Detect Virtual machine by calling NtQueryLicenseValue with Kernel-VMDetection-Private as license value. This detection works on Windows 7 and does not detect Microsoft Hypervisor. */ BOOL query_license_value() { auto RtlInitUnicodeString = static_cast<pRtlInitUnicodeString>(API::GetAPI(API_IDENTIFIER::API_RtlInitUnicodeString)); auto NtQueryLicenseValue = static_cast<pNtQueryLicenseValue>(API::GetAPI(API_IDENTIFIER::API_NtQueryLicenseValue)); if (RtlInitUnicodeString == nullptr || NtQueryLicenseValue == nullptr) return FALSE; UNICODE_STRING LicenseValue; RtlInitUnicodeString(&LicenseValue, L"Kernel-VMDetection-Private"); ULONG Result = 0, ReturnLength; NTSTATUS Status = NtQueryLicenseValue(&LicenseValue, NULL, reinterpret_cast<PVOID>(&Result), sizeof(ULONG), &ReturnLength); if (NT_SUCCESS(Status)) { return (Result != 0); } return FALSE; } int wmi_query_count(const _TCHAR* query) { IWbemServices *pSvc = NULL; IWbemLocator *pLoc = NULL; IEnumWbemClassObject* pEnumerator = NULL; BOOL bStatus = FALSE; HRESULT hRes; int count = 0; // Init WMI bStatus = InitWMI(&pSvc, &pLoc, _T("ROOT\\CIMV2")); if (bStatus) { // If success, execute the desired query bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, query); if (bStatus) { // Get the data from the query IWbemClassObject *pclsObj = NULL; ULONG uReturn = 0; // Iterate over our enumator while (pEnumerator) { hRes = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) break; count++; pclsObj->Release(); } // Cleanup pEnumerator->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); } else { pSvc->Release(); pLoc->Release(); CoUninitialize(); } } else return -1; return count; } /* Check Win32_CacheMemory for entries */ BOOL cachememory_wmi() { int count = wmi_query_count(_T("SELECT * FROM Win32_CacheMemory")); if (count == 0) { return TRUE; } return FALSE; } /* Check Win32_PhysicalMemory for entries */ BOOL physicalmemory_wmi() { int count = wmi_query_count(_T("SELECT * FROM Win32_PhysicalMemory")); if (count == 0) { return TRUE; } return FALSE; } /* Check Win32_MemoryDevice for entries */ BOOL memorydevice_wmi() { int count = wmi_query_count(_T("SELECT * FROM Win32_MemoryDevice")); if (count == 0) { return TRUE; } return FALSE; } /* Check Win32_MemoryArray for entries */ BOOL memoryarray_wmi() { int count = wmi_query_count(_T("SELECT * FROM Win32_MemoryArray")); if (count == 0) { return TRUE; } return FALSE; } /* Check Win32_VoltageProbe for entries */ BOOL voltageprobe_wmi() { int count = wmi_query_count(_T("SELECT * FROM Win32_VoltageProbe")); if (count == 0) { return TRUE; } return FALSE; } /* Check Win32_PortConnector for entries */ BOOL portconnector_wmi() { int count = wmi_query_count(_T("SELECT * FROM Win32_PortConnector")); if (count == 0) { return TRUE; } return FALSE; } /* Check Win32_SMBIOSMemory for entries */ BOOL smbiosmemory_wmi() { int count = wmi_query_count(_T("SELECT * FROM Win32_SMBIOSMemory")); if (count == 0) { return TRUE; } return FALSE; } /* Check Win32_PerfFormattedData_Counters_ThermalZoneInformation for entries */ BOOL perfctrs_thermalzoneinfo_wmi() { int count = wmi_query_count(_T("SELECT * FROM Win32_PerfFormattedData_Counters_ThermalZoneInformation")); if (count == 0) { return TRUE; } return FALSE; } /* Check CIM_Memory for entries */ BOOL cim_memory_wmi() { int count = wmi_query_count(_T("SELECT * FROM CIM_Memory")); if (count == 0) { return TRUE; } return FALSE; } /* Check CIM_NumericSensor for entries */ BOOL cim_numericsensor_wmi() { int count = wmi_query_count(_T("SELECT * FROM CIM_NumericSensor")); if (count == 0) { return TRUE; } return FALSE; } /* Check CIM_PhysicalConnector for entries */ BOOL cim_physicalconnector_wmi() { int count = wmi_query_count(_T("SELECT * FROM CIM_PhysicalConnector")); if (count == 0) { return TRUE; } return FALSE; } /* Check CIM_Sensor for entries */ BOOL cim_sensor_wmi() { int count = wmi_query_count(_T("SELECT * FROM CIM_Sensor")); if (count == 0) { return TRUE; } return FALSE; } /* Check CIM_Slot for entries */ BOOL cim_slot_wmi() { int count = wmi_query_count(_T("SELECT * FROM CIM_Slot")); if (count == 0) { return TRUE; } return FALSE; } /* Check CIM_TemperatureSensor for entries */ BOOL cim_temperaturesensor_wmi() { int count = wmi_query_count(_T("SELECT * FROM CIM_TemperatureSensor")); if (count == 0) { return TRUE; } return FALSE; } /* Check CIM_VoltageSensor for entries */ BOOL cim_voltagesensor_wmi() { int count = wmi_query_count(_T("SELECT * FROM CIM_VoltageSensor")); if (count == 0) { return TRUE; } return FALSE; } /* Checks whether the specified application is a genuine Windows installation. */ #define WINDOWS_SLID \ { 0x55c92734, \ 0xd682, \ 0x4d71, \ { 0x98, 0x3e, 0xd6, 0xec, 0x3f, 0x16, 0x05, 0x9f } \ } BOOL pirated_windows() { CONST SLID AppId = WINDOWS_SLID; SL_GENUINE_STATE GenuineState; HRESULT hResult; hResult = SLIsGenuineLocal(&AppId, &GenuineState, NULL); if (hResult == S_OK) { if (GenuineState != SL_GEN_STATE_IS_GENUINE) { return TRUE; } } return FALSE; } /* Check HKLM\System\CurrentControlSet\Services\Disk\Enum for values related * to virtual machines. */ BOOL registry_services_disk_enum() { HKEY hkResult = NULL; const TCHAR* diskEnumKey = _T("System\\CurrentControlSet\\Services\\Disk\\Enum"); DWORD diskCount = 0; DWORD cbData = sizeof(diskCount); const TCHAR* szChecks[] = { /* Checked for by Smokeloader * https://research.checkpoint.com/2019-resurgence-of-smokeloader/*/ _T("qemu"), _T("virtio"), _T("vmware"), _T("vbox"), _T("xen"), /* Checked for by Kutaki (not including ones from above) * https://cofense.com/kutaki-malware-bypasses-gateways-steal-users-credentials/ */ _T("VMW"), _T("Virtual"), }; WORD dwChecksLength = sizeof(szChecks) / sizeof(szChecks[0]); BOOL bFound = FALSE; /* Each disk has a corresponding value where the value name starts at '0' for * the first disk and increases by 1 for each subsequent disk. The 'Count' * value appears to store the total number of disk entries.*/ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, diskEnumKey, NULL, KEY_READ, &hkResult) == ERROR_SUCCESS) { if (RegQueryValueEx(hkResult, _T("Count"), NULL, NULL, (LPBYTE)&diskCount, &cbData) != ERROR_SUCCESS) { RegCloseKey(hkResult); return bFound; } RegCloseKey(hkResult); } for (unsigned int i = 0; i < diskCount; i++) { TCHAR subkey[11]; _stprintf_s(subkey, sizeof(subkey) / sizeof(subkey[0]), _T("%d"), i); for (unsigned int j = 0; j < dwChecksLength; j++) { //_tprintf(_T("Checking %s %s for %s (%d)\n"), diskEnumKey, subkey, szChecks[j], diskCount); if (Is_RegKeyValueExists(HKEY_LOCAL_MACHINE, diskEnumKey, subkey, szChecks[j])) { bFound = TRUE; break; } } if (bFound) { break; } } return bFound; } BOOL registry_disk_enum() { HKEY hkResult = NULL; const TCHAR* szEntries[] = { _T("System\\CurrentControlSet\\Enum\\IDE"), _T("System\\CurrentControlSet\\Enum\\SCSI"), }; const TCHAR* szChecks[] = { /* Checked for by Smokeloader * https://research.checkpoint.com/2019-resurgence-of-smokeloader/*/ _T("qemu"), _T("virtio"), _T("vmware"), _T("vbox"), _T("xen"), /* Checked for by Kutaki (not including ones from above) * https://cofense.com/kutaki-malware-bypasses-gateways-steal-users-credentials/ */ _T("VMW"), _T("Virtual"), }; WORD dwEntriesLength = sizeof(szEntries) / sizeof(szEntries[0]); WORD dwChecksLength = sizeof(szChecks) / sizeof(szChecks[0]); BOOL bFound = FALSE; for (unsigned int i = 0; i < dwEntriesLength; i++) { DWORD cSubKeys = 0; DWORD cbMaxSubKeyLen = 0; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szEntries[i], NULL, KEY_READ, &hkResult) != ERROR_SUCCESS) { continue; } if (RegQueryInfoKey(hkResult, NULL, NULL, NULL, &cSubKeys, &cbMaxSubKeyLen, NULL, NULL, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { RegCloseKey(hkResult); continue; } DWORD subKeyBufferLen = (cbMaxSubKeyLen + 1) * sizeof(TCHAR); TCHAR* subKeyBuffer = (TCHAR *)malloc(subKeyBufferLen); if (!subKeyBuffer) { RegCloseKey(hkResult); continue; } for (unsigned int j = 0; j < cSubKeys; j++) { DWORD cchName = subKeyBufferLen; if (RegEnumKeyEx(hkResult, j, subKeyBuffer, &cchName, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { continue; } for (unsigned int k = 0; k < dwChecksLength; k++) { //_tprintf(_T("Checking %s %s for %s (%d)\n"), szEntries[i], subKeyBuffer, szChecks[k], cSubKeys); if (StrStrI(subKeyBuffer, szChecks[k]) != NULL) { bFound = TRUE; break; } } if (bFound) { break; } } free(subKeyBuffer); RegCloseKey(hkResult); if (bFound) { break; } } return bFound; } BOOL handle_one_table(BYTE* currentPosition, UINT& bias, BYTE* smBiosTableBoundary) { struct SmbiosTableHeader { BYTE type; // Table type BYTE length; // Length of the table WORD handle; // Handle of the table }; SmbiosTableHeader* tableHeader = reinterpret_cast<SmbiosTableHeader*>(currentPosition); SmbiosTableHeader* tableBoundary = reinterpret_cast<SmbiosTableHeader*>(smBiosTableBoundary); const BYTE lastEntry = 127; if (tableHeader->type == lastEntry) { // End of tables reached return TRUE; } currentPosition += tableHeader->length; UINT i = 0; // Find the end of the table while (!(currentPosition[i] == 0 && currentPosition[i + 1] == 0) && (currentPosition + i + 1 < smBiosTableBoundary)) { i++; } //pair of terminal zeros i += 2; bias = i + tableHeader->length; return FALSE; } BOOL check_tables_number(const PBYTE smbios) { struct RawSMBIOSData { BYTE method; // Access method(obsolete) BYTE mjVer; // Major part of the SMB version(major) BYTE mnVer; // Minor part of the SMB version(minor) BYTE dmiRev; // DMI version(obsolete) DWORD length; // Data table size BYTE tableData[]; // Table data }; RawSMBIOSData* smBiosData = reinterpret_cast<RawSMBIOSData*>(smbios); BYTE* smBiosTableBoundary = smBiosData->tableData + smBiosData->length; BYTE* currentPosition = smBiosData->tableData; UINT tableNumber = 0; while (currentPosition < smBiosTableBoundary) { UINT biasNewTable = 0; tableNumber++; if (handle_one_table(currentPosition, biasNewTable, smBiosTableBoundary)) { break; } currentPosition += biasNewTable; } const UINT tableMinReal = 40; if (tableNumber <= tableMinReal) { return TRUE; } return FALSE; } /* Check for SMBIOS tables number */ BOOL number_SMBIOS_tables() { BOOL result = FALSE; DWORD smbiosSize = 0; PBYTE smbios = get_system_firmware(static_cast<DWORD>('RSMB'), 0x0000, &smbiosSize); if (smbios != NULL) { result = check_tables_number(smbios); free(smbios); } return result; }
49,194
C++
.cpp
1,744
24.948968
138
0.677868
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,063
VirtualPC.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/VirtualPC.cpp
#include "pch.h" #include "VirtualPC.h" /* Check for process list */ VOID virtual_pc_process() { const TCHAR *szProcesses[] = { _T("VMSrvc.exe"), _T("VMUSrvc.exe"), }; WORD iLength = sizeof(szProcesses) / sizeof(szProcesses[0]); for (int i = 0; i < iLength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking Virtual PC processes %s "), szProcesses[i]); if (GetProcessIdFromName(szProcesses[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } } VOID virtual_pc_reg_keys() { /* Array of strings of blacklisted registry keys */ const TCHAR* szKeys[] = { _T("SOFTWARE\\Microsoft\\Virtual Machine\\Guest\\Parameters"), }; WORD dwlength = sizeof(szKeys) / sizeof(szKeys[0]); /* Check one by one */ for (int i = 0; i < dwlength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking reg key %s "), szKeys[i]); if (Is_RegKeyExists(HKEY_LOCAL_MACHINE, szKeys[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } }
1,065
C++
.cpp
40
24.2
105
0.661417
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,064
HyperV.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/HyperV.cpp
#include "pch.h" #include "HyperV.h" BOOL check_hyperv_driver_objects() { auto driverList = enumerate_object_directory(L"\\Driver"); if (driverList == nullptr) { return FALSE; } for (wchar_t* driver : *driverList) { if (StrCmpCW(driver, L"VMBusHID") == 0) { return TRUE; } if (StrCmpCW(driver, L"vmbus") == 0) { return TRUE; } if (StrCmpCW(driver, L"vmgid") == 0) { return TRUE; } if (StrCmpCW(driver, L"IndirectKmd") == 0) { return TRUE; } if (StrCmpCW(driver, L"HyperVideo") == 0) { return TRUE; } if (StrCmpCW(driver, L"hyperkbd") == 0) { return TRUE; } } return FALSE; } BOOL check_hyperv_global_objects() { auto globalObjs = enumerate_object_directory(L"\\GLOBAL??"); if (globalObjs == nullptr) { return FALSE; } for (wchar_t* globalObj : *globalObjs) { if (StrStrW(globalObj, L"VMBUS#") != NULL) { return TRUE; } if (StrCmpCW(globalObj, L"VDRVROOT") == 0) { return TRUE; } if (StrCmpCW(globalObj, L"VmGenerationCounter") == 0) { return TRUE; } if (StrCmpCW(globalObj, L"VmGid") == 0) { return TRUE; } } return FALSE; }
1,139
C++
.cpp
66
14.530303
61
0.63985
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,065
Qemu.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/Qemu.cpp
#include "pch.h" #include "Qemu.h" /* Registry key values */ VOID qemu_reg_key_value() { /* Array of strings of blacklisted registry key values */ const TCHAR *szEntries[][3] = { { _T("HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 0\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0"), _T("Identifier"), _T("QEMU") }, { _T("HARDWARE\\Description\\System"), _T("SystemBiosVersion"), _T("QEMU") }, }; WORD dwLength = sizeof(szEntries) / sizeof(szEntries[0]); for (int i = 0; i < dwLength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking reg key %s "), szEntries[i][0]); if (Is_RegKeyValueExists(HKEY_LOCAL_MACHINE, szEntries[i][0], szEntries[i][1], szEntries[i][2])) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check for process list */ VOID qemu_processes() { const TCHAR *szProcesses[] = { _T("qemu-ga.exe"), // QEMU guest agent. _T("vdagent.exe"), // SPICE guest tools. _T("vdservice.exe"), // SPICE guest tools. }; WORD iLength = sizeof(szProcesses) / sizeof(szProcesses[0]); for (int i = 0; i < iLength; i++) { TCHAR msg[256] = _T(""); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking qemu processes %s "), szProcesses[i]); if (GetProcessIdFromName(szProcesses[i])) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check against blacklisted directories. */ VOID qemu_dir() { TCHAR szProgramFile[MAX_PATH]; TCHAR szPath[MAX_PATH] = _T(""); const TCHAR* szDirectories[] = { _T("qemu-ga"), // QEMU guest agent. _T("SPICE Guest Tools"), // SPICE guest tools. }; WORD iLength = sizeof(szDirectories) / sizeof(szDirectories[0]); for (int i = 0; i < iLength; i++) { TCHAR msg[256] = _T(""); if (IsWoW64()) ExpandEnvironmentStrings(_T("%ProgramW6432%"), szProgramFile, ARRAYSIZE(szProgramFile)); else SHGetSpecialFolderPath(NULL, szProgramFile, CSIDL_PROGRAM_FILES, FALSE); PathCombine(szPath, szProgramFile, szDirectories[i]); _stprintf_s(msg, sizeof(msg) / sizeof(TCHAR), _T("Checking QEMU directory %s "), szPath); if (is_DirectoryExists(szPath)) print_results(TRUE, msg); else print_results(FALSE, msg); } } /* Check for SMBIOS firmware */ BOOL qemu_firmware_SMBIOS() { BOOL result = FALSE; DWORD smbiosSize = 0; PBYTE smbios = get_system_firmware(static_cast<DWORD>('RSMB'), 0x0000, &smbiosSize); if (smbios != NULL) { PBYTE qemuString1 = (PBYTE)"qemu"; size_t StringLen = 4; PBYTE qemuString2 = (PBYTE)"QEMU"; if (find_str_in_data(qemuString1, StringLen, smbios, smbiosSize) || find_str_in_data(qemuString2, StringLen, smbios, smbiosSize)) { result = TRUE; } free(smbios); } return result; } /* Check for ACPI firmware */ BOOL qemu_firmware_ACPI() { BOOL result = FALSE; PDWORD tableNames = static_cast<PDWORD>(malloc(4096)); if (tableNames) { SecureZeroMemory(tableNames, 4096); DWORD tableSize = enum_system_firmware_tables(static_cast<DWORD>('ACPI'), tableNames, 4096); // API not available if (tableSize == -1) return FALSE; DWORD tableCount = tableSize / 4; if (tableSize < 4 || tableCount == 0) { result = TRUE; } else { for (DWORD i = 0; i < tableCount; i++) { DWORD tableSize = 0; PBYTE table = get_system_firmware(static_cast<DWORD>('ACPI'), tableNames[i], &tableSize); if (table) { PBYTE qemuString1 = (PBYTE)"BOCHS"; size_t StringLen = 4; PBYTE qemuString2 = (PBYTE)"BXPC"; if (find_str_in_data(qemuString1, StringLen, table, tableSize) || find_str_in_data(qemuString2, StringLen, table, tableSize)) { result = TRUE; } free(table); } } } free(tableNames); } return result; }
3,720
C++
.cpp
134
24.850746
125
0.671453
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,066
Services.cpp
LordNoteworthy_al-khaser/al-khaser/AntiVM/Services.cpp
#include "pch.h" #include "Services.h" BOOL VMDriverServices() { const int KnownServiceCount = 13; const TCHAR* KnownVMServices[KnownServiceCount] = { L"VBoxWddm", L"VBoxSF", //VirtualBox Shared Folders L"VBoxMouse", //VirtualBox Guest Mouse L"VBoxGuest", //VirtualBox Guest Driver L"vmci", //VMWare VMCI Bus Driver L"vmhgfs", //VMWare Host Guest Control Redirector L"vmmouse", L"vmmemctl", //VMWare Guest Memory Controller Driver L"vmusb", L"vmusbmouse", L"vmx_svga", L"vmxnet", L"vmx86" }; SC_HANDLE hSCM = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT | SC_MANAGER_ENUMERATE_SERVICE); if (hSCM != NULL) { ENUM_SERVICE_STATUS_PROCESS* services = NULL; DWORD serviceCount = 0; if (get_services(hSCM, SERVICE_DRIVER, &services, &serviceCount)) { bool ok = true; for (DWORD i = 0; i < serviceCount; i++) { for (int s = 0; s < KnownServiceCount; s++) { if (StrCmpIW(services[i].lpServiceName, KnownVMServices[s]) == 0) { ok = false; break; } } } free(services); if (ok) { CloseServiceHandle(hSCM); return FALSE; } } else { printf("Failed to get services list.\n"); } CloseServiceHandle(hSCM); } else { printf("Failed to get SCM handle.\n"); } return TRUE; } BOOL get_services(_In_ SC_HANDLE hServiceManager, _In_ DWORD serviceType, _Out_ ENUM_SERVICE_STATUS_PROCESS** servicesBuffer, _Out_ DWORD* serviceCount) { DWORD serviceBufferSize = 1024 * sizeof(ENUM_SERVICE_STATUS_PROCESS); ENUM_SERVICE_STATUS_PROCESS* services = static_cast<ENUM_SERVICE_STATUS_PROCESS*>(malloc(serviceBufferSize)); if (serviceCount) //assume failure *serviceCount = 0; if (services) { SecureZeroMemory(services, serviceBufferSize); DWORD remainderBufferSize = 0; DWORD resumeHandle = 0; if (EnumServicesStatusEx(hServiceManager, SC_ENUM_PROCESS_INFO, serviceType, SERVICE_STATE_ALL, (LPBYTE)services, serviceBufferSize, &remainderBufferSize, serviceCount, &resumeHandle, NULL) != 0) { // success and we enumerated all the services *servicesBuffer = services; return TRUE; } DWORD lastError = GetLastError(); if (lastError == ERROR_MORE_DATA) { // we didn't get all the services, so we'll just re-enumerate all to make things easy serviceBufferSize += remainderBufferSize; ENUM_SERVICE_STATUS_PROCESS* tmp; tmp = static_cast<ENUM_SERVICE_STATUS_PROCESS*>(realloc(services, serviceBufferSize)); if (tmp) { services = tmp; SecureZeroMemory(services, serviceBufferSize); if (EnumServicesStatusEx(hServiceManager, SC_ENUM_PROCESS_INFO, serviceType, SERVICE_STATE_ALL, (LPBYTE)services, serviceBufferSize, &remainderBufferSize, serviceCount, NULL, NULL) != 0) { *servicesBuffer = services; return TRUE; } } } else { printf("ERROR: %u\n", lastError); } free(services); } return FALSE; }
2,925
C++
.cpp
99
26.020202
197
0.713878
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,070
log.cpp
LordNoteworthy_al-khaser/al-khaser/Shared/log.cpp
#include "pch.h" #include "log.h" static int SESSION_TRACKER; //Keeps track of session TCHAR* print_time() { size_t size = 0; TCHAR *buf; errno_t err; TCHAR timestr[32]; /* get current calendar time */ time_t const sourceTime = time(NULL); tm tmDest = { 0 }; err = localtime_s(&tmDest, &sourceTime); if (err) { print_last_error(_T("localtime_s")); exit(1); } // Converts a time_t time value to a tm structure, and corrects for the local time zone. err = _tasctime_s(timestr, 32, &tmDest); if (err) { print_last_error(_T("_tasctime_s")); exit(1); } //Getting rid of \n timestr[_tcsclen(timestr) - 1] = 0; //Additional +2 for square braces size = (_tcsclen(timestr) + 1 + 2) * sizeof(TCHAR); buf = (TCHAR*)malloc(size); if (buf) { memset(buf, 0x0, size); _stprintf_s(buf, size / sizeof(TCHAR), _T("[%s]"), timestr); } return buf; } void log_print(const TCHAR* filename, const TCHAR *fmt, ...) { va_list list; const TCHAR *p, *r; int e; FILE *fp = NULL; errno_t error; TCHAR *pszTime; if (SESSION_TRACKER > 0) error = _tfopen_s(&fp, _T("log.txt"), _T("a+")); else error = _tfopen_s(&fp, _T("log.txt"), _T("w")); // file create/open failed if ((error != 0) || (fp == NULL)) return; pszTime = print_time(); if (pszTime) { _ftprintf(fp, _T("%s "), pszTime); free(pszTime); } va_start(list, fmt); for (p = fmt; *p; ++p) { if (*p != '%')//If simple string fputc(*p, fp); else { switch (*++p) { /* string */ case 's': { r = va_arg(list, TCHAR *); _ftprintf(fp, _T("%s"), r); continue; } /* integer */ case 'd': { e = va_arg(list, int); _ftprintf(fp, _T("%d"), e); continue; } default: fputc(*p, fp); } } } va_end(list); fputc('\n', fp); SESSION_TRACKER++; fclose(fp); }
1,822
C++
.cpp
89
17.662921
90
0.592312
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,072
APIs.cpp
LordNoteworthy_al-khaser/al-khaser/Shared/APIs.cpp
#include "pch.h" #include "APIs.h" #define API_COUNT (sizeof(ApiData)/sizeof(*ApiData)) API_DATA ApiData[] = { /* Identifier Library Export Name X86/X64/either Minimum OS Version Removed in OS Version */ { API_IDENTIFIER::API_CsrGetProcessId, "ntdll.dll", "CsrGetProcessId", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, /* the EnumProcessModulesEx API was moved from psapi.dll into kernel32.dll for Windows 7, then back out afterwards, so we need both versions. */ { API_IDENTIFIER::API_EnumProcessModulesEx_Kernel, "kernel32.dll", "EnumProcessModulesEx", API_OS_BITS::ANY, API_OS_VERSION::WIN_7, API_OS_VERSION::WIN_80 }, { API_IDENTIFIER::API_EnumProcessModulesEx_PSAPI, "psapi.dll", "EnumProcessModulesEx", API_OS_BITS::ANY, API_OS_VERSION::WIN_VISTA, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_EnumSystemFirmwareTables, "kernel32.dll", "EnumSystemFirmwareTables", API_OS_BITS::ANY, API_OS_VERSION::WIN_VISTA, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_GetActiveProcessorCount, "kernel32.dll", "GetActiveProcessorCount", API_OS_BITS::ANY, API_OS_VERSION::WIN_7, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_GetNativeSystemInfo, "kernel32.dll", "GetNativeSystemInfo", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_GetProductInfo, "kernel32.dll", "GetProductInfo", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_GetSystemFirmwareTable, "kernel32.dll", "GetSystemFirmwareTable", API_OS_BITS::ANY, API_OS_VERSION::WIN_VISTA, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_IsWow64Process, "kernel32.dll", "IsWow64Process", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP_SP2, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_LdrEnumerateLoadedModules, "ntdll.dll", "LdrEnumerateLoadedModules", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP_SP1, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtClose, "ntdll.dll", "NtClose", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtSystemDebugControl, "ntdll.dll", "NtSystemDebugControl", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtCreateDebugObject, "ntdll.dll", "NtCreateDebugObject", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtDelayExecution, "ntdll.dll", "NtDelayExecution", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtOpenDirectoryObject, "ntdll.dll", "NtOpenDirectoryObject", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtQueryDirectoryObject, "ntdll.dll", "NtQueryDirectoryObject", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtQueryInformationThread, "ntdll.dll", "NtQueryInformationThread", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtQueryInformationProcess, "ntdll.dll", "NtQueryInformationProcess", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtQueryLicenseValue, "ntdll.dll", "NtQueryLicenseValue", API_OS_BITS::ANY, API_OS_VERSION::WIN_VISTA, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtQueryObject, "ntdll.dll", "NtQueryObject", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtQuerySystemInformation, "ntdll.dll", "NtQuerySystemInformation", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtSetInformationThread, "ntdll.dll", "NtSetInformationThread", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtWow64QueryInformationProcess64, "ntdll.dll", "NtWow64QueryInformationProcess64", API_OS_BITS::X86_ONLY, API_OS_VERSION::WIN_XP_SP1, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtWow64ReadVirtualMemory64, "ntdll.dll", "NtWow64ReadVirtualMemory64", API_OS_BITS::X86_ONLY, API_OS_VERSION::WIN_XP_SP1, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_NtWow64QueryVirtualMemory64, "ntdll.dll", "NtWow64QueryVirtualMemory64", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP_SP1, API_OS_VERSION::WIN_10 }, { API_IDENTIFIER::API_NtYieldExecution, "ntdll.dll", "NtYieldExecution", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_RtlInitUnicodeString, "ntdll.dll", "RtlInitUnicodeString", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_RtlGetVersion, "ntdll.dll", "RtlGetVersion", API_OS_BITS::ANY, API_OS_VERSION::WIN_XP, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_WudfIsAnyDebuggerPresent, "WUDFPlatform.dll", "WudfIsAnyDebuggerPresent", API_OS_BITS::X64_ONLY, API_OS_VERSION::WIN_VISTA, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_WudfIsKernelDebuggerPresent, "WUDFPlatform.dll", "WudfIsKernelDebuggerPresent", API_OS_BITS::X64_ONLY, API_OS_VERSION::WIN_VISTA, API_OS_VERSION::NONE }, { API_IDENTIFIER::API_WudfIsUserDebuggerPresent, "WUDFPlatform.dll", "WudfIsUserDebuggerPresent", API_OS_BITS::X64_ONLY, API_OS_VERSION::WIN_VISTA, API_OS_VERSION::NONE } }; void API::Init() { for (int i = 0; i < API_COUNT; i++) { ApiData[i].ExpectedAvailable = ShouldFunctionExistOnCurrentPlatform(ApiData[i].PlatformBits, ApiData[i].MinVersion, ApiData[i].RemovedInVersion); HMODULE hLib = LoadLibraryA(ApiData[i].Library); if (hLib == NULL) { ApiData[i].Available = false; continue; } ApiData[i].Pointer = GetProcAddress(hLib, ApiData[i].EntryName); if (ApiData[i].Pointer == NULL) { ApiData[i].Available = false; continue; } else { ApiData[i].Available = true; } } } bool API::ShouldFunctionExistOnCurrentPlatform(API_OS_BITS bits, API_OS_VERSION minVersion, API_OS_VERSION removedInVersion) { // check if the API should exist on the OS // does it meet bitness requirements? if (bits != API_OS_BITS::ANY) { #ifdef ENV64BIT if (bits != API_OS_BITS::X64_ONLY) return false; #endif #ifdef ENV32BIT if (bits != API_OS_BITS::X86_ONLY) return false; #endif } // does it meet minimum version bool foundMinVer = false; bool metMinimumRequirement = false; for (int i = 0; i < API_OS_VERSION::VERSION_MAX; i++) { if (i == API_OS_VERSION::NONE) continue; if (VersionFunctionMap[i].Version == minVersion) { foundMinVer = true; metMinimumRequirement = VersionFunctionMap[i].Function(); } } if (!foundMinVer) { printf("ERROR: Minimum version value was invalid.\n"); assert(false); return false; } if (!metMinimumRequirement) return false; // if there's no maximum OS restriction, the API should exist if (removedInVersion == API_OS_VERSION::NONE) return true; // we have an upper restriction. was the API removed in this version? bool foundRemovedVer = false; bool metMaximumRequirement = false; for (int i = 0; i < API_OS_VERSION::VERSION_MAX; i++) { if (VersionFunctionMap[i].Version == removedInVersion) { foundRemovedVer = true; metMaximumRequirement = !VersionFunctionMap[i].Function(); } } if (!foundRemovedVer) { printf("ERROR: Removed version value was invalid.\n"); assert(false); return false; } return metMaximumRequirement; } void API::PrintAvailabilityReport() { int warningCount = 0; for (int i = 0; i < API_COUNT; i++) { if (ApiData[i].ExpectedAvailable && !ApiData[i].Available) { printf("[*] Warning: API %s!%s was expected to exist but was not found.\n", ApiData[i].Library, ApiData[i].EntryName); warningCount += 1; } } if (warningCount == 0) { printf("[*] All APIs present and accounted for.\n"); } } bool API::IsAvailable(API_IDENTIFIER api) { for (int i = 0; i < API_COUNT; i++) { if (ApiData[i].Identifier == api) { return ApiData[i].Available; } } assert(false); return false; } void* API::GetAPI(API_IDENTIFIER api) { for (int i = 0; i < API_COUNT; i++) { if (ApiData[i].Identifier == api) { if (ApiData[i].Available) { return ApiData[i].Pointer; } else { return nullptr; } } } assert(false); return nullptr; }
8,619
C++
.cpp
166
49.451807
192
0.681086
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,076
pch.h
LordNoteworthy_al-khaser/Tools/ATAIdentifyDump/pch.h
#ifndef PCH_H #define PCH_H #include <Windows.h> #include <ntddscsi.h> #include <stdio.h> #include "IdentifyDeviceData.h" #endif // PCH_H
139
C++
.h
7
18.714286
31
0.755725
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,077
IdentifyDeviceData.h
LordNoteworthy_al-khaser/Tools/ATAIdentifyDump/IdentifyDeviceData.h
#pragma once typedef struct _IDENTIFY_DEVICE_DATA { struct { USHORT Reserved1 : 1; USHORT Retired3 : 1; USHORT ResponseIncomplete : 1; USHORT Retired2 : 3; USHORT FixedDevice : 1; USHORT RemovableMedia : 1; USHORT Retired1 : 7; USHORT DeviceType : 1; } GeneralConfiguration; USHORT NumCylinders; USHORT ReservedWord2; USHORT NumHeads; USHORT Retired1[2]; USHORT NumSectorsPerTrack; USHORT VendorUnique1[3]; UCHAR SerialNumber[20]; USHORT Retired2[2]; USHORT Obsolete1; UCHAR FirmwareRevision[8]; UCHAR ModelNumber[40]; UCHAR MaximumBlockTransfer; UCHAR VendorUnique2; USHORT ReservedWord48; struct { UCHAR ReservedByte49; UCHAR DmaSupported : 1; UCHAR LbaSupported : 1; UCHAR IordyDisable : 1; UCHAR IordySupported : 1; UCHAR Reserved1 : 1; UCHAR StandybyTimerSupport : 1; UCHAR Reserved2 : 2; USHORT ReservedWord50; } Capabilities; USHORT ObsoleteWords51[2]; USHORT TranslationFieldsValid : 3; USHORT Reserved3 : 13; USHORT NumberOfCurrentCylinders; USHORT NumberOfCurrentHeads; USHORT CurrentSectorsPerTrack; ULONG CurrentSectorCapacity; UCHAR CurrentMultiSectorSetting; UCHAR MultiSectorSettingValid : 1; UCHAR ReservedByte59 : 7; ULONG UserAddressableSectors; USHORT ObsoleteWord62; USHORT MultiWordDMASupport : 8; USHORT MultiWordDMAActive : 8; USHORT AdvancedPIOModes : 8; USHORT ReservedByte64 : 8; USHORT MinimumMWXferCycleTime; USHORT RecommendedMWXferCycleTime; USHORT MinimumPIOCycleTime; USHORT MinimumPIOCycleTimeIORDY; USHORT ReservedWords69[6]; USHORT QueueDepth : 5; USHORT ReservedWord75 : 11; USHORT ReservedWords76[4]; USHORT MajorRevision; USHORT MinorRevision; struct { USHORT SmartCommands : 1; USHORT SecurityMode : 1; USHORT RemovableMediaFeature : 1; USHORT PowerManagement : 1; USHORT Reserved1 : 1; USHORT WriteCache : 1; USHORT LookAhead : 1; USHORT ReleaseInterrupt : 1; USHORT ServiceInterrupt : 1; USHORT DeviceReset : 1; USHORT HostProtectedArea : 1; USHORT Obsolete1 : 1; USHORT WriteBuffer : 1; USHORT ReadBuffer : 1; USHORT Nop : 1; USHORT Obsolete2 : 1; USHORT DownloadMicrocode : 1; USHORT DmaQueued : 1; USHORT Cfa : 1; USHORT AdvancedPm : 1; USHORT Msn : 1; USHORT PowerUpInStandby : 1; USHORT ManualPowerUp : 1; USHORT Reserved2 : 1; USHORT SetMax : 1; USHORT Acoustics : 1; USHORT BigLba : 1; USHORT DeviceConfigOverlay : 1; USHORT FlushCache : 1; USHORT FlushCacheExt : 1; USHORT Resrved3 : 2; USHORT SmartErrorLog : 1; USHORT SmartSelfTest : 1; USHORT MediaSerialNumber : 1; USHORT MediaCardPassThrough : 1; USHORT StreamingFeature : 1; USHORT GpLogging : 1; USHORT WriteFua : 1; USHORT WriteQueuedFua : 1; USHORT WWN64Bit : 1; USHORT URGReadStream : 1; USHORT URGWriteStream : 1; USHORT ReservedForTechReport : 2; USHORT IdleWithUnloadFeature : 1; USHORT Reserved4 : 2; } CommandSetSupport; struct { USHORT SmartCommands : 1; USHORT SecurityMode : 1; USHORT RemovableMediaFeature : 1; USHORT PowerManagement : 1; USHORT Reserved1 : 1; USHORT WriteCache : 1; USHORT LookAhead : 1; USHORT ReleaseInterrupt : 1; USHORT ServiceInterrupt : 1; USHORT DeviceReset : 1; USHORT HostProtectedArea : 1; USHORT Obsolete1 : 1; USHORT WriteBuffer : 1; USHORT ReadBuffer : 1; USHORT Nop : 1; USHORT Obsolete2 : 1; USHORT DownloadMicrocode : 1; USHORT DmaQueued : 1; USHORT Cfa : 1; USHORT AdvancedPm : 1; USHORT Msn : 1; USHORT PowerUpInStandby : 1; USHORT ManualPowerUp : 1; USHORT Reserved2 : 1; USHORT SetMax : 1; USHORT Acoustics : 1; USHORT BigLba : 1; USHORT DeviceConfigOverlay : 1; USHORT FlushCache : 1; USHORT FlushCacheExt : 1; USHORT Resrved3 : 2; USHORT SmartErrorLog : 1; USHORT SmartSelfTest : 1; USHORT MediaSerialNumber : 1; USHORT MediaCardPassThrough : 1; USHORT StreamingFeature : 1; USHORT GpLogging : 1; USHORT WriteFua : 1; USHORT WriteQueuedFua : 1; USHORT WWN64Bit : 1; USHORT URGReadStream : 1; USHORT URGWriteStream : 1; USHORT ReservedForTechReport : 2; USHORT IdleWithUnloadFeature : 1; USHORT Reserved4 : 2; } CommandSetActive; USHORT UltraDMASupport : 8; USHORT UltraDMAActive : 8; USHORT ReservedWord89[4]; USHORT HardwareResetResult; USHORT CurrentAcousticValue : 8; USHORT RecommendedAcousticValue : 8; USHORT ReservedWord95[5]; ULONG Max48BitLBA[2]; USHORT StreamingTransferTime; USHORT ReservedWord105; struct { USHORT LogicalSectorsPerPhysicalSector : 4; USHORT Reserved0 : 8; USHORT LogicalSectorLongerThan256Words : 1; USHORT MultipleLogicalSectorsPerPhysicalSector : 1; USHORT Reserved1 : 2; } PhysicalLogicalSectorSize; USHORT InterSeekDelay; USHORT WorldWideName[4]; USHORT ReservedForWorldWideName128[4]; USHORT ReservedForTlcTechnicalReport; USHORT WordsPerLogicalSector[2]; struct { USHORT ReservedForDrqTechnicalReport : 1; USHORT WriteReadVerifySupported : 1; USHORT Reserved01 : 11; USHORT Reserved1 : 2; } CommandSetSupportExt; struct { USHORT ReservedForDrqTechnicalReport : 1; USHORT WriteReadVerifyEnabled : 1; USHORT Reserved01 : 11; USHORT Reserved1 : 2; } CommandSetActiveExt; USHORT ReservedForExpandedSupportandActive[6]; USHORT MsnSupport : 2; USHORT ReservedWord1274 : 14; struct { USHORT SecuritySupported : 1; USHORT SecurityEnabled : 1; USHORT SecurityLocked : 1; USHORT SecurityFrozen : 1; USHORT SecurityCountExpired : 1; USHORT EnhancedSecurityEraseSupported : 1; USHORT Reserved0 : 2; USHORT SecurityLevel : 1; USHORT Reserved1 : 7; } SecurityStatus; USHORT ReservedWord129[31]; struct { USHORT MaximumCurrentInMA2 : 12; USHORT CfaPowerMode1Disabled : 1; USHORT CfaPowerMode1Required : 1; USHORT Reserved0 : 1; USHORT Word160Supported : 1; } CfaPowerModel; USHORT ReservedForCfaWord161[8]; struct { USHORT SupportsTrim : 1; USHORT Reserved0 : 15; } DataSetManagementFeature; USHORT ReservedForCfaWord170[6]; USHORT CurrentMediaSerialNumber[30]; USHORT ReservedWord206; USHORT ReservedWord207[2]; struct { USHORT AlignmentOfLogicalWithinPhysical : 14; USHORT Word209Supported : 1; USHORT Reserved0 : 1; } BlockAlignment; USHORT WriteReadVerifySectorCountMode3Only[2]; USHORT WriteReadVerifySectorCountMode2Only[2]; struct { USHORT NVCachePowerModeEnabled : 1; USHORT Reserved0 : 3; USHORT NVCacheFeatureSetEnabled : 1; USHORT Reserved1 : 3; USHORT NVCachePowerModeVersion : 4; USHORT NVCacheFeatureSetVersion : 4; } NVCacheCapabilities; USHORT NVCacheSizeLSW; USHORT NVCacheSizeMSW; USHORT NominalMediaRotationRate; USHORT ReservedWord218; struct { UCHAR NVCacheEstimatedTimeToSpinUpInSeconds; UCHAR Reserved; } NVCacheOptions; USHORT ReservedWord220[35]; USHORT Signature : 8; USHORT CheckSum : 8; } IDENTIFY_DEVICE_DATA, *PIDENTIFY_DEVICE_DATA;
6,853
C++
.h
249
24.943775
53
0.777862
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,079
timing.h
LordNoteworthy_al-khaser/al-khaser/TimingAttacks/timing.h
#pragma once BOOL timing_SetTimer(UINT delayInMillis); BOOL timing_NtDelayexecution(UINT delayInMillis); BOOL timing_timeSetEvent(UINT delayInMillis); BOOL timing_WaitForSingleObject(UINT delayInMillis); BOOL timing_WaitForMultipleObjects(UINT delayInMillis); BOOL timing_sleep_loop(UINT delayInMillis); BOOL rdtsc_diff_locky(); BOOL rdtsc_diff_vmexit(); BOOL timing_IcmpSendEcho(UINT delayInMillis); BOOL timing_CreateWaitableTimer(UINT delayInMillis); BOOL timing_CreateTimerQueueTimer(UINT delayInMillis); VOID CALLBACK CallbackCTQT(PVOID lParam, BOOLEAN TimerOrWaitFired);
578
C++
.h
13
43.384615
67
0.861702
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,080
TLS_callbacks.h
LordNoteworthy_al-khaser/al-khaser/AntiDebug/TLS_callbacks.h
#pragma once static volatile HANDLE tls_callback_thread_event = 0; static volatile HANDLE tls_callback_process_event = 0; static volatile UINT32 tls_callback_thread_data = 0; static volatile UINT32 tls_callback_process_data = 0; VOID WINAPI tls_callback(PVOID hModule, DWORD dwReason, PVOID pContext); BOOL TLSCallbackThread(); BOOL TLSCallbackProcess();
357
C++
.h
8
43.375
72
0.818444
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false