Skip to content

Commit

Permalink
new: implemented ble.recon (ref bettercap#74)
Browse files Browse the repository at this point in the history
  • Loading branch information
evilsocket committed Feb 26, 2018
1 parent 5366140 commit 7fe6cd2
Show file tree
Hide file tree
Showing 10 changed files with 443 additions and 2 deletions.
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func main() {
sess.Register(modules.NewRestAPI(sess))
sess.Register(modules.NewWOL(sess))
sess.Register(modules.NewWiFiRecon(sess))
sess.Register(modules.NewBLERecon(sess))
sess.Register(modules.NewSynScanner(sess))

if err = sess.Start(); err != nil {
Expand Down
11 changes: 11 additions & 0 deletions modules/ble_options_darwin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package modules

import "github.com/bettercap/gatt"

var defaultBLEClientOptions = []gatt.Option{
gatt.MacDeviceRole(gatt.CentralManager),
}

var defaultBLEServerOptions = []gatt.Option{
gatt.MacDeviceRole(gatt.PeripheralManager),
}
21 changes: 21 additions & 0 deletions modules/ble_options_linux.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package modules

import (
"github.com/bettercap/gatt"
"github.com/bettercap/gatt/linux/cmd"
)

var defaultBLEClientOptions = []gatt.Option{
gatt.LnxMaxConnections(1),
gatt.LnxDeviceID(-1, true),
}

var defaultBLEServerOptions = []gatt.Option{
gatt.LnxMaxConnections(1),
gatt.LnxDeviceID(-1, true),
gatt.LnxSetAdvertisingParameters(&cmd.LESetAdvertisingParameters{
AdvertisingIntervalMin: 0x00f4,
AdvertisingIntervalMax: 0x00f4,
AdvertisingChannelMap: 0x7,
}),
}
220 changes: 220 additions & 0 deletions modules/ble_recon.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
package modules

import (
"fmt"
"io/ioutil"
golog "log"
"os"
"sort"
"strings"
"time"

"github.com/bettercap/bettercap/core"
"github.com/bettercap/bettercap/log"
"github.com/bettercap/bettercap/network"
"github.com/bettercap/bettercap/session"

"github.com/bettercap/gatt"

"github.com/olekukonko/tablewriter"
)

var (
bleAliveInterval = time.Duration(5) * time.Second
blePresentInterval = time.Duration(30) * time.Second
)

type BLERecon struct {
session.SessionModule
gattDevice gatt.Device
quit chan bool
}

func NewBLERecon(s *session.Session) *BLERecon {
d := &BLERecon{
SessionModule: session.NewSessionModule("ble.recon", s),
gattDevice: nil,
quit: make(chan bool),
}

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()
}))

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 <[email protected]>"
}

func (d *BLERecon) Configure() (err error) {
// hey Paypal GATT library, could you please just STFU?!
golog.SetOutput(ioutil.Discard)

if d.gattDevice, err = gatt.NewDevice(defaultBLEClientOptions...); err != nil {
return err
}
return nil
}

func (d *BLERecon) onStateChanged(dev gatt.Device, s gatt.State) {
switch s {
case gatt.StatePoweredOn:
log.Info("Starting BLE discovery ...")
dev.Scan([]gatt.UUID{}, true)
return
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) 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) Start() error {
if d.Running() {
return session.ErrAlreadyStarted
} else if err := d.Configure(); err != nil {
return err
}

return d.SetRunning(true, func() {
log.Debug("Initializing BLE device ...")

d.gattDevice.Handle(gatt.PeripheralDiscovered(d.onPeriphDiscovered))
d.gattDevice.Init(d.onStateChanged)

go d.pruner()

<-d.quit

log.Info("Stopping BLE scan ...")

d.gattDevice.StopScanning()
})
}

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 = core.Bold(lastSeen)
} else if sinceSeen > blePresentInterval {
lastSeen = core.Dim(lastSeen)
address = core.Dim(address)
}

