From 9cd4e380fb6cc25a17a7489d7272123341615c8f Mon Sep 17 00:00:00 2001 From: evilsocket Date: Tue, 12 Feb 2019 15:16:02 +0100 Subject: [PATCH] misc: each module now has its own tagged logging --- modules/any_proxy/any_proxy.go | 7 +-- modules/api_rest/api_rest.go | 17 +++-- modules/api_rest/api_rest_controller.go | 47 +++++++------- modules/api_rest/api_rest_ws.go | 19 +++--- modules/arp_spoof/arp_spoof.go | 41 ++++++------ modules/ble/ble_recon.go | 9 ++- modules/ble/ble_recon_events.go | 22 +++---- modules/ble/ble_recon_view.go | 11 ++-- modules/caplets/caplets.go | 7 +-- modules/dhcp6_spoof/dhcp6_spoof.go | 53 ++++++++-------- modules/discovery/net_recon.go | 3 +- modules/dns_spoof/dns_spoof.go | 21 +++---- modules/events_stream/events_stream.go | 7 +-- modules/events_stream/events_view.go | 2 +- modules/gps/gps.go | 7 +-- modules/http_proxy/http_proxy_base.go | 63 +++++++++++++------ .../http_proxy_base_cookietracker.go | 3 - modules/http_proxy/http_proxy_base_filters.go | 11 ++-- .../http_proxy/http_proxy_base_hosttracker.go | 3 - modules/http_proxy/http_proxy_script.go | 2 +- modules/http_server/http_server.go | 5 +- modules/https_proxy/https_proxy.go | 13 ++-- modules/https_server/https_server.go | 15 +++-- modules/mac_changer/mac_changer.go | 7 +-- modules/mysql_server/mysql_server.go | 35 +++++------ modules/net_sniff/net_sniff.go | 13 ++-- modules/net_sniff/net_sniff_fuzz.go | 13 ++-- .../packet_proxy/packet_proxy_linux_amd64.go | 7 +-- modules/prober/net_probe.go | 9 ++- modules/prober/net_probe_mdns.go | 7 +-- modules/prober/net_probe_nbns.go | 5 +- modules/prober/net_probe_upnp.go | 5 +- modules/prober/net_probe_wsd.go | 5 +- modules/syn_scan/syn_scan.go | 19 +++--- modules/tcp_proxy/tcp_proxy.go | 27 ++++---- modules/tcp_proxy/tcp_proxy_script.go | 8 +-- modules/ticker/ticker.go | 5 +- modules/update/update.go | 7 +-- modules/wifi/wifi.go | 18 +++--- modules/wifi/wifi_ap.go | 5 +- modules/wifi/wifi_assoc.go | 17 +++-- modules/wifi/wifi_deauth.go | 19 +++--- modules/wifi/wifi_hopping.go | 13 ++-- modules/wifi/wifi_recon.go | 26 +++----- modules/wifi/wifi_show.go | 2 +- modules/wol/wol.go | 5 +- session/module.go | 27 ++++++++ 47 files changed, 343 insertions(+), 349 deletions(-) diff --git a/modules/any_proxy/any_proxy.go b/modules/any_proxy/any_proxy.go index 005c12a2..f3bc7ca2 100644 --- a/modules/any_proxy/any_proxy.go +++ b/modules/any_proxy/any_proxy.go @@ -2,7 +2,6 @@ package any_proxy import ( "github.com/bettercap/bettercap/firewall" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" ) @@ -97,7 +96,7 @@ func (p *AnyProxy) Configure() error { } if !p.Session.Firewall.IsForwardingEnabled() { - log.Info("Enabling forwarding.") + p.Info("Enabling forwarding.") p.Session.Firewall.EnableForwarding(true) } @@ -115,7 +114,7 @@ func (p *AnyProxy) Configure() error { return err } - log.Info("Applied redirection %s", p.Redirection.String()) + p.Info("Applied redirection %s", p.Redirection.String()) return nil } @@ -130,7 +129,7 @@ func (p *AnyProxy) Start() error { func (p *AnyProxy) Stop() error { if p.Redirection != nil { - log.Info("Disabling redirection %s", p.Redirection.String()) + p.Info("Disabling redirection %s", p.Redirection.String()) if err := p.Session.Firewall.EnableRedirection(p.Redirection, false); err != nil { return err } diff --git a/modules/api_rest/api_rest.go b/modules/api_rest/api_rest.go index 54b5008b..2325c777 100644 --- a/modules/api_rest/api_rest.go +++ b/modules/api_rest/api_rest.go @@ -6,7 +6,6 @@ import ( "net/http" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/bettercap/bettercap/tls" @@ -157,15 +156,15 @@ func (api *RestAPI) Configure() error { return err } - log.Debug("%+v", cfg) - log.Info("generating TLS key to %s", api.keyFile) - log.Info("generating TLS certificate to %s", api.certFile) + api.Debug("%+v", cfg) + api.Info("generating TLS key to %s", api.keyFile) + api.Info("generating TLS certificate to %s", api.certFile) if err := tls.Generate(cfg, api.certFile, api.keyFile); err != nil { return err } } else { - log.Info("loading TLS key from %s", api.keyFile) - log.Info("loading TLS certificate from %s", api.certFile) + api.Info("loading TLS key from %s", api.keyFile) + api.Info("loading TLS certificate from %s", api.certFile) } } @@ -192,7 +191,7 @@ func (api *RestAPI) Configure() error { api.server.Handler = router if api.username == "" || api.password == "" { - log.Warning("api.rest.username and/or api.rest.password parameters are empty, authentication is disabled.") + api.Warning("api.rest.username and/or api.rest.password parameters are empty, authentication is disabled.") } return nil @@ -207,10 +206,10 @@ func (api *RestAPI) Start() error { var err error if api.isTLS() { - log.Info("api server starting on https://%s", api.server.Addr) + api.Info("api server starting on https://%s", api.server.Addr) err = api.server.ListenAndServeTLS(api.certFile, api.keyFile) } else { - log.Info("api server starting on http://%s", api.server.Addr) + api.Info("api server starting on http://%s", api.server.Addr) err = api.server.ListenAndServe() } diff --git a/modules/api_rest/api_rest_controller.go b/modules/api_rest/api_rest_controller.go index e9e915b1..2148212c 100644 --- a/modules/api_rest/api_rest_controller.go +++ b/modules/api_rest/api_rest_controller.go @@ -7,7 +7,6 @@ import ( "strconv" "strings" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/gorilla/mux" @@ -22,18 +21,18 @@ type APIResponse struct { Message string `json:"msg"` } -func setAuthFailed(w http.ResponseWriter, r *http.Request) { - log.Warning("Unauthorized authentication attempt from %s", r.RemoteAddr) +func (api *RestAPI) setAuthFailed(w http.ResponseWriter, r *http.Request) { + api.Warning("Unauthorized authentication attempt from %s", r.RemoteAddr) w.Header().Set("WWW-Authenticate", `Basic realm="auth"`) w.WriteHeader(401) w.Write([]byte("Unauthorized")) } -func toJSON(w http.ResponseWriter, o interface{}) { +func (api *RestAPI) toJSON(w http.ResponseWriter, o interface{}) { w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(o); err != nil { - log.Error("error while encoding object to JSON: %v", err) + api.Error("error while encoding object to JSON: %v", err) } } @@ -59,7 +58,7 @@ func (api *RestAPI) checkAuth(r *http.Request) bool { } func (api *RestAPI) showSession(w http.ResponseWriter, r *http.Request) { - toJSON(w, session.I) + api.toJSON(w, session.I) } func (api *RestAPI) showBle(w http.ResponseWriter, r *http.Request) { @@ -67,28 +66,28 @@ func (api *RestAPI) showBle(w http.ResponseWriter, r *http.Request) { mac := strings.ToLower(params["mac"]) if mac == "" { - toJSON(w, session.I.BLE) + api.toJSON(w, session.I.BLE) } else if dev, found := session.I.BLE.Get(mac); found { - toJSON(w, dev) + api.toJSON(w, dev) } else { http.Error(w, "Not Found", 404) } } func (api *RestAPI) showEnv(w http.ResponseWriter, r *http.Request) { - toJSON(w, session.I.Env) + api.toJSON(w, session.I.Env) } func (api *RestAPI) showGateway(w http.ResponseWriter, r *http.Request) { - toJSON(w, session.I.Gateway) + api.toJSON(w, session.I.Gateway) } func (api *RestAPI) showInterface(w http.ResponseWriter, r *http.Request) { - toJSON(w, session.I.Interface) + api.toJSON(w, session.I.Interface) } func (api *RestAPI) showModules(w http.ResponseWriter, r *http.Request) { - toJSON(w, session.I.Modules) + api.toJSON(w, session.I.Modules) } func (api *RestAPI) showLan(w http.ResponseWriter, r *http.Request) { @@ -96,24 +95,24 @@ func (api *RestAPI) showLan(w http.ResponseWriter, r *http.Request) { mac := strings.ToLower(params["mac"]) if mac == "" { - toJSON(w, session.I.Lan) + api.toJSON(w, session.I.Lan) } else if host, found := session.I.Lan.Get(mac); found { - toJSON(w, host) + api.toJSON(w, host) } else { http.Error(w, "Not Found", 404) } } func (api *RestAPI) showOptions(w http.ResponseWriter, r *http.Request) { - toJSON(w, session.I.Options) + api.toJSON(w, session.I.Options) } func (api *RestAPI) showPackets(w http.ResponseWriter, r *http.Request) { - toJSON(w, session.I.Queue) + api.toJSON(w, session.I.Queue) } func (api *RestAPI) showStartedAt(w http.ResponseWriter, r *http.Request) { - toJSON(w, session.I.StartedAt) + api.toJSON(w, session.I.StartedAt) } func (api *RestAPI) showWiFi(w http.ResponseWriter, r *http.Request) { @@ -121,11 +120,11 @@ func (api *RestAPI) showWiFi(w http.ResponseWriter, r *http.Request) { mac := strings.ToLower(params["mac"]) if mac == "" { - toJSON(w, session.I.WiFi) + api.toJSON(w, session.I.WiFi) } else if station, found := session.I.WiFi.Get(mac); found { - toJSON(w, station) + api.toJSON(w, station) } else if client, found := session.I.WiFi.GetClient(mac); found { - toJSON(w, client) + api.toJSON(w, client) } else { http.Error(w, "Not Found", 404) } @@ -142,7 +141,7 @@ func (api *RestAPI) runSessionCommand(w http.ResponseWriter, r *http.Request) { } else if err = session.I.Run(cmd.Command); err != nil { http.Error(w, err.Error(), 400) } else { - toJSON(w, APIResponse{Success: true}) + api.toJSON(w, APIResponse{Success: true}) } } @@ -170,7 +169,7 @@ func (api *RestAPI) showEvents(w http.ResponseWriter, r *http.Request) { } } - toJSON(w, events[nevents-n:]) + api.toJSON(w, events[nevents-n:]) } } @@ -182,7 +181,7 @@ func (api *RestAPI) sessionRoute(w http.ResponseWriter, r *http.Request) { api.setSecurityHeaders(w) if !api.checkAuth(r) { - setAuthFailed(w, r) + api.setAuthFailed(w, r) return } else if r.Method == "POST" { api.runSessionCommand(w, r) @@ -239,7 +238,7 @@ func (api *RestAPI) eventsRoute(w http.ResponseWriter, r *http.Request) { api.setSecurityHeaders(w) if !api.checkAuth(r) { - setAuthFailed(w, r) + api.setAuthFailed(w, r) return } diff --git a/modules/api_rest/api_rest_ws.go b/modules/api_rest/api_rest_ws.go index 4d2b00c2..2dfa971c 100644 --- a/modules/api_rest/api_rest_ws.go +++ b/modules/api_rest/api_rest_ws.go @@ -6,7 +6,6 @@ import ( "strings" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/gorilla/websocket" @@ -24,14 +23,14 @@ const ( func (api *RestAPI) streamEvent(ws *websocket.Conn, event session.Event) error { msg, err := json.Marshal(event) if err != nil { - log.Error("Error while creating websocket message: %s", err) + api.Error("Error while creating websocket message: %s", err) return err } ws.SetWriteDeadline(time.Now().Add(writeWait)) if err := ws.WriteMessage(websocket.TextMessage, msg); err != nil { if !strings.Contains(err.Error(), "closed connection") { - log.Error("Error while writing websocket message: %s", err) + api.Error("Error while writing websocket message: %s", err) return err } } @@ -42,7 +41,7 @@ func (api *RestAPI) streamEvent(ws *websocket.Conn, event session.Event) error { func (api *RestAPI) sendPing(ws *websocket.Conn) error { ws.SetWriteDeadline(time.Now().Add(writeWait)) if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil { - log.Error("Error while writing websocket ping message: %s", err) + api.Error("Error while writing websocket ping message: %s", err) return err } return nil @@ -55,7 +54,7 @@ func (api *RestAPI) streamWriter(ws *websocket.Conn, w http.ResponseWriter, r *h events := session.I.Events.Sorted() n := len(events) if n > 0 { - log.Debug("Sending %d events.", n) + api.Debug("Sending %d events.", n) for _, event := range events { if err := api.streamEvent(ws, event); err != nil { return @@ -65,7 +64,7 @@ func (api *RestAPI) streamWriter(ws *websocket.Conn, w http.ResponseWriter, r *h session.I.Events.Clear() - log.Debug("Listening for events and streaming to ws endpoint ...") + api.Debug("Listening for events and streaming to ws endpoint ...") pingTicker := time.NewTicker(pingPeriod) listener := session.I.Events.Listen() @@ -82,7 +81,7 @@ func (api *RestAPI) streamWriter(ws *websocket.Conn, w http.ResponseWriter, r *h return } case <-api.quit: - log.Info("Stopping websocket events streamer ...") + api.Info("Stopping websocket events streamer ...") return } } @@ -96,7 +95,7 @@ func (api *RestAPI) streamReader(ws *websocket.Conn) { for { _, _, err := ws.ReadMessage() if err != nil { - log.Debug("Closing websocket reader.") + api.Debug("Closing websocket reader.") break } } @@ -106,12 +105,12 @@ func (api *RestAPI) startStreamingEvents(w http.ResponseWriter, r *http.Request) ws, err := api.upgrader.Upgrade(w, r, nil) if err != nil { if _, ok := err.(websocket.HandshakeError); !ok { - log.Error("Error while updating api.rest connection to websocket: %s", err) + api.Error("Error while updating api.rest connection to websocket: %s", err) } return } - log.Debug("Websocket streaming started for %s", r.RemoteAddr) + api.Debug("Websocket streaming started for %s", r.RemoteAddr) go api.streamWriter(ws, w, r) api.streamReader(ws) diff --git a/modules/arp_spoof/arp_spoof.go b/modules/arp_spoof/arp_spoof.go index 5eedfe78..d851b4ef 100644 --- a/modules/arp_spoof/arp_spoof.go +++ b/modules/arp_spoof/arp_spoof.go @@ -6,7 +6,6 @@ import ( "sync" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" @@ -110,13 +109,13 @@ func (p *ArpSpoofer) Configure() error { return err } - log.Debug(" addresses=%v macs=%v whitelisted-addresses=%v whitelisted-macs=%v", p.addresses, p.macs, p.wAddresses, p.wMacs) + p.Debug(" addresses=%v macs=%v whitelisted-addresses=%v whitelisted-macs=%v", p.addresses, p.macs, p.wAddresses, p.wMacs) if p.ban { - log.Warning("running in ban mode, forwarding not enabled!") + p.Warning("running in ban mode, forwarding not enabled!") p.Session.Firewall.EnableForwarding(false) } else if !p.Session.Firewall.IsForwardingEnabled() { - log.Info("enabling forwarding") + p.Info("enabling forwarding") p.Session.Firewall.EnableForwarding(true) } @@ -137,13 +136,13 @@ func (p *ArpSpoofer) Start() error { neighbours = list.Expand() nNeigh := len(neighbours) - 2 - log.Warning("arp spoofer started targeting %d possible network neighbours of %d targets.", nNeigh, nTargets) + p.Warning("arp spoofer started targeting %d possible network neighbours of %d targets.", nNeigh, nTargets) } else { - log.Info("arp spoofer started, probing %d targets.", nTargets) + p.Info("arp spoofer started, probing %d targets.", nTargets) } if p.fullDuplex { - log.Warning("full duplex spoofing enabled, if the router has ARP spoofing mechanisms, the attack will fail.") + p.Warning("full duplex spoofing enabled, if the router has ARP spoofing mechanisms, the attack will fail.") } p.waitGroup.Add(1) @@ -166,7 +165,7 @@ func (p *ArpSpoofer) Start() error { func (p *ArpSpoofer) unSpoof() error { nTargets := len(p.addresses) + len(p.macs) - log.Info("restoring ARP cache of %d targets.", nTargets) + p.Info("restoring ARP cache of %d targets.", nTargets) p.arpSpoofTargets(p.Session.Gateway.IP, p.Session.Gateway.HW, false, false) if p.internal { @@ -186,7 +185,7 @@ func (p *ArpSpoofer) unSpoof() error { func (p *ArpSpoofer) Stop() error { return p.SetRunning(false, func() { - log.Info("waiting for ARP spoofer to stop ...") + p.Info("waiting for ARP spoofer to stop ...") p.unSpoof() p.ban = false p.waitGroup.Wait() @@ -215,12 +214,12 @@ func (p *ArpSpoofer) getTargets(probe bool) map[string]net.HardwareAddr { // add targets specified by IP address for _, ip := range p.addresses { if p.Session.Skip(ip) { - log.Debug("skipping IP %s from arp spoofing.", ip) + p.Debug("skipping IP %s from arp spoofing.", ip) continue } // do we have this ip mac address? if hw, err := p.Session.FindMAC(ip, probe); err != nil { - log.Debug("could not find hardware address for %s", ip.String()) + p.Debug("could not find hardware address for %s", ip.String()) } else { targets[ip.String()] = hw } @@ -228,9 +227,9 @@ func (p *ArpSpoofer) getTargets(probe bool) map[string]net.HardwareAddr { // add targets specified by MAC address for _, hw := range p.macs { if ip, err := network.ArpInverseLookup(p.Session.Interface.Name(), hw.String(), false); err != nil { - log.Warning("could not find IP address for %s", hw.String()) + p.Warning("could not find IP address for %s", hw.String()) } else if p.Session.Skip(net.ParseIP(ip)) { - log.Debug("skipping address %s from arp spoofing.", ip) + p.Debug("skipping address %s from arp spoofing.", ip) } else { targets[ip] = hw } @@ -262,7 +261,7 @@ func (p *ArpSpoofer) arpSpoofTargets(saddr net.IP, smac net.HardwareAddr, check_ if check_running && !p.Running() { return } else if p.isWhitelisted(ip, mac) { - log.Debug("%s (%s) is whitelisted, skipping from spoofing loop.", ip, mac) + p.Debug("%s (%s) is whitelisted, skipping from spoofing loop.", ip, mac) continue } else if saddr.String() == ip { continue @@ -270,9 +269,9 @@ func (p *ArpSpoofer) arpSpoofTargets(saddr net.IP, smac net.HardwareAddr, check_ rawIP := net.ParseIP(ip) if err, pkt := packets.NewARPReply(saddr, smac, rawIP, mac); err != nil { - log.Error("error while creating ARP spoof packet for %s: %s", ip, err) + p.Error("error while creating ARP spoof packet for %s: %s", ip, err) } else { - log.Debug("sending %d bytes of ARP packet to %s:%s.", len(pkt), ip, mac.String()) + p.Debug("sending %d bytes of ARP packet to %s:%s.", len(pkt), ip, mac.String()) p.Session.Queue.Send(pkt) } @@ -281,23 +280,23 @@ func (p *ArpSpoofer) arpSpoofTargets(saddr net.IP, smac net.HardwareAddr, check_ gwPacket := []byte(nil) if isSpoofing { - log.Debug("telling the gw we are %s", ip) + p.Debug("telling the gw we are %s", ip) // we told the target we're te gateway, not let's tell the // gateway that we are the target if err, gwPacket = packets.NewARPReply(rawIP, ourHW, gwIP, gwHW); err != nil { - log.Error("error while creating ARP spoof packet: %s", err) + p.Error("error while creating ARP spoof packet: %s", err) } } else { - log.Debug("telling the gw %s is %s", ip, mac) + p.Debug("telling the gw %s is %s", ip, mac) // send the gateway the original MAC of the target if err, gwPacket = packets.NewARPReply(rawIP, mac, gwIP, gwHW); err != nil { - log.Error("error while creating ARP spoof packet: %s", err) + p.Error("error while creating ARP spoof packet: %s", err) } } if gwPacket != nil { if err = p.Session.Queue.Send(gwPacket); err != nil { - log.Error("error while sending packet: %v", err) + p.Error("error while sending packet: %v", err) } } } diff --git a/modules/ble/ble_recon.go b/modules/ble/ble_recon.go index 90a3b6fa..89d3e885 100644 --- a/modules/ble/ble_recon.go +++ b/modules/ble/ble_recon.go @@ -10,7 +10,6 @@ import ( golog "log" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" @@ -110,7 +109,7 @@ func (d *BLERecon) Configure() (err error) { if d.Running() { return session.ErrAlreadyStarted } else if d.gattDevice == nil { - log.Info("Initializing BLE device ...") + d.Info("Initializing BLE device ...") // hey Paypal GATT library, could you please just STFU?! golog.SetOutput(ioutil.Discard) @@ -140,7 +139,7 @@ func (d *BLERecon) Start() error { <-d.quit - log.Info("Stopping BLE scan ...") + d.Info("Stopping BLE scan ...") d.gattDevice.StopScanning() @@ -156,7 +155,7 @@ func (d *BLERecon) Stop() error { } func (d *BLERecon) pruner() { - log.Debug("Started BLE devices pruner ...") + d.Debug("Started BLE devices pruner ...") for d.Running() { for _, dev := range d.Session.BLE.Devices() { @@ -193,7 +192,7 @@ func (d *BLERecon) enumAllTheThings(mac string) error { return err } - log.Info("Connecting to %s ...", mac) + d.Info("Connecting to %s ...", mac) go func() { time.Sleep(d.connTimeout) diff --git a/modules/ble/ble_recon_events.go b/modules/ble/ble_recon_events.go index 6a4da701..e9ade95f 100644 --- a/modules/ble/ble_recon_events.go +++ b/modules/ble/ble_recon_events.go @@ -4,25 +4,23 @@ package ble import ( - "github.com/bettercap/bettercap/log" - "github.com/bettercap/gatt" ) func (d *BLERecon) onStateChanged(dev gatt.Device, s gatt.State) { - log.Info("BLE state changed to %v", s) + d.Info("BLE state changed to %v", s) switch s { case gatt.StatePoweredOn: if d.currDevice == nil { - log.Info("Starting BLE discovery ...") + d.Info("Starting BLE discovery ...") dev.Scan([]gatt.UUID{}, true) } case gatt.StatePoweredOff: d.gattDevice = nil default: - log.Warning("Unexpected BLE state: %v", s) + d.Warning("Unexpected BLE state: %v", s) } } @@ -33,7 +31,7 @@ func (d *BLERecon) onPeriphDiscovered(p gatt.Peripheral, a *gatt.Advertisement, func (d *BLERecon) onPeriphDisconnected(p gatt.Peripheral, err error) { if d.Running() { // restore scanning - log.Info("Device disconnected, restoring BLE discovery.") + d.Info("Device disconnected, restoring BLE discovery.") d.setCurrentDevice(nil) d.gattDevice.Scan([]gatt.UUID{}, true) } @@ -41,31 +39,31 @@ func (d *BLERecon) onPeriphDisconnected(p gatt.Peripheral, err error) { func (d *BLERecon) onPeriphConnected(p gatt.Peripheral, err error) { if err != nil { - log.Warning("Connected to %s but with error: %s", p.ID(), err) + d.Warning("Connected to %s but with error: %s", p.ID(), err) return } else if d.currDevice == nil { // timed out - log.Warning("Connected to %s but after the timeout :(", p.ID()) + d.Warning("Connected to %s but after the timeout :(", p.ID()) return } d.connected = true defer func(per gatt.Peripheral) { - log.Info("Disconnecting from %s ...", per.ID()) + d.Info("Disconnecting from %s ...", per.ID()) per.Device().CancelConnection(per) }(p) d.Session.Events.Add("ble.device.connected", d.currDevice) if err := p.SetMTU(500); err != nil { - log.Warning("Failed to set MTU: %s", err) + d.Warning("Failed to set MTU: %s", err) } - log.Info("Connected, enumerating all the things for %s!", p.ID()) + d.Info("Connected, enumerating all the things for %s!", p.ID()) services, err := p.DiscoverServices(nil) if err != nil { - log.Error("Error discovering services: %s", err) + d.Error("Error discovering services: %s", err) return } diff --git a/modules/ble/ble_recon_view.go b/modules/ble/ble_recon_view.go index b913be9b..c749d49c 100644 --- a/modules/ble/ble_recon_view.go +++ b/modules/ble/ble_recon_view.go @@ -11,7 +11,6 @@ import ( "strings" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/gatt" @@ -153,7 +152,7 @@ func (d *BLERecon) showServices(p gatt.Peripheral, services []*gatt.Service) { chars, err := p.DiscoverCharacteristics(nil, svc) if err != nil { - log.Error("Error while enumerating chars for service %s: %s", svc.UUID(), err) + d.Error("Error while enumerating chars for service %s: %s", svc.UUID(), err) continue } @@ -172,14 +171,14 @@ func (d *BLERecon) showServices(p gatt.Peripheral, services []*gatt.Service) { if wantsToWrite && d.writeUUID.Equal(ch.UUID()) { foundToWrite = true if isWritable { - log.Info("Writing %d bytes to characteristics %s ...", len(d.writeData), d.writeUUID) + d.Info("Writing %d bytes to characteristics %s ...", len(d.writeData), d.writeUUID) } else { - log.Warning("Attempt to write %d bytes to non writable characteristics %s ...", len(d.writeData), d.writeUUID) + d.Warning("Attempt to write %d bytes to non writable characteristics %s ...", len(d.writeData), d.writeUUID) } err := p.WriteCharacteristic(ch, d.writeData, !withResponse) if err != nil { - log.Error("Error while writing: %s", err) + d.Error("Error while writing: %s", err) } } @@ -205,7 +204,7 @@ func (d *BLERecon) showServices(p gatt.Peripheral, services []*gatt.Service) { } if wantsToWrite && !foundToWrite { - log.Error("Writable characteristics %s not found.", d.writeUUID) + d.Error("Writable characteristics %s not found.", d.writeUUID) } else { tui.Table(os.Stdout, columns, rows) d.Session.Refresh() diff --git a/modules/caplets/caplets.go b/modules/caplets/caplets.go index 18ed65a5..d64aa970 100644 --- a/modules/caplets/caplets.go +++ b/modules/caplets/caplets.go @@ -7,7 +7,6 @@ import ( "os" "github.com/bettercap/bettercap/caplets" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/dustin/go-humanize" @@ -115,7 +114,7 @@ func (c *CapletsModule) Paths() error { func (c *CapletsModule) Update() error { if !fs.Exists(caplets.InstallBase) { - log.Info("creating caplets install path %s ...", caplets.InstallBase) + c.Info("creating caplets install path %s ...", caplets.InstallBase) if err := os.MkdirAll(caplets.InstallBase, os.ModePerm); err != nil { return err } @@ -127,7 +126,7 @@ func (c *CapletsModule) Update() error { } defer out.Close() - log.Info("downloading caplets from %s ...", caplets.InstallArchive) + c.Info("downloading caplets from %s ...", caplets.InstallArchive) resp, err := http.Get(caplets.InstallArchive) if err != nil { @@ -139,7 +138,7 @@ func (c *CapletsModule) Update() error { return err } - log.Info("installing caplets to %s ...", caplets.InstallPath) + c.Info("installing caplets to %s ...", caplets.InstallPath) if _, err = zip.Unzip("/tmp/caplets.zip", caplets.InstallBase); err != nil { return err diff --git a/modules/dhcp6_spoof/dhcp6_spoof.go b/modules/dhcp6_spoof/dhcp6_spoof.go index 1b39da81..a7bafb6c 100644 --- a/modules/dhcp6_spoof/dhcp6_spoof.go +++ b/modules/dhcp6_spoof/dhcp6_spoof.go @@ -9,7 +9,6 @@ import ( "sync" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" @@ -104,7 +103,7 @@ func (s *DHCP6Spoofer) Configure() error { } if !s.Session.Firewall.IsForwardingEnabled() { - log.Info("Enabling forwarding.") + s.Info("Enabling forwarding.") s.Session.Firewall.EnableForwarding(true) } @@ -131,21 +130,21 @@ func (s *DHCP6Spoofer) dhcpAdvertise(pkt gopacket.Packet, solicit dhcp6.Packet, fqdn = string(raw[0]) } - log.Info("[%s] Got DHCPv6 Solicit request from %s (%s), sending spoofed advertisement for %d domains.", tui.Green("dhcp6"), tui.Bold(fqdn), target, len(s.Domains)) + s.Info("Got DHCPv6 Solicit request from %s (%s), sending spoofed advertisement for %d domains.", tui.Bold(fqdn), target, len(s.Domains)) err, adv := s.dhcp6For(dhcp6.MessageTypeAdvertise, solicit) if err != nil { - log.Error("%s", err) + s.Error("%s", err) return } var solIANA dhcp6opts.IANA if raw, found := solicit.Options[dhcp6.OptionIANA]; !found || len(raw) < 1 { - log.Error("Unexpected DHCPv6 packet, could not find IANA.") + s.Error("Unexpected DHCPv6 packet, could not find IANA.") return } else if err := solIANA.UnmarshalBinary(raw[0]); err != nil { - log.Error("Unexpected DHCPv6 packet, could not deserialize IANA.") + s.Error("Unexpected DHCPv6 packet, could not deserialize IANA.") return } @@ -153,7 +152,7 @@ func (s *DHCP6Spoofer) dhcpAdvertise(pkt gopacket.Packet, solicit dhcp6.Packet, if h, found := s.Session.Lan.Get(target.String()); found { ip = h.IP } else { - log.Warning("Address %s not known, using random identity association address.", target.String()) + s.Warning("Address %s not known, using random identity association address.", target.String()) rand.Read(ip) } @@ -161,13 +160,13 @@ func (s *DHCP6Spoofer) dhcpAdvertise(pkt gopacket.Packet, solicit dhcp6.Packet, iaaddr, err := dhcp6opts.NewIAAddr(net.ParseIP(addr), 300*time.Second, 300*time.Second, nil) if err != nil { - log.Error("Error creating IAAddr: %s", err) + s.Error("Error creating IAAddr: %s", err) return } iaaddrRaw, err := iaaddr.MarshalBinary() if err != nil { - log.Error("Error serializing IAAddr: %s", err) + s.Error("Error serializing IAAddr: %s", err) return } @@ -175,7 +174,7 @@ func (s *DHCP6Spoofer) dhcpAdvertise(pkt gopacket.Packet, solicit dhcp6.Packet, iana := dhcp6opts.NewIANA(solIANA.IAID, 200*time.Second, 250*time.Second, opts) ianaRaw, err := iana.MarshalBinary() if err != nil { - log.Error("Error serializing IANA: %s", err) + s.Error("Error serializing IANA: %s", err) return } @@ -183,7 +182,7 @@ func (s *DHCP6Spoofer) dhcpAdvertise(pkt gopacket.Packet, solicit dhcp6.Packet, rawAdv, err := adv.MarshalBinary() if err != nil { - log.Error("Error serializing advertisement packet: %s.", err) + s.Error("Error serializing advertisement packet: %s.", err) return } @@ -214,31 +213,31 @@ func (s *DHCP6Spoofer) dhcpAdvertise(pkt gopacket.Packet, solicit dhcp6.Packet, err, raw := packets.Serialize(ð, &ip6, &udp, &dhcp) if err != nil { - log.Error("Error serializing packet: %s.", err) + s.Error("Error serializing packet: %s.", err) return } - log.Debug("Sending %d bytes of packet ...", len(raw)) + s.Debug("Sending %d bytes of packet ...", len(raw)) if err := s.Session.Queue.Send(raw); err != nil { - log.Error("Error sending packet: %s", err) + s.Error("Error sending packet: %s", err) } } func (s *DHCP6Spoofer) dhcpReply(toType string, pkt gopacket.Packet, req dhcp6.Packet, target net.HardwareAddr) { - log.Debug("Sending spoofed DHCPv6 reply to %s after its %s packet.", tui.Bold(target.String()), toType) + s.Debug("Sending spoofed DHCPv6 reply to %s after its %s packet.", tui.Bold(target.String()), toType) err, reply := s.dhcp6For(dhcp6.MessageTypeReply, req) if err != nil { - log.Error("%s", err) + s.Error("%s", err) return } var reqIANA dhcp6opts.IANA if raw, found := req.Options[dhcp6.OptionIANA]; !found || len(raw) < 1 { - log.Error("Unexpected DHCPv6 packet, could not find IANA.") + s.Error("Unexpected DHCPv6 packet, could not find IANA.") return } else if err := reqIANA.UnmarshalBinary(raw[0]); err != nil { - log.Error("Unexpected DHCPv6 packet, could not deserialize IANA.") + s.Error("Unexpected DHCPv6 packet, could not deserialize IANA.") return } @@ -246,7 +245,7 @@ func (s *DHCP6Spoofer) dhcpReply(toType string, pkt gopacket.Packet, req dhcp6.P if raw, found := reqIANA.Options[dhcp6.OptionIAAddr]; found { reqIAddr = raw[0] } else { - log.Error("Unexpected DHCPv6 packet, could not deserialize request IANA IAAddr.") + s.Error("Unexpected DHCPv6 packet, could not deserialize request IANA IAAddr.") return } @@ -254,14 +253,14 @@ func (s *DHCP6Spoofer) dhcpReply(toType string, pkt gopacket.Packet, req dhcp6.P iana := dhcp6opts.NewIANA(reqIANA.IAID, 200*time.Second, 250*time.Second, opts) ianaRaw, err := iana.MarshalBinary() if err != nil { - log.Error("Error serializing IANA: %s", err) + s.Error("Error serializing IANA: %s", err) return } reply.Options.AddRaw(dhcp6.OptionIANA, ianaRaw) rawAdv, err := reply.MarshalBinary() if err != nil { - log.Error("Error serializing advertisement packet: %s.", err) + s.Error("Error serializing advertisement packet: %s.", err) return } @@ -293,13 +292,13 @@ func (s *DHCP6Spoofer) dhcpReply(toType string, pkt gopacket.Packet, req dhcp6.P err, raw := packets.Serialize(ð, &ip6, &udp, &dhcp) if err != nil { - log.Error("Error serializing packet: %s.", err) + s.Error("Error serializing packet: %s.", err) return } - log.Debug("Sending %d bytes of packet ...", len(raw)) + s.Debug("Sending %d bytes of packet ...", len(raw)) if err := s.Session.Queue.Send(raw); err != nil { - log.Error("Error sending packet: %s", err) + s.Error("Error sending packet: %s", err) } if toType == "request" { @@ -309,12 +308,12 @@ func (s *DHCP6Spoofer) dhcpReply(toType string, pkt gopacket.Packet, req dhcp6.P } if h, found := s.Session.Lan.Get(target.String()); found { - log.Info("[%s] IPv6 address %s is now assigned to %s", tui.Green("dhcp6"), addr.String(), h) + s.Info("IPv6 address %s is now assigned to %s", addr.String(), h) } else { - log.Info("[%s] IPv6 address %s is now assigned to %s", tui.Green("dhcp6"), addr.String(), target) + s.Info("IPv6 address %s is now assigned to %s", addr.String(), target) } } else { - log.Debug("DHCPv6 renew sent to %s", target) + s.Debug("DHCPv6 renew sent to %s", target) } } diff --git a/modules/discovery/net_recon.go b/modules/discovery/net_recon.go index b07cebc9..3953a1fa 100644 --- a/modules/discovery/net_recon.go +++ b/modules/discovery/net_recon.go @@ -4,7 +4,6 @@ import ( "github.com/bettercap/bettercap/modules/utils" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" ) @@ -105,7 +104,7 @@ func (d *Discovery) Start() error { iface := d.Session.Interface.Name() for d.Running() { if table, err := network.ArpUpdate(iface); err != nil { - log.Error("%s", err) + d.Error("%s", err) } else { d.runDiff(table) } diff --git a/modules/dns_spoof/dns_spoof.go b/modules/dns_spoof/dns_spoof.go index 6fb71109..ce242885 100644 --- a/modules/dns_spoof/dns_spoof.go +++ b/modules/dns_spoof/dns_spoof.go @@ -6,7 +6,6 @@ import ( "net" "sync" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" @@ -109,7 +108,7 @@ func (s *DNSSpoofer) Configure() error { } if hostsFile != "" { - log.Info("loading hosts from file %s ...", hostsFile) + s.Info("loading hosts from file %s ...", hostsFile) if err, hosts := HostsFromFile(hostsFile); err != nil { return fmt.Errorf("error reading hosts from file %s: %v", hostsFile, err) } else { @@ -122,11 +121,11 @@ func (s *DNSSpoofer) Configure() error { } for _, entry := range s.Hosts { - log.Info("[%s] %s -> %s", tui.Green("dns.spoof"), entry.Host, entry.Address) + s.Info("%s -> %s", entry.Host, entry.Address) } if !s.Session.Firewall.IsForwardingEnabled() { - log.Info("Enabling forwarding.") + s.Info("enabling forwarding.") s.Session.Firewall.EnableForwarding(true) } @@ -141,14 +140,14 @@ func (s *DNSSpoofer) dnsReply(pkt gopacket.Packet, peth *layers.Ethernet, pudp * who = t.String() } - log.Info("[%s] sending spoofed DNS reply for %s %s to %s.", tui.Green("dns"), tui.Red(domain), tui.Dim(redir), tui.Bold(who)) + s.Info("sending spoofed DNS reply for %s %s to %s.", tui.Red(domain), tui.Dim(redir), tui.Bold(who)) var err error var src, dst net.IP nlayer := pkt.NetworkLayer() if nlayer == nil { - log.Debug("missing network layer skipping packet.") + s.Debug("missing network layer skipping packet.") return } @@ -217,7 +216,7 @@ func (s *DNSSpoofer) dnsReply(pkt gopacket.Packet, peth *layers.Ethernet, pudp * err, raw = packets.Serialize(ð, &ip6, &udp, &dns) if err != nil { - log.Error("error serializing packet: %s.", err) + s.Error("error serializing packet: %s.", err) return } } else { @@ -238,14 +237,14 @@ func (s *DNSSpoofer) dnsReply(pkt gopacket.Packet, peth *layers.Ethernet, pudp * err, raw = packets.Serialize(ð, &ip4, &udp, &dns) if err != nil { - log.Error("error serializing packet: %s.", err) + s.Error("error serializing packet: %s.", err) return } } - log.Debug("sending %d bytes of packet ...", len(raw)) + s.Debug("sending %d bytes of packet ...", len(raw)) if err := s.Session.Queue.Send(raw); err != nil { - log.Error("error sending packet: %s", err) + s.Error("error sending packet: %s", err) } } @@ -267,7 +266,7 @@ func (s *DNSSpoofer) onPacket(pkt gopacket.Packet) { s.dnsReply(pkt, eth, udp, qName, address, dns, eth.SrcMAC) break } else { - log.Debug("skipping domain %s", qName) + s.Debug("skipping domain %s", qName) } } } diff --git a/modules/events_stream/events_stream.go b/modules/events_stream/events_stream.go index 991e936c..4b208a0a 100644 --- a/modules/events_stream/events_stream.go +++ b/modules/events_stream/events_stream.go @@ -7,7 +7,6 @@ import ( "sync" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/fs" @@ -263,9 +262,9 @@ func (s *EventsStream) Show(limit int) error { func (s *EventsStream) startWaitingFor(tag string, timeout int) error { if timeout == 0 { - log.Info("waiting for event %s ...", tui.Green(tag)) + s.Info("waiting for event %s ...", tui.Green(tag)) } else { - log.Info("waiting for event %s for %d seconds ...", tui.Green(tag), timeout) + s.Info("waiting for event %s for %d seconds ...", tui.Green(tag), timeout) go func() { time.Sleep(time.Duration(timeout) * time.Second) s.waitFor = "" @@ -279,7 +278,7 @@ func (s *EventsStream) startWaitingFor(tag string, timeout int) error { if event == nil { return fmt.Errorf("'events.waitFor %s %d' timed out.", tag, timeout) } else { - log.Debug("got event: %v", event) + s.Debug("got event: %v", event) } return nil diff --git a/modules/events_stream/events_view.go b/modules/events_stream/events_view.go index d9e5031d..2d44e3c9 100644 --- a/modules/events_stream/events_view.go +++ b/modules/events_stream/events_view.go @@ -2,7 +2,6 @@ package events_stream import ( "fmt" - "github.com/bettercap/bettercap/modules/net_sniff" "os" "strings" "time" @@ -10,6 +9,7 @@ import ( "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" diff --git a/modules/gps/gps.go b/modules/gps/gps.go index 3d8bb70f..e468c042 100644 --- a/modules/gps/gps.go +++ b/modules/gps/gps.go @@ -5,7 +5,6 @@ import ( "io" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/adrianmo/go-nmea" @@ -24,7 +23,7 @@ type GPS struct { func NewGPS(s *session.Session) *GPS { gps := &GPS{ - SessionModule: session.NewSessionModule("http.server", s), + SessionModule: session.NewSessionModule("gps", s), serialPort: "/dev/ttyUSB0", baudRate: 19200, } @@ -136,10 +135,10 @@ func (gps *GPS) Start() error { gps.Session.GPS = m } } else { - log.Debug("Error parsing line '%s': %s", line, err) + gps.Debug("error parsing line '%s': %s", line, err) } } else if err != io.EOF { - log.Warning("Error while reading serial port: %s", err) + gps.Warning("error while reading serial port: %s", err) } } }) diff --git a/modules/http_proxy/http_proxy_base.go b/modules/http_proxy/http_proxy_base.go index f34dcb1d..49eccfe1 100644 --- a/modules/http_proxy/http_proxy_base.go +++ b/modules/http_proxy/http_proxy_base.go @@ -16,7 +16,6 @@ import ( "time" "github.com/bettercap/bettercap/firewall" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" btls "github.com/bettercap/bettercap/tls" @@ -24,6 +23,7 @@ import ( "github.com/inconshreveable/go-vhost" "github.com/evilsocket/islazy/fs" + "github.com/evilsocket/islazy/log" "github.com/evilsocket/islazy/tui" ) @@ -48,6 +48,7 @@ type HTTPProxy struct { stripper *SSLStripper sniListener net.Listener sess *session.Session + tag string } func stripPort(s string) string { @@ -66,6 +67,7 @@ func NewHTTPProxy(s *session.Session) *HTTPProxy { stripper: NewSSLStripper(s, false), isTLS: false, Server: nil, + tag: session.AsTag("http.proxy"), } p.Proxy.Verbose = false @@ -88,6 +90,26 @@ func NewHTTPProxy(s *session.Session) *HTTPProxy { 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 { blacklist := []string{ "localhost", @@ -95,14 +117,14 @@ func (p *HTTPProxy) doProxy(req *http.Request) bool { } if req.Host == "" { - log.Error("Got request with empty host: %v", req) + p.Error("got request with empty host: %v", req) return false } host := strings.Split(req.Host, ":")[0] for _, blacklisted := range blacklist { if host == blacklisted { - log.Error("Got request with blacklisted host: %s", req.Host) + p.Error("got request with blacklisted host: %s", req.Host) return false } } @@ -137,7 +159,7 @@ func (p *HTTPProxy) Configure(address string, proxyPort int, httpPort int, scrip if err, p.Script = LoadHttpProxyScript(scriptPath, p.sess); err != nil { return err } else { - log.Debug("Proxy script %s loaded.", scriptPath) + p.Debug("proxy script %s loaded.", scriptPath) } } @@ -149,7 +171,7 @@ func (p *HTTPProxy) Configure(address string, proxyPort int, httpPort int, scrip } if !p.sess.Firewall.IsForwardingEnabled() { - log.Info("Enabling forwarding.") + p.Info("enabling forwarding.") p.sess.Firewall.EnableForwarding(true) } @@ -163,7 +185,7 @@ func (p *HTTPProxy) Configure(address string, proxyPort int, httpPort int, scrip return err } - log.Debug("Applied redirection %s", p.Redirection.String()) + p.Debug("applied redirection %s", p.Redirection.String()) p.sess.UnkCmdCallback = func(cmd string) bool { if p.Script != nil { @@ -175,7 +197,7 @@ func (p *HTTPProxy) Configure(address string, proxyPort int, httpPort int, scrip return nil } -func TLSConfigFromCA(ca *tls.Certificate) func(host string, ctx *goproxy.ProxyCtx) (*tls.Config, error) { +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] @@ -189,10 +211,10 @@ func TLSConfigFromCA(ca *tls.Certificate) func(host string, ctx *goproxy.ProxyCt cert := getCachedCert(hostname, port) if cert == nil { - log.Debug("Creating spoofed certificate for %s:%d", tui.Yellow(hostname), port) + p.Debug("creating spoofed certificate for %s:%d", tui.Yellow(hostname), port) cert, err = btls.SignCertificateForHost(ca, hostname, port) if err != nil { - log.Warning("Cannot sign host certificate with provided CA: %s", err) + p.Warning("cannot sign host certificate with provided CA: %s", err) return nil, err } @@ -215,6 +237,7 @@ func (p *HTTPProxy) ConfigureTLS(address string, proxyPort int, httpPort int, sc p.isTLS = true p.Name = "https.proxy" + p.tag = session.AsTag("https.proxy") p.CertFile = certFile p.KeyFile = keyFile @@ -230,10 +253,10 @@ func (p *HTTPProxy) ConfigureTLS(address string, proxyPort int, httpPort int, sc } goproxy.GoproxyCa = ourCa - goproxy.OkConnect = &goproxy.ConnectAction{Action: goproxy.ConnectAccept, TLSConfig: TLSConfigFromCA(&ourCa)} - goproxy.MitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectMitm, TLSConfig: TLSConfigFromCA(&ourCa)} - goproxy.HTTPMitmConnect = &goproxy.ConnectAction{Action: goproxy.ConnectHTTPMitm, TLSConfig: TLSConfigFromCA(&ourCa)} - goproxy.RejectConnect = &goproxy.ConnectAction{Action: goproxy.ConnectReject, TLSConfig: TLSConfigFromCA(&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 } @@ -279,7 +302,7 @@ func (p *HTTPProxy) httpsWorker() error { for p.isRunning { c, err := p.sniListener.Accept() if err != nil { - log.Warning("error accepting connection: %s.", err) + p.Warning("error accepting connection: %s.", err) continue } @@ -290,17 +313,17 @@ func (p *HTTPProxy) httpsWorker() error { tlsConn, err := vhost.TLS(c) if err != nil { - log.Warning("error reading SNI: %s.", err) + p.Warning("error reading SNI: %s.", err) return } hostname := tlsConn.Host() if hostname == "" { - log.Warning("client does not support SNI.") + p.Warning("client does not support SNI.") return } - log.Debug("[%s] proxying connection from %s to %s", tui.Green("https.proxy"), tui.Bold(stripPort(c.RemoteAddr().String())), tui.Yellow(hostname)) + p.Debug("proxying connection from %s to %s", tui.Bold(stripPort(c.RemoteAddr().String())), tui.Yellow(hostname)) req := &http.Request{ Method: "CONNECT", @@ -327,7 +350,7 @@ func (p *HTTPProxy) Start() { strip = tui.Dim("disabled") } - log.Info("%s started on %s (sslstrip %s)", tui.Green(p.Name), p.Server.Addr, strip) + p.Info("started on %s (sslstrip %s)", p.Server.Addr, strip) if p.isTLS { err = p.httpsWorker() @@ -336,14 +359,14 @@ func (p *HTTPProxy) Start() { } if err != nil && err.Error() != "http: Server closed" { - log.Fatal("%s", err) + p.Fatal("%s", err) } }() } func (p *HTTPProxy) Stop() error { if p.Redirection != nil { - log.Debug("Disabling redirection %s", p.Redirection.String()) + p.Debug("disabling redirection %s", p.Redirection.String()) if err := p.sess.Firewall.EnableRedirection(p.Redirection, false); err != nil { return err } diff --git a/modules/http_proxy/http_proxy_base_cookietracker.go b/modules/http_proxy/http_proxy_base_cookietracker.go index 0aa9e792..822b99c8 100644 --- a/modules/http_proxy/http_proxy_base_cookietracker.go +++ b/modules/http_proxy/http_proxy_base_cookietracker.go @@ -6,8 +6,6 @@ import ( "strings" "sync" - "github.com/bettercap/bettercap/log" - "github.com/elazarl/goproxy" "github.com/jpillora/go-tld" ) @@ -25,7 +23,6 @@ func NewCookieTracker() *CookieTracker { func (t *CookieTracker) domainOf(req *http.Request) string { if parsed, err := tld.Parse(req.Host); err != nil { - log.Warning("Could not parse host %s: %s", req.Host, err) return req.Host } else { return fmt.Sprintf("%s.%s", parsed.Domain, parsed.TLD) diff --git a/modules/http_proxy/http_proxy_base_filters.go b/modules/http_proxy/http_proxy_base_filters.go index dcd24bbd..d8ad23ce 100644 --- a/modules/http_proxy/http_proxy_base_filters.go +++ b/modules/http_proxy/http_proxy_base_filters.go @@ -5,8 +5,6 @@ import ( "net/http" "strings" - "github.com/bettercap/bettercap/log" - "github.com/elazarl/goproxy" "github.com/evilsocket/islazy/tui" @@ -21,7 +19,7 @@ func (p *HTTPProxy) fixRequestHeaders(req *http.Request) { } func (p *HTTPProxy) onRequestFilter(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { - log.Debug("(%s) < %s %s %s%s", tui.Green(p.Name), req.RemoteAddr, req.Method, req.Host, req.URL.Path) + p.Debug("< %s %s %s%s", req.RemoteAddr, req.Method, req.Host, req.URL.Path) p.fixRequestHeaders(req) @@ -99,8 +97,7 @@ func (p *HTTPProxy) doScriptInjection(res *http.Response, cType string) (error, if err != nil { return err, nil } else if html := string(raw); strings.Contains(html, "") { - log.Info("(%s) > injecting javascript (%d bytes) into %s (%d bytes) for %s", - tui.Green(p.Name), + 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), @@ -126,7 +123,7 @@ func (p *HTTPProxy) onResponseFilter(res *http.Response, ctx *goproxy.ProxyCtx) return nil } - log.Debug("(%s) > %s %s %s%s", tui.Green(p.Name), res.Request.RemoteAddr, res.Request.Method, res.Request.Host, res.Request.URL.Path) + p.Debug("> %s %s %s%s", res.Request.RemoteAddr, res.Request.Method, res.Request.Host, res.Request.URL.Path) p.fixResponseHeaders(res) @@ -145,7 +142,7 @@ func (p *HTTPProxy) onResponseFilter(res *http.Response, ctx *goproxy.ProxyCtx) // inject javascript code if specified and needed if doInject, cType := p.isScriptInjectable(res); doInject { if err, injectedResponse := p.doScriptInjection(res, cType); err != nil { - log.Error("(%s) error while injecting javascript: %s", p.Name, err) + p.Error("error while injecting javascript: %s", err) } else if injectedResponse != nil { return injectedResponse } diff --git a/modules/http_proxy/http_proxy_base_hosttracker.go b/modules/http_proxy/http_proxy_base_hosttracker.go index 0eb3f079..c591b25e 100644 --- a/modules/http_proxy/http_proxy_base_hosttracker.go +++ b/modules/http_proxy/http_proxy_base_hosttracker.go @@ -3,8 +3,6 @@ package http_proxy import ( "net" "sync" - - "github.com/bettercap/bettercap/log" ) type Host struct { @@ -27,7 +25,6 @@ func NewHost(name string) *Host { ph.Address = make(net.IP, len(addrs[0])) copy(ph.Address, addrs[0]) } else { - log.Error("Could not resolve %s: %s", ph.Hostname, err) ph.Address = nil } }(h) diff --git a/modules/http_proxy/http_proxy_script.go b/modules/http_proxy/http_proxy_script.go index f064e044..e9e7df05 100644 --- a/modules/http_proxy/http_proxy_script.go +++ b/modules/http_proxy/http_proxy_script.go @@ -20,7 +20,7 @@ type HttpProxyScript struct { } func LoadHttpProxyScript(path string, sess *session.Session) (err error, s *HttpProxyScript) { - log.Info("loading proxy script %s ...", path) + log.Debug("loading proxy script %s ...", path) plug, err := plugin.Load(path) if err != nil { diff --git a/modules/http_server/http_server.go b/modules/http_server/http_server.go index ac3f5252..2bb7fea5 100644 --- a/modules/http_server/http_server.go +++ b/modules/http_server/http_server.go @@ -7,7 +7,6 @@ import ( "strings" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/evilsocket/islazy/tui" @@ -83,7 +82,7 @@ func (httpd *HttpServer) Configure() error { fileServer := http.FileServer(http.Dir(path)) router.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Info("(%s) %s %s %s%s", tui.Green("httpd"), tui.Bold(strings.Split(r.RemoteAddr, ":")[0]), r.Method, r.Host, r.URL.Path) + httpd.Info("%s %s %s%s", tui.Bold(strings.Split(r.RemoteAddr, ":")[0]), r.Method, r.Host, r.URL.Path) fileServer.ServeHTTP(w, r) })) @@ -109,7 +108,7 @@ func (httpd *HttpServer) Start() error { return httpd.SetRunning(true, func() { var err error - log.Info("HTTP server starting on http://%s", httpd.server.Addr) + httpd.Info("starting on http://%s", httpd.server.Addr) if err = httpd.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { panic(err) } diff --git a/modules/https_proxy/https_proxy.go b/modules/https_proxy/https_proxy.go index 65e893f8..eaa1c97a 100644 --- a/modules/https_proxy/https_proxy.go +++ b/modules/https_proxy/https_proxy.go @@ -1,10 +1,9 @@ package https_proxy import ( - "github.com/bettercap/bettercap/log" + "github.com/bettercap/bettercap/modules/http_proxy" "github.com/bettercap/bettercap/session" "github.com/bettercap/bettercap/tls" - "github.com/bettercap/bettercap/modules/http_proxy" "github.com/evilsocket/islazy/fs" ) @@ -127,15 +126,15 @@ func (p *HttpsProxy) Configure() error { return err } - log.Debug("%+v", cfg) - log.Info("Generating proxy certification authority TLS key to %s", keyFile) - log.Info("Generating proxy certification authority TLS certificate to %s", certFile) + p.Debug("%+v", cfg) + p.Info("generating proxy certification authority TLS key to %s", keyFile) + p.Info("generating proxy certification authority TLS certificate to %s", certFile) if err := tls.Generate(cfg, certFile, keyFile); err != nil { return err } } else { - log.Info("loading proxy certification authority TLS key from %s", keyFile) - log.Info("loading proxy certification authority TLS certificate from %s", certFile) + p.Info("loading proxy certification authority TLS key from %s", keyFile) + p.Info("loading proxy certification authority TLS certificate from %s", certFile) } return p.proxy.ConfigureTLS(address, proxyPort, httpPort, scriptPath, certFile, keyFile, jsToInject, stripSSL) diff --git a/modules/https_server/https_server.go b/modules/https_server/https_server.go index 61cb7458..d4dc479f 100644 --- a/modules/https_server/https_server.go +++ b/modules/https_server/https_server.go @@ -7,7 +7,6 @@ import ( "strings" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/bettercap/bettercap/tls" @@ -101,7 +100,7 @@ func (httpd *HttpsServer) Configure() error { fileServer := http.FileServer(http.Dir(path)) router.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Info("(%s) %s %s %s%s", tui.Green("https"), tui.Bold(strings.Split(r.RemoteAddr, ":")[0]), r.Method, r.Host, r.URL.Path) + httpd.Info("%s %s %s%s", tui.Bold(strings.Split(r.RemoteAddr, ":")[0]), r.Method, r.Host, r.URL.Path) fileServer.ServeHTTP(w, r) })) @@ -135,15 +134,15 @@ func (httpd *HttpsServer) Configure() error { return err } - log.Debug("%+v", cfg) - log.Info("generating server TLS key to %s", keyFile) - log.Info("generating server TLS certificate to %s", certFile) + httpd.Debug("%+v", cfg) + httpd.Info("generating server TLS key to %s", keyFile) + httpd.Info("generating server TLS certificate to %s", certFile) if err := tls.Generate(cfg, certFile, keyFile); err != nil { return err } } else { - log.Info("loading server TLS key from %s", keyFile) - log.Info("loading server TLS certificate from %s", certFile) + httpd.Info("loading server TLS key from %s", keyFile) + httpd.Info("loading server TLS certificate from %s", certFile) } httpd.certFile = certFile @@ -158,7 +157,7 @@ func (httpd *HttpsServer) Start() error { } return httpd.SetRunning(true, func() { - log.Info("HTTPS server starting on https://%s", httpd.server.Addr) + httpd.Info("starting on https://%s", httpd.server.Addr) if err := httpd.server.ListenAndServeTLS(httpd.certFile, httpd.keyFile); err != nil && err != http.ErrServerClosed { panic(err) } diff --git a/modules/mac_changer/mac_changer.go b/modules/mac_changer/mac_changer.go index edbea43e..3fafdbbd 100644 --- a/modules/mac_changer/mac_changer.go +++ b/modules/mac_changer/mac_changer.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/bettercap/bettercap/core" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" @@ -112,16 +111,16 @@ func (mc *MacChanger) Start() error { } return mc.SetRunning(true, func() { - log.Info("Interface mac address set to %s", tui.Bold(mc.fakeMac.String())) + mc.Info("interface mac address set to %s", tui.Bold(mc.fakeMac.String())) }) } func (mc *MacChanger) Stop() error { return mc.SetRunning(false, func() { if err := mc.setMac(mc.originalMac); err == nil { - log.Info("Interface mac address restored to %s", tui.Bold(mc.originalMac.String())) + mc.Info("interface mac address restored to %s", tui.Bold(mc.originalMac.String())) } else { - log.Error("Error while restoring mac address: %s", err) + mc.Error("error while restoring mac address: %s", err) } }) } diff --git a/modules/mysql_server/mysql_server.go b/modules/mysql_server/mysql_server.go index 1b17bade..bf94d811 100644 --- a/modules/mysql_server/mysql_server.go +++ b/modules/mysql_server/mysql_server.go @@ -8,7 +8,6 @@ import ( "net" "strings" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" @@ -104,10 +103,10 @@ func (mysql *MySQLServer) Start() error { } return mysql.SetRunning(true, func() { - log.Info("[%s] server starting on address %s", tui.Green("mysql.server"), mysql.address) + mysql.Info("server starting on address %s", mysql.address) for mysql.Running() { if conn, err := mysql.listener.AcceptTCP(); err != nil { - log.Warning("[%s] error while accepting tcp connection: %s", tui.Green("mysql.server"), err) + mysql.Warning("error while accepting tcp connection: %s", err) continue } else { defer conn.Close() @@ -118,13 +117,13 @@ func (mysql *MySQLServer) Start() error { reader := bufio.NewReader(conn) read := 0 - log.Info("[%s] connection from %s", tui.Green("mysql.server"), clientAddress) + mysql.Info("connection from %s", clientAddress) if _, err := conn.Write(packets.MySQLGreeting); err != nil { - log.Warning("[%s] error while writing server greeting: %s", tui.Green("mysql.server"), err) + mysql.Warning("error while writing server greeting: %s", err) continue } else if read, err = reader.Read(readBuffer); err != nil { - log.Warning("[%s] error while reading client message: %s", tui.Green("mysql.server"), err) + mysql.Warning("error while reading client message: %s", err) continue } @@ -135,38 +134,38 @@ func (mysql *MySQLServer) Start() error { loadData := string(capabilities[8]) username := string(bytes.Split(readBuffer[36:], []byte{0})[0]) - log.Info("[%s] can use LOAD DATA LOCAL: %s", tui.Green("mysql.server"), loadData) - log.Info("[%s] login request username: %s", tui.Green("mysql.server"), tui.Bold(username)) + mysql.Info("can use LOAD DATA LOCAL: %s", loadData) + mysql.Info("login request username: %s", tui.Bold(username)) if _, err := conn.Write(packets.MySQLFirstResponseOK); err != nil { - log.Warning("[%s] error while writing server first response ok: %s", tui.Green("mysql.server"), err) + mysql.Warning("error while writing server first response ok: %s", err) continue } else if _, err := reader.Read(readBuffer); err != nil { - log.Warning("[%s] error while reading client message: %s", tui.Green("mysql.server"), err) + mysql.Warning("error while reading client message: %s", err) continue } else if _, err := conn.Write(packets.MySQLGetFile(mysql.infile)); err != nil { - log.Warning("[%s] error while writing server get file request: %s", tui.Green("mysql.server"), err) + mysql.Warning("error while writing server get file request: %s", err) continue } else if read, err = reader.Read(readBuffer); err != nil { - log.Warning("[%s] error while readind buffer: %s", tui.Green("mysql.server"), err) + mysql.Warning("error while readind buffer: %s", err) continue } if strings.HasPrefix(mysql.infile, "\\") { - log.Info("[%s] NTLM from '%s' relayed to %s", tui.Green("mysql.server"), clientAddress, mysql.infile) + mysql.Info("NTLM from '%s' relayed to %s", clientAddress, mysql.infile) } else if fileSize := read - 9; fileSize < 4 { - log.Warning("[%s] unpexpected buffer size %d", tui.Green("mysql.server"), read) + mysql.Warning("unpexpected buffer size %d", read) } else { - log.Info("[%s] read file ( %s ) is %d bytes", tui.Green("mysql.server"), mysql.infile, fileSize) + mysql.Info("read file ( %s ) is %d bytes", mysql.infile, fileSize) fileData := readBuffer[4 : read-4] if mysql.outfile == "" { - log.Info("\n%s", string(fileData)) + mysql.Info("\n%s", string(fileData)) } else { - log.Info("[%s] saving to %s ...", tui.Green("mysql.server"), mysql.outfile) + mysql.Info("saving to %s ...", mysql.outfile) if err := ioutil.WriteFile(mysql.outfile, fileData, 0755); err != nil { - log.Warning("[%s] error while saving the file: %s", tui.Green("mysql.server"), err) + mysql.Warning("error while saving the file: %s", err) } } } diff --git a/modules/net_sniff/net_sniff.go b/modules/net_sniff/net_sniff.go index 40002d07..2ab18c05 100644 --- a/modules/net_sniff/net_sniff.go +++ b/modules/net_sniff/net_sniff.go @@ -4,7 +4,6 @@ import ( "fmt" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/google/gopacket" @@ -171,7 +170,7 @@ func (s *Sniffer) Start() error { s.pktSourceChan = src.Packets() for packet := range s.pktSourceChan { if !s.Running() { - log.Debug("end pkt loop (pkt=%v filter='%s')", packet, s.Ctx.Filter) + s.Debug("end pkt loop (pkt=%v filter='%s')", packet, s.Ctx.Filter) break } @@ -211,14 +210,14 @@ func (s *Sniffer) Start() error { func (s *Sniffer) Stop() error { return s.SetRunning(false, func() { - log.Debug("stopping sniffer") + s.Debug("stopping sniffer") if s.pktSourceChan != nil { - log.Debug("sending nil") + s.Debug("sending nil") s.pktSourceChan <- nil - log.Debug("nil sent") + s.Debug("nil sent") } - log.Debug("closing ctx") + s.Debug("closing ctx") s.Ctx.Close() - log.Debug("ctx closed") + s.Debug("ctx closed") }) } diff --git a/modules/net_sniff/net_sniff_fuzz.go b/modules/net_sniff/net_sniff_fuzz.go index a48b11b2..ef05b9d2 100644 --- a/modules/net_sniff/net_sniff_fuzz.go +++ b/modules/net_sniff/net_sniff_fuzz.go @@ -6,10 +6,7 @@ import ( "github.com/google/gopacket" - "github.com/bettercap/bettercap/log" - "github.com/evilsocket/islazy/str" - "github.com/evilsocket/islazy/tui" ) var mutators = []func(byte) byte{ @@ -60,13 +57,13 @@ func (s *Sniffer) doFuzzing(pkt gopacket.Packet) { } if bytesChanged > 0 { - logFn := log.Info + logFn := s.Info if s.fuzzSilent { - logFn = log.Debug + logFn = s.Debug } - logFn("[%s] changed %d bytes in %d layers.", tui.Green("net.fuzz"), bytesChanged, layersChanged) + logFn("changed %d bytes in %d layers.", bytesChanged, layersChanged) if err := s.Session.Queue.Send(pkt.Data()); err != nil { - log.Error("error sending fuzzed packet: %s", err) + s.Error("error sending fuzzed packet: %s", err) } } } @@ -110,7 +107,7 @@ func (s *Sniffer) StartFuzzing() error { s.fuzzActive = true - log.Info("[%s] active on layer types %s (rate:%f ratio:%f)", tui.Green("net.fuzz"), strings.Join(s.fuzzLayers, ","), s.fuzzRate, s.fuzzRatio) + s.Info("active on layer types %s (rate:%f ratio:%f)", strings.Join(s.fuzzLayers, ","), s.fuzzRate, s.fuzzRatio) return nil } diff --git a/modules/packet_proxy/packet_proxy_linux_amd64.go b/modules/packet_proxy/packet_proxy_linux_amd64.go index 11f753a8..93f015f1 100644 --- a/modules/packet_proxy/packet_proxy_linux_amd64.go +++ b/modules/packet_proxy/packet_proxy_linux_amd64.go @@ -9,7 +9,6 @@ import ( "syscall" "github.com/bettercap/bettercap/core" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/chifflier/nfqueue-go/nfqueue" @@ -122,7 +121,7 @@ func (pp *PacketProxy) runRule(enable bool) (err error) { "--queue-bypass", }...) - log.Debug("iptables %s", args) + pp.Debug("iptables %s", args) _, err = core.Exec("iptables", args) return @@ -149,7 +148,7 @@ func (pp *PacketProxy) Configure() (err error) { return fmt.Errorf("%s does not exist.", pp.pluginPath) } - log.Info("loading packet proxy plugin from %s ...", pp.pluginPath) + pp.Info("loading packet proxy plugin from %s ...", pp.pluginPath) var ok bool var sym plugin.Symbol @@ -197,7 +196,7 @@ func (pp *PacketProxy) Start() error { } return pp.SetRunning(true, func() { - log.Info("%s started on queue number %d", tui.Green("packet.proxy"), pp.queueNum) + pp.Info("started on queue number %d", pp.queueNum) defer pp.destroyQueue() diff --git a/modules/prober/net_probe.go b/modules/prober/net_probe.go index d701f43f..973bc29b 100644 --- a/modules/prober/net_probe.go +++ b/modules/prober/net_probe.go @@ -4,7 +4,6 @@ import ( "sync" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/session" @@ -91,7 +90,7 @@ func (p *Prober) Configure() error { } else if err, p.probes.WSD = p.BoolParam("net.probe.wsd"); err != nil { return err } else { - log.Debug("Throttling packets of %d ms.", p.throttle) + p.Debug("Throttling packets of %d ms.", p.throttle) } return nil } @@ -106,13 +105,13 @@ func (p *Prober) Start() error { defer p.waitGroup.Done() if p.Session.Interface.IpAddress == network.MonitorModeAddress { - log.Info("Interface is in monitor mode, skipping net.probe") + p.Info("Interface is in monitor mode, skipping net.probe") return } list, err := iprange.Parse(p.Session.Interface.CIDR()) if err != nil { - log.Fatal("%s", err) + p.Fatal("%s", err) } from := p.Session.Interface.IP @@ -137,7 +136,7 @@ func (p *Prober) Start() error { if !p.Running() { return } else if p.Session.Skip(ip) { - log.Debug("skipping address %s from probing.", ip) + p.Debug("skipping address %s from probing.", ip) continue } else if p.probes.NBNS { p.sendProbeNBNS(from, from_hw, ip) diff --git a/modules/prober/net_probe_mdns.go b/modules/prober/net_probe_mdns.go index 959c6db6..df142085 100644 --- a/modules/prober/net_probe_mdns.go +++ b/modules/prober/net_probe_mdns.go @@ -3,18 +3,17 @@ package prober import ( "net" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" ) func (p *Prober) sendProbeMDNS(from net.IP, from_hw net.HardwareAddr) { err, raw := packets.NewMDNSProbe(from, from_hw) if err != nil { - log.Error("error while sending mdns probe: %v", err) + p.Error("error while sending mdns probe: %v", err) return } else if err := p.Session.Queue.Send(raw); err != nil { - log.Error("error sending mdns packet: %s", err) + p.Error("error sending mdns packet: %s", err) } else { - log.Debug("sent %d bytes of MDNS probe", len(raw)) + p.Debug("sent %d bytes of MDNS probe", len(raw)) } } diff --git a/modules/prober/net_probe_nbns.go b/modules/prober/net_probe_nbns.go index 079a1394..f7d8206e 100644 --- a/modules/prober/net_probe_nbns.go +++ b/modules/prober/net_probe_nbns.go @@ -4,16 +4,15 @@ import ( "fmt" "net" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" ) func (p *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 { - log.Debug("could not resolve %s.", name) + p.Debug("could not resolve %s.", name) } else if con, err := net.DialUDP("udp", nil, addr); err != nil { - log.Debug("could not dial %s.", name) + p.Debug("could not dial %s.", name) } else { defer con.Close() if wrote, _ := con.Write(packets.NBNSRequest); wrote > 0 { diff --git a/modules/prober/net_probe_upnp.go b/modules/prober/net_probe_upnp.go index 5c1b01da..397b7422 100644 --- a/modules/prober/net_probe_upnp.go +++ b/modules/prober/net_probe_upnp.go @@ -4,16 +4,15 @@ import ( "fmt" "net" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" ) func (p *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 { - log.Debug("could not resolve %s.", name) + p.Debug("could not resolve %s.", name) } else if con, err := net.DialUDP("udp", nil, addr); err != nil { - log.Debug("could not dial %s.", name) + p.Debug("could not dial %s.", name) } else { defer con.Close() if wrote, _ := con.Write(packets.UPNPDiscoveryPayload); wrote > 0 { diff --git a/modules/prober/net_probe_wsd.go b/modules/prober/net_probe_wsd.go index b17795e4..b9fcf99a 100644 --- a/modules/prober/net_probe_wsd.go +++ b/modules/prober/net_probe_wsd.go @@ -4,16 +4,15 @@ import ( "fmt" "net" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" ) func (p *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 { - log.Debug("could not resolve %s.", name) + p.Debug("could not resolve %s.", name) } else if con, err := net.DialUDP("udp", nil, addr); err != nil { - log.Debug("could not dial %s.", name) + p.Debug("could not dial %s.", name) } else { defer con.Close() if wrote, _ := con.Write(packets.WSDDiscoveryPayload); wrote > 0 { diff --git a/modules/syn_scan/syn_scan.go b/modules/syn_scan/syn_scan.go index 298abb84..bc049a40 100644 --- a/modules/syn_scan/syn_scan.go +++ b/modules/syn_scan/syn_scan.go @@ -8,14 +8,12 @@ import ( "sync/atomic" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" "github.com/malfunkt/iprange" "github.com/evilsocket/islazy/str" - "github.com/evilsocket/islazy/tui" ) const synSourcePort = 666 @@ -157,8 +155,7 @@ func plural(n uint64) string { func (s *SynScanner) showProgress() error { progress := 100.0 * (float64(s.stats.doneProbes) / float64(s.stats.totProbes)) - log.Info("[%s] [%.2f%%] found %d open port%s for %d address%s, sent %d/%d packets in %s", - tui.Green("syn.scan"), + s.Info("[%.2f%%] found %d open port%s for %d address%s, sent %d/%d packets in %s", progress, s.stats.openPorts, plural(s.stats.openPorts), @@ -171,7 +168,7 @@ func (s *SynScanner) showProgress() error { } func (s *SynScanner) Stop() error { - log.Info("[%s] stopping ...", tui.Green("syn.scan")) + s.Info("stopping ...") return s.SetRunning(false, func() { s.waitGroup.Wait() s.showProgress() @@ -197,9 +194,9 @@ func (s *SynScanner) synScan() error { } if s.stats.numPorts > 1 { - log.Info("scanning %d address%s from port %d to port %d ...", s.stats.numAddresses, plural, s.startPort, s.endPort) + s.Info("scanning %d address%s from port %d to port %d ...", s.stats.numAddresses, plural, s.startPort, s.endPort) } else { - log.Info("scanning %d address%s on port %d ...", s.stats.numAddresses, plural, s.startPort) + s.Info("scanning %d address%s on port %d ...", s.stats.numAddresses, plural, s.startPort) } // set the collector @@ -226,7 +223,7 @@ func (s *SynScanner) synScan() error { mac, err := s.Session.FindMAC(address, true) if err != nil { atomic.AddUint64(&s.stats.doneProbes, s.stats.numPorts) - log.Debug("Could not get MAC for %s: %s", address.String(), err) + s.Debug("could not get MAC for %s: %s", address.String(), err) continue } @@ -239,14 +236,14 @@ func (s *SynScanner) synScan() error { err, raw := packets.NewTCPSyn(s.Session.Interface.IP, s.Session.Interface.HW, address, mac, synSourcePort, dstPort) if err != nil { - log.Error("Error creating SYN packet: %s", err) + s.Error("error creating SYN packet: %s", err) continue } if err := s.Session.Queue.Send(raw); err != nil { - log.Error("Error sending SYN packet: %s", err) + s.Error("error sending SYN packet: %s", err) } else { - log.Debug("Sent %d bytes of SYN packet to %s for port %d", len(raw), address.String(), dstPort) + s.Debug("sent %d bytes of SYN packet to %s for port %d", len(raw), address.String(), dstPort) } time.Sleep(time.Duration(10) * time.Millisecond) diff --git a/modules/tcp_proxy/tcp_proxy.go b/modules/tcp_proxy/tcp_proxy.go index 3db45b6b..601c4424 100644 --- a/modules/tcp_proxy/tcp_proxy.go +++ b/modules/tcp_proxy/tcp_proxy.go @@ -7,7 +7,6 @@ import ( "sync" "github.com/bettercap/bettercap/firewall" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" ) @@ -125,12 +124,12 @@ func (p *TcpProxy) Configure() error { if err, p.script = LoadTcpProxyScript(scriptPath, p.Session); err != nil { return err } else { - log.Debug("TCP proxy script %s loaded.", scriptPath) + p.Debug("script %s loaded.", scriptPath) } } if !p.Session.Firewall.IsForwardingEnabled() { - log.Info("Enabling forwarding.") + p.Info("enabling forwarding.") p.Session.Firewall.EnableForwarding(true) } @@ -146,7 +145,7 @@ func (p *TcpProxy) Configure() error { return err } - log.Debug("Applied redirection %s", p.Redirection.String()) + p.Debug("applied redirection %s", p.Redirection.String()) return nil } @@ -159,7 +158,7 @@ func (p *TcpProxy) doPipe(from, to net.Addr, src, dst io.ReadWriter, wg *sync.Wa n, err := src.Read(buff) if err != nil { if err.Error() != "EOF" { - log.Warning("Read failed: %s", err) + p.Warning("read failed: %s", err) } return } @@ -170,7 +169,7 @@ func (p *TcpProxy) doPipe(from, to net.Addr, src, dst io.ReadWriter, wg *sync.Wa if ret != nil { nret := len(ret) - log.Info("Overriding %d bytes of data from %s to %s with %d bytes of new data.", + p.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) @@ -179,28 +178,28 @@ func (p *TcpProxy) doPipe(from, to net.Addr, src, dst io.ReadWriter, wg *sync.Wa n, err = dst.Write(b) if err != nil { - log.Warning("Write failed: %s", err) + p.Warning("write failed: %s", err) return } - log.Debug("%s -> %s : %d bytes", from.String(), to.String(), n) + p.Debug("%s -> %s : %d bytes", from.String(), to.String(), n) } } func (p *TcpProxy) handleConnection(c *net.TCPConn) { defer c.Close() - log.Info("TCP proxy got a connection from %s", c.RemoteAddr().String()) + p.Info("got a connection from %s", c.RemoteAddr().String()) // tcp tunnel enabled if p.tunnelAddr.IP.To4() != nil { - log.Info("TCP tunnel started ( %s -> %s )", p.remoteAddr.String(), p.tunnelAddr.String()) + p.Info("tcp tunnel started ( %s -> %s )", p.remoteAddr.String(), p.tunnelAddr.String()) p.remoteAddr = p.tunnelAddr } remote, err := net.DialTCP("tcp", nil, p.remoteAddr) if err != nil { - log.Warning("Error while connecting to remote %s: %s", p.remoteAddr.String(), err) + p.Warning("error while connecting to remote %s: %s", p.remoteAddr.String(), err) return } defer remote.Close() @@ -221,12 +220,12 @@ func (p *TcpProxy) Start() error { } return p.SetRunning(true, func() { - log.Info("TCP proxy started ( x -> %s -> %s )", p.localAddr.String(), p.remoteAddr.String()) + p.Info("started ( x -> %s -> %s )", p.localAddr.String(), p.remoteAddr.String()) for p.Running() { conn, err := p.listener.AcceptTCP() if err != nil { - log.Warning("Error while accepting TCP connection: %s", err) + p.Warning("error while accepting TCP connection: %s", err) continue } @@ -238,7 +237,7 @@ func (p *TcpProxy) Start() error { func (p *TcpProxy) Stop() error { if p.Redirection != nil { - log.Debug("Disabling redirection %s", p.Redirection.String()) + p.Debug("disabling redirection %s", p.Redirection.String()) if err := p.Session.Firewall.EnableRedirection(p.Redirection, false); err != nil { return err } diff --git a/modules/tcp_proxy/tcp_proxy_script.go b/modules/tcp_proxy/tcp_proxy_script.go index 056e348c..0fc7864d 100644 --- a/modules/tcp_proxy/tcp_proxy_script.go +++ b/modules/tcp_proxy/tcp_proxy_script.go @@ -27,14 +27,14 @@ func LoadTcpProxyScript(path string, sess *session.Session) (err error, s *TcpPr // define session pointer if err = plug.Set("env", sess.Env.Data); err != nil { - log.Error("Error while defining environment: %+v", err) + 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()) + log.Error("error while executing onLoad callback: %s", "\ntraceback:\n "+err.(*otto.Error).String()) return } } @@ -52,12 +52,12 @@ func (s *TcpProxyScript) OnData(from, to net.Addr, data []byte) []byte { addrTo := strings.Split(to.String(), ":")[0] if ret, err := s.Call("onData", addrFrom, addrTo, data); err != nil { - log.Error("Error while executing onData callback: %s", err) + 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) + log.Error("error while casting exported value to array of byte: value = %+v", ret) } return array } diff --git a/modules/ticker/ticker.go b/modules/ticker/ticker.go index 9fec897c..4dfc965b 100644 --- a/modules/ticker/ticker.go +++ b/modules/ticker/ticker.go @@ -3,7 +3,6 @@ package ticker import ( "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" ) @@ -79,7 +78,7 @@ func (t *Ticker) Start() error { } return t.SetRunning(true, func() { - log.Info("ticker running with period %.fs.", t.Period.Seconds()) + t.Info("running with period %.fs", t.Period.Seconds()) tick := time.NewTicker(t.Period) for range tick.C { if !t.Running() { @@ -88,7 +87,7 @@ func (t *Ticker) Start() error { for _, cmd := range t.Commands { if err := t.Session.Run(cmd); err != nil { - log.Error("%s", err) + t.Error("%s", err) } } } diff --git a/modules/update/update.go b/modules/update/update.go index 972250d5..7db74f6c 100644 --- a/modules/update/update.go +++ b/modules/update/update.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/bettercap/bettercap/core" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/session" "github.com/google/go-github/github" @@ -82,17 +81,17 @@ func (u *UpdateModule) Start() error { return u.SetRunning(true, func() { defer u.SetRunning(false, nil) - log.Info("checking latest stable release ...") + u.Info("checking latest stable release ...") if releases, _, err := u.client.Repositories.ListReleases(context.Background(), "bettercap", "bettercap", nil); err == nil { latest := releases[0] if u.versionToNum(core.Version) < u.versionToNum(*latest.TagName) { u.Session.Events.Add("update.available", latest) } else { - log.Info("you are running %s which is the latest stable version.", tui.Bold(core.Version)) + u.Info("you are running %s which is the latest stable version.", tui.Bold(core.Version)) } } else { - log.Error("error while fetching latest release info from GitHub: %s", err) + u.Error("error while fetching latest release info from GitHub: %s", err) } }) } diff --git a/modules/wifi/wifi.go b/modules/wifi/wifi.go index 59e21f48..16339328 100644 --- a/modules/wifi/wifi.go +++ b/modules/wifi/wifi.go @@ -2,13 +2,13 @@ package wifi import ( "fmt" - "github.com/bettercap/bettercap/modules/utils" + "net" "strconv" "sync" "time" - "github.com/bettercap/bettercap/log" + "github.com/bettercap/bettercap/modules/utils" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" @@ -224,7 +224,7 @@ func NewWiFiModule(s *session.Session) *WiFiModule { freqs := []int{} if args[0] != "clear" { - log.Debug("setting hopping channels to %s", args[0]) + w.Debug("setting hopping channels to %s", args[0]) for _, s := range str.Comma(args[0]) { if ch, err := strconv.Atoi(s); err != nil { return err @@ -239,13 +239,13 @@ func NewWiFiModule(s *session.Session) *WiFiModule { } if len(freqs) == 0 { - log.Debug("resetting hopping channels") + w.Debug("resetting hopping channels") if freqs, err = network.GetSupportedFrequencies(w.Session.Interface.Name()); err != nil { return err } } - log.Debug("new frequencies: %v", freqs) + w.Debug("new frequencies: %v", freqs) w.frequencies = freqs // if wifi.recon is not running, this would block forever @@ -338,7 +338,7 @@ func (w *WiFiModule) Configure() error { return fmt.Errorf("error while setting timeout: %s", err) } else if w.handle, err = ihandle.Activate(); err != nil { if retry == 0 && err.Error() == ErrIfaceNotUp { - log.Warning("interface %s is down, bringing it up ...", ifName) + w.Warning("interface %s is down, bringing it up ...", ifName) if err := network.ActivateInterface(ifName); err != nil { return err } @@ -366,14 +366,14 @@ func (w *WiFiModule) Configure() error { return fmt.Errorf("error while getting supported frequencies of %s: %s", ifName, err) } - log.Debug("wifi supported frequencies: %v", w.frequencies) + w.Debug("wifi supported frequencies: %v", w.frequencies) // we need to start somewhere, this is just to check if // this OS supports switching channel programmatically. if err = network.SetInterfaceChannel(ifName, 1); err != nil { return fmt.Errorf("error while initializing %s to channel 1: %s", ifName, err) } - log.Info("wifi.recon started (min rssi: %d dBm)", w.minRSSI) + w.Info("started (min rssi: %d dBm)", w.minRSSI) } } @@ -448,7 +448,7 @@ func (w *WiFiModule) Start() error { if ok, radiotap, dot11 := packets.Dot11Parse(packet); ok { // check FCS checksum if w.skipBroken && !dot11.ChecksumValid() { - log.Debug("Skipping dot11 packet with invalid checksum.") + w.Debug("skipping dot11 packet with invalid checksum.") continue } diff --git a/modules/wifi/wifi_ap.go b/modules/wifi/wifi_ap.go index 65da8e2c..751e9568 100644 --- a/modules/wifi/wifi_ap.go +++ b/modules/wifi/wifi_ap.go @@ -5,7 +5,6 @@ import ( "net" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" @@ -49,7 +48,7 @@ func (w *WiFiModule) startAp() error { if !w.apConfig.Encryption { enc = tui.Green("Open") } - log.Info("Sending beacons as SSID %s (%s) on channel %d (%s).", + w.Info("sending beacons as SSID %s (%s) on channel %d (%s).", tui.Bold(w.apConfig.SSID), w.apConfig.BSSID.String(), w.apConfig.Channel, @@ -60,7 +59,7 @@ func (w *WiFiModule) startAp() error { defer w.writes.Done() if err, pkt := packets.NewDot11Beacon(w.apConfig, seqn); err != nil { - log.Error("Could not create beacon packet: %s", err) + w.Error("could not create beacon packet: %s", err) } else { w.injectPacket(pkt) } diff --git a/modules/wifi/wifi_assoc.go b/modules/wifi/wifi_assoc.go index 9b644352..89483a30 100644 --- a/modules/wifi/wifi_assoc.go +++ b/modules/wifi/wifi_assoc.go @@ -6,20 +6,19 @@ import ( "net" "sort" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" ) func (w *WiFiModule) sendAssocPacket(ap *network.AccessPoint) { if err, pkt := packets.NewDot11Auth(w.Session.Interface.HW, ap.HW, 1); err != nil { - log.Error("cloud not create auth packet: %s", err) + w.Error("cloud not create auth packet: %s", err) } else { w.injectPacket(pkt) } if err, pkt := packets.NewDot11AssociationRequest(w.Session.Interface.HW, ap.HW, ap.ESSID(), 1); err != nil { - log.Error("cloud not create association request packet: %s", err) + w.Error("cloud not create association request packet: %s", err) } else { w.injectPacket(pkt) } @@ -36,7 +35,7 @@ func (w *WiFiModule) skipAssoc(to net.HardwareAddr) bool { func (w *WiFiModule) isAssocSilent() bool { if err, is := w.BoolParam("wifi.assoc.silent"); err != nil { - log.Warning("%v", err) + w.Warning("%v", err) } else { w.assocSilent = is } @@ -45,7 +44,7 @@ func (w *WiFiModule) isAssocSilent() bool { func (w *WiFiModule) doAssocOpen() bool { if err, is := w.BoolParam("wifi.assoc.open"); err != nil { - log.Warning("%v", err) + w.Warning("%v", err) } else { w.assocOpen = is } @@ -78,7 +77,7 @@ func (w *WiFiModule) startAssoc(to net.HardwareAddr) error { if !w.skipAssoc(ap.HW) { toAssoc = append(toAssoc, ap) } else { - log.Debug("skipping ap:%v because skip list %v", ap, w.assocSkip) + w.Debug("skipping ap:%v because skip list %v", ap, w.assocSkip) } } } @@ -104,13 +103,13 @@ func (w *WiFiModule) startAssoc(to net.HardwareAddr) error { // send the association request frames for _, ap := range toAssoc { if w.Running() { - logger := log.Info + logger := w.Info if w.isAssocSilent() { - logger = log.Debug + logger = w.Debug } if ap.IsOpen() && !w.doAssocOpen() { - log.Debug("skipping association for open network %s (wifi.assoc.open is false)", ap.ESSID()) + w.Debug("skipping association for open network %s (wifi.assoc.open is false)", ap.ESSID()) } else { logger("sending association request to AP %s (channel:%d encryption:%s)", ap.ESSID(), ap.Channel(), ap.Encryption) diff --git a/modules/wifi/wifi_deauth.go b/modules/wifi/wifi_deauth.go index 1a05ac7c..db663634 100644 --- a/modules/wifi/wifi_deauth.go +++ b/modules/wifi/wifi_deauth.go @@ -7,14 +7,13 @@ import ( "sort" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" ) func (w *WiFiModule) injectPacket(data []byte) { if err := w.handle.WritePacketData(data); err != nil { - log.Error("cloud not inject WiFi packet: %s", err) + w.Error("could not inject WiFi packet: %s", err) w.Session.Queue.TrackError() } else { w.Session.Queue.TrackSent(uint64(len(data))) @@ -26,14 +25,14 @@ func (w *WiFiModule) injectPacket(data []byte) { func (w *WiFiModule) sendDeauthPacket(ap net.HardwareAddr, client net.HardwareAddr) { for seq := uint16(0); seq < 64 && w.Running(); seq++ { if err, pkt := packets.NewDot11Deauth(ap, client, ap, seq); err != nil { - log.Error("cloud not create deauth packet: %s", err) + w.Error("could not create deauth packet: %s", err) continue } else { w.injectPacket(pkt) } if err, pkt := packets.NewDot11Deauth(client, ap, ap, seq); err != nil { - log.Error("cloud not create deauth packet: %s", err) + w.Error("could not create deauth packet: %s", err) continue } else { w.injectPacket(pkt) @@ -52,7 +51,7 @@ func (w *WiFiModule) skipDeauth(to net.HardwareAddr) bool { func (w *WiFiModule) isDeauthSilent() bool { if err, is := w.BoolParam("wifi.deauth.silent"); err != nil { - log.Warning("%v", err) + w.Warning("%v", err) } else { w.deauthSilent = is } @@ -61,7 +60,7 @@ func (w *WiFiModule) isDeauthSilent() bool { func (w *WiFiModule) doDeauthOpen() bool { if err, is := w.BoolParam("wifi.deauth.open"); err != nil { - log.Warning("%v", err) + w.Warning("%v", err) } else { w.deauthOpen = is } @@ -101,7 +100,7 @@ func (w *WiFiModule) startDeauth(to net.HardwareAddr) error { if !w.skipDeauth(ap.HW) && !w.skipDeauth(client.HW) { toDeauth = append(toDeauth, flow{Ap: ap, Client: client}) } else { - log.Debug("skipping ap:%v client:%v because skip list %v", ap, client, w.deauthSkip) + w.Debug("skipping ap:%v client:%v because skip list %v", ap, client, w.deauthSkip) } } } @@ -130,13 +129,13 @@ func (w *WiFiModule) startDeauth(to net.HardwareAddr) error { client := deauth.Client ap := deauth.Ap if w.Running() { - logger := log.Info + logger := w.Info if w.isDeauthSilent() { - logger = log.Debug + logger = w.Debug } if ap.IsOpen() && !w.doDeauthOpen() { - log.Debug("skipping deauth for open network %s (wifi.deauth.open is false)", ap.ESSID()) + w.Debug("skipping deauth for open network %s (wifi.deauth.open is false)", ap.ESSID()) } else { logger("deauthing client %s from AP %s (channel:%d encryption:%s)", client.String(), ap.ESSID(), ap.Channel(), ap.Encryption) diff --git a/modules/wifi/wifi_hopping.go b/modules/wifi/wifi_hopping.go index 374bb016..076915ae 100644 --- a/modules/wifi/wifi_hopping.go +++ b/modules/wifi/wifi_hopping.go @@ -3,7 +3,6 @@ package wifi import ( "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" ) @@ -15,9 +14,9 @@ func (w *WiFiModule) onChannel(channel int, cb func()) { w.stickChan = channel if err := network.SetInterfaceChannel(w.Session.Interface.Name(), channel); err != nil { - log.Warning("error while hopping to channel %d: %s", channel, err) + w.Warning("error while hopping to channel %d: %s", channel, err) } else { - log.Debug("hopped on channel %d", channel) + w.Debug("hopped on channel %d", channel) } cb() @@ -29,7 +28,7 @@ func (w *WiFiModule) channelHopper() { w.reads.Add(1) defer w.reads.Done() - log.Info("channel hopper started.") + w.Info("channel hopper started.") for w.Running() { delay := w.hopPeriod @@ -51,17 +50,17 @@ func (w *WiFiModule) channelHopper() { channel = w.stickChan } - log.Debug("hopping on channel %d", channel) + w.Debug("hopping on channel %d", channel) w.chanLock.Lock() if err := network.SetInterfaceChannel(w.Session.Interface.Name(), channel); err != nil { - log.Warning("error while hopping to channel %d: %s", channel, err) + w.Warning("error while hopping to channel %d: %s", channel, err) } w.chanLock.Unlock() select { case _ = <-w.hopChanges: - log.Debug("hop changed") + w.Debug("hop changed") break loopCurrentChannels case <-time.After(delay): if !w.Running() { diff --git a/modules/wifi/wifi_recon.go b/modules/wifi/wifi_recon.go index 9ef63c59..a733c1f9 100644 --- a/modules/wifi/wifi_recon.go +++ b/modules/wifi/wifi_recon.go @@ -4,14 +4,11 @@ import ( "bytes" "time" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/network" "github.com/bettercap/bettercap/packets" "github.com/google/gopacket" "github.com/google/gopacket/layers" - - "github.com/evilsocket/islazy/tui" ) var maxStationTTL = 5 * time.Minute @@ -20,13 +17,13 @@ func (w *WiFiModule) stationPruner() { w.reads.Add(1) defer w.reads.Done() - log.Debug("wifi stations pruner started.") + w.Debug("wifi stations pruner started.") for w.Running() { // loop every AP for _, ap := range w.Session.WiFi.List() { sinceLastSeen := time.Since(ap.LastSeen) if sinceLastSeen > maxStationTTL { - log.Debug("station %s not seen in %s, removing.", ap.BSSID(), sinceLastSeen) + w.Debug("station %s not seen in %s, removing.", ap.BSSID(), sinceLastSeen) w.Session.WiFi.Remove(ap.BSSID()) continue } @@ -34,7 +31,7 @@ func (w *WiFiModule) stationPruner() { for _, c := range ap.Clients() { sinceLastSeen := time.Since(c.LastSeen) if sinceLastSeen > maxStationTTL { - log.Debug("client %s of station %s not seen in %s, removing.", c.String(), ap.BSSID(), sinceLastSeen) + w.Debug("client %s of station %s not seen in %s, removing.", c.String(), ap.BSSID(), sinceLastSeen) ap.RemoveClient(c.BSSID()) w.Session.Events.Add("wifi.client.lost", WiFiClientEvent{ @@ -75,7 +72,7 @@ func (w *WiFiModule) discoverAccessPoints(radiotap *layers.RadioTap, dot11 *laye }) } } else { - log.Debug("skipping %s with %d dBm", from.String(), radiotap.DBMAntennaSignal) + w.Debug("skipping %s with %d dBm", from.String(), radiotap.DBMAntennaSignal) } } } @@ -151,7 +148,7 @@ func (w *WiFiModule) discoverHandshakes(radiotap *layers.RadioTap, dot11 *layers // first, locate the AP in our list by its BSSID ap, found := w.Session.WiFi.Get(apMac.String()) if !found { - log.Warning("could not find AP with BSSID %s", apMac.String()) + w.Warning("could not find AP with BSSID %s", apMac.String()) return } @@ -176,8 +173,7 @@ func (w *WiFiModule) discoverHandshakes(radiotap *layers.RadioTap, dot11 *layers PMKID = "with PMKID" } - log.Debug("[%s] got frame 1/4 of the %s <-> %s handshake (%s) (anonce:%x)", - tui.Green("wifi"), + w.Debug("got frame 1/4 of the %s <-> %s handshake (%s) (anonce:%x)", apMac, staMac, PMKID, @@ -186,8 +182,7 @@ func (w *WiFiModule) discoverHandshakes(radiotap *layers.RadioTap, dot11 *layers // [2] (MIC) client is sending SNonce+MIC to the API station.Handshake.AddFrame(1, packet) - log.Debug("[%s] got frame 2/4 of the %s <-> %s handshake (snonce:%x mic:%x)", - tui.Green("wifi"), + w.Debug("got frame 2/4 of the %s <-> %s handshake (snonce:%x mic:%x)", apMac, staMac, key.Nonce, @@ -196,8 +191,7 @@ func (w *WiFiModule) discoverHandshakes(radiotap *layers.RadioTap, dot11 *layers // [3]: (INSTALL+ACK+MIC) AP informs the client that the PTK is installed station.Handshake.AddFrame(2, packet) - log.Debug("[%s] got frame 3/4 of the %s <-> %s handshake (mic:%x)", - tui.Green("wifi"), + w.Debug("got frame 3/4 of the %s <-> %s handshake (mic:%x)", apMac, staMac, key.MIC) @@ -207,9 +201,9 @@ func (w *WiFiModule) discoverHandshakes(radiotap *layers.RadioTap, dot11 *layers numUnsaved := station.Handshake.NumUnsaved() doSave := numUnsaved > 0 if doSave && w.shakesFile != "" { - log.Debug("saving handshake frames to %s", w.shakesFile) + w.Debug("saving handshake frames to %s", w.shakesFile) if err := w.Session.WiFi.SaveHandshakesTo(w.shakesFile, w.handle.LinkType()); err != nil { - log.Error("error while saving handshake frames to %s: %s", w.shakesFile, err) + w.Error("error while saving handshake frames to %s: %s", w.shakesFile, err) } } diff --git a/modules/wifi/wifi_show.go b/modules/wifi/wifi_show.go index 6ae5e5b8..139b45ca 100644 --- a/modules/wifi/wifi_show.go +++ b/modules/wifi/wifi_show.go @@ -2,13 +2,13 @@ package wifi import ( "fmt" - "github.com/bettercap/bettercap/modules/discovery" "os" "sort" "strconv" "strings" "time" + "github.com/bettercap/bettercap/modules/discovery" "github.com/bettercap/bettercap/network" "github.com/dustin/go-humanize" diff --git a/modules/wol/wol.go b/modules/wol/wol.go index 9078e727..0deb8d4e 100644 --- a/modules/wol/wol.go +++ b/modules/wol/wol.go @@ -5,7 +5,6 @@ import ( "net" "regexp" - "github.com/bettercap/bettercap/log" "github.com/bettercap/bettercap/packets" "github.com/bettercap/bettercap/session" @@ -105,7 +104,7 @@ func (w *WOL) wolETH(mac string) error { defer w.SetRunning(false, nil) payload := buildPayload(mac) - log.Info("Sending %d bytes of ethernet WOL packet to %s", len(payload), tui.Bold(mac)) + w.Info("sending %d bytes of ethernet WOL packet to %s", len(payload), tui.Bold(mac)) eth := layers.Ethernet{ SrcMAC: w.Session.Interface.HW, DstMAC: layers.EthernetBroadcast, @@ -126,7 +125,7 @@ func (w *WOL) wolUDP(mac string) error { defer w.SetRunning(false, nil) payload := buildPayload(mac) - log.Info("Sending %d bytes of UDP WOL packet to %s", len(payload), tui.Bold(mac)) + w.Info("sending %d bytes of UDP WOL packet to %s", len(payload), tui.Bold(mac)) eth := layers.Ethernet{ SrcMAC: w.Session.Interface.HW, diff --git a/session/module.go b/session/module.go index 89dd05d9..fda87b06 100644 --- a/session/module.go +++ b/session/module.go @@ -7,6 +7,7 @@ import ( "sync" "time" + "github.com/evilsocket/islazy/log" "github.com/evilsocket/islazy/str" "github.com/evilsocket/islazy/tui" ) @@ -31,6 +32,11 @@ type SessionModule struct { handlers []ModuleHandler params map[string]*ModuleParam + tag string +} + +func AsTag(name string) string { + return fmt.Sprintf("%s ", tui.Wrap(tui.BACKLIGHTBLUE, tui.Wrap(tui.FOREBLACK, name))) } func NewSessionModule(name string, s *Session) SessionModule { @@ -42,11 +48,32 @@ func NewSessionModule(name string, s *Session) SessionModule { handlers: make([]ModuleHandler, 0), params: make(map[string]*ModuleParam), + tag: AsTag(name), } return m } +func (m *SessionModule) Debug(format string, args ...interface{}) { + m.Session.Events.Log(log.DEBUG, m.tag+format, args...) +} + +func (m *SessionModule) Info(format string, args ...interface{}) { + m.Session.Events.Log(log.INFO, m.tag+format, args...) +} + +func (m *SessionModule) Warning(format string, args ...interface{}) { + m.Session.Events.Log(log.WARNING, m.tag+format, args...) +} + +func (m *SessionModule) Error(format string, args ...interface{}) { + m.Session.Events.Log(log.ERROR, m.tag+format, args...) +} + +func (m *SessionModule) Fatal(format string, args ...interface{}) { + m.Session.Events.Log(log.FATAL, m.tag+format, args...) +} + func (m *SessionModule) Handlers() []ModuleHandler { return m.handlers }