os/security/cryptoservices/certificateandkeymgmt/tpkcs7/tcmsstep.cpp
author sl
Tue, 10 Jun 2014 14:32:02 +0200
changeset 1 260cb5ec6c19
permissions -rw-r--r--
Update contrib.
     1 /*
     2 * Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
     3 * All rights reserved.
     4 * This component and the accompanying materials are made available
     5 * under the terms of the License "Eclipse Public License v1.0"
     6 * which accompanies this distribution, and is available
     7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
     8 *
     9 * Initial Contributors:
    10 * Nokia Corporation - initial contribution.
    11 *
    12 * Contributors:
    13 *
    14 * Description: 
    15 *
    16 */
    17 
    18 
    19 
    20 #include "tcmsstep.h"
    21 #include <test/testexecutelog.h>
    22 #include <asnpkcs.h>
    23 #include "pkcs7signedobject.h"
    24 #include <asn1enc.h>
    25 #include <cmssignedobject.h>
    26 #include <cmsdefs.h>
    27 #include <hash.h>
    28 #include <asymmetric.h>
    29 #include <cmssigneridentifier.h>
    30 #include <x509certext.h>
    31 #include <pkixcertchain.h>
    32 #include <cmscontentinfo.h>
    33 #include "validate.h"
    34 
    35 
    36 CTCmsBaseStep::CTCmsBaseStep()
    37 	{
    38 	}
    39 
    40 CTCmsBaseStep::~CTCmsBaseStep()
    41 	{
    42 	iFs.Close ();
    43 	delete iDataContent;
    44 	delete iExpectedEncoding;
    45 	__UHEAP_MARKEND;
    46 	}
    47 
    48 TVerdict CTCmsBaseStep::doTestStepPreambleL()
    49 	{
    50 	__UHEAP_MARK;	
    51 	User::LeaveIfError (iFs.Connect());	
    52 	
    53 	//Read the data to be signed
    54 	iDataContent = readFileL(_L("Data"));
    55 	
    56 	if (iDataContent == NULL)
    57 		{
    58 		iDataContent=KNullDesC8().AllocL();
    59 		}
    60 	
    61 	//Read the expected data type
    62 	TPtrC contentDataType;
    63 	if (GetStringFromConfig(ConfigSection(), _L("ExpectedDataType"), contentDataType))
    64 		{
    65 		iExpectedDataType=CovertContentDataTypeNameToDataType(contentDataType);			
    66 		}
    67 
    68 	//Read the expected result
    69 	iExpectedEncoding = readFileL(_L("Result"));
    70 	if (!iExpectedEncoding)
    71 		{
    72 		INFO_PRINTF1(_L("Failed to read 'Result' section of script"));
    73 		SetTestStepResult(ETestSuiteError);			
    74 		}
    75 
    76 	GetIntFromConfig(ConfigSection(), _L("ExpectedResult"), iExpectedResult);	
    77 	GetBoolFromConfig(ConfigSection(), _L("IsOOMTest"), iIsOOMTest);
    78 	return TestStepResult();	
    79 	}
    80 
    81 TInt CTCmsBaseStep::CovertContentDataTypeNameToDataType(const TDesC& aDataTypeName)
    82 	{
    83 	if (aDataTypeName.Compare(_L("DATA"))==0)
    84 		{
    85 		return EContentTypeData;	
    86 		}
    87 	else	if (aDataTypeName.Compare(_L("SIGNEDDATA"))==0)
    88 				{
    89 				return EContentTypeSignedData;
    90 				}
    91 		 else	if (aDataTypeName.Compare(_L("ENVELOPEDDATA"))==0)
    92 					 {
    93 					 return EContentTypeEnvelopedData;	
    94 					 }
    95 			  else	if (aDataTypeName.Compare(_L("DIGESTEDDATA"))==0)
    96 						{
    97 						return EContentTypeDigestedData;
    98 						}
    99 					else 	if (aDataTypeName.Compare(_L("ENCRYPTEDDATA"))==0)
   100 								{
   101 								return EContentTypeEncryptedData;
   102 								}
   103 							else 	if (aDataTypeName.Compare(_L("SIGNEDANDENVELOPEDDATA"))==0)
   104 										{
   105 										return CPKCS7ContentInfo::EContentTypeSignedAndEnvelopedData;	
   106 										}
   107 									else	if (aDataTypeName.Compare(_L("AUTHDATA"))==0)
   108 												{
   109 												return EContentTypeAuthenticatedData;	
   110 												}
   111 											else
   112 												{
   113 												User::Leave(KErrArgument);
   114 												return EContentTypeData;
   115 												}
   116 	}
   117 
   118 HBufC8* CTCmsBaseStep::readFileL (TPtrC tag)
   119 	{
   120 	TPtrC fileName;
   121 	if (GetStringFromConfig(ConfigSection(), tag, fileName) == EFalse)
   122 		{
   123 		return NULL;
   124 		}
   125 
   126 	RFile file;
   127 	if (file.Open(iFs, fileName, EFileRead) != KErrNone)
   128 		{
   129 		INFO_PRINTF2(_L("Cannot open file %S for reading"), &fileName);
   130 		return NULL;
   131 		}
   132 	CleanupClosePushL(file);
   133 	TInt fileSize = 0;
   134 	User::LeaveIfError(file.Size(fileSize));
   135 	HBufC8* result = HBufC8::NewMaxL(fileSize);
   136 	TPtr8 rawDataPtr(result->Des());
   137 	file.Read (rawDataPtr);
   138 	CleanupStack::PopAndDestroy (&file);
   139 	INFO_PRINTF3(_L("Read %d octets from %S"), result->Size(), &fileName);
   140 	return result;
   141 	}
   142 
   143 void CTCmsBaseStep::OutputResultToFileL(const TDesC8& aSignature)
   144 	{
   145 	TDriveUnit sysDrive (RFs::GetSystemDrive());
   146 	TBuf<128> rName (sysDrive.Name());;
   147 	rName.Append(_L("\\tpkcs7\\myresults\\"));
   148 			
   149 	TInt err=iFs.MkDir(rName);
   150 	if (err!=KErrNone && err!=KErrAlreadyExists)
   151 		{
   152 		User::Leave(err);	
   153 		}
   154 				
   155 	RFile file;
   156 	CleanupClosePushL(file);
   157 	
   158 	_LIT(KExtension, ".der");
   159 	rName.Append(ConfigSection());
   160 	rName.Append(KExtension);
   161 	rName.LowerCase();
   162 	User::LeaveIfError(file.Replace(iFs, rName, EFileWrite | EFileStream));
   163 	User::LeaveIfError(file.Write(aSignature));
   164 	CleanupStack::PopAndDestroy(&file);
   165 	}
   166 
   167 
   168 HBufC8* CTCmsBaseStep::CreateDEREncodingLC(const CASN1EncBase& aEncoding)
   169 	{	
   170 	TUint len = aEncoding.LengthDER();
   171 	HBufC8* buf = HBufC8::NewMaxLC(len);
   172 	TUint pos = 0;
   173 	TPtr8 bufptr(buf->Des());
   174 	aEncoding.WriteDERL(bufptr, pos);
   175 	return buf;
   176 	}
   177 
   178 TVerdict CTCmsBaseStep::doTestStepL()
   179 	{
   180 	if (!iIsOOMTest)
   181 		{
   182 		TRAPD(err, doTestL();)
   183 		if (err!=iExpectedResult)
   184 			{
   185 			SetTestStepResult(EFail);
   186 			User::Leave(err);
   187 			}
   188 		return TestStepResult();
   189 		}
   190 	else
   191 		{
   192 		return doOOMTestL();	
   193 		}	
   194 	}
   195 
   196 TVerdict CTCmsBaseStep::doOOMTestL()
   197 	{
   198 	TVerdict verdict = EFail;
   199  	TInt countAfter = 0;
   200 	TInt countBefore = 0;
   201  	for (TInt oomCount = 0; ; oomCount++)
   202  		{
   203  		__UHEAP_RESET;
   204  		__UHEAP_SETFAIL(RHeap::EDeterministic, oomCount);
   205  		countBefore = User::CountAllocCells();
   206  		TRAPD(error, doTestL());
   207  		countAfter = User::CountAllocCells();
   208  		__UHEAP_RESET;
   209  		if (error != KErrNoMemory)
   210  			{
   211  			verdict = EPass;
   212  			INFO_PRINTF2(_L("OOM Status %d"),error);
   213 			INFO_PRINTF1(_L("Test outcome : Passed"));
   214  			break;
   215  			}
   216  		else
   217  			{
   218  			if (countBefore != countAfter)
   219  				{
   220  				INFO_PRINTF2(_L("OOM Status %d"),error);
   221  				INFO_PRINTF2(_L("OOM Failed at %d"), oomCount);
   222  				SetTestStepResult(EFail);
   223  				break;
   224  				}
   225  			}
   226  		INFO_PRINTF2(_L("OOM Failed Point status %d"), error);
   227 		}
   228 	INFO_PRINTF3(_L("Heap alloc count ok: %d final vs %d initial"), countAfter,countBefore);
   229  	SetTestStepResult(verdict);
   230  	if (verdict==EFail)
   231 	 	{
   232  		User::Leave(KErrGeneral);	 		
   233 	 	}	 	
   234  	return verdict;
   235 	}
   236 
   237 
   238 //
   239 // Implementation of CMS Data Test Step
   240 //
   241 CTCmsDataStep::CTCmsDataStep()
   242 	{
   243 	}
   244 
   245 CTCmsDataStep::~CTCmsDataStep()
   246 	{
   247 	}
   248 
   249 	
   250 void CTCmsDataStep::doTestL()
   251 	{
   252 	__UHEAP_MARK;
   253 	CCmsContentInfo* content=CCmsContentInfo::NewL(EContentTypeData, *iDataContent);
   254 	CleanupStack::PushL(content);
   255 	CASN1EncSequence* contentSeq=content->EncodeASN1DERLC();
   256 	HBufC8* signature=CreateDEREncodingLC(*contentSeq);
   257 	CleanupStack::Pop(signature);
   258 	CleanupStack::PopAndDestroy(2, content);
   259 	CleanupStack::PushL(signature);
   260 	//OutputResultToFileL(signature->Des());
   261 
   262 	TBool r=signature->Compare(*iExpectedEncoding);
   263 	if (r!=0 && !iIsOOMTest)
   264 		{
   265 		INFO_PRINTF1(_L("CMS Data Type Encoding Error"));
   266 		User::Leave(KErrGeneral);
   267 		}
   268 	else
   269 		{
   270 		DecodingAndCheckL(*iExpectedEncoding);
   271 		}
   272 
   273 	CleanupStack::PopAndDestroy(signature);	
   274 	}
   275 void CTCmsDataStep::DecodingAndCheckL(TDesC8& aRawData)
   276 	{
   277 	INFO_PRINTF1(_L("Start CMS Data Type Decoding"));
   278 	CCmsContentInfo* content=CCmsContentInfo::NewL(aRawData);
   279 	CleanupStack::PushL(content);
   280 	if (content->ContentType()!=EContentTypeData)
   281 		{
   282 		INFO_PRINTF1(_L("CMS Data Type is not as expected"));
   283 		User::Leave(KErrGeneral);
   284 		}
   285 	else
   286 		{
   287 		if (content->ContentData()!=iDataContent->Des())
   288 			{
   289 			INFO_PRINTF1(_L("CMS Data Content is not as expected"));
   290 			User::Leave(KErrGeneral);					
   291 			}
   292 		}
   293 	CleanupStack::PopAndDestroy(content);		
   294 	}
   295 //
   296 // Implementation of CMS Data Test Step
   297 //
   298 CTCmsDataDecodingStep::CTCmsDataDecodingStep()
   299 	{
   300 	}
   301 
   302 CTCmsDataDecodingStep::~CTCmsDataDecodingStep()
   303 	{
   304 	}
   305 
   306 void CTCmsDataDecodingStep::doTestL()
   307 	{
   308 	DecodingAndCheckL(*iExpectedEncoding);	
   309 	}
   310 
   311 
   312 //
   313 // Implementation of Signed Data Test Base Step
   314 //
   315 CTSignedDataBaseStep::CTSignedDataBaseStep() : iContentType(EContentTypeData), iRsaAlgorithm(ETrue) 
   316 	{
   317 	}
   318 
   319 CTSignedDataBaseStep::~CTSignedDataBaseStep()
   320 	{
   321 	iDecPKCS8Data.ResetAndDestroy();
   322 	iCertificates.ResetAndDestroy();
   323 	iSignerInfoVersion.Close();
   324 	iHashName.Close();
   325 	iValidateResults.Close();
   326 	iSignedAttributePresent.Close();
   327 	iUnSignedAttributePresent.Close();
   328 	delete iRootCertificate;
   329 	delete iAdditionalCertificate;
   330 	delete iAdditionalEncodedCertificate;
   331 	}
   332 
   333 
   334 TInt CTSignedDataBaseStep::CovertHashNameToAlgorithmId(const TDesC& aHashName)
   335 	{
   336 	if (aHashName.Compare(_L("SHA1"))==0)
   337 		{
   338 		return ESHA1;	
   339 		}
   340 	else if (aHashName.Compare(_L("MD5"))==0)
   341 			{
   342 			return EMD5;
   343 			}
   344 		 else
   345 			 {
   346 			 return EMD2;	
   347 			 }
   348 	}
   349 
   350 TInt CTSignedDataBaseStep::CovertCertificateNameToCertificateType(const TDesC& aCertificateName)
   351 	{
   352 	if (aCertificateName.Compare(_L("X509"))==0)
   353 		{
   354 		return CCmsCertificateChoice::ECertificateX509;	
   355 		}
   356 	else if (aCertificateName.Compare(_L("Attribute"))==0)
   357 			{
   358 			return CCmsCertificateChoice::ECertificateAttribute;
   359 			}
   360 		 else
   361 			 {
   362 			 return CCmsCertificateChoice::ECertificateExtendedCerificate;	
   363 			 }
   364 	}
   365 
   366 
   367 TVerdict CTSignedDataBaseStep::doTestStepPreambleL()
   368 	{
   369 	if (CTCmsBaseStep::doTestStepPreambleL()==EFail)
   370 		{
   371 		SetTestStepResult(EFail);
   372 		}
   373 	else
   374 		{
   375 		//Read the configurations
   376 		GetBoolFromConfig(ConfigSection(), _L("HashAvailable"), iIsHashAvailable);
   377 		GetBoolFromConfig(ConfigSection(), _L("DataDetached"), iIsDetached);
   378 		GetBoolFromConfig(ConfigSection(), _L("CertificateSetPresent"), iCertificateSetPresent);
   379 		GetBoolFromConfig(ConfigSection(), _L("CRLsSetPresent"), iCRLsSetPresent);
   380 		GetIntFromConfig(ConfigSection(), _L("SignedDataVersion"), iSignedDataVersion);
   381 		GetIntFromConfig(ConfigSection(), _L("AlgorithmCount"), iAlgorithmCount);
   382 		GetIntFromConfig(ConfigSection(), _L("CertsCount"), iCertsCount);
   383 		GetIntFromConfig(ConfigSection(), _L("SignerCount"), iSignerCount);
   384 		GetBoolFromConfig(ConfigSection(), _L("NoCertSet"), iNoCertSet);
   385 		GetBoolFromConfig(ConfigSection(), _L("ValidateUsingUserCerts"), iValidateUsingUserCerts);
   386 		GetBoolFromConfig(ConfigSection(), _L("NoSigning"), iNoSigning);
   387 		GetBoolFromConfig(ConfigSection(), _L("NoValidationTest"), iNoValidationTest);
   388 		GetBoolFromConfig(ConfigSection(), _L("TwoStepCreation"), iTwoStepCreation);
   389 		GetBoolFromConfig(ConfigSection(), _L("ValidationDetachedWithoutInput"), iValidationDetachedWithoutInput);
   390 		
   391 
   392 		HBufC8* certificate = readFileL(_L("RootCertificate"));
   393 		if (certificate)
   394 			{
   395 			CleanupStack::PushL(certificate);
   396 			iRootCertificate = CX509Certificate::NewL(*certificate);
   397 			CleanupStack::PopAndDestroy (certificate);
   398 			}
   399 
   400 		certificate = readFileL(_L("AddtionalCertificate"));
   401 		if (certificate)
   402 			{
   403 			CleanupStack::PushL(certificate);
   404 			iAdditionalCertificate = CX509Certificate::NewL(*certificate);
   405 			CleanupStack::PopAndDestroy (certificate);			
   406 			}
   407 		TPtrC certTypeName;
   408 		if (GetStringFromConfig(ConfigSection(), _L("AdditionalEncodedCertificateType"), certTypeName))
   409 			{
   410 			iAdditionalEncodedCertificateType=CovertCertificateNameToCertificateType(certTypeName);
   411 			iAdditionalEncodedCertificate=readFileL (_L("AdditionalEncodedCertificate"));				
   412 			}
   413 					
   414 		//Read the certificates, private keys and hash algorithm
   415 		TInt index(0);
   416 		
   417 		TName fKeyName;
   418 		fKeyName.Format(_L("PrivateKey_%d"), index);
   419 		
   420 		TName fCertName;
   421 		fCertName.Format(_L("Certificate_%d"), index);
   422 		
   423 		TName fHashAlgorithmName;
   424 		fHashAlgorithmName.Format(_L("HashAlgorithm_%d"), index);
   425 
   426 		TName fValidationResult;
   427 		fValidationResult.Format(_L("ValidationResult_%d"), index);
   428 		
   429 		TName fSignedAttributePresent;
   430 		fSignedAttributePresent.Format(_L("SignedAttributePresent_%d"), index);
   431 		
   432 		TName fUnSignedAttributePresent;
   433 		fUnSignedAttributePresent.Format(_L("UnSignedAttributePresent_%d"), index);
   434 
   435 		TName fSignerInfoVersion;
   436 		fSignerInfoVersion.Format(_L("SignerInfoVersion_%d"), index);
   437 
   438 		TPtrC hashName;
   439 		TBool vResult(EFalse);
   440 		TBool sAP(EFalse);
   441 		TBool uSAP(EFalse);
   442 		TInt signerInfoVersion;
   443 		TPtrC keyName;
   444 		TPtrC certName;
   445 		
   446 		while ( GetStringFromConfig(ConfigSection(), fKeyName, keyName)
   447 				&& GetStringFromConfig(ConfigSection(), fCertName, certName)
   448 				&& GetStringFromConfig(ConfigSection(), fHashAlgorithmName, hashName)
   449 				&& GetBoolFromConfig(ConfigSection(), fValidationResult, vResult)
   450 				&& GetBoolFromConfig(ConfigSection(), fSignedAttributePresent, sAP)
   451 				&& GetBoolFromConfig(ConfigSection(), fUnSignedAttributePresent, uSAP)
   452 				&& GetIntFromConfig(ConfigSection(), fSignerInfoVersion, signerInfoVersion) )
   453 			{
   454 			//Construct private keys
   455 			HBufC8* privateKey(NULL);
   456 			if ((privateKey=readFileL(fKeyName))!=NULL)
   457 				{
   458 				CleanupStack::PushL (privateKey);
   459 				CDecPKCS8Data* pkcs8Data=TASN1DecPKCS8::DecodeDERL(privateKey->Des());
   460 				CleanupStack::PushL (pkcs8Data);
   461 				iDecPKCS8Data.AppendL(pkcs8Data);
   462 				CleanupStack::Pop(pkcs8Data);
   463 				CleanupStack::PopAndDestroy(privateKey);	
   464 				}
   465 			
   466 			//Construct X509 certificate
   467 			HBufC8* cert(NULL);
   468 			if ((cert=readFileL(fCertName))!=NULL)
   469 				{
   470 				CleanupStack::PushL (cert);
   471 				CX509Certificate* x509cert=CX509Certificate::NewLC(cert->Des());		
   472 				iCertificates.AppendL(x509cert);
   473 				CleanupStack::Pop(x509cert);
   474 				CleanupStack::PopAndDestroy(cert);				
   475 				}
   476 				
   477 			TInt hashId=CovertHashNameToAlgorithmId(hashName);		
   478 			iHashName.AppendL(hashId);
   479 					
   480 			iValidateResults.AppendL(vResult);
   481 			iSignedAttributePresent.AppendL(sAP);
   482 			iUnSignedAttributePresent.AppendL(uSAP);
   483 			iSignerInfoVersion.AppendL(signerInfoVersion);
   484 			
   485 			//for next pair
   486 			index++;
   487 			fKeyName.Format(_L("PrivateKey_%d"), index);
   488 			fCertName.Format(_L("Certificate_%d"), index);
   489 			fHashAlgorithmName.Format(_L("HashAlgorithm_%d"), index);
   490 			fValidationResult.Format(_L("ValidationResult_%d"), index);
   491 			fSignedAttributePresent.Format(_L("SignedAttributePresent_%d"), index);
   492 			fUnSignedAttributePresent.Format(_L("UnSignedAttributePresent_%d"), index);
   493 			fSignerInfoVersion.Format(_L("SignerInfoVersion_%d"), index);
   494 			}			
   495 		}
   496 	return TestStepResult();
   497 	}
   498 
   499 CMessageDigest* CTSignedDataBaseStep::CreateHashLC(TAlgorithmId aAlgorithmId)
   500 	{
   501 	CMessageDigest* hash(NULL);
   502 	switch (aAlgorithmId)
   503 		{
   504 	case EMD2:
   505 		hash=CMD2::NewL();
   506 		break;
   507 		
   508 	case EMD5:
   509 		hash=CMD5::NewL();
   510 		break;
   511 		
   512 	case ESHA1:
   513 		hash=CSHA1::NewL();
   514 		break;
   515 		
   516 	default:
   517 		User::Leave(KErrNotSupported);
   518 		}
   519 	CleanupStack::PushL(hash);
   520 	return hash;		
   521 	}
   522 
   523 
   524 //
   525 // Implementation of CMS Signed Data Test Step
   526 //
   527 CTCmsSignedDataStep::CTCmsSignedDataStep()
   528 	{
   529 	}
   530 
   531 CTCmsSignedDataStep::~CTCmsSignedDataStep()
   532 	{
   533 	}
   534 
   535 
   536 void CTCmsSignedDataStep::CheckAndValidateSignedDataL(TDesC8& aRawData)
   537 	{
   538 	//Decode the content info encoding read from predefined file	
   539 	CCmsContentInfo* content=CCmsContentInfo::NewL(aRawData);
   540 	CleanupStack::PushL(content);
   541 	if (content->ContentType()!=EContentTypeSignedData)
   542 		{
   543 		INFO_PRINTF1(_L("Content Type is not Signed Data"));
   544 		User::Leave(KErrGeneral);
   545 		}
   546 	else
   547 		{
   548 		//Decode the signed data and check the fields
   549 		CCmsSignedObject* signedData=CCmsSignedObject::NewL(*content);
   550 		CleanupStack::PushL(signedData);	
   551 		CheckSignedDataFieldsL(*signedData);
   552 		
   553 		//Validate the signatures
   554 		const RPointerArray<CCmsSignerInfo>& signerInfos=signedData->SignerInfo();
   555 		CheckSignerInfoFieldsL(signerInfos);
   556 		
   557 		if (!iNoValidationTest)
   558 			{
   559 			TInt count=signerInfos.Count();
   560 			for (TInt i=0;i<count;i++)
   561 				{
   562 				HBufC8* certificateEncoding = NULL;
   563 				
   564 				CMessageDigest* hash(NULL);
   565 				if (iIsHashAvailable)
   566 					{
   567 					hash=CreateHashLC((TAlgorithmId)iHashName[i]);
   568 					}
   569 					
   570 				TBool isValid(EFalse);
   571 				if (iValidateUsingUserCerts)
   572 					{
   573 					INFO_PRINTF1(_L("Test validation by using given certificates"));
   574 					if (iIsHashAvailable)
   575 						{
   576 						isValid = signedData->ValidateSignerLC(*signerInfos[i], iCertificates, certificateEncoding, ETrue, hash->Hash(iDataContent->Des()));
   577 						}
   578 					else 
   579 						{
   580 						if (iIsDetached)
   581 							{
   582 							if (!iValidationDetachedWithoutInput)
   583 								{
   584 								isValid = signedData->ValidateSignerLC(*signerInfos[i], iCertificates, certificateEncoding, EFalse, iDataContent->Des());
   585 								}
   586 							else
   587 								{
   588 								isValid = signedData->ValidateSignerLC(*signerInfos[i], iCertificates, certificateEncoding);	
   589 								}							
   590 							}
   591 						else
   592 							{
   593 							isValid = signedData->ValidateSignerLC(*signerInfos[i], iCertificates, certificateEncoding);	
   594 							}
   595 						}					
   596 					}
   597 				else
   598 					{
   599 					INFO_PRINTF1(_L("Test validation by using the embedded certificates"));
   600 					
   601 					if (iIsHashAvailable)
   602 						{
   603 						isValid = signedData->ValidateSignerLC(*signerInfos[i], certificateEncoding, ETrue, hash->Hash(iDataContent->Des()));
   604 						}
   605 					else 
   606 						{
   607 						if (iIsDetached)
   608 							{
   609 							if (!iValidationDetachedWithoutInput)
   610 								{
   611 								isValid = signedData->ValidateSignerLC(*signerInfos[i], certificateEncoding, EFalse, iDataContent->Des());	
   612 								}
   613 							else
   614 								{
   615 								isValid = signedData->ValidateSignerLC(*signerInfos[i], certificateEncoding);	
   616 								}
   617 							}
   618 						else
   619 							{
   620 							isValid = signedData->ValidateSignerLC(*signerInfos[i], certificateEncoding);	
   621 							}
   622 						}					
   623 					}
   624 									
   625 				if (!isValid)
   626 					{
   627 					INFO_PRINTF1(_L("Couldn't validate signer"));
   628 					}
   629 				else
   630 					{
   631 					CActiveScheduler* sched = NULL;
   632 					if (CActiveScheduler::Current() == NULL)
   633 						{
   634 						INFO_PRINTF1(_L("Installing scheduler"));
   635 						sched = new (ELeave) CActiveScheduler();
   636 						CleanupStack::PushL (sched);
   637 						CActiveScheduler::Install (sched);
   638 						}
   639 					RPointerArray<CX509Certificate> roots (&iRootCertificate, 1);
   640 					CPKIXCertChain * chain = CPKIXCertChain::NewLC(iFs, *certificateEncoding, roots);
   641 					
   642 					TTime tm;
   643 					_LIT(KDateCorrect1,"20061128:"); 
   644 					TBuf <24> theDate(KDateCorrect1); 
   645 					TInt err=tm.Set(theDate); 
   646 					if(err)
   647 						{
   648 						tm.HomeTime();
   649 						}
   650 						
   651 					CPKIXValidationResult* result = CPKIXValidationResult::NewLC();
   652 					CTPKCS7Validator* validator = new (ELeave) CTPKCS7Validator (chain, result, &tm);
   653 					validator->doValidate ();
   654 					sched->Start ();
   655 					if (result->Error().iReason == EValidatedOK)
   656 						{
   657 						isValid = ETrue;
   658 						INFO_PRINTF1(_L("Validation success"));
   659 						}
   660 					else
   661 						{
   662 						isValid = EFalse;
   663 						INFO_PRINTF2(_L("Validation failed: %d"), result->Error().iReason);
   664 						}
   665 	        		delete validator;
   666 					CleanupStack::PopAndDestroy(result);
   667 					CleanupStack::PopAndDestroy(chain);
   668 					if (sched)
   669 						{
   670 						CActiveScheduler::Install (NULL);
   671 						CleanupStack::PopAndDestroy (sched);
   672 						}
   673 					}
   674 				
   675 				CleanupStack::PopAndDestroy(certificateEncoding);				
   676 				if (hash)
   677 					{
   678 					CleanupStack::PopAndDestroy(hash);	
   679 					}				
   680 				
   681 				if (isValid!=iValidateResults[i])
   682 					{
   683 					INFO_PRINTF1(_L("validate result not as expected"));
   684 					User::Leave(KErrGeneral);
   685 					}
   686 				}			
   687 			}
   688 		CleanupStack::PopAndDestroy(signedData);
   689 		}
   690 	CleanupStack::PopAndDestroy(content);						
   691 	}
   692 
   693 void CTCmsSignedDataStep::CheckEncapsulatedContentFieldsL(const CEncapsulatedContentInfo& aEncapContentInfo)
   694 	{
   695 	if (aEncapContentInfo.ContentType()!=EContentTypeData)
   696 		{
   697 		INFO_PRINTF1(_L("Encapsulated data Content is not data content type"));
   698 		User::Leave(KErrGeneral);
   699 		}
   700 	else
   701 		{
   702 		if (aEncapContentInfo.IsContentDataPresent() == iIsDetached)
   703 			{
   704 			INFO_PRINTF1(_L("Encapsulated data Content attachment not as expected"));
   705 			User::Leave(KErrGeneral);
   706 			}
   707 		else
   708 			{
   709 			if (aEncapContentInfo.IsContentDataPresent() && aEncapContentInfo.ContentData()!=*iDataContent)
   710 				{
   711 				INFO_PRINTF1(_L("Encapsulated data Content not as expected"));
   712 				User::Leave(KErrGeneral);
   713 				}
   714 			}
   715 		}		
   716 	}
   717 
   718 void CTCmsSignedDataStep::CheckAlgorithmSetFieldsL(const RPointerArray<CX509AlgorithmIdentifier>& aAlgorithms)
   719 	{
   720 	if (iAlgorithmCount!=aAlgorithms.Count())
   721 		{
   722 		INFO_PRINTF1(_L("Number of Algorithm ID is not as expected"));
   723 		User::Leave(KErrGeneral);
   724 		}
   725 	}
   726 
   727 void CTCmsSignedDataStep::CheckCertificateSetFieldsL(const CCmsSignedObject& aSignedData)
   728 	{
   729 	if (aSignedData.IsCertificateSetPresent())
   730 		{
   731 		const RPointerArray<CCmsCertificateChoice>& certSet=aSignedData.Certificates();
   732 		if (iCertsCount!=certSet.Count())
   733 			{
   734 			INFO_PRINTF1(_L("Number of Certificates is not as expected"));
   735 			User::Leave(KErrGeneral);
   736 			}
   737 		else
   738 			{
   739 			//Signer Certificate is in the Signed data
   740 			if (!iNoCertSet)
   741 				{
   742 				TInt count = iCertificates.Count();
   743 				for (TInt i=0;i<count;i++)
   744 					{
   745 					if (certSet[i]->CertificateType()==CCmsCertificateChoice::ECertificateX509 && !iCertificates[i]->IsEqualL(certSet[i]->Certificate()))
   746 						{
   747 						INFO_PRINTF2(_L("X509 Certificates %d is not as expected"), i);
   748 						User::Leave(KErrGeneral);						
   749 						}
   750 					}
   751 				}
   752 			
   753 			if (iAdditionalCertificate || iAdditionalEncodedCertificate)
   754 				{
   755 				if (certSet[iCertsCount-1]->CertificateType()==CCmsCertificateChoice::ECertificateAttribute && 
   756 						certSet[iCertsCount-1]->AttributeCertificate()->Compare(*iAdditionalEncodedCertificate)!=0)
   757 					{
   758 					INFO_PRINTF1(_L("Additional Attribute Certificates is not as expected"));
   759 					User::Leave(KErrGeneral);						
   760 					}
   761 				else if (certSet[iCertsCount-1]->CertificateType()==CCmsCertificateChoice::ECertificateX509)
   762 						{
   763 						if (iAdditionalCertificate && !certSet[iCertsCount-1]->Certificate().IsEqualL(*iAdditionalCertificate))
   764 							{
   765 							INFO_PRINTF1(_L("Additional X509 Certificates is not as expected"));
   766 							User::Leave(KErrGeneral);																					
   767 							}
   768 						else
   769 							{
   770 							if (iAdditionalEncodedCertificate)
   771 								{
   772 								CX509Certificate* addX509Cert=CX509Certificate::NewLC(*iAdditionalEncodedCertificate);
   773 								if (!certSet[iCertsCount-1]->Certificate().IsEqualL(*addX509Cert))
   774 									{
   775 									INFO_PRINTF1(_L("Additional X509 Certificates is not as expected"));
   776 									User::Leave(KErrGeneral);										
   777 									}
   778 								CleanupStack::PopAndDestroy(addX509Cert);
   779 								}
   780 							}
   781 						}
   782 				}
   783 			}
   784 		}
   785 	}
   786 
   787 void CTCmsSignedDataStep::CheckSignerInfoFieldsL(const RPointerArray<CCmsSignerInfo>& signerInfos)
   788 	{
   789 	TInt count=signerInfos.Count();
   790 	if (iDecPKCS8Data.Count()!=count && iSignerCount!=count)
   791 		{
   792 		INFO_PRINTF1(_L("Number of Signer Info is not as expected"));
   793 		User::Leave(KErrGeneral);
   794 		}
   795 	for (TInt i=0;i<count;i++)
   796 		{
   797 		if (signerInfos[i]->IsSignedAttributesPresent()!=iSignedAttributePresent[i]
   798 			|| signerInfos[i]->IsUnsignedAttributesPresent()!=iUnSignedAttributePresent[i]
   799 			|| signerInfos[i]->Version()!=iSignerInfoVersion[i])
   800 			{
   801 			INFO_PRINTF1(_L("Signed or Unsigned Attribute presence or Signer Version is not as expected"));
   802 			User::Leave(KErrGeneral);
   803 			}
   804 			
   805 		const CX509AlgorithmIdentifier& digestId=signerInfos[i]->DigestAlgorithm();
   806 		if (digestId.Algorithm()!=(TAlgorithmId)iHashName[i])
   807 			{
   808 			INFO_PRINTF1(_L("Digest Algorithm ID is not as expected"));
   809 			User::Leave(KErrGeneral);
   810 			}
   811 			
   812 		const CX509AlgorithmIdentifier& sigId=signerInfos[i]->SignatureAlgorithm();
   813 		if (iDecPKCS8Data[i]->Algorithm()!=sigId.Algorithm())
   814 			{
   815 			INFO_PRINTF1(_L("Signature Algorithm ID is not as expected"));
   816 			User::Leave(KErrGeneral);
   817 			}
   818 			
   819 		const CCmsSignerIdentifier& signerId=signerInfos[i]->SignerIdentifier();
   820 		if (signerId.SignerIdentifierType()==CCmsSignerIdentifier::EIssuerAndSerialNumber)
   821 			{
   822 			if (!iCertificates[i]->IssuerName().ExactMatchL(signerId.IssuerAndSerialNumber()->IssuerName()))
   823 				{
   824 				INFO_PRINTF1(_L("Issuer name is not as expected"));
   825 				User::Leave(KErrGeneral);
   826 				}
   827 			else
   828 				{
   829 				RInteger sn1=RInteger::NewL(iCertificates[i]->SerialNumber());
   830 				CleanupClosePushL(sn1);
   831 				RInteger sn2=RInteger::NewL(signerId.IssuerAndSerialNumber()->SerialNumber());
   832 				CleanupClosePushL(sn2);
   833 				if (sn1!=sn2)
   834 					{
   835 					INFO_PRINTF1(_L("Serial number is not as expected"));
   836 					User::Leave(KErrGeneral);					
   837 					}
   838 				CleanupStack::PopAndDestroy(2, &sn1);//sn2, sn1
   839 					
   840 				}
   841 			}
   842 		else if (signerId.SignerIdentifierType()==CCmsSignerIdentifier::ESubjectKeyIdentifier)
   843 				{
   844 				const CX509CertExtension* certExt = iCertificates[i]->Extension(KSubjectKeyId);
   845 				if (certExt)
   846 					{
   847 					CX509SubjectKeyIdExt* ext=CX509SubjectKeyIdExt::NewLC(certExt->Data());
   848 					if (signerId.SubjectKeyIdentifier().Compare(ext->KeyId())!=0)
   849 						{
   850 						INFO_PRINTF1(_L("Subject Key Id is not as expected"));
   851 						User::Leave(KErrGeneral);
   852 						}
   853 					CleanupStack::PopAndDestroy(ext);
   854 					}
   855 				}
   856 		}
   857 	}
   858 
   859 void CTCmsSignedDataStep::CheckSignedDataFieldsL(const CCmsSignedObject& aSignedData)
   860 	{		
   861 	if (aSignedData.IsCertificateSetPresent()!=iCertificateSetPresent ||
   862 		aSignedData.IsCertificateRevocationListsPresent()!=iCRLsSetPresent ||
   863 		aSignedData.Version()!=iSignedDataVersion)
   864 		{
   865 		INFO_PRINTF1(_L("cert present or CRL present or version not as expected"));
   866 		User::Leave(KErrGeneral);
   867 		}
   868 	else
   869 		{
   870 		const CEncapsulatedContentInfo& encapContentInfo=aSignedData.ContentInfo();
   871 		CheckEncapsulatedContentFieldsL(encapContentInfo);
   872 		const RPointerArray<CX509AlgorithmIdentifier>& algorithms=aSignedData.DigestAlgorithms();
   873 		CheckAlgorithmSetFieldsL(algorithms);
   874 		CheckCertificateSetFieldsL(aSignedData);
   875 		}
   876 	}
   877 
   878 void CTCmsSignedDataStep::doTestL()
   879 	{
   880 	__UHEAP_MARK;
   881 	
   882 	CCmsSignedObject* signedData(NULL);
   883 	TInt count=iDecPKCS8Data.Count();
   884 	
   885 	//Create Signed Object
   886 	for (TInt i=0;i<count;i++)
   887 		{
   888 		//Get the key pair
   889 		CDecPKCS8Data* decPKCS8Data=iDecPKCS8Data[i];
   890 		MPKCS8DecodedKeyPairData* keyPair = decPKCS8Data->KeyPairData();
   891 		
   892 		CMessageDigest* hash(NULL);
   893 		TPtrC8 hashValue;
   894 		if (iIsHashAvailable)
   895 			{
   896 			hash=CreateHashLC((TAlgorithmId)iHashName[i]);
   897 			hashValue.Set(hash->Hash(iDataContent->Des()));
   898 			}
   899 		
   900 		//If it is the first time, a signed object needs to be created
   901 		if (i==0)
   902 			{
   903 			if (iIsHashAvailable)
   904 				{
   905 				if (decPKCS8Data->Algorithm()==ERSA)
   906 					{
   907 					const CRSAPrivateKey& RSAPrivateKey=static_cast<CPKCS8KeyPairRSA*>(keyPair)->PrivateKey();
   908 					if (!iTwoStepCreation)
   909 						{
   910 						signedData=CCmsSignedObject::NewL((TCmsContentInfoType)iContentType,
   911 															hashValue,
   912 															(TAlgorithmId)iHashName[i],
   913 															RSAPrivateKey,
   914 															*iCertificates[i],
   915 															!iNoCertSet);
   916 						CleanupStack::PushL(signedData);																
   917 						}
   918 					else
   919 						{
   920 						signedData=CCmsSignedObject::NewL((TCmsContentInfoType)iContentType, iIsDetached, iDataContent->Des());
   921 						CleanupStack::PushL(signedData);
   922 						signedData->SignL(hashValue, (TAlgorithmId)iHashName[i], RSAPrivateKey, *iCertificates[i], !iNoCertSet);
   923 						}
   924 					}
   925 				else
   926 					{
   927 					const CDSAPrivateKey& DSAPrivateKey=static_cast<CPKCS8KeyPairDSA*>(keyPair)->PrivateKey();
   928 					if (!iTwoStepCreation)
   929 						{
   930 						signedData=CCmsSignedObject::NewL((TCmsContentInfoType)iContentType,
   931 															hashValue,
   932 															(TAlgorithmId)iHashName[i],
   933 															DSAPrivateKey,
   934 															*iCertificates[i],
   935 															!iNoCertSet);
   936 						CleanupStack::PushL(signedData);																	
   937 						}
   938 					else
   939 						{
   940 						signedData=CCmsSignedObject::NewL((TCmsContentInfoType)iContentType, iIsDetached, iDataContent->Des());
   941 						CleanupStack::PushL(signedData);
   942 						signedData->SignL(hashValue, (TAlgorithmId)iHashName[i], DSAPrivateKey, *iCertificates[i], !iNoCertSet);
   943 						}
   944 					iRsaAlgorithm=EFalse;			
   945 					}
   946 				CleanupStack::Pop(signedData);	
   947 				CleanupStack::PopAndDestroy(hash);
   948 				CleanupStack::PushL(signedData);
   949 				}		
   950 			else
   951 				{
   952 				signedData=CCmsSignedObject::NewL((TCmsContentInfoType)iContentType, iIsDetached, iDataContent->Des());
   953 				CleanupStack::PushL(signedData);
   954 				if (!iNoSigning)
   955 					{
   956 					if (decPKCS8Data->Algorithm()==ERSA)
   957 						{
   958 						const CRSAPrivateKey& RSAPrivateKey=static_cast<CPKCS8KeyPairRSA*>(keyPair)->PrivateKey();
   959 						signedData->SignL(KNullDesC8, (TAlgorithmId)iHashName[i], RSAPrivateKey, *iCertificates[i], !iNoCertSet);
   960 						}
   961 					else
   962 						{
   963 						const CDSAPrivateKey& DSAPrivateKey=static_cast<CPKCS8KeyPairDSA*>(keyPair)->PrivateKey();
   964 						signedData->SignL(KNullDesC8, (TAlgorithmId)iHashName[i], DSAPrivateKey, *iCertificates[i], !iNoCertSet);
   965 						iRsaAlgorithm=EFalse;
   966 						}												
   967 					}
   968 				}
   969 			}
   970 		else
   971 			{
   972 			//multiple signatures
   973 			if (iIsHashAvailable)
   974 				{
   975 				if (decPKCS8Data->Algorithm()==ERSA)
   976 					{
   977 					const CRSAPrivateKey& RSAPrivateKey=static_cast<CPKCS8KeyPairRSA*>(keyPair)->PrivateKey();
   978 					signedData->SignL(hashValue, (TAlgorithmId)iHashName[i], RSAPrivateKey, *iCertificates[i], !iNoCertSet);
   979 					}
   980 				else
   981 					{
   982 					const CDSAPrivateKey& DSAPrivateKey=static_cast<CPKCS8KeyPairDSA*>(keyPair)->PrivateKey();
   983 					signedData->SignL(hashValue, (TAlgorithmId)iHashName[i], DSAPrivateKey, *iCertificates[i], !iNoCertSet);
   984 					iRsaAlgorithm=EFalse;
   985 					}
   986 				CleanupStack::PopAndDestroy(hash);	
   987 				}
   988 			else
   989 				{
   990 				if (decPKCS8Data->Algorithm()==ERSA)
   991 					{
   992 					const CRSAPrivateKey& RSAPrivateKey=static_cast<CPKCS8KeyPairRSA*>(keyPair)->PrivateKey();
   993 					signedData->SignL(KNullDesC8, (TAlgorithmId)iHashName[i], RSAPrivateKey, *iCertificates[i], !iNoCertSet);
   994 					}
   995 				else
   996 					{
   997 					const CDSAPrivateKey& DSAPrivateKey=static_cast<CPKCS8KeyPairDSA*>(keyPair)->PrivateKey();
   998 					signedData->SignL(KNullDesC8, (TAlgorithmId)iHashName[i], DSAPrivateKey, *iCertificates[i], !iNoCertSet);
   999 					iRsaAlgorithm=EFalse;
  1000 					}						
  1001 				}
  1002 			}	
  1003 		}
  1004 	
  1005 	if (iAdditionalCertificate)
  1006 		{
  1007 		signedData->AddCertificateL(*iAdditionalCertificate);	
  1008 		}
  1009 
  1010  	if (iAdditionalEncodedCertificate)
  1011  		{
  1012  		signedData->AddCertificateL(*iAdditionalEncodedCertificate, (CCmsCertificateChoice::TCertificateType)iAdditionalEncodedCertificateType);
  1013  		}
  1014 		
  1015 	//Encoding the Signed object
  1016 	CASN1EncSequence* signedObjectSeq=signedData->EncodeASN1DERLC();
  1017 	HBufC8* buf=CreateDEREncodingLC(*signedObjectSeq);
  1018 
  1019 	//Encoding the wrapper Content Info
  1020 	CCmsContentInfo* content=CCmsContentInfo::NewL(EContentTypeSignedData, *buf);
  1021 	CleanupStack::PushL(content);
  1022 	CASN1EncSequence* contentSeq=content->EncodeASN1DERLC();
  1023 	HBufC8* signature=CreateDEREncodingLC(*contentSeq);
  1024 	CleanupStack::Pop(signature);
  1025 	CleanupStack::PopAndDestroy(5, signedData);	//contentSeq,content,buf,signedObjectSeq,signedData
  1026 	CleanupStack::PushL(signature);
  1027 
  1028 
  1029 	//write the result to a file, for initial debuging
  1030 	//OutputResultToFileL(signature->Des());
  1031 	
  1032 	//Compare the result with the expected result, if the signature algorithms are RSA
  1033 		
  1034 	if (iRsaAlgorithm)
  1035 		{
  1036 		
  1037 		//Check if the signature is the same as expected
  1038 		TBool r=signature->Compare(*iExpectedEncoding);
  1039 		if (r!=0 && !iIsOOMTest)
  1040 			{
  1041 			INFO_PRINTF1(_L("RSA Signature Encoding Error"));
  1042 			User::Leave(KErrGeneral);
  1043 			}
  1044 		else
  1045 			{
  1046 			CheckAndValidateSignedDataL(*iExpectedEncoding);
  1047 			}
  1048 		}
  1049 	else	
  1050 		{
  1051 		CheckAndValidateSignedDataL(*iExpectedEncoding);
  1052 		CheckAndValidateSignedDataL(*signature);		
  1053 		}	
  1054 			
  1055 	CleanupStack::PopAndDestroy(signature);
  1056 	__UHEAP_MARKEND;
  1057 	}
  1058 
  1059 //
  1060 // Implementation of CMS Signed Data Decoding Test Step
  1061 //
  1062 
  1063 CTCmsSignedDataDecodingStep::CTCmsSignedDataDecodingStep()
  1064 	{
  1065 	}
  1066 
  1067 CTCmsSignedDataDecodingStep::~CTCmsSignedDataDecodingStep()
  1068 	{
  1069 	}
  1070 
  1071 void CTCmsSignedDataDecodingStep::doTestL()
  1072 	{
  1073 	__UHEAP_MARK;
  1074 	CheckAndValidateSignedDataL(*iExpectedEncoding);
  1075 	__UHEAP_MARKEND;
  1076 	}
  1077 
  1078 //
  1079 // Implementation of CMS Content Info Test step
  1080 //
  1081 CTCmsContentInfoDecodingStep::CTCmsContentInfoDecodingStep()
  1082 	{	
  1083 	}
  1084 
  1085 CTCmsContentInfoDecodingStep::~CTCmsContentInfoDecodingStep()
  1086 	{	
  1087 	}
  1088 	
  1089 void CTCmsContentInfoDecodingStep::doTestL()
  1090 	{
  1091 	INFO_PRINTF1(_L("Start CMS Data Type Decoding"));
  1092 	CCmsContentInfo* content=CCmsContentInfo::NewL(*iExpectedEncoding);
  1093 	CleanupStack::PushL(content);
  1094 	if (content->ContentType()!=iExpectedDataType)
  1095 		{
  1096 		INFO_PRINTF1(_L("CMS Data Type is not as expected"));
  1097 		User::Leave(KErrGeneral);
  1098 		}
  1099 	CleanupStack::PopAndDestroy(content);		
  1100 	}
  1101 
  1102 
  1103 
  1104 
  1105 
  1106 
  1107 
  1108 
  1109