Exemplo n.º 1
0
CX509Certificate* IkePkiUtils::FindCaCertificateL(const CX509Certificate& aUserCert,
                                                  const CIkeCaList& aTrustedCAList)
    {
	//
	// Find a CA certificate from Trusted CA list (iTrustedCAList) for
	// specified user certificate
	//	
	const CX500DistinguishedName& issuerName = aUserCert.IssuerName();	
	CX509Certificate* caCert = NULL;

    for (TInt i = 0; i < aTrustedCAList.Count(); i++)
	    {
    	//
	    // Find CA certificate for current user certificate by
	    // comparing certificate issuer name to the subject name of a
	    // CA certificate
	    //		
		caCert = aTrustedCAList.At(i)->Certificate();
		if ( issuerName.ExactMatchL(caCert->SubjectName()) )
		    {
		    break;	
		    }
		caCert = NULL;
	    }	

	return caCert;
    }
Exemplo n.º 2
0
void CX509Certificate::ConstructL(const CX509Certificate& aCertificate)
	{
	iKeyFactory = new(ELeave) TX509KeyFactory;

	iEncoding = aCertificate.iEncoding->AllocL();
	iSignature = aCertificate.iSignature->AllocL();
	iFingerprint = aCertificate.iFingerprint->AllocL();
	iSigningAlgorithm = CSigningAlgorithmIdentifier::NewL(aCertificate.SigningAlgorithm());	
	iSerialNumber = aCertificate.iSerialNumber->Des().AllocL();
	iIssuerName = CX500DistinguishedName::NewL(*(aCertificate.iIssuerName));
	iValidityPeriod = new(ELeave) CValidityPeriod(*(aCertificate.iValidityPeriod));
	iSubjectName = CX500DistinguishedName::NewL(*(aCertificate.iSubjectName));
	iSubjectPublicKeyInfo = CSubjectPublicKeyInfo::NewL(*(aCertificate.iSubjectPublicKeyInfo));
	iIssuerUid = aCertificate.iIssuerUid->Des().AllocL();
	iSubjectUid = aCertificate.iSubjectUid->Des().AllocL();
	iExtensions = new(ELeave) CArrayPtrFlat<CX509CertExtension> (1);
	TInt count = aCertificate.iExtensions->Count();
	for (TInt i = 0; i < count; i++)
		{
		CX509CertExtension* ext = CX509CertExtension::NewLC(*aCertificate.iExtensions->At(i));
		iExtensions->AppendL(ext);
		CleanupStack::Pop();//ext
		}
	iVersion = aCertificate.Version();
	InitDataElementsL(aCertificate);
	}
Exemplo n.º 3
0
EXPORT_C CX509Certificate* CX509Certificate::NewLC(const TDesC8& aBinaryData, TInt& aPos)
	{	
	CX509Certificate* self = new(ELeave) CX509Certificate();
	CleanupStack::PushL(self);
	self->ConstructL(aBinaryData, aPos);
	return self;
	}
Exemplo n.º 4
0
EXPORT_C CX509Certificate* CX509Certificate::NewLC(RReadStream& aStream)
	{
	CX509Certificate* self = new(ELeave) CX509Certificate;
	CleanupStack::PushL(self);
	self->InternalizeL(aStream);
	return self;
	}
