From b64be66906ebdba08c604a97f355e5dab63605b7 Mon Sep 17 00:00:00 2001 From: boreq Date: Tue, 21 Nov 2023 13:22:36 +0100 Subject: [PATCH] Don't connect to private or loopback addresses This probably doesn't matter but it is pointless to try to connect to those. --- service/app/downloader.go | 5 +++++ service/domain/relay_address.go | 11 ++++++++++ service/domain/relay_address_test.go | 31 ++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/service/app/downloader.go b/service/app/downloader.go index 1742ffc..80aebce 100644 --- a/service/app/downloader.go +++ b/service/app/downloader.go @@ -338,6 +338,11 @@ func (m *DatabaseRelaySource) GetRelays(ctx context.Context) ([]domain.RelayAddr Message("address is invalid") continue } + + if address.IsLoopbackOrPrivate() { + continue + } + result = append(result, address) } diff --git a/service/domain/relay_address.go b/service/domain/relay_address.go index 1fcdb79..9b84911 100644 --- a/service/domain/relay_address.go +++ b/service/domain/relay_address.go @@ -1,6 +1,8 @@ package domain import ( + "net" + "net/url" "strings" "github.com/boreq/errors" @@ -32,6 +34,15 @@ func NewRelayAddressFromMaybeAddress(maybe MaybeRelayAddress) (RelayAddress, err return NewRelayAddress(maybe.String()) } +func (r RelayAddress) IsLoopbackOrPrivate() bool { + u, err := url.Parse(r.s) + if err != nil { + return false + } + ip := net.ParseIP(u.Host) + return ip.IsLoopback() || ip.IsPrivate() +} + func (r RelayAddress) String() string { return r.s } diff --git a/service/domain/relay_address_test.go b/service/domain/relay_address_test.go index c547ceb..63e165e 100644 --- a/service/domain/relay_address_test.go +++ b/service/domain/relay_address_test.go @@ -51,3 +51,34 @@ func TestRelayAddress(t *testing.T) { }) } } + +func TestRelayAddress_IsLocal(t *testing.T) { + testCases := []struct { + Input string + Result bool + }{ + { + Input: "ws://127.0.0.1", + Result: true, + }, + { + Input: "ws://192.168.0.10", + Result: true, + }, + { + Input: "ws://1.2.3.4", + Result: false, + }, + { + Input: "ws://example.com", + Result: false, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.Input, func(t *testing.T) { + address := MustNewRelayAddress(testCase.Input) + require.Equal(t, testCase.Result, address.IsLoopbackOrPrivate()) + }) + } +}