-
-
Notifications
You must be signed in to change notification settings - Fork 513
/
stack.go
264 lines (231 loc) · 8.01 KB
/
stack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package vif
import (
"context"
"fmt"
"net"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
"gvisor.dev/gvisor/pkg/waiter"
"github.com/datawire/dlib/dlog"
"github.com/telepresenceio/telepresence/v2/pkg/tunnel"
)
func NewStack(ctx context.Context, dev stack.LinkEndpoint, streamCreator tunnel.StreamCreator) (*stack.Stack, error) {
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{
ipv4.NewProtocol,
ipv6.NewProtocol,
},
TransportProtocols: []stack.TransportProtocolFactory{
icmp.NewProtocol4,
icmp.NewProtocol6,
tcp.NewProtocol,
udp.NewProtocol,
},
HandleLocal: false,
})
if err := setDefaultOptions(s); err != nil {
return nil, err
}
if err := setNIC(ctx, s, dev); err != nil {
return nil, err
}
setTCPHandler(ctx, s, streamCreator)
setUDPHandler(ctx, s, streamCreator)
return s, nil
}
const (
myWindowScale = 6
maxReceiveWindow = 1 << (myWindowScale + 14) // 1MiB
)
// maxInFlight specifies the max number of in-flight connection attempts.
const maxInFlight = 512
// keepAliveIdle is used as the very first alive interval. Subsequent intervals
// use keepAliveInterval.
const keepAliveIdle = 60 * time.Second
// keepAliveInterval is the interval between sending keep-alive packets.
const keepAliveInterval = 30 * time.Second
// keepAliveCount is the max number of keep-alive probes that can be sent
// before the connection is killed due to lack of response.
const keepAliveCount = 9
type idStringer stack.TransportEndpointID
func (i idStringer) String() string {
return fmt.Sprintf("%s:%d -> %s:%d", i.RemoteAddress, i.RemotePort, i.LocalAddress, i.LocalPort)
}
func setDefaultOptions(s *stack.Stack) error {
// Forwarding
if err := s.SetForwardingDefaultAndAllNICs(ipv4.ProtocolNumber, true); err != nil {
return fmt.Errorf("SetForwardingDefaultAndAllNICs(ipv4, %t): %s", true, err)
}
if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {
return fmt.Errorf("SetForwardingDefaultAndAllNICs(ipv6, %t): %s", true, err)
}
ttl := tcpip.DefaultTTLOption(64)
if err := s.SetNetworkProtocolOption(ipv4.ProtocolNumber, &ttl); err != nil {
return fmt.Errorf("SetDefaultTTL(ipv4, %d): %s", ttl, err)
}
if err := s.SetNetworkProtocolOption(ipv6.ProtocolNumber, &ttl); err != nil {
return fmt.Errorf("SetDefaultTTL(ipv6, %d): %s", ttl, err)
}
return nil
}
func setNIC(ctx context.Context, s *stack.Stack, ep stack.LinkEndpoint) error {
nicID := tcpip.NICID(s.UniqueID())
if err := s.CreateNICWithOptions(nicID, ep, stack.NICOptions{Name: "tel", Context: ctx}); err != nil {
return fmt.Errorf("create NIC failed: %s", err)
}
if err := s.SetPromiscuousMode(nicID, true); err != nil {
return fmt.Errorf("SetPromiscuousMode(%d, %t): %s", nicID, true, err)
}
if err := s.SetSpoofing(nicID, true); err != nil {
return fmt.Errorf("SetSpoofing(%d, %t): %s", nicID, true, err)
}
s.SetRouteTable([]tcpip.Route{
{
Destination: header.IPv4EmptySubnet,
NIC: nicID,
},
{
Destination: header.IPv6EmptySubnet,
NIC: nicID,
},
})
return nil
}
func setTCPHandler(ctx context.Context, s *stack.Stack, streamCreator tunnel.StreamCreator) {
f := tcp.NewForwarder(s, maxReceiveWindow, maxInFlight, func(fr *tcp.ForwarderRequest) {
var ep tcpip.Endpoint
var err tcpip.Error
id := fr.ID()
ctx, span := otel.GetTracerProvider().Tracer("").Start(ctx, "TCPHandler",
trace.WithNewRoot(),
trace.WithAttributes(
attribute.String("tel2.remote-ip", id.RemoteAddress.To4().String()),
attribute.String("tel2.local-ip", id.LocalAddress.To4().String()),
attribute.Int("tel2.local-port", int(id.LocalPort)),
attribute.Int("tel2.remote-port", int(id.RemotePort)),
))
defer func() {
if err != nil {
msg := fmt.Sprintf("forward TCP %s: %s", idStringer(id), err)
span.SetStatus(codes.Error, msg)
dlog.Errorf(ctx, msg)
}
span.End()
}()
wq := waiter.Queue{}
if ep, err = fr.CreateEndpoint(&wq); err != nil {
fr.Complete(true)
return
}
defer fr.Complete(false)
so := ep.SocketOptions()
so.SetKeepAlive(true)
idle := tcpip.KeepaliveIdleOption(keepAliveIdle)
if err = ep.SetSockOpt(&idle); err != nil {
return
}
ivl := tcpip.KeepaliveIntervalOption(keepAliveInterval)
if err = ep.SetSockOpt(&ivl); err != nil {
return
}
if err = ep.SetSockOptInt(tcpip.KeepaliveCountOption, keepAliveCount); err != nil {
return
}
var rs tcpip.TCPReceiveBufferSizeRangeOption
if err = s.TransportProtocolOption(header.TCPProtocolNumber, &rs); err != nil {
return
}
so.SetReceiveBufferSize(int64(rs.Default), false)
var ss tcpip.TCPSendBufferSizeRangeOption
if err = s.TransportProtocolOption(header.TCPProtocolNumber, &ss); err != nil {
return
}
so.SetSendBufferSize(int64(ss.Default), false)
if err = s.SetTransportProtocolOption(tcp.ProtocolNumber,
&tcpip.TCPSendBufferSizeRangeOption{
Min: tcp.MinBufferSize,
Default: tcp.DefaultSendBufferSize,
Max: tcp.MaxBufferSize,
}); err != nil {
return
}
if err = s.SetTransportProtocolOption(tcp.ProtocolNumber,
&tcpip.TCPReceiveBufferSizeRangeOption{
Min: tcp.MinBufferSize,
Default: tcp.DefaultSendBufferSize,
Max: tcp.MaxBufferSize,
}); err != nil {
return
}
sa := tcpip.TCPSACKEnabled(true)
s.SetTransportProtocolOption(tcp.ProtocolNumber, &sa)
// Enable Receive Buffer Auto-Tuning, see:
// https://github.com/google/gvisor/issues/1666
mo := tcpip.TCPModerateReceiveBufferOption(true)
s.SetTransportProtocolOption(tcp.ProtocolNumber, &mo)
dispatchToStream(ctx, newConnID(header.TCPProtocolNumber, id), gonet.NewTCPConn(&wq, ep), streamCreator)
})
s.SetTransportProtocolHandler(tcp.ProtocolNumber, f.HandlePacket)
}
var blockedUDPPorts = map[uint16]bool{ //nolint:gochecknoglobals // constant
137: true, // NETBIOS Name Service
138: true, // NETBIOS Datagram Service
139: true, // NETBIOS
}
func setUDPHandler(ctx context.Context, s *stack.Stack, streamCreator tunnel.StreamCreator) {
f := udp.NewForwarder(s, func(fr *udp.ForwarderRequest) {
id := fr.ID()
ctx, span := otel.GetTracerProvider().Tracer("").Start(ctx, "UDPHandler",
trace.WithNewRoot(),
trace.WithAttributes(
attribute.String("tel2.remote-ip", id.RemoteAddress.To4().String()),
attribute.String("tel2.local-ip", id.LocalAddress.To4().String()),
attribute.Int("tel2.local-port", int(id.LocalPort)),
attribute.Int("tel2.remote-port", int(id.RemotePort)),
attribute.Bool("tel2.port-blocked", false),
))
defer span.End()
if _, ok := blockedUDPPorts[id.LocalPort]; ok {
span.SetAttributes(attribute.Bool("tel2.port-blocked", true))
return
}
wq := waiter.Queue{}
ep, err := fr.CreateEndpoint(&wq)
if err != nil {
msg := fmt.Sprintf("forward UDP %s: %s", idStringer(id), err)
span.SetStatus(codes.Error, msg)
dlog.Errorf(ctx, msg)
return
}
dispatchToStream(ctx, newConnID(udp.ProtocolNumber, id), gonet.NewUDPConn(s, &wq, ep), streamCreator)
})
s.SetTransportProtocolHandler(udp.ProtocolNumber, f.HandlePacket)
}
func newConnID(proto tcpip.TransportProtocolNumber, id stack.TransportEndpointID) tunnel.ConnID {
return tunnel.NewConnID(int(proto), ([]byte)(id.RemoteAddress), ([]byte)(id.LocalAddress), id.RemotePort, id.LocalPort)
}
func dispatchToStream(ctx context.Context, id tunnel.ConnID, conn net.Conn, streamCreator tunnel.StreamCreator) {
ctx, cancel := context.WithCancel(ctx)
stream, err := streamCreator(ctx, id)
if err != nil {
if err != nil {
dlog.Errorf(ctx, "forward %s: %s", id, err)
}
cancel()
return
}
ep := tunnel.NewConnEndpoint(stream, conn, cancel)
ep.Start(ctx)
}