Synchronizer for exchanging encrypted files between CyberSafe and cloud resources

    The CyberSafe cloud encryption function allows you to automatically copy encrypted files to “clouds”, such as Google Drive (this particular cloud resource is considered in this article) and any others. At the same time, if several users are working simultaneously with the cloud folder, encrypted files are synchronized on each of their computers. The general principles of working with the cloud encryption function were described here , in this article we will focus on the operation of the synchronizer itself.

    During its development, the technical problem was that when synchronizing files from the Google Drive folder on the user's computer with the Google web folderin the cloud, service information about encrypted files recorded in ADS is not transmitted and is lost. That is, the files on other devices after synchronization are encrypted, but the user cannot decrypt them.

    To solve this problem, an option was created with the creation of the CyberSafe Cloud folder , which is a mirror for the Google Drive folder . The user copies new unencrypted files to this folder, which are automatically encrypted by the Alfa Transparent File Encryptor Driver . The service information for the encrypted file (hash of the identifier of the encryption key) of 4096 bytes in size is recorded in ADS and is available to the driver for work. At the same time in itselfGoogle Drive folder, encrypted files are sent with service information recorded in the file header without using ADS, which allows you to save it when transferring to the "cloud".

    A mirror folder is created by CyberSafe automatically when a Google Drive folder is added to the program:



    The administrator of this folder is the first to add it to CyberSafe and assign keys to other users, which are written in a digital envelope to ADS folders (more about this is written here ). In the Google Drive folder, the program creates the cybersafe.cloud.conf file. This file contains information similar to the information in the ADS encrypted folder, namely: a symmetric encryption key protected by public keys of authorized users, the ID of this key, a list of used certificates.

    Cybersafe.cloud.conf “travels” on the Internet and spreads to computers of users who have access to an encrypted folder. By adding the Google Drive folder to CyberSafe on their computers, users no longer assign keys - the information is written to the ADS of this folder on their computers from cybersafe.cloud.conf .

    Now about how the synchronizer works. The program has two separate processes CloudSync.exe and СloudSync2.exethat synchronize between the CyberSafe mirror folder and the Google Drive folder .

    CloudSync.exe copies encrypted files with service information placed in the header from the mirrored folder to the Google Drive folder. This process is added to the “excluded” list for the encryption driver, which allows it to “see” the files in the mirror folder as encrypted and with service information in the header (the driver automatically displays information from ADS in the file header for such processes).

    The CloudSync.exe process does not have separate access to the ADS file.

    СloudSync2.exe is a normal process, which in the mirror folder “sees” the files decrypted, has access to ADS, can copy files fromGoogle Drive folders in the mirror, followed by automatic driver encryption.



    In the process of synchronizing files, there are several scenarios:

    1. A new file is copied to the Google Drive folder. It can be already encrypted, being copied there directly from the cloud as a result of actions performed on the computers of other users, or not encrypted - the user himself copies the new unencrypted file to the Google Drive folder on his computer.

    Checks for a service header at the beginning of the file.

    1.1 If there is a header, then we consider the file encrypted. Whether the file is encrypted or not determines the CloudSync.exe process. To do this, the first 4096 bytes of the file are analyzed for the presence of the ATE_HEADER header structure with the fields filled in:

    ATE_HEADER = Record
    KeyIDLength, KeyXOR: DWORD;
    Data: Array[1..ATE_KEY_ID_SIZE div sizeof(DWORD)] Of DWORD;
    KeyIDLength2, KeyXOR2: DWORD;
    Data2: Array[1..ATE_KEY_ID_SIZE div sizeof(DWORD)] Of DWORD;
    Flags, Flags2: DWORD;
    cData: Array[0..3575] Of AnsiChar;
    End;

    The scan function whether the file is encrypted or not:

    function isFileHasRightHeader(FileName: string): Boolean;
    var
    HEADER: ATE_HEADER;
    fs: TFileStream;
    begin
    Result := False;
    try
    fs := TFileStream.Create(FileName, fmOpenRead);
    try
    fs.Read(HEADER, SIZE_OF_ATE_HEADER);
    Result := (HEADER.KeyIDLength = ATE_KEY_ID_SIZE) and (HEADER.KeyIDLength2 = ATE_KEY_ID_SIZE);
    finally
    fs.Free;
    end;
    except
    on E: Exception do
    WriteToLog('!!! isFileHasRightHeader: ' + E.Message + #13 + FileName);
    end;
    end;

    The CloudSync.exe process copies the first 4096 bytes to a temporary file with the extension .ads. It then copies the remainder of the file with encrypted contents to a temporary file. Then it saves the service information (the header from the temporary file with the extension .ads) in the ADS temporary file (: AlfaFileEncryptor). Then it moves the temporary file to the mirror folder.

    Another technical problem : how to make sure that when copying encrypted files from the Google Drive folder to a mirrored folder, they are not re-encrypted by the driver? The solution to this issue is displayed by the code, due to which when the file is moved to a controlled encrypted folder, the driver does not perform any actions on the file and therefore the file is not re-encrypted: 1.2 If there is no header, consider the file not encrypted.

    function TrimHeaderAndMoveFile(SyncIndex: Integer; FileNameFrom, FileNameTo: TFileName): Boolean;
    // FileNameFrom - имя файла с "правильным" заголовком
    // FileNameTo - имя файла в шифрованном каталоге
    // P.S. FileNameFrom и FileNameTo должны быть на 1-ом разделе
    var
    fs, fs1: TFileStream;
    fn: string;
    begin
    Result := False;
    // путь к временному файлу
    fn := GetTempFileName(SyncIndex, FileNameFrom);
    try
    try
    // открываем зашифрованный файл в облачной папке
    fs := TFileStream.Create(FileNameFrom, fmOpenRead);
    try
    try
    // создаем временный файл с расширением .ads для сохранения служебного заголовка
    fs1 := TFileStream.Create(fn + '.ads', fmCreate);
    try
    fs1.CopyFrom(fs, SIZE_OF_ATE_HEADER); // 4096 байт
    finally
    fs1.Free;
    end;
    except
    on E: Exception do
    WriteToLog('!!! TrimHeaderAndMoveFile: ' + E.Message + #13 + fn);
    end;

    try
    if fs.Size > SIZE_OF_ATE_HEADER then // если содержимое зашифрованного файла не пустое
    begin
    fs1 := TFileStream.Create(fn, fmCreate);
    try
    fs1.CopyFrom(fs, fs.Size - SIZE_OF_ATE_HEADER); // копируем содержимое зашифрованного файла из облака во временный файл
    finally
    fs1.Free;
    end;
    end
    else
    begin
    CreateEmptyFile(fn); // если нет содержимого, то создаем пустой временный файл
    end;
    except
    on E: Exception do
    WriteToLog('!!! TrimHeaderAndMoveFile: ' + E.Message + #13 + fn);
    end;
    finally
    fs.Free;
    end;
    WriteADS(fn, fn + '.ads', 'AlfaFileEncryptor'); // создаем ADS для временного файла и копируем туда содержимое временного файла с расширением .ads
    DeleteFile(fn + '.ads'); // удаляем временный файл с расширением .ads


    // Вызываем функцию проверки наличия файла в зеркальной папке из процесса CloudSync2.exe
    if RemoteIsFileExists(FileNameTo) then
    begin
    // Вызываем функцию удаления файла в зеркальной папке из процесса CloudSync2.exe
    RemoteDeleteFile(FileNameTo);
    end;
    // Перемещаем временный файл в зеркальную папку
    RenameFile(fn, FileNameTo);

    Result := True;
    except
    end;
    finally
    if FileExists(fn) then
    begin
    try
    DeleteFile(fn);
    except
    end;
    end;
    if FileExists(fn + '.ads') then
    begin
    try
    DeleteFile(fn + '.ads');
    except
    end;
    end;
    end;
    end;

    The CloudSync2.exe process copies the file to the mirror folder, after which it is automatically encrypted by the driver. An unencrypted file is deleted from the Google Drive folder. Next, the CloudSync.exe process copies the encrypted file to the Google Drive folder from the mirror file, after which it is automatically sent to the “cloud” and gets to other users.

    2. The file is copied or edited in the CyberSafe mirror folder

    If a new file is copied by the user to the CyberSafe mirror folder, it is automatically encrypted by the driver. When editing an existing file in the mirror folder, it is also saved to the disk in encrypted form automatically. Next, the encrypted file is sent by the CloudSync.exe process to the Google Drive folder with service information in the header and from there it gets to the “cloud”.

    To properly synchronize and respond to changes to files in the Google Drive and mirror folders, the CloudSync.exe and CloudSync2.exe processes monitor the activity in these folders and carry out the corresponding copy operations described above.

    Also popular now: