Skip to content

Commit

Permalink
Fixes issue #18
Browse files Browse the repository at this point in the history
Dont check for sudo first, try to open fd
  • Loading branch information
MarinX committed Jun 4, 2024
1 parent a54d783 commit 01e950c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
11 changes: 7 additions & 4 deletions keylogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,15 @@ var allowedDevices = devices{"keyboard", "logitech mx keys"}
// New creates a new keylogger for a device path
func New(devPath string) (*KeyLogger, error) {
k := &KeyLogger{}
if !k.IsRoot() {
return nil, errors.New("Must be run as root")
}
fd, err := os.OpenFile(devPath, os.O_RDWR, os.ModeCharDevice)
if err != nil {
if os.IsPermission(err) && !k.IsRoot() {
return nil, errors.New("permission denied. run with root permission or use a user with access to " + devPath)
}
return nil, err
}
k.fd = fd
return k, err
return k, nil
}

// FindKeyboardDevice by going through each device registered on OS
Expand Down
24 changes: 24 additions & 0 deletions keylogger_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package keylogger

import (
"os"
"testing"
)

Expand Down Expand Up @@ -38,3 +39,26 @@ func TestBufferParser(t *testing.T) {
return
}
}

func TestWithPermission(t *testing.T) {
fd, err := os.CreateTemp("", "*")
if err != nil {
t.Fatal(err)
}
// try to create new keylogger with file descriptor which has the permission
k, err := New(fd.Name())
if err != nil {
t.Fatal(err)
}
k.Close()
fd.Close()

// try to create new keylogger with file descriptor which has no permission
_, err = New("/dev/tty0")
if err == nil {
t.Fatal("expected error, got nil")
}
if err.Error() != "permission denied. run with root permission or use a user with access to /dev/tty0" {
t.Fatalf("unexpected error: %v", err)
}
}

0 comments on commit 01e950c

Please sign in to comment.