Debian Codegraph @

modules/hid/build_microsoft.go

raw symbols SCIP
1 package hid
2
3 import (
4 "fmt"
5
6 "github.com/bettercap/bettercap/network"
7 )
8
9 type MicrosoftBuilder struct {
10 seqn uint16
11 }
12
13 func (b MicrosoftBuilder) frameFor(template []byte, cmd *Command) []byte {
14 data := make([]byte, len(template))
15 copy(data, template)
16
17 data[4] = byte(b.seqn & 0xff)
18 data[5] = byte((b.seqn >> 8) & 0xff)
19 data[7] = cmd.Mode
20 data[9] = cmd.HID
21 // MS checksum algorithm - as per KeyKeriki paper
22 sum := byte(0)
23 last := len(data) - 1
24 for i := 0; i < last; i++ {
25 sum ^= data[i]
26 }
27 sum = ^sum & 0xff
28 data[last] = sum
29
30 b.seqn++
31
32 return data
33 }
34
35 func (b MicrosoftBuilder) BuildFrames(dev *network.HIDDevice, commands []*Command) error {
36 if dev == nil {
37 return fmt.Errorf("the microsoft frame injection requires the device to be visible")
38 }
39
40 tpl := ([]byte)(nil)
41 dev.EachPayload(func(p []byte) bool {
42 if len(p) == 19 {
43 tpl = p
44 return true
45 }
46 return false
47 })
48
49 if tpl == nil {
50 return fmt.Errorf("at least one packet of 19 bytes needed to hijack microsoft devices, try to hid.sniff the device first")
51 }
52
53 last := len(commands) - 1
54 for i, cmd := range commands {
55 next := (*Command)(nil)
56 if i < last {
57 next = commands[i+1]
58 }
59
60 if cmd.IsHID() {
61 cmd.AddFrame(b.frameFor(tpl, cmd), 5)
62 if next == nil || cmd.HID == next.HID || next.IsSleep() {
63 cmd.AddFrame(b.frameFor(tpl, &Command{}), 0)
64 }
65 } else if cmd.IsSleep() {
66 for i, num := 0, cmd.Sleep/10; i < num; i++ {
67 cmd.AddFrame(b.frameFor(tpl, &Command{}), 0)
68 }
69 }
70 }
71
72 return nil
73 }