Refactoring modules

This commit is contained in:
Giuseppe Trotta 2019-02-10 23:58:08 +01:00
commit ed652622e2
89 changed files with 186 additions and 138 deletions

View file

@ -0,0 +1,25 @@
package ble
import (
"github.com/bettercap/gatt"
// "github.com/bettercap/gatt/linux/cmd"
)
var defaultBLEClientOptions = []gatt.Option{
gatt.LnxMaxConnections(255),
gatt.LnxDeviceID(-1, true),
}
/*
var defaultBLEServerOptions = []gatt.Option{
gatt.LnxMaxConnections(255),
gatt.LnxDeviceID(-1, true),
gatt.LnxSetAdvertisingParameters(&cmd.LESetAdvertisingParameters{
AdvertisingIntervalMin: 0x00f4,
AdvertisingIntervalMax: 0x00f4,
AdvertisingChannelMap: 0x7,
}),
}
*/

209
modules/ble/ble_recon.go Normal file
View file

@ -0,0 +1,209 @@
// +build !windows
// +build !darwin
package ble
import (
"encoding/hex"
"fmt"
"io/ioutil"
golog "log"
"time"
"github.com/bettercap/bettercap/log"
"github.com/bettercap/bettercap/network"
"github.com/bettercap/bettercap/session"
"github.com/bettercap/gatt"
)
type BLERecon struct {
session.SessionModule
gattDevice gatt.Device
currDevice *network.BLEDevice
writeUUID *gatt.UUID
writeData []byte
connected bool
connTimeout time.Duration
quit chan bool
done chan bool
}
func NewBLERecon(s *session.Session) *BLERecon {
d := &BLERecon{
SessionModule: session.NewSessionModule("ble.recon", s),
gattDevice: nil,
quit: make(chan bool),
done: make(chan bool),
connTimeout: time.Duration(10) * time.Second,
currDevice: nil,
connected: false,
}
d.AddHandler(session.NewModuleHandler("ble.recon on", "",
"Start Bluetooth Low Energy devices discovery.",
func(args []string) error {
return d.Start()
}))
d.AddHandler(session.NewModuleHandler("ble.recon off", "",
"Stop Bluetooth Low Energy devices discovery.",
func(args []string) error {
return d.Stop()
}))
d.AddHandler(session.NewModuleHandler("ble.show", "",
"Show discovered Bluetooth Low Energy devices.",
func(args []string) error {
return d.Show()
}))
d.AddHandler(session.NewModuleHandler("ble.enum MAC", "ble.enum "+network.BLEMacValidator,
"Enumerate services and characteristics for the given BLE device.",
func(args []string) error {
if d.isEnumerating() {
return fmt.Errorf("An enumeration for %s is already running, please wait.", d.currDevice.Device.ID())
}
d.writeData = nil
d.writeUUID = nil
return d.enumAllTheThings(network.NormalizeMac(args[0]))
}))
d.AddHandler(session.NewModuleHandler("ble.write MAC UUID HEX_DATA", "ble.write "+network.BLEMacValidator+" ([a-fA-F0-9]+) ([a-fA-F0-9]+)",
"Write the HEX_DATA buffer to the BLE device with the specified MAC address, to the characteristics with the given UUID.",
func(args []string) error {
mac := network.NormalizeMac(args[0])
uuid, err := gatt.ParseUUID(args[1])
if err != nil {
return fmt.Errorf("Error parsing %s: %s", args[1], err)
}
data, err := hex.DecodeString(args[2])
if err != nil {
return fmt.Errorf("Error parsing %s: %s", args[2], err)
}
return d.writeBuffer(mac, uuid, data)
}))
return d
}
func (d BLERecon) Name() string {
return "ble.recon"
}
func (d BLERecon) Description() string {
return "Bluetooth Low Energy devices discovery."
}
func (d BLERecon) Author() string {
return "Simone Margaritelli <evilsocket@protonmail.com>"
}
func (d *BLERecon) isEnumerating() bool {
return d.currDevice != nil
}
func (d *BLERecon) Configure() (err error) {
if d.Running() {
return session.ErrAlreadyStarted
} else if d.gattDevice == nil {
log.Info("Initializing BLE device ...")
// hey Paypal GATT library, could you please just STFU?!
golog.SetOutput(ioutil.Discard)
if d.gattDevice, err = gatt.NewDevice(defaultBLEClientOptions...); err != nil {
return err
}
d.gattDevice.Handle(
gatt.PeripheralDiscovered(d.onPeriphDiscovered),
gatt.PeripheralConnected(d.onPeriphConnected),
gatt.PeripheralDisconnected(d.onPeriphDisconnected),
)
d.gattDevice.Init(d.onStateChanged)
}
return nil
}
func (d *BLERecon) Start() error {
if err := d.Configure(); err != nil {
return err
}
return d.SetRunning(true, func() {
go d.pruner()
<-d.quit
log.Info("Stopping BLE scan ...")
d.gattDevice.StopScanning()
d.done <- true
})
}
func (d *BLERecon) Stop() error {
return d.SetRunning(false, func() {
d.quit <- true
<-d.done
})
}
func (d *BLERecon) pruner() {
log.Debug("Started BLE devices pruner ...")
for d.Running() {
for _, dev := range d.Session.BLE.Devices() {
if time.Since(dev.LastSeen) > blePresentInterval {
d.Session.BLE.Remove(dev.Device.ID())
}
}
time.Sleep(5 * time.Second)
}
}
func (d *BLERecon) setCurrentDevice(dev *network.BLEDevice) {
d.connected = false
d.currDevice = dev
}
func (d *BLERecon) writeBuffer(mac string, uuid gatt.UUID, data []byte) error {
d.writeUUID = &uuid
d.writeData = data
return d.enumAllTheThings(mac)
}
func (d *BLERecon) enumAllTheThings(mac string) error {
dev, found := d.Session.BLE.Get(mac)
if !found || dev == nil {
return fmt.Errorf("BLE device with address %s not found.", mac)
} else if d.Running() {
d.gattDevice.StopScanning()
}
d.setCurrentDevice(dev)
if err := d.Configure(); err != nil && err != session.ErrAlreadyStarted {
return err
}
log.Info("Connecting to %s ...", mac)
go func() {
time.Sleep(d.connTimeout)
if d.isEnumerating() && !d.connected {
d.Session.Events.Add("ble.connection.timeout", d.currDevice)
d.onPeriphDisconnected(nil, nil)
}
}()
d.gattDevice.Connect(dev.Device)
return nil
}

