Пример #1
0
static long TestPteidSendApdu(CReader & oReader)
{
	long lErrors = 0;

	printf("\nTesting SendAPDU()\n");

	// Send a Get Card Data APDU
	unsigned char tucGetCardData[] = {0x80, 0xE4, 0x00, 0x00, 0x1C};
	CByteArray oGetCardData(tucGetCardData, sizeof(tucGetCardData));
	CByteArray oData = oReader.SendAPDU(oGetCardData);
	// Serial nr. are the first 16 bytes of the Get Card Data APDU
	std::string csSerialNr = oReader.GetSerialNr();
	if (csSerialNr != oData.ToString(false, true, 0, 16))
		ERR_LOG("SendAPDU(GetCardData) returns wrong data (bad serial nr.)\n", lErrors);

	// Send a Select MF APDU
	unsigned char tucSelectMF[] = {0x00, 0xa4, 0x02, 0x0C, 0x02, 0x3f, 0x00};
	CByteArray oSelectMF(tucSelectMF, sizeof(tucSelectMF));
	oData = oReader.SendAPDU(oSelectMF);
	// Result should be 90 00
	if (oData.Size() != 2 || oData.GetByte(0) != 0x90 || oData.GetByte(1) != 0x00)
	{
		ERR_LOG("SendAPDU(GetCardData) returns wrong data (bad serial nr.)\n", lErrors);
		printf("    (result = %s\n", oData.ToString().c_str());
	}

	return lErrors;
}
Пример #2
0
static long TestPteidPinStatus(CReader & oReader, unsigned char ucVersion)
{
	long lErrors = 0;

	printf("\nTesting PinStatus()\n");

	tPin pin = oReader.GetPin(0);
	unsigned long ulTriesLeft = oReader.PinStatus(pin);

	if (ucVersion < 0x20)
	{
		if (ulTriesLeft != PIN_STATUS_UNKNOWN)
		{
			ERR_LOG("PinStatus() for a V1 card doesn't return PIN_STATUS_UNKNOWN\n", lErrors);
			printf("    (remaining attempts = %ld)\n", ulTriesLeft);
		}
	}
	else
	{
		if (ulTriesLeft > 3)
		{
			ERR_LOG("PinStatus() for a V2 card doesn't return 0, 1, 2 or 3\n", lErrors);
			printf("    (remaining attempts = %ld)\n", ulTriesLeft);
		}
		else
		if (ulTriesLeft != 3)
		  printf("    (warning: remaining tries for the \"%s\" PIN: %ld)\n", pin.csLabel.c_str(), ulTriesLeft);
	}

	return lErrors;
}
Пример #3
0
static long TestReadLongFile(CReader & oReader, const std::string & csPath)
{
	long lErrors = 0;

	printf("\nTesting CReader::ReadFile() for long files\n");

	try
	{
		CByteArray oFullData = oReader.ReadFile(csPath, 0, FULL_FILE);

		CByteArray oData1 = oReader.ReadFile(csPath, 0, 252);
		if (oData1.Size() != 252 || memcmp(oFullData.GetBytes(), oData1.GetBytes(), 252) != 0)
			ERR_LOG("ERR: CReader::ReadFile(length != 252) failed\n", lErrors);

		CByteArray oData2 = oReader.ReadFile(csPath, 0, 253);
		if (oData2.Size() != 253 || memcmp(oFullData.GetBytes(), oData2.GetBytes(), 253) != 0)
			ERR_LOG("ERR: CReader::ReadFile(length != 253) failed\n", lErrors);

		CByteArray oData3 = oReader.ReadFile(csPath, 100, 400);
		if (oData3.Size() != 400 || memcmp(oFullData.GetBytes() + 100, oData3.GetBytes(), 400) != 0)
			ERR_LOG("ERR: CReader::ReadFile(offs=100, len = 400) failed\n", lErrors);
	}
	catch(const CMWException &e)
	{
		ERR_LOG("ERR: CReader::ReadFile() threw an MWException\n", lErrors);
		printf("   MWException code: 0x%0x\n", (unsigned)e.GetError());
	}
	catch (...)
	{
		ERR_LOG("ERR: CReader::ReadFile() threw an MWException\n", lErrors);
	}

	return lErrors;
}
Пример #4
0
static long TestPteidCtrl(CReader & oReader, unsigned char ucVersion)
{
	long lErrors = 0;

	printf("\nTesting Ctrl()\n");

	// CTRL_PTEID_GETCARDDATA
	CByteArray oCardInfo = oReader.GetInfo();
	CByteArray oUnsignedCardData = oReader.Ctrl(CTRL_PTEID_GETCARDDATA, CByteArray());
	if (!oCardInfo.Equals(oUnsignedCardData))
		ERR_LOG("ERR: Ctrl(CTRL_PTEID_GETCARDDATA) != GetInfo()\n", lErrors);

	// CTRL_PTEID_GETSIGNEDCARDDATA
	if (ucVersion >= 0x20)
	{
		CByteArray oSignedCardData = oReader.Ctrl(CTRL_PTEID_GETSIGNEDCARDDATA, CByteArray());

		if (oSignedCardData.Size() != oUnsignedCardData.Size() + 128)
			ERR_LOG("ERR: signed and unsigned card data should differ in size by 128 bytes\n", lErrors);

		oSignedCardData.Chop(128);
		if (!oUnsignedCardData.Equals(oSignedCardData))
			ERR_LOG("ERR: start of unsigned card data should be the same as for unsigned card data\n", lErrors);
	}

	// CTRL_PTEID_GETSIGNEDPINSTATUS
	if (ucVersion >= 0x20)
	{
		tPin pin = oReader.GetPin(0);

		CByteArray oData(1);
		oData.Append((unsigned char) pin.ulPinRef);
		CByteArray oSignedPinStatus = oReader.Ctrl(CTRL_PTEID_GETSIGNEDPINSTATUS, oData);

		if (oSignedPinStatus.Size() != 129)
			ERR_LOG("ERR: signed pin status response should be (1 + 128) bytes\n", lErrors);
		else if (oSignedPinStatus.GetByte(0) != oReader.PinStatus(pin))
			ERR_LOG("ERR: signed pin status differs from unsigned PIN status\n", lErrors);
	}

	// CTRL_PTEID_INTERNAL_AUTH
	CByteArray oData(21); // Key ref (1 byte) + challenge(20 bytes)
	oData.Append(0x81);
	for (int i = 0; i < 20; i++)
		oData.Append((unsigned char) rand());
	CByteArray oResp1 = oReader.Ctrl(CTRL_PTEID_INTERNAL_AUTH, oData);
	if (oResp1.Size() != 128)
		ERR_LOG("ERR: Internal Auth. didn't return 128 bytes\n", lErrors);
	CByteArray oResp2 = oReader.Ctrl(CTRL_PTEID_INTERNAL_AUTH, oData);
	if (!oResp1.Equals(oResp2))
		ERR_LOG("ERR: Internal Auth. on the same data returns a different result\n", lErrors);
	oData.SetByte(oData.GetByte(5) + 0x01, 5);
	CByteArray oResp3 = oReader.Ctrl(CTRL_PTEID_INTERNAL_AUTH, oData);
	if (oResp1.Equals(oResp3))
		ERR_LOG("ERR: Internal Auth. on the different data returns the same result\n", lErrors);

	return lErrors;
}
Пример #5
0
static long TestSignaturesWithKey(CReader & oReader, tPrivKey & key, bool bFullTest)
{
	// Note tested for now: SIGN_ALGO_RSA_RAW
	unsigned long tulSignAlgos[] = {SIGN_ALGO_SHA1_RSA_PKCS, 
		SIGN_ALGO_MD5_RSA_PKCS,
#if (OPENSSL_VERSION_NUMBER > 0x009070ffL)
		SIGN_ALGO_SHA256_RSA_PKCS, 
		SIGN_ALGO_SHA384_RSA_PKCS, 
		SIGN_ALGO_SHA512_RSA_PKCS,
		SIGN_ALGO_RIPEMD160_RSA_PKCS,
#endif
		SIGN_ALGO_SHA1_RSA_PSS, 
		SIGN_ALGO_RSA_PKCS};

	long lErrors = 0;

	CByteArray oCertData;
	tCert cert = oReader.GetCertByID(key.ulID);
	if (cert.bValid)
		oCertData = oReader.ReadFile(cert.csPath);
	else
	  printf("  warning: no cert found for key \"%s\", can't verify the signatures!\n", key.csLabel.c_str() );

	unsigned long ulSupportedAlgos = oReader.GetSupportedAlgorithms();

	std::string csAlgos;
	int iAlgoCount = 0;
	// For each of the supported algos
	for (int i = 0; i < sizeof(tulSignAlgos) / sizeof(unsigned long); i++)
	{
		if (tulSignAlgos[i] & ulSupportedAlgos)
		{
			lErrors += SignVerify(oReader, key, oCertData, tulSignAlgos[i]);
			csAlgos += std::string(SignAlgo2String(tulSignAlgos[i]));
			iAlgoCount++;
			if (!bFullTest)
				break;
		}
	}
	if (iAlgoCount != 0)
	{
		printf("      used %d algo(s): %s\n", iAlgoCount, csAlgos.c_str());
		if (key.ulUserConsent != 0)
			printf("      (not all algos were used because each signature requires a PIN entry for this key)\n");
	}
	else
		printf("  ERR/warning: no signature algorithms are supported!\n");

	return lErrors;
}
Пример #6
0
static long TestPteid(CReader & oReader, const std::string & csPin)
{
	long lErrors = 0;

	CByteArray oCardData = oReader.GetInfo();
	unsigned char ucVersion = oCardData.GetByte(21);

	printf("Card: Belgian eID V%d.%d\n", ucVersion / 16, ucVersion % 16);

	lErrors += TestPteidSendApdu(oReader);

	lErrors += TestPteidCtrl(oReader, ucVersion);

	lErrors += TestCache(oReader, "3F00DF014035");
	lErrors += TestReadShortFile(oReader, "3F002F00");

	lErrors += TestReadLongFile(oReader, "3F00DF005038");

	std::vector <CByteArray> vAIDs;
	vAIDs.push_back(CByteArray("A000000177504B43532D3135", true));
	if (ucVersion >= 0x20)
		vAIDs.push_back(CByteArray("A000000177496446696C6573", true));
	lErrors += TestSelectApplication(oReader, vAIDs);

	lErrors += TestRandom(oReader);

	lErrors += TestPteidP15(oReader, ucVersion);

	lErrors += TestPteidPinStatus(oReader, ucVersion);

	lErrors += TestSignatures(oReader, csPin);

	return lErrors;
}
Пример #7
0
BOOL WINAPI
eidmwGenRandom(
    IN  HCRYPTPROV hProv,  //!< Handle to provider previously obtained through a call to CPAcquireContext
    IN  DWORD cbLen,       //!< Number of bytes of random data requested
    OUT LPBYTE pbBuffer)   //!< Buffer to store the random data
{
	BOOL bReturnVal = FALSE;
	DWORD dwLastError = 0;

	__CSP_TRY__

	MWLOG(LEV_INFO, MOD_CSP, L"CPGenRandom(hProv = %d) called", hProv);
	MWLOG(LEV_INFO, MOD_CSP, L"  - IN: cbLen = %d", cbLen);

	CProviderContext *poProvCtx = g_oProviderContextPool.GetProviderContext(hProv);
	std::string csContainerName = poProvCtx->GetContainerName();

	if (csContainerName == "")
	{
		dwLastError = NTE_NO_KEY;
	}
	else
	{
		CAutoMutex oAutoMutex(&g_oCalMutex);

		CReader *poReader = FindCard(poProvCtx);
		if (poReader == NULL)
		{
			dwLastError = NTE_FAIL;
		}
		else
		{
			CByteArray oRandom = poReader->GetRandom(cbLen);
			memcpy(pbBuffer, oRandom.GetBytes(), oRandom.Size());
			bReturnVal = TRUE;
		}
	}

	__STORE_LASTERROR__

	MWLOG(LEV_INFO, MOD_CSP, L" Returning CPGenRandom(hProv = %d) with code 0x%0x",
		hProv, bReturnVal ? 0 : dwLastError);

	__CSP_CATCH_SETLASTERROR__

	return (bReturnVal);
}
Пример #8
0
static long VerifyPIN(CReader &oReader, unsigned long ulAuthID)
{
	long lRet = 0;

	// If no PIN specified, do nothing
	if (g_csPin != "")
	{
		if (g_ulPinIdx >= oReader.PinCount())
		{
			printf("ERR: PIN index (%d) too big\n", g_ulPinIdx);
			lRet = -4;
		}
		else
		{
			tPin pin = oReader.GetPin(g_ulPinIdx);

			if (ulAuthID != 0)
			{
				tPin pin2 = oReader.GetPinByID(ulAuthID);
				if (memcmp(&pin, &pin2, sizeof(tPin)) != 0)
				{
					printf("ERR, PIN corresponding to AuthID (%0x) differs from the\n", ulAuthID);
					printf("  specified PIN (ID = %0x), exiting\n", pin.ulID);
					lRet = -3;
				}
			}

			if (lRet == 0)
			{
				unsigned long ulRemaining;

				if (!oReader.PinCmd(PIN_OP_VERIFY, pin, g_csPin, "", ulRemaining))
				{
					printf("ERR: wrong PIN specified on the command line, %d remaining tries\n",
						ulRemaining);
					lRet = -2;
				}
				else
					printf("\nPIN verification succeeded\n");
			}
		}
	}

	return lRet;
}
Пример #9
0
void CStringTableReader::ReadFromMemory( CReader &Reader, const uint8* pData, uint32 dataSize, const SFileHeader::SStringTable &headerInfo, uint32 &outReadLoc )
{
	assert( m_stringAddrs.empty());

	m_stringAddrs.resize( headerInfo.m_numStrings );
	FlatAddr* pstringAddrsTable = &(m_stringAddrs[0]);
	Reader.ReadDataFromMemory( pData, dataSize, pstringAddrsTable, sizeof(FlatAddr) * headerInfo.m_numStrings, outReadLoc );

	m_buffer.ReadFromMemory( Reader, pData, dataSize, headerInfo.m_sizeStringData, outReadLoc );
}
Пример #10
0
static long SignVerify(CReader & oReader, tPrivKey & key,
	const CByteArray & oCertData, unsigned long ulSignAlgo)
{
	CByteArray oData(1000);
	for (int i = 0; i < 300; i++)
		oData.Append((unsigned char) rand());

	long lHashAlgo = sign2hashAlgo(ulSignAlgo);

	if (lHashAlgo != -1)
	{
		CByteArray oSignature;
	
		CHash oHash;
		oHash.Init((tHashAlgo) lHashAlgo);
		oHash.Update(oData);

		if (ulSignAlgo == SIGN_ALGO_RSA_PKCS)
		{
			// To test SIGN_ALGO_RSA_PKCS, we take as input the SHA1 AID
			// plus the SHA1 hash of oData. This way, we can use OpenSSL's
			// SHA1 signature verification in VerifySignature().
			const unsigned char SHA1_AID[] = {0x30, 0x21, 0x30, 0x09,
				0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00,0x04, 0x14};
			CByteArray oTobeSigned(SHA1_AID, sizeof(SHA1_AID));
			oTobeSigned.Append(oHash.GetHash());
			oSignature = oReader.Sign(key, ulSignAlgo, oTobeSigned);
		}
		else
			oSignature = oReader.Sign(key, ulSignAlgo, oHash);

		bool bVerified = VerifySignature(oData, oSignature, oCertData, ulSignAlgo);

		return bVerified ? 0 : 1;
	}
	else
	{
		printf("      Signature algo %s can't be tested yet\n", SignAlgo2String(ulSignAlgo));
		return 0;
	}
}
Пример #11
0
BOOL CSelectReaderDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	CReader*	pReader;
	CString		strTitle;
	HTREEITEM	hCurrentItem;

	m_treeDevices.SetImageList(&m_ilDevice, TVSIL_NORMAL);
	m_treeDevices.SetBkColor(GetSysColor(COLOR_3DFACE));
	for (POSITION pos = m_pListReader->GetHeadPosition(); pos != NULL; )
	{
		pReader = m_pListReader->GetNext(pos);
		strTitle.Format(_T("%s, %s"), pReader->GetModel(), pReader->GetSerialNumber());
		hCurrentItem = m_treeDevices.InsertItem(strTitle, pReader->m_nState, pReader->m_nState);
		m_treeDevices.SetItemData(hCurrentItem, (DWORD_PTR)pReader);
	}
	hCurrentItem = m_treeDevices.GetFirstVisibleItem();
	if (hCurrentItem != NULL) m_treeDevices.SelectItem(hCurrentItem);
	m_treeDevices.SetFocus();
	return TRUE;
}
Пример #12
0
void CStringTableReader::ReadFromFile( CReader &Reader, IPlatformOS::ISaveReaderPtr pOSSaveReader, const SFileHeader::SStringTable &headerInfo )
{
	assert( m_stringAddrs.empty());

	m_stringAddrs.resize( headerInfo.m_numStrings );
	FlatAddr* pstringAddrsTable = &(m_stringAddrs[0]);
	Reader.ReadDataFromFile( pOSSaveReader, pstringAddrsTable, sizeof(FlatAddr) * headerInfo.m_numStrings );
	for (uint32 i = 0; i < m_stringAddrs.size(); ++i)
	{
		SwapIntegerValue( m_stringAddrs[i] );
	}

	m_buffer.ReadFromFile( Reader, pOSSaveReader, headerInfo.m_sizeStringData );
}
Пример #13
0
static long TestSignatures(CReader & oReader, const std::string & csPin)
{
	long lErrors = 0;

	printf("\nTesting CReader::Sign()\n");

	if (g_bVerifyFailed)
	{
		printf("PIN verification has failed, skipping signature tests\n");
		return lErrors;
	}

	// For all keys
	unsigned long ulPrivKeys = oReader.PrivKeyCount();
	for (unsigned long i = 0; i < ulPrivKeys && !g_bVerifyFailed; i++)
	{
		tPrivKey key = oReader.GetPrivKey(i);
		printf("  - for key \"%s\"\n", key.csLabel.c_str());

		// Verify if PIN is specified and needed
		tPin pin = oReader.GetPinByID(key.ulAuthID);
		if (csPin != "" && pin.bValid && key.ulUserConsent == 0)
		{
			unsigned long ulRemaining;
			if (!oReader.PinCmd(PIN_OP_VERIFY, pin, csPin, "", ulRemaining))
			{
				printf("ERR: PIN verification failed, quiting signature tests\n");
				g_bVerifyFailed = true;
			}
		}

		if (!g_bVerifyFailed)
			lErrors += TestSignaturesWithKey(oReader, key, i == 0);
	}

	return lErrors;
}
Пример #14
0
static long TestReadShortFile(CReader & oReader, const std::string & csPath)
{
	long lErrors = 0;

	printf("\nTesting CReader::ReadFile() for short files\n");

	try
	{
		CByteArray oFullData = oReader.ReadFile(csPath, 0, FULL_FILE);

		CByteArray oData1 = oReader.ReadFile(csPath, 2, FULL_FILE);
		if (oData1.Size() + 2 != oFullData.Size() ||
			memcmp(oData1.GetBytes(), oFullData.GetBytes() + 2, oData1.Size()) != 0)
		{
			ERR_LOG("ERR: CReader::ReadFile(offset != 0) failed\n", lErrors);
		}

		CByteArray oData2 = oReader.ReadFile(csPath, 2, oFullData.Size() - 3);
		if (oData2.Size() + 3 != oFullData.Size() ||
			memcmp(oData2.GetBytes(), oFullData.GetBytes() + 2, oData2.Size()) != 0)
		{
			ERR_LOG("ERR: CReader::ReadFile(length != FULL_FILE) failed\n", lErrors);
		}

		CByteArray oData3 = oReader.ReadFile(csPath, 0, oFullData.Size() + 1);
		if (!oData3.Equals(oFullData))
			ERR_LOG("ERR: CReader::ReadFile(length = too long) returned a wrong data\n", lErrors);

		bool bExceptionCaught = false;
		try
		{
			CByteArray oData4 = oReader.ReadFile(csPath, oFullData.Size() + 1, 1);
		}
		catch(CMWException & e) {
			bExceptionCaught = true;
			if ( (unsigned) e.GetError() != EIDMW_ERR_PARAM_RANGE)
			ERR_LOG("ERR: CReader::ReadFile(offset = too long) has thrown the wrong exception\n", lErrors);
		}
		if (!bExceptionCaught)
			ERR_LOG("ERR: CReader::ReadFile(offset = too long) didn't throw an exception\n", lErrors);

		CByteArray oData5 = oReader.ReadFile(csPath, 0, oFullData.Size());
		if (!oData5.Equals(oFullData))
			ERR_LOG("ERR: CReader::ReadFile(length = file size) failed\n", lErrors);
	}
	catch(const CMWException &e)
	{
		ERR_LOG("ERR: CReader::ReadFile() threw an MWException\n", lErrors);
		printf("   MWException code: 0x%0x\n", (unsigned) e.GetError());
	}
	catch (...)
	{
		ERR_LOG("ERR: CReader::ReadFile() threw an Exception\n", lErrors);
	}

	return lErrors;
}
Пример #15
0
static long TestRandom(CReader & oReader)
{
	long lErrors = 0;

	printf("\nTesting CReader::GetRandom()\n");

	try
	{
		for (unsigned long i = 0; i < 4; i++)
			CByteArray oData4 = oReader.GetRandom(5 * i);
	}
	catch(CMWException & e) {
		ERR_LOG("ERR: CReader::GetRandom() returned an exception\n", lErrors);
		e;
	}

	for (unsigned long i = 6; i < 10; i++)
	{
		if (oReader.GetRandom(i).Equals(oReader.GetRandom(i)))
			ERR_LOG("ERR: CReader::GetRandom() returned twice the same value\n", lErrors);
	}

	return lErrors;
}
Пример #16
0
static long TestSelectApplication(CReader & oReader, const std::vector <CByteArray> & vAIDs)
{
	long lErrors = 0;

	printf("\nTesting CReader::SelectApplication()\n");

	for (size_t i = 0; i < vAIDs.size(); i++)
	{
		try
		{
			oReader.SelectApplication(vAIDs[i]);
		}
		catch(const CMWException & e) 
		{
			ERR_LOG("ERR: CReader::SelectApplication() failed\n", lErrors);
			printf("  AID = %s, err = 0x%0x\n", vAIDs[i].ToString().c_str(), (unsigned) e.GetError());
		}
	}

	return lErrors;
}
Пример #17
0
static CByteArray HashAndSign(CReader & oReader, const tPrivKey & key,
	unsigned long signAlgo, const CByteArray & oData)
{
	tHashAlgo hashAlgo;
	if (signAlgo == SIGN_ALGO_MD5_RSA_PKCS)
		hashAlgo = ALGO_MD5;
	else if (signAlgo == SIGN_ALGO_SHA1_RSA_PKCS)
		hashAlgo = ALGO_SHA1;
	else if (signAlgo == SIGN_ALGO_SHA256_RSA_PKCS)
		hashAlgo = ALGO_SHA256;
	else
	{
		printf("Unsupport signature algorithm %d, can't sign\n", signAlgo);
		return CByteArray();
	}

	CHash oHash;
	oHash.Init(hashAlgo);
	oHash.Update(oData);

	return oReader.Sign(key, signAlgo, oHash);
}
Пример #18
0
/**
 * csPath should be the path to a big file that can be cached
 * Best do this test first, because anything is cached.
 */
