Debian Codegraph @

control.go

raw
1 package nebula
2
3 import (
4 "context"
5 "errors"
6 "log/slog"
7 "net/netip"
8 "os"
9 "os/signal"
10 "sync"
11 "syscall"
12
13 "github.com/slackhq/nebula/cert"
14 "github.com/slackhq/nebula/header"
15 "github.com/slackhq/nebula/overlay"
16 )
17
18 type RunState int
19
20 const (
21 StateUnknown RunState = iota
22 StateReady
23 StateStarted
24 StateStopping
25 StateStopped
26 )
27
28 var ErrAlreadyStarted = errors.New("nebula is already started")
29 var ErrAlreadyStopped = errors.New("nebula cannot be restarted")
30 var ErrUnknownState = errors.New("nebula state is invalid")
31
32 // Every interaction here needs to take extra care to copy memory and not return or use arguments "as is" when touching
33 // core. This means copying IP objects, slices, de-referencing pointers and taking the actual value, etc
34
35 type controlEach func(h *HostInfo)
36
37 type controlHostLister interface {
38 QueryVpnAddr(vpnAddr netip.Addr) *HostInfo
39 ForEachIndex(each controlEach)
40 ForEachVpnAddr(each controlEach)
41 GetPreferredRanges() []netip.Prefix
42 }
43
44 type Control struct {
45 stateLock sync.Mutex
46 state RunState
47
48 f *Interface
49 l *slog.Logger
50 ctx context.Context
51 cancel context.CancelFunc
52 sshStart func()
53 statsStart func()
54 dnsStart func()
55 lighthouseStart func()
56 networkChangeStart func(rebind func())
57 connectionManagerStart func(context.Context)
58 }
59
60 type ControlHostInfo struct {
61 VpnAddrs []netip.Addr `json:"vpnAddrs"`
62 LocalIndex uint32 `json:"localIndex"`
63 RemoteIndex uint32 `json:"remoteIndex"`
64 RemoteAddrs []netip.AddrPort `json:"remoteAddrs"`
65 Cert cert.Certificate `json:"cert"`
66 MessageCounter uint64 `json:"messageCounter"`
67 CurrentRemote netip.AddrPort `json:"currentRemote"`
68 CurrentRelaysToMe []netip.Addr `json:"currentRelaysToMe"`
69 CurrentRelaysThroughMe []netip.Addr `json:"currentRelaysThroughMe"`
70 }
71
72 // Start actually runs nebula, this is a nonblocking call.
73 // Use Wait to block until nebula has fully stopped and to learn whether a fatal reader error caused the shutdown.
74 func (c *Control) Start() error {
75 c.stateLock.Lock()
76 defer c.stateLock.Unlock()
77 switch c.state {
78 case StateReady:
79 //yay!
80 case StateStopped, StateStopping:
81 return ErrAlreadyStopped
82 case StateStarted:
83 return ErrAlreadyStarted
84 default:
85 return ErrUnknownState
86 }
87
88 // Activate the interface
89 err := c.f.activate()
90 if err != nil {
91 // Cancel before Close so a caller returning from Wait always observes a dead Context
92 c.cancel()
93 _ = c.f.Close()
94 c.state = StateStopped
95 return err
96 }
97
98 // Call all the delayed funcs that waited patiently for the interface to be created.
99 if c.sshStart != nil {
100 go c.sshStart()
101 }
102 if c.statsStart != nil {
103 go c.statsStart()
104 }
105 if c.dnsStart != nil {
106 go c.dnsStart()
107 }
108 if c.networkChangeStart != nil {
109 go c.networkChangeStart(c.RebindUDPServer)
110 }
111 if c.connectionManagerStart != nil {
112 go c.connectionManagerStart(c.ctx)
113 }
114 if c.lighthouseStart != nil {
115 c.lighthouseStart()
116 }
117
118 c.f.triggerShutdown = c.Stop
119
120 // Start reading packets.
121 c.f.run()
122 c.state = StateStarted
123 return nil
124 }
125
126 func (c *Control) State() RunState {
127 c.stateLock.Lock()
128 defer c.stateLock.Unlock()
129 return c.state
130 }
131
132 func (c *Control) Context() context.Context {
133 return c.ctx
134 }
135
136 // Stop tears nebula down, closing all tunnels and releasing everything it holds.
137 // Use Wait to block until the shutdown has completed.
138 // A Control that has been stopped cannot be started again, Start will return ErrAlreadyStopped.
139 func (c *Control) Stop() {
140 c.stateLock.Lock()
141 switch c.state {
142 case StateStarted:
143 // Fall through to the full teardown below
144
145 case StateReady:
146 // Never started
147 c.cancel()
148 c.state = StateStopped
149 if err := c.f.Close(); err != nil {
150 c.l.Error("Close interface failed", "error", err)
151 }
152 c.stateLock.Unlock()
153 return
154
155 default:
156 c.stateLock.Unlock()
157 // We are stopping or stopped already
158 return
159 }
160
161 c.state = StateStopping
162 c.stateLock.Unlock()
163
164 // Closing tunnels can be slow with a large hostmap, don't hold the lock for it
165 c.cancel()
166 c.CloseAllTunnels(false)
167
168 c.stateLock.Lock()
169 c.state = StateStopped
170 if err := c.f.Close(); err != nil {
171 c.l.Error("Close interface failed", "error", err)
172 }
173 c.stateLock.Unlock()
174 }
175
176 // Wait blocks until nebula has fully stopped, either via Stop or an internal fatal error,
177 // and returns the first fatal packet reader error if there was one.
178 // It is safe to call from multiple goroutines and at any point in the lifecycle,
179 // but a Wait on a Control that is never started and never stopped will block forever.
180 func (c *Control) Wait() error {
181 return c.f.wait()
182 }
183
184 // ShutdownBlock will listen for and block on term and interrupt signals, calling Control.Stop() once signalled
185 func (c *Control) ShutdownBlock() {
186 sigChan := make(chan os.Signal, 1)
187 signal.Notify(sigChan, syscall.SIGTERM)
188 signal.Notify(sigChan, syscall.SIGINT)
189
190 rawSig := <-sigChan
191 sig := rawSig.String()
192 c.l.Info("Caught signal, shutting down", "signal", sig)
193 c.Stop()
194 }
195
196 // RebindUDPServer asks the UDP listener to rebind it's listener. Mainly used on mobile clients when interfaces change.
197 func (c *Control) RebindUDPServer() {
198 c.stateLock.Lock()
199 defer c.stateLock.Unlock()
200
201 if c.state != StateStarted {
202 return
203 }
204
205 // A failure here means we are likely still pinned to the interface we came up on, so the rest of this is
206 // unlikely to help. Say so instead of silently carrying on as if we rebound.
207 if err := c.f.outside.Rebind(); err != nil {
208 c.l.Error("Failed to rebind udp socket", "error", err)
209 }
210
211 // Trigger a lighthouse update, useful for mobile clients that should have an update interval of 0
212 c.f.lightHouse.SendUpdate()
213
214 // Let the main interface know that we rebound so that underlying tunnels know to trigger punches from their remotes
215 c.f.rebindCount++
216 }
217
218 // ListHostmapHosts returns details about the actual or pending (handshaking) hostmap by vpn ip
219 func (c *Control) ListHostmapHosts(pendingMap bool) []ControlHostInfo {
220 if pendingMap {
221 return listHostMapHosts(c.f.handshakeManager)
222 } else {
223 return listHostMapHosts(c.f.hostMap)
224 }
225 }
226
227 // ListHostmapIndexes returns details about the actual or pending (handshaking) hostmap by local index id
228 func (c *Control) ListHostmapIndexes(pendingMap bool) []ControlHostInfo {
229 if pendingMap {
230 return listHostMapIndexes(c.f.handshakeManager)
231 } else {
232 return listHostMapIndexes(c.f.hostMap)
233 }
234 }
235
236 // GetCertByVpnIp returns the authenticated certificate of the given vpn IP, or nil if not found
237 func (c *Control) GetCertByVpnIp(vpnIp netip.Addr) cert.Certificate {
238 if c.f.myVpnAddrsTable.Contains(vpnIp) {
239 // Only returning the default certificate since its impossible
240 // for any other host but ourselves to have more than 1
241 return c.f.pki.getCertState().GetDefaultCertificate().Copy()
242 }
243 hi := c.f.hostMap.QueryVpnAddr(vpnIp)
244 if hi == nil {
245 return nil
246 }
247 return hi.GetCert().Certificate.Copy()
248 }
249
250 // CreateTunnel creates a new tunnel to the given vpn ip.
251 func (c *Control) CreateTunnel(vpnIp netip.Addr) {
252 c.f.handshakeManager.StartHandshake(vpnIp, nil)
253 }
254
255 // PrintTunnel creates a new tunnel to the given vpn ip.
256 func (c *Control) PrintTunnel(vpnIp netip.Addr) *ControlHostInfo {
257 hi := c.f.hostMap.QueryVpnAddr(vpnIp)
258 if hi == nil {
259 return nil
260 }
261 chi := copyHostInfo(hi, c.f.hostMap.GetPreferredRanges())
262 return &chi
263 }
264
265 // QueryLighthouse queries the lighthouse.
266 func (c *Control) QueryLighthouse(vpnIp netip.Addr) *CacheMap {
267 hi := c.f.lightHouse.Query(vpnIp)
268 if hi == nil {
269 return nil
270 }
271 return hi.CopyCache()
272 }
273
274 // GetHostInfoByVpnAddr returns a single tunnels hostInfo, or nil if not found
275 // Caller should take care to Unmap() any 4in6 addresses prior to calling.
276 func (c *Control) GetHostInfoByVpnAddr(vpnAddr netip.Addr, pending bool) *ControlHostInfo {
277 var hl controlHostLister
278 if pending {
279 hl = c.f.handshakeManager
280 } else {
281 hl = c.f.hostMap
282 }
283
284 h := hl.QueryVpnAddr(vpnAddr)
285 if h == nil {
286 return nil
287 }
288
289 ch := copyHostInfo(h, c.f.hostMap.GetPreferredRanges())
290 return &ch
291 }
292
293 // SetRemoteForTunnel forces a tunnel to use a specific remote
294 // Caller should take care to Unmap() any 4in6 addresses prior to calling.
295 func (c *Control) SetRemoteForTunnel(vpnIp netip.Addr, addr netip.AddrPort) *ControlHostInfo {
296 hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
297 if hostInfo == nil {
298 return nil
299 }
300
301 hostInfo.SetRemote(addr)
302 ch := copyHostInfo(hostInfo, c.f.hostMap.GetPreferredRanges())
303 return &ch
304 }
305
306 // CloseTunnel closes a fully established tunnel. If localOnly is false it will notify the remote end as well.
307 // Caller should take care to Unmap() any 4in6 addresses prior to calling.
308 func (c *Control) CloseTunnel(vpnIp netip.Addr, localOnly bool) bool {
309 hostInfo := c.f.hostMap.QueryVpnAddr(vpnIp)
310 if hostInfo == nil {
311 return false
312 }
313
314 if !localOnly {
315 c.f.send(
316 header.CloseTunnel,
317 0,
318 hostInfo.ConnectionState,
319 hostInfo,
320 []byte{},
321 make([]byte, 12, 12),
322 make([]byte, mtu),
323 )
324 }
325
326 c.f.closeTunnel(hostInfo)
327 return true
328 }
329
330 // CloseAllTunnels is just like CloseTunnel except it goes through and shuts them all down, optionally you can avoid shutting down lighthouse tunnels
331 // the int returned is a count of tunnels closed
332 func (c *Control) CloseAllTunnels(excludeLighthouses bool) (closed int) {
333 shutdown := func(h *HostInfo) {
334 if excludeLighthouses && c.f.lightHouse.IsAnyLighthouseAddr(h.vpnAddrs) {
335 return
336 }
337 c.f.send(header.CloseTunnel, 0, h.ConnectionState, h, []byte{}, make([]byte, 12, 12), make([]byte, mtu))
338 c.f.closeTunnel(h)
339
340 c.l.Debug("Sending close tunnel message",
341 "vpnAddrs", h.vpnAddrs,
342 "udpAddr", h.GetRemote(),
343 )
344 closed++
345 }
346
347 // Learn which hosts are being used as relays, so we can shut them down last.
348 relayingHosts := map[netip.Addr]*HostInfo{}
349 // Grab the hostMap lock to access the Relays map
350 c.f.hostMap.Lock()
351 for _, relayingHost := range c.f.hostMap.Relays {
352 relayingHosts[relayingHost.vpnAddrs[0]] = relayingHost
353 }
354 c.f.hostMap.Unlock()
355
356 hostInfos := []*HostInfo{}
357 // Grab the hostMap lock to access the Hosts map
358 c.f.hostMap.Lock()
359 for _, relayHost := range c.f.hostMap.Indexes {
360 if _, ok := relayingHosts[relayHost.vpnAddrs[0]]; !ok {
361 hostInfos = append(hostInfos, relayHost)
362 }
363 }
364 c.f.hostMap.Unlock()
365
366 for _, h := range hostInfos {
367 shutdown(h)
368 }
369 for _, h := range relayingHosts {
370 shutdown(h)
371 }
372 return
373 }
374
375 func (c *Control) Device() overlay.Device {
376 return c.f.inside
377 }
378
379 func copyHostInfo(h *HostInfo, preferredRanges []netip.Prefix) ControlHostInfo {
380 chi := ControlHostInfo{
381 VpnAddrs: make([]netip.Addr, len(h.vpnAddrs)),
382 LocalIndex: h.localIndexId,
383 RemoteIndex: h.remoteIndexId,
384 RemoteAddrs: h.remotes.CopyAddrs(preferredRanges),
385 CurrentRelaysToMe: h.relayState.CopyRelayIps(),
386 CurrentRelaysThroughMe: h.relayState.CopyRelayForIps(),
387 CurrentRemote: h.GetRemote(),
388 }
389
390 for i, a := range h.vpnAddrs {
391 chi.VpnAddrs[i] = a
392 }
393
394 if h.ConnectionState != nil {
395 chi.MessageCounter = h.ConnectionState.messageCounter.Load()
396 }
397
398 if c := h.GetCert(); c != nil {
399 chi.Cert = c.Certificate.Copy()
400 }
401
402 return chi
403 }
404
405 func listHostMapHosts(hl controlHostLister) []ControlHostInfo {
406 hosts := make([]ControlHostInfo, 0)
407 pr := hl.GetPreferredRanges()
408 hl.ForEachVpnAddr(func(hostinfo *HostInfo) {
409 hosts = append(hosts, copyHostInfo(hostinfo, pr))
410 })
411 return hosts
412 }
413
414 func listHostMapIndexes(hl controlHostLister) []ControlHostInfo {
415 hosts := make([]ControlHostInfo, 0)
416 pr := hl.GetPreferredRanges()
417 hl.ForEachIndex(func(hostinfo *HostInfo) {
418 hosts = append(hosts, copyHostInfo(hostinfo, pr))
419 })
420 return hosts
421 }