Ejemplo n.º 1
0
void CBuzzController::ProcessInMsgs() {
   /* Reset neighbor information */
   buzzneighbors_reset(m_tBuzzVM);
   /* Go through RAB messages and add them to the FIFO */
   const CCI_RangeAndBearingSensor::TReadings& tPackets = m_pcRABS->GetReadings();
   for(size_t i = 0; i < tPackets.size(); ++i) {
      /* Copy packet into temporary buffer */
      CByteArray cData = tPackets[i].Data;
      /* Get robot id and update neighbor information */
      UInt16 unRobotId = cData.PopFront<UInt16>();
      buzzneighbors_add(m_tBuzzVM,
                        unRobotId,
                        tPackets[i].Range,
                        tPackets[i].HorizontalBearing.GetValue(),
                        tPackets[i].VerticalBearing.GetValue());
      /* Go through the messages until there's nothing else to read */
      UInt16 unMsgSize;
      do {
         /* Get payload size */
         unMsgSize = cData.PopFront<UInt16>();
         /* Append message to the Buzz input message queue */
         if(unMsgSize > 0 && cData.Size() >= unMsgSize) {
            buzzinmsg_queue_append(m_tBuzzVM,
                                   unRobotId,
                                   buzzmsg_payload_frombuffer(cData.ToCArray(), unMsgSize));
            /* Get rid of the data read */
            for(size_t i = 0; i < unMsgSize; ++i) cData.PopFront<UInt8>();
         }
      }
      while(cData.Size() > sizeof(UInt16) && unMsgSize > 0);
   }
   /* Process messages */
   buzzvm_process_inmsgs(m_tBuzzVM);
}
Ejemplo n.º 2
0
void CBuzzController::ProcessOutMsgs() {
   /* Send robot id */
   CByteArray cData;
   cData << m_tBuzzVM->robot;
   /* Send messages from FIFO */
   do {
      /* Are there more messages? */
      if(buzzoutmsg_queue_isempty(m_tBuzzVM->outmsgs)) break;
      /* Get first message */
      buzzmsg_payload_t m = buzzoutmsg_queue_first(m_tBuzzVM->outmsgs);
      /* Make sure the next message fits the data buffer */
      if(cData.Size() + buzzmsg_payload_size(m) + sizeof(UInt16)
         >
         m_pcRABA->GetSize()) {
         buzzmsg_payload_destroy(&m);
         break;
      }
      /* Add message length to data buffer */
      cData << static_cast<UInt16>(buzzmsg_payload_size(m));
      /* Add payload to data buffer */
      cData.AddBuffer(reinterpret_cast<UInt8*>(m->data), buzzmsg_payload_size(m));
      /* Get rid of message */
      buzzoutmsg_queue_next(m_tBuzzVM->outmsgs);
      buzzmsg_payload_destroy(&m);
   } while(1);
   /* Pad the rest of the data with zeroes */
   while(cData.Size() < m_pcRABA->GetSize()) cData << static_cast<UInt8>(0);
   /* Send message */
   m_pcRABA->SetData(cData);
}
Ejemplo n.º 3
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;
}
Ejemplo n.º 4
0
bool CByteArray::Equals(const CByteArray & oByteArray) const
{
    if (m_bMallocError)
        throw CMWEXCEPTION(EIDMW_ERR_MEMORY);

    if (m_ulSize == 0 && oByteArray.Size() == 0)
        return true;

    return m_ulSize == oByteArray.Size() &&
        memcmp(m_pucData, oByteArray.GetBytes(), m_ulSize) == 0;
}
Ejemplo n.º 5
0
void CPkiCard::WriteUncachedFile(const std::string & csPath,
    unsigned long ulOffset, const CByteArray & oData)
{
    CAutoLock autolock(this);

    tFileInfo fileInfo = SelectFile(csPath, true);

    const unsigned char *pucData = oData.GetBytes();
    unsigned long ulDataLen = oData.Size();
    for (unsigned long i = 0; i < ulDataLen; i += MAX_APDU_WRITE_LEN)
    {
        unsigned long ulLen = ulDataLen - i;
		if (ulLen > MAX_APDU_WRITE_LEN)
            ulLen = MAX_APDU_WRITE_LEN;

        CByteArray oResp = UpdateBinary(ulOffset + i, CByteArray(pucData + i, ulLen));
		unsigned long ulSW12 = getSW12(oResp);
		if (ulSW12 == 0x6982)
			throw CNotAuthenticatedException(
				EIDMW_ERR_NOT_AUTHENTICATED, fileInfo.lWritePINRef);
		else if (ulSW12 != 0x9000)
			throw CMWEXCEPTION(m_poContext->m_oPCSC.SW12ToErr(ulSW12));
    }

	MWLOG(LEV_INFO, MOD_CAL, L"Written file %ls to card", utilStringWiden(csPath).c_str());

}
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
0
CByteArray CPkiCard::GetRandom(unsigned long ulLen)
{
	CAutoLock oAutoLock(this);

	if (m_selectAppletMode == ALW_SELECT_APPLET)
	{
		SelectApplet();
	}

	CByteArray oRandom(ulLen);

try_again:
    // Use a Get Challenge command to gather 8 bytes with each loop
    for (unsigned long i = 0; i < ulLen; i += 20)
    {
        unsigned char ucLen = (unsigned char) (ulLen - i > 20 ? 20 : ulLen - i);

        // Get challenge command
        CByteArray oResp = SendAPDU(0x84, 0x00, 0x00, (unsigned char) ucLen);
		if (ShouldSelectApplet(0x84, getSW12(oResp)))
		{
			// First try to select 
			if (SelectApplet())
			{
				m_selectAppletMode = ALW_SELECT_APPLET;
				goto try_again;
			}
		}
		getSW12(oResp, 0x9000);

		oRandom.Append(oResp.GetBytes(), oResp.Size() - 2);
    }

    return oRandom;
}
Ejemplo n.º 8
0
static long UpdateFile(const std::vector <std::string> & vcsPaths,
	const CByteArray & oData, unsigned long ulOffset)
{
	long lRet = 0;

	CReader &oReader = g_oCardLayer.getReader(g_csReaderName);

	if (oReader.Connect())
	{
		printf("Reader \"%s\":\n", oReader.GetReaderName().c_str());

		// Verify PIN if specified
		lRet = VerifyPIN(oReader, 0);
		if (lRet == 0)
		{
			oReader.WriteFile(vcsPaths[0], ulOffset, oData);
			printf("Written %d bytes to file %s, starting at offset %d\n",
				oData.Size(), vcsPaths[0].c_str(), ulOffset);
		}

		oReader.Disconnect();
	}
	else
		printf("  No card found in the reader, exiting\n");

	return lRet;
}
Ejemplo n.º 9
0
static long SendAPDUs(std::vector <std::string> & vcsAPDUs)
{
	long lRet = 0;

	CReader &oReader = g_oCardLayer.getReader(g_csReaderName);

	if (oReader.Connect())
	{
		for (unsigned int i = 0; i < vcsAPDUs.size(); i++)
		{
			CByteArray oRequestAPDU(vcsAPDUs[i], true);
			printf("\nIN:  %s\n", oRequestAPDU.ToString().c_str());
			CByteArray oResponseAPDU = oReader.SendAPDU(oRequestAPDU);
			printf("OUT: %s\n", oResponseAPDU.Size() < 14 ? oResponseAPDU.ToString().c_str():
				oResponseAPDU.ToString(true, false).c_str());
		}

		oReader.Disconnect();
	}
	else
		printf("  No card found in the reader, exiting\n");

	return lRet;

}
Ejemplo n.º 10
0
CByteArray CBeidCard::SignInternal(const tPrivKey & key, unsigned long algo,
    const CByteArray & oData, const tPin *pPin)
{
	CAutoLock autolock(this);

	// For V1.7 cards, the Belpic dir has to be selected
	if (m_ucAppletVersion >= 0x17)
		SelectFile(key.csPath);
	else if (m_selectAppletMode == ALW_SELECT_APPLET)
		SelectApplet();

	SetSecurityEnv(key, algo, oData.Size());
 
	// Pretty unique for smart cards: first MSE SET, then verify PIN
    // (needed for the nonrep key/pin, but also usable for the auth key/pin)
    if (pPin != NULL)
    {
        //unsigned long ulRemaining = 0;
        bool bOK = PinCmd(PIN_OP_VERIFY, *pPin, "", "", m_ulRemaining, &key);
        if (!bOK)
			throw CMWEXCEPTION(m_ulRemaining == 0 ? EIDMW_ERR_PIN_BLOCKED : EIDMW_ERR_PIN_BAD);
    }

    // PSO: Compute Digital Signature
    CByteArray oResp = SendAPDU(0x2A, 0x9E, 0x9A, oData);
	unsigned long ulSW12 = getSW12(oResp);
	if (ulSW12 != 0x9000)
		throw CMWEXCEPTION(m_poContext->m_oPCSC.SW12ToErr(ulSW12));

	// Remove SW1-SW2 from the response
	oResp.Chop(2);

	return oResp;
}
Ejemplo n.º 11
0
static bool BeidCardSelectApplet(CContext *poContext, SCARDHANDLE hCard)
{
	long lRetVal = 0; 
	unsigned char tucSelectApp[] = {0x00, 0xA4, 0x04, 0x00};
	CByteArray oCmd(40);
	oCmd.Append(tucSelectApp, sizeof(tucSelectApp));
	oCmd.Append((unsigned char) sizeof(APPLET_AID));
	oCmd.Append(APPLET_AID, sizeof(APPLET_AID));
	CByteArray oResp;

	try {
		oResp = poContext->m_oPCSC.Transmit(hCard, oCmd, &lRetVal);
	}
    catch(CMWException e)
    {
		MWLOG(LEV_CRIT, MOD_CAL, L"Failed to select applet: 0x%0x", e.GetError());
        return false;
    }
    catch(...)
    {
        MWLOG(LEV_CRIT, MOD_CAL, L"Failed to select applet");
        return false;
    }

	return (oResp.Size() == 2 && (oResp.GetByte(0) == 0x61 || oResp.GetByte(0) == 0x90));
}
Ejemplo n.º 12
0
/**
 * This is something you typically do just once, unless you
 * want to check if new readers were inserted/removed.
 * Note: PKCS#11 assumes that the number of readers never
 * change, so you have to call this function only in
 * C_GetSlotList().
 */
	CReadersInfo CCardLayer::ListReaders()
	{
		CReadersInfo theReadersInfo;
		CByteArray oReaders;

		// Do an SCardEstablishContext() if not done yet
		try
		{
			m_oPCSC.EstablishContext();
			oReaders = m_oPCSC.ListReaders();
		}
		catch(CMWException & e)
		{
			unsigned long err = e.GetError();

			if (err == EIDMW_ERR_NO_READER)
				return theReadersInfo;

			throw;
		}

		theReadersInfo = CReadersInfo(oReaders);

		if (oReaders.Size() != 0)
		{
			m_szDefaultReaderName = (char *) oReaders.GetBytes();
		}

		return theReadersInfo;
	}
