This file is indexed.

/usr/share/perl5/EBox/Iptables.pm is in zentyal-firewall 2.3.3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# Copyright (C) 2008-2012 eBox Technologies S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

package EBox::Iptables;
# Package to manage iptables command utility

# private functions will return references to sets of commands to be run
# instead of running the commands themselves

use strict;
use warnings;

use EBox;
use EBox::Firewall;
use EBox::Config;
use EBox::Global;
use EBox::Gettext;
use EBox::Objects;
use EBox::Network;
use EBox::Firewall::IptablesHelper;
use EBox::Exceptions::External;
use EBox::Exceptions::Internal;
use Error qw( :try );
use Perl6::Junction qw( any );
use EBox::Sudo;

my $statenew = " -m state --state NEW ";

use constant IPT_MODULES => ('ip_conntrack_ftp', 'ip_nat_ftp', 'ip_conntrack_tftp');
use constant SYSLOG_LEVEL => 7;

# Constructor: new
#
#      Create a new EBox::Iptables object
#
# Returns:
#
#      A recently created EBox::Iptables object
sub new
{
    my $class = shift;
    my $self = {};
    $self->{firewall} = EBox::Global->modInstance('firewall');
    $self->{objects} = EBox::Global->modInstance('objects');
    $self->{net} = EBox::Global->modInstance('network');
    $self->{deny} = $self->{firewall}->denyAction;

    bless($self, $class);
    return $self;
}

# Method: pf
#
#       Execute iptables command with options
#
# Parameters:
#
#       opts - options passed to iptables
#
# Returns:
#
#       array ref - the output of iptables command in an array
#
sub pf # (options)
{
    my ($opts) = @_;
    return "/sbin/iptables $opts";
}

# Method: _startIPForward
#
#       Change kernel to do IPv4 forwarding (default)
#
# Returns:
#
#       array ref - the output of sysctl command in an array
#
sub _startIPForward
{
    return [ '/sbin/sysctl -q -w net.ipv4.ip_forward="1"' ];
}

# Method: _stopIPForward
#
#       Change kernel to stop doing IPv4 forwarding
#
# Returns:
#
#       array ref - the output of sysctl command in an array
#
sub _stopIPForward
{
    return [ '/sbin/sysctl -q -w net.ipv4.ip_forward="0"' ];
}

# Method: _setKernelParameters
#
#       Set kernel parameters for increased security
#
# Returns:
#
#       array ref - the output of sysctl command in an array
#
sub _setKernelParameters
{
    my @commands;
    # enable TCP SYN cookie protection
    push(@commands, '/sbin/sysctl -q -w net.ipv4.tcp_syncookies="1"');
    # don't log spoofed, source-routed, or redirect packets
    push(@commands, '/sbin/sysctl -q -w net.ipv4.conf.all.log_martians="0"');
    # disable ICMP redirects
    push(@commands, '/sbin/sysctl -q -w net.ipv4.conf.all.accept_redirects="0"');
    push(@commands, '/sbin/sysctl -q -w net.ipv4.conf.all.send_redirects="0"');
    # drop source-routed packets
    push(@commands, '/sbin/sysctl -q -w net.ipv4.conf.all.accept_source_route="0"');
    # enable bad error message protection
    push(@commands, '/sbin/sysctl -q -w net.ipv4.icmp_ignore_bogus_error_responses="1"');
    # enable ICMP broadcast echo protection
    push(@commands, '/sbin/sysctl -q -w net.ipv4.icmp_echo_ignore_broadcasts="1"');
    return \@commands;
}

# Method: _clearTables
#
#       Clear all tables (user defined and nat), set a policy to
#       OUTPUT, INPUT and FORWARD chains and allow always traffic
#       from/to loopback interface.
#
# Parameters:
#
#       policy - It can be a target
#       (ACCEPT|DROP|REJECT|QUEUE|RETURN|user-defined chain)
#       See iptables TARGETS section
#
sub _clearTables # (policy)
{
    my $self = shift;
    my $policy = shift;
    my @commands;
    push(@commands,
            pf("-F"),
            pf("-X"),
            pf("-t nat -F"),
            pf("-t nat -X"),
        );
# Allow loopback
    if (($policy eq 'DROP') or ($policy eq 'REJECT')) {
        push(@commands,
                pf('-A INPUT -i lo -j ACCEPT'),
                pf('-A OUTPUT -o lo -j ACCEPT'),
            );
    }
    push(@commands,
            pf("-P OUTPUT $policy"),
            pf("-P INPUT $policy"),
            pf("-P FORWARD $policy"),
        );
    return \@commands;
}

