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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
// Copyright Pit Kleyersburg <pitkley@googlemail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified or distributed
// except according to those terms.

use super::{
    rule::RuleBuilder, Family, Hook, Nftables, Type, DFW_MARK, NF_PRIORITY_INET_FILTER_ANY_DFW,
    NF_PRIORITY_IP6_NAT_POSTROUTING_DFW, NF_PRIORITY_IP6_NAT_PREROUTING_DFW,
    NF_PRIORITY_IP_NAT_POSTROUTING_DFW, NF_PRIORITY_IP_NAT_PREROUTING_DFW,
};
use crate::{errors::*, process::*, types::*, FirewallBackend};
use failure::{format_err, ResultExt};
use slog::{debug, info, o, trace, warn};
use std::process::Command;

impl Process<Nftables> for DFW<Nftables> {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        info!(ctx.logger, "Starting processing";
              o!("started_processing_at" => time::OffsetDateTime::now_utc().format("%FT%T%z")));
        let mut rules = vec![
            add_table(Family::Inet, "dfw"),
            flush_table(Family::Inet, "dfw"),
            add_base_chain(
                Family::Inet,
                "dfw",
                "input",
                Type::Filter,
                Hook::Input,
                NF_PRIORITY_INET_FILTER_ANY_DFW,
            ),
            add_rule(Family::Inet, "dfw", "input", "ct state invalid drop"),
            add_rule(
                Family::Inet,
                "dfw",
                "input",
                "ct state { related, established } accept",
            ),
            add_base_chain(
                Family::Inet,
                "dfw",
                "forward",
                Type::Filter,
                Hook::Forward,
                NF_PRIORITY_INET_FILTER_ANY_DFW,
            ),
            add_rule(Family::Inet, "dfw", "forward", "ct state invalid drop"),
            add_rule(
                Family::Inet,
                "dfw",
                "forward",
                "ct state { related, established } accept",
            ),
            add_table(Family::Ip, "dfw"),
            flush_table(Family::Ip, "dfw"),
            add_base_chain(
                Family::Ip,
                "dfw",
                "prerouting",
                Type::Nat,
                Hook::Prerouting,
                NF_PRIORITY_IP_NAT_PREROUTING_DFW,
            ),
            add_base_chain(
                Family::Ip,
                "dfw",
                "postrouting",
                Type::Nat,
                Hook::Postrouting,
                NF_PRIORITY_IP_NAT_POSTROUTING_DFW,
            ),
            add_table(Family::Ip6, "dfw"),
            flush_table(Family::Ip6, "dfw"),
            add_base_chain(
                Family::Ip6,
                "dfw",
                "prerouting",
                Type::Nat,
                Hook::Prerouting,
                NF_PRIORITY_IP6_NAT_PREROUTING_DFW,
            ),
            add_base_chain(
                Family::Ip6,
                "dfw",
                "postrouting",
                Type::Nat,
                Hook::Postrouting,
                NF_PRIORITY_IP6_NAT_POSTROUTING_DFW,
            ),
        ];
        for sub_rules in vec![
            self.backend_defaults
                .clone()
                .or_else(|| {
                    // NOTE: this is only required to retain backwards compatibility for version
                    // <1.2. This can be removed in major-version 2 (hence the conditional
                    // compile-error).
                    #[cfg(not(crate_major_version = "1"))]
                    compile_error!("remove this workaround with version 2");

                    Some(Default::default())
                })
                .process(ctx)?,
            self.global_defaults.process(ctx)?,
            self.container_to_container.process(ctx)?,
            self.container_to_wider_world.process(ctx)?,
            self.container_to_host.process(ctx)?,
            self.wider_world_to_container.process(ctx)?,
            self.container_dnat.process(ctx)?,
        ] {
            if let Some(mut sub_rules) = sub_rules {
                rules.append(&mut sub_rules);
            }
        }

        info!(ctx.logger, "Finished processing";
              o!("finished_processing_at" => time::OffsetDateTime::now_utc().format("%FT%T%z")));

        Ok(Some(rules))
    }
}

