Beispiel #1
0
bool  FileVEILOperationsImpl::ValidateFileContents_PublicOnly(const tscrypto::tsCryptoString& sFile)
{
	TSDECLARE_FUNCTIONExt(true);

	std::shared_ptr<ICryptoHelper> helper;
	std::shared_ptr<IDataReader> reader;
	std::shared_ptr<IDataIOBase> ioBase;
	std::shared_ptr<IKeyVEILSession> empty;

	if (!(helper = CreateCryptoHelper(empty)))
	{
		LogError("Unable to create the decryption processor.");
		return TSRETURN_ERROR(("Unable to create the decryption processor"), false);
	}

	helper->SetOperationStatusCallback(m_status);
	helper->SetTaskInformation(m_currentTask, m_taskCount);
	if (!!m_keyGenCallback)
		helper->SetKeyGenCallback(m_keyGenCallback);

	if (!(reader = std::dynamic_pointer_cast<IDataReader>(CreateFileReader(sFile))))
	{
		LogError("Error occurred trying to open input file '%s'.", sFile.c_str());
		return TSRETURN_ERROR(("Bad File"), false);
	}

	if (!helper->ValidateFileContents_PublicOnly(reader))
	{
		LogError("ERROR:  The file has been modified.");
		return TSRETURN_ERROR(("The file has been modified."), false);
	}
	return TSRETURN(("OK"), true);
}
Beispiel #2
0
bool FileVEILOperationsImpl::RegenerateStreamKey(const tscrypto::tsCryptoString &sFilename, tscrypto::tsCryptoData& headerSignature, tscrypto::tsCryptoData& workingKey)
{
	TSDECLARE_FUNCTIONExt(true);

	std::shared_ptr<IDataReader> reader;
	std::shared_ptr<ICmsHeaderBase> headerBase;
	std::shared_ptr<ICmsHeader> header7;
	std::shared_ptr<IDataIOBase> ioBase;

	if (!(reader = std::dynamic_pointer_cast<IDataReader>(CreateFileReader(sFilename))))
	{
		LogError("Error occured trying to open input file '%s'.", sFilename.c_str());
		return TSRETURN_ERROR(("Bad File"), false);
	}
	headerSignature.clear();
	workingKey.clear();
	if (!StreamStartsWithCmsHeader(reader, headerBase))
	{
		return true;
	}
	if (!(header7 = std::dynamic_pointer_cast<ICmsHeader>(headerBase)))
	{
		return TSRETURN_ERROR(("Not a CKM7 header"), false);
	}

	if (!m_session && header7->NeedsSession())
	{
		if (!!m_sessionCallback)
		{
			if (!(m_sessionCallback->GetSessionForHeader(false, headerBase, 0, m_session)))
			{
				LogError("No session.");
				reader->Close();
				return TSRETURN_ERROR(("Returns ~~"), false);
			}
		}
	}
	if (!m_session)
	{
		LOG(DebugError, "Unable to regenerate the working key and encrypted data.");
		return TSRETURN_ERROR(("Unable to regenerate the working key and encrypted data."), false);
	}
	else
	{
		std::shared_ptr<ICkmOperations> ops = std::dynamic_pointer_cast<ICkmOperations>(header7);

		if (!ops || !ops->RegenerateWorkingKey(m_session, workingKey))
		{
			LOG(DebugError, "Unable to regenerate the working key and encrypted data.");
			return TSRETURN_ERROR(("Unable to regenerate the working key and encrypted data."), false);
		}
	}

	headerSignature = header7->GetSignature();

	return TSRETURN(("OK"), true);
}
Beispiel #3
0
//------------------------------------------------------------------------
bool CFileReadSLK::LoadFromFile( const char* pFileName )
//------------------------------------------------------------------------
{
	assert( NULL == m_data );
	assert( NULL == m_column );

	//OutputDebugString(pFileName);
	//OutputDebugString("\n==================================\n");
	IFileReader* fileReader = NULL;
	if( !CreateFileReader( &fileReader ) )
		return false;

	bool isLoadOk = true;
	for( unsigned int i = 0; i < _TSLKValueArray.size(); i++ )
	{
		_TSLKValue* p = _TSLKValueArray[i];
		SAFE_DELETE( p );
	}
	_TSLKValueArray.clear();
	char*	buffer = NULL;
	uInt32	bufferSize = 0;
	if(fileReader)
	{
		if( !(fileReader->OpenFile( pFileName )) )
		{
			isLoadOk = false;
			goto OPEN_FILE_FAIL;
		}
		bufferSize = fileReader->GetSize();
		assert( bufferSize > 0 );
		buffer = new char[bufferSize+1];
		memset( buffer, 0, (bufferSize + 1) * sizeof(char) );
		char tmpBuffer[1024];
		memset( tmpBuffer, 0, 1024 * sizeof(char) );

		char* ptrBuffer = buffer;
		size_t size = fileReader->Read( (void*)tmpBuffer, 1024 );
		assert( "出现异常错误!" && size <= 1024 );
		size_t count = 0;
		while( size > 0 )		
		{
			memcpy( ptrBuffer, tmpBuffer, size );
			ptrBuffer	+= size;
			count		+= size;
			memset( tmpBuffer, 0, 1024 * sizeof(char) );
			size = fileReader->Read( tmpBuffer, 1024 );
			assert( "出现异常错误!" && size <= 1024 );
		}
		assert( "文件大小错误!" && bufferSize == count );
		if( bufferSize != count )
			isLoadOk = false;
		else if( !GetInfoFromMemory( buffer, bufferSize ) )
			isLoadOk = false;

		SAFE_DELETE_ARRAY( buffer );
	}

OPEN_FILE_FAIL:
	if(fileReader)
		fileReader->Close();
	SAFE_DELETE( fileReader );

	for( unsigned int i = 0; i < _TSLKValueArray.size(); i++ )
	{
		_TSLKValue* p = _TSLKValueArray[i];
		SAFE_DELETE( p );
	}
	_TSLKValueArray.clear();

	return isLoadOk;
}
Beispiel #4
0
bool FileVEILOperationsImpl::EncryptSignFile(const tscrypto::tsCryptoString &sFilename, const tscrypto::tsCryptoString &sEncryptedFilename, const tscrypto::tsCryptoString &lpszTempFile,
	std::shared_ptr<ICmsHeader> Header, CompressionType comp, TS_ALG_ID algorithm, TS_ALG_ID hashAlgorithm, bool SignHeader, bool bindData,
	CMSFileFormatIds DataFormat, bool randomIvec, SymmetricPaddingType paddingType, int blockSize)
{
	TSDECLARE_FUNCTIONExt(true);

	std::shared_ptr<IDataReader>   inputFile;
	std::shared_ptr<IDataWriter>   outputFile;
	std::shared_ptr<IDataIOBase>   ioBase;
	tscrypto::tsCryptoData buff;
	tscrypto::tsCryptoString sTempFile;

	if (lpszTempFile.size() > 0)
	{
		sTempFile = lpszTempFile;
	}
	else
	{
		sTempFile = sEncryptedFilename;
		sTempFile += ".tmp";
	}

	LOG(DebugInfo3, "Encrypting file '" << sFilename << "'");

	//
	// Now create the output file.
	//
	if (!(outputFile = std::dynamic_pointer_cast<IDataWriter>(CreateDataWriter(sTempFile.c_str()))))
	{
		LogError("Error occurred while creating temporary file '%s'.", sTempFile.c_str());
		return TSRETURN_ERROR(("FAILED"), false);
	}

	if (!(inputFile = std::dynamic_pointer_cast<IDataReader>(CreateFileReader(sFilename.c_str()))))
	{
		outputFile->Close();
		xp_DeleteFile(sTempFile);
		LogError("Error occurred trying to open input file '%s'.", sFilename.c_str());
		return TSRETURN_ERROR(("Bad File"), false);
	}

	if (!EncryptSignStream(inputFile, outputFile, Header, comp, algorithm, hashAlgorithm, SignHeader, bindData, DataFormat, randomIvec, paddingType, blockSize))
	{
		inputFile->Close();
		outputFile->Close();
		xp_DeleteFile(sTempFile);
		return TSRETURN_ERROR(("Returns ~~"), false);
	}
	inputFile->Close();
	outputFile->Close();

	if (lpszTempFile.size() == 0)
	{
		xp_DeleteFile(sEncryptedFilename);

		// Copy the temp file to the destination file
		// According to Jeffrey Richter, "...MoveFile() does not support
		// the moving/renaming of streams."
		// (http://www.microsoft.com/msj/1198/ntfs/ntfs.aspx)
		//if(!MoveFile(sTempFile, sEncryptedFilename))

		if (!xp_RenameFile(sTempFile, sEncryptedFilename))
		{
			tscrypto::tsCryptoString msg;

			switch (errno)
			{
			case EACCES:
				msg = "The destination file already exists";
				break;
			case ENOENT:
				msg = "The source file does not exist";
				break;
			case EINVAL:
				if ((xp_GetFileAttributes(sEncryptedFilename.c_str()) & XP_FILE_ATTRIBUTE_DIRECTORY) != 0)
					msg = "There is a directory called " + sEncryptedFilename + " already.";
				else
					msg = "The file name contains invalid characters";
				break;
			default:
				msg = "An unknown error has occurred while creating the encrypted file.";
				break;
			}
			// Process any inserts in lpMsgBuf.
			// ...
			// Check to see if this was a file permissions error
			DWORD dwAttributes = ::xp_GetFileAttributes(sEncryptedFilename.c_str());

			if (dwAttributes & XP_FILE_ATTRIBUTE_READONLY)
				LogError("The specified output file cannot be accessed because it has Read Only permissions.");
			//else if(dwAttributes & FILE_ATTRIBUTE_SYSTEM)
			//	SetErrorMessage("The specified output file cannot be accessed because it is used exclusively by the Operating System.");
			//else if(dwAttributes & FILE_ATTRIBUTE_HIDDEN)
			//	SetErrorMessage("The specified output file cannot be accessed because it has the Hidden file attribute set.");
			else
				LogError(msg.c_str());

			secureDeleteEntireFile(sTempFile.c_str(), 3);
			return TSRETURN_ERROR(("FAILED"), false);
		}

		xp_DeleteFile(sTempFile);
		//CKMUtility::secureDelete((CKMString)sTempFile);
	}
	return TSRETURN(("OK"), true);
}
Beispiel #5
0
bool FileVEILOperationsImpl::DecryptVerify(std::shared_ptr<ICmsHeader> header, const tscrypto::tsCryptoString &sFilename, const tscrypto::tsCryptoString &sDecryptedFilename, const tscrypto::tsCryptoString &lpszTempFile, const tscrypto::tsCryptoString &sTempFile, bool headerIncluded)
{
	TSDECLARE_FUNCTIONExt(true);

	std::shared_ptr<IDataReader> reader;
	std::shared_ptr<IDataWriter> writer;
	tscrypto::tsCryptoString outputFilename;

	// Get output filename
	if (sDecryptedFilename.size() > 0)
	{
		outputFilename = sDecryptedFilename;
	}
	else
	{
		outputFilename = header->GetDataName();
		if (outputFilename.size() == 0)
		{
			LogError("Unable to retrieve the original file name from the encrypted file.");
			return TSRETURN_ERROR(("false"), false);
		}
	}
	std::shared_ptr<IDataIOBase> ioBase;

	if (!(reader = std::dynamic_pointer_cast<IDataReader>(CreateFileReader(sFilename))))
	{
		xp_DeleteFile(sTempFile);
		LogError("Error occured trying to open input file '%s'.", sFilename.c_str());
		return TSRETURN_ERROR(("Bad File"), false);
	}
	ioBase.reset();

	if (!(writer = std::dynamic_pointer_cast<IDataWriter>(CreateDataWriter(sTempFile))))
	{
		reader->Close();
		xp_DeleteFile(sTempFile);
		LogError("Error occured trying to open input file '%s'.", sFilename.c_str());
		return TSRETURN_ERROR(("Bad File"), false);
	}
	ioBase.reset();

	std::shared_ptr<ICryptoHelper> helper;

	if (!m_session && header->NeedsSession())
	{
		if (!!m_sessionCallback)
		{
			if (!m_sessionCallback->GetSessionForHeader(false, std::dynamic_pointer_cast<ICmsHeaderBase>(header), 0, m_session))
			{
				LogError("No session.");
				reader->Close();
				xp_DeleteFile(sTempFile);
				return TSRETURN_ERROR(("Returns ~~"), false);
			}
		}
	}
	if (!m_session)
	{
		LogError("Unable to retrieve the cryptographic helper object from the CKM Runtime.");
		reader->Close();
		xp_DeleteFile(sTempFile);
		return TSRETURN_ERROR(("Returns ~~"), false);
	}
	else
	{
		if (!(helper = CreateCryptoHelper(m_session)))
		{
			LogError("Unable to retrieve the cryptographic helper object from the CKM Runtime.");
			reader->Close();
			xp_DeleteFile(sTempFile);
			return TSRETURN_ERROR(("Returns ~~"), false);
		}
	}

	helper->SetOperationStatusCallback(m_status);
	helper->SetTaskInformation(m_currentTask, m_taskCount);
	if (!!m_keyGenCallback)
		helper->SetKeyGenCallback(m_keyGenCallback);

	std::shared_ptr<ICmsHeaderBase> headerBase; // TODO:  Issue with new code for disconnected streams.     = header;

	if (!(helper->DecryptStream(headerBase, reader, writer, headerIncluded)))
	{
		LogError("Unable to decrypt the data.");
		return TSRETURN_ERROR(("Unable to decrypt the data."), false);
	}

	reader->Close();
	writer->Close();
	reader.reset();
	writer.reset();

	if (lpszTempFile.size() == 0)
	{
		xp_DeleteFile(sDecryptedFilename);

		// Copy the temp file to the destination file
		// According to Jeffrey Richter, "...MoveFile() does not support
		// the moving/renaming of streams."
		// (http://www.microsoft.com/msj/1198/ntfs/ntfs.aspx)
		//if(!MoveFile(sTempFile, sEncryptedFilename))
		if (!xp_RenameFile(sTempFile, sDecryptedFilename))
		{
			tscrypto::tsCryptoString msg;

			switch (errno)
			{
			case EACCES:
				msg = "The destination file already exists";
				break;
			case ENOENT:
				msg = "The source file does not exist";
				break;
			case EINVAL:
				if ((xp_GetFileAttributes(sDecryptedFilename.c_str()) & XP_FILE_ATTRIBUTE_DIRECTORY) != 0)
					msg = "There is a directory called " + sDecryptedFilename + " already.";
				else
					msg = "The file name contains invalid characters";
				break;
			default:
				msg = "An unknown error has occurred while creating the decrypted file.";
				break;
			}
			// Process any inserts in lpMsgBuf.
			// ...
			// Check to see if this was a file permissions error
			DWORD dwAttributes = ::xp_GetFileAttributes(sDecryptedFilename.c_str());

			if (dwAttributes & XP_FILE_ATTRIBUTE_READONLY)
				LogError("The specified output file cannot be accessed because it has Read Only permissions.");
			//else if(dwAttributes & FILE_ATTRIBUTE_SYSTEM)
			//	SetErrorMessage("The specified output file cannot be accessed because it is used exclusively by the Operating System.");
			//else if(dwAttributes & FILE_ATTRIBUTE_HIDDEN)
			//	SetErrorMessage("The specified output file cannot be accessed because it has the Hidden file attribute set.");
			else
				LogError(msg.c_str());

			secureDeleteEntireFile(sTempFile.c_str(), 3);
			return TSRETURN_ERROR(("FAILED"), false);
		}

		xp_DeleteFile(sTempFile);
		//CKMUtility::secureDelete((CKMString)sTempFile);
	}
	return TSRETURN(("OK"), true);
}
Beispiel #6
0
HGRPOBJ DGraphicStore::AcquireSMD( SString strFilename, int Preset )
{
	strFilename = strFilename.LowerCase();

	HGRPOBJ Handle;
	HGRPOBJ Null; 

	bool bCloneWhenItFound;
	DPOOLMODE Mode;
	bool bEasyToUpdate;
	switch( Preset )
	{
		case SkinningMesh:
			Mode = DPOOL_DEFAULT;
			bEasyToUpdate = true;
			bCloneWhenItFound = true;
			break;
		case StaticMesh:
		default:
			Mode = DPOOL_DEFAULT;
			bEasyToUpdate = false;
			bCloneWhenItFound = false;
			break;
	}

	// Finding
	MeshIterator iMeshAdd = m_Case.find( SFullName("offline", DCutPath(strFilename)) );
	if( !iMeshAdd.valid() )
	{// not found, create new one
		iMeshAdd = m_Case.addEmpty();

		Handle.pObject = iMeshAdd.ptr();
		Handle.ID = iMeshAdd.index();
		m_Case.setName( iMeshAdd.index(), SFullName("offline", DCutPath(strFilename)) );
		if( !Handle.IsValid() )
		{
			DLogWriteSystem( "DGraphicStore(%s) has fatal error on creation.", (lpctstr)strFilename );
			return Handle;
		}
	}
	else
	{// already exist
		Handle.pObject = iMeshAdd.ptr();
		Handle.ID = iMeshAdd.index();

		if( bCloneWhenItFound )
		{
			return CloneSMD( Handle );
		}
		else
		{// increase reference count
			m_Case.addEmpty( iMeshAdd.index() ); // this func. just add ref if object already exists in the index.
			return Handle;
		}
	}

	if( Handle.pObject==NULL ) { return Null; }
#ifdef _DEBUG
	Handle.pObject->m_strDebugRscName = strFilename;// 디버그를 위한 객체이름
#endif
	Handle.pObject->Name = SName((const char*)strFilename);

	// Load from file
	DFile File;
	if( !File.Open( (const char*)strFilename ) )
	{// cannot open a file!
		DLogWriteSystem( "DGraphicStore::AcquireSMD(%s) couldn't open file!", (const char*)strFilename );
		m_Case.remove( Handle.ID );
		return Null;
	}

	DProgressiveMesh *pMesh = Handle.pObject;
	////////////////////////////////////////////
	// Convert
	// Old SMD -> Latest SMD
	//
	// : Test File Type to convert
	////////////////////////////////////////////
	char aTestBuffer[4];
	File.Read( aTestBuffer, 4*sizeof(char) );
	if( appStrncmp( aTestBuffer, "SSKF", 4 )!=0 )
	{
		File.SeekToBegin();
		// Read mesh
		GMeshGrp meshOther;
		if( !meshOther.Load( &File, false ) )
		{ 
			File.Close();
			return Null;
		}

		// Cut Texture Name's Path string
		GMaterial *pMaterial = meshOther.GetMaterial();
		DWORD nNumMaterials = meshOther.GetNumMaterials();
		for( DWORD i=0; i<nNumMaterials; i++ )
		{
			SString strTemp = pMaterial[i].GetTexture();
			pMaterial[i].SetTexture( DCutPath(strTemp) );
		}

		// Convert it!
		pMesh->ImportOtherMesh( meshOther );
	}
	// End of Converting
	else
	{
		File.SeekToBegin();
		DArchive *Ar = CreateFileReader( File.GetFile() );
		
		pMesh->Serialize( *Ar );
		// release buffer
		SAFE_DELETE( Ar );
	}
	// End of Loading
	

	pMesh->BuildVertexBuffer();

	pMesh->Textures.Empty();
	For( int i = 0; i < pMesh->Materials.Num(); ++i )
	{		
		SString strTexName;
		strTexName = DGetParentDir(strFilename,2);
		strTexName += "png\\";
		strTexName += (const char*)*pMesh->Materials[i].DiffuseTex;
		DTexture *pTex = DGlobalMng()->TextureAcquire( strTexName, true, true );
		if( pTex==NULL )
		{
			strTexName = DGetPathOnly(strFilename);
			strTexName += (const char*)*pMesh->Materials[i].DiffuseTex;
			pTex = DGlobalMng()->TextureAcquire( strTexName, true, true );
		}
		pMesh->Textures.AddItem( pTex );
	}
	
	
	File.Close();

	return Handle;
}
uint32 FFileManagerGeneric::CopyWithProgress( const TCHAR* InDestFile, const TCHAR* InSrcFile, bool ReplaceExisting, bool EvenIfReadOnly, bool Attributes, FCopyProgress* Progress )
{
	uint32	Result = COPY_OK;

	// Direct file copier.
	if( Progress->Poll( 0.0 ) )
	{
		FString SrcFile		= InSrcFile;
		FString DestFile	= InDestFile;
	
		FArchive* Src = CreateFileReader( *SrcFile );
		if( !Src )
		{
			Result = COPY_Fail;
		}
		else
		{
			FArchive* Dest = CreateFileWriter( *DestFile,( ReplaceExisting ? 0 : FILEWRITE_NoReplaceExisting ) | ( EvenIfReadOnly ? FILEWRITE_EvenIfReadOnly : 0 ) );
			if( !Dest )
			{
				Result = COPY_Fail;
			}
			else
			{
				int64 Size = Src->TotalSize();
				int64 Percent = 0, NewPercent = 0;
				uint8* Buffer = new uint8[COPYBLOCKSIZE];
				for( int64 Total = 0; Total < Size; Total += sizeof(Buffer) )
				{
					int64 Count = FMath::Min( Size - Total, (int64)sizeof(Buffer) );
					Src->Serialize( Buffer, Count );
					if( Src->IsError() )
					{
						Result = COPY_Fail;
						break;
					}
					Dest->Serialize( Buffer, Count );
					if( Dest->IsError() )
					{
						Result = COPY_Fail;
						break;
					}
					NewPercent = Total * 100 / Size;
					if( Progress && Percent != NewPercent && !Progress->Poll( ( float )NewPercent / 100.f ) )
					{
						Result = COPY_Canceled;
						break;
					}
					Percent = NewPercent;
				}
				delete [] Buffer;
				if( Result == COPY_OK && !Dest->Close() )
				{
					Result = COPY_Fail;
				}
				delete Dest;
				if( Result != COPY_OK )
				{
					Delete( *DestFile );
				}
			}
			if( Result == COPY_OK && !Src->Close() )
			{
				Result = COPY_Fail;
			}
			delete Src;
		}
		if( Progress && Result==COPY_OK && !Progress->Poll( 1.0 ) )
		{
			Result = COPY_Canceled;
		}
	}
	else
	{
		Result = COPY_Canceled;
	}

	return Result;
}