# Method: _setStructure
#
#       Set structure to Firewall module to work
#
sub _setStructure
{
    my ($self) = @_;

    my @commands = ();
    push(@commands,
            @{$self->_clearTables("DROP")}
        );

    # state rules
    push(@commands,
            pf('-N odrop'),
            pf('-A OUTPUT -m state --state INVALID -j odrop'),
            pf('-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT'),
            pf('-N idrop'),
            pf('-A INPUT -m state --state INVALID -j idrop'),
            pf('-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT'),
            pf('-N fdrop'),
            pf('-A FORWARD -m state --state INVALID -j fdrop'),

            pf('-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT'),

            pf('-t nat -N premodules'),

            pf('-t nat -N postmodules'),

            pf('-N fnospoofmodules'),
            pf('-N fnospoof'),
            pf('-A fnospoof -j fnospoofmodules'),
            pf('-N fredirects'),
            pf('-N fmodules'),
            pf('-N ffwdrules'),
            pf('-N fnoexternal'),
            pf('-N fdns'),
            pf('-N fobjects'),
            pf('-N fglobal'),
            pf('-N ftoexternalonly'),

            pf('-N inospoofmodules'),
            pf('-N inospoof'),
            pf('-A inospoof -j inospoofmodules'),
            pf('-N inointernal'),
            pf('-N iexternalmodules'),
            pf('-N iexternal'),
            pf('-N inoexternal'),
            pf('-N imodules'),
            pf('-N iintservs'),
            pf('-N iglobal'),

            pf('-N drop'),

            pf('-N log'),

            pf('-N ointernal'),
            pf('-N omodules'),
            pf('-N oglobal'),

            pf('-t nat -A PREROUTING -j premodules'),

            pf('-t nat -A POSTROUTING -j postmodules'),

            pf('-A FORWARD -j fnospoof'),
            pf('-A FORWARD -j fredirects'),
            pf('-A FORWARD -j fmodules'),
            pf('-A FORWARD -j ffwdrules'),
            pf('-A FORWARD -j fnoexternal'),
            pf('-A FORWARD -j fdns'),
            pf('-A FORWARD -j fobjects'),
            pf('-A FORWARD -j fglobal'),
            pf("-A FORWARD -p icmp --icmp-type echo-request ! -f $statenew -j ACCEPT"), # accept ping requests
            pf("-A FORWARD -p icmp --icmp-type echo-reply ! -f $statenew -j ACCEPT"), # accept ping responses
            pf("-A FORWARD -p icmp --icmp-type destination-unreachable ! -f $statenew -j ACCEPT"), # accept notifications of unreachable hosts
            pf("-A FORWARD -p icmp --icmp-type source-quench ! -f $statenew -j ACCEPT"), # accept notifications to reduce sending speed
            pf("-A FORWARD -p icmp --icmp-type time-exceeded ! -f $statenew -j ACCEPT"), # accept notifications of lost packets
            pf("-A FORWARD -p icmp --icmp-type parameter-problem ! -f $statenew -j ACCEPT"), # accept notifications of protocol problems
            pf('-A FORWARD -j fdrop'),

            pf('-A INPUT -j inospoof'),
            pf('-A INPUT -j iexternalmodules'),
            pf('-A INPUT -j iexternal'),
            pf('-A INPUT -j inoexternal'),
            pf('-A INPUT -j imodules'),
            pf('-A INPUT -j iintservs'),
            pf('-A INPUT -j iglobal'),
            pf("-A INPUT -p icmp --icmp-type echo-request ! -f $statenew -j ACCEPT"), # accept ping requests
            pf("-A INPUT -p icmp --icmp-type echo-reply ! -f $statenew -j ACCEPT"), # accept ping responses
            pf("-A INPUT -p icmp --icmp-type destination-unreachable ! -f $statenew -j ACCEPT"), # accept notifications of unreachable hosts
            pf("-A INPUT -p icmp --icmp-type source-quench ! -f $statenew -j ACCEPT"), # accept notifications to reduce sending speed
            pf("-A INPUT -p icmp --icmp-type time-exceeded ! -f $statenew -j ACCEPT"), # accept notifications of lost packets
            pf("-A INPUT -p icmp --icmp-type parameter-problem ! -f $statenew -j ACCEPT"), # accept notifications of protocol problems
            pf('-A INPUT -j idrop'),

            pf('-A OUTPUT -j ointernal'),
            pf('-A OUTPUT -j omodules'),
            pf('-A OUTPUT -j oglobal'),
            pf("-A OUTPUT -p icmp --icmp-type echo-request ! -f $statenew -j ACCEPT"), # accept ping requests
            pf("-A OUTPUT -p icmp --icmp-type echo-reply ! -f $statenew -j ACCEPT"), # accept ping responses
            pf("-A OUTPUT -p icmp --icmp-type destination-unreachable ! -f $statenew -j ACCEPT"), # accept notifications of unreachable hosts
            pf("-A OUTPUT -p icmp --icmp-type source-quench ! -f $statenew -j ACCEPT"), # accept notifications to reduce sending speed
            pf("-A OUTPUT -p icmp --icmp-type time-exceeded ! -f $statenew -j ACCEPT"), # accept notifications of lost packets
            pf("-A OUTPUT -p icmp --icmp-type parameter-problem ! -f $statenew -j ACCEPT"), # accept notifications of protocol problems
            pf('-A OUTPUT -j odrop'),

            pf("-A idrop -j drop"),
            pf("-A odrop -j drop"),
            pf("-A fdrop -j drop"),
            );
    return \@commands;
}