impl Process<Nftables> for <Nftables as FirewallBackend>::Defaults {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        // NOTE: v1.2.0 deprecated the `nftables::types::Defaults::rules` field in favour of the
        // field present in the `Initialization` sub-type. To retain backwards-compatibility we
        // allow the old field to be present and we will use it if the new field was not specified.
        // (We also warn the user if they used the deprecated field.)
        let mut rules = self
            .initialization
            .clone()
            .and_then(|initialization| initialization.rules)
            .or_else(|| {
                #[cfg_attr(crate_major_version = "1", allow(deprecated))]
                ctx.dfw
                    .initialization
                    .as_ref()
                    .and_then(|initialization| initialization.rules.clone())
                    .filter(|_| {
                        warn!(
                            ctx.logger,
                            "You are using the deprecated `initialization.rules` field in your \
                                configuration! This field has been replaced by the \
                                `backend_defaults.initialization.rules` field. The value format of the \
                                field has stayed unchanged, which means that moving the field to the new \
                                section is sufficient to fix this warning.";
                            o!("deprecated_field" => "initialization.rules",
                                "deprecated_since" => "1.2.0",
                                "planned_removal_in" => "2.0.0",
                                "new_field" => "backend_defaults.initialization.rules",
                                "field_value_format_changed" => false));
                        true
                    })
            })
            .unwrap_or_else(Vec::new);

        // NOTE: v1.2.0 deprecated the `GlobalDefaults::custom_tables` field in favour of the field
        // present in the backend-specific defaults-type. To retain backwards-compatibility we
        // allow the old field to be present and we will use it if the backend-specific field was
        // not specified. (We also warn the user if they used the deprecated field.)
        #[cfg_attr(crate_major_version = "1", allow(deprecated))]
        let custom_tables = self.custom_tables.as_ref().or_else(|| {
            ctx.dfw.global_defaults.custom_tables.as_ref().filter(|_| {
                warn!(
                        ctx.logger,
                        "You are using the deprecated `global_defaults.custom_tables` field in \
                         your configuration! This field has been replaced by the \
                         `backend_defaults.custom_tables` field. The value format of the field has \
                         stayed unchanged, which means that moving the field to the new section is \
                         sufficient to fix this warning.";
                        o!("deprecated_field" => "global_defaults.custom_tables",
                           "deprecated_since" => "1.2.0",
                           "planned_removal_in" => "2.0.0",
                           "new_field" => "backend_defaults.custom_tables",
                           "field_value_format_changed" => false));
                true
            })
        });

        // Hook into other chains if requested
        if let Some(custom_tables) = custom_tables {
            // Retrieve current ruleset to avoid duplication of already existing rules.
            let current_ruleset = Command::new("nft")
                .args(&["list", "ruleset"])
                .output()
                .map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
                .ok();

            for custom_table in custom_tables {
                for chain in &custom_table.chains {
                    let mut additional_rules = Vec::new();

                    // This is a small helper macro to de-duplicate the "add if it doesn't already
                    // exist" logic. It essentially generates a marker which uniquely identifies a
                    // rule, checks if that marker is already in the current ruleset, and if not,
                    // adds it. This enables us to not duplicate rules that are outside of our table
                    // where flushing is not an option.
                    macro_rules! m {
                        ($mark:expr, $rule:expr) => {
                            let marker =
                                generate_marker(&["defaults", &custom_table.name, chain, $mark]);
                            if !current_ruleset
                                .as_ref()
                                .map(|current_ruleset| current_ruleset.contains(&marker))
                                .unwrap_or(false)
                            {
                                additional_rules.push(insert_rule(
                                    Family::Inet,
                                    &custom_table.name,
                                    chain,
                                    &format!("{} comment \"{}\"", $rule, marker),
                                    None,
                                ));
                            }
                        };
                    }
                    // Handle `ct state invalid drop` rule
                    m!("ct-state-invalid-drop", "ct state invalid drop");
                    // Handle `ct state { related, established } accept` rule
                    m!(
                        "ct-state-relatedestablished-accept",
                        "ct state { related, established } accept"
                    );
                    // Handle `meta mark ... accept` rule
                    m!(
                        "meta-mark",
                        &format!("meta mark and {} == {} accept", DFW_MARK, DFW_MARK)
                    );

                    // The rules above are not added at the end, but inserted at the top. We thus
                    // reverse the order of the rules here to effectively retain the initial order
                    // of the vec.
                    additional_rules.reverse();
                    rules.append(&mut additional_rules);
                }
            }
        }

        Ok(Some(rules))
    }
}

impl Process<Nftables> for GlobalDefaults {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        let mut rules = Vec::new();

