/
keylogger.go
104 lines (88 loc) · 2.29 KB
/
keylogger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package loggers
import (
"bytes"
"errors"
"fmt"
"os/exec"
"time"
gologme "github.com/erasche/gologme/types"
)
type KeyLogger struct {
X11DeviceID string
Cmd *exec.Cmd
ProcBytes *bytes.Buffer
SharedBuf *bytes.Buffer
}
func (logger *KeyLogger) Setup() {
logger.ProcBytes = &bytes.Buffer{}
logger.SharedBuf = &bytes.Buffer{}
logger.Cmd = exec.Command("xinput", "test", logger.X11DeviceID)
logger.Cmd.Stdout = logger.ProcBytes
go func() {
// Start command asynchronously
_ = logger.Cmd.Start()
// Only proceed once the process has finished
logger.Cmd.Wait()
}()
}
func NewKeyLogger(conf map[string]string) (LogGenerator, error) {
var devId string
fmt.Println(conf)
v, x := conf["X11_DEVICE_ID"]
fmt.Println("%s %s", v, x)
fmt.Println(conf)
if val, ok := conf["X11_DEVICE_ID"]; ok {
devId = val
} else {
return &KeyLogger{}, errors.New("X11_DEVICE_ID is required for the key logger")
}
return &KeyLogger{
X11DeviceID: devId,
}, nil
}
func (logger *KeyLogger) GetFreshestTxtLogs() *gologme.WindowLogs {
// not implemented
return nil
}
func (logger *KeyLogger) GetFreshestNumLogs() *gologme.KeyLogs {
// Find the current length
expectedBytes := len(logger.ProcBytes.Bytes())
// Extract those bytes into a new byte array
newBytes := logger.ProcBytes.Next(expectedBytes)
// And write those to our "sharedBuf" -- sharedBuf now
// contains all the latest keylogs
n, err := logger.SharedBuf.Write(newBytes)
// Handle posisble errors
if n != expectedBytes {
fmt.Printf("Unexpected bytes copied %s vs %s\n", expectedBytes, n)
}
if err != nil {
fmt.Print(err)
}
// Number of pressed keys
keyCount := 0
// Here we copy data from the latest procBytes into sharedBuf
// and attempt to process it.
for {
// Read as much data as possible
line, err := logger.SharedBuf.ReadBytes(10)
// If we hit EOF before '\n', then we get a non-nil error
if err != nil {
// So we write back the remaining data to be recylced
// into the next run
logger.SharedBuf.Write(line)
break
}
// Now we have a line of data (and there's a '\n' after
// it), we must
if bytes.Contains(line, []byte("key press")) {
keyCount++
}
}
// We're done processing recent data, so we need to send back
// a message
return &gologme.KeyLogs{
Time: time.Now(),
Count: keyCount,
}
}