# Method: _setDNS
#
#       Set DNS traffic for forwarding and output with destination dns
#
# Parameters:
#
#       dns - address/[mask] destination to accept DNS traffic
#
sub _setDNS # (dns)
{
    my ($self, $dns) = @_;

    my @commands = (
        pf("-A ointernal $statenew -p udp --dport 53 -d $dns -j ACCEPT || true"),
        pf("-A ointernal $statenew -p tcp --dport 53 -d $dns -j ACCEPT || true"),
        pf("-A fdns $statenew -p udp --dport 53 -d $dns -j ACCEPT || true"),
        pf("-A fdns $statenew -p tcp --dport 53 -d $dns -j ACCEPT || true"),
    );
    return \@commands;
}

# Method: _setDHCP
#
#       Set output DHCP traffic
#
# Parameters:
#
#       interface -
#
sub _setDHCP
{
    my ($self, $interface) = @_;

    $interface = $self->{net}->realIface($interface);
    return [ pf("-A ointernal $statenew -o $interface -p udp --dport 67 -j ACCEPT") ];
}

# Method: _setRemoteServices
#
#       Set output rules required to remote services to work
#
#
sub _setRemoteServices
{
    my ($self) = @_;

    my @commands;

    my $gl = EBox::Global->getInstance();
    if ( $gl->modExists('remoteservices') ) {
        my $rsMod = $gl->modInstance('remoteservices');
        if ( $rsMod->eBoxSubscribed() ) {
            my $vpnIface = $rsMod->ifaceVPN();
            push(@commands,
                pf("-A ointernal $statenew -o $vpnIface -j ACCEPT")
            );
            try {
                my %vpnSettings = %{$rsMod->vpnSettings()};
                push(@commands,
                     pf("-A ointernal $statenew -p $vpnSettings{protocol} "
                          . "-d $vpnSettings{ipAddr} --dport $vpnSettings{port} -j ACCEPT")
                );

                # Allow communications between ns and www
                eval "use EBox::RemoteServices::Configuration";
                my ($dnsServer, $publicWebServer, $mirrorCount) = (
                        EBox::RemoteServices::Configuration->DNSServer(),
                        EBox::RemoteServices::Configuration->PublicWebServer(),
                        EBox::RemoteServices::Configuration->eBoxServicesMirrorCount(),
                        );
                # We are assuming just one name server
                push(@commands,
                    pf("-A ointernal $statenew -p udp -d $dnsServer --dport 53 -j ACCEPT || true"),
                );
                # Public WWW servers to connect to
                for my $no ( 1 .. $mirrorCount ) {
                    my $site = $publicWebServer;
                    $site =~ s:\.:$no.:;
                    push(@commands,
                        pf("-A ointernal $statenew -p tcp -d $site --dport 443 -j ACCEPT || true")
                    );
                }
            } catch EBox::Exceptions::External with {
                # Cannot contact eBox CC, no DNS?
                my ($exc) = @_;
                my $msg = "Cannot contact Zentyal Cloud: $exc";
                EBox::error($msg);
                $gl->addSaveMessage($msg);
            };
        }
    }
    return \@commands;
}