static long TestCache(CReader & oReader, const std::string & csPath)
{
	long lErrors = 0;

	printf("\nTesting caching functionality (using file %s)\n", csPath.c_str());

	CByteArray oMaybeFromDisk = oReader.ReadFile(csPath);

	bool bDeleted = g_oCardLayer.DeleteFromCache(oReader.GetSerialNr());
	if (!bDeleted)
	{
		ERR_LOG("ERR: CCardLayer::DeleteFromCache() seems to fail\n", lErrors);
		printf("  (File %s should have been cached, but isn't deleted)\n", csPath.c_str());
	}

	CByteArray oFromCard = oReader.ReadFile(csPath);
	//diffFromCard = fromCard2 - fromCard1;

	CByteArray oFromMem = oReader.ReadFile(csPath);
	//diffFromMem = fromMem2 - fromMem1;

	/*
	if (2 * diffFromMem > diffFromCard)
	{
		printf("WARNING: reading %d bytes from the card (%d msec) isn't much\n",
			oFromCard.Size(), diffFromCard);
		printf("  faster then reading it from cach (%d msec)\n", diffFromMem);
	}
	*/

	if (!oFromCard.Equals(oFromMem))
		ERR_LOG("ERR: cached file contents (from memory) differ from those on the card\n", lErrors);
	else if (!oFromCard.Equals(oMaybeFromDisk))
		ERR_LOG("ERR: cached file contents (from disk) differ from those on the card\n", lErrors);

	oFromCard = oReader.ReadFile(csPath, 10, 20);
	oFromMem = oReader.ReadFile(csPath, 10, 20);
	if (!oFromCard.Equals(oFromMem))
		ERR_LOG("ERR: reading part of the cached contents fails\n", lErrors);

	return lErrors;
}
Пример #19
0
BOOL WINAPI
eidmwSignHash(
    IN  HCRYPTPROV hProv,      //!< Handle to provider previously obtained through a call to CPAcquireContext
    IN  HCRYPTHASH hHash,      //!< Handle to the hash object to be signed
    IN  DWORD dwKeySpec,       //!< Key specifier of the key with which to sign
    IN  LPCWSTR szDescription, //!< Discription of the signature (this parameter should no longer be used)
    IN  DWORD dwFlags,         //!<Currently no flags defined, should be 0
    OUT LPBYTE pbSignature,    //!< Pointer to an output buffer that will contain the resulting signature
    IN OUT LPDWORD pcbSigLen)  //!< Length of the resulting signature 
{
	BOOL bReturnVal = FALSE;
	DWORD dwLastError = 0;

	__CSP_TRY__

	MWLOG(LEV_INFO, MOD_CSP, L"CPSignHash(hProv = %d) called", hProv);
	MWLOG(LEV_INFO, MOD_CSP, L"  - IN: hHash = %d", hHash);
	MWLOG(LEV_INFO, MOD_CSP, L"  - IN: dwKeySpec = %d", dwKeySpec);
	MWLOG(LEV_INFO, MOD_CSP, L"  - IN: pbSignature = %p", pbSignature);

	CProviderContext *poProvCtx = g_oProviderContextPool.GetProviderContext(hProv);
	CProviderHash *poProvHash = poProvCtx->GetHash(hHash, false);
	std::string csContainerName = poProvCtx->GetContainerName();

	if (csContainerName == "")
	{
		dwLastError = NTE_NO_KEY;
	}
	else if (poProvHash == NULL)
	{
		dwLastError = NTE_BAD_HASH;
	}
	else
	{
		CAutoMutex oAutoMutex(&g_oCalMutex);

		CReader *poReader = FindCard(poProvCtx);
		if (poReader == NULL)
		{
			dwLastError = NTE_NO_KEY;
		}
		else
		{
			tPrivKey privKey = FindKey(poReader, csContainerName);

			if (pbSignature == NULL)
			{
				*pcbSigLen = privKey.ulKeyLenBytes;
				if (*pcbSigLen == 0)
					*pcbSigLen = 128; // Default, just in case
				bReturnVal = TRUE;
			}
			else
			{
				unsigned long ulSignAlgo = GetSignAlgo(poProvHash->GetAlgid());
				CByteArray oSignature;
				// If the hash has already been calculated (or given via CPSetHashParam())
				// then we present this value. Otherwise we present the hash object itself
				CByteArray & oHashValue = poProvHash->GetHashValue();
				if (oHashValue.Size() == 0)
					oSignature = poReader->Sign(privKey, ulSignAlgo, poProvHash->GetHashObject());
				else
					oSignature = poReader->Sign(privKey, ulSignAlgo, oHashValue);

				bReturnVal = FillProvParam(pbSignature, pcbSigLen,
					oSignature.GetBytes(), oSignature.Size());
				if (bReturnVal)
					ReverseByteOrder(pbSignature, *pcbSigLen);
			}
		}
	}

	__STORE_LASTERROR__

	MWLOG(LEV_INFO, MOD_CSP, L" Returning CPSignHash(hProv = %d) with code 0x%0x",
		hProv, bReturnVal ? 0 : dwLastError);
	if (bReturnVal)
		MWLOG(LEV_INFO, MOD_CSP, L"   - OUT: *pcbSigLen = %d", *pcbSigLen);

	__CSP_CATCH_SETLASTERROR__

	return (bReturnVal);
}
Пример #20
0
/**
 * Find the reader containing the card that corresponds to the serial number in
 * the container name.
 * If the card couldn't be found then ask for it (at least, if a reader is present)
 * If a reader has been found previously, then check if the card is still present;
 * otherwise look for the card again.
 */
