-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcreate.go
1490 lines (1350 loc) · 43.8 KB
/
create.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package whalewall
import (
"bytes"
"context"
"database/sql"
"encoding/binary"
"encoding/gob"
"errors"
"fmt"
"net/netip"
"slices"
"strconv"
"strings"
"syscall"
"github.com/docker/docker/api/types"
"github.com/google/nftables"
"github.com/google/nftables/expr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/exp/maps"
"golang.org/x/sys/unix"
"gopkg.in/yaml.v3"
"github.com/capnspacehook/whalewall/database"
)
const (
hostNetworkName = "host"
composeProjectLabel = "com.docker.compose.project"
composeServiceLabel = "com.docker.compose.service"
composeContNumLabel = "com.docker.compose.container-number"
chainPrefix = "whalewall-"
srcAddrOffset = uint32(12)
dstAddrOffset = uint32(16)
srcPortOffset = uint32(0)
dstPortOffset = uint32(2)
stateNew = expr.CtStateBitNEW
stateEst = expr.CtStateBitESTABLISHED | expr.CtStateBitRELATED
stateNewEst = stateNew | stateEst
)
var (
localAddr = netip.MustParseAddr("127.0.0.1")
zeroUint32 = []byte{0, 0, 0, 0}
acceptVerdict = &expr.Verdict{
Kind: expr.VerdictAccept,
}
dropVerdict = &expr.Verdict{
Kind: expr.VerdictDrop,
}
)
// createRules adds nftables rules for started containers.
func (r *RuleManager) createRules(ctx context.Context) {
for c := range r.createCh {
if err := r.createContainerRules(ctx, c.container, c.isNew); err != nil {
r.logger.Error("error creating rules",
zap.String("container.id", c.container.ID[:12]),
zap.String("container.name", stripName(c.container.Name)),
zap.Error(err),
)
}
}
}
// createContainerRules creates nftables rules for a container.
func (r *RuleManager) createContainerRules(ctx context.Context, container types.ContainerJSON, isNew bool) (retErr error) {
ctx, cleanup := r.containerTracker.StartCreatingContainer(ctx, container.ID)
defer cleanup()
contName := stripName(container.Name)
logger := r.logger.With(zap.String("container.id", container.ID[:12]), zap.String("container.name", contName))
logger.Info("creating rules", zap.Bool("container.is_new", isNew))
// check that network settings are valid
if container.NetworkSettings == nil {
return fmt.Errorf("container %q has no network settings", contName)
}
if len(container.NetworkSettings.Networks) == 1 {
if _, ok := container.NetworkSettings.Networks[hostNetworkName]; ok {
return fmt.Errorf("container %q is using host networking, rules cannot be created for it", contName)
}
}
// parse rules config if the rules label exists; if the label
// does not exist, no rules will be added but all traffic to
// and from the container will still be dropped
var rulesCfg config
cfg, configExists := container.Config.Labels[rulesLabel]
if configExists {
dec := yaml.NewDecoder(strings.NewReader(cfg))
dec.KnownFields(true)
if err := dec.Decode(&rulesCfg); err != nil {
return fmt.Errorf("error parsing rules: %w", err)
}
if err := validateConfig(rulesCfg); err != nil {
return fmt.Errorf("error validating rules: %w", err)
}
}
// ensure specified networks and containers in rules are valid
addrs := make(map[string][]byte, len(container.NetworkSettings.Networks))
for netName, netSettings := range container.NetworkSettings.Networks {
addr, err := netip.ParseAddr(netSettings.IPAddress)
if err != nil {
return fmt.Errorf("error parsing IP of container: %q: %w", contName, err)
}
addrs[netName] = ref(addr.As4())[:]
}
nfc, err := r.newFirewallClient()
if err != nil {
return fmt.Errorf("error creating netlink connection: %w", err)
}
// create chain for this container's rules
contChainName := buildChainName(contName, container.ID)
chain := &nftables.Chain{
Name: contChainName,
Table: filterTable,
Type: nftables.ChainTypeFilter,
}
nfc.AddChain(chain)
if err := ignoringErr(nfc.Flush, syscall.EEXIST); err != nil {
return fmt.Errorf("error creating chain: %w", err)
}
// add container IPs to jump set so traffic to/from this
// container will go to the correct chain
addrElems := make([]nftables.SetElement, 0, len(addrs))
for _, addr := range addrs {
addrElems = append(addrElems, nftables.SetElement{
Key: addr,
VerdictData: &expr.Verdict{
Kind: expr.VerdictJump,
Chain: contChainName,
},
})
}
if err := nfc.SetAddElements(containerAddrSet, addrElems); err != nil {
return fmt.Errorf("error marshaling set elements: %w", err)
}
if err := ignoringErr(nfc.Flush, syscall.EEXIST); err != nil {
return fmt.Errorf("error adding elements to container address set: %w", err)
}
// cleanup created rules if the context was canceled
var createdRules []*nftables.Rule
defer func() {
if retErr == nil {
return
} else if !errors.Is(retErr, context.Canceled) {
return
}
// if we are shutting down, don't delete rules
select {
case <-r.stopping:
return
default:
}
logger.Info("rule creation canceled, deleting created rules")
if err := nfc.SetDeleteElements(containerAddrSet, addrElems); err != nil {
logger.Error("error marshaling set elements", zap.Error(err))
}
if err := ignoringErr(nfc.Flush, syscall.ENOENT); err != nil {
logger.Error("error deleting elements to container address set", zap.Error(err))
}
for _, rule := range createdRules {
if rule.Chain.Name == chain.Name {
continue
}
if err := nfc.DelRule(rule); err != nil {
logger.Error("error deleting rule", zap.Error(err))
continue
}
if err := ignoringErr(nfc.Flush, syscall.ENOENT); err != nil {
logger.Error("error deleting rule", zap.Error(err))
}
}
nfc.DelChain(chain)
if err := ignoringErr(nfc.Flush, syscall.ENOENT); err != nil {
logger.Error("error deleting chain", zap.String("chain.name", chain.Name), zap.Error(err))
}
}()
createRules := func(rules []*nftables.Rule, insert bool) error {
if err := ctx.Err(); err != nil {
return err
}
// keep track of rules that were generated from the given config
// so we can remove rules in this container's chain not created
// by whalewall
createdRules = append(createdRules, rules...)
// ensure we aren't creating existing rules
currentRules := make(map[string][]*nftables.Rule)
for _, rule := range rules {
if _, ok := currentRules[rule.Chain.Name]; ok {
continue
}
curRules, err := nfc.GetRules(filterTable, rule.Chain)
if err != nil {
return fmt.Errorf("error getting rules of chain %q: %w", rule.Chain.Name, err)
}
currentRules[rule.Chain.Name] = curRules
}
j := 0
for _, rule := range rules {
// keep rules that don't already exist, discard the rest
if findRule(logger, rule, currentRules[rule.Chain.Name]) {
continue
}
rules[j] = rule
j++
}
rules = rules[:j]
if insert {
// insert rules in reverse order that they were created in to maintain order
for i := len(rules) - 1; i >= 0; i-- {
nfc.InsertRule(rules[i])
}
} else {
for _, rule := range rules {
nfc.AddRule(rule)
}
}
return nfc.Flush()
}
// create rule to drop all not explicitly allowed traffic
err = createRules([]*nftables.Rule{createDropRule(chain, container.ID)}, false)
if err != nil {
return fmt.Errorf("error creating drop rule: %w", err)
}
// add container to database
tx, err := r.db.Begin(ctx, logger)
if err != nil {
return err
}
defer tx.Rollback()
if isNew {
if err := tx.AddContainer(ctx, container.ID, contName); err != nil {
return fmt.Errorf("error adding container to database: %w", err)
}
}
project := container.Config.Labels[composeProjectLabel]
estContainers := make(map[string]struct{})
if configExists {
if err := r.populateOutputRules(ctx, tx, rulesCfg, container.ID, project, addrs, estContainers); err != nil {
return fmt.Errorf("error validating rules: %w", err)
}
}
// create rules that allow traffic from another container to this
// container if necessary that couldn't be created before
service := container.Config.Labels[composeServiceLabel]
logger.Debug("creating waiting rules")
waitingRules, err := r.createWaitingContainerRules(ctx, nfc, logger, tx, container.ID, contName, service, project, addrs, chain, estContainers)
if err != nil {
return fmt.Errorf("error creating waiting output rules: %w", err)
}
if err := createRules(waitingRules, true); err != nil {
logger.Error("error creating waiting rules", zap.Error(err))
}
// if no rules were explicitly specified, only the rule that drops
// traffic to/from the container will be added
if configExists {
// handle outbound rules
logger.Debug("creating output rules")
outputRules, err := r.createOutputRules(ctx, nfc, logger, tx, rulesCfg.Output, project, addrs, chain, contName, container.ID)
if err != nil {
return fmt.Errorf("error creating output rules: %w", err)
}
if err := createRules(outputRules, true); err != nil {
logger.Error("error creating output rules", zap.Error(err))
}
// handle port mapping rules
logger.Debug("creating mapped port rules")
portMapRules, err := r.createPortMappingRules(nfc, logger, container, contName, rulesCfg.MappedPorts, addrs, chain)
if err != nil {
return fmt.Errorf("error creating port mapping rules: %w", err)
}
if err := createRules(portMapRules, true); err != nil {
logger.Error("error creating mapped port rules", zap.Error(err))
}
}
// remove rules in this container's chain not created by whalewall
currentRules, err := nfc.GetRules(chain.Table, chain)
if err != nil {
return fmt.Errorf("error getting rules of chain %q: %w", chain.Name, err)
}
createdContRules := make([]*nftables.Rule, 0, len(createdRules)/2)
for _, rule := range createdRules {
if rule.Chain.Name == chain.Name {
createdContRules = append(createdContRules, rule)
}
}
for _, currentRule := range currentRules {
if !findRule(logger, currentRule, createdContRules) {
if err := nfc.DelRule(currentRule); err != nil {
logger.Error("error deleting rule", zap.Error(err))
continue
}
logger.Warn("deleting rule not created by whalewall", zap.String("chain.name", chain.Name))
if err := ignoringErr(nfc.Flush, syscall.ENOENT); err != nil {
logger.Error("error deleting rule", zap.Error(err))
}
}
}
if !isNew {
return nil
}
logger.Debug("adding to database")
if err := r.addContainer(ctx, tx, container.ID, contName, service, addrs, estContainers); err != nil {
return fmt.Errorf("error adding container information to database: %w", err)
}
return nil
}
// stripName removes the leading "/" from a container name if necessary.
func stripName(name string) string {
if len(name) > 0 && name[0] == '/' {
name = name[1:]
}
return name
}
// populateOutputRules attempts to find the IPs of containers specified
// in output rules and fills the rules appropriately.
func (r *RuleManager) populateOutputRules(ctx context.Context, tx database.TX, cfg config, id, project string, addrs map[string][]byte, estConts map[string]struct{}) error {
// only get a list of containers if at least one rule specifies a
// container
i := slices.IndexFunc(cfg.Output, func(r ruleConfig) bool {
return r.Container != ""
})
if i == -1 {
return nil
}
listedConts, err := r.dockerCli.ContainerList(ctx, types.ContainerListOptions{})
if err != nil {
return fmt.Errorf("error listing running containers: %w", err)
}
containers := make(map[string]types.ContainerJSON)
for i, ruleCfg := range cfg.Output {
// ensure the specified network exists
if ruleCfg.Network != "" {
if _, _, ok := findNetwork(ruleCfg.Network, project, addrs); !ok {
return fmt.Errorf("output rule #%d: network %q not found",
i,
ruleCfg.Network,
)
}
}
if ruleCfg.Container != "" {
// if the specified container is started, check that whalewall
// is enabled for it and that it is a member of the specified
// network
var found bool
for _, listedCont := range listedConts {
if !containerNameMatches(ruleCfg.Container, listedCont.Labels, listedCont.Names...) {
continue
}
// validate container settings
cont, ok := containers[ruleCfg.Container]
if !ok {
cont, err = r.dockerCli.ContainerInspect(ctx, listedCont.ID)
if err != nil {
return fmt.Errorf("error inspecting container %s", listedCont.ID[:12])
}
enabled, err := whalewallEnabled(cont.Config.Labels)
if err != nil {
return fmt.Errorf("error parsing container %q label: %w", cont.ID[:12], err)
}
if !enabled {
return fmt.Errorf("output rule #%d: container %q does not have whalewall enabled",
i,
ruleCfg.Container,
)
}
containers[ruleCfg.Container] = cont
}
dstProject := cont.Config.Labels[composeProjectLabel]
dstNetName, dstNetwork, ok := findNetwork(ruleCfg.Network, dstProject, cont.NetworkSettings.Networks)
if !ok {
return fmt.Errorf("output rule #%d: network %q not found for container %q",
i,
ruleCfg.Network,
ruleCfg.Container,
)
}
// if the container exists in the database it's been
// processed already, and we can create rules involving
// it now
exists, err := r.containerExists(ctx, tx, cont.ID)
if err != nil {
return fmt.Errorf("error querying container %s from database: %w", cont.ID[:12], err)
}
if !exists {
break
}
estConts[cont.ID] = struct{}{}
found = true
addr, err := netip.ParseAddr(dstNetwork.IPAddress)
if err != nil {
return fmt.Errorf("error parsing IP of container %q from network %q: %w", ruleCfg.Container, dstNetName, err)
}
cfg.Output[i].IPs = []addrOrRange{
{addr: addr},
}
break
}
if !found {
// we need to add rules to this container's chain, but it
// hasn't been processed yet; wait until this container
// is processed to create the rules
cfg.Output[i].skip = true
}
// Add the rule to the database so when we are processing
// this container, this rule will be created. This is done
// even when the container has been processed so future
// rule creation will be idempotent.
var buf bytes.Buffer
encoder := gob.NewEncoder(&buf)
if err := encoder.Encode(ruleCfg); err != nil {
return fmt.Errorf("error encoding waiting container rule: %w", err)
}
err := tx.AddWaitingContainerRule(ctx, database.AddWaitingContainerRuleParams{
SrcContainerID: id,
DstContainerName: ruleCfg.Container,
Rule: buf.Bytes(),
})
if err != nil {
return fmt.Errorf("error adding waiting container rule to database: %w", err)
}
}
}
return nil
}
// findNetwork attempts to find a given Docker network, returning the
// name the network was found by if possible. Docker Compose sometimes
// prepends the name of the Compose project to the name the user originally
// gave the network.
func findNetwork[T any](network, project string, addrs map[string]T) (string, T, bool) {
var zero T
netNames := [2]string{
network,
project + "_" + network,
}
for _, netName := range netNames {
v, ok := addrs[netName]
if ok {
return netName, v, true
}
}
return "", zero, false
}
// containerNameMatches returns true if a canonical container name can
// be found from a combination of labels and names.
func containerNameMatches(expectedName string, labels map[string]string, names ...string) bool {
if len(expectedName) == 0 {
return false
}
// maybe user prefixed a backslash already?
if slices.Contains(names, expectedName) {
return true
}
// docker prepends a backslash to container names
slashPrefix := expectedName[0] == '/'
if !slashPrefix && slices.Contains(names, "/"+expectedName) {
return true
}
// if the user did prefix a slash, remove it here so we hopefully
// get a match; the service name won't be prefixed with a backslash
if slashPrefix {
expectedName = expectedName[1:]
}
// check if the Docker Compose service name matches
if serviceName, ok := labels[composeServiceLabel]; ok && serviceName == expectedName {
return true
}
return false
}
func buildChainName(name, id string) string {
return fmt.Sprintf("%s%s-%s", chainPrefix, name, id[:12])
}
// TODO: avoid creating almost duplicate rules as output rules
// createPortMappingRules adds nftables rules to allow or deny access to
// mapped ports.
func (r *RuleManager) createPortMappingRules(nfc firewallClient, logger *zap.Logger, container types.ContainerJSON, contName string, mappedPortsCfg mappedPorts, addrs map[string][]byte, chain *nftables.Chain) ([]*nftables.Rule, error) {
// check if there are any mapped ports to create rules for
var hasMappedPorts bool
for _, hostPorts := range container.NetworkSettings.Ports {
// if an image exposes a port but no mapped ports are configured,
// the container port it will be here with no host ports
if len(hostPorts) != 0 {
hasMappedPorts = true
break
}
}
if (mappedPortsCfg.Localhost.Allow || mappedPortsCfg.External.Allow) && !hasMappedPorts {
logger.Warn("local and/or external access to mapped ports is allowed, but there are not any mapped ports")
return nil, nil
}
if !hasMappedPorts {
return nil, nil
}
// prepend container name and ID to log prefixes
if mappedPortsCfg.Localhost.LogPrefix != "" {
mappedPortsCfg.Localhost.LogPrefix = formatLogPrefix(mappedPortsCfg.Localhost.LogPrefix, contName, container.ID)
}
if mappedPortsCfg.External.LogPrefix != "" {
mappedPortsCfg.External.LogPrefix = formatLogPrefix(mappedPortsCfg.External.LogPrefix, contName, container.ID)
}
nftRules := make([]*nftables.Rule, 0, len(container.NetworkSettings.Networks))
for netName, netSettings := range container.NetworkSettings.Networks {
gateway, err := netip.ParseAddr(netSettings.Gateway)
if err != nil {
return nil, fmt.Errorf("error parsing gateway of network: %w", err)
}
// sort mapped ports so rules are created deterministically making
// testing much easier
sortedPorts := maps.Keys(container.NetworkSettings.Ports)
slices.Sort(sortedPorts)
for _, port := range sortedPorts {
hostPorts := container.NetworkSettings.Ports[port]
localAllowed := mappedPortsCfg.Localhost.Allow
var proto protocol
if err := proto.UnmarshalText([]byte(port.Proto())); err != nil {
return nil, fmt.Errorf("error parsing protocol: %w", err)
}
for _, hostPort := range hostPorts {
addr, err := netip.ParseAddr(hostPort.HostIP)
if err != nil {
return nil, fmt.Errorf("error parsing IP of port mapping: %w", err)
}
// TODO: support IPv6
if addr.Is6() {
continue
}
// TODO: make same checks for external
if localAllowed && !addr.IsUnspecified() && addr != localAddr {
logger.Sugar().Warnf("local access to mapped ports is allowed, but port %s is listening on %s which is not accessible to localhost",
hostPort.HostPort,
addr,
)
continue
}
if !localAllowed && !addr.IsUnspecified() && addr != localAddr {
// local access is not allowed, but localhost won't
// be able to reach this port anyway since it isn't
// listening on 0.0.0.0 or 127.0.0.1, so no need to
// create any rules
continue
}
if !localAllowed || (localAllowed && (!mappedPortsCfg.External.Allow || len(mappedPortsCfg.External.IPs) != 0)) {
// Create rules to allow/drop traffic from container
// network gateway to container; this will only be hit
// for traffic originating from localhost after being
// NATed by docker rules. If all external inbound
// traffic is allowed, creating this is pointless as
// the rule to allow all external inbound traffic will
// cover traffic from the gateway too.
rule := ruleDetails{
inbound: true,
addr: addrs[netName],
cfg: ruleConfig{
LogPrefix: mappedPortsCfg.Localhost.LogPrefix,
IPs: []addrOrRange{
{addr: gateway},
},
Proto: proto,
DstPorts: []rulePorts{
{
single: uint16(port.Int()),
},
},
Verdict: mappedPortsCfg.Localhost.Verdict,
},
chain: chain,
contID: container.ID,
}
rule.cfg.Verdict.drop = !localAllowed
rules, err := createNFTRules(nfc, logger, rule)
if err != nil {
return nil, fmt.Errorf("error creating firewall rules: %w", err)
}
nftRules = append(nftRules, rules...)
}
if !localAllowed {
// Create rule to drop traffic going to the mapped
// host port. This will prevent traffic originating
// from localhost to be seen by Docker at all.
hostPortInt, err := strconv.ParseUint(hostPort.HostPort, 10, 16)
if err != nil {
return nil, fmt.Errorf("error parsing host port of port mapping: %w", err)
}
localhostDropRule := ruleDetails{
inbound: true,
cfg: ruleConfig{
IPs: []addrOrRange{
{addr: localAddr},
},
Proto: proto,
DstPorts: []rulePorts{
{
single: uint16(hostPortInt),
},
},
Verdict: verdict{
drop: true,
},
},
chain: whalewallChain,
contID: container.ID,
}
rules, err := createNFTRules(nfc, logger, localhostDropRule)
if err != nil {
return nil, fmt.Errorf("error creating firewall rules: %w", err)
}
nftRules = append(nftRules, rules...)
}
}
// if there are no host ports mapped to the container port,
// don't create allow rules as the port wasn't exposed by
// the user but rather was created from an EXPOSE Dockerfile
// directive
if mappedPortsCfg.External.Allow && len(hostPorts) > 0 {
// create rules to allow external traffic to container
rule := ruleDetails{
inbound: true,
addr: addrs[netName],
cfg: ruleConfig{
LogPrefix: mappedPortsCfg.External.LogPrefix,
IPs: mappedPortsCfg.External.IPs,
Proto: proto,
DstPorts: []rulePorts{
{
single: uint16(port.Int()),
},
},
Verdict: mappedPortsCfg.External.Verdict,
},
chain: chain,
contID: container.ID,
}
rules, err := createNFTRules(nfc, logger, rule)
if err != nil {
return nil, fmt.Errorf("error creating firewall rules: %w", err)
}
nftRules = append(nftRules, rules...)
}
}
}
return nftRules, nil
}
// createOutputRules adds nftables rules to allow outbound access from
// a container.
func (r *RuleManager) createOutputRules(ctx context.Context, nfc firewallClient, logger *zap.Logger, tx database.TX, ruleCfgs []ruleConfig, project string, addrs map[string][]byte, chain *nftables.Chain, name, id string) ([]*nftables.Rule, error) {
nftRules := make([]*nftables.Rule, 0, len(ruleCfgs)*3)
for _, ruleCfg := range ruleCfgs {
// prepend container name and ID to log prefixes
if ruleCfg.LogPrefix != "" {
ruleCfg.LogPrefix = formatLogPrefix(ruleCfg.LogPrefix, name, id)
}
rule := ruleDetails{
inbound: false,
cfg: ruleCfg,
chain: chain,
contID: id,
}
if ruleCfg.Network != "" {
_, addr, ok := findNetwork(ruleCfg.Network, project, addrs)
if !ok {
return nil, fmt.Errorf("network %q not found", ruleCfg.Network)
}
rule.addr = addr
if ruleCfg.Container != "" {
if ruleCfg.skip {
// the container either hasn't been started yet or
// doesn't exist; this rule will be created when
// processing this container later
continue
}
dstID, dstName, err := r.getContainerIDAndName(ctx, tx, ruleCfg.Container)
if err != nil {
return nil, fmt.Errorf("error getting container %q ID from database: %w", ruleCfg.Container, err)
}
rule.estChain = &nftables.Chain{
Table: filterTable,
Name: buildChainName(dstName, dstID),
}
rule.contID = dstID
rule.estContID = id
}
rules, err := createNFTRules(nfc, logger, rule)
if err != nil {
return nil, fmt.Errorf("error creating firewall rules: %w", err)
}
nftRules = append(nftRules, rules...)
} else {
for _, addr := range addrs {
rule.addr = addr
rules, err := createNFTRules(nfc, logger, rule)
if err != nil {
return nil, fmt.Errorf("error creating firewall rules: %w", err)
}
nftRules = append(nftRules, rules...)
}
}
}
return nftRules, nil
}
// getContainerIDAndName returns the ID and canonical name of a container
// if it is present in the database.
func (r *RuleManager) getContainerIDAndName(ctx context.Context, db database.Querier, contName string) (string, string, error) {
name := contName
id, err := db.GetContainerID(ctx, contName)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return "", "", fmt.Errorf("error getting container %q ID from database: %w", contName, err)
}
info, err := db.GetContainerIDAndNameFromAlias(ctx, contName)
if err != nil {
return "", "", fmt.Errorf("error getting container %q ID from database: %w", contName, err)
}
id = info.ID
name = info.Name
}
return id, name, nil
}
// createWaitingContainerRules creates nftables rules to allow access
// from another container to this container. The other container was
// processed before this container, so rules concerning this container
// couldn't be created until now.
func (r *RuleManager) createWaitingContainerRules(ctx context.Context, nfc firewallClient, logger *zap.Logger, tx database.TX, id, name, service, project string, addrs map[string][]byte, chain *nftables.Chain, estContainers map[string]struct{}) ([]*nftables.Rule, error) {
var (
waitingRules []database.GetWaitingContainerRulesRow
err error
aliases = append([]string{name}, containerAliases(name, service)...)
)
for _, alias := range aliases {
waitingRules, err = tx.GetWaitingContainerRules(ctx, alias)
if err != nil {
return nil, fmt.Errorf("error getting waiting container rules of %q from database: %w", alias, err)
}
if len(waitingRules) == 0 {
continue
}
break
}
if waitingRules == nil {
return nil, nil
}
nftRules := make([]*nftables.Rule, 0, len(waitingRules)*3)
for _, waitingRule := range waitingRules {
decoder := gob.NewDecoder(bytes.NewReader(waitingRule.Rule))
var ruleCfg ruleConfig
if err := decoder.Decode(&ruleCfg); err != nil {
return nil, fmt.Errorf("error decoding waiting container rule: %w", err)
}
// find source container IP (not this container)
srcCont, err := r.dockerCli.ContainerInspect(ctx, waitingRule.SrcContainerID)
if err != nil {
return nil, fmt.Errorf("error inspecting container %q: %w", waitingRule.Name, err)
}
srcProject := srcCont.Config.Labels[composeProjectLabel]
srcNetName, srcNetwork, ok := findNetwork(ruleCfg.Network, srcProject, srcCont.NetworkSettings.Networks)
if !ok {
return nil, fmt.Errorf("network %q not found for container %q",
ruleCfg.Network,
ruleCfg.Container,
)
}
srcAddr, err := netip.ParseAddr(srcNetwork.IPAddress)
if err != nil {
return nil, fmt.Errorf("error parsing IP of container %q from network %q: %w", ruleCfg.Container, srcNetName, err)
}
// find destination container IP (this container)
dstNetName, dstNetwork, ok := findNetwork(ruleCfg.Network, project, addrs)
if !ok {
return nil, fmt.Errorf("network %q not found", ruleCfg.Network)
}
dstAddr, ok := netip.AddrFromSlice(dstNetwork)
if !ok {
return nil, fmt.Errorf("error parsing IP of from network %q", dstNetName)
}
ruleCfg.IPs = []addrOrRange{{addr: dstAddr}}
// create rules
rule := ruleDetails{
inbound: false,
addr: ref(srcAddr.As4())[:],
cfg: ruleCfg,
chain: &nftables.Chain{
Table: filterTable,
Name: buildChainName(waitingRule.Name, waitingRule.SrcContainerID),
},
estChain: chain,
contID: id,
estContID: waitingRule.SrcContainerID,
}
rules, err := createNFTRules(nfc, logger, rule)
if err != nil {
return nil, fmt.Errorf("error creating firewall rules: %w", err)
}
nftRules = append(nftRules, rules...)
estContainers[waitingRule.SrcContainerID] = struct{}{}
}
return nftRules, nil
}
func formatLogPrefix(prefix, name, id string) string {
prefix = fmt.Sprintf("whalewall-%s-%s %s", name, id[:12], prefix)
if !strings.HasSuffix(prefix, ": ") {
prefix += ": "
}
return prefix
}
type ruleDetails struct {
inbound bool
addr []byte
cfg ruleConfig
chain *nftables.Chain
estChain *nftables.Chain
contID string
estContID string
}
func (r ruleDetails) MarshalLogObject(enc zapcore.ObjectEncoder) error {
enc.AddBool("inbound", r.inbound)
if len(r.addr) != 0 {
ip, ok := netip.AddrFromSlice(r.addr)
if !ok {
return fmt.Errorf("error parsing addr %v", r.addr)
}
enc.AddString("container_addr", ip.String())
}
zap.Inline(r.cfg).AddTo(enc)
if r.chain != nil {
enc.AddString("chain", r.chain.Name)
}
if r.estChain != nil {
enc.AddString("est_chain", r.estChain.Name)
}
enc.AddString("cont_id", r.contID[:12])
if r.estContID != "" {
enc.AddString("est_cont_id", r.estContID[:12])
}
return nil
}
// createNFTRules returns a slice of [*nftables.Rule] described by rd.
func createNFTRules(nfc firewallClient, logger *zap.Logger, rd ruleDetails) ([]*nftables.Rule, error) {
logger.Debug("generating rule", zap.Object("rule", rd))
rules := make([]*nftables.Rule, 0, 3)
estContID := rd.contID
if rd.estChain == nil {
rd.estChain = rd.chain
} else {
estContID = rd.estContID
}
// if the rule is a drop rule, only need to handle new traffic
if rd.cfg.Verdict.drop {
rule, err := createNFTRule(nfc, rd.inbound, false, stateNew, rd.addr, rd.cfg, 0, rd.chain, rd.contID)
if err != nil {
return nil, err
}
return append(rules, rule), nil
}
if rd.cfg.Verdict.Queue == 0 {
if rd.cfg.LogPrefix == "" {
newEstRule, err := createNFTRule(nfc, rd.inbound, false, stateNewEst, rd.addr, rd.cfg, 0, rd.chain, rd.contID)
if err != nil {
return nil, err
}
estRule, err := createNFTRule(nfc, !rd.inbound, true, stateEst, rd.addr, rd.cfg, 0, rd.estChain, estContID)
if err != nil {
return nil, err
}
return append(rules, newEstRule, estRule), nil
}
// create a separate rule for new traffic to log it
dstNewRule, err := createNFTRule(nfc, rd.inbound, false, stateNew, rd.addr, rd.cfg, 0, rd.chain, rd.contID)
if err != nil {
return nil, err
}
dstEstRule, err := createNFTRule(nfc, rd.inbound, false, stateEst, rd.addr, rd.cfg, 0, rd.chain, rd.contID)
if err != nil {
return nil, err
}
srcEstRule, err := createNFTRule(nfc, !rd.inbound, true, stateEst, rd.addr, rd.cfg, 0, rd.estChain, estContID)
if err != nil {
return nil, err
}
return append(rules, dstNewRule, dstEstRule, srcEstRule), nil
}
// If there is no log prefix set we can create one inbound rule and
// one outbound rule in some situations. Otherwise new traffic must
// be logged.
if rd.cfg.LogPrefix == "" {
if rd.inbound && rd.cfg.Verdict.Queue == rd.cfg.Verdict.InputEstQueue {
// if rule is inbound and queue and established inbound queue
// are the same, create one rule for inbound traffic
newEstRule, err := createNFTRule(nfc, true, false, stateNewEst, rd.addr, rd.cfg, rd.cfg.Verdict.Queue, rd.chain, rd.contID)
if err != nil {
return nil, err
}
estRule, err := createNFTRule(nfc, false, true, stateEst, rd.addr, rd.cfg, rd.cfg.Verdict.OutputEstQueue, rd.estChain, estContID)
if err != nil {
return nil, err
}
return append(rules, newEstRule, estRule), nil
} else if !rd.inbound && rd.cfg.Verdict.Queue == rd.cfg.Verdict.OutputEstQueue {
// if rule is outbound and queue and established outbound queue
// are the same, create one rule for outbound traffic
newEstRule, err := createNFTRule(nfc, false, false, stateNewEst, rd.addr, rd.cfg, rd.cfg.Verdict.Queue, rd.chain, rd.contID)
if err != nil {
return nil, err
}
estRule, err := createNFTRule(nfc, true, true, stateEst, rd.addr, rd.cfg, rd.cfg.Verdict.InputEstQueue, rd.estChain, estContID)
if err != nil {