Debian Codegraph @

main.go

raw
1 package nebula
2
3 import (
4 "context"
5 "fmt"
6 "log/slog"
7 "net"
8 "net/netip"
9 "runtime/debug"
10 "strings"
11 "time"
12
13 "github.com/slackhq/nebula/config"
14 "github.com/slackhq/nebula/overlay"
15 "github.com/slackhq/nebula/sshd"
16 "github.com/slackhq/nebula/udp"
17 "github.com/slackhq/nebula/util"
18 "go.yaml.in/yaml/v3"
19 )
20
21 type m = map[string]any
22
23 func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, deviceFactory overlay.DeviceFactory) (retcon *Control, reterr error) {
24 ctx, cancel := context.WithCancel(context.Background())
25 // Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
26 defer func() {
27 if reterr != nil {
28 cancel()
29 }
30 }()
31
32 if buildVersion == "" {
33 buildVersion = moduleVersion()
34 }
35
36 // Print the config if in test, the exit comes later
37 if configTest {
38 b, err := yaml.Marshal(c.Settings)
39 if err != nil {
40 return nil, err
41 }
42
43 // Print the final config
44 l.Info(string(b))
45 }
46
47 pki, err := NewPKIFromConfig(l, c)
48 if err != nil {
49 return nil, util.ContextualizeIfNeeded("Failed to load PKI from config", err)
50 }
51
52 fw, err := NewFirewallFromConfig(l, pki.getCertState(), c)
53 if err != nil {
54 return nil, util.ContextualizeIfNeeded("Error while loading firewall rules", err)
55 }
56 l.Info("Firewall started", "firewallHashes", fw.GetRuleHashes())
57
58 ssh, err := sshd.NewSSHServer(ctx, l.With("subsystem", "sshd"))
59 if err != nil {
60 return nil, util.ContextualizeIfNeeded("Error while creating SSH server", err)
61 }
62 wireSSHReload(l, ssh, c)
63 var sshStart func()
64 if c.GetBool("sshd.enabled", false) {
65 sshStart, err = configSSH(l, ssh, c)
66 if err != nil {
67 l.Warn("Failed to configure sshd, ssh debugging will not be available", "error", err)
68 sshStart = nil
69 }
70 }
71
72 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
73 // All non system modifying configuration consumption should live above this line
74 // tun config, listeners, anything modifying the computer should be below
75 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
76
77 var routines int
78
79 // If `routines` is set, use that and ignore the specific values
80 if routines = c.GetInt("routines", 0); routines != 0 {
81 if routines < 1 {
82 routines = 1
83 }
84 if routines > 1 {
85 l.Info("Using multiple routines", "routines", routines)
86 }
87 } else {
88 // deprecated and undocumented
89 tunQueues := c.GetInt("tun.routines", 1)
90 udpQueues := c.GetInt("listen.routines", 1)
91 routines = max(tunQueues, udpQueues)
92 if routines != 1 {
93 l.Warn("Setting tun.routines and listen.routines is deprecated. Use `routines` instead", "routines", routines)
94 }
95 }
96
97 // EXPERIMENTAL
98 // Intentionally not documented yet while we do more testing and determine
99 // a good default value.
100 conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
101 if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
102 // Use a different default if we are running with multiple routines
103 conntrackCacheTimeout = 1 * time.Second
104 }
105 if conntrackCacheTimeout > 0 {
106 l.Info("Using routine-local conntrack cache", "duration", conntrackCacheTimeout)
107 }
108
109 var tun overlay.Device
110 if !configTest {
111 c.CatchHUP(ctx)
112
113 if deviceFactory == nil {
114 deviceFactory = overlay.NewDeviceFromConfig
115 }
116
117 tun, err = deviceFactory(c, l, pki.getCertState().myVpnNetworks, routines)
118 if err != nil {
119 return nil, util.ContextualizeIfNeeded("Failed to get a tun/tap device", err)
120 }
121
122 defer func() {
123 if reterr != nil {
124 tun.Close()
125 }
126 }()
127 }
128
129 // set up our UDP listener
130 udpConns := make([]udp.Conn, routines)
131 port := c.GetInt("listen.port", 0)
132
133 // Callers get no handle to these until the Control is returned, release them on any error.
134 defer func() {
135 if reterr != nil {
136 for _, u := range udpConns {
137 if u != nil {
138 _ = u.Close()
139 }
140 }
141 }
142 }()
143
144 if !configTest {
145 rawListenHost := c.GetString("listen.host", "0.0.0.0")
146 var listenHost netip.Addr
147 if rawListenHost == "[::]" {
148 // Old guidance was to provide the literal `[::]` in `listen.host` but that won't resolve.
149 listenHost = netip.IPv6Unspecified()
150
151 } else {
152 ips, err := net.DefaultResolver.LookupNetIP(context.Background(), "ip", rawListenHost)
153 if err != nil {
154 return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
155 }
156 if len(ips) == 0 {
157 return nil, util.ContextualizeIfNeeded("Failed to resolve listen.host", err)
158 }
159 listenHost = ips[0].Unmap()
160 }
161
162 for i := 0; i < routines; i++ {
163 l.Info("listening", "addr", netip.AddrPortFrom(listenHost, uint16(port)))
164 udpServer, err := udp.NewListener(l, listenHost, port, routines > 1, c.GetInt("listen.batch", 64))
165 if err != nil {
166 return nil, util.NewContextualError("Failed to open udp listener", m{"queue": i}, err)
167 }
168 udpServer.ReloadConfig(c)
169 udpConns[i] = udpServer
170
171 // If port is dynamic, discover it before the next pass through the for loop
172 // This way all routines will use the same port correctly
173 if port == 0 {
174 uPort, err := udpServer.LocalAddr()
175 if err != nil {
176 return nil, util.NewContextualError("Failed to get listening port", nil, err)
177 }
178 port = int(uPort.Port())
179 }
180 }
181 }
182
183 hostMap := NewHostMapFromConfig(l, c)
184 punchy := NewPunchyFromConfig(l, c, udpConns[0])
185 connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
186 lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
187 if err != nil {
188 return nil, util.ContextualizeIfNeeded("Failed to initialize lighthouse handler", err)
189 }
190
191 var messageMetrics *MessageMetrics
192 if c.GetBool("stats.message_metrics", false) {
193 messageMetrics = newMessageMetrics()
194 } else {
195 messageMetrics = newMessageMetricsOnlyRecvError()
196 }
197
198 handshakeConfig := HandshakeConfig{
199 tryInterval: c.GetDuration("handshakes.try_interval", DefaultHandshakeTryInterval),
200 retries: int64(c.GetInt("handshakes.retries", DefaultHandshakeRetries)),
201 triggerBuffer: c.GetInt("handshakes.trigger_buffer", DefaultHandshakeTriggerBuffer),
202 messageMetrics: messageMetrics,
203 }
204
205 handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
206 lightHouse.handshakeTrigger = handshakeManager.trigger
207
208 ds, err := newDnsServerFromConfig(ctx, l, pki, hostMap, c)
209 if err != nil {
210 l.Warn("Failed to start DNS responder", "error", err)
211 }
212
213 ifConfig := &InterfaceConfig{
214 HostMap: hostMap,
215 Inside: tun,
216 Outside: udpConns[0],
217 pki: pki,
218 Firewall: fw,
219 DnsServer: ds,
220 HandshakeManager: handshakeManager,
221 connectionManager: connManager,
222 lightHouse: lightHouse,
223 tryPromoteEvery: c.GetUint32("counters.try_promote", defaultPromoteEvery),
224 reQueryEvery: c.GetUint32("counters.requery_every_packets", defaultReQueryEvery),
225 reQueryWait: c.GetDuration("timers.requery_wait_duration", defaultReQueryWait),
226 DropLocalBroadcast: c.GetBool("tun.drop_local_broadcast", false),
227 DropMulticast: c.GetBool("tun.drop_multicast", false),
228 routines: routines,
229 MessageMetrics: messageMetrics,
230 version: buildVersion,
231 relayManager: NewRelayManager(ctx, l, hostMap, c),
232 punchy: punchy,
233 ConntrackCacheTimeout: conntrackCacheTimeout,
234 l: l,
235 }
236
237 var ifce *Interface
238 if !configTest {
239 ifce, err = NewInterface(ctx, ifConfig)
240 if err != nil {
241 return nil, fmt.Errorf("failed to initialize interface: %s", err)
242 }
243
244 ifce.writers = udpConns
245 lightHouse.ifce = ifce
246
247 ifce.RegisterConfigChangeCallbacks(c)
248 ifce.reloadDisconnectInvalid(c)
249 ifce.reloadSendRecvError(c)
250 ifce.reloadAcceptRecvError(c)
251
252 handshakeManager.f = ifce
253 go handshakeManager.Run(ctx)
254
255 punchy.Start(ctx, ifce, hostMap, lightHouse)
256 }
257
258 stats, err := newStatsServerFromConfig(ctx, l, c, buildVersion, configTest)
259 if err != nil {
260 return nil, util.ContextualizeIfNeeded("Failed to start stats emitter", err)
261 }
262
263 if configTest {
264 return nil, nil
265 }
266
267 go ifce.emitStats(ctx, c.GetDuration("stats.interval", time.Second*10))
268
269 attachCommands(l, c, ssh, ifce)
270
271 networkChanges := udp.NewNetworkChangeMonitor(ctx, l, c)
272
273 return &Control{
274 state: StateReady,
275 f: ifce,
276 l: l,
277 ctx: ctx,
278 cancel: cancel,
279 sshStart: sshStart,
280 statsStart: stats.Start,
281 dnsStart: ds.Start,
282 lighthouseStart: lightHouse.StartUpdateWorker,
283 networkChangeStart: networkChanges.Start,
284 connectionManagerStart: connManager.Start,
285 }, nil
286 }
287
288 func moduleVersion() string {
289 info, ok := debug.ReadBuildInfo()
290 if !ok {
291 return ""
292 }
293
294 for _, dep := range info.Deps {
295 if dep.Path == "github.com/slackhq/nebula" {
296 return strings.TrimPrefix(dep.Version, "v")
297 }
298 }
299
300 return ""
301 }