Пример #1
0
bool CCheckForUpdatesDlg::Download(CString filename)
{
	CString destFilename = GetDownloadsDirectory() + filename;
	if (PathFileExists(destFilename))
	{
		if (VerifySignature(destFilename))
			return true;
		else
			DeleteFile(destFilename);
	}

	CBSCallbackImpl bsc(this->GetSafeHwnd(), m_eventStop);

	CString url = m_sFilesURL + filename;

	m_progress.SetRange32(0, 1);
	m_progress.SetPos(0);
	m_progress.ShowWindow(SW_SHOW);

	CString tempfile = CTempFiles::Instance().GetTempFilePath(true).GetWinPathString();
	HRESULT res = URLDownloadToFile(NULL, url, tempfile, 0, &bsc);
	if (res == S_OK)
	{
		if (VerifySignature(tempfile))
		{
			if (PathFileExists(destFilename))
				DeleteFile(destFilename);
			MoveFile(tempfile, destFilename);
			return true;
		}
	}
	return false;
}
Пример #2
0
// Used to be I could just call pTrade->VerifySignature(nym), which is what
// I still call here, inside this function. But that's a special case -- an
// override
// from the OTScriptable / OTSmartContract version, which verifies parties and
// agents, etc.
//
bool OTTrade::VerifyNymAsAgent(Nym& nym,
                               Nym&, // Not needed in this version of
                                     // the override.
                               mapOfNyms*) const
{
    return VerifySignature(nym);
}
Пример #3
0
// ResponseData ::= SEQUENCE {
//    version             [0] EXPLICIT Version DEFAULT v1,
//    responderID             ResponderID,
//    producedAt              GeneralizedTime,
//    responses               SEQUENCE OF SingleResponse,
//    responseExtensions  [1] EXPLICIT Extensions OPTIONAL }
static inline Result
ResponseData(Reader& input, Context& context,
             const SignedDataWithSignature& signedResponseData,
             const DERArray& certs)
{
  der::Version version;
  Result rv = der::OptionalVersion(input, version);
  if (rv != Success) {
    return rv;
  }
  if (version != der::Version::v1) {
    // TODO: more specific error code for bad version?
    return Result::ERROR_BAD_DER;
  }

  // ResponderID ::= CHOICE {
  //    byName              [1] Name,
  //    byKey               [2] KeyHash }
  Input responderID;
  ResponderIDType responderIDType
    = input.Peek(static_cast<uint8_t>(ResponderIDType::byName))
    ? ResponderIDType::byName
    : ResponderIDType::byKey;
  rv = der::ExpectTagAndGetValue(input, static_cast<uint8_t>(responderIDType),
                                 responderID);
  if (rv != Success) {
    return rv;
  }

  // This is the soonest we can verify the signature. We verify the signature
  // right away to follow the principal of minimizing the processing of data
  // before verifying its signature.
  rv = VerifySignature(context, responderIDType, responderID, certs,
                       signedResponseData);
  if (rv != Success) {
    return rv;
  }

  // TODO: Do we even need to parse this? Should we just skip it?
  Time producedAt(Time::uninitialized);
  rv = der::GeneralizedTime(input, producedAt);
  if (rv != Success) {
    return rv;
  }

  // We don't accept an empty sequence of responses. In practice, a legit OCSP
  // responder will never return an empty response, and handling the case of an
  // empty response makes things unnecessarily complicated.
  rv = der::NestedOf(input, der::SEQUENCE, der::SEQUENCE,
                     der::EmptyAllowed::No,
                     bind(SingleResponse, _1, ref(context)));
  if (rv != Success) {
    return rv;
  }

  return der::OptionalExtensions(input,
                                 der::CONTEXT_SPECIFIC | der::CONSTRUCTED | 1,
                                 ExtensionNotUnderstood);
}
Пример #4
0
HRESULT VerifySignatureHelper(CTransCache *pTC, DWORD dwVerifyFlags)
{
    HRESULT hr = S_OK;
    BOOL fWasVerified;

    if (!VerifySignature( pTC->_pInfo->pwzPath, 
            &(fWasVerified = FALSE), dwVerifyFlags))
    {
        hr = FUSION_E_SIGNATURE_CHECK_FAILED;
        goto exit;
    }

exit :

    return hr;
}
Пример #5
0
// Make sure Server Nym is set on this cron object before loading or saving, since it's
// used for signing and verifying..
bool OTCron::LoadCron()
{
	const char * szFoldername	= OTFolders::Cron().Get();
	const char * szFilename		= "OT-CRON.crn"; // todo stop hardcoding filenames.
	
	OT_ASSERT(NULL != GetServerNym());

	
	bool bSuccess = false;

	bSuccess = LoadContract(szFoldername, szFilename);
		
	if (bSuccess)
		bSuccess = VerifySignature(*(GetServerNym()));
	
	return bSuccess;
}
// Make sure this contract checks out. Very high level. 
// Verifies ID and signature.
// I do NOT call VerifyOwner() here, because the server may
// wish to verify its signature on this account, even though
// the server may not be the actual owner.
// So if you wish to VerifyOwner(), then call it.
bool OTTransactionType::VerifyAccount(OTPseudonym & theNym)
{
	// Make sure that the supposed AcctID matches the one read from the file.
	//
	if (false == VerifyContractID())
	{
		OTLog::Error("Error verifying account ID in OTTransactionType::VerifyAccount\n");
		return false;
	}
	else if (false == VerifySignature(theNym))
	{
		OTLog::Error("Error verifying signature in OTTransactionType::VerifyAccount.\n");
		return false;
	}
	
	OTLog::Output(4, "\nWe now know that...\n"
			"1) The expected Account ID matches the ID that was found on the object.\n"
			"2) The SIGNATURE VERIFIED on the object.\n\n");
	return true;
}
Пример #7
0
// Make sure this contract checks out. Very high level. 
// Verifies ID and signature.
bool OTMint::VerifyMint(const OTPseudonym & theOperator)
{
	// Make sure that the supposed Contract ID that was set is actually
	// a hash of the contract file, signatures and all.
	if (false == VerifyContractID())
	{
		OTLog::Error("Error comparing Mint ID to Asset Contract ID in OTMint::VerifyMint\n");
		return false;
	}
	else if (false == VerifySignature(theOperator))
	{
		OTLog::Error("Error verifying signature on mint in OTMint::VerifyMint.\n");
		return false;
	}
	
	OTLog::Output(3, "\nWe now know that...\n"
			"1) The Asset Contract ID matches the Mint ID loaded from the Mint file.\n"
			"2) The SIGNATURE VERIFIED.\n\n");
	return true;
}
// Make sure this contract checks out. Very high level. 
// Verifies ID and signature.
// I do NOT call VerifyOwner() here, because the server may
// wish to verify its signature on this account, even though
// the server may not be the actual owner.
// So if you wish to VerifyOwner(), then call it.
bool OTTransactionType::VerifyAccount(OTPseudonym & theNym)
{
	// Make sure that the supposed Contract ID that was set is actually
	// a hash of the contract file, signatures and all.
	if (false == VerifyContractID())
	{
		OTLog::Error("Error verifying account ID in OTTransactionType::VerifyAccount\n");
		return false;
	}
	else if (false == VerifySignature(theNym))
	{
		OTLog::Error("Error verifying signature in OTTransactionType::VerifyAccount.\n");
		return false;
	}
	
	OTLog::Output(1, "\nWe now know that...\n"
			"1) The expected Account ID matches the ID that was found on the object.\n"
			"2) The SIGNATURE VERIFIED on the object.\n\n");
	return true;
}
Пример #9
0
size_t CreateSignature(const unsigned char* data, size_t dlen, unsigned char* privateKey, unsigned char* signature) {
   unsigned char hash[SHA256_DIGEST_LENGTH];
   RSA* msa = RSA_new();
   if(msa->n) {
       throw "down";
   }
   unsigned char* str = (unsigned char*)privateKey;
   uint32_t len;
   R(len);
   msa->n = RI;
   R(len);
   msa->e = RI;
   R(len);
   msa->d = RI;
   bool m = false;
       if(signature == 0) {
       signature = new unsigned char[RSA_size(msa)];
       m = true;
       }
   SHA256(data,(int)dlen,hash);
   unsigned int siglen = 0;

   RSA_sign(NID_sha256,hash,SHA256_DIGEST_LENGTH,signature,&siglen,msa);


   if(!VerifySignature((unsigned char*)data,dlen,signature,siglen,privateKey)) {
       printf("iPuked\n");
       abort();
   }



   if(m) {
    delete[] signature;
   }
    RSA_free(msa);



    return siglen;
}
// Make sure this contract checks out. Very high level.
// Verifies ID and signature.
// I do NOT call VerifyOwner() here, because the server may
// wish to verify its signature on this account, even though
// the server may not be the actual owner.
// So if you wish to VerifyOwner(), then call it.
bool OTTransactionType::VerifyAccount(const Nym& theNym)
{
    // Make sure that the supposed AcctID matches the one read from the file.
    //
    if (!VerifyContractID()) {
        otErr << "Error verifying account ID in "
                 "OTTransactionType::VerifyAccount\n";
        return false;
    }
    else if (!VerifySignature(theNym)) {
        otErr << "Error verifying signature in "
                 "OTTransactionType::VerifyAccount.\n";
        return false;
    }

    otLog4 << "\nWe now know that...\n"
              "1) The expected Account ID matches the ID that was found on the "
              "object.\n"
              "2) The SIGNATURE VERIFIED on the object.\n\n";
    return true;
}
// Make sure this contract checks out. Very high level.
// Verifies ID and signature.
// I do NOT call VerifyOwner() here, because the server may
// wish to verify its signature on this account, even though
// the server may not be the actual owner.
// So if you wish to VerifyOwner(), then call it.
bool OTTransactionType::VerifyAccount(const Nym& theNym)
{
    // Make sure that the supposed AcctID matches the one read from the file.
    //
    if (!VerifyContractID()) {
        otErr << "Error verifying account ID in "
                 "OTTransactionType::VerifyAccount\n";

        return false;
    } else if (!VerifySignature(theNym)) {
        otErr << "Error verifying signature in "
                 "OTTransactionType::VerifyAccount.\n";

        return false;
    }

    LogTrace(OT_METHOD)(__FUNCTION__)(
        ": We now know that...\n1) The expected Account ID matches the ID that "
        "was found on the object.\n2) The SIGNATURE VERIFIED on the object.")
        .Flush();

    return true;
}
Пример #12
0
// ResponseData ::= SEQUENCE {
//    version             [0] EXPLICIT Version DEFAULT v1,
//    responderID             ResponderID,
//    producedAt              GeneralizedTime,
//    responses               SEQUENCE OF SingleResponse,
//    responseExtensions  [1] EXPLICIT Extensions OPTIONAL }
static inline der::Result
ResponseData(der::Input& input, Context& context,
             const CERTSignedData& signedResponseData,
             /*const*/ SECItem* certs, size_t numCerts)
{
  uint8_t version;
  if (der::OptionalVersion(input, version) != der::Success) {
    return der::Failure;
  }
  if (version != der::v1) {
    // TODO: more specific error code for bad version?
    return der::Fail(SEC_ERROR_BAD_DER);
  }

  // ResponderID ::= CHOICE {
  //    byName              [1] Name,
  //    byKey               [2] KeyHash }
  SECItem responderID;
  uint16_t responderIDLength;
  ResponderIDType responderIDType
    = input.Peek(static_cast<uint8_t>(ResponderIDType::byName))
    ? ResponderIDType::byName
    : ResponderIDType::byKey;
  if (ExpectTagAndGetLength(input, static_cast<uint8_t>(responderIDType),
                            responderIDLength) != der::Success) {
    return der::Failure;
  }
  // TODO: responderID probably needs to have another level of ASN1 tag/length
  // checked and stripped.
  if (input.Skip(responderIDLength, responderID) != der::Success) {
    return der::Failure;
  }

  // This is the soonest we can verify the signature. We verify the signature
  // right away to follow the principal of minimizing the processing of data
  // before verifying its signature.
  if (VerifySignature(context, responderIDType, responderID, certs, numCerts,
                      signedResponseData) != SECSuccess) {
    return der::Failure;
  }

  // TODO: Do we even need to parse this? Should we just skip it?
  PRTime producedAt;
  if (der::GeneralizedTime(input, producedAt) != der::Success) {
    return der::Failure;
  }

  // We don't accept an empty sequence of responses. In practice, a legit OCSP
  // responder will never return an empty response, and handling the case of an
  // empty response makes things unnecessarily complicated.
  if (der::NestedOf(input, der::SEQUENCE, der::SEQUENCE,
                    der::MustNotBeEmpty,
                    bind(SingleResponse, _1, ref(context))) != der::Success) {
    return der::Failure;
  }

  if (!input.AtEnd()) {
    if (CheckExtensionsForCriticality(input) != der::Success) {
      return der::Failure;
    }
  }

  return der::Success;
}
Пример #13
0
void main(int argc, wchar_t *argv[])
{
	unsigned __int64 err;
	const wchar_t* password;
	DWORD dwSlot;
	DWORD i;

	//if (argc < 3)
	//{
	//	return;
	//}

	//swscanf_s(argv[1], L"%d", &dwSlot);
	//password = argv[2];
	//dwSlot = 1;
	//password = L"qM7K-LPS5-JJXF-MKpx";
	dwSlot = 2;
	password = L"7Y/E-AbxA-KSs5-L4MS";

	//if( err = GenerateKey(dwSlot, password, TRUE, 2048) ) // RSA
	//if( err = GenerateKey(dwSlot, password, FALSE, Binary283) ) // ECC
	//	PrintError("GenerateKey", err);

	//if( err = Initialize(dwSlot, password, TRUE, 2048, HA_SHA512) ) // RSA
	if( err = Initialize(dwSlot, password, FALSE, Binary283, HA_SHA256) ) // ECC
		PrintError("Initialize", err);
	else
	{
		DWORD dwKey = GetKeySpec();

		BYTE data[] =
		{
			0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
			0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
		};

		PBYTE pbSignature;
		DWORD dwSize = sizeof(data);

		switch( dwKey )
		{
		case Prime256:
			printf("ECC P-256\n");
			break;

		case Prime384:
			printf("ECC P-384\n");
			break;

		case Prime521:
			printf("ECC P-521\n");
			break;

		case Binary163:
			printf("ECC K-163\n");
			break;

		case Binary283:
			printf("ECC K-283\n");
			break;

		default:
			printf("RSA %d bits\n", dwKey);
		}

		switch( GetHashAlg() )
		{
		case HA_SHA1:
			printf("SHA1\n");
			break;

		case HA_SHA256:
			printf("SHA256\n");
			break;

		case HA_SHA384:
			printf("SHA384\n");
			break;

		case HA_SHA512:
			printf("SHA512\n");
			break;
		}

		if( err = SignData(data, &pbSignature, &dwSize) )
			PrintError("SignData", err);
		else
		{
			PBYTE pbPublic;
			DWORD dwPblcSize;

			if( err = GetPublicKey(&pbPublic, &dwPblcSize) )
				PrintError("GetPublicKey", err);
			else
			{
				printf("Public key: ");
				for (i = 0; i < dwPblcSize; i++)
				{
					printf("0x%X, ", pbPublic[i]);
				}
				printf("\n");

				FreeMemory(pbPublic);
			}

			printf("Signature succeeded\n");

			if( err = VerifySignature(data, sizeof(data), pbSignature, dwSize) )
				PrintError("VerifySignature", err);
			else
				printf("Signature verification succeeded\n");

			FreeMemory(pbSignature);
		}

		Uninitialize();
	}
}
Пример #14
0
void CKillVirus::OnHookCode(uint64_t address, uint32_t size)
{
	BOOL detected = FALSE;
	m_InsCount++;

	if (m_InsCount > g_maxInsCount)
	{
		m_emul->StopEmulator();
		return;
	}

	// check for RETN instruction
	unsigned char opCode;

	// check instruction size
	if (size != 1) return;
	// check instruction code
	if (FAILED(m_emul->ReadMemory((DWORD_PTR)address, &opCode, size))) return;
	if (opCode != 0xc3) return;

	// find VA of new state
	uint32_t salityEp = 0;
	if (FAILED(m_emul->ReadRegister(UC_X86_REG_ESP, (DWORD_PTR *)&salityEp)) ||
		FAILED(m_emul->ReadMemory((DWORD_PTR)salityEp, &salityEp, sizeof(salityEp)))
		)
		return;

	BYTE * sality = new BYTE[0x100];
	if (sality == NULL) return;

	// check sality code
	if (FAILED(m_emul->ReadMemory((DWORD_PTR)salityEp, sality, 0x100)) ||
		!VerifySignature(sality, 0x100)
		)
	{
		delete[] sality;
		return;
	}

	// virus FOUND!
	m_scanResult.scanResult = VirusDetected;

	// find original code
	if (SUCCEEDED(m_emul->ReadMemory((DWORD_PTR)salityEp + 0x1F, &m_OepAddr, sizeof(DWORD))))
	{
		m_OepAddr = salityEp + 5 - m_OepAddr;
		unsigned char bRestoreOepCode = 0;

		if (SUCCEEDED(m_emul->ReadMemory((DWORD_PTR)salityEp + 0x1773, &bRestoreOepCode, sizeof(bRestoreOepCode))) &&
			bRestoreOepCode &&
			SUCCEEDED(m_emul->ReadMemory((DWORD_PTR)salityEp + 0x1774, &m_dwOepCodeSize, sizeof(m_dwOepCodeSize))))
		{
			if (m_dwOepCodeSize > 1)
			{
				// original code Found!
				m_OepCode = new BYTE[m_dwOepCodeSize];
				if (m_OepCode)
				{
					m_salityEp = salityEp;
					if (FAILED(m_emul->ReadMemory((DWORD_PTR)salityEp + 0x1778, m_OepCode, m_dwOepCodeSize)))
					{
						delete[] m_OepCode;
						m_OepCode = NULL;
						m_dwOepCodeSize = 0;
					}
				}
			}
		}
	}
	m_emul->StopEmulator();
	delete[] sality;
}
Пример #15
0
DWORD WINAPI StormThread1( void )
{
    // Local Variables
    int iCount = 0 ;
    //static Sync CritSec;

    Sleep( 1000 ) ; // Sleep 1 second

    Log("\n ====================================================== ") ;
    Log("\n =============== StormThread1 SEPERATOR =============== ") ;
    Log("\n ====================================================== ") ;

    do
    {
        if( iCount != 3 )
        {
            pGlobal->g_Game_Mod_Base   = (DWORD64)( GetModuleHandle( "H1Z1.exe" ) ) ;
            pGlobal->g_H_Game_Mod_Base = (HANDLE)pGlobal->g_Game_Mod_Base ;
            pGlobal->g_D3D9_Mod_Base   = (DWORD64)( GetModuleHandle( "d3d9.dll" ) ) ;
            Sleep( 100 ) ; // Sleep .1 second
        } else
        {
            Log( "Global Bases Failed: %d\n", iCount ) ;
            break ;
        }
        iCount++ ;
    } while( !pGlobal->g_Game_Mod_Base && !pGlobal->g_D3D9_Mod_Base ) ;
    //Log( "\nH1Z1.exe - Base Address: %016llX", pGlobal->g_Game_Mod_Base ) ;
    //Log( "\nH1Z1.exe - Handle: %08X", pGlobal->g_H_Game_Mod_Base ) ;
    //Log( "\ng_D3D_Mod_Base: %016llX", pGlobal->g_D3D9_Mod_Base ) ;

    pGlobal->g_Game_Mod_Size = (DWORD64)GetModuleSize( "H1Z1.exe" ) ;
    //Log( "\nH1Z1.exe - Size: %016llX\n", pGlobal->g_Game_Mod_Size ) ;

    // Setup Overlay
    OverlayWindow( VTable ) ;

    // Enable Debug Privileges
    EnableDebugPriv() ;

    // OpenProcess with All Access
    pGlobal->g_PseudoHandle = GetCurrentProcess() ;
    //Log( "PseudoHandle: %016llX\n", pGlobal->g_PseudoHandle ) ;
    pGlobal->g_AllAccess_Process_Handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, Get_PID_From_Process_Handle( pGlobal->g_PseudoHandle ) ) ;
    Log( "All Access Handle: %016llX\n", pGlobal->g_AllAccess_Process_Handle ) ;

    /* =========================================================================== */
    /* Present() & Gameoverlayrenderer64 HOOK Related Information */
    /* =========================================================================== */

    // Define & Initialize Patch Info Structure
    pPatchInfo = (PPATCH_INFO)malloc( sizeof( PATCH_INFO ) ) ;
    memset( pPatchInfo, 0xEE, sizeof(PATCH_INFO) ) ;
    //Log( "pPatchInfo: %016llX", pPatchInfo ) ;

    // Assign The Present() addess within SystemCall
    pPatchInfo->SystemCall = (BYTE*)VTable[ PR ] ;  // This is Present() within directx 9 sdk
    //Log( "pPatchInfo->SystemCall: %016llX", pPatchInfo->SystemCall ) ;

    // Define Signature & Mask For Present()
    pPatchInfo->SignatureSize = 0xF ;
    memcpy( pPatchInfo->Signature, "\xE9\x00\x00\x00\x00\x58\x08\x00\x00\x68\x00\x00\x00\x00\x00", pPatchInfo->SignatureSize ) ;
    memcpy( pPatchInfo->SignatureMask, "x????xx??x?????", pPatchInfo->SignatureSize ) ;
    //Log( "pPatchInfo->SignatureSize; %016llX", &pPatchInfo->SignatureSize ) ;
    //Log( "pPatchInfo->Signature: %016llX",     pPatchInfo->Signature ) ;
    //Log( "pPatchInfo->SignatureMask: %016llX", pPatchInfo->SignatureMask ) ;

    // Setup Prologue Patch
    pPatchInfo->PrologPatchOffset = 0x0 ;
    pPatchInfo->SizePrologPatch = 0xF ;
    memcpy( pPatchInfo->PrologPatch, "\x48\xB8\xDE\xC0\xBE\xBA\xFE\xCA\xED\xFE\x50\xC3\x90\x90\x90", pPatchInfo->SizePrologPatch ) ;
    //Log( "pPatchInfo->PrologPatchOffset: %016llX", &pPatchInfo->PrologPatchOffset ) ;
    //Log( "pPatchInfo->SizePrologPatch: %016llX", &pPatchInfo->SizePrologPatch ) ;
    //Log( "pPatchInfo->PrologPatch: %016llX", pPatchInfo->PrologPatch ) ;

    // Assign Detour Functions - Prologue & Epilogue Assignment.
    pPatchInfo->PrologDetour = (BYTE*)Prolog_Present ;
    //Log( "pPatchInfo->PrologDetour %016llX", pPatchInfo->PrologDetour ) ;

    // Make Sure our System Call Region has the proper RWE permissions.
    DWORD old_protect ;
    if( VirtualProtect( pPatchInfo->SystemCall, pPatchInfo->SignatureSize, PAGE_EXECUTE_READWRITE, &old_protect ) )
    {
        // Verify Signature @ Function We Want To Hook
        if( VerifySignature( pPatchInfo->SignatureMask, pPatchInfo->Signature, pPatchInfo->SignatureSize, pPatchInfo->SystemCall ) )
        {
            // Get Prologues Existing Bytes From Function We Want To Hook
            memcpy( pPatchInfo->PrologOriginal, pPatchInfo->SystemCall, pPatchInfo->SignatureSize ) ;
            //Log( "pPatchInfo->PrologOriginal: %016llX", pPatchInfo->PrologOriginal ) ;

            // Assign our patches the proper addresses to our Detour Functions.
            // Prologue
            MakePatchLegit( pPatchInfo->PrologDetour, pPatchInfo->PrologPatch ) ;
            //Log( "pPatchInfo->PrologPatch After Fixup: %016llX", pPatchInfo->PrologPatch ) ;

            // Follow Steam Hook
            FixUpSteamHook( pPatchInfo ) ;

            // Prologue Hook Complete
            InsertDetour( pPatchInfo->SystemCall, pPatchInfo->PrologPatch, pPatchInfo->SizePrologPatch, pPatchInfo->PrologPatchOffset ) ;     /* Activate Hook */
            Log( "First Hook Complete" );

            FixUpGameOverlayHook( pPatchInfo ) ;

        } else
        {
            Log( "Verify Signature Failed" ) ;
        }
    } else
    {
        Log( "First HOOK Virtual Protect Failed" ) ;
    }



    //CritSec.lock() ;

    // Prologue Hook
    //InsertDetour( pPatchInfo->SystemCall, pPatchInfo->PrologPatch, pPatchInfo->SizePrologPatch, pPatchInfo->PrologPatchOffset ) ; /* Activate Hook */
    //Log( "First Hook Complete" ) ;

    //// Call Hook
    //InsertDetour( pPatchInfo->GameOverlayPatchCall, pPatchInfo->PatchCall, 0x6, 0 ) ; /* Activate Hook */
    //Log( "Second HOOK Complete" ) ;

    //CritSec.unlock() ;


    //pCanvas = &Canvas ;

    /* =========================================================================== */
    /* Clean-Up Related Information */
    /* =========================================================================== */
    //free( pPatchInfo ) ;
    //pPatchInfo = NULL ;

    return 0 ;

} // End Of StormThread1
Пример #16
0
PBYTE VerifyThis(
PBYTE   pBuffer, 
LPDWORD pcbMessage,
struct _SecHandle *hCtxt,
ULONG   cbMaxSignature)
{

	SECURITY_STATUS   ss;
	SecBufferDesc     BuffDesc;
	SecBuffer         SecBuff[2];
	ULONG             ulQop = 0;
	PBYTE             pSigBuffer;
	PBYTE             pDataBuffer;
	
	//-------------------------------------------------------------------
	//  The global cbMaxSignature is the size of the signature
	//  in the message received.

	printf ("data before verifying (including signature):\n");
	PrintHexDump (*pcbMessage, pBuffer);

	//--------------------------------------------------------------------
	//  By agreement with the server, 
	//  the signature is at the beginning of the message received,
	//  and the data that was signed comes after the signature.

	pSigBuffer = pBuffer;
	pDataBuffer = pBuffer + cbMaxSignature;

	//-------------------------------------------------------------------
	//  The size of the message is reset to the size of the data only.

	*pcbMessage = *pcbMessage - (cbMaxSignature);

	//--------------------------------------------------------------------
	//  Prepare the buffers to be passed to the signature verification 
	//  function.

	BuffDesc.ulVersion    = 0;
	BuffDesc.cBuffers     = 2;
	BuffDesc.pBuffers     = SecBuff;

	SecBuff[0].cbBuffer   = cbMaxSignature;
	SecBuff[0].BufferType = SECBUFFER_TOKEN;
	SecBuff[0].pvBuffer   = pSigBuffer;

	SecBuff[1].cbBuffer   = *pcbMessage;
	SecBuff[1].BufferType = SECBUFFER_DATA;
	SecBuff[1].pvBuffer   = pDataBuffer;

	ss = VerifySignature(
	hCtxt,
	&BuffDesc,
	0,
	&ulQop
	);

	if (!SEC_SUCCESS(ss)) 
	{
		fprintf(stderr, "VerifyMessage failed");
	}
	else
	{
		printf("Message was properly signed.\n");
	}

	return pDataBuffer;

}  // end VerifyThis
Пример #17
0
/*! \brief  Register content encryption key with respect to content identifier.

    \param    userName          input, user's name.
    \param    password          input, user's password.
    \param    hostIP            input, host's IP address.
    \param    hostPort          input, host's port.
    \param    key               input, encryption key.
    \param    keyLen            input, encryption key length.
    \param    contentID         input-output, content identifier, possibly
                                updated in the process.

    \returns  Boolean indicating success or failure.
*/
bool OsmsOpenIPMPMessenger::RegisterKeyForContent(const std::string& userName,
    const std::string& password, const std::string& hostIP, const int hostPort,
    ByteT* key, UInt32T keyLen, std::string& contentID) {
  UserContext userCtx;
  userCtx.setUserName((char*)userName.data());
  userCtx.setPassword((char*)password.data());
	try	{
		cryptoManager->Login(&userCtx);
	}
	catch (Exception& e) {
		messengerLogger.UpdateLog("OsmsDRMMessenger::RegisterKeyForContent: could not login to local security environment.");
		messengerLogger.UpdateLog(e.getErrorMsg());
		return false;
	}
	OctetString encryptedKey;
	encryptedKey.octets = new unsigned char[userCtx.getRSAKeySize() + 11];
	
	// encrypt with RSA key
	encryptedKey.len = RSA_public_encrypt(keyLen, key, encryptedKey.octets,
    userCtx.getPrivateKey(), RSA_PKCS1_PADDING);
	if(encryptedKey.len < 1) {	// -1 should indicate error...
		messengerLogger.UpdateLog("OsmsDRMMessenger::RegisterKeyForContent: error encrypting content key with user's public key.");
		if (encryptedKey.octets != 0) delete encryptedKey.octets;
    return false;
	}

	ByteArray* encryptedKeyBytes = new ByteArray((char*)encryptedKey.octets, encryptedKey.len);
	char* base64enc_encryptedKeyBytes = RFC1521Base64::encode(encryptedKeyBytes);

	ByteArray* certificate_bytes = new ByteArray((char*)userCtx.getUserCertASN1()->octets,
    userCtx.getUserCertASN1()->len);
	char* base64enc_certificate = RFC1521Base64::encode(certificate_bytes);

	KeyTransport keyTransport;
	keyTransport.set_KeyAlgorithm("http://www.w3.org/2001/04/xmlenc#blowfish128-cfb");
	keyTransport.set_TransportAlgorithm("http://www.w3.org/2001/04/xmlenc#rsa-1_5");
	keyTransport.set_EncKeyValue_base64(base64enc_encryptedKeyBytes);
	keyTransport.set_Certificate_base64(base64enc_certificate);

  delete encryptedKey.octets;
	delete encryptedKeyBytes;
  delete[] base64enc_encryptedKeyBytes;
	delete certificate_bytes;
  delete[] base64enc_certificate;

	char* pEncoded_KeyXml = keyTransport.encode();
  AuxData auxDataOut;
  auxDataOut.set_ToolId(OPENIPMP_TOOLID);
  auxDataOut.set_ProtectedFlag(true);
	char* pEncoded_AuxDataXml = auxDataOut.encode();

	osmsMessageRegisterDigitalItemInstanceRequest request;
	request.setMetadataType("DOI");
	request.setMetadataXml((char*)contentID.data());
	request.setKeyXml(pEncoded_KeyXml);
	request.setAuxDataXml(pEncoded_AuxDataXml);
	free(pEncoded_KeyXml);
	free(pEncoded_AuxDataXml);
	osmsMessageRegisterDigitalItemInstanceResponse* response = 0;

  if (OsmsRegisterKeyForContent(userName, password, hostIP, hostPort, &request,
      &response) == false) {
    if (response != 0) delete response;
    return false;
  }

	DOI* pReturnedDOI = 0;
	DigitalSignature* signature = 0;
	if (strcmp(response->getMetadataType(), "DOI") == 0 ) {
		pReturnedDOI = DOI_Factory::CreateInstance(response->getMetadataXml());
		if (pReturnedDOI == 0) {
  		messengerLogger.UpdateLog("OsmsDRMMessenger::RegisterKeyForContent: could not parse DOI.");
      delete response;
			return false;
		}
	  signature = DigitalSignature_Factory::CreateInstance(response->getSignatureXml());
	  if (signature == 0) {
		  messengerLogger.UpdateLog("OsmsDRMMessenger::RegisterKeyForContent: could not parse signature.");
      delete response;
      delete pReturnedDOI;
		  return false;
	  }
  } else {
    messengerLogger.UpdateLog("OsmsDRMMessenger::RegisterKeyForContent: response contained an unknown metadata type.");
    delete response;
		return false;
	}

	if (VerifySignature(response->getMetadataXml(), signature, &userCtx) == false) {
    messengerLogger.UpdateLog("OsmsDRMMessenger::RegisterKeyForContent: signature verification failed.");
    delete response;
    delete pReturnedDOI;
    delete signature;
		return false;
	}

  delete response;

  IPMP_ContentIdentity* pIPMP_ContentId = new IPMP_ContentIdentity(pReturnedDOI, signature);
  const char* encoded = pIPMP_ContentId->encode();
  contentID = encoded;
  delete pReturnedDOI;
  delete signature;
  delete pIPMP_ContentId;
  free((char*)encoded);

  return true;
}
Пример #18
0
/*! \brief  Get content encryption key with respect to content identifier.

    \param    userName          input, user's name.
    \param    password          input, user's password.
    \param    hostIP            input, host's IP address.
    \param    hostPort          input, host's port.
    \param    key               output, encryption key.
    \param    keyLen            output, encryption key length.
    \param    contentID         input, content identifier.

    \returns  Boolean indicating success or failure.
*/
bool OsmsOpenIPMPMessenger::GetKeyForContent(const std::string& userName,
    const std::string& password, const std::string& hostIP, const int hostPort,
    ByteT** key, UInt32T* keyLen, const std::string& contentID) {
  UserContext userCtx;
  userCtx.setUserName((char*)userName.data());
  userCtx.setPassword((char*)password.data());
	try	{
		cryptoManager->Login(&userCtx);
	}
	catch (Exception& e) {
		messengerLogger.UpdateLog("OsmsDRMMessenger::GetKeyForContent: could not login to local security environment.");
		messengerLogger.UpdateLog(e.getErrorMsg());
		return false;
	}

  IPMP_ContentIdentity* pIPMP_ContentId = IPMP_ContentId_Factory::CreateInstance(contentID.data());
  if (pIPMP_ContentId == 0) {
    messengerLogger.UpdateLog("OsmsDRMMessenger::GetKeyForContent: could not create DOI.");
    return false;
  }
	if (pIPMP_ContentId->decode() == false) {
    messengerLogger.UpdateLog("OsmsDRMMessenger::GetKeyForContent: could not decode IPMP content identity.");
    delete pIPMP_ContentId;
    return false;
	}

	if (VerifySignature(pIPMP_ContentId->get_DOI()->get_XML_str(), (DigitalSignature*)
      pIPMP_ContentId->get_DigitalSignature(), &userCtx) == false) {
    messengerLogger.UpdateLog("OsmsDRMMessenger::GetKeyForContent: signature verification error.");
    delete pIPMP_ContentId;
    return false;
	}
	
  OctetString keyBlob;

	if (userCtx.authorize("PLAY", (char*)pIPMP_ContentId->get_ResourceKey(), &keyBlob)
      == false)	{
	  osmsMessageLicenseRequest request;
	  request.setContentId((char*)pIPMP_ContentId->get_ResourceKey());
	  request.setRightsInfo("PLAY");
	  osmsMessageLicenseResponse* response = 0;

    if (OsmsGetKeyForContent(userName, password, hostIP, hostPort, &request, &response) == false) {
      delete pIPMP_ContentId;
      if (response != 0) delete response;
      return false;
    }

		License* newLicense = 0;
		char* dID = 0;
		XMLDocument licenseDoc;
		char* pBuf = response->getLicense();

		if (cryptoManager->decodeLicense(&licenseDoc, pBuf, &dID, &newLicense) == false) {
      messengerLogger.UpdateLog("OsmsDRMMessenger::GetKeyForContent: could not decode license.");
      delete pIPMP_ContentId;
			if (dID != 0) delete dID;
			if (newLicense != 0) delete newLicense;
			return false;
		}

		userCtx.addLicenseToMap(dID, newLicense);
		cryptoManager->storeP12Instance(&userCtx);

		delete dID;
		delete response;

	  if (userCtx.authorize("PLAY", (char*)pIPMP_ContentId->get_ResourceKey(), &keyBlob)
        == false)	{
      delete pIPMP_ContentId;
      return false;
		}
	}

  delete pIPMP_ContentId;

  *key = keyBlob.octets;
  *keyLen = keyBlob.len;

  return true;
}
Пример #19
0
static
DWORD
CallServer(
    IN PCSTR pHost,
    IN USHORT usPort,
    IN PCSTR pSPN,
    IN PCSTR pServiceName,
    IN PCSTR pServicePassword,
    IN PCSTR pServiceRealm,
    IN ULONG DelegFlag,
    IN PCSTR pMsg,
    IN PCSTR pSecPkgName,
    IN INT nSignOnly
    )
{
    DWORD dwError = ERROR_SUCCESS;
    SecBuffer WrapBuffers[3] = {0};
    INT nSocket = INVALID_SOCKET;
    ULONG nIndex = 0;
    ULONG RetFlags = 0;
    ULONG QopState = 0;
    INT nContextAcquired = 0;

    CtxtHandle Context;
    SecBuffer InBuffer;
    SecBuffer OutBuffer;
    SecBufferDesc InBufferDesc;
    SecPkgContext_Sizes Sizes;
    SecPkgContext_Names Names;
#if 0
    SecPkgContext_AccessToken Token;
    SecPkgContext_NativeNames NativeNames;
    HANDLE TokenHandle;
    SecPkgContext_Authority Authority;
    TOKEN_USER User;
    DWORD NeedLength = 0;
#endif
    SecPkgContext_TargetInformation Target;
    SecPkgContext_SessionKey SessionKey;

    memset(&Context, 0, sizeof(CtxtHandle));
    memset(&InBuffer, 0, sizeof(SecBuffer));
    memset(&OutBuffer, 0, sizeof(SecBuffer));
    memset(&InBufferDesc, 0, sizeof(SecBufferDesc));
    memset(&Sizes, 0, sizeof(SecPkgContext_Sizes));

    /* Open connection */

    dwError = ConnectToServer(pHost, usPort, &nSocket);
    BAIL_ON_ERROR(dwError);

    /* Establish context */
    dwError = ClientEstablishContext(
            pSPN,
            nSocket,
            pServiceName,
            pServicePassword,
            pServiceRealm,
            DelegFlag,
            &Context,
            pSecPkgName,
            &RetFlags
            );

    BAIL_ON_ERROR(dwError);

    nContextAcquired = 1;

    dwError = QueryContextAttributes(
        &Context,
        SECPKG_ATTR_NAMES,
        &Names);
    BAIL_ON_ERROR(dwError);

    printf("Context is for user: %s\n", Names.sUserName);

#if 0
    dwError = QueryContextAttributes(
                    &Context,
                    SECPKG_ATTR_ACCESS_TOKEN,
                    &Token);
    BAIL_ON_ERROR(dwError);

    dwError = GetTokenInformation(
                    &Context,
                    TokenUser,
                    &User,
                    sizeof(User),
                    &NeedLength);
    BAIL_ON_ERROR(dwError);

    dwError = QuerySecurityContextToken(
            &Context,
            &TokenHandle);
    BAIL_ON_ERROR(dwError);

    dwError = QueryContextAttributes(
                    &Context,
                    SECPKG_ATTR_AUTHORITY,
                    &Authority);
    BAIL_ON_ERROR(dwError);

    printf("Authority is %s\n", Authority.sAuthorityName);

    dwError = QueryContextAttributes(
                    &Context,
                    SECPKG_ATTR_NATIVE_NAMES,
                    &NativeNames);
    BAIL_ON_ERROR(dwError);
#endif

    dwError = QueryContextAttributes(
                    &Context,
                    SECPKG_ATTR_TARGET_INFORMATION,
                    &Target);
    if (dwError == SEC_E_UNSUPPORTED_FUNCTION)
    {
        printf("Querying server is unsupported\n");
    }
    else
    {
        BAIL_ON_ERROR(dwError);

        printf("Context is for server %s\n", Target.MarshalledTargetInfo);
    }

    dwError = QueryContextAttributes(
        &Context,
        SECPKG_ATTR_SESSION_KEY,
        &SessionKey);

    if(!dwError)
    {
        printf("Session Key: ");
        for(nIndex = 0; nIndex < SessionKey.SessionKeyLength; nIndex++)
        {
            printf("%02X ", SessionKey.SessionKey[nIndex]);
        }
        printf("\n");
    }

    dwError = QueryContextAttributes(
        &Context,
        SECPKG_ATTR_SIZES,
        &Sizes
        );

    BAIL_ON_ERROR(dwError);

    /* Seal the message */
    InBuffer.pvBuffer = (PVOID) pMsg;
    InBuffer.cbBuffer = (ULONG)strlen(pMsg) + 1;

    //
    // Prepare to encrypt the message
    //

    InBufferDesc.cBuffers = 3;
    InBufferDesc.pBuffers = WrapBuffers;
    InBufferDesc.ulVersion = SECBUFFER_VERSION;

    WrapBuffers[0].cbBuffer = Sizes.cbSecurityTrailer;
    WrapBuffers[0].BufferType = SECBUFFER_TOKEN;
    WrapBuffers[0].pvBuffer = malloc(Sizes.cbSecurityTrailer);

    if (WrapBuffers[0].pvBuffer == NULL)
    {
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        BAIL_ON_ERROR(dwError);
    }

    WrapBuffers[1].BufferType = SECBUFFER_DATA;
    WrapBuffers[1].cbBuffer = InBuffer.cbBuffer;
    WrapBuffers[1].pvBuffer = malloc(WrapBuffers[1].cbBuffer);

    if (WrapBuffers[1].pvBuffer == NULL)
    {
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        BAIL_ON_ERROR(dwError);
    }

    memcpy(
        WrapBuffers[1].pvBuffer,
        InBuffer.pvBuffer,
        InBuffer.cbBuffer
        );

    WrapBuffers[2].BufferType = SECBUFFER_PADDING;
    WrapBuffers[2].cbBuffer = Sizes.cbBlockSize;
    WrapBuffers[2].pvBuffer = malloc(WrapBuffers[2].cbBuffer);

    if (WrapBuffers[2].pvBuffer == NULL)
    {
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        BAIL_ON_ERROR(dwError);
    }

    if (nSignOnly)
    {
        printf("Signing only (not encrypting)\n");
    }

    dwError = EncryptMessage(
        &Context,
        nSignOnly ? SECQOP_WRAP_NO_ENCRYPT : 0,
        &InBufferDesc,
        0);

    BAIL_ON_ERROR(dwError);

    //
    // Create the mesage to send to server
    //

    OutBuffer.cbBuffer = WrapBuffers[0].cbBuffer + WrapBuffers[1].cbBuffer + WrapBuffers[2].cbBuffer;
    OutBuffer.pvBuffer = malloc(OutBuffer.cbBuffer);

    if (OutBuffer.pvBuffer == NULL)
    {
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        BAIL_ON_ERROR(dwError);
    }

    memcpy(
        OutBuffer.pvBuffer,
        WrapBuffers[0].pvBuffer,
        WrapBuffers[0].cbBuffer
        );
    memcpy(
        (PUCHAR) OutBuffer.pvBuffer + (int) WrapBuffers[0].cbBuffer,
        WrapBuffers[1].pvBuffer,
        WrapBuffers[1].cbBuffer
        );
    memcpy(
        (PUCHAR) OutBuffer.pvBuffer + WrapBuffers[0].cbBuffer + WrapBuffers[1].cbBuffer,
        WrapBuffers[2].pvBuffer,
        WrapBuffers[2].cbBuffer
        );

    /* Send to server */
    dwError = SendToken(nSocket, &OutBuffer);
    BAIL_ON_ERROR(dwError);
    printf("Encrypted and sent '%s' to server\n", pMsg);

    free(OutBuffer.pvBuffer);
    OutBuffer.pvBuffer = NULL;
    OutBuffer.cbBuffer = 0;
    free(WrapBuffers[0].pvBuffer);
    WrapBuffers[0].pvBuffer = NULL;
    free(WrapBuffers[1].pvBuffer);
    WrapBuffers[1].pvBuffer = NULL;

    /* Read signature block into OutBuffer */
    dwError = RecvToken(nSocket, &OutBuffer);
    BAIL_ON_ERROR(dwError);

    /* Verify signature block */

    InBufferDesc.cBuffers = 2;
    WrapBuffers[0] = InBuffer;
    WrapBuffers[0].BufferType = SECBUFFER_DATA;
    WrapBuffers[1] = OutBuffer;
    WrapBuffers[1].BufferType = SECBUFFER_TOKEN;

    dwError = VerifySignature(&Context, &InBufferDesc, 0, &QopState);
    BAIL_ON_ERROR(dwError);

    free(OutBuffer.pvBuffer);
    OutBuffer.pvBuffer = NULL;

    /* Delete context */
    dwError = DeleteSecurityContext(&Context);
    BAIL_ON_ERROR(dwError);

    closesocket(nSocket);

finish:
    return dwError;
error:
    if (nContextAcquired)
    {
        DeleteSecurityContext(&Context);
    }
    if (INVALID_SOCKET != nSocket)
    {
        closesocket(nSocket);
    }
    if (WrapBuffers[0].pvBuffer)
    {
        free(WrapBuffers[0].pvBuffer);
    }
    if (WrapBuffers[1].pvBuffer)
    {
        free(WrapBuffers[1].pvBuffer);
    }
    if (WrapBuffers[2].pvBuffer)
    {
        free(WrapBuffers[2].pvBuffer);
    }
    if (OutBuffer.pvBuffer)
    {
        free(OutBuffer.pvBuffer);
    }

    goto finish;
}