From c6740a5750adc3d6c5eb9da4d33369055cfe326f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=B8=EF=B8=8F?= <29265684+buffermet@users.noreply.github.com> Date: Mon, 20 Sep 2021 19:18:43 +1000 Subject: [PATCH] fix automatic gateway detection for Linux --- routing/update_linux.go | 72 +++++++++++++++++++++++++++-------------- 1 file changed, 48 insertions(+), 24 deletions(-) diff --git a/routing/update_linux.go b/routing/update_linux.go index 016fe8f4..89885589 100644 --- a/routing/update_linux.go +++ b/routing/update_linux.go @@ -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) } }