void COCSPDirectAuthorisationScheme::OnRetrievingEntryL()
// Called when retrieving an entry completes.
{
    CX509Certificate* cert = CX509Certificate::NewLC(*iEncodedCertPtr);

    if (	OCSPUtils::DoesResponderIdMatchCertL(*iResponse, *cert)
            &&	OCSPUtils::IsResponseSignedByCertL(iResponse, *cert)
            &&	cert->ValidityPeriod().Valid(iValidationTime))
        // found a good one, job finished
    {
        delete iResponseCert;
        iResponseCert = NULL;
        CleanupStack::Pop(cert);
        iResponseCert = cert;
        *iOCSPStatus = OCSP::EValid;
        User::RequestComplete(iClientStatus, KErrNone);
    }
    else
        // wasn't good, try next one
    {
        iState = ERetrieveNext;
        TRequestStatus* status = &iStatus;
        User::RequestComplete(status, KErrNone);
        SetActive();
        CleanupStack::PopAndDestroy(cert);
    }

}
// -----------------------------------------------------------------------------
// CSTSCredentialManager::RemoveVerify
// Verifies that the certificate to be removed has correct issuer and serial
// -----------------------------------------------------------------------------
//
void CSTSCredentialManager::RemoveVerifyL()
{

    TPtr8 certPtr(iEncodedCert->Des());
    CX509Certificate* cert = CX509Certificate::NewLC(certPtr);

    // Check issuer
    const CX500DistinguishedName& certIssuer = cert->IssuerName();
    if (!certIssuer.ExactMatchL(iIssuerAndSerialNumber->IssuerName()))
    {
        // remove current certificate from array, fetch next
        (*iCertInfoArray)[ 0 ]->Release();
        iCertInfoArray->Remove(0);
        RemoveRetrieveL();
    }
    // check serialNumber
    else if (cert->SerialNumber() != iIssuerAndSerialNumber->SerialNumber())
    {
        // remove current certificate from array, fetch next
        (*iCertInfoArray)[ 0 ]->Release();
        iCertInfoArray->Remove(0);
        RemoveRetrieveL();
    }
    else
    {
        // We have a match, show dialog
        RemoveDialog();
    }
    CleanupStack::PopAndDestroy(cert);

}
void CListCertificates::AddDNL(const TDesC8& aDNBuf)
	{
	if (aDNBuf.Length())
		{
		RFs fs;
		User::LeaveIfError(fs.Connect());
		CleanupClosePushL(fs);
		
		TFileName fn;
		fn.Copy(aDNBuf);
		RFile file;
		file.Open(fs, fn, EFileRead);
		CleanupClosePushL(file);
		
		TInt size;
		file.Size(size);
		
		HBufC8* cert = HBufC8::NewMaxLC(size);
		TPtr8 ptr(cert->Des());
		file.Read(ptr);
		
		CX509Certificate* parsedCert = CX509Certificate::NewLC(*cert);
		HBufC8* issuer = parsedCert->DataElementEncoding(CX509Certificate::EIssuerName)->AllocLC();
		User::LeaveIfError(iDNs.Append(issuer));
		
		CleanupStack::Pop(issuer);
		CleanupStack::PopAndDestroy(4, &fs);
		}
	}
// ---------------------------------------------------------------------------
// CServerAuthFailOperation::SaveServerCertToTrustedSiteCertStoreL()
// ---------------------------------------------------------------------------
//
void CServerAuthFailOperation::SaveServerCertToTrustedSiteCertStoreL()
    {
    TRACE( "CServerAuthFailOperation::SaveServerCertToTrustedSiteCertStoreL" );

    ASSERT( iCertLabel == NULL );
    CX509Certificate* serverCert = CX509Certificate::NewLC( iEncodedServerCert );
    const CX500DistinguishedName& dName = serverCert->SubjectName();
    HBufC* commonName = dName.ExtractFieldL( KX520CommonName );
    if( commonName )
        {
        CleanupStack::PushL( commonName );
        TInt commonNameLen = commonName->Length();
        if( commonNameLen > 0 && commonNameLen <= KMaxCommonNameLength )
            {
            iCertLabel = commonName->AllocL();
            }
        CleanupStack::PopAndDestroy( commonName );
        }
    CleanupStack::PopAndDestroy( serverCert );

    if( !iCertLabel )
        {
        iCertLabel = iServerName->AllocL();
        }

    iTrustedSiteCertStore->Add( *iCertLabel, EX509Certificate, EPeerCertificate,
            NULL, NULL, iEncodedServerCert, iStatus );
    iMode = ESavingServerCert;
    SetActive();
    }
Exemplo n.º 9
0
EXPORT_C CX509Certificate* CX509Certificate::NewLC(const CX509Certificate& aCert)
	{
	CX509Certificate* self = new(ELeave) CX509Certificate;
	CleanupStack::PushL(self);
	self->ConstructL(aCert);
	return self;
	}
Exemplo n.º 10
0
EXPORT_C TInt X509CertNameParser::IssuerFullNameL( 
                                      const CX509Certificate& aCertificate,
                                      HBufC*& aIssuerName )
    {
    // Get issuerName
    const CX500DistinguishedName& dName = aCertificate.IssuerName();
    // Get issuer alternative name
    const CX509CertExtension* extension = 
        aCertificate.Extension( KIssuerAltName );

    return GetFullNameL( dName, extension, aIssuerName );
    }
Exemplo n.º 11
0
EXPORT_C TInt X509CertNameParser::SubjectFullNameL(
                                      const CX509Certificate& aCertificate,
                                      HBufC*& aSubjectName,
									  const TDesC& aLabel )
    {
    // Get subjectname
    const CX500DistinguishedName& dName = aCertificate.SubjectName();
    // Get subject alternative name
    const CX509CertExtension* extension = 
        aCertificate.Extension( KSubjectAltName );
    
    return GetFullNameL( dName, extension, aSubjectName, aLabel );
    }