        // Enforce policy for default Docker-bridge (usually docker0) to access host-resources
        if let Some(bridge_network) = ctx.network_map.get("bridge") {
            if let Some(bridge_name) = bridge_network
                .options
                .as_ref()
                .ok_or_else(|| format_err!("couldn't get network options"))?
                .get("com.docker.network.bridge.name")
            {
                // Set policy for input-chain
                rules.push(add_rule(
                    Family::Inet,
                    "dfw",
                    "input",
                    &format!(
                        "meta iifname {} meta mark set {} {}",
                        bridge_name, DFW_MARK, self.default_docker_bridge_to_host_policy,
                    ),
                ));

                // Set policy for forward-chain, divided by the external network interfaces.
                if let Some(ref external_network_interfaces) = self.external_network_interfaces {
                    for external_network_interface in external_network_interfaces {
                        rules.push(add_rule(
                            Family::Inet,
                            "dfw",
                            "forward",
                            &format!(
                                "meta iifname {} oifname {} meta mark set {} {}",
                                bridge_name,
                                external_network_interface,
                                DFW_MARK,
                                self.default_docker_bridge_to_host_policy,
                            ),
                        ));
                    }
                }
            }
        }

        // Configure postrouting
        if let Some(ref external_network_interfaces) = self.external_network_interfaces {
            for external_network_interface in external_network_interfaces {
                // Configure postrouting
                rules.push(add_rule(
                    Family::Ip,
                    "dfw",
                    "postrouting",
                    &format!(
                        "meta oifname {} meta mark set {} masquerade",
                        external_network_interface, DFW_MARK,
                    ),
                ));
                rules.push(add_rule(
                    Family::Ip6,
                    "dfw",
                    "postrouting",
                    &format!(
                        "meta oifname {} meta mark set {} masquerade",
                        external_network_interface, DFW_MARK,
                    ),
                ));
            }
        }
        Ok(Some(rules))
    }
}

impl Process<Nftables> for ContainerToContainer {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        let mut rules = Vec::new();

        // Enforce default policy for container-to-container communication.
        rules.push(set_chain_policy(
            Family::Inet,
            "dfw",
            "forward",
            self.default_policy,
        ));

        if let Some(mut ctc_rules) = self.rules.process(ctx)? {
            rules.append(&mut ctc_rules);
        }

        Ok(Some(rules))
    }
}

impl Process<Nftables> for ContainerToContainerRule {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        let mut rules = Vec::new();
        let mut nft_rule = RuleBuilder::default();
        let network = match ctx.network_map.get(&self.network) {
            Some(network) => network,
            None => return Ok(None),
        };
        trace!(ctx.logger, "Got network";
                    o!("network_name" => &self.network,
                        "network" => format!("{:?}", network)));
        let bridge_name = get_bridge_name(&network.id)?;
        trace!(ctx.logger, "Got bridge name";
                    o!("network_name" => &network.name,
                        "bridge_name" => &bridge_name));

        nft_rule
            .in_interface(&bridge_name)
            .out_interface(&bridge_name);

        if let Some(ref src_container) = self.src_container {
            trace!(ctx.logger, "Getting network for container");
            let src_network = match get_network_for_container(
                ctx.docker,
                &ctx.container_map,
                src_container,
                &network.id,
            )? {
                Some(src_network) => src_network,
                None => return Ok(None),
            };
            trace!(ctx.logger, "Got source network";
                        o!("network_name" => &network.name,
                            "src_network" => format!("{:?}", src_network)));

            let bridge_name = get_bridge_name(&network.id)?;
            trace!(ctx.logger, "Got bridge name";
                        o!("network_name" => &network.name,
                            "bridge_name" => &bridge_name));

            nft_rule
                .in_interface(&bridge_name)
                .out_interface(&bridge_name)
                .source_address(
                    src_network
                        .ipv4_address
                        .split('/')
                        .next()
                        .ok_or_else(|| format_err!("IPv4 address is empty"))?,
                );
        }

        if let Some(ref dst_container) = self.dst_container {
            let dst_network = match get_network_for_container(
                ctx.docker,
                &ctx.container_map,
                dst_container,
                &network.id,
            )? {
                Some(dst_network) => dst_network,
                None => return Ok(None),
            };
            trace!(ctx.logger, "Got destination network";
                        o!("network_name" => &network.name,
                            "dst_network" => format!("{:?}", dst_network)));

            let bridge_name = get_bridge_name(&network.id)?;
            trace!(ctx.logger, "Got bridge name";
                        o!("network_name" => &network.name,
                            "bridge_name" => &bridge_name));

            nft_rule.out_interface(&bridge_name).destination_address(
                dst_network
                    .ipv4_address
                    .split('/')
                    .next()
                    .ok_or_else(|| format_err!("IPv4 address is empty"))?,
            );
        }

        if let Some(matches) = &self.matches {
            nft_rule.matches(matches);
        }
        nft_rule.verdict(self.verdict);

