Debian Codegraph @

connection_manager_test.go

raw
1 package nebula
2
3 import (
4 "crypto/ed25519"
5 "crypto/rand"
6 "net/netip"
7 "testing"
8 "time"
9
10 "github.com/slackhq/nebula/cert"
11 "github.com/slackhq/nebula/config"
12 "github.com/slackhq/nebula/overlay/overlaytest"
13 "github.com/slackhq/nebula/test"
14 "github.com/slackhq/nebula/udp"
15 "github.com/stretchr/testify/assert"
16 "github.com/stretchr/testify/require"
17 )
18
19 func newTestLighthouse() *LightHouse {
20 lh := &LightHouse{
21 l: test.NewLogger(),
22 addrMap: map[netip.Addr]*RemoteList{},
23 queryChan: make(chan netip.Addr, 10),
24 }
25 lighthouses := []netip.Addr{}
26 staticList := map[netip.Addr]struct{}{}
27
28 lh.localAddrsFn = func(*LocalAllowList) []netip.Addr { return nil }
29 lh.lighthouses.Store(&lighthouses)
30 lh.staticList.Store(&staticList)
31
32 return lh
33 }
34
35 func Test_NewConnectionManagerTest(t *testing.T) {
36 l := test.NewLogger()
37 //_, tuncidr, _ := net.ParseCIDR("1.1.1.1/24")
38 localrange := netip.MustParsePrefix("10.1.1.1/24")
39 vpnIp := netip.MustParseAddr("172.1.1.2")
40 preferredRanges := []netip.Prefix{localrange}
41
42 // Very incomplete mock objects
43 hostMap := newHostMap(l)
44 hostMap.preferredRanges.Store(&preferredRanges)
45
46 cs := &CertState{
47 initiatingVersion: cert.Version1,
48 privateKey: []byte{},
49 v1Cert: &dummyCert{version: cert.Version1},
50 v1Credential: nil,
51 }
52
53 lh := newTestLighthouse()
54 ifce := &Interface{
55 hostMap: hostMap,
56 inside: &overlaytest.NoopTun{},
57 outside: &udp.NoopConn{},
58 firewall: &Firewall{},
59 lightHouse: lh,
60 pki: &PKI{},
61 handshakeManager: NewHandshakeManager(l, hostMap, lh, &udp.NoopConn{}, defaultHandshakeConfig),
62 l: l,
63 }
64 ifce.pki.cs.Store(cs)
65
66 // Create manager
67 conf := config.NewC(test.NewLogger())
68 punchy := NewPunchyFromConfig(test.NewLogger(), conf, nil)
69 nc := newConnectionManagerFromConfig(test.NewLogger(), conf, hostMap, punchy)
70 nc.intf = ifce
71 p := []byte("")
72 nb := make([]byte, 12, 12)
73 out := make([]byte, mtu)
74
75 // Add an ip we have established a connection w/ to hostmap
76 hostinfo := &HostInfo{
77 vpnAddrs: []netip.Addr{vpnIp},
78 localIndexId: 1099,
79 remoteIndexId: 9901,
80 }
81 hostinfo.ConnectionState = &ConnectionState{
82 myCert: &dummyCert{version: cert.Version1},
83 }
84 nc.hostMap.unlockedAddHostInfo(hostinfo, ifce)
85
86 // We saw traffic out to vpnIp
87 nc.Out(hostinfo)
88 nc.In(hostinfo)
89 assert.False(t, hostinfo.pendingDeletion.Load())
90 assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
91 assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
92 assert.True(t, hostinfo.out.Load())
93 assert.True(t, hostinfo.in.Load())
94
95 // Do a traffic check tick, should not be pending deletion but should not have any in/out packets recorded
96 nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
97 assert.False(t, hostinfo.pendingDeletion.Load())
98 assert.False(t, hostinfo.out.Load())
99 assert.False(t, hostinfo.in.Load())
100
101 // Do another traffic check tick, this host should be pending deletion now
102 nc.Out(hostinfo)
103 assert.True(t, hostinfo.out.Load())
104 nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
105 assert.True(t, hostinfo.pendingDeletion.Load())
106 assert.False(t, hostinfo.out.Load())
107 assert.False(t, hostinfo.in.Load())
108 assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
109 assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
110
111 // Do a final traffic check tick, the host should now be removed
112 nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
113 assert.NotContains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs)
114 assert.NotContains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
115 }
116
117 func Test_NewConnectionManagerTest2(t *testing.T) {
118 l := test.NewLogger()
119 //_, tuncidr, _ := net.ParseCIDR("1.1.1.1/24")
120 localrange := netip.MustParsePrefix("10.1.1.1/24")
121 vpnIp := netip.MustParseAddr("172.1.1.2")
122 preferredRanges := []netip.Prefix{localrange}
123
124 // Very incomplete mock objects
125 hostMap := newHostMap(l)
126 hostMap.preferredRanges.Store(&preferredRanges)
127
128 cs := &CertState{
129 initiatingVersion: cert.Version1,
130 privateKey: []byte{},
131 v1Cert: &dummyCert{version: cert.Version1},
132 v1Credential: nil,
133 }
134
135 lh := newTestLighthouse()
136 ifce := &Interface{
137 hostMap: hostMap,
138 inside: &overlaytest.NoopTun{},
139 outside: &udp.NoopConn{},
140 firewall: &Firewall{},
141 lightHouse: lh,
142 pki: &PKI{},
143 handshakeManager: NewHandshakeManager(l, hostMap, lh, &udp.NoopConn{}, defaultHandshakeConfig),
144 l: l,
145 }
146 ifce.pki.cs.Store(cs)
147
148 // Create manager
149 conf := config.NewC(test.NewLogger())
150 punchy := NewPunchyFromConfig(test.NewLogger(), conf, nil)
151 nc := newConnectionManagerFromConfig(test.NewLogger(), conf, hostMap, punchy)
152 nc.intf = ifce
153 p := []byte("")
154 nb := make([]byte, 12, 12)
155 out := make([]byte, mtu)
156
157 // Add an ip we have established a connection w/ to hostmap
158 hostinfo := &HostInfo{
159 vpnAddrs: []netip.Addr{vpnIp},
160 localIndexId: 1099,
161 remoteIndexId: 9901,
162 }
163 hostinfo.ConnectionState = &ConnectionState{
164 myCert: &dummyCert{version: cert.Version1},
165 }
166 nc.hostMap.unlockedAddHostInfo(hostinfo, ifce)
167
168 // We saw traffic out to vpnIp
169 nc.Out(hostinfo)
170 nc.In(hostinfo)
171 assert.True(t, hostinfo.in.Load())
172 assert.True(t, hostinfo.out.Load())
173 assert.False(t, hostinfo.pendingDeletion.Load())
174 assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
175 assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
176
177 // Do a traffic check tick, should not be pending deletion but should not have any in/out packets recorded
178 nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
179 assert.False(t, hostinfo.pendingDeletion.Load())
180 assert.False(t, hostinfo.out.Load())
181 assert.False(t, hostinfo.in.Load())
182
183 // Do another traffic check tick, this host should be pending deletion now
184 nc.Out(hostinfo)
185 nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
186 assert.True(t, hostinfo.pendingDeletion.Load())
187 assert.False(t, hostinfo.out.Load())
188 assert.False(t, hostinfo.in.Load())
189 assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
190 assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
191
192 // We saw traffic, should no longer be pending deletion
193 nc.In(hostinfo)
194 nc.doTrafficCheck(hostinfo.localIndexId, p, nb, out, time.Now())
195 assert.False(t, hostinfo.pendingDeletion.Load())
196 assert.False(t, hostinfo.out.Load())
197 assert.False(t, hostinfo.in.Load())
198 assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
199 assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
200 }
201
202 func Test_NewConnectionManager_DisconnectInactive(t *testing.T) {
203 l := test.NewLogger()
204 localrange := netip.MustParsePrefix("10.1.1.1/24")
205 vpnAddrs := []netip.Addr{netip.MustParseAddr("172.1.1.2")}
206 preferredRanges := []netip.Prefix{localrange}
207
208 // Very incomplete mock objects
209 hostMap := newHostMap(l)
210 hostMap.preferredRanges.Store(&preferredRanges)
211
212 cs := &CertState{
213 initiatingVersion: cert.Version1,
214 privateKey: []byte{},
215 v1Cert: &dummyCert{version: cert.Version1},
216 v1Credential: nil,
217 }
218
219 lh := newTestLighthouse()
220 ifce := &Interface{
221 hostMap: hostMap,
222 inside: &overlaytest.NoopTun{},
223 outside: &udp.NoopConn{},
224 firewall: &Firewall{},
225 lightHouse: lh,
226 pki: &PKI{},
227 handshakeManager: NewHandshakeManager(l, hostMap, lh, &udp.NoopConn{}, defaultHandshakeConfig),
228 l: l,
229 }
230 ifce.pki.cs.Store(cs)
231
232 // Create manager
233 conf := config.NewC(test.NewLogger())
234 conf.Settings["tunnels"] = map[string]any{
235 "drop_inactive": true,
236 }
237 punchy := NewPunchyFromConfig(test.NewLogger(), conf, nil)
238 nc := newConnectionManagerFromConfig(test.NewLogger(), conf, hostMap, punchy)
239 assert.True(t, nc.dropInactive.Load())
240 nc.intf = ifce
241
242 // Add an ip we have established a connection w/ to hostmap
243 hostinfo := &HostInfo{
244 vpnAddrs: vpnAddrs,
245 localIndexId: 1099,
246 remoteIndexId: 9901,
247 }
248 hostinfo.ConnectionState = &ConnectionState{
249 myCert: &dummyCert{version: cert.Version1},
250 }
251 nc.hostMap.unlockedAddHostInfo(hostinfo, ifce)
252
253 // Do a traffic check tick, in and out should be cleared but should not be pending deletion
254 nc.Out(hostinfo)
255 nc.In(hostinfo)
256 assert.True(t, hostinfo.out.Load())
257 assert.True(t, hostinfo.in.Load())
258
259 now := time.Now()
260 decision, _, _ := nc.makeTrafficDecision(hostinfo.localIndexId, now)
261 assert.Equal(t, tryRehandshake, decision)
262 assert.Equal(t, now, hostinfo.lastUsed)
263 assert.False(t, hostinfo.pendingDeletion.Load())
264 assert.False(t, hostinfo.out.Load())
265 assert.False(t, hostinfo.in.Load())
266
267 decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Second*5))
268 assert.Equal(t, doNothing, decision)
269 assert.Equal(t, now, hostinfo.lastUsed)
270 assert.False(t, hostinfo.pendingDeletion.Load())
271 assert.False(t, hostinfo.out.Load())
272 assert.False(t, hostinfo.in.Load())
273
274 // Do another traffic check tick, should still not be pending deletion
275 decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Second*10))
276 assert.Equal(t, doNothing, decision)
277 assert.Equal(t, now, hostinfo.lastUsed)
278 assert.False(t, hostinfo.pendingDeletion.Load())
279 assert.False(t, hostinfo.out.Load())
280 assert.False(t, hostinfo.in.Load())
281 assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
282 assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
283
284 // Finally advance beyond the inactivity timeout
285 decision, _, _ = nc.makeTrafficDecision(hostinfo.localIndexId, now.Add(time.Minute*10))
286 assert.Equal(t, closeTunnel, decision)
287 assert.Equal(t, now, hostinfo.lastUsed)
288 assert.False(t, hostinfo.pendingDeletion.Load())
289 assert.False(t, hostinfo.out.Load())
290 assert.False(t, hostinfo.in.Load())
291 assert.Contains(t, nc.hostMap.Indexes, hostinfo.localIndexId)
292 assert.Contains(t, nc.hostMap.Hosts, hostinfo.vpnAddrs[0])
293 }
294
295 // Check if we can disconnect the peer.
296 // Validate if the peer's certificate is invalid (expired, etc.)
297 // Disconnect only if disconnectInvalid: true is set.
298 func Test_NewConnectionManagerTest_DisconnectInvalid(t *testing.T) {
299 now := time.Now()
300 l := test.NewLogger()
301
302 vpncidr := netip.MustParsePrefix("172.1.1.1/24")
303 localrange := netip.MustParsePrefix("10.1.1.1/24")
304 vpnIp := netip.MustParseAddr("172.1.1.2")
305 preferredRanges := []netip.Prefix{localrange}
306 hostMap := newHostMap(l)
307 hostMap.preferredRanges.Store(&preferredRanges)
308
309 // Generate keys for CA and peer's cert.
310 pubCA, privCA, _ := ed25519.GenerateKey(rand.Reader)
311 tbs := &cert.TBSCertificate{
312 Version: 1,
313 Name: "ca",
314 IsCA: true,
315 NotBefore: now,
316 NotAfter: now.Add(1 * time.Hour),
317 PublicKey: pubCA,
318 }
319
320 caCert, err := tbs.Sign(nil, cert.Curve_CURVE25519, privCA)
321 require.NoError(t, err)
322 ncp := cert.NewCAPool()
323 require.NoError(t, ncp.AddCA(caCert))
324
325 pubCrt, _, _ := ed25519.GenerateKey(rand.Reader)
326 tbs = &cert.TBSCertificate{
327 Version: 1,
328 Name: "host",
329 Networks: []netip.Prefix{vpncidr},
330 NotBefore: now,
331 NotAfter: now.Add(60 * time.Second),
332 PublicKey: pubCrt,
333 }
334 peerCert, err := tbs.Sign(caCert, cert.Curve_CURVE25519, privCA)
335 require.NoError(t, err)
336
337 cachedPeerCert, err := ncp.VerifyCertificate(now.Add(time.Second), peerCert)
338
339 cs := &CertState{
340 privateKey: []byte{},
341 v1Cert: &dummyCert{},
342 v1Credential: nil,
343 }
344
345 lh := newTestLighthouse()
346 ifce := &Interface{
347 hostMap: hostMap,
348 inside: &overlaytest.NoopTun{},
349 outside: &udp.NoopConn{},
350 firewall: &Firewall{},
351 lightHouse: lh,
352 handshakeManager: NewHandshakeManager(l, hostMap, lh, &udp.NoopConn{}, defaultHandshakeConfig),
353 l: l,
354 pki: &PKI{},
355 }
356 ifce.pki.cs.Store(cs)
357 ifce.pki.caPool.Store(ncp)
358 ifce.disconnectInvalid.Store(true)
359
360 // Create manager
361 conf := config.NewC(test.NewLogger())
362 punchy := NewPunchyFromConfig(test.NewLogger(), conf, nil)
363 nc := newConnectionManagerFromConfig(test.NewLogger(), conf, hostMap, punchy)
364 nc.intf = ifce
365 ifce.connectionManager = nc
366
367 hostinfo := &HostInfo{
368 vpnAddrs: []netip.Addr{vpnIp},
369 ConnectionState: &ConnectionState{
370 myCert: &dummyCert{},
371 peerCert: cachedPeerCert,
372 },
373 }
374 nc.hostMap.unlockedAddHostInfo(hostinfo, ifce)
375
376 // Move ahead 45s.
377 // Check if to disconnect with invalid certificate.
378 // Should be alive.
379 nextTick := now.Add(45 * time.Second)
380 invalid := nc.isInvalidCertificate(nextTick, hostinfo)
381 assert.False(t, invalid)
382
383 // Move ahead 61s.
384 // Check if to disconnect with invalid certificate.
385 // Should be disconnected.
386 nextTick = now.Add(61 * time.Second)
387 invalid = nc.isInvalidCertificate(nextTick, hostinfo)
388 assert.True(t, invalid)
389 }
390
391 type dummyCert struct {
392 version cert.Version
393 curve cert.Curve
394 groups []string
395 isCa bool
396 issuer string
397 name string
398 networks []netip.Prefix
399 notAfter time.Time
400 notBefore time.Time
401 publicKey []byte
402 signature []byte
403 unsafeNetworks []netip.Prefix
404 }
405
406 func (d *dummyCert) Version() cert.Version {
407 return d.version
408 }
409
410 func (d *dummyCert) Curve() cert.Curve {
411 return d.curve
412 }
413
414 func (d *dummyCert) Groups() []string {
415 return d.groups
416 }
417
418 func (d *dummyCert) IsCA() bool {
419 return d.isCa
420 }
421
422 func (d *dummyCert) Issuer() string {
423 return d.issuer
424 }
425
426 func (d *dummyCert) Name() string {
427 return d.name
428 }
429
430 func (d *dummyCert) Networks() []netip.Prefix {
431 return d.networks
432 }
433
434 func (d *dummyCert) NotAfter() time.Time {
435 return d.notAfter
436 }
437
438 func (d *dummyCert) NotBefore() time.Time {
439 return d.notBefore
440 }
441
442 func (d *dummyCert) PublicKey() []byte {
443 return d.publicKey
444 }
445
446 func (d *dummyCert) MarshalPublicKeyPEM() []byte {
447 return cert.MarshalPublicKeyToPEM(d.curve, d.publicKey)
448 }
449
450 func (d *dummyCert) Signature() []byte {
451 return d.signature
452 }
453
454 func (d *dummyCert) UnsafeNetworks() []netip.Prefix {
455 return d.unsafeNetworks
456 }
457
458 func (d *dummyCert) MarshalForHandshakes() ([]byte, error) {
459 return nil, nil
460 }
461
462 func (d *dummyCert) Sign(curve cert.Curve, key []byte) error {
463 return nil
464 }
465
466 func (d *dummyCert) CheckSignature(key []byte) bool {
467 return true
468 }
469
470 func (d *dummyCert) Expired(t time.Time) bool {
471 return false
472 }
473
474 func (d *dummyCert) CheckRootConstraints(signer cert.Certificate) error {
475 return nil
476 }
477
478 func (d *dummyCert) VerifyPrivateKey(curve cert.Curve, key []byte) error {
479 return nil
480 }
481
482 func (d *dummyCert) String() string {
483 return ""
484 }
485
486 func (d *dummyCert) Marshal() ([]byte, error) {
487 return nil, nil
488 }
489
490 func (d *dummyCert) MarshalPEM() ([]byte, error) {
491 return nil, nil
492 }
493
494 func (d *dummyCert) Fingerprint() (string, error) {
495 return "", nil
496 }
497
498 func (d *dummyCert) MarshalJSON() ([]byte, error) {
499 return nil, nil
500 }
501
502 func (d *dummyCert) Copy() cert.Certificate {
503 return d
504 }