flags := make([]string, 0)
raw := uint8(0)
if len(dev.Advertisement.Flags) > 0 {
raw = uint8(dev.Advertisement.Flags[0])
}

bits := map[uint]string{
0: "LE Limited Discoverable",
1: "LE General Discoverable",
2: "BR/EDR",
3: "LE + BR/EDR Controller Mode",
4: "LE + BR/EDR Host Mode",
}

for bit, desc := range bits {
if raw&(1<<bit) != 0 {
flags = append(flags, desc)
}
}

sort.Strings(flags)

isConnectable := core.Red("✕")
if dev.Advertisement.Connectable == true {
isConnectable = core.Green("✓")
}

return []string{
fmt.Sprintf("%d dBm", dev.RSSI),
address,
dev.Device.Name(),
vendor,
strings.Join(flags, ", "),
isConnectable,
lastSeen,
}
}

func (d *BLERecon) showTable(header []string, rows [][]string) {
fmt.Println()
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(header)
table.SetColWidth(80)
table.AppendBulk(rows)
table.Render()
}

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", "Flags", "Connectable", "Last Seen"}

if nrows > 0 {
d.showTable(columns, rows)
}

d.Session.Refresh()
return nil
}

func (d *BLERecon) Stop() error {
return d.SetRunning(false, func() {
d.quit <- true
})
}
13 changes: 13 additions & 0 deletions modules/ble_recon_sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package modules

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
}
48 changes: 47 additions & 1 deletion modules/events_view.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,50 @@ func (s EventsStream) viewSnifferEvent(e session.Event) {
misc)
}

func (s EventsStream) viewBLEEvent(e session.Event) {
if e.Tag == "ble.device.new" {
dev := e.Data.(*network.BLEDevice)
name := dev.Device.Name()
if name != "" {
name = " " + core.Bold(name)
}
vend := dev.Vendor
if vend != "" {
vend = fmt.Sprintf(" (%s)", core.Yellow(vend))
}

fmt.Printf("[%s] [%s] New BLE device%s detected as %s%s %s.\n",
e.Time.Format(eventTimeFormat),
core.Green(e.Tag),
name,
dev.Device.ID(),
vend,
core.Dim(fmt.Sprintf("%d dBm", dev.RSSI)))
} else if e.Tag == "ble.device.lost" {
dev := e.Data.(*network.BLEDevice)
name := dev.Device.Name()
if name != "" {
name = " " + core.Bold(name)
}
vend := dev.Vendor
if vend != "" {
vend = fmt.Sprintf(" (%s)", core.Yellow(vend))
}

fmt.Printf("[%s] [%s] BLE device%s %s%s lost.\n",
e.Time.Format(eventTimeFormat),
core.Green(e.Tag),
name,
dev.Device.ID(),
vend)
} else {
fmt.Printf("[%s] [%s] %v\n",
e.Time.Format(eventTimeFormat),
core.Green(e.Tag),
e.Data)
}
}

func (s EventsStream) viewSynScanEvent(e session.Event) {
se := e.Data.(SynScanEvent)
fmt.Printf("[%s] [%s] Found open port %d for %s\n",
Expand All @@ -155,11 +199,13 @@ func (s *EventsStream) View(e session.Event, refresh bool) {
s.viewEndpointEvent(e)
} else if strings.HasPrefix(e.Tag, "wifi.") {
s.viewWiFiEvent(e)
} else if strings.HasPrefix(e.Tag, "ble.") {
s.viewBLEEvent(e)
} else if strings.HasPrefix(e.Tag, "mod.") {
s.viewModuleEvent(e)
} else if strings.HasPrefix(e.Tag, "net.sniff.") {
s.viewSnifferEvent(e)
} else if strings.HasPrefix(e.Tag, "syn.scan") {
} else if strings.HasPrefix(e.Tag, "syn.scan.") {
s.viewSynScanEvent(e)
} else {
fmt.Printf("[%s] [%s] %v\n", e.Time.Format(eventTimeFormat), core.Green(e.Tag), e)
Expand Down
Loading

0 comments on commit 7fe6cd2

Please sign in to comment.