Exemplo n.º 12
0
HBufC* PkiUtil::CertSubjectNameL(const TDesC8& aCertData)
{
    CX509Certificate* certificate = CX509Certificate::NewL(aCertData);
    CleanupStack::PushL(certificate);

    CX500DistinguishedName* subjectDn;
    subjectDn = CX500DistinguishedName::NewL(certificate->SubjectName());
    CleanupStack::PushL(subjectDn);

    HBufC* certDn = CertDnL(*subjectDn);

    CleanupStack::PopAndDestroy(2); // subjectDn, certificate

    return certDn;
}
Exemplo n.º 13
0
HBufC* PkiUtil::CertIssuerNameL(const TDesC8& aCertData)
{
    CX509Certificate* certificate = CX509Certificate::NewL(aCertData);
    CleanupStack::PushL(certificate);

    CX500DistinguishedName* issuerDn;
    issuerDn = CX500DistinguishedName::NewL(certificate->IssuerName());
    CleanupStack::PushL(issuerDn);

    HBufC* certDn = CertDnL(*issuerDn);

    CleanupStack::PopAndDestroy(2); // issuerDn, certificate

    return certDn;
}
Exemplo n.º 14
0
void CPKCS12Handler::SaveCertificatesToDiskL() 
    {
    LOG_("-> CPKCS12Handler::SaveCertificatesToDiskL()");

    TInt certCount(0);

    // first the CAs (if any; not required necessarily)
    if (iCACerts) 
        {
        certCount = iCACerts->Count();
        LOG_1(" Saving %d CA Certificates", certCount);

        for (TInt i = 0; i < certCount; i++)
            {
            CX509Certificate* cert = iCACerts->At(i);

            // Generate filename with running identifier
            // Use TFileName, because the function isn't stack
            // critical
            TFileName fn;
            fn.Format(KCAFileNameStem(), i+1);

            WriteToFileL(cert->Encoding(), fn);
            }
        }
    LOG(else LOG_(" No CA Certs found!"));

    // Then the user certs
    if (iUserCerts)
        {
        certCount = iUserCerts->Count();
        LOG_1(" Saving %d User Certificates", certCount);

        for (TInt i = 0; i < certCount; i++) 
            {
            CX509Certificate* cert = iUserCerts->At(i);

            TFileName fn;
            fn.Format(KUserCertFileNameStem(), i+1);

            WriteToFileL(cert->Encoding(), fn);
            }
        }

    LOG(else LOG_(" No User Certs found!"));

    LOG_("<- CPKCS12Handler::SaveCertificatesToDiskL()");
    }
Exemplo n.º 15
0
TBool CExtensionTest::CheckCapabilitiesL(const CX509Certificate& cert) 
	{
	const CX509CertExtension* ext = cert.Extension(KCapabilitiesConstraint);
	TBool match = ETrue;
	if (ext)
		{		
		// use NewL because this covers NewLC as well
		CX509CapabilitySetExt* capabilitySetExt = CX509CapabilitySetExt::NewL(ext->Data());		
		CleanupStack::PushL(capabilitySetExt);
		
		const TCapabilitySet& capabilitySet = capabilitySetExt->CapabilitySet();		

		if (! (capabilitySet.HasCapabilities(iExpectedCapabilities)
			&& iExpectedCapabilities.HasCapabilities(capabilitySet)))
			{
			PrintLine(_L("Capability constraints are different."));
			match = EFalse;
			}
		CleanupStack::PopAndDestroy(capabilitySetExt);		
		}	
	else if (iCapabilitiesPresent) 
		{
		PrintLine(_L("Capability constraint is missing."));
		match = EFalse;
		}	
	return match;		
	}
Exemplo n.º 16
0
void CPKCS12Handler::AttachCertificatesL() 
    {
    LOG_("-> CPKCS12Handler::AttachCertificatesL()");
    TInt certCount = iUserCerts->Count();
    for (TInt i = 0; i < certCount; i++) 
        {
        CX509Certificate* cert = iUserCerts->At(i);
        TKeyIdentifier certKeyId = cert->KeyIdentifierL();
        
        // Note: KeyID parameter is effectively redundant
        // (it can always be fetched from CX509Certificate object)
        AttachCertificateL(cert, certKeyId);

        }
    LOG_("<- CPKCS12Handler::AttachCertificatesL() OK");
    }
