Debian Codegraph @

network/net.go

raw symbols SCIP
1 package network
2
3 import (
4 "errors"
5 "fmt"
6 "net"
7 "regexp"
8 "strings"
9
10 "github.com/bettercap/bettercap/core"
11
12 "github.com/evilsocket/islazy/data"
13 "github.com/evilsocket/islazy/str"
14 "github.com/evilsocket/islazy/tui"
15
16 "github.com/malfunkt/iprange"
17 )
18
19 var ErrNoIfaces = errors.New("No active interfaces found.")
20 var ErrNoGateway = errors.New("Could not detect gateway.")
21
22 const (
23 MonitorModeAddress = "0.0.0.0"
24 BroadcastSuffix = ".255"
25 BroadcastMac = "ff:ff:ff:ff:ff:ff"
26 IPv4MulticastStart = "01:00:5e:00:00:00"
27 IPv4MulticastEnd = "01:00:5e:7f:ff:ff"
28 )
29
30 var (
31 BroadcastHw = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
32 IPv4BlockValidator = regexp.MustCompile(`^` +
33 `(?:(?:25[0-5]|2[0-4][0-9]|[1][0-9]{2}|[1-9]?[0-9])\.){3}` +
34 `(?:25[0-5]|2[0-4][0-9]|[1][0-9]{2}|[1-9]?[0-9])` +
35 `/(?:3[0-2]|2[0-9]|[1]?[0-9])` + `$`)
36 IPv4RangeValidator = regexp.MustCompile(`^` +
37 `(?:(?:(?:25[0-5]|2[0-4][0-9]|[1][0-9]{2}|[1-9]?[0-9])-)?(?:25[0-5]|2[0-4][0-9]|[1][0-9]{2}|[1-9]?[0-9])\.){3}` +
38 `(?:(?:25[0-5]|2[0-4][0-9]|[1][0-9]{2}|[1-9]?[0-9])-)?(?:25[0-5]|2[0-4][0-9]|[1][0-9]{2}|[1-9]?[0-9])` + `$`)
39 IPv4Validator = regexp.MustCompile(`^` +
40 `(?:(?:25[0-5]|2[0-4][0-9]|[1][0-9]{2}|[1-9]?[0-9])\.){3}` +
41 `(?:25[0-5]|2[0-4][0-9]|[1][0-9]{2}|[1-9]?[0-9])` + `$`)
42 MACValidator = regexp.MustCompile(`(?i)^(?:[a-f0-9]{2}:){5}[a-f0-9]{2}$`)
43 // lulz this sounds like a hamburger
44 macParser = regexp.MustCompile(`(?i)((?:[a-f0-9]{2}:){5}[a-f0-9]{2})`)
45 aliasParser = regexp.MustCompile(`(?i)([a-z_][a-z_0-9]+)`)
46 )
47
48 func IsZeroMac(mac net.HardwareAddr) bool {
49 for _, b := range mac {
50 if b != 0x00 {
51 return false
52 }
53 }
54 return true
55 }
56
57 func IsBroadcastMac(mac net.HardwareAddr) bool {
58 for _, b := range mac {
59 if b != 0xff {
60 return false
61 }
62 }
63 return true
64 }
65
66 func NormalizeMac(mac string) string {
67 var parts []string
68 if strings.ContainsRune(mac, '-') {
69 parts = strings.Split(mac, "-")
70 } else {
71 parts = strings.Split(mac, ":")
72 }
73
74 for i, p := range parts {
75 if len(p) < 2 {
76 parts[i] = "0" + p
77 }
78 }
79 return strings.ToLower(strings.Join(parts, ":"))
80 }
81
82 func ParseMACs(targets string) (macs []net.HardwareAddr, err error) {
83 macs = make([]net.HardwareAddr, 0)
84 if targets = str.Trim(targets); targets == "" {
85 return
86 }
87
88 for _, mac := range macParser.FindAllString(targets, -1) {
89 mac = NormalizeMac(mac)
90 hw, err := net.ParseMAC(mac)
91 if err != nil {
92 return nil, fmt.Errorf("error while parsing MAC '%s': %s", mac, err)
93 }
94
95 macs = append(macs, hw)
96 targets = strings.Replace(targets, mac, "", -1)
97 }
98
99 return
100 }
101
102 func ParseTargets(targets string, aliasMap *data.UnsortedKV) (ips []net.IP, macs []net.HardwareAddr, err error) {
103 ips = make([]net.IP, 0)
104 macs = make([]net.HardwareAddr, 0)
105
106 if targets = str.Trim(targets); targets == "" {
107 return
108 }
109
110 // first isolate MACs and parse them
111 for _, mac := range macParser.FindAllString(targets, -1) {
112 normalizedMac := NormalizeMac(mac)
113 hw, err := net.ParseMAC(normalizedMac)
114 if err != nil {
115 return nil, nil, fmt.Errorf("error while parsing MAC '%s': %s", normalizedMac, err)
116 }
117
118 macs = append(macs, hw)
119 targets = strings.Replace(targets, mac, "", -1)
120 }
121 targets = strings.Trim(targets, ", ")
122
123 // fmt.Printf("targets=%s macs=%#v\n", targets, macs)
124
125 // check and resolve aliases
126 for _, targetAlias := range aliasParser.FindAllString(targets, -1) {
127 found := false
128 aliasMap.Each(func(mac, alias string) bool {
129 if alias == targetAlias {
130 if hw, err := net.ParseMAC(mac); err == nil {
131 macs = append(macs, hw)
132 targets = strings.Replace(targets, targetAlias, "", -1)
133 found = true
134 return true
135 }
136 }
137 return false
138 })
139
140 if !found {
141 return nil, nil, fmt.Errorf("could not resolve alias %s", targetAlias)
142 }
143 }
144 targets = strings.Trim(targets, ", ")
145
146 // parse what's left
147 if targets != "" {
148 list, err := iprange.ParseList(targets)
149 if err != nil {
150 return nil, nil, fmt.Errorf("error while parsing address list '%s': %s", targets, err)
151 }
152
153 ips = list.Expand()
154 }
155
156 return
157 }
158
159 func ParseEndpoints(targets string, lan *LAN) ([]*Endpoint, error) {
160 ips, macs, err := ParseTargets(targets, lan.Aliases())
161 if err != nil {
162 return nil, err
163 }
164
165 tmp := make(map[string]*Endpoint)
166 for _, ip := range ips {
167 if e := lan.GetByIp(ip.String()); e != nil {
168 tmp[e.HW.String()] = e
169 }
170 }
171
172 for _, mac := range macs {
173 if e, found := lan.Get(mac.String()); found {
174 tmp[e.HW.String()] = e
175 }
176 }
177
178 ret := make([]*Endpoint, 0)
179 for _, e := range tmp {
180 ret = append(ret, e)
181 }
182 return ret, nil
183 }
184
185 func buildEndpointFromInterface(iface net.Interface) (*Endpoint, error) {
186 addrs, err := iface.Addrs()
187 if err != nil {
188 return nil, err
189 }
190
191 ifName := getInterfaceName(iface)
192
193 e := NewEndpointNoResolve(MonitorModeAddress, iface.HardwareAddr.String(), ifName, 0)
194
195 e.Index = iface.Index
196
197 for _, a := range addrs {
198 address := a.String()
199 switch true {
200 case IPv4Validator.MatchString(address):
201 e.SetIP(address)
202 break
203 case IPv4BlockValidator.MatchString(address):
204 e.SetNetwork(address)
205 break
206 default:
207 e.SetIPv6(address)
208 break
209 }
210 }
211
212 return e, nil
213 }
214
215 func matchByAddress(iface net.Interface, name string) bool {
216 ifMac := iface.HardwareAddr.String()
217 if NormalizeMac(ifMac) == NormalizeMac(name) {
218 return true
219 }
220
221 addrs, err := iface.Addrs()
222 if err == nil {
223 for _, addr := range addrs {
224 ip := addr.String()
225 if ip == name || strings.HasPrefix(ip, name) {
226 return true
227 }
228 }
229 }
230
231 return false
232 }
233
234 func findInterfaceByName(name string, ifaces []net.Interface) (*Endpoint, error) {
235 for _, iface := range ifaces {
236 ifName := getInterfaceName(iface)
237 if ifName == name || matchByAddress(iface, name) {
238 return buildEndpointFromInterface(iface)
239 }
240 }
241
242 return nil, fmt.Errorf("no interface matching '%s' found.", name)
243 }
244
245 func FindInterface(name string) (*Endpoint, error) {
246 ifaces, err := net.Interfaces()
247 if err != nil {
248 return nil, err
249 }
250 name = str.Trim(name)
251 if name != "" {
252 return findInterfaceByName(name, ifaces)
253 }
254
255 // user did not provide an interface name,
256 // return the first one with a valid ipv4
257 // address that does not loop back
258 for _, iface := range ifaces {
259 // if name has not been provided, avoid default to a tun interface
260 if strings.Contains(iface.Name, "tun") {
261 continue
262 }
263
264 addrs, err := iface.Addrs()
265 if err != nil {
266 fmt.Printf("wtf of the day: %s", err)
267 continue
268 }
269
270 for _, address := range addrs {
271 ip := address.String()
272 if !strings.HasPrefix(ip, "127.0.0.1") && IPv4BlockValidator.MatchString(ip) {
273 return buildEndpointFromInterface(iface)
274 }
275 }
276 }
277
278 return nil, ErrNoIfaces
279 }
280
281 func SetWiFiRegion(region string) error {
282 if core.HasBinary("iw") {
283 if out, err := core.Exec("iw", []string{"reg", "set", region}); err != nil {
284 return err
285 } else if out != "" {
286 return fmt.Errorf("unexpected output while setting WiFi region %s: %s", region, out)
287 }
288 }
289 return nil
290 }
291
292 func ActivateInterface(name string) error {
293 if out, err := core.Exec("ifconfig", []string{name, "up"}); err != nil {
294 if out != "" {
295 return fmt.Errorf("%v: %s", err, out)
296 } else {
297 return err
298 }
299 } else if out != "" {
300 return fmt.Errorf("unexpected output while activating interface %s: %s", name, out)
301 }
302 return nil
303 }
304
305 func SetInterfaceTxPower(name string, txpower int) error {
306 if core.HasBinary("iw") {
307 Debug("SetInterfaceTxPower(%s, %d) iw based", name, txpower)
308 if _, err := core.Exec("iw", []string{"dev", name, "set", "txpower", "fixed", fmt.Sprintf("%d", txpower)}); err != nil {
309 return err
310 }
311 } else if core.HasBinary("iwconfig") {
312 Debug("SetInterfaceTxPower(%s, %d) iwconfig based", name, txpower)
313 if out, err := core.Exec("iwconfig", []string{name, "txpower", fmt.Sprintf("%d", txpower)}); err != nil {
314 return err
315 } else if out != "" {
316 return fmt.Errorf("unexpected output while setting txpower to %d for interface %s: %s", txpower, name, out)
317 }
318 }
319 return nil
320 }
321
322 func GatewayProvidedByUser(iface *Endpoint, gateway string) (*Endpoint, error) {
323 if IPv4Validator.MatchString(gateway) {
324 Debug("valid gateway ip %s", gateway)
325 // we have the address, now we need its mac
326 if mac, err := ArpLookup(iface.Name(), gateway, false); err != nil {
327 return nil, err
328 } else {
329 Debug("gateway is %s[%s]", gateway, mac)
330 return NewEndpoint(gateway, mac), nil
331 }
332 }
333 return nil, fmt.Errorf("Provided gateway %s not a valid IPv4 address! Revert to find default gateway.", gateway)
334 }
335
336 func ColorRSSI(n int) string {
337 // ref. https://www.metageek.com/training/resources/understanding-rssi-2.html
338 rssi := fmt.Sprintf("%d dBm", n)
339 if n >= -67 {
340 rssi = tui.Green(rssi)
341 } else if n >= -70 {
342 rssi = tui.Dim(tui.Green(rssi))
343 } else if n >= -80 {
344 rssi = tui.Yellow(rssi)
345 } else {
346 rssi = tui.Dim(tui.Red(rssi))
347 }
348 return rssi
349 }