/
interfaces.go
106 lines (93 loc) · 2.5 KB
/
interfaces.go
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
package main
import (
"fmt"
"github.com/google/gopacket/pcap"
log "github.com/sirupsen/logrus"
)
// Interfaces is a map between interface name and pcap data structure
var Interfaces = map[string]pcap.Interface{}
func initializeInterface(l *Listen) {
// find our interface via libpcap
getConfiguredInterfaces()
if len(Interfaces[l.iname].Addresses) == 0 {
log.Fatalf("%s is not configured", l.iname)
}
// configure libpcap listener
inactive, err := pcap.NewInactiveHandle(l.iname)
if err != nil {
log.Fatalf("%s: %s", l.iname, err)
}
defer inactive.CleanUp()
// set our timeout
err = inactive.SetTimeout(l.timeout)
if err != nil {
log.Fatalf("%s: %s", l.iname, err)
}
// Promiscuous mode on/off
err = inactive.SetPromisc(l.promisc)
if err != nil {
log.Fatalf("%s: %s", l.iname, err)
}
// Get the entire packet
err = inactive.SetSnapLen(9000)
if err != nil {
log.Fatalf("%s: %s", l.iname, err)
}
// activate libpcap handle
if l.handle, err = inactive.Activate(); err != nil {
log.Fatalf("%s: %s", l.iname, err)
}
if !isValidLayerType(l.handle.LinkType()) {
log.Fatalf("%s: has an invalid layer type: %s", l.iname, l.handle.LinkType().String())
}
// set our BPF filter
bpf_filter := buildBPFFilter(l.ports, Interfaces[l.iname].Addresses, l.promisc)
log.Debugf("%s: applying BPF Filter: %s", l.iname, bpf_filter)
err = l.handle.SetBPFFilter(bpf_filter)
if err != nil {
log.Fatalf("%s: %s", l.iname, err)
}
// just inbound packets
err = l.handle.SetDirection(pcap.DirectionIn)
if err != nil {
log.Fatalf("%s: %s", l.iname, err)
}
log.Debugf("Opened pcap handle on %s", l.iname)
}
// Uses libpcap to get a list of configured interfaces
// and populate the Interfaces.
func getConfiguredInterfaces() {
if len(Interfaces) > 0 {
return
}
ifs, err := pcap.FindAllDevs()
if err != nil {
log.Fatal(err)
}
for _, i := range ifs {
if len(i.Addresses) == 0 {
continue
}
Interfaces[i.Name] = i
}
}
// Print out a list of all the interfaces that libpcap sees
func listInterfaces() {
getConfiguredInterfaces()
for k, v := range Interfaces {
fmt.Printf("Interface: %s\n", k)
for _, a := range v.Addresses {
ones, _ := a.Netmask.Size()
if a.Broadaddr != nil {
fmt.Printf("\t- IP: %s/%d Broadaddr: %s\n",
a.IP.String(), ones, a.Broadaddr.String())
} else if a.P2P != nil {
fmt.Printf("\t- IP: %s/%d PointToPoint: %s\n",
a.IP.String(), ones, a.P2P.String())
} else {
fmt.Printf("\t- IP: %s/%d\n", a.IP.String(), ones)
}
}
fmt.Printf("\n")
}
}