Exemplo n.º 17
0
TCertStatus PkiUtil::CertStatusL(const CX509Certificate& aCert, TInt aCertRenewalThreshold)
{

    TTime validationTime;
    validationTime.UniversalTime();

    TCertStatus certStatus = ECertValid;

    if (aCert.ValidityPeriod().Finish() <= validationTime)
    {
        certStatus = ECertExpired;
    }

    if (aCert.ValidityPeriod().Start() >= validationTime)
    {
        certStatus = ECertNotValidYet;
    }

    // Additional validity check - if a certificate renewal threshold
    // has been specified, it can cause an otherwise valid certificate
    // to be marked as expired. This is determined as follows:
    // - Calculate the entire lifetime of the certificate (entireLifetime)
    // - Calculate the passed lifetime of the certificate (passedLifetime)
    // - Calculate thresholdLifetime as aCertRenewalTreshold % * entireLifetime
    //   (i.e. (aCertRenewalTreshold / 100) * entireLifetime
    // - If passedLifetime > thresholdLifetime --> certificate expired

    if (certStatus == ECertValid && aCertRenewalThreshold >= 0)
    {
        TInt64 entireLifetime = aCert.ValidityPeriod().Finish().Int64() -
                                aCert.ValidityPeriod().Start().Int64();

        TInt64 passedLifetime = validationTime.Int64() -
                                aCert.ValidityPeriod().Start().Int64();

        TInt64 thresholdInPercents(aCertRenewalThreshold);
        TInt64 hundred(100);
        TInt64 tresholdLifetime = (thresholdInPercents * entireLifetime) / hundred;

        if (passedLifetime > tresholdLifetime)
        {
            certStatus = ECertExpired;
        }
    }

    return certStatus;
}
Exemplo n.º 18
0
TInt PkiUtil::CertKeySizeL(const TDesC8& aCertData)
{
    TInt keySize = 0;

    CX509Certificate* certificate = CX509Certificate::NewLC(aCertData);
    const CSubjectPublicKeyInfo& publicKeyInfo = certificate->PublicKey();
    const TPtrC8 keyData = publicKeyInfo.KeyData();

    TX509KeyFactory keyFactory;

    switch(publicKeyInfo.AlgorithmId())
    {
    case ERSA:
    {
        const CRSAPublicKey* keyRSA = keyFactory.RSAPublicKeyL(keyData);
        const TInteger&  n = keyRSA->N();
        keySize = n.BitCount();
        delete keyRSA;
    }
    break;
    case EDSA:
    {
        TPtrC8 params = publicKeyInfo.EncodedParams();

        const CDSAPublicKey* keyDSA =
            keyFactory.DSAPublicKeyL(params, keyData);

        const TInteger& y = keyDSA->Y();
        keySize = y.BitCount();
        delete keyDSA;
    }
    break;
    default:
        User::Leave(KErrNotSupported);
        break;
    }

    CleanupStack::PopAndDestroy(certificate);

    return keySize;
}
/**
	Checks whether the encoded cert chain contains exactly
	one cert which matches the supplied cert.

	This is used to verify that, when a cert chain is sent with
	the response, it contains exactly the CA cert.

	@param	aCertChainData	DER-encoded certificate chain data
							extracted from response.
	@param	aCert			Certificate to look for.
	@return					ETrue if the certificate chain contains
							exactly one response which matches
							aCert; EFalse otherwise.
 */
TBool COCSPCaDirectAuthorisationScheme::CertChainMatchesCertL(
	const TDesC8& aCertChainData, const CX509Certificate& aCert)
	{
	// here we cannot assume that the response contains only the CA certificate,
	// which signed the response as that can be a subordinate CA, so the chain
	// can be like RCA(root CA) -> ICA(intermediate CA) -> SCA (sub-ordinate CA)
	// we need to retrieve the SCA for this verification.
	CX509Certificate* respCert = OCSPUtils::GetResponderCertLC(aCertChainData);
	TBool match = aCert.IsEqualL(*respCert);
	CleanupStack::PopAndDestroy(respCert);
	return match;
	}
Exemplo n.º 20
0
void CX509Certificate::InitDataElementsL(const CX509Certificate& aCertificate)
	{
	iDataElements = new(ELeave) TFixedArray<TPtrC8*, KX509MaxDataElements>;
	iDataElements->Reset();
	TPtrC8 signedData = SignedDataL();
	TASN1DecSequence encSeq;
	TInt pos = 0;
	CArrayPtrFlat<TASN1DecGeneric>* seq = encSeq.DecodeDERLC(signedData, pos, 6, KMaxTInt);//6 is the minimum number of elements in an x509 cert
	pos = 0;

	TPtrC8** pElement = iDataElements->Begin();
	*pElement++ = aCertificate.DataElementEncoding(CX509Certificate::EVersionNumber)? new(ELeave) TPtrC8(seq->At(pos++)->Encoding()):NULL;
	for (TInt i = 0; i < 6; i++)	//init all the non-optional elements
		{
		*pElement++ = new(ELeave) TPtrC8(seq->At(pos++)->Encoding());
		}
	*pElement++ = aCertificate.DataElementEncoding(CX509Certificate::EIssuerUID)? new(ELeave) TPtrC8(seq->At(pos++)->Encoding()):NULL;
	*pElement++ = aCertificate.DataElementEncoding(CX509Certificate::ESubjectUID)? new(ELeave) TPtrC8(seq->At(pos++)->Encoding()):NULL;
	*pElement++ = aCertificate.DataElementEncoding(CX509Certificate::EExtensionList)? new(ELeave) TPtrC8(seq->At(pos++)->Encoding()):NULL;
	CleanupStack::PopAndDestroy();
	}