# Method: _nospoof
#
#       Set no IP spoofing (forged) for the given addresses to the
#       interface given
#
# Parameters:
#
# interface - the allowed interface for the addresses
# addresses - An array ref with the address to allow traffic from
#             the given interface. Each slot has the following
#             fields:
#                - address - the IP address
#                - netmask - the IP network mask

sub _nospoof # (interface, \@addresses)
{
    my ($self, $iface, $addresses) = @_;

    $iface = $self->{net}->realIface($iface);

    my @commands;
    foreach (@{$addresses}) {
        my $addr = $_->{address};
        my $mask = $_->{netmask};
        push(@commands,
                pf("-A fnospoof -s $addr/$mask ! -i $iface -j fdrop"),
                pf("-A inospoof -s $addr/$mask ! -i $iface -j idrop"),
               # pf("-A inospoof ! -i $iface -d $addr -j idrop"),
            );
    }
    return \@commands;
}

# Method: _localRedirects
#
#       Do effective local redirections. Done via
#       <EBox::Firewall::addLocalRedirect> using NAT.
#
sub _localRedirects
{
    my $self = shift;
    my $redirects = $self->{firewall}->localRedirects();
    my @commands;
    foreach my $redir (@{$redirects}) {
        my $service = $redir->{service};
        my $protocol = $self->{firewall}->serviceProtocol($service);
        my $dport = $self->{firewall}->servicePort($service);
        my $eport = $redir->{port};
        my @ifaces = @{$self->{net}->InternalIfaces()};
        foreach my $ifc (@ifaces) {
            my $addr = $self->{net}->ifaceAddress($ifc);
            $ifc = $self->{net}->realIface($ifc);
            (defined($addr) && $addr ne "") or next;
            push(@commands,
                    pf("-t nat -A PREROUTING -i $ifc -p $protocol ".
                        "! -d $addr --dport $eport " .
                        "-j REDIRECT --to-ports $dport")
                );
        }
    }
    return \@commands;
}

# Method: stop
#
#       Stop iptables service, stop forwarding from kernel
#       and free all tables
#
sub stop
{
    my ($self) = @_;

    my @commands;
    push(@commands, @{_stopIPForward()});
    push(@commands, @{$self->_clearTables("ACCEPT")});
    EBox::Sudo::root(@commands);
}

# Method: vifaceRealname
#
#       Return the real name from a virtual interface
#
# Parameters:
#
#       viface - Virtual interface
#
# Returns:
#
#       string - The real name from the given virtual interface
#
sub vifaceRealname # (viface)
{
    my $virtual = shift;
    $virtual =~ s/:.*$//;
    return $virtual;
}

