-
Notifications
You must be signed in to change notification settings - Fork 1
/
unetstack.go
492 lines (414 loc) · 12.4 KB
/
unetstack.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
package netem
//
// UNetStack: userspace network stack.
//
import (
"context"
"crypto/tls"
"crypto/x509"
"net"
"net/netip"
"strings"
"syscall"
"time"
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
)
// UNetStack is a network stack in user space. The zero value is
// invalid; please, use [NewUNetStack] to construct.
//
// Because [UNetStack] implements [UnderlyingNetwork], you can use
// it to perform the following operations:
//
// - connect TCP/UDP sockets using [UNetStack.DialContext];
//
// - create listening UDP sockets using [UNetStack.ListenUDP];
//
// - create listening TCP sockets using [UNetStack.ListenTCP];
//
// - perform getaddrinfo like DNS lookups using [UNetStack.GetaddrinfoLookupANY];
//
// Use [UNetStack.NIC] to obtain a [NIC] to read and write the [Frames]
// produced by using the network stack as the [UnderlyingNetwork].
type UNetStack struct {
// ca is the underlying CA.
ca *CA
// ns is the GVisor network stack.
ns *gvisorStack
// resoAddr is the resolver IPv4 address.
resoAddr netip.Addr
}
var (
_ CertificationAuthority = &UNetStack{}
_ HTTPUnderlyingNetwork = &UNetStack{}
_ NIC = &UNetStack{}
_ UnderlyingNetwork = &UNetStack{}
)
// NewUNetStack constructs a new [UNetStack] instance.
//
// Arguments:
//
// - logger is the logger to use;
//
// - MTU is the MTU to use (you MUST use at least 1252 bytes if you
// want to use github.com/lucas-clemente/quic-go);
//
// - stackAddress is the IPv4 address to assign to the stack;
//
// - cfg contains TLS MITM configuration;
//
// - resolverAddress is the IPv4 address of the resolver.
func NewUNetStack(
logger Logger,
MTU uint32,
stackAddress string,
ca *CA,
resolverAddress string,
) (*UNetStack, error) {
// parse the stack address
stackAddr, err := netip.ParseAddr(stackAddress)
if err != nil {
return nil, err
}
if !stackAddr.Is4() {
return nil, syscall.EAFNOSUPPORT
}
// parse the resolver address
resolverAddr, err := netip.ParseAddr(resolverAddress)
if err != nil {
return nil, err
}
if !resolverAddr.Is4() {
return nil, syscall.EAFNOSUPPORT
}
// create userspace network stack
ns, err := newGVisorStack(logger, stackAddr, MTU)
if err != nil {
return nil, err
}
// fill and return the network stack
stack := &UNetStack{
ca: ca,
ns: ns,
resoAddr: resolverAddr,
}
return stack, nil
}
// CACert implements CertificationAuthority.
func (gs *UNetStack) CACert() *x509.Certificate {
return gs.ca.CACert()
}
// DefaultCertPool implements CertificationAuthority.
func (gs *UNetStack) DefaultCertPool() *x509.CertPool {
return gs.ca.DefaultCertPool()
}
// MustNewServerTLSConfig implements CertificationAuthority.
func (gs *UNetStack) MustNewServerTLSConfig(commonName string, extraNames ...string) *tls.Config {
return gs.ca.MustNewServerTLSConfig(commonName, extraNames...)
}
// MustNewTLSCertificate implements implements CertificationAuthority.
func (gs *UNetStack) MustNewTLSCertificate(commonName string, extraNames ...string) *tls.Certificate {
return gs.ca.MustNewTLSCertificate(commonName, extraNames...)
}
// MustNewTLSCertificateWithTimeNow implements CertificationAuthority.
func (gs *UNetStack) MustNewTLSCertificateWithTimeNow(timeNow func() time.Time,
commonName string, extraNames ...string) *tls.Certificate {
return gs.ca.MustNewTLSCertificateWithTimeNow(timeNow, commonName, extraNames...)
}
// Logger implements HTTPUnderlyingNetwork.
func (gs *UNetStack) Logger() Logger {
return gs.ns.logger
}
// FrameAvailable implements NIC
func (gs *UNetStack) FrameAvailable() <-chan any {
return gs.ns.FrameAvailable()
}
// ReadFrameNonblocking implements NIC
func (gs *UNetStack) ReadFrameNonblocking() (*Frame, error) {
return gs.ns.ReadFrameNonblocking()
}
// StackClosed implements NIC
func (gs *UNetStack) StackClosed() <-chan any {
return gs.ns.StackClosed()
}
// IPAddress implements NIC
func (gs *UNetStack) IPAddress() string {
return gs.ns.IPAddress()
}
// InterfaceName implements NIC
func (gs *UNetStack) InterfaceName() string {
return gs.ns.InterfaceName()
}
// WriteFrame implements NIC
func (gs *UNetStack) WriteFrame(frame *Frame) error {
return gs.ns.WriteFrame(frame)
}
// Close shuts down the virtual network stack.
func (gs *UNetStack) Close() error {
return gs.ns.Close()
}
// DialContext implements UnderlyingNetwork.
func (gs *UNetStack) DialContext(
ctx context.Context, network string, address string) (net.Conn, error) {
var (
conn net.Conn
err error
)
// parse the address into a [netip.Addr]
addrport, err := netip.ParseAddrPort(address)
if err != nil {
return nil, err
}
// determine what "dial" actualls means in this context (sorry)
switch network {
case "tcp":
conn, err = gs.ns.DialContextTCPAddrPort(ctx, addrport)
case "udp":
conn, err = gs.ns.DialUDPAddrPort(netip.AddrPort{}, addrport)
default:
return nil, syscall.EPROTOTYPE
}
// make sure we return an error on failure
if err != nil {
return nil, mapUNetError(err)
}
// wrap returned connection to correctly map errors
return &unetConnWrapper{conn}, nil
}
// GetaddrinfoLookupANY implements UnderlyingNetwork.
func (gs *UNetStack) GetaddrinfoLookupANY(ctx context.Context, domain string) ([]string, string, error) {
// shortcircuit IP addresses
if net.ParseIP(domain) != nil {
return []string{domain}, "", nil
}
// create the query message
query := NewDNSRequestA(domain)
// perform the DNS round trip
resp, err := DNSRoundTrip(ctx, gs, gs.resoAddr.String(), query)
if err != nil {
return nil, "", err
}
// parse the results into a getaddrinfo result
return DNSParseResponse(query, resp)
}
// GetaddrinfoResolverNetwork implements UnderlyingNetwork
func (gs *UNetStack) GetaddrinfoResolverNetwork() string {
return "getaddrinfo" // pretend we are calling the getaddrinfo(3) func
}
// ListenUDP implements UnderlyingNetwork.
func (gs *UNetStack) ListenUDP(network string, addr *net.UDPAddr) (UDPLikeConn, error) {
if network != "udp" {
return nil, syscall.EPROTOTYPE
}
// convert addr to [netip.AddrPort]
ipaddr, good := netip.AddrFromSlice(addr.IP)
if !good {
return nil, syscall.EADDRNOTAVAIL
}
addrport := netip.AddrPortFrom(ipaddr, uint16(addr.Port))
pconn, err := gs.ns.DialUDPAddrPort(addrport, netip.AddrPort{})
if err != nil {
return nil, mapUNetError(err)
}
return &unetPacketConnWrapper{pconn}, nil
}
// ListenTCP implements UnderlyingNetwork
func (gs *UNetStack) ListenTCP(network string, addr *net.TCPAddr) (net.Listener, error) {
if network != "tcp" {
return nil, syscall.EPROTOTYPE
}
// convert addr to [netip.AddrPort]
ipaddr, good := netip.AddrFromSlice(addr.IP)
if !good {
return nil, syscall.EADDRNOTAVAIL
}
addrport := netip.AddrPortFrom(ipaddr, uint16(addr.Port))
listener, err := gs.ns.ListenTCPAddrPort(addrport)
if err != nil {
return nil, mapUNetError(err)
}
return &unetListenerWrapper{listener}, nil
}
// unetSuffixToError maps a gvisor error suffix to an stdlib error.
type unetSuffixToError struct {
// suffix is the unet err.Error() suffix.
suffix string
// err is generally a syscall error but it could
// also be any other stdlib error.
err error
}
// allUNetSyscallErrors defines [unetSuffixToError] rules for all the
// errors emitted by unet that matter to measuring censorship.
//
// See https://github.com/google/gvisor/blob/master/pkg/tcpip/errors.go
//
// See https://github.com/google/gvisor/blob/master/pkg/syserr/netstack.go
var allUNetSyscallErrors = []*unetSuffixToError{{
suffix: "endpoint is closed for receive",
err: net.ErrClosed,
}, {
suffix: "endpoint is closed for send",
err: net.ErrClosed,
}, {
suffix: "connection aborted",
err: syscall.ECONNABORTED,
}, {
suffix: "connection was refused",
err: syscall.ECONNREFUSED,
}, {
suffix: "connection reset by peer",
err: syscall.ECONNRESET,
}, {
suffix: "network is unreachable",
err: syscall.ENETUNREACH,
}, {
suffix: "no route to host",
err: syscall.EHOSTUNREACH,
}, {
suffix: "host is down",
err: syscall.EHOSTDOWN,
}, {
suffix: "machine is not on the network",
err: syscall.ENETDOWN,
}, {
suffix: "operation timed out",
err: syscall.ETIMEDOUT,
}, {
suffix: "endpoint is in invalid state",
err: syscall.EINVAL,
}}
// mapUNetError maps a unet error to an stdlib error.
func mapUNetError(err error) error {
if err != nil {
estring := err.Error()
for _, entry := range allUNetSyscallErrors {
if strings.HasSuffix(estring, entry.suffix) {
return entry.err
}
}
}
return err
}
// unetConnWrapper wraps a [net.Conn] to remap unet errors
// so that we can emulate stdlib errors.
type unetConnWrapper struct {
c net.Conn
}
var _ net.Conn = &unetConnWrapper{}
// Close implements net.Conn
func (gcw *unetConnWrapper) Close() error {
return gcw.c.Close()
}
// LocalAddr implements net.Conn
func (gcw *unetConnWrapper) LocalAddr() net.Addr {
return gcw.c.LocalAddr()
}
// Read implements net.Conn
func (gcw *unetConnWrapper) Read(b []byte) (n int, err error) {
count, err := gcw.c.Read(b)
return count, mapUNetError(err)
}
// RemoteAddr implements net.Conn
func (gcw *unetConnWrapper) RemoteAddr() net.Addr {
return gcw.c.RemoteAddr()
}
// SetDeadline implements net.Conn
func (gcw *unetConnWrapper) SetDeadline(t time.Time) error {
return gcw.c.SetDeadline(t)
}
// SetReadDeadline implements net.Conn
func (gcw *unetConnWrapper) SetReadDeadline(t time.Time) error {
return gcw.c.SetReadDeadline(t)
}
// SetWriteDeadline implements net.Conn
func (gcw *unetConnWrapper) SetWriteDeadline(t time.Time) error {
return gcw.c.SetWriteDeadline(t)
}
// Write implements net.Conn
func (gcw *unetConnWrapper) Write(b []byte) (n int, err error) {
count, err := gcw.c.Write(b)
return count, mapUNetError(err)
}
// unetPacketConnWrapper wraps a [model.UDPLikeConn] such that we can use
// this connection with lucas-clemente/quic-go and remaps unet errors to
// emulate actual stdlib errors.
type unetPacketConnWrapper struct {
c *gonet.UDPConn
}
var (
_ UDPLikeConn = &unetPacketConnWrapper{}
_ syscall.RawConn = &unetPacketConnWrapper{}
)
// Close implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) Close() error {
return gpcw.c.Close()
}
// LocalAddr implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) LocalAddr() net.Addr {
return gpcw.c.LocalAddr()
}
// ReadFrom implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) ReadFrom(p []byte) (int, net.Addr, error) {
count, addr, err := gpcw.c.ReadFrom(p)
return count, addr, mapUNetError(err)
}
// SetDeadline implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) SetDeadline(t time.Time) error {
return gpcw.c.SetDeadline(t)
}
// SetReadDeadline implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) SetReadDeadline(t time.Time) error {
return gpcw.c.SetReadDeadline(t)
}
// SetWriteDeadline implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) SetWriteDeadline(t time.Time) error {
return gpcw.c.SetWriteDeadline(t)
}
// WriteTo implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) WriteTo(p []byte, addr net.Addr) (int, error) {
count, err := gpcw.c.WriteTo(p, addr)
return count, mapUNetError(err)
}
// Implementation note: the following function calls are all stubs and they
// should nonetheless work with lucas-clemente/quic-go.
// SetReadBuffer implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) SetReadBuffer(bytes int) error {
return nil
}
// SyscallConn implements model.UDPLikeConn
func (gpcw *unetPacketConnWrapper) SyscallConn() (syscall.RawConn, error) {
return gpcw, nil
}
// Control implements syscall.RawConn
func (gpcw *unetPacketConnWrapper) Control(f func(fd uintptr)) error {
return nil
}
// Read implements syscall.RawConn
func (gpcw *unetPacketConnWrapper) Read(f func(fd uintptr) (done bool)) error {
return nil
}
// Write implements syscall.RawConn
func (gpcw *unetPacketConnWrapper) Write(f func(fd uintptr) (done bool)) error {
return nil
}
// unetListenerWrapper wraps a [net.Listener] and maps unet
// errors to the corresponding stdlib errors.
type unetListenerWrapper struct {
l *gonet.TCPListener
}
var _ net.Listener = &unetListenerWrapper{}
// Accept implements net.Listener
func (glw *unetListenerWrapper) Accept() (net.Conn, error) {
conn, err := glw.l.Accept()
if err != nil {
return nil, mapUNetError(err)
}
return &unetConnWrapper{conn}, nil
}
// Addr implements net.Listener
func (glw *unetListenerWrapper) Addr() net.Addr {
return glw.l.Addr()
}
// Close implements net.Listener
func (glw *unetListenerWrapper) Close() error {
return glw.l.Close()
}