        let rule = nft_rule.build()?;
        rules.push(add_rule(Family::Inet, "dfw", "forward", &rule));

        Ok(Some(rules))
    }
}

impl Process<Nftables> for ContainerToWiderWorld {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        let mut rules = Vec::new();

        if let Some(mut ctww_rules) = self.rules.process(ctx)? {
            rules.append(&mut ctww_rules);
        }

        // Enforce default policy for container-to-wider-world communication.
        if let Some(external_network_interfaces) = &ctx.external_network_interfaces {
            debug!(ctx.logger, "Set default policy for external network interfaces";
                   o!("part" => "container_to_wider_world",
                      "external_network_interfaces" => format!("{:?}", external_network_interfaces),
                      "default_policy" => &self.default_policy));
            for external_network_interface in external_network_interfaces {
                trace!(ctx.logger, "Process default policy for external network interface";
                       o!("part" => "container_to_wider_world",
                          "external_network_interface" => external_network_interface,
                          "default_policy" => &self.default_policy));
                for network in ctx.network_map.values() {
                    let bridge_name = get_bridge_name(&network.id)?;
                    trace!(ctx.logger, "Got bridge name";
                           o!("network_name" => &network.name,
                              "bridge_name" => &bridge_name));

                    let rule = RuleBuilder::default()
                        .in_interface(&bridge_name)
                        .out_interface(external_network_interface)
                        .verdict(self.default_policy)
                        .build()?;

                    debug!(ctx.logger, "Add forward rule for default policy";
                           o!("part" => "container_to_wider_world",
                              "external_network_interface" => external_network_interface,
                              "default_policy" => &self.default_policy,
                              "rule" => &rule));

                    rules.push(add_rule(Family::Inet, "dfw", "forward", &rule));
                }
            }
        }

        Ok(Some(rules))
    }
}

impl Process<Nftables> for ContainerToWiderWorldRule {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        let mut rules = Vec::new();
        debug!(ctx.logger, "Process rule";
                   o!("part" => "container_to_wider_world",
                      "rule" => format!("{:?}", self)));
        let mut nft_rule = RuleBuilder::default();

        if let Some(ref network) = self.network {
            if let Some(network) = ctx.network_map.get(network) {
                let bridge_name = get_bridge_name(&network.id)?;
                trace!(ctx.logger, "Got bridge name";
                           o!("network_name" => &network.name,
                              "bridge_name" => &bridge_name));

                nft_rule.in_interface(&bridge_name);

                if let Some(ref src_container) = self.src_container {
                    if let Some(src_network) = get_network_for_container(
                        ctx.docker,
                        &ctx.container_map,
                        src_container,
                        &network.id,
                    )? {
                        trace!(ctx.logger, "Got source network";
                                   o!("network_name" => &network.name,
                                      "src_network" => format!("{:?}", src_network)));

                        let bridge_name = get_bridge_name(&network.id)?;
                        trace!(ctx.logger, "Got bridge name";
                                   o!("network_name" => &network.name,
                                      "bridge_name" => &bridge_name));

                        nft_rule.in_interface(&bridge_name).source_address(
                            src_network
                                .ipv4_address
                                .split('/')
                                .next()
                                .ok_or_else(|| format_err!("IPv4 address is empty"))?,
                        );
                    }
                } else {
                    let bridge_name = get_bridge_name(&network.id)?;
                    trace!(ctx.logger, "Got bridge name";
                               o!("network_name" => &network.name,
                                  "bridge_name" => &bridge_name));

                    nft_rule.in_interface(&bridge_name);
                }
            }
        }

        if let Some(ref matches) = self.matches {
            nft_rule.matches(matches);
        }

        nft_rule.verdict(self.verdict);

        // Try to build the rule without the out_interface defined to see if any of the other
        // mandatory fields has been populated.
        debug!(ctx.logger, "Build rule to verify contents";
                   o!("args" => format!("{:?}", nft_rule)));
        nft_rule.build().context(format!(
            "failed to build rule, maybe the network `{:?}` or container `{:?}` doesn't exist",
            self.network, self.src_container
        ))?;

        if let Some(ref external_network_interface) = self.external_network_interface {
            trace!(ctx.logger, "Rule has specific external network interface";
                       o!("external_network_interface" => external_network_interface));
            nft_rule.out_interface(external_network_interface);
        } else if let Some(ref primary_external_network_interface) =
            ctx.primary_external_network_interface
        {
            trace!(ctx.logger, "Rule uses primary external network interface";
                       o!("external_network_interface" => primary_external_network_interface));
            nft_rule.out_interface(primary_external_network_interface);
        }