Ejemplo n.º 13
0
 void CCI_RangeAndBearingActuator::SetData(const CByteArray& c_data) {
    if(m_cData.Size() == c_data.Size()) {
       m_cData = c_data;
    }
    else {
       THROW_ARGOSEXCEPTION("CCI_RangeAndBearingActuator::SetData() : data size does not match, expected " << m_cData.Size() << ", got " << c_data.Size());
    }
 }
Ejemplo n.º 14
0
 void CRABEquippedEntity::SetData(const CByteArray& c_data) {
    if(m_cData.Size() == c_data.Size()) {
       m_cData = c_data;
    }
    else {
       THROW_ARGOSEXCEPTION("CRABEquippedEntity::SetData() : data size does not match, expected " << m_cData.Size() << ", got " << c_data.Size());
    }
 }
Ejemplo n.º 15
0
CByteArray CPkiCard::ReadUncachedFile(const std::string & csPath,
    unsigned long ulOffset, unsigned long ulMaxLen)
{
    CByteArray oData(ulMaxLen);

	CAutoLock autolock(this);

    tFileInfo fileInfo = SelectFile(csPath, true);

    // Loop until we've read ulMaxLen bytes or until EOF (End Of File)
    bool bEOF = false;
    for (unsigned long i = 0; i < ulMaxLen && !bEOF; i += MAX_APDU_READ_LEN)
    {
        unsigned long ulLen = ulMaxLen - i <= MAX_APDU_READ_LEN ?
            ulMaxLen - i : MAX_APDU_READ_LEN;

        CByteArray oResp = ReadBinary(ulOffset + i, ulLen);

        unsigned long ulSW12 = getSW12(oResp);
		// If the file is a multiple of the block read size, you will get
		// an SW12 = 6B00 (at least with BE eID) but that OK then..
        if (ulSW12 == 0x9000 || (i != 0 && ulSW12 == 0x6B00))
            oData.Append(oResp.GetBytes(), oResp.Size() - 2);
		else if (ulSW12 == 0x6982) {
			throw CNotAuthenticatedException(
				EIDMW_ERR_NOT_AUTHENTICATED, fileInfo.lReadPINRef);
		}
		else if (ulSW12 == 0x6B00)
			throw CMWEXCEPTION(EIDMW_ERR_PARAM_RANGE);
		else if (ulSW12 == 0x6D00)
			throw CMWEXCEPTION(EIDMW_ERR_NOT_ACTIVATED);
		else
            throw CMWEXCEPTION(m_poContext->m_oPCSC.SW12ToErr(ulSW12));

        // If the driver/reader itself did the 6CXX handling,
        // we assume we're at the EOF
        if (oResp.Size() < MAX_APDU_READ_LEN)
            bEOF = true;
    }

	MWLOG(LEV_INFO, MOD_CAL, L"   Read file %ls (%d bytes) from card",
		utilStringWiden(csPath).c_str(), oData.Size());

    return oData;
}
Ejemplo n.º 16
0
BOOL WINAPI
eidmwGetHashParam(
    IN  HCRYPTPROV hProv,      //!< Handle to provider previously obtained through a call to CPAcquireContext
    IN  HCRYPTHASH hHash,      //!< A reference to the hash object for which to set the parameter
    IN  DWORD dwParam,         //!< Parameter to set
    OUT LPBYTE pbData,         //!< A data buffer in which the parameter data will be returned
    IN OUT LPDWORD pcbDataLen, //!< Length of the data to be returned
    IN  DWORD dwFlags)         //!< No flags currently defined
{
	BOOL bReturnVal = FALSE;
	DWORD dwLastError = 0;

	__CSP_TRY__

	MWLOG(LEV_INFO, MOD_CSP, L"CPGetHashParam(hProv = %d) called", hProv);
	MWLOG(LEV_INFO, MOD_CSP, L"  - IN: hHash = %d", hHash);
	MWLOG(LEV_INFO, MOD_CSP, L"  - IN: dwParam = 0x%0x", dwParam);
	MWLOG(LEV_INFO, MOD_CSP, L"  - IN: pbData = %p", pbData);

	CProviderContext *poProvCtx = g_oProviderContextPool.GetProviderContext(hProv);
	CProviderHash *poProvHash = poProvCtx->GetHash(hHash);

	switch(dwParam)
	{
	case HP_ALGID:
		{
		DWORD dwAlgID = (DWORD) poProvHash->GetAlgid();
		bReturnVal = FillProvParam(pbData, pcbDataLen, &dwAlgID, sizeof(DWORD));
		break;
		}
	case HP_HASHSIZE:
		{
		DWORD dwHashSize = (DWORD) poProvHash->GetLengthBytes();
		bReturnVal = FillProvParam(pbData, pcbDataLen, &dwHashSize, sizeof(DWORD));
		break;
		}
	case HP_HASHVAL:
		{
		CByteArray oHashValue = poProvHash->GetHashValue();
		bReturnVal = FillProvParam(pbData, pcbDataLen, oHashValue.GetBytes(), oHashValue.Size());
		break;
		}
	default:
		dwLastError = NTE_BAD_TYPE;
	}

	__STORE_LASTERROR__

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

	__CSP_CATCH_SETLASTERROR__

	return (bReturnVal);
}
Ejemplo n.º 17
0
void CBuzzController::ProcessOutMsgs() {
   /* Process outgoing messages */
   buzzvm_process_outmsgs(m_tBuzzVM);
   /* Send robot id */
   CByteArray cData;
   cData << m_tBuzzVM->robot;
   /* Send messages from FIFO */
   do {
      /* Are there more messages? */
      if(buzzoutmsg_queue_isempty(m_tBuzzVM)) break;
      /* Get first message */
      buzzmsg_payload_t m = buzzoutmsg_queue_first(m_tBuzzVM);
      /* Make sure the message is smaller than the data buffer
       * Without this check, large messages would clog the queue forever
       */
      size_t unMsgSize = buzzmsg_payload_size(m) + sizeof(UInt16);
      if(unMsgSize < m_pcRABA->GetSize() - sizeof(UInt16)) {
         /* Make sure the next message fits the data buffer */
         if(cData.Size() + unMsgSize > m_pcRABA->GetSize()) {
            buzzmsg_payload_destroy(&m);
            break;
         }
         /* Add message length to data buffer */
         cData << static_cast<UInt16>(buzzmsg_payload_size(m));
         /* Add payload to data buffer */
         cData.AddBuffer(reinterpret_cast<UInt8*>(m->data), buzzmsg_payload_size(m));
      }
      else {
         RLOGERR << "Discarded oversize message ("
                 << unMsgSize
                 << " bytes). Max size is "
                 << m_pcRABA->GetSize() - sizeof(UInt16)
                 << " bytes."
                 << std::endl;
      }
      /* Get rid of message */
      buzzoutmsg_queue_next(m_tBuzzVM);
      buzzmsg_payload_destroy(&m);
   } while(1);
   /* Pad the rest of the data with zeroes */
   while(cData.Size() < m_pcRABA->GetSize()) cData << static_cast<UInt8>(0);
   /* Send message */
   m_pcRABA->SetData(cData);
}
Ejemplo n.º 18
0
void SODParser::ParseSodEncapsulatedContent(const CByteArray & contents){
	ASN1_ITEM           xLev0Item;
	ASN1_ITEM           xLev1Item;
	ASN1_ITEM           xLev2Item;
	ASN1_ITEM           xLev3Item;
	ASN1_ITEM           xLev4Item;

	xLev0Item.p_data = (unsigned char*)contents.GetBytes();
	xLev0Item.l_data = contents.Size();

	if ((asn1_next_item(&xLev0Item, &xLev1Item)!= 0) ||(xLev1Item.tag != ASN_SEQUENCE))
		throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);

	if ((xLev1Item.l_data < 2)|| (asn1_next_item(&xLev1Item, &xLev2Item)!= 0) ||(xLev2Item.tag != ASN_INTEGER))
		throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);

	if (bin2int(xLev2Item.p_data, xLev2Item.l_data)!=0)
		throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_VALUE);

	if ((xLev1Item.l_data < 2)|| (asn1_next_item(&xLev1Item, &xLev2Item)!= 0) ||(xLev2Item.tag != ASN_SEQUENCE))
		throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);

	if ((xLev2Item.l_data < 2)|| (asn1_next_item(&xLev2Item, &xLev3Item)!= 0) ||(xLev3Item.tag != ASN_OID))
		throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);

	// martinho: not the intended way, but for now it will do just fine.
	if (memcmp(xLev3Item.p_data, OID_SHA256_ALGORITHM, xLev3Item.l_data) != 0)
		throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ALGO_OID);

	if ((xLev2Item.l_data < 2)|| (asn1_next_item(&xLev2Item, &xLev3Item)!= 0) ||(xLev3Item.tag != ASN_NULL))
		throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);

	if ((xLev1Item.l_data < 2)|| (asn1_next_item(&xLev1Item, &xLev2Item)!= 0) ||(xLev2Item.tag != ASN_SEQUENCE))
		throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);


	attr = new SODAttributes();
	int i=0;
	while(xLev2Item.l_data > 0){

		if ((xLev2Item.l_data < 2)|| (asn1_next_item(&xLev2Item, &xLev3Item)!= 0) ||(xLev3Item.tag != ASN_SEQUENCE))
			throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);

		if ((xLev3Item.l_data < 2)|| (asn1_next_item(&xLev3Item, &xLev4Item)!= 0) ||(xLev4Item.tag != ASN_INTEGER))
			throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);

		if (bin2int(xLev4Item.p_data, xLev4Item.l_data)!=(i+1))
			throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_VALUE);

		if ((xLev3Item.l_data < 2)|| (asn1_next_item(&xLev3Item, &xLev4Item)!= 0) ||(xLev4Item.tag != ASN_OCTET_STRING))
			throw CMWEXCEPTION(EIDMW_SOD_UNEXPECTED_ASN1_TAG);

		attr->hashes[i].Append(xLev4Item.p_data,xLev4Item.l_data);
		i++;
	}
}
Ejemplo n.º 19
0
bool APL_CryptoFwk::VerifyRoot(const CByteArray &cert, const unsigned char *const *roots)
{
	const unsigned char *const *proot;
	for(proot=roots;*proot!=NULL;proot++)
	{
		if(memcmp(cert.GetBytes(),*proot,cert.Size())==0)
			return true;
	}

	return false;
}
Ejemplo n.º 20
0
static void WriteFile(const std::string & csSerial, const std::string & csPath, const CByteArray &oData)
{
	std::string csFileName;
	if (csSerial != "")
		csFileName += csSerial + "_";
	csFileName += csPath;
#ifdef WIN32
	FILE *f;
	fopen_s(&f,csFileName.c_str(), "wb");
#else
	FILE *f = fopen(csFileName.c_str(), "wb");
#endif
	if (f != NULL)
	{
		fwrite(oData.GetBytes(), 1, oData.Size(), f);
		printf(" - Written %d bytes to %s\n", oData.Size(), csFileName.c_str());
		fclose(f);
	}
	else
		printf(" - ERR: couldn't write file %s\n", csFileName.c_str());
}
Ejemplo n.º 21
0
CByteArray CPkiCard::Sign(const tPrivKey & key, const tPin & Pin,
        unsigned long algo, const CByteArray & oData)
{
	// If SSO (Single Sign-On) is false and we didn't verify the
	// PIN yet, then we do this first without trying if it's
	// realy needed.
	if (!m_poContext->m_bSSO)
	{
		bool bFound = false;
		for (size_t i = 0; i < m_verifiedPINs.size() && !bFound; i++)
			bFound = (m_verifiedPINs[i] == Pin.ulID);

		if (!bFound)
		{
			MWLOG(LEV_INFO, MOD_CAL, L"     No SSO: ask PIN and sign (key: ID=0x%0x, algo=0x%0x, "
				L"%d bytes input)", key.ulID, algo, oData.Size());
			return SignInternal(key, algo, oData, &Pin);
		}
	}

	// First try to sign.
    // If this returns a "Security conditions not satisfied"
    // then first do a Pin verify and then try again
	MWLOG(LEV_INFO, MOD_CAL, L"     Trying to Sign (key: ID=0x%0x, algo=0x%0x, "
		L"%d bytes input)", key.ulID, algo, oData.Size());
    try
    {
        return SignInternal(key, algo, oData);
    }
    catch(CMWException & e)
    {
      if ((unsigned)e.GetError() == EIDMW_ERR_NOT_AUTHENTICATED)
        {
					MWLOG(LEV_INFO, MOD_CAL, L"     Couldn't sign, asking PIN and trying again");
					return VerifyAndSign(key, Pin, algo, oData);	
        }
        else
            throw e;
    }
}
Ejemplo n.º 22
0
void CBuzzController::Init(TConfigurationNode& t_node) {
   try {
      /* Get pointers to devices */
      m_pcRABA   = GetActuator<CCI_RangeAndBearingActuator>("range_and_bearing");
      m_pcRABS   = GetSensor  <CCI_RangeAndBearingSensor  >("range_and_bearing");
      try {
         m_pcPos = GetSensor  <CCI_PositioningSensor>("positioning");
      }
      catch(CARGoSException& ex) {}
      /* Get the script name */
      std::string strBCFName;
      GetNodeAttributeOrDefault(t_node, "bytecode_file", strBCFName, strBCFName);
      /* Get the script name */
      std::string strDbgFName;
      GetNodeAttributeOrDefault(t_node, "debug_file", strDbgFName, strDbgFName);
      /* Initialize the rest */
      bool bIDSuccess = false;
      m_unRobotId = 0;
      /* Find Buzz ID */
      size_t tStartPos = GetId().find_last_of("_");
      if(tStartPos != std::string::npos){
         /* Checks for ID after last "_" ie. footbot_group3_10 -> 10 */
         m_unRobotId = FromString<UInt16>(GetId().substr(tStartPos+1));
         bIDSuccess = true;
      }
      /* FromString() returns 0 if passed an invalid string */
      if(!m_unRobotId || !bIDSuccess){
         /* Checks for ID after first number footbot_simulated10 -> 10 */
         tStartPos = GetId().find_first_of("0123456789");
         if(tStartPos != std::string::npos){
            m_unRobotId = FromString<UInt16>(GetId().substr(tStartPos));
            bIDSuccess = true;
         }
      }
      if(!bIDSuccess) {
            THROW_ARGOSEXCEPTION("Error in finding Buzz ID from name \"" << GetId() << "\"");
      }
      if(strBCFName != "" && strDbgFName != "")
         SetBytecode(strBCFName, strDbgFName);
      else
         m_tBuzzVM = buzzvm_new(m_unRobotId);
      UpdateSensors();
      /* Set initial robot message (id and then all zeros) */
      CByteArray cData;
      cData << m_tBuzzVM->robot;
      while(cData.Size() < m_pcRABA->GetSize()) cData << static_cast<UInt8>(0);
      m_pcRABA->SetData(cData);
   }
   catch(CARGoSException& ex) {
      THROW_ARGOSEXCEPTION_NESTED("Error initializing the Buzz controller", ex);
   }
}
Ejemplo n.º 23
0
static CByteArray ReadInternal(CPCSC *poPCSC, SCARDHANDLE hCard, unsigned long ulOffset, unsigned long ulMaxLen)
{
	unsigned long ulLen = ulMaxLen > 252 ? 252 : ulMaxLen;
	long lretVal = 0;
	unsigned char tucReadDat[5] = {0xFF, 0xB2};
	tucReadDat[2] = (unsigned char)(ulOffset/256);
	tucReadDat[3] = (unsigned char)(ulOffset%256);
	tucReadDat[4] = (unsigned char)(ulLen);
	CByteArray oCmd(tucReadDat, sizeof(tucReadDat));
	CByteArray oData = poPCSC->Transmit(hCard, oCmd, &lretVal);

	oData.Chop(2); // remove SW12

	// If we read enough, or there isn't more to read, return
	if (ulMaxLen == ulLen || oData.Size() < ulLen)
	{
		MWLOG(LEV_INFO, MOD_CAL, L"   Read %d bytes from the SIS card", oData.Size());
		return oData;
	}

	ulLen = oData.Size();
	ulOffset += ulLen;
	ulMaxLen -= ulLen;
	ulLen = ulMaxLen > 252 ? 252 : ulMaxLen;
	tucReadDat[2] = (unsigned char)(ulOffset/256);
	tucReadDat[3] = (unsigned char)(ulOffset%256);
	tucReadDat[4] = (unsigned char)(ulLen);
	oCmd = CByteArray(tucReadDat, sizeof(tucReadDat));
	CByteArray oData2 = poPCSC->Transmit(hCard, oCmd,&lretVal);

	oData2.Chop(2); // remove SW12

	oData.Append(oData2);

	MWLOG(LEV_INFO, MOD_CAL, L"   Read %d bytes from the SIS card", oData.Size());

	return oData;
}
Ejemplo n.º 24
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;
}
Ejemplo n.º 25
0
CByteArray GetData(const std::string & csData)
{
	CByteArray oData;

	// If it starts with "file:", we have to read a file
	if (csData.substr(0, 7) == "file://")
	{
		const char *csFileName = csData.c_str() + 7;
#ifdef WIN32
		FILE *f;
		fopen_s(&f,csFileName, "rb");
#else
		FILE *f = fopen(csFileName, "rb");
#endif
		if (f != NULL)
		{
			unsigned char tucBuf[1000];
			size_t len = fread(tucBuf, 1, sizeof(tucBuf), f);
			while (len != 0)
			{
				oData.Append(tucBuf, (unsigned long) len);
				len = fread(tucBuf, 1, sizeof(tucBuf), f);
			}
			printf("Read %d bytes from file \"%s\"\n", oData.Size(), csFileName);
			fclose(f);
		}
		else
			printf("Couldn't open file \"%s\", using empty data\n", csFileName);
	}
	else
	{
		oData = CByteArray(csData.c_str());
		printf("Input: %d bytes\n", oData.Size());
	}

	return oData;
}
Ejemplo n.º 26
0
	std::string * CCardLayer::GetDefaultReader()
	{
		std::string * pRet = &m_szDefaultReaderName;

		if (m_szDefaultReaderName.size() == 0)
		{
			CByteArray csReaders = m_oPCSC.ListReaders();
			if (csReaders.Size() != 0)
			{
				m_szDefaultReaderName = (char *)csReaders.GetBytes();
			}
		}

		return pRet;
	}
