1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
|
package packets
import (
"encoding/json"
"fmt"
"net"
"sync"
"sync/atomic"
"github.com/bettercap/bettercap/network"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
)
type Activity struct {
IP net.IP
MAC net.HardwareAddr
Meta map[string]string
Source bool
}
type Traffic struct {
Sent uint64 `json:"sent"`
Received uint64 `json:"received"`
}
type Stats struct {
Sent uint64 `json:"sent"`
Received uint64 `json:"received"`
PktReceived uint64 `json:"pkts_received"`
Errors uint64 `json:"errors"`
}
type Queue struct {
sync.RWMutex
// keep on top because of https://github.com/bettercap/bettercap/issues/500
Stats Stats
Protos sync.Map
Traffic sync.Map
Activities chan Activity
iface *network.Endpoint
handle *pcap.Handle
source *gopacket.PacketSource
srcChannel chan gopacket.Packet
writes *sync.WaitGroup
active bool
}
type queueJSON struct {
Stats Stats `json:"stats"`
Protos map[string]int `json:"protos"`
Traffic map[string]*Traffic `json:"traffic"`
}
func NewQueue(iface *network.Endpoint) (q *Queue, err error) {
q = &Queue{
Protos: sync.Map{},
Traffic: sync.Map{},
Stats: Stats{},
Activities: make(chan Activity),
writes: &sync.WaitGroup{},
iface: iface,
active: !iface.IsMonitor(),
}
if q.active {
if q.handle, err = network.Capture(iface.Name()); err != nil {
return
}
q.source = gopacket.NewPacketSource(q.handle, q.handle.LinkType())
q.srcChannel = q.source.Packets()
go q.worker()
}
return
}
func (q *Queue) MarshalJSON() ([]byte, error) {
q.Lock()
defer q.Unlock()
doc := queueJSON{
Stats: q.Stats,
Protos: make(map[string]int),
Traffic: make(map[string]*Traffic),
}
q.Protos.Range(func(k, v interface{}) bool {
doc.Protos[k.(string)] = v.(int)
return true
})
q.Traffic.Range(func(k, v interface{}) bool {
doc.Traffic[k.(string)] = v.(*Traffic)
return true
})
return json.Marshal(doc)
}
func (q *Queue) trackProtocols(pkt gopacket.Packet) {
// gather protocols stats
pktLayers := pkt.Layers()
for _, layer := range pktLayers {
proto := layer.LayerType()
if proto == gopacket.LayerTypeDecodeFailure || proto == gopacket.LayerTypePayload {
continue
}
name := proto.String()
if v, found := q.Protos.Load(name); !found {
q.Protos.Store(name, 1)
} else {
q.Protos.Store(name, v.(int)+1)
}
}
}
func (q *Queue) trackActivity(eth *layers.Ethernet, address net.IP, meta map[string]string, pktSize uint64, isSent bool) {
// push to activity channel
q.Activities <- Activity{
IP: address,
MAC: eth.SrcMAC,
Meta: meta,
Source: isSent,
}
// initialize or update stats
addr := address.String()
if v, found := q.Traffic.Load(addr); !found {
if isSent {
q.Traffic.Store(addr, &Traffic{Sent: pktSize})
} else {
q.Traffic.Store(addr, &Traffic{Received: pktSize})
}
} else {
if isSent {
v.(*Traffic).Sent += pktSize
} else {
v.(*Traffic).Received += pktSize
}
}
}
func (q *Queue) TrackPacket(size uint64) {
// https://github.com/bettercap/bettercap/issues/500
if q == nil {
panic("track packet on nil queue!")
}
atomic.AddUint64(&q.Stats.PktReceived, 1)
atomic.AddUint64(&q.Stats.Received, size)
}
func (q *Queue) TrackSent(size uint64) {
atomic.AddUint64(&q.Stats.Sent, size)
}
func (q *Queue) TrackError() {
atomic.AddUint64(&q.Stats.Errors, 1)
}
func (q *Queue) getPacketMeta(pkt gopacket.Packet) map[string]string {
meta := make(map[string]string)
if mdns := MDNSGetMeta(pkt); mdns != nil {
meta = mdns
} else if nbns := NBNSGetMeta(pkt); nbns != nil {
meta = nbns
} else if upnp := UPNPGetMeta(pkt); upnp != nil {
meta = upnp
}
return meta
}
func (q *Queue) worker() {
for pkt := range q.srcChannel {
if !q.active {
return
}
q.trackProtocols(pkt)
pktSize := uint64(len(pkt.Data()))
q.TrackPacket(pktSize)
// decode eth and ipv4/6 layers
leth := pkt.Layer(layers.LayerTypeEthernet)
lip4 := pkt.Layer(layers.LayerTypeIPv4)
lip6 := pkt.Layer(layers.LayerTypeIPv6)
if leth != nil && (lip4 != nil || lip6 != nil) {
var srcIP, dstIP net.IP
if lip4 != nil {
ip4 := lip4.(*layers.IPv4)
srcIP = ip4.SrcIP
dstIP = ip4.DstIP
} else {
ip6 := lip6.(*layers.IPv6)
srcIP = ip6.SrcIP
dstIP = ip6.DstIP
}
// here we try to discover new hosts
// on this lan by inspecting packets
// we manage to sniff
eth := leth.(*layers.Ethernet)
// something coming from someone on the LAN
isFromMe := q.iface.IP.Equal(srcIP) || q.iface.IPv6.Equal(srcIP)
isFromLAN := q.iface.Net.Contains(srcIP)
if !isFromMe && isFromLAN {
meta := q.getPacketMeta(pkt)
q.trackActivity(eth, srcIP, meta, pktSize, true)
}
// something going to someone on the LAN
isToMe := q.iface.IP.Equal(dstIP) || q.iface.IPv6.Equal(dstIP)
isToLAN := q.iface.Net.Contains(dstIP)
if !isToMe && isToLAN {
q.trackActivity(eth, dstIP, nil, pktSize, false)
}
}
}
}
func (q *Queue) Send(raw []byte) error {
q.Lock()
defer q.Unlock()
if !q.active {
return fmt.Errorf("Packet queue is not active.")
}
q.writes.Add(1)
defer q.writes.Done()
if err := q.handle.WritePacketData(raw); err != nil {
q.TrackError()
return err
} else {
q.TrackSent(uint64(len(raw)))
}
return nil
}
func (q *Queue) Stop() {
q.Lock()
defer q.Unlock()
if q.active {
// wait for write operations to be completed
q.writes.Wait()
// signal the main loop to exit and close the handle
q.active = false
q.srcChannel <- nil
q.handle.Close()
}
}
|