Exemplo n.º 21
0
void CSecEngine::PrintCertInfo(const CX509Certificate& aSource)
	{
	_LIT(KCertInfoMessage1, "\nCertificate received: \n\tIssuer %S \n\tSubject %S");
	_LIT(KCertInfoMessage2, "\n\tValid from %S to %S");
	_LIT(KDateString,"%F%/0%M%/1%Y%/2%D%/3");

	TRAP_IGNORE(
		// Print issuer and subject
		HBufC* issuer = aSource.IssuerL();
		HBufC* subject = aSource.SubjectL();
		iConsole->Printf(KCertInfoMessage1, issuer, subject);
		delete issuer;
		delete subject;
		
		// Print validity period
		TBuf<20> startTime;
		TBuf<20> finishTime;
		aSource.ValidityPeriod().Start().FormatL(startTime,KDateString);
		aSource.ValidityPeriod().Finish().FormatL(finishTime,KDateString);
		iConsole->Printf(KCertInfoMessage2, &startTime, &finishTime);
		);
// ---------------------------------------------------------------------------
// CServerAuthFailOperation::IsRetrievedCertSameAsServerCertL()
// ---------------------------------------------------------------------------
//
TBool CServerAuthFailOperation::IsRetrievedCertSameAsServerCertL()
    {
    TRACE( "CServerAuthFailOperation::IsRetrievedCertSameAsServerCertL, begin" );
    TBool isSame = EFalse;
    CX509Certificate* cert = CX509Certificate::NewLC( *iRetrievedCertBuffer );

    if( !iServerCertFingerprint )
        {
        CX509Certificate* serverCert = CX509Certificate::NewLC( iEncodedServerCert );
        iServerCertFingerprint = serverCert->Fingerprint().AllocL();
        CleanupStack::PopAndDestroy( serverCert );
        }

    if( cert->Fingerprint() == *iServerCertFingerprint )
        {
        isSame = ETrue;
        }

    CleanupStack::PopAndDestroy( cert );
    TRACE( "CServerAuthFailOperation::IsRetrievedCertSameAsServerCertL, isSame=%d", isSame );
    return isSame;
    }
Exemplo n.º 23
0
void CPolicyImporter::StateAfterImportCaCertL()
    {
    SetCurrState(EStateAfterImportCaCert);

    iPkiService.Finalize(iPkiOpContext);


    if (iStatus == KErrArgument)
        {
        User::Leave(KVpnErrInvalidCaCertFile);
        }
    else if (iStatus != KErrNone)
        {
        User::Leave(iStatus.Int());
        }

    // Set VPN trusted
    CX509Certificate* tempCert = CX509Certificate::NewLC(*iCertFileData);
    RArray<TUid> appArray;
    CleanupClosePushL(appArray);
    appArray.AppendL(TUid::Uid(KUidVpnManager));

    const TPtrC8* serialNumber = tempCert->DataElementEncoding(
        CX509Certificate::ESerialNumber);
    const TPtrC8* issuername = tempCert->DataElementEncoding(
        CX509Certificate::EIssuerName);

    iPkiService.SetApplicabilityL(
        *issuername,
        *serialNumber,
        appArray);

    CleanupStack::PopAndDestroy(2); // appArray, tempCert

    // Handle the next certificate, if present
    GotoState(EStateImportCaCert);
    }
// -----------------------------------------------------------------------------
// CSTSCredentialManager::AddVerify
// Verifies that the certificate does not have correct serial
// -----------------------------------------------------------------------------
//
void CSTSCredentialManager::AddVerifyL()
{

    TPtr8 certPtr(iEncodedCert->Des());
    CX509Certificate* cert = CX509Certificate::NewLC(certPtr);

    CX509Certificate* certToAdd = CX509Certificate::NewLC(iSubject);

    // check serialNumber
    if (cert->SerialNumber() != certToAdd->SerialNumber())
    {
        // remove current certificate from array, fetch next
        (*iCertInfoArray)[ 0 ]->Release();
        iCertInfoArray->Remove(0);
        AddRetrieveL();
    }
    else
    {
        // We have a match, bail out
        Complete(KSTSErrAlreadyRegistered);
    }
    CleanupStack::PopAndDestroy(2);   // certToAdd, cert

}
Exemplo n.º 25
0
TBool CExtensionTest::CheckDeviceIdListL(const CX509Certificate& cert) 
	{
	TBool match = ETrue;
	const CX509CertExtension* ext = cert.Extension(KDeviceIdListConstraint);	
	if (ext)
		{
		// use NewL because this covers NewLC as well
		CX509Utf8StringListExt* stringListExt = CX509Utf8StringListExt::NewL(ext->Data());	
		CleanupStack::PushL(stringListExt);
		if (! IsEqual(stringListExt->StringArray(), iExpectedDeviceIdList))
			{
			PrintLine(_L("Device Id list is different."));
			match = EFalse;
			}
		CleanupStack::PopAndDestroy(stringListExt);		
		}	
	else if (iDeviceIdsPresent) 
		{
		PrintLine(_L("Device Id constraint is missing."));
		match = EFalse;
		}	
	return match;
	}
Exemplo n.º 26
0
TBool CExtensionTest::CheckSidListL(const CX509Certificate& cert) 
	{
	const CX509CertExtension* ext = cert.Extension(KSidListConstraint);
	TBool match = ETrue;
	if (ext)
		{				
		// use NewL because this covers NewLC as well
		CX509IntListExt* intListExt = CX509IntListExt::NewL(ext->Data());
		CleanupStack::PushL(intListExt);
		if (! IsEqual(intListExt->IntArray(), iExpectedSidList))
			{
			PrintLine(_L("SID list is different"));
			match = EFalse;
			}
		CleanupStack::PopAndDestroy(intListExt);		
		}	
	else if (iSidsPresent) 
		{
			PrintLine(_L("SID constraint is missing."));
			match = EFalse;
		}
	return match;	
	}
Exemplo n.º 27
0
void CmsUtils::AddCertificateL(RPointerArray<CCmsCertificateChoice>& aCertList, const CX509Certificate& aCert)
	{
	
	TInt found(EFalse);
	TInt count=aCertList.Count();
	for (TInt i=0;i<count;i++)
		{
		if (aCertList[i]->CertificateType()==CCmsCertificateChoice::ECertificateX509
				&& aCert.IsEqualL(aCertList[i]->Certificate()))
			{
			found=ETrue;
			break;
			}
		}
	
	if (!found)
		{
		CCmsCertificateChoice* cert=CCmsCertificateChoice::NewL(aCert);
		CleanupStack::PushL(cert);
		aCertList.AppendL(cert);
		CleanupStack::Pop(cert);					
		}
		
	}
TVerdict CVerifySignatureStep::doTestStepL()
	{
	INFO_PRINTF1(_L("Calling TLS Provider to fetch cipher suites."));
	// first we have to retrieve the available cipher suites
	TInt err = GetCipherSuitesL();
	
	if (err != KErrNone)
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
	
	INFO_PRINTF1(_L("Calling TLS Provider to verify server certificate."));
	CX509Certificate* cert = NULL;
	err = VerifyServerCertificateL(cert);
	CleanupStack::PushL(cert);

	if (err != KErrNone)
		{
		SetTestStepResult(EFail);
		return TestStepResult();
		}
		
	// sign some random data, and call it a signature....
	// doesn't have to be an actual digest, since we don't pass the data buffer.
	
	TBuf8<36> digest;
	CTlsCryptoAttributes* atts = Provider()->Attributes();

	TInt index = KErrNotFound;
	for(TInt j=0;j<CipherSuites().Count();j++)
		{
		if(CipherSuites()[j] == atts->iCurrentCipherSuite)
			{
			index = j;
			break;
			}
		}
	User::LeaveIfError(index);

	TTLSCipherSuite suite = CipherSuites()[index];
	// ajust the pseudo-digest size for sig algorithm
	switch(suite.CipherDetails()->iSigAlg)
		{
	case EDsa:
		atts->isignatureAlgorithm = EDsa;
		digest.SetLength(20); // only one SHA-1 in size
		break;
	
	case ERsaSigAlg:
		atts->isignatureAlgorithm = ERsaSigAlg;
		digest.SetLength(36); // MD5 + SHA-1 in size
		break;
	
	default:
		User::Leave(KErrUnknown);
		break;
		}
	
	TRandom::RandomL(digest);
	
	// get the server private key data
	CDecPKCS8Data* keyData = ServerPrivateKeyL();
	CleanupStack::PushL(keyData);
	
	// sign the "digest" with the appropriate signature algorithm
	HBufC8* signature = NULL;
	switch(suite.CipherDetails()->iSigAlg)
		{
	case EDsa:
		{
		// we don't own this pointer
		CPKCS8KeyPairDSA* key = static_cast<CPKCS8KeyPairDSA*>(keyData->KeyPairData());
		
		CDSASigner* signer = CDSASigner::NewLC(key->PrivateKey());
		const CDSASignature* sig = signer->SignL(digest);
		CleanupStack::PushL(const_cast<CDSASignature*>(sig));
		
		// DSA sig is an ASN.1 sequence of R followed by S
		CASN1EncSequence* sigSeq = CASN1EncSequence::NewLC();
		
		CASN1EncBigInt* rAsn = CASN1EncBigInt::NewLC(sig->R());
		sigSeq->AddAndPopChildL(rAsn);
		
		CASN1EncBigInt* sAsn = CASN1EncBigInt::NewLC(sig->S());
		sigSeq->AddAndPopChildL(sAsn);
		
		signature = HBufC8::NewLC(sigSeq->LengthDER());
		TPtr8 sigPtr = signature->Des();
		sigPtr.SetLength(sigSeq->LengthDER());
		TUint pos = 0;
		sigSeq->WriteDERL(sigPtr, pos);
		CleanupStack::Pop(signature);
		
		CleanupStack::PopAndDestroy(3, signer); //sig, sigSeq
		}
		break;

	case ERsaSigAlg:
		{
		// we don't own this pointer
		CPKCS8KeyPairRSA* key = static_cast<CPKCS8KeyPairRSA*>(keyData->KeyPairData());
		
		CRSAPKCS1v15Signer* signer = CRSAPKCS1v15Signer::NewLC(key->PrivateKey());
		const CRSASignature* sig = signer->SignL(digest);
		CleanupStack::PushL(const_cast<CRSASignature*>(sig));
		
		signature = sig->S().BufferLC();
		CleanupStack::Pop(signature);
	
		CleanupStack::PopAndDestroy(2, signer); // sig
		}
		break;
		
	default:
		User::Leave(KErrUnknown);
		break;
		}
	
	CleanupStack::PushL(signature);
	
	//Code to check VerifySignatureL()
	TBool expectedResult = ETrue;
	
	// security test - we may wish to munge the digest we pass to the method
	TBool tamperDigest(EFalse);
	GetBoolFromConfig(ConfigSection(), KTamperedDigest, tamperDigest); // ignore error
	
	if (tamperDigest)
		{
		expectedResult = EFalse;
		TRandom::RandomL(digest);
		}
	// now, invoke the verify signature method.
	TBool result = Provider()->VerifySignatureL(cert->PublicKey(), digest, *signature);
	
	if (result == expectedResult)
		{
		SetTestStepResult(EPass);
		}
	else
		{
		SetTestStepResult(EFail);
		}
		
	//now invoke the verify signature method with invalid params and ensure that it fails accordingly
		TRandom::RandomL(digest);
	result = Provider()->VerifySignatureL(cert->PublicKey(), digest, *signature);
			expectedResult = EFalse;
	if (result == expectedResult)
		{
		SetTestStepResult(EPass);
		}
	else
		{
		SetTestStepResult(EFail);
		}
	
	CleanupStack::PopAndDestroy(3, cert); // keyData, signature
	return TestStepResult();
	}
Exemplo n.º 29
0
EXPORT_C CX509Certificate* IkePkiUtils::VerifyCertChainL(const CArrayFixFlat<CX509Certificate*>& aCerts, CX509Certificate*& realUserCert, const CIkeCaList& aTrustedCAList)
    {
    CX509Certificate* currCaCert=NULL;
    CX509Certificate* certOk=NULL;
    CArrayFixFlat<const CX500DistinguishedName*>* issuerArray=new (ELeave) CArrayFixFlat<const CX500DistinguishedName*> (aCerts.Count()); 
    CArrayFixFlat<const CX500DistinguishedName*>* subjectArray=new (ELeave) CArrayFixFlat<const CX500DistinguishedName*> (aCerts.Count()); 
    CleanupStack::PushL(issuerArray);
    CleanupStack::PushL(subjectArray);
    for ( TInt i = 0; i < aCerts.Count(); i++  ) 
        {
        issuerArray->AppendL(&aCerts.At(i)->IssuerName());
        subjectArray->AppendL(&aCerts.At(i)->SubjectName());
        }
    TInt userCertIndex=0; 
    TInt caCertIndex=0;
    
    //find UserCert from aCerts array if not in first certificate payload
    for ( TInt i = 0; i < (aCerts.Count()); i++  )
        {
        for ( TInt j = 0; j < (aCerts.Count()); j++  )
            {
            caCertIndex=j;
            if ( i!=caCertIndex )
                {
                const CX500DistinguishedName& issuerNameStr=*issuerArray->At(j);
                if ( issuerNameStr.ExactMatchL(*subjectArray->At(i)) )
                    userCertIndex=i+1;
                }
            }
        if ( userCertIndex == i && i!=caCertIndex )
            break;
        userCertIndex=i;
        }
    CleanupStack::PopAndDestroy(subjectArray);
    CleanupStack::PopAndDestroy(issuerArray);
    CX509Certificate* currCert = aCerts.At(userCertIndex);
    TInt currCertIndex=0; 
    realUserCert=currCert;
    //Verify chain and return highest CA
    while ( currCertIndex < aCerts.Count())
        {
        CX509Certificate* trustedCaCert  = IkePkiUtils::FindCaCertificateL(*currCert, aTrustedCAList);
        if ( trustedCaCert )
            return currCert;
        else
            {
            for ( TInt j = 0; j < aCerts.Count(); j++ )
                {
                currCaCert = aCerts.At(j);
                if ( currCert->IssuerName().ExactMatchL(currCaCert->SubjectName()))
                    {
                    certOk = IkePkiUtils::VerifyX509CertificateL(*currCaCert, *currCert);
                    if ( certOk )
                        break;
                    }
                }       
            if ( !certOk  ) //if chain is malicious break and return NULL
                break;
            currCertIndex++;
            currCert=currCaCert;
            }
        }
        return NULL;
    }
// -----------------------------------------------------------------------------
// CCMSX509CertificateList::ConstructL
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
EXPORT_C void CCMSX509CertificateList::ConstructL(
	const CX509Certificate& aSigningCertificate,
	const CArrayPtrFlat<CX509Certificate>& aRevokedCertificates )
    {
	ConstructL();

	// setting signature
	const CSigningAlgorithmIdentifier& signAlgorithm =
		aSigningCertificate.SigningAlgorithm();
	iParams->iSignatureAlgorithm =
		CCMSX509AlgorithmIdentifier::NewL( signAlgorithm.AsymmetricAlgorithm(),
										   signAlgorithm.DigestAlgorithm() );

	// setting issuer
	iParams->iIssuer =
		CX500DistinguishedName::NewL( aSigningCertificate.IssuerName() );

	// setting validity
	const CValidityPeriod& validity = aSigningCertificate.ValidityPeriod();
	iParams->iThisUpdate = validity.Start();
	iParams->iNextUpdate = validity.Finish();


	// copying revoked certificates
	TInt revCerts = aRevokedCertificates.Count();
	if( revCerts > 0 )
		{
		iParams->iRevokedCertificates =
			new( ELeave )CArrayPtrFlat< CCMSX509RevokedCertificate >
												( KDefaultGranularity );
		for( TInt i = 0; i < revCerts; i++ )
			{
			CX509Certificate* cert = aRevokedCertificates[ i ];
			CCMSX509RevokedCertificate* tmpRevCer =
				new(ELeave) CCMSX509RevokedCertificate();
			CleanupStack::PushL( tmpRevCer );
			// convert serial from des to int
            TPtrC8 serialDes = cert->SerialNumber();
            TInt length = serialDes.Size();
            const TUint8* ptr = serialDes.Ptr();
            TInt serial = ( ptr[ 0 ] & 0x80 ) ? -1 : 0;
            for( TInt j = 0; j < length; j++ )
                {
                serial <<= 8;
                serial += *ptr++;
                }
			tmpRevCer->iUserCertificateSerialNumber = serial;

			const CValidityPeriod& reValidity = cert->ValidityPeriod();
			tmpRevCer->iRevokationDate = reValidity.Start();

			// copying extensions
			const CArrayPtrFlat<CX509CertExtension>& extensions =
				cert->Extensions();
			TInt extensionCount = extensions.Count();
			if( extensionCount > 0 )
				{
				tmpRevCer->iExtensions =
					new(ELeave) CArrayPtrFlat<CX509CertExtension>
														( KDefaultGranularity );
				for( TInt j = 0; j < extensionCount; j++ )
					{
					CX509CertExtension* ext = extensions[ j ];
					CX509CertExtension* tmpExt =
									CX509CertExtension::NewLC( *ext );
					tmpRevCer->iExtensions->AppendL( tmpExt );
					CleanupStack::Pop( tmpExt );
					}
				}
			iParams->iRevokedCertificates->AppendL( tmpRevCer );
			CleanupStack::Pop( tmpRevCer );
			}
		}
	// copying possible extensions
	TInt extensionCount = aSigningCertificate.Extensions().Count();
	if( extensionCount > 0 )
		{
		iParams->iExtensions =
			new( ELeave )CArrayPtrFlat< CX509CertExtension >
														( KDefaultGranularity );
		const CArrayPtrFlat< CX509CertExtension >& extensions =
			aSigningCertificate.Extensions();

		for( TInt i = 0; i < extensionCount; i++ )
			{
			CX509CertExtension* copy = CX509CertExtension::NewL( *extensions[ i ] );
			CleanupStack::PushL( copy );
			iParams->iExtensions->AppendL( copy );
			CleanupStack::Pop( copy );
			}
		}

	// copying signature
	iParams->iSignature = aSigningCertificate.Signature().AllocL();
    }