Ejemplo n.º 27
0
CSISCard::CSISCard(
        SCARDHANDLE			hCard, 
        CContext            *poContext,
	    CPinpad             *poPinpad, 
        const CByteArray    &  oData    // is either the first 26 bytes, or the whole 404 bytes
        ) :CCard(hCard, poContext, poPinpad)
{
	if (oData.Size() == 26)
		m_oCardAtr = oData;
	else
	{
	    m_oCardAtr = CByteArray(oData.GetBytes(), 26);
		m_oCardData = oData;
	}
}
Ejemplo n.º 28
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);
}
Ejemplo n.º 29
0
bool CEmulationCard::TransmitSpecified(
		IN LPCBYTE pbSendBuffer,
		IN DWORD cbSendLength,
		OUT LPBYTE pbRecvBuffer,
		IN OUT LPDWORD pcbRecvLength,
		LONG & lRet)
{
return false;

	CByteArray *poResp = NULL;
	bool bFound = true;

	if (m_bEnforce)
	{
		poResp = &m_oDefaultResponseAPDU;
		lRet = m_lDefaultRet;
	}
	else
	{
		CByteArray oReq(pbSendBuffer, cbSendLength);
		int i;
		for (i = (int) m_Commands.size() - 1; i >= 0; i--)
		{
			if (m_Commands[i].m_oReq.Equals(oReq))
			{
				poResp = &m_Commands[i].m_oReq;
				lRet = m_Commands[i].m_lRet;
				break;
			}
		}
		if (i < 0)
			bFound = false;
		else
		{
			if (poResp->Size() > *pcbRecvLength)
				lRet = SCARD_E_INSUFFICIENT_BUFFER;
			else
			{
				*pcbRecvLength = m_oDefaultResponseAPDU.Size();
				memcpy(pbRecvBuffer, m_oDefaultResponseAPDU.GetBytes(), *pcbRecvLength);
				lRet = SCARD_S_SUCCESS;
			}
		}
	}

	return bFound;
}
Ejemplo n.º 30
0
CCard *SISCardGetInstance(unsigned long ulVersion, const char *csReader,
	SCARDHANDLE hCard, CContext *poContext, CPinpad *poPinpad)
{
	CCard *poCard = NULL;
	bool bIsSisCard = false;
	CByteArray oData;

	// Check if it's a SIS card by reading the ATR and serial number
	try
	{
		poContext->m_oPCSC.BeginTransaction(hCard);

#ifndef SWITCH_TO_ASYNC_AFTER_READ
		unsigned long ulReadLen = 26;  // read only the first part
#else
		unsigned long ulReadLen = 404; // read everything
		try {
#endif
		oData = ReadInternal(&poContext->m_oPCSC, hCard, 0, ulReadLen);
		bIsSisCard =
			(oData.Size() >= 26) &&
			(oData.GetByte(21) == 0xA0) && (oData.GetByte(22) == 0x00) &&
			(oData.GetByte(23) == 0x00) && (oData.GetByte(24) == 0x00) && (oData.GetByte(25) == 0x33);
#ifdef SWITCH_TO_ASYNC_AFTER_READ
		} catch (...) {
			// Switch back to asynchronous mode.
			BackToAsyncMode(hCard, &poContext->m_oPCSC, csReader);
			throw;
		}
		// Switch back to asynchronous mode.
		BackToAsyncMode(hCard, &poContext->m_oPCSC, csReader);
#endif

		if (bIsSisCard)
			poCard = new CSISCard(hCard, poContext, poPinpad, oData);

		poContext->m_oPCSC.EndTransaction(hCard);
	}
	catch(...)
	{
		poContext->m_oPCSC.EndTransaction(hCard);
		//printf("Exception in cardPluginSIS.SISCardGetInstance()\n");
	}

	return poCard;
}