# Method: start
#
#       Start firewall service setting up the structure and the rules
#       to work with iptables.
#
sub start
{
    my $self = shift;

    my @commands;

    push(@commands, @{$self->_loadIptModules()});

    push(@commands, @{$self->_setStructure()});

    my @dns = @{$self->{net}->nameservers()};
    foreach (@dns) {
        push(@commands, @{$self->_setDNS($_)});
    }

    foreach my $object (@{$self->{objects}->objects}) {
        my $members = $self->{objects}->objectMembers($object->{id});
        foreach my $member (@{$members}) {
            my $mac = $member->{macaddr};
            defined($mac) or next;
            ($mac ne "") or next;
            my $address = $member->{ipaddr};
            push(@commands,
                    pf("-A inospoof -m mac -s $address " .
                        "! --mac-source $mac -j idrop"),
                    pf("-A fnospoof -m mac -s $address " .
                        "! --mac-source $mac -j fdrop"),
                );
        }
    }

    my @ifaces = @{$self->{net}->ifaces()};
    foreach my $ifc (@ifaces) {
        next if ($self->{net}->ifaceMethod($ifc) eq 'bridged');

        if ($self->{net}->ifaceMethod($ifc) eq any('dhcp', 'ppp')) {
            push(@commands, @{$self->_setDHCP($ifc)});
            my $dnsSrvs = $self->{net}->DHCPNameservers($ifc);
            foreach my $srv (@{$dnsSrvs}) {
                push(@commands, @{$self->_setDNS($srv)});
            }
        } else {
            # Anti-spoof rules only for static interfaces
            my $addrs = $self->{net}->ifaceAddresses($ifc);
            push(@commands, @{$self->_nospoof($ifc, $addrs)});
        }
    }

    push(@commands, @{$self->_setRemoteServices()});

    push(@commands, @{$self->_redirects()});

    @ifaces = @{$self->{net}->ExternalIfaces()};
    foreach my $if (@ifaces) {
        my $method = $self->{net}->ifaceMethod($if);
        $if = $self->{net}->realIface($if);

        my $input = $self->_inputIface($if);
        my $output = $self->_outputIface($if);

        unless ( $self->{net}->ifaceIsBridge($if) ) {
            push(@commands,
                pf("-A fnoexternal $statenew $input -j fdrop"),
                pf("-A inoexternal $statenew $input -j idrop"),
                pf("-A ftoexternalonly $output -j ACCEPT"),
            );
        }

        next unless (_natEnabled());

        if ($method eq 'static') {
            my $addr = $self->{net}->ifaceAddress($if);
            my $src = $addr;

            # If it's a bridge SNAT traffic out of the network
            if ( $self->{net}->ifaceIsBridge($if) ) {
                my $mask = $self->{net}->ifaceNetmask($if);
                $src = "$addr/$mask";
            }
            push(@commands,
                pf("-t nat -A POSTROUTING ! -s $src $output " .
                   "-j SNAT --to $addr")
            );
        } elsif (($method eq 'dhcp') or ($method eq 'ppp')) {
            if ( $self->{net}->ifaceIsBridge($if) ) {
                push(@commands,
                    pf("-t nat -A POSTROUTING $output -m physdev" .
                       " ! --physdev-is-bridged -j MASQUERADE")
                );
            }
            else {
                push(@commands,
                    pf("-t nat -A POSTROUTING $output -j MASQUERADE")
                );
            }
        }
    }

    push(@commands, @{$self->_drop()});

    push(@commands, @{$self->_log()});

    push(@commands, @{$self->_iexternal()});

    push(@commands, @{$self->_iglobal()});

    push(@commands, pf("-A ftoexternalonly -j fdrop"));

    my $rules = $self->{firewall}->OutputRules();
    foreach my $rule (@{$rules}) {
        defined($rule) or next;
        my $port = $rule->{port};
        my $proto = $rule->{protocol};
        push(@commands,
                pf("-A ointernal $statenew -p $proto --dport $port -j ACCEPT")
            );
    }

    push(@commands, @{$self->_fglobal()});

    push(@commands, @{$self->_ffwdrules()});

    push(@commands, @{$self->_oglobal()});

    push(@commands, @{$self->_localRedirects()});

    push(@commands, @{_startIPForward()});

    push(@commands, @{_setKernelParameters()});

    EBox::Sudo::root(@commands);

    # Create rules by modules firewall helpers
    $self->_executeModuleRules();
}