View file

@ -0,0 +1,73 @@
// +build !windows
// +build !darwin
package ble
import (
"github.com/bettercap/bettercap/log"
"github.com/bettercap/gatt"
)
func (d *BLERecon) onStateChanged(dev gatt.Device, s gatt.State) {
log.Info("BLE state changed to %v", s)
switch s {
case gatt.StatePoweredOn:
if d.currDevice == nil {
log.Info("Starting BLE discovery ...")
dev.Scan([]gatt.UUID{}, true)
}
case gatt.StatePoweredOff:
d.gattDevice = nil
default:
log.Warning("Unexpected BLE state: %v", s)
}
}
func (d *BLERecon) onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int) {
d.Session.BLE.AddIfNew(p.ID(), p, a, rssi)
}
func (d *BLERecon) onPeriphDisconnected(p gatt.Peripheral, err error) {
if d.Running() {
// restore scanning
log.Info("Device disconnected, restoring BLE discovery.")
d.setCurrentDevice(nil)
d.gattDevice.Scan([]gatt.UUID{}, true)
}
}
func (d *BLERecon) onPeriphConnected(p gatt.Peripheral, err error) {
if err != nil {
log.Warning("Connected to %s but with error: %s", p.ID(), err)
return
} else if d.currDevice == nil {
// timed out
log.Warning("Connected to %s but after the timeout :(", p.ID())
return
}
d.connected = true
defer func(per gatt.Peripheral) {
log.Info("Disconnecting from %s ...", per.ID())
per.Device().CancelConnection(per)
}(p)
d.Session.Events.Add("ble.device.connected", d.currDevice)
if err := p.SetMTU(500); err != nil {
log.Warning("Failed to set MTU: %s", err)
}
log.Info("Connected, enumerating all the things for %s!", p.ID())
services, err := p.DiscoverServices(nil)
if err != nil {
log.Error("Error discovering services: %s", err)
return
}
d.showServices(p, services)
}