        let rule = nft_rule.build()?;
        debug!(ctx.logger, "Add forward rule";
                   o!("part" => "container_to_wider_world",
                      "rule" => &rule));

        // Apply the rule
        rules.push(add_rule(Family::Inet, "dfw", "forward", &rule));
        Ok(Some(rules))
    }
}

impl Process<Nftables> for ContainerToHost {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        let mut rules = Vec::new();

        if let Some(mut cth_rules) = self.rules.process(ctx)? {
            rules.append(&mut cth_rules);
        }

        // Default policy
        for network in ctx.network_map.values() {
            let bridge_name = get_bridge_name(&network.id)?;
            trace!(ctx.logger, "Got bridge name";
                   o!("network_name" => &network.name,
                      "bridge_name" => &bridge_name));

            let rule = RuleBuilder::default()
                .in_interface(&bridge_name)
                .verdict(self.default_policy)
                .build()?;

            trace!(ctx.logger, "Add input rule for default policy";
                   o!("part" => "container_to_host",
                      "default_policy" => self.default_policy,
                      "rule" => &rule));
            rules.push(add_rule(Family::Inet, "dfw", "input", &rule));
        }

        Ok(Some(rules))
    }
}

impl Process<Nftables> for ContainerToHostRule {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        let mut rules = Vec::new();
        debug!(ctx.logger, "Process rule";
                   o!("part" => "container_to_host",
                      "rule" => format!("{:?}", self)));
        let mut nft_rule = RuleBuilder::default();

        let network = match ctx.network_map.get(&self.network) {
            Some(network) => network,
            None => return Ok(None),
        };
        trace!(ctx.logger, "Got network";
                   o!("network_name" => &network.name,
                      "network" => format!("{:?}", network)));

        let bridge_name = get_bridge_name(&network.id)?;
        trace!(ctx.logger, "Got bridge name";
                   o!("network_name" => &network.name,
                      "bridge_name" => &bridge_name));

        nft_rule.in_interface(&bridge_name);

        if let Some(ref src_container) = self.src_container {
            if let Some(src_network) = get_network_for_container(
                ctx.docker,
                &ctx.container_map,
                src_container,
                &network.id,
            )? {
                trace!(ctx.logger, "Got source network";
                           o!("network_name" => &network.name,
                              "src_network" => format!("{:?}", src_network)));
                nft_rule.source_address(
                    src_network
                        .ipv4_address
                        .split('/')
                        .next()
                        .ok_or_else(|| format_err!("IPv4 address is empty"))?,
                );
            }
        }

        if let Some(ref matches) = self.matches {
            nft_rule.matches(matches);
        }

        nft_rule.verdict(self.verdict);

        // Try to build the rule without the out_interface defined to see if any of the other
        // mandatory fields has been populated.
        debug!(ctx.logger, "Build rule to verify contents";
                   o!("args" => format!("{:?}", nft_rule)));
        nft_rule.build().context(format!(
            "failed to build rule, maybe the container `{:?}` doesn't exist",
            self.src_container
        ))?;

        let rule = nft_rule.build()?;
        debug!(ctx.logger, "Add input rule";
                   o!("part" => "container_to_host",
                      "rule" => &rule));

        // Apply the rule
        rules.push(add_rule(Family::Inet, "dfw", "input", &rule));

        Ok(Some(rules))
    }
}

impl Process<Nftables> for WiderWorldToContainer {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        if self.rules.is_some() {
            debug!(ctx.logger, "Process rules";
                   o!("part" => "wider_world_to_container"));
            self.rules.process(ctx)
        } else {
            trace!(ctx.logger, "No rules";
                   o!("part" => "wider_world_to_container"));
            Ok(None)
        }
    }
}