# Method: moduleRules
#
#       Get the rules added by the Zentyal modules through FirewallObserver
#
# Returns:
#
#      Reference to array of hashrefs { module, priority, rule }
#
sub moduleRules
{
    my ($self) = @_;

    my $global = EBox::Global->getInstance();
    my @modNames = @{$global->modNames};
    my @mods = @{$global->modInstancesOfType('EBox::FirewallObserver')};
    my @modRules;
    foreach my $mod (@mods) {
        my $helper = $mod->firewallHelper();
        ($helper) or next;

        # add rules
        push(@modRules, @{$self->_modRules($mod, $helper)});
    }

    return \@modRules;
}

sub _loadIptModules
{
    my @commands;
    foreach my $module (IPT_MODULES) {
        push(@commands, "modprobe $module || true");
    }
    return \@commands;
}


# Execute firewall helper rules for each module
sub _executeModuleRules
{
    my ($self) = @_;

    my $global = EBox::Global->getInstance();
    my $model = $self->{firewall}->{'EBoxServicesRuleTable'};
    my %enabledRules =
        map { $model->row($_)->valueByName('rule') => 1 } @{$model->enabledRows()};

    my @mods = @{$global->modInstancesOfType('EBox::FirewallObserver')};
    my @failedMods;
    foreach my $mod (@mods) {
        my $helper = $mod->firewallHelper();
        ($helper) or next;

        my $modRules = $self->_modRules($mod, $helper);

        my @sortedRules = sort { $a->{'priority'} <=> $b->{'priority'} } @{$modRules};
        my @commands = map { my $r = $_->{'rule'}; pf($r) if $enabledRules{$r} } @sortedRules;

        try {
            EBox::Sudo::root(@commands);
        } otherwise {
            EBox::error('Error executing firewall rules for module ' . $mod->name());
            push(@failedMods, $mod->name());
        };
    }

    if (@failedMods) {
        my $message = __('Firewall failed to add rules for the following modules: ');
        $message .= join(', ', @failedMods) . '. ';

        $message .= __('Probably this is caused by a lack of connectivity, ' .
                       'check your configuration or disable those modules');
        $global->addSaveMessage($message);
    }
}

# Helper rules for one module
sub _modRules
{
    my ($self, $mod, $helper) = @_;
    my @modRules;

    push(@modRules, @{$self->_createChains($mod, $helper)});

    push(@modRules,
            @{$self->_doRuleset($mod, 'nat', 'premodules', $helper->prerouting())}
        );
    push(@modRules,
            @{$self->_doRuleset($mod, 'nat', 'postmodules', $helper->postrouting())}
        );
    push(@modRules,
            @{$self->_doRuleset($mod, 'filter', 'fnospoofmodules', $helper->forwardNoSpoof())}
        );
    push(@modRules,
            @{$self->_doRuleset($mod, 'filter', 'inospoofmodules', $helper->inputNoSpoof())}
        );
    push(@modRules,
            @{$self->_doRuleset($mod, 'filter', 'fmodules', $helper->forward())}
        );
    push(@modRules,
            @{$self->_doRuleset($mod, 'filter', 'iexternalmodules', $helper->externalInput())}
        );
    push(@modRules,
            @{$self->_doRuleset($mod, 'filter', 'imodules', $helper->input())}
        );
    push(@modRules,
            @{$self->_doRuleset($mod, 'filter', 'omodules', $helper->output())}
        );

    return \@modRules;
}


sub _createChains
{
    my ($self, $module, $helper) = @_;

    my @commands;
    my %chains = %{$helper->chains()};
    foreach my $table ( keys %chains ) {
        my @tchains = @{$chains{$table}};
        foreach my $chain (@tchains) {
            my $pfrule = "-t $table -N $chain";
            my $r = { 'module' => $module, 'priority' => 1, 'rule' => $pfrule };
            push(@commands, $r);
        }
    }
    return \@commands;
}