View file

@ -0,0 +1,16 @@
// +build !windows
// +build !darwin
package ble
import (
"github.com/bettercap/bettercap/network"
)
type ByBLERSSISorter []*network.BLEDevice
func (a ByBLERSSISorter) Len() int { return len(a) }
func (a ByBLERSSISorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByBLERSSISorter) Less(i, j int) bool {
return a[i].RSSI > a[j].RSSI
}

View file

@ -0,0 +1,213 @@
// +build !windows
// +build !darwin
package ble
import (
"fmt"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/bettercap/bettercap/log"
"github.com/bettercap/bettercap/network"
"github.com/bettercap/gatt"
"github.com/evilsocket/islazy/tui"
)
var (
bleAliveInterval = time.Duration(5) * time.Second
blePresentInterval = time.Duration(30) * time.Second
)
func (d *BLERecon) getRow(dev *network.BLEDevice) []string {
address := network.NormalizeMac(dev.Device.ID())
vendor := dev.Vendor
sinceSeen := time.Since(dev.LastSeen)
lastSeen := dev.LastSeen.Format("15:04:05")
if sinceSeen <= bleAliveInterval {
lastSeen = tui.Bold(lastSeen)
} else if sinceSeen > blePresentInterval {
lastSeen = tui.Dim(lastSeen)
address = tui.Dim(address)
}
isConnectable := tui.Red("no")
if dev.Advertisement.Connectable {
isConnectable = tui.Green("yes")
}
return []string{
fmt.Sprintf("%d dBm", dev.RSSI),
address,
dev.Device.Name(),
vendor,
isConnectable,
lastSeen,
}
}
func (d *BLERecon) Show() error {
devices := d.Session.BLE.Devices()
sort.Sort(ByBLERSSISorter(devices))
rows := make([][]string, 0)
for _, dev := range devices {
rows = append(rows, d.getRow(dev))
}
nrows := len(rows)
columns := []string{"RSSI", "Address", "Name", "Vendor", "Connectable", "Last Seen"}
if nrows > 0 {
tui.Table(os.Stdout, columns, rows)
}
d.Session.Refresh()
return nil
}
func parseProperties(ch *gatt.Characteristic) (props []string, isReadable bool, isWritable bool, withResponse bool) {
isReadable = false
isWritable = false
withResponse = false
props = make([]string, 0)
mask := ch.Properties()
if (mask & gatt.CharBroadcast) != 0 {
props = append(props, "bcast")
}
if (mask & gatt.CharRead) != 0 {
isReadable = true
props = append(props, "read")
}
if (mask&gatt.CharWriteNR) != 0 || (mask&gatt.CharWrite) != 0 {
props = append(props, tui.Bold("write"))
isWritable = true
withResponse = (mask & gatt.CharWriteNR) == 0
}
if (mask & gatt.CharNotify) != 0 {
props = append(props, "notify")
}
if (mask & gatt.CharIndicate) != 0 {
props = append(props, "indicate")
}
if (mask & gatt.CharSignedWrite) != 0 {
props = append(props, tui.Yellow("*write"))
isWritable = true
withResponse = true
}
if (mask & gatt.CharExtended) != 0 {
props = append(props, "x")
}
return
}
func parseRawData(raw []byte) string {
s := ""
for _, b := range raw {
if b != 00 && !strconv.IsPrint(rune(b)) {
return fmt.Sprintf("%x", raw)
} else if b == 0 {
break
} else {
s += fmt.Sprintf("%c", b)
}
}
return tui.Yellow(s)
}
func (d *BLERecon) showServices(p gatt.Peripheral, services []*gatt.Service) {
columns := []string{"Handles", "Service > Characteristics", "Properties", "Data"}
rows := make([][]string, 0)
wantsToWrite := d.writeUUID != nil
foundToWrite := false
for _, svc := range services {
d.Session.Events.Add("ble.device.service.discovered", svc)
name := svc.Name()
if name == "" {
name = svc.UUID().String()
} else {
name = fmt.Sprintf("%s (%s)", tui.Green(name), tui.Dim(svc.UUID().String()))
}
row := []string{
fmt.Sprintf("%04x -> %04x", svc.Handle(), svc.EndHandle()),
name,
"",
"",
}
rows = append(rows, row)
chars, err := p.DiscoverCharacteristics(nil, svc)
if err != nil {
log.Error("Error while enumerating chars for service %s: %s", svc.UUID(), err)
continue
}
for _, ch := range chars {
d.Session.Events.Add("ble.device.characteristic.discovered", ch)
name = ch.Name()
if name == "" {
name = " " + ch.UUID().String()
} else {
name = fmt.Sprintf(" %s (%s)", tui.Green(name), tui.Dim(ch.UUID().String()))
}
props, isReadable, isWritable, withResponse := parseProperties(ch)
if wantsToWrite && d.writeUUID.Equal(ch.UUID()) {
foundToWrite = true
if isWritable {
log.Info("Writing %d bytes to characteristics %s ...", len(d.writeData), d.writeUUID)
} else {
log.Warning("Attempt to write %d bytes to non writable characteristics %s ...", len(d.writeData), d.writeUUID)
}
err := p.WriteCharacteristic(ch, d.writeData, !withResponse)
if err != nil {
log.Error("Error while writing: %s", err)
}
}
data := ""
if isReadable {
raw, err := p.ReadCharacteristic(ch)
if err != nil {
data = tui.Red(err.Error())
} else {
data = parseRawData(raw)
}
}
row := []string{
fmt.Sprintf("%04x", ch.Handle()),
name,
strings.Join(props, ", "),
data,
}
rows = append(rows, row)
}
}
if wantsToWrite && !foundToWrite {
log.Error("Writable characteristics %s not found.", d.writeUUID)
} else {
tui.Table(os.Stdout, columns, rows)
d.Session.Refresh()
}
}

