mirror of
https://github.com/netbirdio/gvisor.git
synced 2026-05-22 17:12:49 -07:00
Implement neighbor unreachability detection for ARP and NDP.
This change implements the Neighbor Unreachability Detection (NUD) state machine, as per RFC 4861 [1]. The state machine operates on a single neighbor in the local network. This requires the state machine to be implemented on each entry of the neighbor table. This change also adds, but does not expose, several APIs. The first API is for performing basic operations on the neighbor table: - Create a static entry - List all entries - Delete all entries - Remove an entry by address The second API is used for changing the NUD protocol constants on a per-NIC basis to allow Neighbor Discovery to operate over links with widely varying performance characteristics. See [RFC 4861 Section 10][2] for the list of constants. Finally, the last API is for allowing users to subscribe to NUD state changes. See [RFC 4861 Appendix C][3] for the list of edges. [1]: https://tools.ietf.org/html/rfc4861 [2]: https://tools.ietf.org/html/rfc4861#section-10 [3]: https://tools.ietf.org/html/rfc4861#appendix-C Tests: pkg/tcpip/stack:stack_test - TestNeighborCacheAddStaticEntryThenOverflow - TestNeighborCacheClear - TestNeighborCacheClearThenOverflow - TestNeighborCacheConcurrent - TestNeighborCacheDuplicateStaticEntryWithDifferentLinkAddress - TestNeighborCacheDuplicateStaticEntryWithSameLinkAddress - TestNeighborCacheEntry - TestNeighborCacheEntryNoLinkAddress - TestNeighborCacheGetConfig - TestNeighborCacheKeepFrequentlyUsed - TestNeighborCacheNotifiesWaker - TestNeighborCacheOverflow - TestNeighborCacheOverwriteWithStaticEntryThenOverflow - TestNeighborCacheRemoveEntry - TestNeighborCacheRemoveEntryThenOverflow - TestNeighborCacheRemoveStaticEntry - TestNeighborCacheRemoveStaticEntryThenOverflow - TestNeighborCacheRemoveWaker - TestNeighborCacheReplace - TestNeighborCacheResolutionFailed - TestNeighborCacheResolutionTimeout - TestNeighborCacheSetConfig - TestNeighborCacheStaticResolution - TestEntryAddsAndClearsWakers - TestEntryDelayToProbe - TestEntryDelayToReachableWhenSolicitedOverrideConfirmation - TestEntryDelayToReachableWhenUpperLevelConfirmation - TestEntryDelayToStaleWhenConfirmationWithDifferentAddress - TestEntryDelayToStaleWhenProbeWithDifferentAddress - TestEntryFailedGetsDeleted - TestEntryIncompleteToFailed - TestEntryIncompleteToIncompleteDoesNotChangeUpdatedAt - TestEntryIncompleteToReachable - TestEntryIncompleteToReachableWithRouterFlag - TestEntryIncompleteToStale - TestEntryInitiallyUnknown - TestEntryProbeToFailed - TestEntryProbeToReachableWhenSolicitedConfirmationWithSameAddress - TestEntryProbeToReachableWhenSolicitedOverrideConfirmation - TestEntryProbeToStaleWhenConfirmationWithDifferentAddress - TestEntryProbeToStaleWhenProbeWithDifferentAddress - TestEntryReachableToStaleWhenConfirmationWithDifferentAddress - TestEntryReachableToStaleWhenConfirmationWithDifferentAddressAndOverride - TestEntryReachableToStaleWhenProbeWithDifferentAddress - TestEntryReachableToStaleWhenTimeout - TestEntryStaleToDelay - TestEntryStaleToReachableWhenSolicitedOverrideConfirmation - TestEntryStaleToStaleWhenOverrideConfirmation - TestEntryStaleToStaleWhenProbeUpdateAddress - TestEntryStaysDelayWhenOverrideConfirmationWithSameAddress - TestEntryStaysProbeWhenOverrideConfirmationWithSameAddress - TestEntryStaysReachableWhenConfirmationWithRouterFlag - TestEntryStaysReachableWhenProbeWithSameAddress - TestEntryStaysStaleWhenProbeWithSameAddress - TestEntryUnknownToIncomplete - TestEntryUnknownToStale - TestEntryUnknownToUnknownWhenConfirmationWithUnknownAddress pkg/tcpip/stack:stack_x_test - TestDefaultNUDConfigurations - TestNUDConfigurationFailsForNotSupported - TestNUDConfigurationsBaseReachableTime - TestNUDConfigurationsDelayFirstProbeTime - TestNUDConfigurationsMaxMulticastProbes - TestNUDConfigurationsMaxRandomFactor - TestNUDConfigurationsMaxUnicastProbes - TestNUDConfigurationsMinRandomFactor - TestNUDConfigurationsRetransmitTimer - TestNUDConfigurationsUnreachableTime - TestNUDStateReachableTime - TestNUDStateRecomputeReachableTime - TestSetNUDConfigurationFailsForBadNICID - TestSetNUDConfigurationFailsForNotSupported [1]: https://tools.ietf.org/html/rfc4861 [2]: https://tools.ietf.org/html/rfc4861#section-10 [3]: https://tools.ietf.org/html/rfc4861#appendix-C Updates #1889 Updates #1894 Updates #1895 Updates #1947 Updates #1948 Updates #1949 Updates #1950 PiperOrigin-RevId: 324070795
This commit is contained in:
@@ -1089,3 +1089,10 @@ go_repository(
|
||||
sum = "h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o=",
|
||||
version = "v1.0.0",
|
||||
)
|
||||
|
||||
go_repository(
|
||||
name = "com_github_dpjacques_clockwork",
|
||||
importpath = "github.com/dpjacques/clockwork",
|
||||
sum = "h1:7krODee+eIlZYoLiEDmP1kLFNCvd0bQ0eEXOympdN6U=",
|
||||
version = "v0.1.1-0.20190114191937-d864eecc357b",
|
||||
)
|
||||
|
||||
@@ -22,6 +22,7 @@ require (
|
||||
github.com/docker/go-connections v0.3.0 // indirect
|
||||
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c // indirect
|
||||
github.com/docker/go-units v0.4.0 // indirect
|
||||
github.com/dpjacques/clockwork v0.1.1-0.20190114191937-d864eecc357b // indirect
|
||||
github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e // indirect
|
||||
github.com/gofrs/flock v0.6.1-0.20180915234121-886344bea079 // indirect
|
||||
github.com/gogo/googleapis v1.4.0 // indirect
|
||||
@@ -43,7 +44,6 @@ require (
|
||||
github.com/vishvananda/netns v0.0.0-20200520041808-52d707b772fe // indirect
|
||||
go.uber.org/atomic v1.6.0 // indirect
|
||||
go.uber.org/multierr v1.2.0 // indirect
|
||||
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 // indirect
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0 // indirect
|
||||
golang.org/x/tools v0.0.0-20200707200213-416e8f4faf8a // indirect
|
||||
google.golang.org/grpc v1.29.0 // indirect
|
||||
|
||||
@@ -74,6 +74,8 @@ github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c h1:+pKlWGMw7gf6bQ
|
||||
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA=
|
||||
github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw=
|
||||
github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/dpjacques/clockwork v0.1.1-0.20190114191937-d864eecc357b h1:7krODee+eIlZYoLiEDmP1kLFNCvd0bQ0eEXOympdN6U=
|
||||
github.com/dpjacques/clockwork v0.1.1-0.20190114191937-d864eecc357b/go.mod h1:D8mP2A8vVT2GkXqPorSBmhnshhkFBYgzhA90KmJt25Y=
|
||||
github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
@@ -288,6 +290,7 @@ golang.org/x/sys v0.0.0-20191210023423-ac6580df4449/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200120151820-655fe14d7479/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200523222454-059865788121 h1:rITEj+UZHYC927n8GT97eC3zrpzXdb/voyeOuVKS46o=
|
||||
golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
|
||||
@@ -15,6 +15,18 @@ go_template_instance(
|
||||
},
|
||||
)
|
||||
|
||||
go_template_instance(
|
||||
name = "neighbor_entry_list",
|
||||
out = "neighbor_entry_list.go",
|
||||
package = "stack",
|
||||
prefix = "neighborEntry",
|
||||
template = "//pkg/ilist:generic_list",
|
||||
types = {
|
||||
"Element": "*neighborEntry",
|
||||
"Linker": "*neighborEntry",
|
||||
},
|
||||
)
|
||||
|
||||
go_template_instance(
|
||||
name = "packet_buffer_list",
|
||||
out = "packet_buffer_list.go",
|
||||
@@ -53,7 +65,12 @@ go_library(
|
||||
"linkaddrcache.go",
|
||||
"linkaddrentry_list.go",
|
||||
"ndp.go",
|
||||
"neighbor_cache.go",
|
||||
"neighbor_entry.go",
|
||||
"neighbor_entry_list.go",
|
||||
"neighborstate_string.go",
|
||||
"nic.go",
|
||||
"nud.go",
|
||||
"packet_buffer.go",
|
||||
"packet_buffer_list.go",
|
||||
"rand.go",
|
||||
@@ -89,6 +106,7 @@ go_test(
|
||||
size = "medium",
|
||||
srcs = [
|
||||
"ndp_test.go",
|
||||
"nud_test.go",
|
||||
"stack_test.go",
|
||||
"transport_demuxer_test.go",
|
||||
"transport_test.go",
|
||||
@@ -118,8 +136,11 @@ go_test(
|
||||
name = "stack_test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"fake_time_test.go",
|
||||
"forwarder_test.go",
|
||||
"linkaddrcache_test.go",
|
||||
"neighbor_cache_test.go",
|
||||
"neighbor_entry_test.go",
|
||||
"nic_test.go",
|
||||
],
|
||||
library = ":stack",
|
||||
@@ -129,5 +150,8 @@ go_test(
|
||||
"//pkg/tcpip",
|
||||
"//pkg/tcpip/buffer",
|
||||
"//pkg/tcpip/header",
|
||||
"@com_github_dpjacques_clockwork//:go_default_library",
|
||||
"@com_github_google_go_cmp//cmp:go_default_library",
|
||||
"@com_github_google_go_cmp//cmp/cmpopts:go_default_library",
|
||||
],
|
||||
)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// Copyright 2020 The gVisor Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package stack
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/dpjacques/clockwork"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
)
|
||||
|
||||
type fakeClock struct {
|
||||
clock clockwork.FakeClock
|
||||
|
||||
// mu protects the fields below.
|
||||
mu sync.RWMutex
|
||||
|
||||
// times is min-heap of times. A heap is used for quick retrieval of the next
|
||||
// upcoming time of scheduled work.
|
||||
times *timeHeap
|
||||
|
||||
// waitGroups stores one WaitGroup for all work scheduled to execute at the
|
||||
// same time via AfterFunc. This allows parallel execution of all functions
|
||||
// passed to AfterFunc scheduled for the same time.
|
||||
waitGroups map[time.Time]*sync.WaitGroup
|
||||
}
|
||||
|
||||
func newFakeClock() *fakeClock {
|
||||
return &fakeClock{
|
||||
clock: clockwork.NewFakeClock(),
|
||||
times: &timeHeap{},
|
||||
waitGroups: make(map[time.Time]*sync.WaitGroup),
|
||||
}
|
||||
}
|
||||
|
||||
var _ tcpip.Clock = (*fakeClock)(nil)
|
||||
|
||||
// NowNanoseconds implements tcpip.Clock.NowNanoseconds.
|
||||
func (fc *fakeClock) NowNanoseconds() int64 {
|
||||
return fc.clock.Now().UnixNano()
|
||||
}
|
||||
|
||||
// NowMonotonic implements tcpip.Clock.NowMonotonic.
|
||||
func (fc *fakeClock) NowMonotonic() int64 {
|
||||
return fc.NowNanoseconds()
|
||||
}
|
||||
|
||||
// AfterFunc implements tcpip.Clock.AfterFunc.
|
||||
func (fc *fakeClock) AfterFunc(d time.Duration, f func()) tcpip.Timer {
|
||||
until := fc.clock.Now().Add(d)
|
||||
wg := fc.addWait(until)
|
||||
return &fakeTimer{
|
||||
clock: fc,
|
||||
until: until,
|
||||
timer: fc.clock.AfterFunc(d, func() {
|
||||
defer wg.Done()
|
||||
f()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// addWait adds an additional wait to the WaitGroup for parallel execution of
|
||||
// all work scheduled for t. Returns a reference to the WaitGroup modified.
|
||||
func (fc *fakeClock) addWait(t time.Time) *sync.WaitGroup {
|
||||
fc.mu.RLock()
|
||||
wg, ok := fc.waitGroups[t]
|
||||
fc.mu.RUnlock()
|
||||
|
||||
if ok {
|
||||
wg.Add(1)
|
||||
return wg
|
||||
}
|
||||
|
||||
fc.mu.Lock()
|
||||
heap.Push(fc.times, t)
|
||||
fc.mu.Unlock()
|
||||
|
||||
wg = &sync.WaitGroup{}
|
||||
wg.Add(1)
|
||||
|
||||
fc.mu.Lock()
|
||||
fc.waitGroups[t] = wg
|
||||
fc.mu.Unlock()
|
||||
|
||||
return wg
|
||||
}
|
||||
|
||||
// removeWait removes a wait from the WaitGroup for parallel execution of all
|
||||
// work scheduled for t.
|
||||
func (fc *fakeClock) removeWait(t time.Time) {
|
||||
fc.mu.RLock()
|
||||
defer fc.mu.RUnlock()
|
||||
|
||||
wg := fc.waitGroups[t]
|
||||
wg.Done()
|
||||
}
|
||||
|
||||
// advance executes all work that have been scheduled to execute within d from
|
||||
// the current fake time. Blocks until all work has completed execution.
|
||||
func (fc *fakeClock) advance(d time.Duration) {
|
||||
// Block until all the work is done
|
||||
until := fc.clock.Now().Add(d)
|
||||
for {
|
||||
fc.mu.Lock()
|
||||
if fc.times.Len() == 0 {
|
||||
fc.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
t := heap.Pop(fc.times).(time.Time)
|
||||
if t.After(until) {
|
||||
// No work to do
|
||||
heap.Push(fc.times, t)
|
||||
fc.mu.Unlock()
|
||||
return
|
||||
}
|
||||
fc.mu.Unlock()
|
||||
|
||||
diff := t.Sub(fc.clock.Now())
|
||||
fc.clock.Advance(diff)
|
||||
|
||||
fc.mu.RLock()
|
||||
wg := fc.waitGroups[t]
|
||||
fc.mu.RUnlock()
|
||||
|
||||
wg.Wait()
|
||||
|
||||
fc.mu.Lock()
|
||||
delete(fc.waitGroups, t)
|
||||
fc.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
type fakeTimer struct {
|
||||
clock *fakeClock
|
||||
timer clockwork.Timer
|
||||
|
||||
mu sync.RWMutex
|
||||
until time.Time
|
||||
}
|
||||
|
||||
var _ tcpip.Timer = (*fakeTimer)(nil)
|
||||
|
||||
// Reset implements tcpip.Timer.Reset.
|
||||
func (ft *fakeTimer) Reset(d time.Duration) {
|
||||
if !ft.timer.Reset(d) {
|
||||
return
|
||||
}
|
||||
|
||||
ft.mu.Lock()
|
||||
defer ft.mu.Unlock()
|
||||
|
||||
ft.clock.removeWait(ft.until)
|
||||
ft.until = ft.clock.clock.Now().Add(d)
|
||||
ft.clock.addWait(ft.until)
|
||||
}
|
||||
|
||||
// Stop implements tcpip.Timer.Stop.
|
||||
func (ft *fakeTimer) Stop() bool {
|
||||
if !ft.timer.Stop() {
|
||||
return false
|
||||
}
|
||||
|
||||
ft.mu.RLock()
|
||||
defer ft.mu.RUnlock()
|
||||
|
||||
ft.clock.removeWait(ft.until)
|
||||
return true
|
||||
}
|
||||
|
||||
type timeHeap []time.Time
|
||||
|
||||
var _ heap.Interface = (*timeHeap)(nil)
|
||||
|
||||
func (h timeHeap) Len() int {
|
||||
return len(h)
|
||||
}
|
||||
|
||||
func (h timeHeap) Less(i, j int) bool {
|
||||
return h[i].Before(h[j])
|
||||
}
|
||||
|
||||
func (h timeHeap) Swap(i, j int) {
|
||||
h[i], h[j] = h[j], h[i]
|
||||
}
|
||||
|
||||
func (h *timeHeap) Push(x interface{}) {
|
||||
*h = append(*h, x.(time.Time))
|
||||
}
|
||||
|
||||
func (h *timeHeap) Pop() interface{} {
|
||||
last := (*h)[len(*h)-1]
|
||||
*h = (*h)[:len(*h)-1]
|
||||
return last
|
||||
}
|
||||
@@ -33,12 +33,6 @@ const (
|
||||
// Default = 1 (from RFC 4862 section 5.1)
|
||||
defaultDupAddrDetectTransmits = 1
|
||||
|
||||
// defaultRetransmitTimer is the default amount of time to wait between
|
||||
// sending NDP Neighbor solicitation messages.
|
||||
//
|
||||
// Default = 1s (from RFC 4861 section 10).
|
||||
defaultRetransmitTimer = time.Second
|
||||
|
||||
// defaultMaxRtrSolicitations is the default number of Router
|
||||
// Solicitation messages to send when a NIC becomes enabled.
|
||||
//
|
||||
@@ -79,16 +73,6 @@ const (
|
||||
// Default = true.
|
||||
defaultAutoGenGlobalAddresses = true
|
||||
|
||||
// minimumRetransmitTimer is the minimum amount of time to wait between
|
||||
// sending NDP Neighbor solicitation messages. Note, RFC 4861 does
|
||||
// not impose a minimum Retransmit Timer, but we do here to make sure
|
||||
// the messages are not sent all at once. We also come to this value
|
||||
// because in the RetransmitTimer field of a Router Advertisement, a
|
||||
// value of 0 means unspecified, so the smallest valid value is 1.
|
||||
// Note, the unit of the RetransmitTimer field in the Router
|
||||
// Advertisement is milliseconds.
|
||||
minimumRetransmitTimer = time.Millisecond
|
||||
|
||||
// minimumRtrSolicitationInterval is the minimum amount of time to wait
|
||||
// between sending Router Solicitation messages. This limit is imposed
|
||||
// to make sure that Router Solicitation messages are not sent all at
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
// Copyright 2020 The gVisor Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package stack
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/sleep"
|
||||
"gvisor.dev/gvisor/pkg/sync"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
)
|
||||
|
||||
const neighborCacheSize = 512 // max entries per interface
|
||||
|
||||
// neighborCache maps IP addresses to link addresses. It uses the Least
|
||||
// Recently Used (LRU) eviction strategy to implement a bounded cache for
|
||||
// dynmically acquired entries. It contains the state machine and configuration
|
||||
// for running Neighbor Unreachability Detection (NUD).
|
||||
//
|
||||
// There are two types of entries in the neighbor cache:
|
||||
// 1. Dynamic entries are discovered automatically by neighbor discovery
|
||||
// protocols (e.g. ARP, NDP). These protocols will attempt to reconfirm
|
||||
// reachability with the device once the entry's state becomes Stale.
|
||||
// 2. Static entries are explicitly added by a user and have no expiration.
|
||||
// Their state is always Static. The amount of static entries stored in the
|
||||
// cache is unbounded.
|
||||
//
|
||||
// neighborCache implements NUDHandler.
|
||||
type neighborCache struct {
|
||||
nic *NIC
|
||||
state *NUDState
|
||||
|
||||
// mu protects the fields below.
|
||||
mu sync.RWMutex
|
||||
|
||||
cache map[tcpip.Address]*neighborEntry
|
||||
dynamic struct {
|
||||
lru neighborEntryList
|
||||
|
||||
// count tracks the amount of dynamic entries in the cache. This is
|
||||
// needed since static entries do not count towards the LRU cache
|
||||
// eviction strategy.
|
||||
count uint16
|
||||
}
|
||||
}
|
||||
|
||||
var _ NUDHandler = (*neighborCache)(nil)
|
||||
|
||||
// getOrCreateEntry retrieves a cache entry associated with addr. The
|
||||
// returned entry is always refreshed in the cache (it is reachable via the
|
||||
// map, and its place is bumped in LRU).
|
||||
//
|
||||
// If a matching entry exists in the cache, it is returned. If no matching
|
||||
// entry exists and the cache is full, an existing entry is evicted via LRU,
|
||||
// reset to state incomplete, and returned. If no matching entry exists and the
|
||||
// cache is not full, a new entry with state incomplete is allocated and
|
||||
// returned.
|
||||
func (n *neighborCache) getOrCreateEntry(remoteAddr, localAddr tcpip.Address, linkRes LinkAddressResolver) *neighborEntry {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
|
||||
if entry, ok := n.cache[remoteAddr]; ok {
|
||||
entry.mu.RLock()
|
||||
if entry.neigh.State != Static {
|
||||
n.dynamic.lru.Remove(entry)
|
||||
n.dynamic.lru.PushFront(entry)
|
||||
}
|
||||
entry.mu.RUnlock()
|
||||
return entry
|
||||
}
|
||||
|
||||
// The entry that needs to be created must be dynamic since all static
|
||||
// entries are directly added to the cache via addStaticEntry.
|
||||
entry := newNeighborEntry(n.nic, remoteAddr, localAddr, n.state, linkRes)
|
||||
if n.dynamic.count == neighborCacheSize {
|
||||
e := n.dynamic.lru.Back()
|
||||
e.mu.Lock()
|
||||
|
||||
delete(n.cache, e.neigh.Addr)
|
||||
n.dynamic.lru.Remove(e)
|
||||
n.dynamic.count--
|
||||
|
||||
e.dispatchRemoveEventLocked()
|
||||
e.setStateLocked(Unknown)
|
||||
e.notifyWakersLocked()
|
||||
e.mu.Unlock()
|
||||
}
|
||||
n.cache[remoteAddr] = entry
|
||||
n.dynamic.lru.PushFront(entry)
|
||||
n.dynamic.count++
|
||||
return entry
|
||||
}
|
||||
|
||||
// entry looks up the neighbor cache for translating address to link address
|
||||
// (e.g. IP -> MAC). If the LinkEndpoint requests address resolution and there
|
||||
// is a LinkAddressResolver registered with the network protocol, the cache
|
||||
// attempts to resolve the address and returns ErrWouldBlock. If a Waker is
|
||||
// provided, it will be notified when address resolution is complete (success
|
||||
// or not).
|
||||
//
|
||||
// If address resolution is required, ErrNoLinkAddress and a notification
|
||||
// channel is returned for the top level caller to block. Channel is closed
|
||||
// once address resolution is complete (success or not).
|
||||
func (n *neighborCache) entry(remoteAddr, localAddr tcpip.Address, linkRes LinkAddressResolver, w *sleep.Waker) (NeighborEntry, <-chan struct{}, *tcpip.Error) {
|
||||
if linkRes != nil {
|
||||
if linkAddr, ok := linkRes.ResolveStaticAddress(remoteAddr); ok {
|
||||
e := NeighborEntry{
|
||||
Addr: remoteAddr,
|
||||
LocalAddr: localAddr,
|
||||
LinkAddr: linkAddr,
|
||||
State: Static,
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
return e, nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
entry := n.getOrCreateEntry(remoteAddr, localAddr, linkRes)
|
||||
entry.mu.Lock()
|
||||
defer entry.mu.Unlock()
|
||||
|
||||
switch s := entry.neigh.State; s {
|
||||
case Reachable, Static:
|
||||
return entry.neigh, nil, nil
|
||||
|
||||
case Unknown, Incomplete, Stale, Delay, Probe:
|
||||
entry.addWakerLocked(w)
|
||||
|
||||
if entry.done == nil {
|
||||
// Address resolution needs to be initiated.
|
||||
if linkRes == nil {
|
||||
return entry.neigh, nil, tcpip.ErrNoLinkAddress
|
||||
}
|
||||
entry.done = make(chan struct{})
|
||||
}
|
||||
|
||||
entry.handlePacketQueuedLocked()
|
||||
return entry.neigh, entry.done, tcpip.ErrWouldBlock
|
||||
|
||||
case Failed:
|
||||
return entry.neigh, nil, tcpip.ErrNoLinkAddress
|
||||
|
||||
default:
|
||||
panic(fmt.Sprintf("Invalid cache entry state: %s", s))
|
||||
}
|
||||
}
|
||||
|
||||
// removeWaker removes a waker that has been added when link resolution for
|
||||
// addr was requested.
|
||||
func (n *neighborCache) removeWaker(addr tcpip.Address, waker *sleep.Waker) {
|
||||
n.mu.Lock()
|
||||
if entry, ok := n.cache[addr]; ok {
|
||||
delete(entry.wakers, waker)
|
||||
}
|
||||
n.mu.Unlock()
|
||||
}
|
||||
|
||||
// entries returns all entries in the neighbor cache.
|
||||
func (n *neighborCache) entries() []NeighborEntry {
|
||||
entries := make([]NeighborEntry, 0, len(n.cache))
|
||||
n.mu.RLock()
|
||||
for _, entry := range n.cache {
|
||||
entry.mu.RLock()
|
||||
entries = append(entries, entry.neigh)
|
||||
entry.mu.RUnlock()
|
||||
}
|
||||
n.mu.RUnlock()
|
||||
return entries
|
||||
}
|
||||
|
||||
// addStaticEntry adds a static entry to the neighbor cache, mapping an IP
|
||||
// address to a link address. If a dynamic entry exists in the neighbor cache
|
||||
// with the same address, it will be replaced with this static entry. If a
|
||||
// static entry exists with the same address but different link address, it
|
||||
// will be updated with the new link address. If a static entry exists with the
|
||||
// same address and link address, nothing will happen.
|
||||
func (n *neighborCache) addStaticEntry(addr tcpip.Address, linkAddr tcpip.LinkAddress) {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
|
||||
if entry, ok := n.cache[addr]; ok {
|
||||
entry.mu.Lock()
|
||||
if entry.neigh.State != Static {
|
||||
// Dynamic entry found with the same address.
|
||||
n.dynamic.lru.Remove(entry)
|
||||
n.dynamic.count--
|
||||
} else if entry.neigh.LinkAddr == linkAddr {
|
||||
// Static entry found with the same address and link address.
|
||||
entry.mu.Unlock()
|
||||
return
|
||||
} else {
|
||||
// Static entry found with the same address but different link address.
|
||||
entry.neigh.LinkAddr = linkAddr
|
||||
entry.dispatchChangeEventLocked(entry.neigh.State)
|
||||
entry.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Notify that resolution has been interrupted, just in case the entry was
|
||||
// in the Incomplete or Probe state.
|
||||
entry.dispatchRemoveEventLocked()
|
||||
entry.setStateLocked(Unknown)
|
||||
entry.notifyWakersLocked()
|
||||
entry.mu.Unlock()
|
||||
}
|
||||
|
||||
entry := newStaticNeighborEntry(n.nic, addr, linkAddr, n.state)
|
||||
n.cache[addr] = entry
|
||||
}
|
||||
|
||||
// removeEntryLocked removes the specified entry from the neighbor cache.
|
||||
func (n *neighborCache) removeEntryLocked(entry *neighborEntry) {
|
||||
if entry.neigh.State != Static {
|
||||
n.dynamic.lru.Remove(entry)
|
||||
n.dynamic.count--
|
||||
}
|
||||
if entry.neigh.State != Failed {
|
||||
entry.dispatchRemoveEventLocked()
|
||||
}
|
||||
entry.setStateLocked(Unknown)
|
||||
entry.notifyWakersLocked()
|
||||
|
||||
delete(n.cache, entry.neigh.Addr)
|
||||
}
|
||||
|
||||
// removeEntry removes a dynamic or static entry by address from the neighbor
|
||||
// cache. Returns true if the entry was found and deleted.
|
||||
func (n *neighborCache) removeEntry(addr tcpip.Address) bool {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
|
||||
entry, ok := n.cache[addr]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
entry.mu.Lock()
|
||||
defer entry.mu.Unlock()
|
||||
|
||||
n.removeEntryLocked(entry)
|
||||
return true
|
||||
}
|
||||
|
||||
// clear removes all dynamic and static entries from the neighbor cache.
|
||||
func (n *neighborCache) clear() {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
|
||||
for _, entry := range n.cache {
|
||||
entry.mu.Lock()
|
||||
entry.dispatchRemoveEventLocked()
|
||||
entry.setStateLocked(Unknown)
|
||||
entry.notifyWakersLocked()
|
||||
entry.mu.Unlock()
|
||||
}
|
||||
|
||||
n.dynamic.lru = neighborEntryList{}
|
||||
n.cache = make(map[tcpip.Address]*neighborEntry)
|
||||
n.dynamic.count = 0
|
||||
}
|
||||
|
||||
// config returns the NUD configuration.
|
||||
func (n *neighborCache) config() NUDConfigurations {
|
||||
return n.state.Config()
|
||||
}
|
||||
|
||||
// setConfig changes the NUD configuration.
|
||||
//
|
||||
// If config contains invalid NUD configuration values, it will be fixed to
|
||||
// use default values for the erroneous values.
|
||||
func (n *neighborCache) setConfig(config NUDConfigurations) {
|
||||
config.resetInvalidFields()
|
||||
n.state.SetConfig(config)
|
||||
}
|
||||
|
||||
// HandleProbe implements NUDHandler.HandleProbe by following the logic defined
|
||||
// in RFC 4861 section 7.2.3. Validation of the probe is expected to be handled
|
||||
// by the caller.
|
||||
func (n *neighborCache) HandleProbe(remoteAddr, localAddr tcpip.Address, protocol tcpip.NetworkProtocolNumber, remoteLinkAddr tcpip.LinkAddress) {
|
||||
entry := n.getOrCreateEntry(remoteAddr, localAddr, nil)
|
||||
entry.mu.Lock()
|
||||
entry.handleProbeLocked(remoteLinkAddr)
|
||||
entry.mu.Unlock()
|
||||
}
|
||||
|
||||
// HandleConfirmation implements NUDHandler.HandleConfirmation by following the
|
||||
// logic defined in RFC 4861 section 7.2.5.
|
||||
//
|
||||
// TODO(gvisor.dev/issue/2277): To protect against ARP poisoning and other
|
||||
// attacks against NDP functions, Secure Neighbor Discovery (SEND) Protocol
|
||||
// should be deployed where preventing access to the broadcast segment might
|
||||
// not be possible. SEND uses RSA key pairs to produce cryptographically
|
||||
// generated addresses, as defined in RFC 3972, Cryptographically Generated
|
||||
// Addresses (CGA). This ensures that the claimed source of an NDP message is
|
||||
// the owner of the claimed address.
|
||||
func (n *neighborCache) HandleConfirmation(addr tcpip.Address, linkAddr tcpip.LinkAddress, flags ReachabilityConfirmationFlags) {
|
||||
n.mu.RLock()
|
||||
entry, ok := n.cache[addr]
|
||||
n.mu.RUnlock()
|
||||
if ok {
|
||||
entry.mu.Lock()
|
||||
entry.handleConfirmationLocked(linkAddr, flags)
|
||||
entry.mu.Unlock()
|
||||
}
|
||||
// The confirmation SHOULD be silently discarded if the recipient did not
|
||||
// initiate any communication with the target. This is indicated if there is
|
||||
// no matching entry for the remote address.
|
||||
}
|
||||
|
||||
// HandleUpperLevelConfirmation implements
|
||||
// NUDHandler.HandleUpperLevelConfirmation by following the logic defined in
|
||||
// RFC 4861 section 7.3.1.
|
||||
func (n *neighborCache) HandleUpperLevelConfirmation(addr tcpip.Address) {
|
||||
n.mu.RLock()
|
||||
entry, ok := n.cache[addr]
|
||||
n.mu.RUnlock()
|
||||
if ok {
|
||||
entry.mu.Lock()
|
||||
entry.handleUpperLevelConfirmationLocked()
|
||||
entry.mu.Unlock()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,482 @@
|
||||
// Copyright 2020 The gVisor Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package stack
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/sleep"
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
)
|
||||
|
||||
// NeighborEntry describes a neighboring device in the local network.
|
||||
type NeighborEntry struct {
|
||||
Addr tcpip.Address
|
||||
LocalAddr tcpip.Address
|
||||
LinkAddr tcpip.LinkAddress
|
||||
State NeighborState
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// NeighborState defines the state of a NeighborEntry within the Neighbor
|
||||
// Unreachability Detection state machine, as per RFC 4861 section 7.3.2.
|
||||
type NeighborState uint8
|
||||
|
||||
const (
|
||||
// Unknown means reachability has not been verified yet. This is the initial
|
||||
// state of entries that have been created automatically by the Neighbor
|
||||
// Unreachability Detection state machine.
|
||||
Unknown NeighborState = iota
|
||||
// Incomplete means that there is an outstanding request to resolve the
|
||||
// address.
|
||||
Incomplete
|
||||
// Reachable means the path to the neighbor is functioning properly for both
|
||||
// receive and transmit paths.
|
||||
Reachable
|
||||
// Stale means reachability to the neighbor is unknown, but packets are still
|
||||
// able to be transmitted to the possibly stale link address.
|
||||
Stale
|
||||
// Delay means reachability to the neighbor is unknown and pending
|
||||
// confirmation from an upper-level protocol like TCP, but packets are still
|
||||
// able to be transmitted to the possibly stale link address.
|
||||
Delay
|
||||
// Probe means a reachability confirmation is actively being sought by
|
||||
// periodically retransmitting reachability probes until a reachability
|
||||
// confirmation is received, or until the max amount of probes has been sent.
|
||||
Probe
|
||||
// Static describes entries that have been explicitly added by the user. They
|
||||
// do not expire and are not deleted until explicitly removed.
|
||||
Static
|
||||
// Failed means traffic should not be sent to this neighbor since attempts of
|
||||
// reachability have returned inconclusive.
|
||||
Failed
|
||||
)
|
||||
|
||||
// neighborEntry implements a neighbor entry's individual node behavior, as per
|
||||
// RFC 4861 section 7.3.3. Neighbor Unreachability Detection operates in
|
||||
// parallel with the sending of packets to a neighbor, necessitating the
|
||||
// entry's lock to be acquired for all operations.
|
||||
type neighborEntry struct {
|
||||
neighborEntryEntry
|
||||
|
||||
nic *NIC
|
||||
protocol tcpip.NetworkProtocolNumber
|
||||
|
||||
// linkRes provides the functionality to send reachability probes, used in
|
||||
// Neighbor Unreachability Detection.
|
||||
linkRes LinkAddressResolver
|
||||
|
||||
// nudState points to the Neighbor Unreachability Detection configuration.
|
||||
nudState *NUDState
|
||||
|
||||
// mu protects the fields below.
|
||||
mu sync.RWMutex
|
||||
|
||||
neigh NeighborEntry
|
||||
|
||||
// wakers is a set of waiters for address resolution result. Anytime state
|
||||
// transitions out of incomplete these waiters are notified. It is nil iff
|
||||
// address resolution is ongoing and no clients are waiting for the result.
|
||||
wakers map[*sleep.Waker]struct{}
|
||||
|
||||
// done is used to allow callers to wait on address resolution. It is nil
|
||||
// iff nudState is not Reachable and address resolution is not yet in
|
||||
// progress.
|
||||
done chan struct{}
|
||||
|
||||
isRouter bool
|
||||
job *tcpip.Job
|
||||
}
|
||||
|
||||
// newNeighborEntry creates a neighbor cache entry starting at the default
|
||||
// state, Unknown. Transition out of Unknown by calling either
|
||||
// `handlePacketQueuedLocked` or `handleProbeLocked` on the newly created
|
||||
// neighborEntry.
|
||||
func newNeighborEntry(nic *NIC, remoteAddr tcpip.Address, localAddr tcpip.Address, nudState *NUDState, linkRes LinkAddressResolver) *neighborEntry {
|
||||
return &neighborEntry{
|
||||
nic: nic,
|
||||
linkRes: linkRes,
|
||||
nudState: nudState,
|
||||
neigh: NeighborEntry{
|
||||
Addr: remoteAddr,
|
||||
LocalAddr: localAddr,
|
||||
State: Unknown,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// newStaticNeighborEntry creates a neighbor cache entry starting at the Static
|
||||
// state. The entry can only transition out of Static by directly calling
|
||||
// `setStateLocked`.
|
||||
func newStaticNeighborEntry(nic *NIC, addr tcpip.Address, linkAddr tcpip.LinkAddress, state *NUDState) *neighborEntry {
|
||||
if nic.stack.nudDisp != nil {
|
||||
nic.stack.nudDisp.OnNeighborAdded(nic.id, addr, linkAddr, Static, time.Now())
|
||||
}
|
||||
return &neighborEntry{
|
||||
nic: nic,
|
||||
nudState: state,
|
||||
neigh: NeighborEntry{
|
||||
Addr: addr,
|
||||
LinkAddr: linkAddr,
|
||||
State: Static,
|
||||
UpdatedAt: time.Now(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// addWaker adds w to the list of wakers waiting for address resolution.
|
||||
// Assumes the entry has already been appropriately locked.
|
||||
func (e *neighborEntry) addWakerLocked(w *sleep.Waker) {
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
if e.wakers == nil {
|
||||
e.wakers = make(map[*sleep.Waker]struct{})
|
||||
}
|
||||
e.wakers[w] = struct{}{}
|
||||
}
|
||||
|
||||
// notifyWakersLocked notifies those waiting for address resolution, whether it
|
||||
// succeeded or failed. Assumes the entry has already been appropriately locked.
|
||||
func (e *neighborEntry) notifyWakersLocked() {
|
||||
for w := range e.wakers {
|
||||
w.Assert()
|
||||
}
|
||||
e.wakers = nil
|
||||
if ch := e.done; ch != nil {
|
||||
close(ch)
|
||||
e.done = nil
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchAddEventLocked signals to stack's NUD Dispatcher that the entry has
|
||||
// been added.
|
||||
func (e *neighborEntry) dispatchAddEventLocked(nextState NeighborState) {
|
||||
if nudDisp := e.nic.stack.nudDisp; nudDisp != nil {
|
||||
nudDisp.OnNeighborAdded(e.nic.id, e.neigh.Addr, e.neigh.LinkAddr, nextState, time.Now())
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchChangeEventLocked signals to stack's NUD Dispatcher that the entry
|
||||
// has changed state or link-layer address.
|
||||
func (e *neighborEntry) dispatchChangeEventLocked(nextState NeighborState) {
|
||||
if nudDisp := e.nic.stack.nudDisp; nudDisp != nil {
|
||||
nudDisp.OnNeighborChanged(e.nic.id, e.neigh.Addr, e.neigh.LinkAddr, nextState, time.Now())
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchRemoveEventLocked signals to stack's NUD Dispatcher that the entry
|
||||
// has been removed.
|
||||
func (e *neighborEntry) dispatchRemoveEventLocked() {
|
||||
if nudDisp := e.nic.stack.nudDisp; nudDisp != nil {
|
||||
nudDisp.OnNeighborRemoved(e.nic.id, e.neigh.Addr, e.neigh.LinkAddr, e.neigh.State, time.Now())
|
||||
}
|
||||
}
|
||||
|
||||
// setStateLocked transitions the entry to the specified state immediately.
|
||||
//
|
||||
// Follows the logic defined in RFC 4861 section 7.3.3.
|
||||
//
|
||||
// e.mu MUST be locked.
|
||||
func (e *neighborEntry) setStateLocked(next NeighborState) {
|
||||
// Cancel the previously scheduled action, if there is one. Entries in
|
||||
// Unknown, Stale, or Static state do not have scheduled actions.
|
||||
if timer := e.job; timer != nil {
|
||||
timer.Cancel()
|
||||
}
|
||||
|
||||
prev := e.neigh.State
|
||||
e.neigh.State = next
|
||||
e.neigh.UpdatedAt = time.Now()
|
||||
config := e.nudState.Config()
|
||||
|
||||
switch next {
|
||||
case Incomplete:
|
||||
var retryCounter uint32
|
||||
var sendMulticastProbe func()
|
||||
|
||||
sendMulticastProbe = func() {
|
||||
if retryCounter == config.MaxMulticastProbes {
|
||||
// "If no Neighbor Advertisement is received after
|
||||
// MAX_MULTICAST_SOLICIT solicitations, address resolution has failed.
|
||||
// The sender MUST return ICMP destination unreachable indications with
|
||||
// code 3 (Address Unreachable) for each packet queued awaiting address
|
||||
// resolution." - RFC 4861 section 7.2.2
|
||||
//
|
||||
// There is no need to send an ICMP destination unreachable indication
|
||||
// since the failure to resolve the address is expected to only occur
|
||||
// on this node. Thus, redirecting traffic is currently not supported.
|
||||
//
|
||||
// "If the error occurs on a node other than the node originating the
|
||||
// packet, an ICMP error message is generated. If the error occurs on
|
||||
// the originating node, an implementation is not required to actually
|
||||
// create and send an ICMP error packet to the source, as long as the
|
||||
// upper-layer sender is notified through an appropriate mechanism
|
||||
// (e.g. return value from a procedure call). Note, however, that an
|
||||
// implementation may find it convenient in some cases to return errors
|
||||
// to the sender by taking the offending packet, generating an ICMP
|
||||
// error message, and then delivering it (locally) through the generic
|
||||
// error-handling routines.' - RFC 4861 section 2.1
|
||||
e.dispatchRemoveEventLocked()
|
||||
e.setStateLocked(Failed)
|
||||
return
|
||||
}
|
||||
|
||||
if err := e.linkRes.LinkAddressRequest(e.neigh.Addr, e.neigh.LocalAddr, "", e.nic.linkEP); err != nil {
|
||||
// There is no need to log the error here; the NUD implementation may
|
||||
// assume a working link. A valid link should be the responsibility of
|
||||
// the NIC/stack.LinkEndpoint.
|
||||
e.dispatchRemoveEventLocked()
|
||||
e.setStateLocked(Failed)
|
||||
return
|
||||
}
|
||||
|
||||
retryCounter++
|
||||
e.job = e.nic.stack.newJob(&e.mu, sendMulticastProbe)
|
||||
e.job.Schedule(config.RetransmitTimer)
|
||||
}
|
||||
|
||||
sendMulticastProbe()
|
||||
|
||||
case Reachable:
|
||||
e.job = e.nic.stack.newJob(&e.mu, func() {
|
||||
e.dispatchChangeEventLocked(Stale)
|
||||
e.setStateLocked(Stale)
|
||||
})
|
||||
e.job.Schedule(e.nudState.ReachableTime())
|
||||
|
||||
case Delay:
|
||||
e.job = e.nic.stack.newJob(&e.mu, func() {
|
||||
e.dispatchChangeEventLocked(Probe)
|
||||
e.setStateLocked(Probe)
|
||||
})
|
||||
e.job.Schedule(config.DelayFirstProbeTime)
|
||||
|
||||
case Probe:
|
||||
var retryCounter uint32
|
||||
var sendUnicastProbe func()
|
||||
|
||||
sendUnicastProbe = func() {
|
||||
if retryCounter == config.MaxUnicastProbes {
|
||||
e.dispatchRemoveEventLocked()
|
||||
e.setStateLocked(Failed)
|
||||
return
|
||||
}
|
||||
|
||||
if err := e.linkRes.LinkAddressRequest(e.neigh.Addr, e.neigh.LocalAddr, e.neigh.LinkAddr, e.nic.linkEP); err != nil {
|
||||
e.dispatchRemoveEventLocked()
|
||||
e.setStateLocked(Failed)
|
||||
return
|
||||
}
|
||||
|
||||
retryCounter++
|
||||
if retryCounter == config.MaxUnicastProbes {
|
||||
e.dispatchRemoveEventLocked()
|
||||
e.setStateLocked(Failed)
|
||||
return
|
||||
}
|
||||
|
||||
e.job = e.nic.stack.newJob(&e.mu, sendUnicastProbe)
|
||||
e.job.Schedule(config.RetransmitTimer)
|
||||
}
|
||||
|
||||
sendUnicastProbe()
|
||||
|
||||
case Failed:
|
||||
e.notifyWakersLocked()
|
||||
e.job = e.nic.stack.newJob(&e.mu, func() {
|
||||
e.nic.neigh.removeEntryLocked(e)
|
||||
})
|
||||
e.job.Schedule(config.UnreachableTime)
|
||||
|
||||
case Unknown, Stale, Static:
|
||||
// Do nothing
|
||||
|
||||
default:
|
||||
panic(fmt.Sprintf("Invalid state transition from %q to %q", prev, next))
|
||||
}
|
||||
}
|
||||
|
||||
// handlePacketQueuedLocked advances the state machine according to a packet
|
||||
// being queued for outgoing transmission.
|
||||
//
|
||||
// Follows the logic defined in RFC 4861 section 7.3.3.
|
||||
func (e *neighborEntry) handlePacketQueuedLocked() {
|
||||
switch e.neigh.State {
|
||||
case Unknown:
|
||||
e.dispatchAddEventLocked(Incomplete)
|
||||
e.setStateLocked(Incomplete)
|
||||
|
||||
case Stale:
|
||||
e.dispatchChangeEventLocked(Delay)
|
||||
e.setStateLocked(Delay)
|
||||
|
||||
case Incomplete, Reachable, Delay, Probe, Static, Failed:
|
||||
// Do nothing
|
||||
|
||||
default:
|
||||
panic(fmt.Sprintf("Invalid cache entry state: %s", e.neigh.State))
|
||||
}
|
||||
}
|
||||
|
||||
// handleProbeLocked processes an incoming neighbor probe (e.g. ARP request or
|
||||
// Neighbor Solicitation for ARP or NDP, respectively).
|
||||
//
|
||||
// Follows the logic defined in RFC 4861 section 7.2.3.
|
||||
func (e *neighborEntry) handleProbeLocked(remoteLinkAddr tcpip.LinkAddress) {
|
||||
// Probes MUST be silently discarded if the target address is tentative, does
|
||||
// not exist, or not bound to the NIC as per RFC 4861 section 7.2.3. These
|
||||
// checks MUST be done by the NetworkEndpoint.
|
||||
|
||||
switch e.neigh.State {
|
||||
case Unknown, Incomplete, Failed:
|
||||
e.neigh.LinkAddr = remoteLinkAddr
|
||||
e.dispatchAddEventLocked(Stale)
|
||||
e.setStateLocked(Stale)
|
||||
e.notifyWakersLocked()
|
||||
|
||||
case Reachable, Delay, Probe:
|
||||
if e.neigh.LinkAddr != remoteLinkAddr {
|
||||
e.neigh.LinkAddr = remoteLinkAddr
|
||||
e.dispatchChangeEventLocked(Stale)
|
||||
e.setStateLocked(Stale)
|
||||
}
|
||||
|
||||
case Stale:
|
||||
if e.neigh.LinkAddr != remoteLinkAddr {
|
||||
e.neigh.LinkAddr = remoteLinkAddr
|
||||
e.dispatchChangeEventLocked(Stale)
|
||||
}
|
||||
|
||||
case Static:
|
||||
// Do nothing
|
||||
|
||||
default:
|
||||
panic(fmt.Sprintf("Invalid cache entry state: %s", e.neigh.State))
|
||||
}
|
||||
}
|
||||
|
||||
// handleConfirmationLocked processes an incoming neighbor confirmation
|
||||
// (e.g. ARP reply or Neighbor Advertisement for ARP or NDP, respectively).
|
||||
//
|
||||
// Follows the state machine defined by RFC 4861 section 7.2.5.
|
||||
//
|
||||
// TODO(gvisor.dev/issue/2277): To protect against ARP poisoning and other
|
||||
// attacks against NDP functions, Secure Neighbor Discovery (SEND) Protocol
|
||||
// should be deployed where preventing access to the broadcast segment might
|
||||
// not be possible. SEND uses RSA key pairs to produce Cryptographically
|
||||
// Generated Addresses (CGA), as defined in RFC 3972. This ensures that the
|
||||
// claimed source of an NDP message is the owner of the claimed address.
|
||||
func (e *neighborEntry) handleConfirmationLocked(linkAddr tcpip.LinkAddress, flags ReachabilityConfirmationFlags) {
|
||||
switch e.neigh.State {
|
||||
case Incomplete:
|
||||
if len(linkAddr) == 0 {
|
||||
// "If the link layer has addresses and no Target Link-Layer Address
|
||||
// option is included, the receiving node SHOULD silently discard the
|
||||
// received advertisement." - RFC 4861 section 7.2.5
|
||||
break
|
||||
}
|
||||
|
||||
e.neigh.LinkAddr = linkAddr
|
||||
if flags.Solicited {
|
||||
e.dispatchChangeEventLocked(Reachable)
|
||||
e.setStateLocked(Reachable)
|
||||
} else {
|
||||
e.dispatchChangeEventLocked(Stale)
|
||||
e.setStateLocked(Stale)
|
||||
}
|
||||
e.isRouter = flags.IsRouter
|
||||
e.notifyWakersLocked()
|
||||
|
||||
// "Note that the Override flag is ignored if the entry is in the
|
||||
// INCOMPLETE state." - RFC 4861 section 7.2.5
|
||||
|
||||
case Reachable, Stale, Delay, Probe:
|
||||
sameLinkAddr := e.neigh.LinkAddr == linkAddr
|
||||
|
||||
if !sameLinkAddr {
|
||||
if !flags.Override {
|
||||
if e.neigh.State == Reachable {
|
||||
e.dispatchChangeEventLocked(Stale)
|
||||
e.setStateLocked(Stale)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
e.neigh.LinkAddr = linkAddr
|
||||
|
||||
if !flags.Solicited {
|
||||
if e.neigh.State != Stale {
|
||||
e.dispatchChangeEventLocked(Stale)
|
||||
e.setStateLocked(Stale)
|
||||
} else {
|
||||
// Notify the LinkAddr change, even though NUD state hasn't changed.
|
||||
e.dispatchChangeEventLocked(e.neigh.State)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if flags.Solicited && (flags.Override || sameLinkAddr) {
|
||||
if e.neigh.State != Reachable {
|
||||
e.dispatchChangeEventLocked(Reachable)
|
||||
}
|
||||
// Set state to Reachable again to refresh timers.
|
||||
e.setStateLocked(Reachable)
|
||||
e.notifyWakersLocked()
|
||||
}
|
||||
|
||||
if e.isRouter && !flags.IsRouter {
|
||||
// "In those cases where the IsRouter flag changes from TRUE to FALSE as
|
||||
// a result of this update, the node MUST remove that router from the
|
||||
// Default Router List and update the Destination Cache entries for all
|
||||
// destinations using that neighbor as a router as specified in Section
|
||||
// 7.3.3. This is needed to detect when a node that is used as a router
|
||||
// stops forwarding packets due to being configured as a host."
|
||||
// - RFC 4861 section 7.2.5
|
||||
e.nic.mu.Lock()
|
||||
e.nic.mu.ndp.invalidateDefaultRouter(e.neigh.Addr)
|
||||
e.nic.mu.Unlock()
|
||||
}
|
||||
e.isRouter = flags.IsRouter
|
||||
|
||||
case Unknown, Failed, Static:
|
||||
// Do nothing
|
||||
|
||||
default:
|
||||
panic(fmt.Sprintf("Invalid cache entry state: %s", e.neigh.State))
|
||||
}
|
||||
}
|
||||
|
||||
// handleUpperLevelConfirmationLocked processes an incoming upper-level protocol
|
||||
// (e.g. TCP acknowledgements) reachability confirmation.
|
||||
func (e *neighborEntry) handleUpperLevelConfirmationLocked() {
|
||||
switch e.neigh.State {
|
||||
case Reachable, Stale, Delay, Probe:
|
||||
if e.neigh.State != Reachable {
|
||||
e.dispatchChangeEventLocked(Reachable)
|
||||
// Set state to Reachable again to refresh timers.
|
||||
}
|
||||
e.setStateLocked(Reachable)
|
||||
|
||||
case Unknown, Incomplete, Failed, Static:
|
||||
// Do nothing
|
||||
|
||||
default:
|
||||
panic(fmt.Sprintf("Invalid cache entry state: %s", e.neigh.State))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,44 @@
|
||||
// Copyright 2020 The gVisor Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Code generated by "stringer -type NeighborState"; DO NOT EDIT.
|
||||
|
||||
package stack
|
||||
|
||||
import "strconv"
|
||||
|
||||
func _() {
|
||||
// An "invalid array index" compiler error signifies that the constant values have changed.
|
||||
// Re-run the stringer command to generate them again.
|
||||
var x [1]struct{}
|
||||
_ = x[Unknown-0]
|
||||
_ = x[Incomplete-1]
|
||||
_ = x[Reachable-2]
|
||||
_ = x[Stale-3]
|
||||
_ = x[Delay-4]
|
||||
_ = x[Probe-5]
|
||||
_ = x[Static-6]
|
||||
_ = x[Failed-7]
|
||||
}
|
||||
|
||||
const _NeighborState_name = "UnknownIncompleteReachableStaleDelayProbeStaticFailed"
|
||||
|
||||
var _NeighborState_index = [...]uint8{0, 7, 17, 26, 31, 36, 41, 47, 53}
|
||||
|
||||
func (i NeighborState) String() string {
|
||||
if i >= NeighborState(len(_NeighborState_index)-1) {
|
||||
return "NeighborState(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||
}
|
||||
return _NeighborState_name[_NeighborState_index[i]:_NeighborState_index[i+1]]
|
||||
}
|
||||
@@ -16,6 +16,7 @@ package stack
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -45,6 +46,7 @@ type NIC struct {
|
||||
context NICContext
|
||||
|
||||
stats NICStats
|
||||
neigh *neighborCache
|
||||
|
||||
mu struct {
|
||||
sync.RWMutex
|
||||
@@ -141,6 +143,16 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC
|
||||
nic.mu.packetEPs[netProto.Number()] = []PacketEndpoint{}
|
||||
}
|
||||
|
||||
// Check for Neighbor Unreachability Detection support.
|
||||
if ep.Capabilities()&CapabilityResolutionRequired != 0 && len(stack.linkAddrResolvers) != 0 {
|
||||
rng := rand.New(rand.NewSource(stack.clock.NowNanoseconds()))
|
||||
nic.neigh = &neighborCache{
|
||||
nic: nic,
|
||||
state: NewNUDState(stack.nudConfigs, rng),
|
||||
cache: make(map[tcpip.Address]*neighborEntry, neighborCacheSize),
|
||||
}
|
||||
}
|
||||
|
||||
nic.linkEP.Attach(nic)
|
||||
|
||||
return nic
|
||||
@@ -1540,6 +1552,27 @@ func (n *NIC) setNDPConfigs(c NDPConfigurations) {
|
||||
n.mu.Unlock()
|
||||
}
|
||||
|
||||
// NUDConfigs gets the NUD configurations for n.
|
||||
func (n *NIC) NUDConfigs() (NUDConfigurations, *tcpip.Error) {
|
||||
if n.neigh == nil {
|
||||
return NUDConfigurations{}, tcpip.ErrNotSupported
|
||||
}
|
||||
return n.neigh.config(), nil
|
||||
}
|
||||
|
||||
// setNUDConfigs sets the NUD configurations for n.
|
||||
//
|
||||
// Note, if c contains invalid NUD configuration values, it will be fixed to
|
||||
// use default values for the erroneous values.
|
||||
func (n *NIC) setNUDConfigs(c NUDConfigurations) *tcpip.Error {
|
||||
if n.neigh == nil {
|
||||
return tcpip.ErrNotSupported
|
||||
}
|
||||
c.resetInvalidFields()
|
||||
n.neigh.setConfig(c)
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleNDPRA handles an NDP Router Advertisement message that arrived on n.
|
||||
func (n *NIC) handleNDPRA(ip tcpip.Address, ra header.NDPRouterAdvert) {
|
||||
n.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
// Copyright 2020 The gVisor Authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package stack
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gvisor.dev/gvisor/pkg/tcpip"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultBaseReachableTime is the default base duration for computing the
|
||||
// random reachable time.
|
||||
//
|
||||
// Reachable time is the duration for which a neighbor is considered
|
||||
// reachable after a positive reachability confirmation is received. It is a
|
||||
// function of a uniformly distributed random value between the minimum and
|
||||
// maximum random factors, multiplied by the base reachable time. Using a
|
||||
// random component eliminates the possibility that Neighbor Unreachability
|
||||
// Detection messages will synchronize with each other.
|
||||
//
|
||||
// Default taken from REACHABLE_TIME of RFC 4861 section 10.
|
||||
defaultBaseReachableTime = 30 * time.Second
|
||||
|
||||
// minimumBaseReachableTime is the minimum base duration for computing the
|
||||
// random reachable time.
|
||||
//
|
||||
// Minimum = 1ms
|
||||
minimumBaseReachableTime = time.Millisecond
|
||||
|
||||
// defaultMinRandomFactor is the default minimum value of the random factor
|
||||
// used for computing reachable time.
|
||||
//
|
||||
// Default taken from MIN_RANDOM_FACTOR of RFC 4861 section 10.
|
||||
defaultMinRandomFactor = 0.5
|
||||
|
||||
// defaultMaxRandomFactor is the default maximum value of the random factor
|
||||
// used for computing reachable time.
|
||||
//
|
||||
// The default value depends on the value of MinRandomFactor.
|
||||
// If MinRandomFactor is less than MAX_RANDOM_FACTOR of RFC 4861 section 10,
|
||||
// the value from the RFC will be used; otherwise, the default is
|
||||
// MinRandomFactor multiplied by three.
|
||||
defaultMaxRandomFactor = 1.5
|
||||
|
||||
// defaultRetransmitTimer is the default amount of time to wait between
|
||||
// sending reachability probes.
|
||||
//
|
||||
// Default taken from RETRANS_TIMER of RFC 4861 section 10.
|
||||
defaultRetransmitTimer = time.Second
|
||||
|
||||
// minimumRetransmitTimer is the minimum amount of time to wait between
|
||||
// sending reachability probes.
|
||||
//
|
||||
// Note, RFC 4861 does not impose a minimum Retransmit Timer, but we do here
|
||||
// to make sure the messages are not sent all at once. We also come to this
|
||||
// value because in the RetransmitTimer field of a Router Advertisement, a
|
||||
// value of 0 means unspecified, so the smallest valid value is 1. Note, the
|
||||
// unit of the RetransmitTimer field in the Router Advertisement is
|
||||
// milliseconds.
|
||||
minimumRetransmitTimer = time.Millisecond
|
||||
|
||||
// defaultDelayFirstProbeTime is the default duration to wait for a
|
||||
// non-Neighbor-Discovery related protocol to reconfirm reachability after
|
||||
// entering the DELAY state. After this time, a reachability probe will be
|
||||
// sent and the entry will transition to the PROBE state.
|
||||
//
|
||||
// Default taken from DELAY_FIRST_PROBE_TIME of RFC 4861 section 10.
|
||||
defaultDelayFirstProbeTime = 5 * time.Second
|
||||
|
||||
// defaultMaxMulticastProbes is the default number of reachabililty probes
|
||||
// to send before concluding negative reachability and deleting the neighbor
|
||||
// entry from the INCOMPLETE state.
|
||||
//
|
||||
// Default taken from MAX_MULTICAST_SOLICIT of RFC 4861 section 10.
|
||||
defaultMaxMulticastProbes = 3
|
||||
|
||||
// defaultMaxUnicastProbes is the default number of reachability probes to
|
||||
// send before concluding retransmission from within the PROBE state should
|
||||
// cease and the entry SHOULD be deleted.
|
||||
//
|
||||
// Default taken from MAX_UNICASE_SOLICIT of RFC 4861 section 10.
|
||||
defaultMaxUnicastProbes = 3
|
||||
|
||||
// defaultMaxAnycastDelayTime is the default time in which the stack SHOULD
|
||||
// delay sending a response for a random time between 0 and this time, if the
|
||||
// target address is an anycast address.
|
||||
//
|
||||
// Default taken from MAX_ANYCAST_DELAY_TIME of RFC 4861 section 10.
|
||||
defaultMaxAnycastDelayTime = time.Second
|
||||
|
||||
// defaultMaxReachbilityConfirmations is the default amount of unsolicited
|
||||
// reachability confirmation messages a node MAY send to all-node multicast
|
||||
// address when it determines its link-layer address has changed.
|
||||
//
|
||||
// Default taken from MAX_NEIGHBOR_ADVERTISEMENT of RFC 4861 section 10.
|
||||
defaultMaxReachbilityConfirmations = 3
|
||||
|
||||
// defaultUnreachableTime is the default duration for how long an entry will
|
||||
// remain in the FAILED state before being removed from the neighbor cache.
|
||||
//
|
||||
// Note, there is no equivalent protocol constant defined in RFC 4861. It
|
||||
// leaves the specifics of any garbage collection mechanism up to the
|
||||
// implementation.
|
||||
defaultUnreachableTime = 5 * time.Second
|
||||
)
|
||||
|
||||
// NUDDispatcher is the interface integrators of netstack must implement to
|
||||
// receive and handle NUD related events.
|
||||
type NUDDispatcher interface {
|
||||
// OnNeighborAdded will be called when a new entry is added to a NIC's (with
|
||||
// ID nicID) neighbor table.
|
||||
//
|
||||
// This function is permitted to block indefinitely without interfering with
|
||||
// the stack's operation.
|
||||
//
|
||||
// May be called concurrently.
|
||||
OnNeighborAdded(nicID tcpip.NICID, ipAddr tcpip.Address, linkAddr tcpip.LinkAddress, state NeighborState, updatedAt time.Time)
|
||||
|
||||
// OnNeighborChanged will be called when an entry in a NIC's (with ID nicID)
|
||||
// neighbor table changes state and/or link address.
|
||||
//
|
||||
// This function is permitted to block indefinitely without interfering with
|
||||
// the stack's operation.
|
||||
//
|
||||
// May be called concurrently.
|
||||
OnNeighborChanged(nicID tcpip.NICID, ipAddr tcpip.Address, linkAddr tcpip.LinkAddress, state NeighborState, updatedAt time.Time)
|
||||
|
||||
// OnNeighborRemoved will be called when an entry is removed from a NIC's
|
||||
// (with ID nicID) neighbor table.
|
||||
//
|
||||
// This function is permitted to block indefinitely without interfering with
|
||||
// the stack's operation.
|
||||
//
|
||||
// May be called concurrently.
|
||||
OnNeighborRemoved(nicID tcpip.NICID, ipAddr tcpip.Address, linkAddr tcpip.LinkAddress, state NeighborState, updatedAt time.Time)
|
||||
}
|
||||
|
||||
// ReachabilityConfirmationFlags describes the flags used within a reachability
|
||||
// confirmation (e.g. ARP reply or Neighbor Advertisement for ARP or NDP,
|
||||
// respectively).
|
||||
type ReachabilityConfirmationFlags struct {
|
||||
// Solicited indicates that the advertisement was sent in response to a
|
||||
// reachability probe.
|
||||
Solicited bool
|
||||
|
||||
// Override indicates that the reachability confirmation should override an
|
||||
// existing neighbor cache entry and update the cached link-layer address.
|
||||
// When Override is not set the confirmation will not update a cached
|
||||
// link-layer address, but will update an existing neighbor cache entry for
|
||||
// which no link-layer address is known.
|
||||
Override bool
|
||||
|
||||
// IsRouter indicates that the sender is a router.
|
||||
IsRouter bool
|
||||
}
|
||||
|
||||
// NUDHandler communicates external events to the Neighbor Unreachability
|
||||
// Detection state machine, which is implemented per-interface. This is used by
|
||||
// network endpoints to inform the Neighbor Cache of probes and confirmations.
|
||||
type NUDHandler interface {
|
||||
// HandleProbe processes an incoming neighbor probe (e.g. ARP request or
|
||||
// Neighbor Solicitation for ARP or NDP, respectively). Validation of the
|
||||
// probe needs to be performed before calling this function since the
|
||||
// Neighbor Cache doesn't have access to view the NIC's assigned addresses.
|
||||
HandleProbe(remoteAddr, localAddr tcpip.Address, protocol tcpip.NetworkProtocolNumber, remoteLinkAddr tcpip.LinkAddress)
|
||||
|
||||
// HandleConfirmation processes an incoming neighbor confirmation (e.g. ARP
|
||||
// reply or Neighbor Advertisement for ARP or NDP, respectively).
|
||||
HandleConfirmation(addr tcpip.Address, linkAddr tcpip.LinkAddress, flags ReachabilityConfirmationFlags)
|
||||
|
||||
// HandleUpperLevelConfirmation processes an incoming upper-level protocol
|
||||
// (e.g. TCP acknowledgements) reachability confirmation.
|
||||
HandleUpperLevelConfirmation(addr tcpip.Address)
|
||||
}
|
||||
|
||||
// NUDConfigurations is the NUD configurations for the netstack. This is used
|
||||
// by the neighbor cache to operate the NUD state machine on each device in the
|
||||
// local network.
|
||||
type NUDConfigurations struct {
|
||||
// BaseReachableTime is the base duration for computing the random reachable
|
||||
// time.
|
||||
//
|
||||
// Reachable time is the duration for which a neighbor is considered
|
||||
// reachable after a positive reachability confirmation is received. It is a
|
||||
// function of uniformly distributed random value between minRandomFactor and
|
||||
// maxRandomFactor multiplied by baseReachableTime. Using a random component
|
||||
// eliminates the possibility that Neighbor Unreachability Detection messages
|
||||
// will synchronize with each other.
|
||||
//
|
||||
// After this time, a neighbor entry will transition from REACHABLE to STALE
|
||||
// state.
|
||||
//
|
||||
// Must be greater than 0.
|
||||
BaseReachableTime time.Duration
|
||||
|
||||
// LearnBaseReachableTime enables learning BaseReachableTime during runtime
|
||||
// from the neighbor discovery protocol, if supported.
|
||||
//
|
||||
// TODO(gvisor.dev/issue/2240): Implement this NUD configuration option.
|
||||
LearnBaseReachableTime bool
|
||||
|
||||
// MinRandomFactor is the minimum value of the random factor used for
|
||||
// computing reachable time.
|
||||
//
|
||||
// See BaseReachbleTime for more information on computing the reachable time.
|
||||
//
|
||||
// Must be greater than 0.
|
||||
MinRandomFactor float32
|
||||
|
||||
// MaxRandomFactor is the maximum value of the random factor used for
|
||||
// computing reachabile time.
|
||||
//
|
||||
// See BaseReachbleTime for more information on computing the reachable time.
|
||||
//
|
||||
// Must be great than or equal to MinRandomFactor.
|
||||
MaxRandomFactor float32
|
||||
|
||||
// RetransmitTimer is the duration between retransmission of reachability
|
||||
// probes in the PROBE state.
|
||||
RetransmitTimer time.Duration
|
||||
|
||||
// LearnRetransmitTimer enables learning RetransmitTimer during runtime from
|
||||
// the neighbor discovery protocol, if supported.
|
||||
//
|
||||
// TODO(gvisor.dev/issue/2241): Implement this NUD configuration option.
|
||||
LearnRetransmitTimer bool
|
||||
|
||||
// DelayFirstProbeTime is the duration to wait for a non-Neighbor-Discovery
|
||||
// related protocol to reconfirm reachability after entering the DELAY state.
|
||||
// After this time, a reachability probe will be sent and the entry will
|
||||
// transition to the PROBE state.
|
||||
//
|
||||
// Must be greater than 0.
|
||||
DelayFirstProbeTime time.Duration
|
||||
|
||||
// MaxMulticastProbes is the number of reachability probes to send before
|
||||
// concluding negative reachability and deleting the neighbor entry from the
|
||||
// INCOMPLETE state.
|
||||
//
|
||||
// Must be greater than 0.
|
||||
MaxMulticastProbes uint32
|
||||
|
||||
// MaxUnicastProbes is the number of reachability probes to send before
|
||||
// concluding retransmission from within the PROBE state should cease and
|
||||
// entry SHOULD be deleted.
|
||||
//
|
||||
// Must be greater than 0.
|
||||
MaxUnicastProbes uint32
|
||||
|
||||
// MaxAnycastDelayTime is the time in which the stack SHOULD delay sending a
|
||||
// response for a random time between 0 and this time, if the target address
|
||||
// is an anycast address.
|
||||
//
|
||||
// TODO(gvisor.dev/issue/2242): Use this option when sending solicited
|
||||
// neighbor confirmations to anycast addresses and proxying neighbor
|
||||
// confirmations.
|
||||
MaxAnycastDelayTime time.Duration
|
||||
|
||||
// MaxReachabilityConfirmations is the number of unsolicited reachability
|
||||
// confirmation messages a node MAY send to all-node multicast address when
|
||||
// it determines its link-layer address has changed.
|
||||
//
|
||||
// TODO(gvisor.dev/issue/2246): Discuss if implementation of this NUD
|
||||
// configuration option is necessary.
|
||||
MaxReachabilityConfirmations uint32
|
||||
|
||||
// UnreachableTime describes how long an entry will remain in the FAILED
|
||||
// state before being removed from the neighbor cache.
|
||||
UnreachableTime time.Duration
|
||||
}
|
||||
|
||||
// DefaultNUDConfigurations returns a NUDConfigurations populated with default
|
||||
// values defined by RFC 4861 section 10.
|
||||
func DefaultNUDConfigurations() NUDConfigurations {
|
||||
return NUDConfigurations{
|
||||
BaseReachableTime: defaultBaseReachableTime,
|
||||
LearnBaseReachableTime: true,
|
||||
MinRandomFactor: defaultMinRandomFactor,
|
||||
MaxRandomFactor: defaultMaxRandomFactor,
|
||||
RetransmitTimer: defaultRetransmitTimer,
|
||||
LearnRetransmitTimer: true,
|
||||
DelayFirstProbeTime: defaultDelayFirstProbeTime,
|
||||
MaxMulticastProbes: defaultMaxMulticastProbes,
|
||||
MaxUnicastProbes: defaultMaxUnicastProbes,
|
||||
MaxAnycastDelayTime: defaultMaxAnycastDelayTime,
|
||||
MaxReachabilityConfirmations: defaultMaxReachbilityConfirmations,
|
||||
UnreachableTime: defaultUnreachableTime,
|
||||
}
|
||||
}
|
||||
|
||||
// resetInvalidFields modifies an invalid NDPConfigurations with valid values.
|
||||
// If invalid values are present in c, the corresponding default values will be
|
||||
// used instead. This is needed to check, and conditionally fix, user-specified
|
||||
// NUDConfigurations.
|
||||
func (c *NUDConfigurations) resetInvalidFields() {
|
||||
if c.BaseReachableTime < minimumBaseReachableTime {
|
||||
c.BaseReachableTime = defaultBaseReachableTime
|
||||
}
|
||||
if c.MinRandomFactor <= 0 {
|
||||
c.MinRandomFactor = defaultMinRandomFactor
|
||||
}
|
||||
if c.MaxRandomFactor < c.MinRandomFactor {
|
||||
c.MaxRandomFactor = calcMaxRandomFactor(c.MinRandomFactor)
|
||||
}
|
||||
if c.RetransmitTimer < minimumRetransmitTimer {
|
||||
c.RetransmitTimer = defaultRetransmitTimer
|
||||
}
|
||||
if c.DelayFirstProbeTime == 0 {
|
||||
c.DelayFirstProbeTime = defaultDelayFirstProbeTime
|
||||
}
|
||||
if c.MaxMulticastProbes == 0 {
|
||||
c.MaxMulticastProbes = defaultMaxMulticastProbes
|
||||
}
|
||||
if c.MaxUnicastProbes == 0 {
|
||||
c.MaxUnicastProbes = defaultMaxUnicastProbes
|
||||
}
|
||||
if c.UnreachableTime == 0 {
|
||||
c.UnreachableTime = defaultUnreachableTime
|
||||
}
|
||||
}
|
||||
|
||||
// calcMaxRandomFactor calculates the maximum value of the random factor used
|
||||
// for computing reachable time. This function is necessary for when the
|
||||
// default specified in RFC 4861 section 10 is less than the current
|
||||
// MinRandomFactor.
|
||||
//
|
||||
// Assumes minRandomFactor is positive since validation of the minimum value
|
||||
// should come before the validation of the maximum.
|
||||
func calcMaxRandomFactor(minRandomFactor float32) float32 {
|
||||
if minRandomFactor > defaultMaxRandomFactor {
|
||||
return minRandomFactor * 3
|
||||
}
|
||||
return defaultMaxRandomFactor
|
||||
}
|
||||
|
||||
// A Rand is a source of random numbers.
|
||||
type Rand interface {
|
||||
// Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).
|
||||
Float32() float32
|
||||
}
|
||||
|
||||
// NUDState stores states needed for calculating reachable time.
|
||||
type NUDState struct {
|
||||
rng Rand
|
||||
|
||||
// mu protects the fields below.
|
||||
//
|
||||
// It is necessary for NUDState to handle its own locking since neighbor
|
||||
// entries may access the NUD state from within the goroutine spawned by
|
||||
// time.AfterFunc(). This goroutine may run concurrently with the main
|
||||
// process for controlling the neighbor cache and would otherwise introduce
|
||||
// race conditions if NUDState was not locked properly.
|
||||
mu sync.RWMutex
|
||||
|
||||
config NUDConfigurations
|
||||
|
||||
// reachableTime is the duration to wait for a REACHABLE entry to
|
||||
// transition into STALE after inactivity. This value is calculated with
|
||||
// the algorithm defined in RFC 4861 section 6.3.2.
|
||||
reachableTime time.Duration
|
||||
|
||||
expiration time.Time
|
||||
prevBaseReachableTime time.Duration
|
||||
prevMinRandomFactor float32
|
||||
prevMaxRandomFactor float32
|
||||
}
|
||||
|
||||
// NewNUDState returns new NUDState using c as configuration and the specified
|
||||
// random number generator for use in recomputing ReachableTime.
|
||||
func NewNUDState(c NUDConfigurations, rng Rand) *NUDState {
|
||||
s := &NUDState{
|
||||
rng: rng,
|
||||
}
|
||||
s.config = c
|
||||
return s
|
||||
}
|
||||
|
||||
// Config returns the NUD configuration.
|
||||
func (s *NUDState) Config() NUDConfigurations {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.config
|
||||
}
|
||||
|
||||
// SetConfig replaces the existing NUD configurations with c.
|
||||
func (s *NUDState) SetConfig(c NUDConfigurations) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.config = c
|
||||
}
|
||||
|
||||
// ReachableTime returns the duration to wait for a REACHABLE entry to
|
||||
// transition into STALE after inactivity. This value is recalculated for new
|
||||
// values of BaseReachableTime, MinRandomFactor, and MaxRandomFactor using the
|
||||
// algorithm defined in RFC 4861 section 6.3.2.
|
||||
func (s *NUDState) ReachableTime() time.Duration {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if time.Now().After(s.expiration) ||
|
||||
s.config.BaseReachableTime != s.prevBaseReachableTime ||
|
||||
s.config.MinRandomFactor != s.prevMinRandomFactor ||
|
||||
s.config.MaxRandomFactor != s.prevMaxRandomFactor {
|
||||
return s.recomputeReachableTimeLocked()
|
||||
}
|
||||
return s.reachableTime
|
||||
}
|
||||
|
||||
// recomputeReachableTimeLocked forces a recalculation of ReachableTime using
|
||||
// the algorithm defined in RFC 4861 section 6.3.2.
|
||||
//
|
||||
// This SHOULD automatically be invoked during certain situations, as per
|
||||
// RFC 4861 section 6.3.4:
|
||||
//
|
||||
// If the received Reachable Time value is non-zero, the host SHOULD set its
|
||||
// BaseReachableTime variable to the received value. If the new value
|
||||
// differs from the previous value, the host SHOULD re-compute a new random
|
||||
// ReachableTime value. ReachableTime is computed as a uniformly
|
||||
// distributed random value between MIN_RANDOM_FACTOR and MAX_RANDOM_FACTOR
|
||||
// times the BaseReachableTime. Using a random component eliminates the
|
||||
// possibility that Neighbor Unreachability Detection messages will
|
||||
// synchronize with each other.
|
||||
//
|
||||
// In most cases, the advertised Reachable Time value will be the same in
|
||||
// consecutive Router Advertisements, and a host's BaseReachableTime rarely
|
||||
// changes. In such cases, an implementation SHOULD ensure that a new
|
||||
// random value gets re-computed at least once every few hours.
|
||||
//
|
||||
// s.mu MUST be locked for writing.
|
||||
func (s *NUDState) recomputeReachableTimeLocked() time.Duration {
|
||||
s.prevBaseReachableTime = s.config.BaseReachableTime
|
||||
s.prevMinRandomFactor = s.config.MinRandomFactor
|
||||
s.prevMaxRandomFactor = s.config.MaxRandomFactor
|
||||
|
||||
randomFactor := s.config.MinRandomFactor + s.rng.Float32()*(s.config.MaxRandomFactor-s.config.MinRandomFactor)
|
||||
|
||||
// Check for overflow, given that minRandomFactor and maxRandomFactor are
|
||||
// guaranteed to be positive numbers.
|
||||
if float32(math.MaxInt64)/randomFactor < float32(s.config.BaseReachableTime) {
|
||||
s.reachableTime = time.Duration(math.MaxInt64)
|
||||
} else if randomFactor == 1 {
|
||||
// Avoid loss of precision when a large base reachable time is used.
|
||||
s.reachableTime = s.config.BaseReachableTime
|
||||
} else {
|
||||
reachableTime := int64(float32(s.config.BaseReachableTime) * randomFactor)
|
||||
s.reachableTime = time.Duration(reachableTime)
|
||||
}
|
||||
|
||||
s.expiration = time.Now().Add(2 * time.Hour)
|
||||
return s.reachableTime
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -445,6 +445,9 @@ type Stack struct {
|
||||
// ndpConfigs is the default NDP configurations used by interfaces.
|
||||
ndpConfigs NDPConfigurations
|
||||
|
||||
// nudConfigs is the default NUD configurations used by interfaces.
|
||||
nudConfigs NUDConfigurations
|
||||
|
||||
// autoGenIPv6LinkLocal determines whether or not the stack will attempt
|
||||
// to auto-generate an IPv6 link-local address for newly enabled non-loopback
|
||||
// NICs. See the AutoGenIPv6LinkLocal field of Options for more details.
|
||||
@@ -454,6 +457,10 @@ type Stack struct {
|
||||
// integrator NDP related events.
|
||||
ndpDisp NDPDispatcher
|
||||
|
||||
// nudDisp is the NUD event dispatcher that is used to send the netstack
|
||||
// integrator NUD related events.
|
||||
nudDisp NUDDispatcher
|
||||
|
||||
// uniqueIDGenerator is a generator of unique identifiers.
|
||||
uniqueIDGenerator UniqueID
|
||||
|
||||
@@ -518,6 +525,9 @@ type Options struct {
|
||||
// before assigning an address to a NIC.
|
||||
NDPConfigs NDPConfigurations
|
||||
|
||||
// NUDConfigs is the default NUD configurations used by interfaces.
|
||||
NUDConfigs NUDConfigurations
|
||||
|
||||
// AutoGenIPv6LinkLocal determines whether or not the stack will attempt to
|
||||
// auto-generate an IPv6 link-local address for newly enabled non-loopback
|
||||
// NICs.
|
||||
@@ -536,6 +546,10 @@ type Options struct {
|
||||
// receive NDP related events.
|
||||
NDPDisp NDPDispatcher
|
||||
|
||||
// NUDDisp is the NUD event dispatcher that an integrator can provide to
|
||||
// receive NUD related events.
|
||||
NUDDisp NUDDispatcher
|
||||
|
||||
// RawFactory produces raw endpoints. Raw endpoints are enabled only if
|
||||
// this is non-nil.
|
||||
RawFactory RawFactory
|
||||
@@ -670,6 +684,8 @@ func New(opts Options) *Stack {
|
||||
// Make sure opts.NDPConfigs contains valid values only.
|
||||
opts.NDPConfigs.validate()
|
||||
|
||||
opts.NUDConfigs.resetInvalidFields()
|
||||
|
||||
s := &Stack{
|
||||
transportProtocols: make(map[tcpip.TransportProtocolNumber]*transportProtocolState),
|
||||
networkProtocols: make(map[tcpip.NetworkProtocolNumber]NetworkProtocol),
|
||||
@@ -685,9 +701,11 @@ func New(opts Options) *Stack {
|
||||
icmpRateLimiter: NewICMPRateLimiter(),
|
||||
seed: generateRandUint32(),
|
||||
ndpConfigs: opts.NDPConfigs,
|
||||
nudConfigs: opts.NUDConfigs,
|
||||
autoGenIPv6LinkLocal: opts.AutoGenIPv6LinkLocal,
|
||||
uniqueIDGenerator: opts.UniqueID,
|
||||
ndpDisp: opts.NDPDisp,
|
||||
nudDisp: opts.NUDDisp,
|
||||
opaqueIIDOpts: opts.OpaqueIIDOpts,
|
||||
tempIIDSeed: opts.TempIIDSeed,
|
||||
forwarder: newForwardQueue(),
|
||||
@@ -1869,10 +1887,38 @@ func (s *Stack) SetNDPConfigurations(id tcpip.NICID, c NDPConfigurations) *tcpip
|
||||
}
|
||||
|
||||
nic.setNDPConfigs(c)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NUDConfigurations gets the per-interface NUD configurations.
|
||||
func (s *Stack) NUDConfigurations(id tcpip.NICID) (NUDConfigurations, *tcpip.Error) {
|
||||
s.mu.RLock()
|
||||
nic, ok := s.nics[id]
|
||||
s.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return NUDConfigurations{}, tcpip.ErrUnknownNICID
|
||||
}
|
||||
|
||||
return nic.NUDConfigs()
|
||||
}
|
||||
|
||||
// SetNUDConfigurations sets the per-interface NUD configurations.
|
||||
//
|
||||
// Note, if c contains invalid NUD configuration values, it will be fixed to
|
||||
// use default values for the erroneous values.
|
||||
func (s *Stack) SetNUDConfigurations(id tcpip.NICID, c NUDConfigurations) *tcpip.Error {
|
||||
s.mu.RLock()
|
||||
nic, ok := s.nics[id]
|
||||
s.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return tcpip.ErrUnknownNICID
|
||||
}
|
||||
|
||||
return nic.setNUDConfigs(c)
|
||||
}
|
||||
|
||||
// HandleNDPRA provides a NIC with ID id a validated NDP Router Advertisement
|
||||
// message that it needs to handle.
|
||||
func (s *Stack) HandleNDPRA(id tcpip.NICID, ip tcpip.Address, ra header.NDPRouterAdvert) *tcpip.Error {
|
||||
|
||||
Reference in New Issue
Block a user