0

I am trying to replace a keyboard key press with other key. The terminal crashes as soon as I type 'A'. How do I replace the key press in write syscall.

unsigned long hacked_write_test( struct pt_regs *regs ) {
    int r, i;
    unsigned int fd = regs->di;
    char *buf = (char*) regs->si;
    if (fd == 1 || fd == 3 || fd == 4) {
      if (buf[0] == 0x61) {
        printk("in write: A received");
        regs->si = 0x62;
      }
    }
    r = original_write(regs);
    return r;
}
tarun14110
  • 940
  • 5
  • 26
  • 57
  • 2
    FYI an `'a'` received on a `write` syscall has nothing to do with a key press, it can originate from literally anywhere. You will inevitably break your entire system with such a global modification. Moreover, `regs->si = 0x62` that is a completely invalid address. You seem to want to change `buf[0]` instead. In any case, dereferencing a pointer passed by userspace like that is bad, you should never do that directly from kernel. Either copy the buffer or check the pointer first. – Marco Bonelli Sep 22 '21 at 11:42
  • 1
    Also, you are breaking the `const` guarantee for the write buffer. – Ian Abbott Sep 22 '21 at 15:34
  • @MarcoBonelli Thanks. I was able to replace one character. Yes! you are right it will replace all inputs. My eventual goal is to replace inputs from any device (keyboard, file etc), that's why I choose to start with overwriting write sys call. Is there a way to just restrict it to keyboard inputs for now? – tarun14110 Sep 22 '21 at 22:13
  • @IanAbbott Can you please elaborate? I was able to replace the key press by replacing value in buf[0]. – tarun14110 Sep 22 '21 at 22:14
  • 2
    What @IanAbbott is saying is that `write(2)` takes a `const void *` pointer as argument, so it may very well be `const` data or data that is in a read only region, therefore modifying the contents of the buffer directly is a bug, you should copy it and modify the copy if you really want, or figure out some other way which does not involve modifying `buf` directly. – Marco Bonelli Sep 22 '21 at 22:16

0 Answers0