impl WiderWorldToContainerRule {
    fn apply_source_cidrs_v4(
        &self,
        ctx: &ProcessContext<Nftables>,
        rules: &mut Vec<String>,
        source_cidrs: &[String],
        nft_forward_rule: RuleBuilder,
        nft_dnat_rule: RuleBuilder,
    ) -> Result<()> {
        debug!(ctx.logger, "Generate extended FORWARD rules, source CIDRs (IPv4) were specified";
               o!("args" => format!("{:?}", nft_dnat_rule),
                  "source_cidrs" => source_cidrs.join(", ")));
        for additional_forward_rule in source_cidrs
            .iter()
            .map(|source_cidr| {
                let mut forward_rule = nft_forward_rule.clone();
                forward_rule.source_address(source_cidr);
                forward_rule
            })
            .map(|forward_rule| forward_rule.build())
            .collect::<Result<Vec<_>>>()?
        {
            debug!(ctx.logger, "Add FORWARD rule";
                   o!("part" => "wider_world_to_container",
                      "rule" => &additional_forward_rule));
            rules.push(add_rule(
                Family::Inet,
                "dfw",
                "forward",
                &additional_forward_rule,
            ));
        }
        for additional_dnat_rule in source_cidrs
            .iter()
            .map(|source_cidr| {
                let mut dnat_rule = nft_dnat_rule.clone();
                dnat_rule.source_address(source_cidr);
                dnat_rule
            })
            .map(|dnat_rule| dnat_rule.build())
            .collect::<Result<Vec<_>>>()?
        {
            debug!(ctx.logger, "Add DNAT rule";
                   o!("part" => "wider_world_to_container",
                      "rule" => &additional_dnat_rule));
            rules.push(add_rule(
                Family::Ip,
                "dfw",
                "prerouting",
                &additional_dnat_rule,
            ));
        }

        Ok(())
    }

    fn apply_source_cidrs_v6(
        &self,
        ctx: &ProcessContext<Nftables>,
        rules: &mut Vec<String>,
        source_cidrs: &[String],
        nft_mark_rule: RuleBuilder,
    ) -> Result<()> {
        debug!(ctx.logger, "Generate extended prerouting rules, source CIDRs (IPv6) were specified";
               o!("args" => format!("{:?}", nft_mark_rule),
                  "source_cidrs" => source_cidrs.join(", ")));
        for additional_mark_rule in source_cidrs
            .iter()
            .map(|source_cidr| {
                let mut mark_rule = nft_mark_rule.clone();
                mark_rule.source_address_v6(source_cidr);
                mark_rule
            })
            .map(|dnat_rule| dnat_rule.build())
            .collect::<Result<Vec<_>>>()?
        {
            debug!(ctx.logger, "Add mark rule";
                            o!("part" => "wider_world_to_container",
                               "rule" => &additional_mark_rule));
            rules.push(add_rule(
                Family::Ip6,
                "dfw",
                "prerouting",
                &additional_mark_rule,
            ));
        }
        Ok(())
    }
}

