From f325aa7e38b0cc363d03f41979b38b49d7d7fc80 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Mon, 12 Apr 2021 09:06:57 -0700 Subject: [PATCH] portlist: exclude services bound to IPv6 loopback address Fixes #1683 Signed-off-by: Brad Fitzpatrick --- portlist/netstat.go | 5 ++++- portlist/netstat_test.go | 14 +++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/portlist/netstat.go b/portlist/netstat.go index 7eb8ed973..2d738355c 100644 --- a/portlist/netstat.go +++ b/portlist/netstat.go @@ -42,7 +42,10 @@ func parsePort(s string) int { } func isLoopbackAddr(s string) bool { - return strings.HasPrefix(s, "127.0.0.1:") || strings.HasPrefix(s, "127.0.0.1.") + return strings.HasPrefix(s, "127.0.0.1:") || + strings.HasPrefix(s, "127.0.0.1.") || + strings.HasPrefix(s, "[::1]:") || + strings.HasPrefix(s, "::1.") } type nothing struct{} diff --git a/portlist/netstat_test.go b/portlist/netstat_test.go index 8f1d33abd..56adeffb0 100644 --- a/portlist/netstat_test.go +++ b/portlist/netstat_test.go @@ -5,6 +5,7 @@ package portlist import ( + "encoding/json" "testing" ) @@ -40,7 +41,11 @@ udp6 0 0 :::5354 :::* // macOS tcp4 0 0 *.23 *.* LISTEN -tcp6 0 0 *.24 *.* LISTEN +tcp6 0 0 *.24 *.* LISTEN +tcp4 0 0 *.8185 *.* LISTEN +tcp4 0 0 127.0.0.1.8186 *.* LISTEN +tcp6 0 0 ::1.8187 *.* LISTEN + udp6 0 0 *.5453 *.* udp4 0 0 *.5553 *.* @@ -73,14 +78,21 @@ func TestParsePortsNetstat(t *testing.T) { Port{"udp", 5354, "", ""}, Port{"udp", 5453, "", ""}, Port{"udp", 5553, "", ""}, + Port{"tcp", 8185, "", ""}, // but not 8186 or 8187 on localhost Port{"udp", 9353, "iTunes", ""}, } pl := parsePortsNetstat(netstatOutput) + jgot, _ := json.MarshalIndent(pl, "", "\t") + jwant, _ := json.MarshalIndent(want, "", "\t") + if len(pl) != len(want) { + t.Fatalf("Got:\n%s\n\nWant:\n%s\n", jgot, jwant) + } for i := range pl { if pl[i] != want[i] { t.Errorf("row#%d\n got: %#v\n\nwant: %#v\n", i, pl[i], want[i]) + t.Fatalf("Got:\n%s\n\nWant:\n%s\n", jgot, jwant) } } }