View file

@ -0,0 +1,66 @@
// +build windows darwin
package ble
import (
"github.com/bettercap/bettercap/session"
)
type BLERecon struct {
session.SessionModule
}
/*
// darwin
var defaultBLEClientOptions = []gatt.Option{
gatt.MacDeviceRole(gatt.CentralManager),
}
var defaultBLEServerOptions = []gatt.Option{
gatt.MacDeviceRole(gatt.PeripheralManager),
}
*/
func NewBLERecon(s *session.Session) *BLERecon {
d := &BLERecon{
SessionModule: session.NewSessionModule("ble.recon", s),
}
d.AddHandler(session.NewModuleHandler("ble.recon on", "",
"Start Bluetooth Low Energy devices discovery.",
func(args []string) error {
return session.ErrNotSupported
}))
d.AddHandler(session.NewModuleHandler("ble.recon off", "",
"Stop Bluetooth Low Energy devices discovery.",
func(args []string) error {
return session.ErrNotSupported
}))
return d
}
func (d BLERecon) Name() string {
return "ble.recon"
}
func (d BLERecon) Description() string {
return "Bluetooth Low Energy devices discovery."
}
func (d BLERecon) Author() string {
return "Simone Margaritelli <evilsocket@protonmail.com>"
}
func (d *BLERecon) Configure() (err error) {
return session.ErrNotSupported
}
func (d *BLERecon) Start() error {
return session.ErrNotSupported
}
func (d *BLERecon) Stop() error {
return session.ErrNotSupported
}