Защита информации в системах дистанционного обучения с монопольным доступом
}
CkgExcept(id, EXTERNAL_COM_ERROR);
}
//-----------------------------------------------------------------------------
Файл globalDef.h.
#ifndef __GLOBAL_DEF_H_
#define __GLOBAL_DEF_H_
//Версия модуля. Используется при запросе информации.
const short moduleVersionInfo = 0x0110; // 1.10
#endif //__GLOBAL_DEF_H_
Файл protect.h.
// protect.h : Declaration of the CProtect
#ifndef __PROTECT_H_
#define __PROTECT_H_
#include "resource.h" // main symbols
#include "cpp_ptr.h"
#include "ckg_array.h"
#include "ckg_buf.h"
enum E_FILE_OPEN_MODE
{
EF_READONLY, EF_READWRITE
};
class ObjectFile
{
CreateMode fileMode;
FILE *f;
cpp_ptr
E_FILE_OPEN_MODE mode;
CkgString uptFileNameForWrite;
CkgString uptFileNameForRead;
bool isOpened;
bool isClosed;
ObjectFile() : f(NULL), isOpened(false), isClosed(false) { };
void CryptBuf();
void DecryptBuf();
public:
static ObjectFile &Create(BSTR name, BSTR uptFileNameForWrite,
CreateMode mode);
static ObjectFile &Open(BSTR name, BSTR uptFileNameForWrite,
BSTR uptFileNameForRead);
void Write(const void *buf, unsigned size);
void Read(void *buf, unsigned size);
void Seek(int position, int mode);
unsigned GetPosition() const { return buffer->GetPosition(); }
void Close();
~ObjectFile();
};
/////////////////////////////////////////////////////////////////////////////
// CProtect
class ATL_NO_VTABLE CProtect :
public
CComObjectRootEx
public
CComCoClass
public ISupportErrorInfo,
public
IDispatchImpl
public
IDispatchImpl
public
IDispatchImpl
//
public IDispatchImpl
{
static
CkgArray
static
CkgSimpleContainerArray
void ContinueOpen(ObjectFile &file, short &handle);
void ContinueGenerateTimeLimitUPTfiles(BSTR algorithmCryptFileName,
BSTR algorithmDecryptFileName,
long LimitDaysCrypt,
long LimitDaysDecrypt);
HRESULT InternalGetAlgName(const CkgString &Strings,
CkgString SearchName,
CkgString &Result);
HRESULT InternalGetDataName(const CkgString &Strings,
CkgString SearchName,
CkgString &Result);
public:
CProtect()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_PROTECT)
DECLARE_PROTECT_FINAL_CONSTRUCT()
BEGIN_COM_MAP(CProtect)
COM_INTERFACE_ENTRY(IProtect)
//DEL COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY2(IDispatch, IProtect)
COM_INTERFACE_ENTRY(IProtectFile)
COM_INTERFACE_ENTRY(IProtectConformity)
// COM_INTERFACE_ENTRY(IProtectBase)
END_COM_MAP()
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// IProtect
public:
STDMETHOD(GenerateTimeLimitUPTfiles2)(/*[in]*/ BSTR algorithmCryptFileName, /*[in]*/ BSTR algorithmDecryptFileName, /*[in]*/ long LimitDaysCrypt, /*[in]*/ long LimitDaysDecrypt);
STDMETHOD(GenerateTimeLimitUPTfiles)(/*[in]*/ BSTR algorithmCryptFileName, /*[in]*/ BSTR algorithmDecryptFileName, /*[in]*/ long LimitDays);
STDMETHOD(GenerateUPTfiles)(/*[in]*/ BSTR algorithmCryptFileName, /*[in]*/ BSTR algorithmDecryptFileName);
STDMETHOD(GetInfo)(/*[out]*/ short *version, /*[out]*/ BSTR *info);
// IProtectFile
STDMETHOD(Create)(/*[in]*/ BSTR name, /*[in]*/ CreateMode mode, /*[in]*/ BSTR uptFileName, /*[out, retval]*/ short *handle);
STDMETHOD(Open)(/*[in]*/ BSTR name, /*[in]*/ BSTR uptFileNameForRead, /*[in]*/ BSTR uptFileNameForWrite, /*[out, retval]*/ short *handle);
STDMETHOD(Write)(/*[in]*/ short handle, /*[in]*/ VARIANT buffer, /*[out, retval]*/ long *written);
STDMETHOD(Read)(/*[in]*/ short handle, /*[out]*/ VARIANT *buffer, /*[out, retval]*/ long *read);
STDMETHOD(Close)(/*[in]*/ short handle);
STDMETHOD(WriteString)(/*[in]*/ short handle, /*[in]*/ BSTR buffer, /*[out, retval]*/ long *written);
STDMETHOD(ReadString)(/*[in]*/ short handle, /*[out]*/ BSTR *buffer, /*[out, retval]*/ long *read);
STDMETHOD(ToFile)(/*[in]*/ short handle, /*[in]*/ BSTR FileName, /*[oit, retval]*/ long *written);
STDMETHOD(FromFile)(/*[in]*/ short handle, /*[in]*/ BSTR FileName, /*[oit, retval]*/ long *read);
// IProtectConformity
STDMETHOD(CreateConformityFile)(/*[in]*/ BSTR name, /*[in]*/ BSTR uptFileNameForRead, /*[in]*/ BSTR uptFileNameForWrite, /*[in]*/ BSTR ArrayOfStrings);
STDMETHOD(EasyCreateConformityFile)(/*[in]*/ BSTR name, /*[in]*/ BSTR uptFileNameForCreate, /*[in]*/ BSTR ArrayOfStrings);
STDMETHOD(ReadConformityFile)(/*[in]*/ BSTR name, /*[in]*/ BSTR uptFileNameForRead, /*[out, retval]*/ BSTR *ArrayOfStrings);
STDMETHOD(GetAlgName)(/*[in]*/ BSTR Strings, /*[in]*/ BSTR SearchName, /*[out, retval]*/ BSTR *ResultStr);
STDMETHOD(GetDataName)(/*[in]*/ BSTR Strings, /*[in]*/ BSTR SearchName, /*[out, retval]*/ BSTR *ResultStr);
STDMETHOD(GetAlgFromFile)(/*[in]*/ BSTR FileName, /*[in]*/ BSTR uptFileNameForRead, /*[in]*/ BSTR SearchName, /*[out, retval]*/ BSTR *ResultStr);
STDMETHOD(GetDataFromFile)(/*[in]*/ BSTR FileName, /*[in]*/ BSTR uptFileNameForRead, /*[in]*/ BSTR SearchName, /*[out, retval]*/ BSTR *ResultStr);
// IProtectBase
};
#endif //__PROTECT_H_
Файл protect.cpp.
// protect.cpp : Implementation of CProtect
#include "stdafx.h"
#include
#include
#include
#include "globalDef.h"
#include "c_ptr.h"
#include "cpp_ptr.h"
#include "ckg_str.h"
#include "ckg_error_com.h"
#include "com_mem.h"
#include "Uniprot.h"
#include "protect.h"
#include "polymorphism.h"
#include "ArchiverBase.h"
#include "pdebug.h"
// В Visaul Basic все равно больше нельзя
const static unsigned maxDimDimensions = 60;
static bool TestFilePresent(BSTR name, bool maybeUnnecessary = false)
{
WriteToLog(_T("TestFilePresent()"));
if (!name && maybeUnnecessary)
return true;
if (!name)
return false;
USES_CONVERSION;
CkgString strName(W2T(name));
if (strName.IsEmpty() && maybeUnnecessary)
return true;
if (strName.IsEmpty())
return false;
FILE *f = _tfopen(strName, _T("rb"));
if (!f)
return false;
if (fclose(f))
CkgExcept(ERROR_CLOSE_FILE);
return true;
}
//=============================================================================
//class ObjectFile
//-----------------------------------------------------------------------------
void ObjectFile::CryptBuf()
{
WriteToLog(_T("ObjectFile::CryptBuf()"));
byte compressionLevel;
if (fileMode == DISABLE_ARC)
compressionLevel = 1; // min compression level
else
compressionLevel = 0; // default
unsigned long sizeOut;
BYTE *bufOut;
EIAB_ErrorNum err;
if (!Pack(compressionLevel, buffer->GetSize(),
static_cast
ArcExcept(err);
_ASSERT(sizeOut && bufOut);
pure_com_mem
buffer->Clear();
buffer->Write(&sizeOut, sizeof(unsigned));
buffer->Write(bufOut, sizeOut);
unsigned needAdd =
static_cast
(ROUND_SATA_SIZE - (sizeOut % ROUND_SATA_SIZE)) % ROUND_SATA_SIZE);
_ASSERT(needAdd != ROUND_SATA_SIZE);
for (unsigned i = 0; i < needAdd; i++)
{
int rnd = CoolRand();
Write(&rnd, 1);
}
_ASSERT((buffer->GetSize() - sizeof(unsigned)) % ROUND_SATA_SIZE == 0);
CryptData(*(static_cast
buffer->GetSize() - sizeof(unsigned),
*static_cast
}
//-----------------------------------------------------------------------------
void ObjectFile::DecryptBuf()
{
WriteToLog(_T("ObjectFile::DecryptBuf()"));
if (buffer->GetSize() < sizeof(TitleArcData) + sizeof(unsigned))
CkgExcept(ERROR_FILE_FORMAT);
unsigned packSize =
*(static_cast
DecryptData(*(static_cast
buffer->GetSize() - sizeof(unsigned),
*static_cast
unsigned long sizeOut;
BYTE *bufOut;
EIAB_ErrorNum err;
if(!Unpacking(packSize,
static_cast
&sizeOut, &bufOut, &err))
ArcExcept(err);
_ASSERT(sizeOut && bufOut);
pure_com_mem
buffer->Clear();
buffer->Write(bufOut, sizeOut);
}
//-----------------------------------------------------------------------------
ObjectFile &ObjectFile::Create(BSTR name, BSTR uptFileNameForWrite,
CreateMode mode)
{
WriteToLog(_T("ObjectFile::Create()"));
USES_CONVERSION;
if ((mode != DEFAULT && mode != DISABLE_ARC) || !uptFileNameForWrite ||
!name)
CkgExcept(ERROR_INVALID_ARGUMENT);
CkgString fileName(W2T(name));
if (fileName.IsEmpty())
CkgExcept(ERROR_OPEN_FILE);
if (!TestFilePresent(uptFileNameForWrite))
CkgExcept(_T("UPT-файл для шифрования файла не найден."));
cpp_ptr
TestPtr(obj);
obj->fileMode = mode;
obj->mode = EF_READWRITE;
obj->uptFileNameForWrite = W2T(uptFileNameForWrite);
obj->buffer = &CkgBuffer::Create(4096);
obj->f = _tfopen(fileName, _T("wb"));
if (!obj->f)
CkgExcept(ERROR_OPEN_FILE);
obj->isOpened = true;
return *obj.Detach();
}
//-----------------------------------------------------------------------------
ObjectFile &ObjectFile::Open(BSTR name, BSTR uptFileNameForWrite,
BSTR uptFileNameForRead)
{
WriteToLog(_T("ObjectFile::Open()"));
USES_CONVERSION;
if (!name)
CkgExcept(ERROR_INVALID_ARGUMENT);
CkgString fileName(W2T(name));
if (fileName.IsEmpty())
CkgExcept(ERROR_OPEN_FILE);
if (!TestFilePresent(uptFileNameForWrite, true))
CkgExcept(_T("UPT-файл для шифрования файла не найден."));
if (!TestFilePresent(uptFileNameForRead))
CkgExcept(_T("UPT-файл для расшифровки файла не найден."));
cpp_ptr
TestPtr(obj);
if (uptFileNameForWrite)
obj->uptFileNameForWrite = W2T(uptFileNameForWrite);
if (uptFileNameForRead)
obj->uptFileNameForRead = W2T(uptFileNameForRead);
obj->mode = (!uptFileNameForWrite || CkgString(obj->uptFileNameForWrite).IsEmpty()) ?
EF_READONLY : EF_READWRITE;
obj->f = _tfopen(fileName, _T("r+b"));
if (!obj->f)
CkgExcept(ERROR_OPEN_FILE);
if (fread(&obj->fileMode, sizeof(BYTE), sizeof(CreateMode), obj->f) != sizeof(CreateMode))
CkgExcept(ERROR_READ_FILE);
unsigned fileSize;
if (fread(&fileSize, sizeof(BYTE), sizeof(unsigned), obj->f) != sizeof(unsigned))
CkgExcept(ERROR_READ_FILE);
cpp_arr_ptr
TestPtr(buf);
if (fread(buf, sizeof(BYTE), fileSize, obj->f) != fileSize)
CkgExcept(ERROR_READ_FILE);
BYTE tmp;
if (fread(&tmp, sizeof(BYTE), 1, obj->f) == 1)
CkgExcept(ERROR_READ_FILE);
obj->buffer = &CkgBuffer::Create(4096);
obj->buffer->Write(buf, fileSize);
obj->DecryptBuf();
obj->buffer->LSeek(0);
obj->isOpened = true;
return *obj.Detach();
}
//-----------------------------------------------------------------------------
void ObjectFile::Write(const void *buf, unsigned size)
{
WriteToLog(_T("ObjectFile::Write()"));
if (mode == EF_READONLY)
CkgExcept(_T("Файл открыт только для чтения."));
if (!size)
{
buffer->SetSize(buffer->GetPosition());
return;
}
buffer->Write(buf, size);
}
//-----------------------------------------------------------------------------
void ObjectFile::Read(void *buf, unsigned size)
{
_ASSERT(!isClosed);
unsigned position = buffer->GetPosition();
if (buffer->GetSize() - position < size)
CkgExcept(ERROR_INVALID_ARGUMENT);
memcpy(buf,
static_cast
buffer->LSeek(position + size);
}
//-----------------------------------------------------------------------------
void ObjectFile::Seek(int position, int mode)
{
WriteToLog(_T("ObjectFile::Seek()"));
_ASSERT(!isClosed);
if (mode == SEEK_SET)
buffer->LSeek(position);
else if (mode == SEEK_CUR)
buffer->LSeek(buffer->GetPosition() + position);
else if (mode == SEEK_END)
buffer->LSeek(buffer->GetSize() + position);
else
CkgExcept(ERROR_INVALID_ARGUMENT);
}
//-----------------------------------------------------------------------------
void ObjectFile::Close()
{
WriteToLog(_T("ObjectFile::Close()"));
_ASSERT(!isClosed && isOpened);
isClosed = true; // Даже если и не закроем (возникнет исключение), то больше
// пробовать все равно толку нет
if (mode == EF_READWRITE)
{
if (fseek(f, 0, SEEK_SET))
CkgExcept(ERROR_WRITE_FILE);
if (fwrite(&fileMode, sizeof(BYTE), sizeof(CreateMode), f) != sizeof(CreateMode))
CkgExcept(ERROR_WRITE_FILE);
CryptBuf();
unsigned dataSize = buffer->GetSize();
if (fwrite(&dataSize, sizeof(BYTE), sizeof(unsigned), f) != sizeof(unsigned))
CkgExcept(ERROR_WRITE_FILE);
if (fwrite(buffer->GetBuf(), sizeof(BYTE),
dataSize, f) != dataSize)
CkgExcept(ERROR_WRITE_FILE);
if (fwrite(0, 1, 0, f) != 0)
CkgExcept(ERROR_WRITE_FILE);
}
if (fclose(f))
CkgExcept(ERROR_CLOSE_FILE);
f = NULL;
buffer = 0;
}
//-----------------------------------------------------------------------------
ObjectFile::~ObjectFile()
{
WriteToLog(_T("ObjectFile::~ObjectFile()"));
_ASSERT(isClosed);
if (isOpened && !isClosed)
Close();
if (f)
fclose(f);
}
//-----------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////
// CProtect
CkgArray
CkgSimpleContainerArray
STDMETHODIMP CProtect::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IProtect
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
STDMETHODIMP CProtect::GetInfo(short *version, BSTR *info)
{
try
{
*version = moduleVersionInfo;
CComBSTR str;
str.LoadString(IDS_MODULE_INFO);
*info = str.Copy();
return S_OK;
}
CONVERT_EXCEPTION_TO_COM_EXCEPTION
}
STDMETHODIMP CProtect::GenerateUPTfiles(BSTR algorithmCryptFileName,
BSTR algorithmDecryptFileName)
{
return GenerateTimeLimitUPTfiles(algorithmCryptFileName,
algorithmDecryptFileName,
0);
}
void CProtect::ContinueGenerateTimeLimitUPTfiles(
BSTR algorithmCryptFileName, BSTR algorithmDecryptFileName,
long LimitDaysDecrypt, long LimitDaysCrypt)
{
if (LimitDaysDecrypt)
LimitDaysDecrypt += GetCurrentDayNum();
if (LimitDaysCrypt)
LimitDaysCrypt += GetCurrentDayNum();
USES_CONVERSION;
if (!algorithmCryptFileName || !algorithmDecryptFileName)
CkgExcept(_T("Строка с именем upt-файла пустая."));
LPCTSTR fileNameCrypt(W2T(algorithmCryptFileName));
LPCTSTR fileNameDecrypt(W2T(algorithmDecryptFileName));
if (!_tcslen(fileNameCrypt) || !_tcslen(fileNameDecrypt))
CkgExcept(_T("Строка с именем upt-файла пустая."));
GenerateAlgorithm(*fileNameCrypt, *fileNameDecrypt,
static_cast
static_cast
}
STDMETHODIMP CProtect::GenerateTimeLimitUPTfiles(BSTR algorithmCryptFileName,
BSTR algorithmDecryptFileName,
long LimitDays)
{