fix automatic gateway detection for Linux

This commit is contained in:
☸️ 2021-09-20 19:18:43 +10:00 committed by GitHub
parent aba29e03f6
commit c6740a5750
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,43 +1,67 @@
package routing
import (
"github.com/bettercap/bettercap/core"
"github.com/evilsocket/islazy/str"
"regexp"
"strings"
"github.com/bettercap/bettercap/core"
"github.com/evilsocket/islazy/str"
)
var parser = regexp.MustCompile(`^(.+)\sdev\s([^\s]+)\s(.+)$`)
var (
routeHeadings []string
whitespaceParser = regexp.MustCompile(`\s+`)
)
func update() ([]Route, error) {
table = make([]Route, 0)
for ip, inet := range map[RouteType]string{IPv4: "inet", IPv6: "inet6"} {
output, err := core.Exec("ip", []string{"-f", inet, "route"})
if err != nil {
return nil, err
}
output, err := core.Exec("netstat", []string{"-r", "-n"})
if err != nil {
return nil, err
}
for _, line := range strings.Split(output, "\n") {
if line = str.Trim(line); len(line) > 0 {
matches := parser.FindStringSubmatch(line)
if num := len(matches); num == 4 {
route := Route{
Type: ip,
Destination: matches[1],
Device: matches[2],
Flags: matches[3],
Default: strings.Index(matches[1], "default ") == 0,
}
for _, line := range strings.Split(output, "\n") {
if line = str.Trim(line); len(line) != 0 {
parts := whitespaceParser.Split(line, -1)
if parts[0] == "Kernel" {
continue
}
if idx := strings.Index(route.Destination, " via "); idx >= 0 {
route.Gateway = route.Destination[idx + len(" via "):]
route.Destination = route.Destination[:idx]
}
if parts[0] == "Destination" {
routeHeadings = parts
continue
}
table = append(table, route)
route := Route{}
for i, s := range parts {
switch routeHeadings[i] {
case "Destination":
route.Destination = s
break
case "Flags":
route.Flags = s
break
case "Gateway":
route.Gateway = s
break
case "Iface":
route.Device = s
break
}
}
route.Default = strings.Contains(route.Flags, "G")
if route.Destination != "" {
if strings.ContainsRune(route.Destination, '.') || strings.ContainsRune(route.Gateway, '.') {
route.Type = "IPv4"
} else {
route.Type = "IPv6"
}
}
table = append(table, route)
}
}