sub _doRuleset # (module, table, chain, \@rules)
{
    my ($self, $module, $table, $chain, $rules) = @_;

    my @commands;
    foreach my $r (@{$rules}) {
        my $priority = 50;
        my $pfrule;
        my $pfchain = $chain;
        if (ref($r) eq 'HASH') {
            if(defined($r->{'priority'})) {
                $priority = $r->{'priority'};
            }
            if(defined($r->{'chain'})) {
                $pfchain = $r->{'chain'};
            }
            $pfrule = $r->{'rule'};
        } else {
            $pfrule = $r;
        }
        $pfrule = "-t $table -A $pfchain $pfrule";
        my $r = { 'module' => $module, 'priority' => $priority, 'rule' => $pfrule };
        push(@commands, $r);
    }
    return \@commands;
}

# Method: _iexternalCheckInit
#
#	Add checks to iexternalmodules and iexternal to only affect
#	packates coming from external interfaces
sub _iexternalCheckInit
{
    my ($self) = @_;

    my @commands;

    my @internalIfaces = @{$self->{net}->InternalIfaces()};
    foreach my $if (@internalIfaces) {
        $if = $self->{net}->realIface($if);
        my $input = $self->_inputIface($if);

        push(@commands,
            pf("-A iexternalmodules $input -j RETURN"),
            pf("-A iexternal $input -j RETURN"),
        );
    }
    foreach my $if (@{_vpnIfaces()}) {
        my $input = $self->_inputIface($if);

        push(@commands,
            pf("-A iexternalmodules $input -j RETURN"),
            pf("-A iexternal $input -j RETURN"),
        );
    }
    return \@commands;
}

# Method: _iexternal
#
# Add checks to iexternalmodules and iexternal to only affect
# packates coming from external interfaces
sub _iexternal
{
    my ($self) = @_;

    my @commands;

    push (@commands, @{$self->_iexternalCheckInit()});
    my $iptHelper = new EBox::Firewall::IptablesHelper;
    for my $rule (@{$iptHelper->ExternalToEBoxRuleTable()}) {
        push(@commands, pf("$rule"));
    }
    return \@commands;
}

# Method: _iglobal
#
#	Add rules to iglobal, that is the chain to control access
#	from the internal networks to Zentyal
sub _iglobal
{
    my ($self) = @_;

    my @commands;

    my $iptHelper = new EBox::Firewall::IptablesHelper;
    for my $rule (@{$iptHelper->InternalToEBoxRuleTable()}) {
        push(@commands, pf("$rule"));
    }
    return \@commands;
}

# Method: _oglobal
#
#   Add rules to iglobal, that is the chain to control access
#   from Zentyal to external services
sub _oglobal
{
    my ($self) = @_;

    my @commands;

    my $iptHelper = new EBox::Firewall::IptablesHelper;
    for my $rule (@{$iptHelper->EBoxOutputRuleTable()}) {
        push(@commands, pf("$rule"));
    }
    return \@commands;
}


# Method: _fglobal
#
#   Add rules to fglobal, that is the chain to control access
#   from the internal networks to Internet
sub _fglobal
{
    my ($self) = @_;

    my @commands;

    my $iptHelper = new EBox::Firewall::IptablesHelper;
    for my $rule (@{$iptHelper->ToInternetRuleTable()}) {
        push(@commands, pf("$rule"));
    }
    return \@commands;
}

# Method: _ffwdrules
#
#   Add rules to ffwdrules, that is the chain to control access
#   from the external networks to Internet
sub _ffwdrules
{
    my ($self) = @_;

    my @commands;

    my @internalIfaces = @{$self->{net}->InternalIfaces()};
    foreach my $if (@internalIfaces) {
        $if = $self->{net}->realIface($if);
        my $input = $self->_inputIface($if);

        push(@commands, pf("-A ffwdrules $input -j RETURN"));
    }
    my $iptHelper = new EBox::Firewall::IptablesHelper;
    for my $rule (@{$iptHelper->ExternalToInternalRuleTable()}) {
        push(@commands, pf("$rule"));
    }
    return \@commands;
}

# Method: _redirects
#
#	Add redirects rules
sub _redirects
{
    my ($self) = @_;

    my @commands;

    my $iptHelper = new EBox::Firewall::IptablesHelper;
    for my $rule (@{$iptHelper->RedirectsRuleTable()}) {
        push(@commands, pf("$rule"));
    }
    return \@commands;
}

