Debian Codegraph @

inside.go

raw
1 package nebula
2
3 import (
4 "context"
5 "log/slog"
6 "net/netip"
7
8 "github.com/slackhq/nebula/firewall"
9 "github.com/slackhq/nebula/header"
10 "github.com/slackhq/nebula/iputil"
11 "github.com/slackhq/nebula/noiseutil"
12 "github.com/slackhq/nebula/routing"
13 )
14
15 func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []byte, q int, localCache firewall.ConntrackCache) {
16 err := newPacket(packet, false, fwPacket)
17 if err != nil {
18 if f.l.Enabled(context.Background(), slog.LevelDebug) {
19 f.l.Debug("Error while validating outbound packet",
20 "packet", packet,
21 "error", err,
22 )
23 }
24 return
25 }
26
27 // Ignore local broadcast packets
28 if f.dropLocalBroadcast {
29 if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
30 return
31 }
32 }
33
34 if f.myVpnAddrsTable.Contains(fwPacket.RemoteAddr) {
35 // Immediately forward packets from self to self.
36 // This should only happen on Darwin-based and FreeBSD hosts, which
37 // routes packets from the Nebula addr to the Nebula addr through the Nebula
38 // TUN device.
39 if immediatelyForwardToSelf {
40 _, err := f.readers[q].Write(packet)
41 if err != nil {
42 f.l.Error("Failed to forward to tun", "error", err)
43 }
44 }
45 // Otherwise, drop. On linux, we should never see these packets - Linux
46 // routes packets from the nebula addr to the nebula addr through the loopback device.
47 return
48 }
49
50 // Ignore multicast packets
51 if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
52 return
53 }
54
55 hostinfo, ready := f.getOrHandshakeConsiderRouting(fwPacket, func(hh *HandshakeHostInfo) {
56 hh.cachePacket(f.l, header.Message, 0, packet, f.sendMessageNow, f.cachedPacketMetrics)
57 })
58
59 if hostinfo == nil {
60 f.rejectInside(packet, out, q)
61 if f.l.Enabled(context.Background(), slog.LevelDebug) {
62 f.l.Debug("dropping outbound packet, vpnAddr not in our vpn networks or in unsafe networks",
63 "vpnAddr", fwPacket.RemoteAddr,
64 "fwPacket", fwPacket,
65 )
66 }
67 return
68 }
69
70 if !ready {
71 return
72 }
73
74 dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
75 if dropReason == nil {
76 f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q)
77
78 } else {
79 f.rejectInside(packet, out, q)
80 if f.l.Enabled(context.Background(), slog.LevelDebug) {
81 hostinfo.logger(f.l).Debug("dropping outbound packet",
82 "fwPacket", fwPacket,
83 "reason", dropReason,
84 )
85 }
86 }
87 }
88
89 func (f *Interface) rejectInside(packet []byte, out []byte, q int) {
90 if !f.firewall.OutboundSendReject {
91 return
92 }
93
94 out = iputil.CreateRejectPacket(packet, out)
95 if len(out) == 0 {
96 return
97 }
98
99 _, err := f.readers[q].Write(out)
100 if err != nil {
101 f.l.Error("Failed to write to tun", "error", err)
102 }
103 }
104
105 func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *HostInfo, nb, out []byte, q int) {
106 if !f.firewall.InboundSendReject {
107 return
108 }
109
110 out = iputil.CreateRejectPacket(packet, out)
111 if len(out) == 0 {
112 return
113 }
114
115 if len(out) > iputil.MaxRejectPacketSize {
116 if f.l.Enabled(context.Background(), slog.LevelInfo) {
117 f.l.Info("rejectOutside: packet too big, not sending",
118 "packet", packet,
119 "outPacket", out,
120 )
121 }
122 return
123 }
124
125 f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q)
126 }
127
128 // Handshake will attempt to initiate a tunnel with the provided vpn address. This is a no-op if the tunnel is already established or being established
129 // it does not check if it is within our vpn networks!
130 func (f *Interface) Handshake(vpnAddr netip.Addr) {
131 f.handshakeManager.GetOrHandshake(vpnAddr, nil)
132 }
133
134 // getOrHandshakeNoRouting returns nil if the vpnAddr is not routable.
135 // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel
136 func (f *Interface) getOrHandshakeNoRouting(vpnAddr netip.Addr, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
137 if f.myVpnNetworksTable.Contains(vpnAddr) {
138 return f.handshakeManager.GetOrHandshake(vpnAddr, cacheCallback)
139 }
140
141 return nil, false
142 }
143
144 // getOrHandshakeConsiderRouting will try to find the HostInfo to handle this packet, starting a handshake if necessary.
145 // If the 2nd return var is false then the hostinfo is not ready to be used in a tunnel.
146 func (f *Interface) getOrHandshakeConsiderRouting(fwPacket *firewall.Packet, cacheCallback func(*HandshakeHostInfo)) (*HostInfo, bool) {
147 destinationAddr := fwPacket.RemoteAddr
148
149 hostinfo, ready := f.getOrHandshakeNoRouting(destinationAddr, cacheCallback)
150
151 // Host is inside the mesh, no routing required
152 if hostinfo != nil {
153 return hostinfo, ready
154 }
155
156 gateways := f.inside.RoutesFor(destinationAddr)
157
158 switch len(gateways) {
159 case 0:
160 return nil, false
161 case 1:
162 // Single gateway route
163 return f.handshakeManager.GetOrHandshake(gateways[0].Addr(), cacheCallback)
164 default:
165 // Multi gateway route, perform ECMP categorization
166 gatewayAddr, balancingOk := routing.BalancePacket(fwPacket, gateways)
167
168 if !balancingOk {
169 // This happens if the gateway buckets were not calculated, this _should_ never happen
170 f.l.Error("Gateway buckets not calculated, fallback from ECMP to random routing. Please report this bug.")
171 }
172
173 var handshakeInfoForChosenGateway *HandshakeHostInfo
174 var hhReceiver = func(hh *HandshakeHostInfo) {
175 handshakeInfoForChosenGateway = hh
176 }
177
178 // Store the handshakeHostInfo for later.
179 // If this node is not reachable we will attempt other nodes, if none are reachable we will
180 // cache the packet for this gateway.
181 if hostinfo, ready = f.handshakeManager.GetOrHandshake(gatewayAddr, hhReceiver); ready {
182 return hostinfo, true
183 }
184
185 // It appears the selected gateway cannot be reached, find another gateway to fallback on.
186 // The current implementation breaks ECMP but that seems better than no connectivity.
187 // If ECMP is also required when a gateway is down then connectivity status
188 // for each gateway needs to be kept and the weights recalculated when they go up or down.
189 // This would also need to interact with unsafe_route updates through reloading the config or
190 // use of the use_system_route_table option
191
192 if f.l.Enabled(context.Background(), slog.LevelDebug) {
193 f.l.Debug("Calculated gateway for ECMP not available, attempting other gateways",
194 "destination", destinationAddr,
195 "originalGateway", gatewayAddr,
196 )
197 }
198
199 for i := range gateways {
200 // Skip the gateway that failed previously
201 if gateways[i].Addr() == gatewayAddr {
202 continue
203 }
204
205 // We do not need the HandshakeHostInfo since we cache the packet in the originally chosen gateway
206 if hostinfo, ready = f.handshakeManager.GetOrHandshake(gateways[i].Addr(), nil); ready {
207 return hostinfo, true
208 }
209 }
210
211 // No gateways reachable, cache the packet in the originally chosen gateway
212 cacheCallback(handshakeInfoForChosenGateway)
213 return hostinfo, false
214 }
215
216 }
217
218 func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubType, hostinfo *HostInfo, p, nb, out []byte) {
219 fp := &firewall.Packet{}
220 err := newPacket(p, false, fp)
221 if err != nil {
222 f.l.Warn("error while parsing outgoing packet for firewall check", "error", err)
223 return
224 }
225
226 // check if packet is in outbound fw rules
227 dropReason := f.firewall.Drop(*fp, false, hostinfo, f.pki.GetCAPool(), nil)
228 if dropReason != nil {
229 if f.l.Enabled(context.Background(), slog.LevelDebug) {
230 f.l.Debug("dropping cached packet",
231 "fwPacket", fp,
232 "reason", dropReason,
233 )
234 }
235 return
236 }
237
238 f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
239 }
240
241 // SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
242 // This function ignores myVpnNetworksTable, and will always attempt to treat the address as a vpnAddr
243 func (f *Interface) SendMessageToVpnAddr(t header.MessageType, st header.MessageSubType, vpnAddr netip.Addr, p, nb, out []byte) {
244 hostInfo, ready := f.handshakeManager.GetOrHandshake(vpnAddr, func(hh *HandshakeHostInfo) {
245 hh.cachePacket(f.l, t, st, p, f.SendMessageToHostInfo, f.cachedPacketMetrics)
246 })
247
248 if hostInfo == nil {
249 if f.l.Enabled(context.Background(), slog.LevelDebug) {
250 f.l.Debug("dropping SendMessageToVpnAddr, vpnAddr not in our vpn networks or in unsafe routes",
251 "vpnAddr", vpnAddr,
252 )
253 }
254 return
255 }
256
257 if !ready {
258 return
259 }
260
261 f.SendMessageToHostInfo(t, st, hostInfo, p, nb, out)
262 }
263
264 func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.MessageSubType, hi *HostInfo, p, nb, out []byte) {
265 f.send(t, st, hi.ConnectionState, hi, p, nb, out)
266 }
267
268 func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
269 f.messageMetrics.Tx(t, st, 1)
270 f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
271 }
272
273 func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
274 f.messageMetrics.Tx(t, st, 1)
275 f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
276 }
277
278 // SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
279 // to the payload for the ultimate target host, making this a useful method for sending
280 // handshake messages to peers through relay tunnels.
281 // via is the HostInfo through which the message is relayed.
282 // ad is the plaintext data to authenticate, but not encrypt
283 // nb is a buffer used to store the nonce value, re-used for performance reasons.
284 // out is a buffer used to store the result of the Encrypt operation
285 // q indicates which writer to use to send the packet.
286 func (f *Interface) SendVia(via *HostInfo,
287 relay *Relay,
288 ad,
289 nb,
290 out []byte,
291 nocopy bool,
292 ) {
293 if noiseutil.EncryptLockNeeded {
294 // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
295 via.ConnectionState.writeLock.Lock()
296 }
297 c := via.ConnectionState.messageCounter.Add(1)
298
299 out = header.Encode(out, header.Version, header.Message, header.MessageRelay, relay.RemoteIndex, c)
300 f.connectionManager.Out(via)
301
302 // Authenticate the header and payload, but do not encrypt for this message type.
303 // The payload consists of the inner, unencrypted Nebula header, as well as the end-to-end encrypted payload.
304 if len(out)+len(ad)+via.ConnectionState.eKey.Overhead() > cap(out) {
305 if noiseutil.EncryptLockNeeded {
306 via.ConnectionState.writeLock.Unlock()
307 }
308 via.logger(f.l).Error("SendVia out buffer not large enough for relay",
309 "outCap", cap(out),
310 "payloadLen", len(ad),
311 "headerLen", len(out),
312 "cipherOverhead", via.ConnectionState.eKey.Overhead(),
313 )
314 return
315 }
316
317 // The header bytes are written to the 'out' slice; Grow the slice to hold the header and associated data payload.
318 offset := len(out)
319 out = out[:offset+len(ad)]
320
321 // In one call path, the associated data _is_ already stored in out. In other call paths, the associated data must
322 // be copied into 'out'.
323 if !nocopy {
324 copy(out[offset:], ad)
325 }
326
327 var err error
328 out, err = via.ConnectionState.eKey.EncryptDanger(out, out, nil, c, nb)
329 if noiseutil.EncryptLockNeeded {
330 via.ConnectionState.writeLock.Unlock()
331 }
332 if err != nil {
333 via.logger(f.l).Info("Failed to EncryptDanger in sendVia", "error", err)
334 return
335 }
336 err = f.writers[0].WriteTo(out, via.GetRemote())
337 if err != nil {
338 via.logger(f.l).Info("Failed to WriteTo in sendVia", "error", err)
339 }
340 f.connectionManager.RelayUsed(relay.LocalIndex)
341 }
342
343 func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
344 if ci.eKey == nil {
345 return
346 }
347 useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
348 fullOut := out
349
350 if useRelay {
351 if len(out) < header.Len {
352 // out always has a capacity of mtu, but not always a length greater than the header.Len.
353 // Grow it to make sure the next operation works.
354 out = out[:header.Len]
355 }
356 // Save a header's worth of data at the front of the 'out' buffer.
357 out = out[header.Len:]
358 }
359
360 if noiseutil.EncryptLockNeeded {
361 // NOTE: for goboring AESGCMTLS we need to lock because of the nonce check
362 ci.writeLock.Lock()
363 }
364 c := ci.messageCounter.Add(1)
365
366 //l.WithField("trace", string(debug.Stack())).Error("out Header ", &Header{Version, t, st, 0, hostinfo.remoteIndexId, c}, p)
367 out = header.Encode(out, header.Version, t, st, hostinfo.remoteIndexId, c)
368 f.connectionManager.Out(hostinfo)
369
370 // Query our LH if we haven't since the last time we've been rebound, this will cause the remote to punch against
371 // all our addrs and enable a faster roaming.
372 if t != header.CloseTunnel && hostinfo.lastRebindCount != f.rebindCount {
373 //NOTE: there is an update hole if a tunnel isn't used and exactly 256 rebinds occur before the tunnel is
374 // finally used again. This tunnel would eventually be torn down and recreated if this action didn't help.
375 f.lightHouse.QueryServer(hostinfo.vpnAddrs[0])
376 hostinfo.lastRebindCount = f.rebindCount
377 if f.l.Enabled(context.Background(), slog.LevelDebug) {
378 f.l.Debug("Lighthouse update triggered for punch due to rebind counter",
379 "vpnAddrs", hostinfo.vpnAddrs,
380 )
381 }
382 }
383
384 var err error
385 out, err = ci.eKey.EncryptDanger(out, out, p, c, nb)
386 if noiseutil.EncryptLockNeeded {
387 ci.writeLock.Unlock()
388 }
389 if err != nil {
390 hostinfo.logger(f.l).Error("Failed to encrypt outgoing packet",
391 "error", err,
392 "udpAddr", remote,
393 "counter", c,
394 )
395 return
396 }
397
398 if remote.IsValid() {
399 err = f.writers[q].WriteTo(out, remote)
400 if err != nil {
401 hostinfo.logger(f.l).Error("Failed to write outgoing packet",
402 "error", err,
403 "udpAddr", remote,
404 )
405 }
406 } else if hr := hostinfo.GetRemote(); hr.IsValid() {
407 err = f.writers[q].WriteTo(out, hr)
408 if err != nil {
409 hostinfo.logger(f.l).Error("Failed to write outgoing packet",
410 "error", err,
411 "udpAddr", hr,
412 )
413 }
414 } else {
415 // Try to send via a relay
416 for _, relayIP := range hostinfo.relayState.CopyRelayIps() {
417 relayHostInfo, relay, err := f.hostMap.QueryVpnAddrsRelayFor(hostinfo.vpnAddrs, relayIP)
418 if err != nil {
419 hostinfo.relayState.DeleteRelay(relayIP)
420 hostinfo.logger(f.l).Info("sendNoMetrics failed to find HostInfo",
421 "relay", relayIP,
422 "error", err,
423 )
424 continue
425 }
426 f.SendVia(relayHostInfo, relay, out, nb, fullOut[:header.Len+len(out)], true)
427 break
428 }
429 }
430 }