| 1 | // +build !windows |
| 2 | |
| 3 | package ble |
| 4 | |
| 5 | import ( |
| 6 | "encoding/hex" |
| 7 | "fmt" |
| 8 | golog "log" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/bettercap/bettercap/modules/utils" |
| 12 | "github.com/bettercap/bettercap/network" |
| 13 | "github.com/bettercap/bettercap/session" |
| 14 | |
| 15 | "github.com/bettercap/gatt" |
| 16 | |
| 17 | "github.com/evilsocket/islazy/str" |
| 18 | ) |
| 19 | |
| 20 | type BLERecon struct { |
| 21 | session.SessionModule |
| 22 | deviceId int |
| 23 | gattDevice gatt.Device |
| 24 | currDevice *network.BLEDevice |
| 25 | writeUUID *gatt.UUID |
| 26 | writeData []byte |
| 27 | connected bool |
| 28 | connTimeout int |
| 29 | devTTL int |
| 30 | quit chan bool |
| 31 | done chan bool |
| 32 | selector *utils.ViewSelector |
| 33 | } |
| 34 | |
| 35 | func NewBLERecon(s *session.Session) *BLERecon { |
| 36 | mod := &BLERecon{ |
| 37 | SessionModule: session.NewSessionModule("ble.recon", s), |
| 38 | deviceId: -1, |
| 39 | gattDevice: nil, |
| 40 | quit: make(chan bool), |
| 41 | done: make(chan bool), |
| 42 | connTimeout: 5, |
| 43 | devTTL: 30, |
| 44 | currDevice: nil, |
| 45 | connected: false, |
| 46 | } |
| 47 | |
| 48 | mod.InitState("scanning") |
| 49 | |
| 50 | mod.selector = utils.ViewSelectorFor(&mod.SessionModule, |
| 51 | "ble.show", |
| 52 | []string{"rssi", "mac", "seen"}, "rssi asc") |
| 53 | |
| 54 | mod.AddHandler(session.NewModuleHandler("ble.recon on", "", |
| 55 | "Start Bluetooth Low Energy devices discovery.", |
| 56 | func(args []string) error { |
| 57 | return mod.Start() |
| 58 | })) |
| 59 | |
| 60 | mod.AddHandler(session.NewModuleHandler("ble.recon off", "", |
| 61 | "Stop Bluetooth Low Energy devices discovery.", |
| 62 | func(args []string) error { |
| 63 | return mod.Stop() |
| 64 | })) |
| 65 | |
| 66 | mod.AddHandler(session.NewModuleHandler("ble.clear", "", |
| 67 | "Clear all devices collected by the BLE discovery module.", |
| 68 | func(args []string) error { |
| 69 | mod.Session.BLE.Clear() |
| 70 | return nil |
| 71 | })) |
| 72 | |
| 73 | mod.AddHandler(session.NewModuleHandler("ble.show", "", |
| 74 | "Show discovered Bluetooth Low Energy devices.", |
| 75 | func(args []string) error { |
| 76 | return mod.Show() |
| 77 | })) |
| 78 | |
| 79 | enum := session.NewModuleHandler("ble.enum MAC", "ble.enum "+network.BLEMacValidator, |
| 80 | "Enumerate services and characteristics for the given BLE device.", |
| 81 | func(args []string) error { |
| 82 | if mod.isEnumerating() { |
| 83 | return fmt.Errorf("An enumeration for %s is already running, please wait.", mod.currDevice.Device.ID()) |
| 84 | } |
| 85 | |
| 86 | mod.writeData = nil |
| 87 | mod.writeUUID = nil |
| 88 | |
| 89 | return mod.enumAllTheThings(network.NormalizeMac(args[0])) |
| 90 | }) |
| 91 | |
| 92 | enum.Complete("ble.enum", s.BLECompleter) |
| 93 | |
| 94 | mod.AddHandler(enum) |
| 95 | |
| 96 | write := session.NewModuleHandler("ble.write MAC UUID HEX_DATA", "ble.write "+network.BLEMacValidator+" ([a-fA-F0-9]+) ([a-fA-F0-9]+)", |
| 97 | "Write the HEX_DATA buffer to the BLE device with the specified MAC address, to the characteristics with the given UUID.", |
| 98 | func(args []string) error { |
| 99 | mac := network.NormalizeMac(args[0]) |
| 100 | uuid, err := gatt.ParseUUID(args[1]) |
| 101 | if err != nil { |
| 102 | return fmt.Errorf("Error parsing %s: %s", args[1], err) |
| 103 | } |
| 104 | data, err := hex.DecodeString(args[2]) |
| 105 | if err != nil { |
| 106 | return fmt.Errorf("Error parsing %s: %s", args[2], err) |
| 107 | } |
| 108 | |
| 109 | return mod.writeBuffer(mac, uuid, data) |
| 110 | }) |
| 111 | |
| 112 | write.Complete("ble.write", s.BLECompleter) |
| 113 | |
| 114 | mod.AddHandler(write) |
| 115 | |
| 116 | mod.AddParam(session.NewIntParameter("ble.device", |
| 117 | fmt.Sprintf("%d", mod.deviceId), |
| 118 | "Index of the HCI device to use, -1 to autodetect.")) |
| 119 | |
| 120 | mod.AddParam(session.NewIntParameter("ble.timeout", |
| 121 | fmt.Sprintf("%d", mod.connTimeout), |
| 122 | "Connection timeout in seconds.")) |
| 123 | |
| 124 | mod.AddParam(session.NewIntParameter("ble.ttl", |
| 125 | fmt.Sprintf("%d", mod.devTTL), |
| 126 | "Seconds of inactivity for a device to be pruned.")) |
| 127 | |
| 128 | return mod |
| 129 | } |
| 130 | |
| 131 | func (mod BLERecon) Name() string { |
| 132 | return "ble.recon" |
| 133 | } |
| 134 | |
| 135 | func (mod BLERecon) Description() string { |
| 136 | return "Bluetooth Low Energy devices discovery." |
| 137 | } |
| 138 | |
| 139 | func (mod BLERecon) Author() string { |
| 140 | return "Simone Margaritelli <[email protected]>" |
| 141 | } |
| 142 | |
| 143 | func (mod *BLERecon) isEnumerating() bool { |
| 144 | return mod.currDevice != nil |
| 145 | } |
| 146 | |
| 147 | type dummyWriter struct { |
| 148 | mod *BLERecon |
| 149 | } |
| 150 | |
| 151 | func (w dummyWriter) Write(p []byte) (n int, err error) { |
| 152 | w.mod.Debug("[gatt.log] %s", str.Trim(string(p))) |
| 153 | return len(p), nil |
| 154 | } |
| 155 | |
| 156 | func (mod *BLERecon) Configure() (err error) { |
| 157 | if mod.Running() { |
| 158 | return session.ErrAlreadyStarted(mod.Name()) |
| 159 | } else if mod.gattDevice == nil { |
| 160 | if err, mod.deviceId = mod.IntParam("ble.device"); err != nil { |
| 161 | return err |
| 162 | } |
| 163 | |
| 164 | mod.Debug("initializing device (id:%d) ...", mod.deviceId) |
| 165 | |
| 166 | golog.SetFlags(0) |
| 167 | golog.SetOutput(dummyWriter{mod}) |
| 168 | |
| 169 | if mod.gattDevice, err = gatt.NewDevice(defaultBLEClientOptions...); err != nil { |
| 170 | mod.Debug("error while creating new gatt device: %v", err) |
| 171 | return err |
| 172 | } |
| 173 | |
| 174 | mod.gattDevice.Handle( |
| 175 | gatt.PeripheralDiscovered(mod.onPeriphDiscovered), |
| 176 | gatt.PeripheralConnected(mod.onPeriphConnected), |
| 177 | gatt.PeripheralDisconnected(mod.onPeriphDisconnected), |
| 178 | ) |
| 179 | |
| 180 | mod.gattDevice.Init(mod.onStateChanged) |
| 181 | } |
| 182 | |
| 183 | if err, mod.connTimeout = mod.IntParam("ble.timeout"); err != nil { |
| 184 | return err |
| 185 | } else if err, mod.devTTL = mod.IntParam("ble.ttl"); err != nil { |
| 186 | return err |
| 187 | } |
| 188 | |
| 189 | return nil |
| 190 | } |
| 191 | |
| 192 | func (mod *BLERecon) Start() error { |
| 193 | if err := mod.Configure(); err != nil { |
| 194 | return err |
| 195 | } |
| 196 | |
| 197 | return mod.SetRunning(true, func() { |
| 198 | go mod.pruner() |
| 199 | |
| 200 | <-mod.quit |
| 201 | |
| 202 | if mod.gattDevice != nil { |
| 203 | mod.Info("stopping scan ...") |
| 204 | |
| 205 | if mod.currDevice != nil && mod.currDevice.Device != nil { |
| 206 | mod.Debug("resetting connection with %v", mod.currDevice.Device) |
| 207 | mod.gattDevice.CancelConnection(mod.currDevice.Device) |
| 208 | } |
| 209 | |
| 210 | mod.Debug("stopping device") |
| 211 | if err := mod.gattDevice.Stop(); err != nil { |
| 212 | mod.Warning("error while stopping device: %v", err) |
| 213 | } else { |
| 214 | mod.Debug("gatt device closed") |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | mod.done <- true |
| 219 | }) |
| 220 | } |
| 221 | |
| 222 | func (mod *BLERecon) Stop() error { |
| 223 | return mod.SetRunning(false, func() { |
| 224 | mod.quit <- true |
| 225 | <-mod.done |
| 226 | mod.Debug("module stopped, cleaning state") |
| 227 | mod.gattDevice = nil |
| 228 | mod.setCurrentDevice(nil) |
| 229 | mod.ResetState() |
| 230 | }) |
| 231 | } |
| 232 | |
| 233 | func (mod *BLERecon) pruner() { |
| 234 | blePresentInterval := time.Duration(mod.devTTL) * time.Second |
| 235 | mod.Debug("started devices pruner with ttl %s", blePresentInterval) |
| 236 | |
| 237 | for mod.Running() { |
| 238 | for _, dev := range mod.Session.BLE.Devices() { |
| 239 | if time.Since(dev.LastSeen) > blePresentInterval { |
| 240 | mod.Session.BLE.Remove(dev.Device.ID()) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | time.Sleep(5 * time.Second) |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | func (mod *BLERecon) setCurrentDevice(dev *network.BLEDevice) { |
| 249 | mod.connected = false |
| 250 | mod.currDevice = dev |
| 251 | mod.State.Store("scanning", dev) |
| 252 | } |
| 253 | |
| 254 | func (mod *BLERecon) writeBuffer(mac string, uuid gatt.UUID, data []byte) error { |
| 255 | mod.writeUUID = &uuid |
| 256 | mod.writeData = data |
| 257 | return mod.enumAllTheThings(mac) |
| 258 | } |
| 259 | |
| 260 | func (mod *BLERecon) enumAllTheThings(mac string) error { |
| 261 | dev, found := mod.Session.BLE.Get(mac) |
| 262 | if !found || dev == nil { |
| 263 | return fmt.Errorf("BLE device with address %s not found.", mac) |
| 264 | } else if mod.Running() { |
| 265 | mod.gattDevice.StopScanning() |
| 266 | } |
| 267 | |
| 268 | mod.setCurrentDevice(dev) |
| 269 | if err := mod.Configure(); err != nil && err.Error() != session.ErrAlreadyStarted("ble.recon").Error() { |
| 270 | return err |
| 271 | } |
| 272 | |
| 273 | mod.Info("connecting to %s ...", mac) |
| 274 | |
| 275 | go func() { |
| 276 | time.Sleep(time.Duration(mod.connTimeout) * time.Second) |
| 277 | if mod.isEnumerating() && !mod.connected { |
| 278 | mod.Warning("connection timeout") |
| 279 | mod.Session.Events.Add("ble.connection.timeout", mod.currDevice) |
| 280 | mod.onPeriphDisconnected(nil, nil) |
| 281 | } |
| 282 | }() |
| 283 | |
| 284 | mod.gattDevice.Connect(dev.Device) |
| 285 | |
| 286 | return nil |
| 287 | } |