# Method: _drop
#
#	Set up drop chain. Log rule and drop rule
#
sub _drop
{
    my ($self) = @_;

    my @commands;
    push(@commands, pf('-I drop -j DROP'));

    my $logDrops = EBox::Config::configkey('iptables_log_drops');
    defined($logDrops) or $logDrops = 'yes';

    # If logging is disabled or we don't want to log drops, then we are done
    if($self->{firewall}->logging() and ($logDrops eq 'yes')) {

        my $limit = EBox::Config::configkey('iptables_log_limit');
        my $burst = EBox::Config::configkey('iptables_log_burst');

        unless (defined($limit) and $limit =~ /^\d+$/) {
        throw EBox::Exceptions::External(__('You must set the ' .
            'iptables_log_limit variable in the ebox configuration file'));

        }

        unless (defined($burst) and $burst =~ /^\d+$/) {
        throw EBox::Exceptions::External(__('You must set the ' .
            'iptables_log_burst variable in the ebox configuration file'));

        }
        push(@commands,
            pf("-I drop -j LOG -m limit --limit $limit/min " .
            "--limit-burst $burst" .
            ' --log-level ' . SYSLOG_LEVEL .
            ' --log-prefix "ebox-firewall drop "')
        );
    }
    return \@commands;
}

# Method: _log
#
#	Set up log chain. Log rule and return rule
#
sub _log
{
    my ($self) = @_;

    my @commands;
    push(@commands, pf('-I log -j RETURN'));

    # If logging is disabled we are done
    if ($self->{firewall}->logging()) {
        my $limit = EBox::Config::configkey('iptables_log_limit');
        my $burst = EBox::Config::configkey('iptables_log_burst');

        unless (defined($limit) and $limit =~ /^\d+$/) {
        throw EBox::Exceptions::External(__('You must set the ' .
            'iptables_log_limit variable in the ebox configuration file'));

        }

        unless (defined($burst) and $burst =~ /^\d+$/) {
        throw EBox::Exceptions::External(__('You must set the ' .
            'iptables_log_burst variable in the ebox configuration file'));

        }
        push(@commands,
            pf("-I log -j LOG -m limit --limit $limit/min " .
            "--limit-burst $burst" .
            ' --log-level ' . SYSLOG_LEVEL .
            ' --log-prefix "ebox-firewall log "')
        );
    }
    return \@commands;
}

# Method: _outputIface
#
#   Returns iptables rule part for output interface selection
#   Takes into account if the iface is part of a bridge
#
# Parameters:
#
#   Iface - Iface name
#
sub _outputIface # (iface)
{
    my ($self, $iface) = @_;

    if ( $self->{net}->ifaceExists($iface) and
         $self->{net}->ifaceMethod($iface) eq 'bridged' ) {
        return  "-m physdev --physdev-out $iface";
    } else {
        return "-o $iface";
    }
}

# Method: _inputIface
#
#   Returns iptables rule part for input interface selection
#   Takes into account if the iface is part of a bridge
#
# Parameters:
#
#   Iface - Iface name
#
sub _inputIface # (iface)
{
    my ($self, $iface) = @_;

    if ( $self->{net}->ifaceExists($iface) and
         $self->{net}->ifaceMethod($iface) eq 'bridged' ) {
        return  "-m physdev --physdev-in $iface";
    } else {
        return "-i $iface";
    }
}


# Method: _natEnabled
#
#   Fetch value to enable NAT
#
sub _natEnabled
{
    my $nat =  EBox::Config::configkey('nat_enabled');

    return 1 unless (defined($nat));

    if ($nat =~ /no/) {
        return undef;
    } else {
        return 1;
    }
}

# Method: _vpnIfaces
#
#   Fetch vpn interfaces
sub _vpnIfaces
{
    my $gl = EBox::Global->getInstance();
    if ($gl->modExists('openvpn')) {
        my $vpn = $gl->modInstance('openvpn');
        $vpn->initializeInterfaces();
        return [map {$_->iface() } $vpn->activeDaemons()];
    } else {
        return [];
    }
}

1;