This commit is contained in:
mk0walsk 2026-05-22 11:32:23 +08:00 committed by GitHub
commit d57c22f17a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 66 additions and 1 deletions

View file

@ -336,7 +336,7 @@ func parseExtAddr(spec string) (ip net.IP, port int, ok bool) {
return nil, 0, false
}
port, err = strconv.Atoi(portstr)
if err != nil {
if err != nil || port < 0 || port > 65535 {
return nil, 0, false
}
return ip, port, true

View file

@ -0,0 +1,43 @@
// Copyright 2026 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
package main
import "testing"
func TestParseExtAddrPortRange(t *testing.T) {
tests := []struct {
input string
ok bool
port int
}{
{input: "127.0.0.1", ok: true, port: 0},
{input: "127.0.0.1:30303", ok: true, port: 30303},
{input: "127.0.0.1:65535", ok: true, port: 65535},
{input: "127.0.0.1:65536", ok: false},
{input: "127.0.0.1:-1", ok: false},
{input: "[2001:db8::1]:30303", ok: true, port: 30303},
}
for _, tc := range tests {
_, port, ok := parseExtAddr(tc.input)
if ok != tc.ok {
t.Fatalf("parseExtAddr(%q) ok=%v, want %v", tc.input, ok, tc.ok)
}
if ok && port != tc.port {
t.Fatalf("parseExtAddr(%q) port=%d, want %d", tc.input, port, tc.port)
}
}
}

View file

@ -205,6 +205,9 @@ func (ln *LocalNode) SetFallbackIP(ip net.IP) {
// SetFallbackUDP sets the last-resort UDP-on-IPv4 port. This port is used
// if no endpoint prediction can be made.
func (ln *LocalNode) SetFallbackUDP(port int) {
if port < 0 || port > 65535 {
return
}
ln.mu.Lock()
defer ln.mu.Unlock()

View file

@ -136,3 +136,22 @@ func TestLocalNodeEndpoint(t *testing.T) {
assert.Equal(t, fallback.Port, ln.Node().UDP())
assert.Equal(t, initialSeq+3, ln.Node().Seq())
}
func TestSetFallbackUDPRejectsOutOfRange(t *testing.T) {
ln, db := newLocalNodeForTesting()
defer db.Close()
initialSeq := ln.Node().Seq()
ln.SetFallbackUDP(30303)
assert.Equal(t, 30303, ln.Node().UDP())
assert.Equal(t, initialSeq+1, ln.Node().Seq())
seqAfterValid := ln.Node().Seq()
ln.SetFallbackUDP(65536)
assert.Equal(t, 30303, ln.Node().UDP())
assert.Equal(t, seqAfterValid, ln.Node().Seq())
ln.SetFallbackUDP(-1)
assert.Equal(t, 30303, ln.Node().UDP())
assert.Equal(t, seqAfterValid, ln.Node().Seq())
}