I'm trying to create a basic program that has tampering protection on the licenseCheck function, however it always says it's correct, even if I nop the whole licenseCheck function in Ollydbg or change and rebuild the code.
I'm following the Surreptitious Software book, and wrote the following program:
#include "stdafx.h"
#define HASH 5131241
void BEGIN() {}
const std::string correctlicense("ABC");
bool licenseCheck() {
std::cout << "Enter license: ";
std::string license;
std::cin >> license;
volatile DWORD d;
// Fingerprint
__asm {
lea ebx, d
mov ebx, 0x050b072b
}
return license.compare(correctlicense) == 0;
}
UINT hash(UINT *beginAddress, UINT *endAddress) {
UINT h = *beginAddress;
for (; beginAddress <= endAddress; beginAddress++) {
h ^= *beginAddress;
}
return h;
}
void END() {}
int main()
{
UINT uHash = hash((UINT*)BEGIN, (UINT*)END);
std::cout << "[Protection checks]" << std::endl;
std::cout << "Tampering: ";
if (uHash != HASH) {
std::cout << "Tampering detected! ( " << uHash << " )" << std::endl;
system("PAUSE");
return 0;
}
else {
std::cout << "Correct" << std::endl;
}
if (licenseCheck()) {
std::cout << "Correct!" << std::endl;
}
else {
std::cout << "Failed!" << std::endl;
}
system("PAUSE");
return 0;
}
The program basically 'hashes' the code between the BEGIN function and END function, but it doesn't seem to work. The hash is always correct even after tampering.
I'm using Windows 7 and Visual studio 2017 the build/run the program.
Related
I found a way to get the information of the stack call in an x86 program. The code is not difficult to understand:
#ifdef X86
void TestGetCallStack_X86()
{
std::cout << "Call -> TestGetCallStack_X86" << std::endl;
std::cout << "***************************************" << std::endl;
DWORD _ebp, _esp;
__asm mov _ebp, ebp
__asm mov _esp, esp
for (unsigned int index = 0; index < CALLSTACK_NUM; index++) {
void* pAddr = (void*)ULongToPtr(*(((DWORD*)ULongToPtr(_ebp)) + 1));
if (!pAddr)
return;
IMAGEHLP_LINE64 Line;
Line.SizeOfStruct = sizeof(Line);
memset(&Line, 0, sizeof(Line));
DWORD Offset = 0;
if (fnSymGetLineFromAddr64(s_Process, (DWORD64)pAddr, &Offset, &Line))
{
std::cout << index << " [" << pAddr << "]";
std::cout << " File Name:" << Line.FileName << " " << "Line Count:" << Line.LineNumber << std::endl;
std::cout << std::endl;
}
else
{
DWORD error = GetLastError();
if (error == 487)
{
OutputDebugString(TEXT("No debug info in current module\n"));
}
else if (error == 126)
{
OutputDebugString(TEXT("Debug info in current module has not loaded\n"));
}
else
{
OutputDebugString(TEXT("SymGetLineFromAddr64 failed\n"));
}
std::cout << std::endl;
}
_ebp = *(DWORD*)ULongToPtr(_ebp);
if (_ebp == 0 || 0 != (_ebp & 0xFC000000) || _ebp < _esp)
break;
}
std::cout << "***************************************" << std::endl;
}
#endif // X86
run result
I wrote an x64 version and found that MSVC for x64 does't support inline assembly.
I try to write a .asm file and load the function in C++ code. but it does't work. (Actually I'm not good at Assembly language)
I found many ways. So far, I have used the _ReturnAddress to achieve.
void TestGetCallStack_X64()
{
void* pAddr = _ReturnAddress();
if (!pAddr)
return;
std::cout << "0" << "\t" << pAddr << std::endl;
std::cout << "Use GetLineFromAddress64:" << std::endl;
IMAGEHLP_LINE64 Line;
Line.SizeOfStruct = sizeof(Line);
memset(&Line, 0, sizeof(Line));
DWORD Offset = 0;
if (fnSymGetLineFromAddr64(s_Process, (DWORD64)pAddr, &Offset, &Line))
{
std::cout << "File Name:" << Line.FileName << "\t" << "Line Count:" << Line.LineNumber << std::endl;
std::cout << std::endl;
}
else
{
//Can not find...
}
}
Run Result
But this way cannot fully display the information of the stack call. How should I achieve the same effect as the x86 version?
PS: I can't understand the condition of break in x86's Code. Can anyone answer, Please! Thank you first.
//what's the mean that <_ebp & 0xFC000000>
if (_ebp == 0 || 0 != (_ebp & 0xFC000000) || _ebp < _esp)
I am lost, when I ran my program last night it ran fine. When I added the power() function, suddenly lines which ran fine without adding the new code now trigger an error message:
warning C4018: '<': signed/unsigned mismatch
Why?
I feel I don't have the chops to explain this, so please follow the code below.
PLEASE RUN THE CODE WITH AND WITHOUT THIS power() FUNCTION. When run with the power() function, it makes error C4018 on the for loops in the exam() function! When run without the power() function, it runs FINE!!
#include <string>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
///the offending function///
double power(double base, int exponent)
{
double product;
//double base; int exponent;
std::cout << "enter a value for base: " << endl;
std::cin >> base;
std::cout << "enter exponenent: " << endl;
std::cin >> exponent;
double result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * base;
//product = base exponent;
}
std::cout << product;
return product;
}
///after here, things run fine if you X out the aforementioned function! Wow!
void exam()
{
std::vector<int> scores;
int F;
F = 0; //string names;
std::cout << "enter exam scores int:" << endl;
//std::vector <string> names;
while (F != -1)
{
std::cout << "Enter a new exame score:" << endl;
std::cin >> F;
scores.push_back(F);
}
if (F == -1)
{
std::cout << "end of score entering" << endl;
}
for (int i = 0; i < scores.size(); i++)
{
std::cout << scores[i];
}
/*
while (i < scores.size())
{
std::cout << scores[i];
i++;
}
*/
std::cout << "yay you made this work!!!!!!!!!!!!!" << endl;
}
int multiply()
{
int a;
int b;
a = 8;
b = 4;
std::cout << a * b << endl;
std::cout << "f*** yeah" << endl << endl;
return 0;
}
void test()
{
std::vector<int> newvector;
int T;
std::cout << "enter vector variables: " << endl;
std::cin >> T;
newvector.push_back(T);
while (T != -1)
{
std::cout << "enter new vector variables T " << endl;
std::cin >> T;
newvector.push_back(T);
if (T == -1)
{
newvector.pop_back();
}
}
std::cout << "end of NewVector data inputs:" << endl;
for (int W = 0; W < newvector.size(); W++)
{
std::cout << newvector[W] << endl;
}
}
int main()
{
power(2, 3);
exam();
/*int result = multiply();
std::cout << "endl ;" << endl;
test();
system("pause"); */
multiply();
string name;
int a;
std::cout << "enter a variable for your name: " << endl;
std::getline(cin, name);
if (name == "aaron")
{
std::cout << " what a dumb name, aAron?" << endl;
}
else if (name == "todd")
{
std::cout << "what a dottly name, Todd" << endl;
}
else
{
std::cout << "your name = " << name << endl;
}
//std::vector <string>
std::vector<int> asdf;
std::cout << "enter an int for a" << endl;
std::cin >> a;
asdf.push_back(a);
while (a != -1)
{
std::cout << "enter another A: " << endl;
std::cin >> a;
asdf.push_back(a);
if (a == -1)
{
asdf.pop_back();
}
} //set var; checks if d<size(); if so, JUMP to std::cout<<; when finished with body, find after size(); == "d++", then refer back to declaration)
/*/ for(int G = 0; G<asdf.size(); G++)
{
std::cout << asdf[G] << endl;
} */
for (int i = 0; i < asdf.size(); i++)
{
std::cout << asdf[i] << "f*** it works!!!!!! " << endl;
}
for (int d = 0; d < asdf.size(); d++)
{ //htt ps://youtu.be/_1AwR-un4Hk?t=155
std::cout << asdf[d] << ", ";
}
std::cout << endl;
std::cout << std::accumulate(asdf.begin(), asdf.end(), 0);
//std::cout<<
system("pause");
return 0;
}
The presence of the power function should have no effect on this problem. Possibly you aren't seeing the warnings because without the power function the program does not compile.
In
for (int W = 0; W < newvector.size(); W++)
newvector.size() returns an unsigned integer. int W is a signed integer. You're getting exactly what you asked for.
You can change int W to vector<int>::size_type W (but the less verbose size_t W should also work) to make the error message go away, but this is an error where you would likely have to add more than 2 billion items to the vector to see manifest.
Solution:
for (vector<int>::size_type W = 0; W < newvector.size(); W++)
However this is a good place for a range-based for loop
for (const auto &val: newvector)
{
std::cout << val << endl;
}
By letting the compiler figure out all the sizes and types your life is much easier.
This is repeated several times throughout the code.
Re: WHEN RUN, It makes error C4018 -
YOU made that error (warning, actually), not "it".
That warning is reported by compiler, so you haven't run anything yet...
Your newly added function uses uninitialized variable product; in my version of Visual Studio it is an error.
I'm trying to use displayVectorVer2() to have it only display the first 10 elements, but I don't know how to do it with iterators. I did try a few dumb things just to see what would happen: I compared the iterator to displayLimit in my for loop. I played around by subtracting vobj.end()-5 since my professor is only having me use 15 elements, but I fully well knew this was not a good idea.
#include <iostream>
#include <vector>
#include <ctime>
template <class T>
void fillVector(std::vector<T>& vobj, int n);
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr);
template <class T>
void fillVector(std::vector<T>& vobj, int n)
{
srand((unsigned int)time(NULL));
for (int i=0; i<n; ++i)
{
vobj.push_back(rand()%99999+1);
}
}
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr)
{
std::cout << "Vector object contains " << vobj.size() << " values which are" << std::endl;
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << std::endl;
}
}
int main()
{
std::vector<int> vobj;
std::cout << "Before calling fillVector(...): vobj contains "
<< vobj.size() << " values." << std::endl;
std::cout << "\nEnter # of random values you'd like to store in vobj: ";
int n;
std::cin >> n;
std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
fillVector(vobj, n);
std::cout << "\n*** Calling displayVectorVer2(...) ***" << std::endl;
std::vector<int>::iterator ptr;
displayVectorVer2(vobj,ptr);
}
Maybe I am thinking too simple but, that wold solve your question:
I'm trying to use displayVectorVer2() to have it only display the
first 10 elements
without knowing your full exercise, that would be my answer:
...
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
for (ptr=vobj.begin(); ptr<vobj.begin()+displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
...
edit:
That worked, but why does it work? I remember adding to vobj.begin() and getting extra empty elements appended to the original vector.
Not sure what exactly you did but maybe that helps you understanding your code:
...
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
//Init ptr outside the for loop
ptr = vobj.begin();
//What the for loop is seeing with a more familiar syntax:
//for( ; i < 0 +displayLimit; ++i)
//what you are seeing
for (/*ptr init*/; ptr < vobj.begin() +displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
...
The iterators just gives you the int value and you can use it with what ever "eats" int values. In your case the for loop.
If you tell the program to use an iterator you tell the program: "Just give me the number the Vector begins with and add 10".
In your case 0 "...and add 10"
You could also write a code like that with n passed to the function
for being able to use .end - input + 10 for showing 10 lines:
...
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr,int n)
{
std::cout << "Vector object contains " << vobj.size() << " values which are" << std::endl;
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
ptr=vobj.begin();
for (; ptr<vobj.end() -n +displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << std::endl;
}
}
int main()
{
std::vector<int> vobj;
std::cout << "Before calling fillVector(...): vobj contains "
<< vobj.size() << " values." << std::endl;
std::cout << "\nEnter # of random values you'd like to store in vobj: ";
int n;
std::cin >> n;
std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
fillVector(vobj, n);
std::cout << "\n*** Calling displayVectorVer2(...) ***" << std::endl;
std::vector<int>::iterator ptr;
displayVectorVer2(vobj,ptr,n);
}
...
You also shouldn't use srand in modern code anymore since it is depricated for more than 10 years since c++11 introduced <random>
and srand can harm your program f.e. if used for generating seeds for sensitive code. Also srand provides not the "randomness" it should provide, srand generates some numbers more often than others - that's not random.
In this program, I am using template class, I have a header file and this is my main file. I am having trouble displaying the (".....") IndexOutOfBounds and displaying it on the screen.
#include "XArray.h"
#include <iomanip>
#include <string>
using namespace std;
template<class T>
void afriend ( XArray<T> );
int main()
{
XArray<double> myAD(18);
myAD.randGen(15, 100);
cout << myAD.getType() << endl;
cout << setprecision(1) << fixed << "\n\n Unsorted: " << myAD;
myAD.sort();
cout << "\n Now Sorted: " << myAD;
cout << "\n\n";
**try
{
cout << "A[-5] = " << setw(6) << myAD[-5] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
e.print();
}
try
{
cout << "A[8] = " << setw(6) << myAD[8] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
e.print();
}**
cout << "\n\n" << setprecision(2) << fixed;
cout << "Size = " << setw(6) << myAD.getSize() << endl;
cout << "Mean = " << setw(6) << myAD.mean() << endl;
cout << "Median = " << setw(6) << myAD.median() << endl;
cout << "STD = " << setw(6) << myAD.std() << endl;
cout << "Min # = " << setw(6) << myAD.min() << endl;
cout << "Max # = " << setw(6) << myAD.max() << endl;
return 0;
}
There is the Array.h file posted as a dropbox link
Array.h
The code for operator[] in Array.h is:
template <class T>
T XArray<T>::operator[] (int idx)
{
if( (idx = 0) && (idx < size) )
{
return Array[idx];
}
else
{
throw IndexOutOfBound();
return numeric_limits<T>::epsilon();
}
}
Although the question is somewhat obscure, give a try to these suggestions.
Firstly, it can happen that XArray<>::IndexOutOfBounds have no proper copy ctor. You can try catching by const reference to workaround that:
try
{
...
}
catch(const XArray<double>::IndexOutOfBound& e)
{
e.print();
}
Index operator in standard library containers does not check for bounds, there is a special getter that does the check called at(). If the XArray class is designed with standard library in mind, it could behave similarly.
However to get more adequate response you need to be more specific describing the trouble you are having.
I'm still wondering what exact question is.
However, I'm understanding the question is that how I can use 'catch' by using 'IndexOutOfBound'.
#include <exception>
#include <iostream>
using namespace std;
template <typename T>
class Array
{
private:
int m_nLength;
T *m_ptData;
public:
...
...
T& operator[](int nIndex)
{
//assert(nIndex >= 0 && nIndex < m_nLength);
if(nIndex < 0 || nIndex > m_nLength)
{
throw myex;
}
else
{
return m_ptData[nIndex];
}
}
//class definition for 'IndexOutOfBound'
class IndexOutOfBound: public exception
{
public:
virtual const char* print() const throw()
{
return "Exception occured 'Index Out Of Bound'";
}
}myex;
};
int main()
{
Array<double> arr(3);
try
{
arr[0] = 1;
//exception will occur here.
arr[4] = 2;
}
catch(Array<double>::IndexOutOfBound &e)
{
cout << e.print() << '\n';
}
return 0;
}
Here is no 'XArray.h', so I've written a sample array class for example.
The problem is in the operator[] function. The code idx = 0 sets idx to 0. So all of your calls to operator[] will return the first element, and therefore there is no out-of-bounds error unless the array is empty.
You probably meant to write if ( idx >= 0 && idx < size ).
BTW the throw aborts the function, it makes no sense to return after throw.
I can't figure out where is the problem with this simple code, I think that here is the trouble with output to Console maybe deadlock or something, can somebody, please help.
#include <iostream>
#include <string>
#include <sstream>
#include <boost/thread.hpp>
using namespace std;
struct IntegrateTask
{
int id;
double from, to, step, result;
IntegrateTask(int id, double from, double to, double step)
{
this -> id;
this -> from = from;
this -> to = to;
this -> step = step;
}
~IntegrateTask()
{}
};
vector<IntegrateTask> * tasks = new vector<IntegrateTask>();
boost::mutex mutlist;
boost::mutex iomutex;
boost::condition_variable condtask;
bool isInterrupted = false;
double foo(double x)
{
return x * x;
}
void integrate(IntegrateTask * task)
{
double result = 0;
double step = task -> step;
for(double i = task -> from ; i != task -> to; i =+ step)
{
result += foo(i) * step;
}
task -> result = result;
}
void integrateThread()
{
boost::thread::id id = boost::this_thread::get_id();
try
{
{
boost::mutex::scoped_lock iolock(iomutex);
cout << "Thread #" << id << " is working!" << endl;
}
while(!isInterrupted)
{
IntegrateTask * currtask = NULL;
{
boost::mutex::scoped_lock lock(mutlist);
while(!isInterrupted && tasks -> empty())
{
condtask.wait(lock);
}
if (!tasks -> empty())
{
currtask = &tasks->back();
tasks->pop_back();
}
}
if (currtask != NULL)
{
integrate(currtask);
boost::mutex::scoped_lock iolock(iomutex);
cout << "Task #" << (currtask->id) << "; result = " << (currtask->result) << endl;
}
}
boost::mutex::scoped_lock iolock(iomutex);
cout << "Thread # " << id << " stoped working normal!" << endl;
}
catch(boost::thread_interrupted)
{
boost::mutex::scoped_lock ioLock(iomutex);
cout << "Thread # " << id << " stoped working by interruption!" << endl;
}
catch(exception & e)
{
boost::mutex::scoped_lock iolock(iomutex);
cout << "Error: " << e.what() << endl;
}
}
int main()
{
cout << "Function for integration: f(x)=x*x" << endl;
cout << "For stopping program press EXIT" << endl;
int thcount = 6;// or boost::thread::hardware_concurrency()
boost::thread_group thgroup;
for (int i = 1; i <= thcount; i++){
thgroup.create_thread(&integrateThread);
}
int id = 0;
while (true)
{
string line;
{
boost::mutex::scoped_lock iolock(iomutex);
cout << "Task #" << ++id << "; left bound, right bound and step: ";
getline(cin, line);
}
if (line.find("e") != string::npos)
{
isInterrupted = true;
condtask.notify_all();
thgroup.interrupt_all();
thgroup.join_all();
return 0;
}
double from, to, step;
istringstream input(line);
input >> from >> to >> step;
IntegrateTask * task = new IntegrateTask(id, from, to, step);
{
boost::mutex::scoped_lock lock(mutlist);
tasks->push_back(*task);
}
condtask.notify_one();
}
}
I haven't tried to follow the logic of what you're aiming to achieve here, but there are 2 issues (at least):
You're not using id in IntegrateTask's constructor. You should generally favour initialisation lists over assignments in constructor bodies, and using class member variable names in function signatures is a recipe for disaster too, so I'd change your constructor to:
IntegrateTask(int id_init, double from_init, double to_init, double step_init)
: from(from_init), to(to_init), step(step_init), id(id_init) {}
The probable cause of the hanging is your use of != in the for loop in integrate. If you change that to < your program shouldn't hang, but I'm not sure if this breaks your program's logic.