해당 프로그램은 악성코드 분석 연구 도중 흥미 위주로 만들어본 프로그램이며, 꼭 사용 전 파일을 백업해주세요. 필자는 이 프로그램을 사용함에 있어 생긴 피해에 대해 어떠한 책임도 지지 않습니다.


PyCLDecryptor.exe


 


 테스트를 위해 실제로 가상머신 내에서 PyCL 랜섬웨어를 돌려 일부러 감염시킨 테스트 파일들입니다.


 

 프로그램 실행 후 복호화 할 파일/폴더의 경로와 키 값을 입력하면 자동으로 해당 경로 하위를 전부 돌면서 감염된 확장자를 확인하고 입력받은 키로 복호화를 시도합니다. 복호화에 실패하더라도 원본 파일을 수정하거나 지우지는 않지만 혹시 모르니 항상 백업은 하고 사용해주시기 바랍니다. 랜섬웨어의 키를 찾는 방법은 이전 포스트의 마지막에 작성해두었습니다.


 소스코드는 gist로 첨부하겠습니다.

PyCLDecryptor.cpp 

/*
The MIT License (MIT)
Copyright (C) 2018 5kyc1ad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <stdio.h>
#include <string>
#include <iostream>
#include <io.h>
#include <stdio.h>
#include <fcntl.h>
#include <Shlwapi.h>
#include <Windows.h>
#include <wincrypt.h>
#include "picosha256.h"
#define BLOCK_SIZE 65536
typedef struct _AES256KEYBLOB
{
BLOBHEADER header;
DWORD keySize;
BYTE keyData[32];
} AES256KEYBLOB;
BOOL PyCLDecryptFile(const BYTE decryptKey[picosha2::k_digest_size], const std::wstring encryptFilePath);
unsigned int PyCLRecursivelyDecryptFiles(const BYTE decryptKey[picosha2::k_digest_size], std::wstring currentPath);
inline bool endswith(std::wstring const & value, std::wstring const & ending)
{
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
std::wstring encryptedPath;
std::wcout << L"[*] Input path for Decryption : ";
std::wcin >> encryptedPath;
if (encryptedPath[encryptedPath.size() - 1] == L'\\')
encryptedPath = encryptedPath.substr(0, encryptedPath.size() - 1);
std::string inputKey;
std::wcout << L"[*] Input Key : ";
std::cin >> inputKey;
BYTE decryptKey[picosha2::k_digest_size] = { 0, };
picosha2::hash256(inputKey, decryptKey, decryptKey + picosha2::k_digest_size);
std::wcout << L"[*] Decrypt Key : ";
for (int i = 0; i < picosha2::k_digest_size; i++)
wprintf(L"%02x ", decryptKey[i]);
std::wcout << std::endl;
DWORD dwAttribute = GetFileAttributes(encryptedPath.c_str());
if (dwAttribute == INVALID_FILE_ATTRIBUTES) // Path not exists
{
std::wcerr << L"[-] Target path not found : " << encryptedPath << std::endl;
return -1;
}
else if ((dwAttribute | FILE_ATTRIBUTE_DIRECTORY)) // Path is a directory
{
unsigned int decryptedCount = PyCLRecursivelyDecryptFiles(decryptKey, encryptedPath);
std::wcout << L"[*] Successfully Decrypted File Count : " << decryptedCount << std::endl;
}
else // Path is a file
{
if(PyCLDecryptFile(decryptKey, encryptedPath))
std::wcout << L"[+] Success : " << encryptedPath << std::endl;
else
std::wcout << L"[-] Failed : " << encryptedPath << std::endl;
}
return 0;
}
BOOL PyCLDecryptFile(const BYTE decryptKey[picosha2::k_digest_size], const std::wstring encryptedFilePath)
{
if (PathFileExists(encryptedFilePath.c_str()) == FALSE)
{
std::wcerr << L"[-] Target file not found : " << encryptedFilePath << std::endl;
return FALSE;
}
std::wstring decryptFilePath = encryptedFilePath.substr(0, encryptedFilePath.find_last_of(L'.'));
HANDLE hDecryptFile;
if ((hDecryptFile = CreateFile(decryptFilePath.c_str(), GENERIC_ALL, FILE_SHARE_READ, NULL, CREATE_ALWAYS, NULL, NULL)) == INVALID_HANDLE_VALUE)
{
std::wcerr << L"[-] Can't get decrypt file handle : " << GetLastError() << L", " << decryptFilePath << std::endl;
return FALSE;
}
const size_t chunkSize = BLOCK_SIZE;
BYTE chunk[chunkSize] = { 0, };
DWORD outLen = 0;
HANDLE hEncryptFile;
if ((hEncryptFile = CreateFile(encryptedFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL)) == INVALID_HANDLE_VALUE)
{
std::wcerr << L"[-] Can't get encrypt file handle : " << GetLastError() << L", " << encryptedFilePath << std::endl;
CloseHandle(hDecryptFile);
DeleteFile(decryptFilePath.c_str());
return FALSE;
}
BOOL bResult = FALSE;
BYTE fileSize[16] = { 0, };
if ((bResult = ReadFile(hEncryptFile, fileSize, 16, &outLen, NULL)) == FALSE)
{
std::wcerr << L"[-] Can't get filesize : " << GetLastError() << L", " << encryptedFilePath << std::endl;
CloseHandle(hEncryptFile);
CloseHandle(hDecryptFile);
DeleteFile(decryptFilePath.c_str());
return FALSE;
}
BYTE IV[16] = { 0, };
if ((bResult = ReadFile(hEncryptFile, IV, 16, &outLen, NULL)) == FALSE)
{
std::wcerr << L"[-] Can't get IV : " << GetLastError() << L", " << encryptedFilePath << std::endl;
CloseHandle(hEncryptFile);
CloseHandle(hDecryptFile);
DeleteFile(decryptFilePath.c_str());
return FALSE;
}
HCRYPTPROV hProv;
if (CryptAcquireContextW(&hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) == FALSE)
{
std::wcerr << L"[-] CryptAcquireContextW Error : " << GetLastError() << std::endl;
CloseHandle(hEncryptFile);
CloseHandle(hDecryptFile);
DeleteFile(decryptFilePath.c_str());
return FALSE;
}
AES256KEYBLOB blob;
blob.header.bType = PLAINTEXTKEYBLOB;
blob.header.bVersion = CUR_BLOB_VERSION;
blob.header.reserved = 0;
blob.header.aiKeyAlg = CALG_AES_256;
blob.keySize = 32;
memcpy(blob.keyData, decryptKey, picosha2::k_digest_size);
HCRYPTKEY hKey;
if (CryptImportKey(hProv, (BYTE*)&blob, sizeof(AES256KEYBLOB), NULL, 0, &hKey) == FALSE)
{
std::wcerr << L"[-] CryptImportKey Error : " << GetLastError() << std::endl;
CryptReleaseContext(hProv, 0);
CryptDestroyKey(hKey);
CloseHandle(hEncryptFile);
CloseHandle(hDecryptFile);
DeleteFile(decryptFilePath.c_str());
return FALSE;
}
DWORD dwMode = CRYPT_MODE_CBC;
if (CryptSetKeyParam(hKey, KP_MODE, (BYTE*)&dwMode, 0) == FALSE)
{
std::wcerr << L"[-] CryptSetKeyParam Mode Error : " << GetLastError() << std::endl;
CryptReleaseContext(hProv, 0);
CryptDestroyKey(hKey);
CloseHandle(hEncryptFile);
CloseHandle(hDecryptFile);
DeleteFile(decryptFilePath.c_str());
return FALSE;
}
if (CryptSetKeyParam(hKey, KP_IV, IV, 0) == FALSE)
{
std::wcerr << L"[-] CryptSetKeyParam IV Error : " << GetLastError() << std::endl;
CryptReleaseContext(hProv, 0);
CryptDestroyKey(hKey);
CloseHandle(hEncryptFile);
CloseHandle(hDecryptFile);
DeleteFile(decryptFilePath.c_str());
return FALSE;
}
DWORD orgFileSize = GetFileSize(hEncryptFile, NULL) - 32;
DWORD readTotalSize = 0;
BOOL isFinal = FALSE;
BOOL isSuccess = FALSE;
while (bResult = ReadFile(hEncryptFile, chunk, chunkSize, &outLen, NULL))
{
if (outLen == 0)
break;
readTotalSize += outLen;
if (readTotalSize == orgFileSize)
isFinal = TRUE;
// Custom Padding used, param Final must not be TRUE
if (CryptDecrypt(hKey, NULL, FALSE, NULL, chunk, &outLen) == FALSE)
{
std::wcerr << L"[-] CryptDecrypt Error : " << GetLastError() << std::endl;
break;
}
// Remove Padding
for (outLen; chunk[outLen - 1] == '\x20'; outLen--);
DWORD outWritten;
if (WriteFile(hDecryptFile, chunk, outLen, &outWritten, NULL) == FALSE)
{
std::wcerr << L"[-] WriteFile Error : " << GetLastError() << std::endl;
break;
}
if (isFinal)
{
isSuccess = TRUE;
break;
}
}
CryptDestroyKey(hKey);
CryptReleaseContext(hProv, 0);
CloseHandle(hEncryptFile);
CloseHandle(hDecryptFile);
if (isSuccess == FALSE)
DeleteFile(decryptFilePath.c_str());
return isSuccess;
}
unsigned int PyCLRecursivelyDecryptFiles(const BYTE decryptKey[picosha2::k_digest_size], std::wstring currentPath)
{
std::wstring tmpCurrentPath = currentPath + L"\\*";
std::wcout << L"[*] Finding target : " << currentPath << std::endl;
unsigned int decryptedCount = 0;
WIN32_FIND_DATA findData;
HANDLE hFile = FindFirstFileEx(tmpCurrentPath.c_str(), FindExInfoMaxInfoLevel, &findData, FINDEX_SEARCH_OPS::FindExSearchNameMatch, NULL, FIND_FIRST_EX_LARGE_FETCH);
if (hFile == INVALID_HANDLE_VALUE)
hFile = FindFirstFile(tmpCurrentPath.c_str(), &findData);
if (hFile == INVALID_HANDLE_VALUE)
{
std::wcout << L"[*] Can't search directory : " << GetLastError() << L", " << tmpCurrentPath << std::endl;
return 0;
}
do
{
if (!wcscmp(findData.cFileName, L".") || !wcscmp(findData.cFileName, L".."))
continue;
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
std::wstring targetPath = currentPath + L"\\" + findData.cFileName;
decryptedCount += PyCLRecursivelyDecryptFiles(decryptKey, targetPath);
}
else if (endswith(findData.cFileName, L".impect"))
{
std::wstring targetPath = currentPath + L"\\" + findData.cFileName;
BOOL isSuccess = PyCLDecryptFile(decryptKey, targetPath);
if(isSuccess)
{
// std::wcout << L"[+] Success : " << targetPath << std::endl;
decryptedCount++;
}
//else
// std::wcout << L"[-] Failed : " << targetPath << std::endl;
}
} while (FindNextFile(hFile, &findData));
FindClose(hFile);
return decryptedCount;
}

블로그 이미지

__미니__

E-mail : skyclad0x7b7@gmail.com 나와 계약해서 슈퍼 하-카가 되어 주지 않을래?

,