static CReader * FindCard(CProviderContext *poProvCtx)
{
	std::string csSerialNr = poProvCtx->GetSerialNr();
	if (csSerialNr == "")
		return NULL;

	// Get the Reader that (perhaps) we used earlier
	CReader *poReader = poProvCtx->GetReader();

	if (poReader == NULL)
	{
		MWLOG(LEV_INFO, MOD_CSP, L" Searching for the card with serial number \"%ls\"",
			utilStringWiden(csSerialNr).c_str());

try_again:
		// Loop over all readers present, look for a card with this serial nr
		CReadersInfo oReadersInfo = g_oCardLayer.ListReaders();
		CReader *poTmpReader = NULL;
		for (unsigned long i = 0; i < oReadersInfo.ReaderCount(); i++)
		{
			try {
				poTmpReader = &g_oCardLayer.getReader(oReadersInfo.ReaderName(i));
				/*We gave up on depending on the correct card serial number to be present in the param */
				if (poTmpReader->Connect())
				{
					poReader = poTmpReader;
					break;
				}
			}
			catch(CMWException &e)
			{
				MWLOG(LEV_ERROR, MOD_CSP, L"CReader::Connect(%d) return error code 0x%0x\n", i, e.GetError());
			}
		}

		// If the card couldn't be found, ask the user for it
		if (poReader == NULL && oReadersInfo.ReaderCount() != 0)
		{
			DlgRet ret = DlgDisplayModal(DLG_ICON_INFO, DLG_MESSAGE_ENTER_CORRECT_CARD,
				L"", DLG_BUTTON_OK | DLG_BUTTON_CANCEL,DLG_BUTTON_OK, DLG_BUTTON_CANCEL);
			if (ret == DLG_OK)
				goto try_again;
			else if (ret != DLG_CANCEL)
				MWLOG(LEV_ERROR, MOD_CSP, L"CSP dialog returned error code %d\n", ret);
		}

		// Log
		if (poReader == NULL)
		{
			MWLOG(LEV_INFO, MOD_CSP, L" The card couldn't be found in the %d reader(s) present",
				oReadersInfo.ReaderCount());
		}
		else
		{
			MWLOG(LEV_INFO, MOD_CSP, L" The card was found in reader \"%ls\"",
				utilStringWiden(poReader->GetReaderName()).c_str());
		}
	}
	else
	{
		// If we already found the reader, check if the same
		// card is still inserted
		poReader->Status(true);

		if (poReader->GetSerialNr() != csSerialNr)
		{
			MWLOG(LEV_INFO, MOD_CSP, L" Card no longer present in reader \"%ls\"",
				utilStringWiden(poReader->GetReaderName()).c_str());
			poProvCtx->SetReader(NULL);
			poReader = FindCard(poProvCtx);
		}
	}

	// Keep this Reader for the next time this function is called
	poProvCtx->SetReader(poReader);

	return poReader;
}
Пример #21
0
int main(int argc, char **argv) {
  CReader *r;
  int idx;
  char *devName;
  const char *fname1;
  const char *fname2;
  const char *fname3;
  uint8_t buffer1[64*1024];
  uint8_t buffer2[64*1024];
  uint8_t buffer3[64*1024];
  int len1;
  int len2;
  int len3;
  int rv;
  uint32_t result;
  cj_ModuleInfo ModuleInfo;
  uint32_t EstimatedUpdateTime;

  if (argc<5) {
    fprintf(stderr, "Usage:\n %s READERNR IMAGEFILE SIGNATUREFILE KEYFILE\n", argv[0]);
    return 1;
  }
  idx=atoi(argv[1]);
  fname1=argv[2];
  fname2=argv[3];
  fname3=argv[4];

  fprintf(stderr, "Reading image file\n");
  len1=readFile(fname1, buffer1);
  if (len1<1) {
    fprintf(stderr, "Error reading file \"%s\"\n", fname1);
    return 2;
  }

  fprintf(stderr, "Reading signature file\n");
  len2=readFile(fname2, buffer2);
  if (len2<1) {
    fprintf(stderr, "Error reading file \"%s\"\n", fname2);
    return 2;
  }

  fprintf(stderr, "Reading key file\n");
  len3=readFile(fname3, buffer3);
  if (len3<1) {
    fprintf(stderr, "Error reading file \"%s\"\n", fname3);
    return 2;
  }


  fprintf(stderr, "Opening reader\n");
  devName=CUSBUnix::createDeviceName(idx);
  if (devName==NULL) {
    fprintf(stderr, "Device %d not found\n", idx);
    return 2;
  }

  if (getenv("CJFLASH_DEBUG"))
    Debug.setLevelMask(0xffffffff);


  r=new CReader(devName);
  rv=r->Connect();
  if (rv!=CJ_SUCCESS) {
    fprintf(stderr, "Could not connect to reader (%d)\n", rv);
    return 2;
  }

  fprintf(stderr, "Updating the keys\n");
  rv=r->CtKeyUpdate(buffer3, len3,&result);
  if (rv!=CJ_SUCCESS) {
	 fprintf(stderr, "Unable to update the keys (%d / %d)\n", rv,result);
	 return 2;
  }

  ModuleInfo.SizeOfStruct=sizeof(ModuleInfo);
  rv=r->CtGetModuleInfoFromFile(buffer1, len1,
				&ModuleInfo,
				&EstimatedUpdateTime);
  if (rv!=CJ_SUCCESS) {
    fprintf(stderr, "Unable to get module info (%d)\n", rv);
    return 2;
  }
  
  if(ModuleInfo.ID==MODULE_ID_KERNEL){
    /* for kernel updates we need the entire flash */
    fprintf(stderr,
	    "Updating the kernel module requires there is no "
	    "other module on the reader.\n"
	    "(please look at the display of "
	    "the reader and press \"OK\")\n");
    rv=r->CtDeleteALLModules(&result);
    if (rv!=CJ_SUCCESS) {
      fprintf(stderr, "Unable to flash reader (%d / %d)\n", rv,result);
      return 2;
    }
  }

  fprintf(stderr,
	  "Flashing image (please look at the "
	  "display of the reader and press \"OK\")\n");
  rv=r->CtLoadModule(buffer1, len1, buffer2, len2, &result);
  if (rv!=CJ_SUCCESS) {
    fprintf(stderr, "Unable to flash reader (%d / %d)\n", rv,result);
    return 2;
  }

  fprintf(stderr,
	  "Now the reader authentication is running.\n"
	  "Please look at the reader for checking all "
	  "versions and variants off the active modules\n");

  rv=r->CtShowAuth();
  if (rv!=CJ_SUCCESS) {
    fprintf(stderr, "Unable to show reader authentication (%d)\n", rv);
    return 2;
  }


  fprintf(stderr,
          "==========================================\n"
	  "Reader sucessfully flashed!\n"
          "\n"
	  "You might need to unplug and replug the reader.\n"
	  "==========================================\n");

  r->Disonnect();
  delete r;
  free(devName);

  return 0;
}
Пример #22
0
BOOL CPlayer::WavIsValidFile(LPCTSTR pszFile)
{
	CReader reader;
	DWORD dwBuf = 0, dwRead = 0;
	WAVEFORMATEX *pwfxSrc, wfxDst;
	pwfxSrc = NULL;

	if (!reader.Open(pszFile))
		return FALSE;

	// "RIFF"
	if (!reader.Read((LPBYTE)&dwBuf, sizeof(dwBuf), &dwRead) ||
		dwBuf != MAKEFOURCC('R', 'I', 'F', 'F'))
		goto error;

	// "WAVE"
	reader.SetPointer(4, FILE_CURRENT);	
	if (!reader.Read((LPBYTE)&dwBuf, sizeof(dwBuf), &dwRead) ||
		dwBuf != MAKEFOURCC('W', 'A', 'V', 'E'))
		goto error;

	// "fmt "
	while (TRUE) {
		if (!reader.Read((LPBYTE)&dwBuf, sizeof(dwBuf), &dwRead))
			goto error;

		if (dwBuf = MAKEFOURCC('f', 'm', 't', ' '))
			break;

		if (!reader.Read((LPBYTE)&dwBuf, sizeof(dwBuf), &dwRead))
			goto error;

		if (reader.SetPointer(dwBuf, FILE_CURRENT) == MAXLONGLONG)
			goto error;
	}

	if (!reader.Read((LPBYTE)&dwBuf, sizeof(dwBuf), &dwRead))
		goto error;

	pwfxSrc = (WAVEFORMATEX*)new BYTE[dwBuf];
	if (!reader.Read((LPBYTE)pwfxSrc, dwBuf, &dwRead))
		goto error;

#if 1
	memset(&wfxDst, 0, sizeof(wfxDst));
	wfxDst.wFormatTag = WAVE_FORMAT_PCM;
	if (acmFormatSuggest(NULL, pwfxSrc, &wfxDst,
		sizeof(WAVEFORMATEX), ACM_FORMATSUGGESTF_WFORMATTAG) != 0)
		goto error;
#endif

	delete pwfxSrc;
	reader.Close();
	return TRUE;

error:
	if (pwfxSrc) delete pwfxSrc;
	reader.Close();
	return FALSE;
}
Пример #23
0
static long TestPteidP15(CReader & oReader, unsigned char ucVersion)
{
	long lErrors = 0;

	printf("\nTesting PKCS15 functions\n");

	unsigned long ulPinCount = ucVersion < 0x20 ? 1 : 2;
	if (oReader.PinCount() != ulPinCount)
	{
		ERR_LOG("ERR: CReader::PinCount() didn't return a wrong value\n", lErrors);
	}
	else
	{
		if (ucVersion < 0x20)
		{
		  const tPin PinPteidV1 = {true, "Basic PIN",3,0,0,1,48,NO_ID, 4, 8, 12, 1, 0xFF,PIN_ENC_GP,"","3F00"};	
			if (!ComparePins(oReader.GetPin(0), PinPteidV1))
				ERR_LOG("ERR: CReader::GetPin(0) returned incorrect PIN info\n", lErrors);
			if (!ComparePins(oReader.GetPinByID(1), PinPteidV1))
				ERR_LOG("ERR: CReader::GetPinByID(1) returned incorrect PIN info\n", lErrors);
		}
		else
		{
		  const tPin pinPteidAuthV2 = {true, "Authentication",0x3,0,0,1,0x30,0, 4, 8, 12, 0x85, 0xFF,PIN_ENC_GP,"","3F00DF00"};
		  const tPin pinPteidSignV2 = {true, "Signature",     0x3,0,0,2,0x30,0, 4, 8, 12, 0x86, 0xFF,PIN_ENC_GP,"","3F00DF00"};
			if (!ComparePins(oReader.GetPin(0), pinPteidAuthV2))
				ERR_LOG("ERR: CReader::GetPin(0) returned incorrect PIN info\n", lErrors);
			if (!ComparePins(oReader.GetPin(1), pinPteidSignV2))
				ERR_LOG("ERR: CReader::GetPin(1) returned incorrect PIN info\n", lErrors);
			if (!ComparePins(oReader.GetPinByID(1), pinPteidAuthV2))
				ERR_LOG("ERR: CReader::GetPinByID(1) returned incorrect PIN info\n", lErrors);
			if (!ComparePins(oReader.GetPinByID(2), pinPteidSignV2))
				ERR_LOG("ERR: CReader::GetPinByID(2) returned incorrect PIN info\n", lErrors);
		}
	}

	if (oReader.PrivKeyCount() != 2)
	{
		ERR_LOG("ERR: CReader::PrivKeyCount() didn't return 2\n", lErrors);
	}
	else
	  {
	    if (ucVersion < 0x20)
	      {
		  
		const tPrivKey KeyAuthPteidV1 = {true, "Authentication", 0x3,1,0,2,4,0x1D,0x82,"3F00DF00", 128,true};
		const tPrivKey KeySignPteidV1 = {true, "Signature", 0x3,1,1,3,0x200,0x1D,0x83,"3F00DF00", 128,true};
		if (!ComparePrivKeys(oReader.GetPrivKey(0), KeyAuthPteidV1))
		  ERR_LOG("ERR: CReader::GetPrivKey(0) returned incorrect key info\n", lErrors);
		if (!ComparePrivKeys(oReader.GetPrivKey(1), KeySignPteidV1))
		  ERR_LOG("ERR: CReader::GetPrivKey(1) returned incorrect key info\n", lErrors);
		if (!ComparePrivKeys(oReader.GetPrivKeyByID(2), KeyAuthPteidV1))
		  ERR_LOG("ERR: CReader::GetPrivKeyByID(2) returned incorrect key info\n", lErrors);
		if (!ComparePrivKeys(oReader.GetPrivKeyByID(3), KeySignPteidV1))
		  ERR_LOG("ERR: CReader::GetPrivKeyByID(3) returned incorrect key info\n", lErrors);
	      }
	    else
	      {  
		const tPrivKey KeyAuthPteidV2 = {true, "Authentication", 0x3,1,0,2,4,0x1D,0x8A,"3F00DF00", 128,true};
		const tPrivKey KeySignPteidV2 = {true, "Signature", 0x3,2,1,3,0x200,0x1D,0x89,"3F00DF00", 128,true};
		if (!ComparePrivKeys(oReader.GetPrivKey(0), KeyAuthPteidV2))
		  ERR_LOG("ERR: CReader::GetPrivKey(0) returned incorrect key info\n", lErrors);
		

		if (!ComparePrivKeys(oReader.GetPrivKey(1), KeySignPteidV2))
		  ERR_LOG("ERR: CReader::GetPrivKey(1) returned incorrect key info\n", lErrors);
		if (!ComparePrivKeys(oReader.GetPrivKeyByID(2), KeyAuthPteidV2))
		  ERR_LOG("ERR: CReader::GetPrivKeyByID(2) returned incorrect key info\n", lErrors);
		if (!ComparePrivKeys(oReader.GetPrivKeyByID(3), KeySignPteidV2))
		  ERR_LOG("ERR: CReader::GetPrivKeyByID(3) returned incorrect key info\n", lErrors);
	      }
	}

	if (oReader.CertCount() != 4)
	{
		ERR_LOG("ERR: CReader::CertCount() didn't return 4\n", lErrors);
	}
	else
	{
	  const tCert CertAuthPteid = {true,"Authentication",3,1,0,2,false,false,"3F00DF005038"};
	  const tCert CertSignPteid = {true,"Signature",3,1,0,3,false,false,"3F00DF005039"};
	  const tCert CertCaPteid = {true,"CA",3,1,0,4,true,false,"3F00DF00503A"};
	  const tCert CertRootPteid = {true,"Root",3,1,0,6,true,false,"3F00DF00503B"};
		if (!CompareCerts(oReader.GetCert(0), CertAuthPteid))
			ERR_LOG("ERR: CReader::GetCert(0) returned incorrect cert info\n", lErrors);
		if (!CompareCerts(oReader.GetCert(1), CertSignPteid))
			ERR_LOG("ERR: CReader::GetCert(1) returned incorrect cert info\n", lErrors);
		if (!CompareCerts(oReader.GetCert(2), CertCaPteid))
			ERR_LOG("ERR: CReader::GetCert(2) returned incorrect cert info\n", lErrors);
		if (!CompareCerts(oReader.GetCert(3), CertRootPteid))
			ERR_LOG("ERR: CReader::GetCert(3) returned incorrect cert info\n", lErrors);
		if (!CompareCerts(oReader.GetCertByID(2), CertAuthPteid))
			ERR_LOG("ERR: CReader::GetCertByID(2) returned incorrect cert info\n", lErrors);
		if (!CompareCerts(oReader.GetCertByID(3), CertSignPteid))
			ERR_LOG("ERR: CReader::GetCertByID(3) returned incorrect cert info\n", lErrors);
		if (!CompareCerts(oReader.GetCertByID(4), CertCaPteid))
			ERR_LOG("ERR: CReader::GetCertByID(4) returned incorrect cert info\n", lErrors);
		if (!CompareCerts(oReader.GetCertByID(6), CertRootPteid))
			ERR_LOG("ERR: CReader::GetCertByID(6) returned incorrect cert info\n", lErrors);
	}

	return lErrors;
}