ble_recon.go 7.0 KB

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