impl Process<Nftables> for WiderWorldToContainerRule {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        let mut rules = Vec::new();
        debug!(ctx.logger, "Process rule";
                   o!("part" => "wider_world_to_container",
                      "rule" => format!("{:?}", self)));
        for expose_port in &self.expose_port {
            let mut nft_forward_rule = RuleBuilder::default();
            let mut nft_dnat_rule = RuleBuilder::default();
            let mut nft_mark_rule = RuleBuilder::default();

            let network = match ctx.network_map.get(&self.network) {
                Some(network) => network,
                None => return Ok(None),
            };
            trace!(ctx.logger, "Got network";
                   o!("network_name" => &network.name,
                      "network" => format!("{:?}", network)));

            let bridge_name = get_bridge_name(&network.id)?;
            trace!(ctx.logger, "Got bridge name";
                   o!("network_name" => &network.name,
                      "bridge_name" => &bridge_name));

            nft_forward_rule.out_interface(&bridge_name);

            if let Some(dst_network) = get_network_for_container(
                ctx.docker,
                &ctx.container_map,
                &self.dst_container,
                &network.id,
            )? {
                trace!(ctx.logger, "Got destination network";
                       o!("network_name" => &network.name,
                          "dst_network" => format!("{:?}", dst_network)));

                nft_forward_rule.destination_address(
                    dst_network
                        .ipv4_address
                        .split('/')
                        .next()
                        .ok_or_else(|| format_err!("IPv4 address is empty"))?,
                );

                let host_port = expose_port.host_port.to_string();
                let container_port = match expose_port.container_port {
                    Some(destination_port) => destination_port.to_string(),
                    None => expose_port.host_port.to_string(),
                };
                nft_forward_rule.destination_port(&container_port);
                nft_dnat_rule.destination_port(&host_port);
                nft_dnat_rule.dnat(&format!(
                    "{}:{}",
                    dst_network
                        .ipv4_address
                        .split('/')
                        .next()
                        .ok_or_else(|| format_err!("IPv4 address is empty"))?,
                    container_port
                ));
                nft_mark_rule.destination_port(&host_port);
            // INFO: correct IPv6 handling would include actually using IPv6-addresses.
            // While the code below is correct, the postrouting does not work since nftables cannot
            // route IPv6 packets to IPv4 destinations.
            //
            // if !dst_network.ipv6_address.is_empty() {
            //     nft_mark_rule.dnat(&format!(
            //         "{}:{}",
            //         dst_network.ipv6_address
            //         .split('/')
            //         .next()
            //         .ok_or_else(|| format_err!("Invalid IPv6 address"))?,
            //     destination_port));
            // }
            } else {
                // Network for container has to exist
                return Ok(None);
            }

            // Set correct protocol
            nft_forward_rule.protocol(&expose_port.family);
            nft_dnat_rule.protocol(&expose_port.family);
            nft_mark_rule.protocol(&expose_port.family);

            nft_forward_rule.verdict(RuleVerdict::Accept);

            // Try to build the rule without the out_interface defined to see if any of the
            // other mandatory fields has been populated.
            debug!(ctx.logger, "Build rule to verify contents";
                   o!("args" => format!("{:?}", nft_forward_rule)));
            nft_forward_rule.build()?;
            debug!(ctx.logger, "build rule to verify contents";
                   o!("args" => format!("{:?}", nft_dnat_rule)));
            nft_dnat_rule.build()?;
            debug!(ctx.logger, "Build rule to verify contents";
                   o!("args" => format!("{:?}", nft_mark_rule)));
            nft_mark_rule.build()?;

            if let Some(ref external_network_interface) = self.external_network_interface {
                trace!(ctx.logger, "Rule has specific external network interface";
                       o!("external_network_interface" => external_network_interface));

                nft_forward_rule.in_interface(external_network_interface);
                nft_dnat_rule.in_interface(external_network_interface);
                nft_mark_rule.in_interface(external_network_interface);
            } else if let Some(ref primary_external_network_interface) =
                ctx.primary_external_network_interface
            {
                trace!(ctx.logger, "Rule uses primary external network interface";
                       o!("external_network_interface" => primary_external_network_interface));

                nft_forward_rule.in_interface(primary_external_network_interface);
                nft_dnat_rule.in_interface(primary_external_network_interface);
                nft_mark_rule.in_interface(primary_external_network_interface);
            } else {
                // The DNAT rule requires the external interface
                return Ok(None);
            }

            // If source CIDRs have been specified, create the FORWARD-rules as required to
            // restrict the traffic as intended.
            if let Some(source_cidrs_v4) = &self.source_cidr_v4 {
                self.apply_source_cidrs_v4(
                    ctx,
                    &mut rules,
                    source_cidrs_v4,
                    nft_forward_rule.clone(),
                    nft_dnat_rule.clone(),
                )?;
            }
            if self.expose_via_ipv6 {
                if let Some(source_cidrs_v6) = &self.source_cidr_v6 {
                    self.apply_source_cidrs_v6(
                        ctx,
                        &mut rules,
                        source_cidrs_v6,
                        nft_mark_rule.clone(),
                    )?;
                }
            }

            // If no source CIDRs were specified, we create the default rules that allow all
            // connections from any IP.
            if self.source_cidr_v4.is_none() && self.source_cidr_v6.is_none() {
                let forward_rule = nft_forward_rule.build()?;
                debug!(ctx.logger, "Add forward rule";
                       o!("part" => "wider_world_to_container",
                          "rule" => &forward_rule));
                let dnat_rule = nft_dnat_rule.build()?;
                debug!(ctx.logger, "Add DNAT rule";
                       o!("part" => "wider_world_to_container",
                          "rule" => &dnat_rule));
                let mark_rule = nft_mark_rule.build()?;
                debug!(ctx.logger, "Add mark rule";
                       o!("part" => "wider_world_to_container",
                          "rule" => &mark_rule));
                // Apply the rule
                rules.push(add_rule(Family::Inet, "dfw", "forward", &forward_rule));
                rules.push(add_rule(Family::Ip, "dfw", "prerouting", &dnat_rule));
                if self.expose_via_ipv6 {
                    rules.push(add_rule(Family::Ip6, "dfw", "prerouting", &mark_rule));
                }
            }
        }

        Ok(Some(rules))
    }
}

impl Process<Nftables> for ContainerDNAT {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        if self.rules.is_some() {
            debug!(ctx.logger, "Process rules";
                o!("part" => "container_dnat"));
            self.rules.process(ctx)
        } else {
            trace!(ctx.logger, "No rules";
                    o!("part" => "container_dnat"));
            Ok(None)
        }
    }
}

