| 1 |
package service |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"log" |
| 9 |
"math" |
| 10 |
"net" |
| 11 |
"net/netip" |
| 12 |
"strings" |
| 13 |
"sync" |
| 14 |
|
| 15 |
"github.com/slackhq/nebula" |
| 16 |
"github.com/slackhq/nebula/overlay" |
| 17 |
"golang.org/x/sync/errgroup" |
| 18 |
"gvisor.dev/gvisor/pkg/buffer" |
| 19 |
"gvisor.dev/gvisor/pkg/tcpip" |
| 20 |
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet" |
| 21 |
"gvisor.dev/gvisor/pkg/tcpip/header" |
| 22 |
"gvisor.dev/gvisor/pkg/tcpip/link/channel" |
| 23 |
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4" |
| 24 |
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6" |
| 25 |
"gvisor.dev/gvisor/pkg/tcpip/stack" |
| 26 |
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp" |
| 27 |
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp" |
| 28 |
"gvisor.dev/gvisor/pkg/tcpip/transport/udp" |
| 29 |
"gvisor.dev/gvisor/pkg/waiter" |
| 30 |
) |
| 31 |
|
| 32 |
const nicID = 1 |
| 33 |
|
| 34 |
type Service struct { |
| 35 |
eg *errgroup.Group |
| 36 |
control *nebula.Control |
| 37 |
ipstack *stack.Stack |
| 38 |
|
| 39 |
mu struct { |
| 40 |
sync.Mutex |
| 41 |
|
| 42 |
listeners map[uint16]*tcpListener |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
func New(control *nebula.Control) (_ *Service, reterr error) { |
| 47 |
// Check this before Start so a failure doesn't leave a running nebula |
| 48 |
device, ok := control.Device().(*overlay.UserDevice) |
| 49 |
if !ok { |
| 50 |
return nil, errors.New("must be using user device") |
| 51 |
} |
| 52 |
|
| 53 |
err := control.Start() |
| 54 |
if err != nil { |
| 55 |
return nil, err |
| 56 |
} |
| 57 |
|
| 58 |
// Anything that fails after a successful Start must tear nebula back down |
| 59 |
defer func() { |
| 60 |
if reterr != nil { |
| 61 |
control.Stop() |
| 62 |
} |
| 63 |
}() |
| 64 |
|
| 65 |
ctx := control.Context() |
| 66 |
eg, ctx := errgroup.WithContext(ctx) |
| 67 |
s := Service{ |
| 68 |
eg: eg, |
| 69 |
control: control, |
| 70 |
} |
| 71 |
s.mu.listeners = map[uint16]*tcpListener{} |
| 72 |
|
| 73 |
s.ipstack = stack.New(stack.Options{ |
| 74 |
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol}, |
| 75 |
TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol, udp.NewProtocol, icmp.NewProtocol4, icmp.NewProtocol6}, |
| 76 |
}) |
| 77 |
sackEnabledOpt := tcpip.TCPSACKEnabled(true) // TCP SACK is disabled by default |
| 78 |
tcpipErr := s.ipstack.SetTransportProtocolOption(tcp.ProtocolNumber, &sackEnabledOpt) |
| 79 |
if tcpipErr != nil { |
| 80 |
return nil, fmt.Errorf("could not enable TCP SACK: %v", tcpipErr) |
| 81 |
} |
| 82 |
linkEP := channel.New( /*size*/ 512 /*mtu*/, 1280, "") |
| 83 |
if tcpipProblem := s.ipstack.CreateNIC(nicID, linkEP); tcpipProblem != nil { |
| 84 |
return nil, fmt.Errorf("could not create netstack NIC: %v", tcpipProblem) |
| 85 |
} |
| 86 |
ipv4Subnet, _ := tcpip.NewSubnet(tcpip.AddrFrom4([4]byte{0x00, 0x00, 0x00, 0x00}), tcpip.MaskFrom(strings.Repeat("\x00", 4))) |
| 87 |
s.ipstack.SetRouteTable([]tcpip.Route{ |
| 88 |
{ |
| 89 |
Destination: ipv4Subnet, |
| 90 |
NIC: nicID, |
| 91 |
}, |
| 92 |
}) |
| 93 |
|
| 94 |
ipNet := device.Networks() |
| 95 |
pa := tcpip.ProtocolAddress{ |
| 96 |
AddressWithPrefix: tcpip.AddrFromSlice(ipNet[0].Addr().AsSlice()).WithPrefix(), |
| 97 |
Protocol: ipv4.ProtocolNumber, |
| 98 |
} |
| 99 |
if err := s.ipstack.AddProtocolAddress(nicID, pa, stack.AddressProperties{ |
| 100 |
PEB: stack.CanBePrimaryEndpoint, // zero value default |
| 101 |
ConfigType: stack.AddressConfigStatic, // zero value default |
| 102 |
}); err != nil { |
| 103 |
return nil, fmt.Errorf("error creating IP: %s", err) |
| 104 |
} |
| 105 |
|
| 106 |
const tcpReceiveBufferSize = 0 |
| 107 |
const maxInFlightConnectionAttempts = 1024 |
| 108 |
tcpFwd := tcp.NewForwarder(s.ipstack, tcpReceiveBufferSize, maxInFlightConnectionAttempts, s.tcpHandler) |
| 109 |
s.ipstack.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpFwd.HandlePacket) |
| 110 |
|
| 111 |
reader, writer := device.Pipe() |
| 112 |
|
| 113 |
go func() { |
| 114 |
<-ctx.Done() |
| 115 |
reader.Close() |
| 116 |
writer.Close() |
| 117 |
}() |
| 118 |
|
| 119 |
// create Goroutines to forward packets between Nebula and Gvisor |
| 120 |
eg.Go(func() error { |
| 121 |
buf := make([]byte, header.IPv4MaximumHeaderSize+header.IPv4MaximumPayloadSize) |
| 122 |
for { |
| 123 |
// this will read exactly one packet |
| 124 |
n, err := reader.Read(buf) |
| 125 |
if err != nil { |
| 126 |
return err |
| 127 |
} |
| 128 |
packetBuf := stack.NewPacketBuffer(stack.PacketBufferOptions{ |
| 129 |
Payload: buffer.MakeWithData(bytes.Clone(buf[:n])), |
| 130 |
}) |
| 131 |
linkEP.InjectInbound(header.IPv4ProtocolNumber, packetBuf) |
| 132 |
|
| 133 |
if err := ctx.Err(); err != nil { |
| 134 |
return err |
| 135 |
} |
| 136 |
} |
| 137 |
}) |
| 138 |
eg.Go(func() error { |
| 139 |
for { |
| 140 |
packet := linkEP.ReadContext(ctx) |
| 141 |
if packet == nil { |
| 142 |
if err := ctx.Err(); err != nil { |
| 143 |
return err |
| 144 |
} |
| 145 |
continue |
| 146 |
} |
| 147 |
bufView := packet.ToView() |
| 148 |
if _, err := bufView.WriteTo(writer); err != nil { |
| 149 |
return err |
| 150 |
} |
| 151 |
bufView.Release() |
| 152 |
} |
| 153 |
}) |
| 154 |
|
| 155 |
// Add the nebula wait function to the group so a fatal reader error |
| 156 |
// propagates out through errgroup.Wait(). |
| 157 |
eg.Go(func() error { |
| 158 |
return control.Wait() |
| 159 |
}) |
| 160 |
|
| 161 |
return &s, nil |
| 162 |
} |
| 163 |
|
| 164 |
func getProtocolNumber(addr netip.Addr) tcpip.NetworkProtocolNumber { |
| 165 |
if addr.Is6() { |
| 166 |
return ipv6.ProtocolNumber |
| 167 |
} |
| 168 |
return ipv4.ProtocolNumber |
| 169 |
} |
| 170 |
|
| 171 |
// DialContext dials the provided address. |
| 172 |
func (s *Service) DialContext(ctx context.Context, network, address string) (net.Conn, error) { |
| 173 |
switch network { |
| 174 |
case "udp", "udp4", "udp6": |
| 175 |
addr, err := net.ResolveUDPAddr(network, address) |
| 176 |
if err != nil { |
| 177 |
return nil, err |
| 178 |
} |
| 179 |
fullAddr := tcpip.FullAddress{ |
| 180 |
NIC: nicID, |
| 181 |
Addr: tcpip.AddrFromSlice(addr.IP), |
| 182 |
Port: uint16(addr.Port), |
| 183 |
} |
| 184 |
num := getProtocolNumber(addr.AddrPort().Addr()) |
| 185 |
return gonet.DialUDP(s.ipstack, nil, &fullAddr, num) |
| 186 |
case "tcp", "tcp4", "tcp6": |
| 187 |
addr, err := net.ResolveTCPAddr(network, address) |
| 188 |
if err != nil { |
| 189 |
return nil, err |
| 190 |
} |
| 191 |
fullAddr := tcpip.FullAddress{ |
| 192 |
NIC: nicID, |
| 193 |
Addr: tcpip.AddrFromSlice(addr.IP), |
| 194 |
Port: uint16(addr.Port), |
| 195 |
} |
| 196 |
num := getProtocolNumber(addr.AddrPort().Addr()) |
| 197 |
return gonet.DialContextTCP(ctx, s.ipstack, fullAddr, num) |
| 198 |
default: |
| 199 |
return nil, fmt.Errorf("unknown network type: %s", network) |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
// Dial dials the provided address |
| 204 |
func (s *Service) Dial(network, address string) (net.Conn, error) { |
| 205 |
return s.DialContext(context.Background(), network, address) |
| 206 |
} |
| 207 |
|
| 208 |
// Listen listens on the provided address. Currently only TCP with wildcard |
| 209 |
// addresses are supported. |
| 210 |
func (s *Service) Listen(network, address string) (net.Listener, error) { |
| 211 |
if network != "tcp" && network != "tcp4" { |
| 212 |
return nil, errors.New("only tcp is supported") |
| 213 |
} |
| 214 |
addr, err := net.ResolveTCPAddr(network, address) |
| 215 |
if err != nil { |
| 216 |
return nil, err |
| 217 |
} |
| 218 |
if addr.IP != nil && !bytes.Equal(addr.IP, []byte{0, 0, 0, 0}) { |
| 219 |
return nil, fmt.Errorf("only wildcard address supported, got %q %v", address, addr.IP) |
| 220 |
} |
| 221 |
if addr.Port == 0 { |
| 222 |
return nil, errors.New("specific port required, got 0") |
| 223 |
} |
| 224 |
if addr.Port < 0 || addr.Port >= math.MaxUint16 { |
| 225 |
return nil, fmt.Errorf("invalid port %d", addr.Port) |
| 226 |
} |
| 227 |
port := uint16(addr.Port) |
| 228 |
|
| 229 |
l := &tcpListener{ |
| 230 |
port: port, |
| 231 |
s: s, |
| 232 |
addr: addr, |
| 233 |
accept: make(chan net.Conn), |
| 234 |
} |
| 235 |
|
| 236 |
s.mu.Lock() |
| 237 |
defer s.mu.Unlock() |
| 238 |
|
| 239 |
if _, ok := s.mu.listeners[port]; ok { |
| 240 |
return nil, fmt.Errorf("already listening on port %d", port) |
| 241 |
} |
| 242 |
s.mu.listeners[port] = l |
| 243 |
|
| 244 |
return l, nil |
| 245 |
} |
| 246 |
|
| 247 |
func (s *Service) Wait() error { |
| 248 |
return s.eg.Wait() |
| 249 |
} |
| 250 |
|
| 251 |
func (s *Service) Close() error { |
| 252 |
s.control.Stop() |
| 253 |
return nil |
| 254 |
} |
| 255 |
|
| 256 |
func (s *Service) tcpHandler(r *tcp.ForwarderRequest) { |
| 257 |
endpointID := r.ID() |
| 258 |
|
| 259 |
s.mu.Lock() |
| 260 |
defer s.mu.Unlock() |
| 261 |
|
| 262 |
l, ok := s.mu.listeners[endpointID.LocalPort] |
| 263 |
if !ok { |
| 264 |
r.Complete(true) |
| 265 |
return |
| 266 |
} |
| 267 |
|
| 268 |
var wq waiter.Queue |
| 269 |
ep, err := r.CreateEndpoint(&wq) |
| 270 |
if err != nil { |
| 271 |
log.Printf("got error creating endpoint %q", err) |
| 272 |
r.Complete(true) |
| 273 |
return |
| 274 |
} |
| 275 |
r.Complete(false) |
| 276 |
ep.SocketOptions().SetKeepAlive(true) |
| 277 |
|
| 278 |
conn := gonet.NewTCPConn(&wq, ep) |
| 279 |
l.accept <- conn |
| 280 |
} |