impl Process<Nftables> for ContainerDNATRule {
    fn process(&self, ctx: &ProcessContext<Nftables>) -> Result<Option<Vec<String>>> {
        debug!(ctx.logger, "Process rule";
                   o!("part" => "container_dnat",
                      "rule" => format!("{:?}", self)));
        let mut rules = Vec::new();
        for expose_port in &self.expose_port {
            let mut nft_rule = RuleBuilder::default();

            if let Some(ref network) = self.src_network {
                if let Some(network) = ctx.network_map.get(network) {
                    trace!(ctx.logger, "Got network";
                               o!("network_name" => &network.name,
                                  "network" => format!("{:?}", network)));

                    let bridge_name = get_bridge_name(&network.id)?;
                    trace!(ctx.logger, "Got bridge name";
                               o!("network_name" => &network.name,
                                  "bridge_name" => &bridge_name));

                    nft_rule.in_interface(&bridge_name);

                    if let Some(ref src_container) = self.src_container {
                        if let Some(src_network) = get_network_for_container(
                            ctx.docker,
                            &ctx.container_map,
                            src_container,
                            &network.id,
                        )? {
                            trace!(ctx.logger, "Got source network";
                                       o!("network_name" => &network.name,
                                          "src_network" => format!("{:?}", src_network)));

                            let bridge_name = get_bridge_name(&network.id)?;
                            trace!(ctx.logger, "Got bridge name";
                                       o!("network_name" => &network.name,
                                          "bridge_name" => &bridge_name));

                            nft_rule.in_interface(&bridge_name).source_address(
                                src_network
                                    .ipv4_address
                                    .split('/')
                                    .next()
                                    .ok_or_else(|| format_err!("IPv4 address is empty"))?,
                            );
                        }
                    }
                }
            }

            let network = match ctx.network_map.get(&self.dst_network) {
                Some(network) => network,
                None => return Ok(None),
            };
            let dst_network = match get_network_for_container(
                ctx.docker,
                &ctx.container_map,
                &self.dst_container,
                &network.id,
            )? {
                Some(dst_network) => dst_network,
                None => return Ok(None),
            };
            trace!(ctx.logger, "Got destination network";
                       o!("network_name" => &network.name,
                          "dst_network" => format!("{:?}", dst_network)));

            let bridge_name = get_bridge_name(&network.id)?;
            trace!(ctx.logger, "Got bridge name";
                       o!("network_name" => &network.name,
                          "bridge_name" => &bridge_name));

            nft_rule.out_interface(&bridge_name);

            let destination_port = match expose_port.container_port {
                Some(destination_port) => destination_port.to_string(),
                None => expose_port.host_port.to_string(),
            };
            nft_rule.destination_port(&destination_port);
            nft_rule.dnat(&format!(
                "{}:{}",
                dst_network
                    .ipv4_address
                    .split('/')
                    .next()
                    .ok_or_else(|| format_err!("IPv4 address is empty"))?,
                destination_port
            ));

            let rule = nft_rule.build()?;
            debug!(ctx.logger, "Add prerouting rule";
                       o!("part" => "container_dnat",
                          "rule" => &rule));

            // Apply the rule
            rules.push(add_rule(Family::Ip, "dfw", "prerouting", &rule));
        }

        Ok(Some(rules))
    }
}

/// Construct nft command for adding a table.
fn add_table(family: Family, table: &str) -> String {
    format!("add table {} {}", family, table)
}

/// Construct nft command for flushing a table.
fn flush_table(family: Family, table: &str) -> String {
    format!("flush table {} {}", family, table)
}

/// Construct nft command for adding a base chain.
fn add_base_chain(
    family: Family,
    table: &str,
    chain: &str,
    r#type: Type,
    hook: Hook,
    priority: i16,
) -> String {
    format!(
        "add chain {} {} {} {{ type {} hook {} priority {} ; }}",
        family, table, chain, r#type, hook, priority
    )
}

/// Construct nft command for setting the policy for a chain.
fn set_chain_policy(family: Family, table: &str, chain: &str, policy: ChainPolicy) -> String {
    format!(
        "add chain {} {} {} {{ policy {} ; }}",
        family, table, chain, policy
    )
}

/// Construct nft command for adding a rule to a chain.
fn add_rule(family: Family, table: &str, chain: &str, rule: &str) -> String {
    format!("add rule {} {} {} {}", family, table, chain, rule)
}

/// Construct nft command for inserting a rule into a chain.
fn insert_rule(
    family: Family,
    table: &str,
    chain: &str,
    rule: &str,
    position: Option<u32>,
) -> String {
    format!(
        "insert rule {} {} {} {}{}",
        family,
        table,
        chain,
        if let Some(position) = position {
            format!("position {} ", position)
        } else {
            "".to_owned()
        },
        rule
    )
}