#!/usr/bin/perl

=head1 NAME

pfdns - PacketFence DNS server

=head1 SYNOPSIS

pfdns [options]

 Options:
   -d      Daemonize
   -h      Help
   -v      Verbose

=cut

use warnings;
use strict;
use Readonly;
use File::Basename qw(basename);
use Getopt::Std;
use Pod::Usage;
use POSIX qw(:signal_h pause :sys_wait_h SIG_BLOCK SIG_UNBLOCK);
use Try::Tiny;
use Net::DNS::Nameserver;
use NetAddr::IP;
use Net::DNS::Resolver;
use Systemd::Daemon qw{ -soft };

BEGIN {
    # log4perl init
    use constant INSTALL_DIR => '/usr/local/pf';
    use lib INSTALL_DIR . "/lib";
    use pf::log(service => 'pfdns');
}

use pf::config qw(
    %Config
    $IF_ENFORCEMENT_VLAN
    %ConfigNetworks
    $IF_ENFORCEMENT_DNS
    is_type_inline
);
use pf::util;
use pf::db;
use pf::services::util;
use pf::CHI;
use pf::ConfigStore::Interface;
use pf::cluster;
use pf::SwitchFactory;
use pf::node;
use Storable 'dclone';
use pf::access_filter::dns;
use pf::CHI::Request;
use pf::util::dns;
use pf::ipset_cache;

pf::SwitchFactory->preloadConfiguredModules();

# initialization
# --------------
# assign process name (see #1464)

# init signal handlers
our $PROGRAM_NAME = $0 = "pfdns";

my $logger = get_logger( $PROGRAM_NAME );

my %args;
getopts( 'dhi:', \%args );

my $daemonize = $args{d};

pod2usage( -verbose => 1 ) if ( $args{h} );

our $RUNNING = 1;
our $started_successfully = 0;


my @ip_addr;
my $loadb_ip;
 @routed_inline_nets_named;
my @routed_isolation_nets_named;
my @routed_registration_nets_named;
my @routed_dns_enforcement_nets_named;

my $CHI_CACHE = pf::CHI->new( namespace => 'pfdns' );
our $IPSET_SESSION = 'pfsession_passthrough';
our $IPSET_ISOL_SESSION = 'pfsession_isol_passthrough';

Readonly::Scalar our $TTL                => '15';
Readonly::Scalar our $HTTPS_PORT         => '443';
Readonly::Scalar our $HTTP_PORT         => '80';

my $cs = pf::ConfigStore::Interface->new;
foreach my $interface ( @{$cs->readAllIds} ) {
    my $full_interface = "interface $interface";
    my $ip = $Config{$full_interface}{'vip'} || $Config{$full_interface}{'ip'};
    if (
        defined ($Config{$full_interface}{'enforcement'}) &&
        (
          ($Config{$full_interface}{'enforcement'} eq $IF_ENFORCEMENT_VLAN)
          || ($Config{$full_interface}{'enforcement'} eq $IF_ENFORCEMENT_DNS)
          || is_type_inline($Config{$full_interface}{'enforcement'})
        )
    ){
        # if cluster is enabled we return the VIP when queried on the server interface
        # we also listen on the VIP in case it's needed
        if ($cluster_enabled){
            $loadb_ip->{$ip} = pf::cluster::cluster_ip($interface);
            push @ip_addr, pf::cluster::cluster_ip($interface);
        }
        push @ip_addr, $ip;
    }
}

foreach my $network ( keys %ConfigNetworks ) {
    if ( $ConfigNetworks{$network}{'named'} eq 'enabled' ) {
        if ( pf::config::is_network_type_inline($network) ) {
            my $inline_obj = NetAddr::IP->new( $network, $ConfigNetworks{$network}{'netmask'} );
            push @routed_inline_nets_named, $inline_obj;
            if (defined($ConfigNetworks{$network}{'reg_network'}) && $ConfigNetworks{$network}{'reg_network'} ne "") {
                $inline_obj = NetAddr::IP->new( $ConfigNetworks{$network}{'reg_network'} );
                push @routed_inline_nets_named, $inline_obj;
            }
        } elsif ( pf::config::is_network_type_vlan_isol($network) ) {
            my $isolation_obj = NetAddr::IP->new( $network, $ConfigNetworks{$network}{'netmask'} );
            push @routed_isolation_nets_named, $isolation_obj;
        } elsif ( pf::config::is_network_type_vlan_reg($network) ) {
            my $registration_obj = NetAddr::IP->new( $network, $ConfigNetworks{$network}{'netmask'} );
            push @routed_registration_nets_named, $registration_obj;
        } elsif ( pf::config::is_network_type_dns_enforcement($network) ) {
            my $dns_enforcement_obj = NetAddr::IP->new( $network, $ConfigNetworks{$network}{'netmask'} );
            push @routed_dns_enforcement_nets_named, $dns_enforcement_obj;
        }
    }
}

tie our %domain_dns_servers, 'pfconfig::cached_hash', 'resource::domain_dns_servers';

my %CHILDREN;
my $IS_CHILD = 0;
my $CHILDREN_TO_START = $Config{advanced}{pfdns_processes};
our @WORKERS = (1 .. $CHILDREN_TO_START);
our $ALARM_RECV = 0;

our $IPSET_CACHE = pf::ipset_cache->new({setname => $IPSET_SESSION});
our $IPSET_ISOL_CACHE = pf::ipset_cache->new({setname => $IPSET_ISOL_SESSION});

#Load the ipset cache before setting up the signals to avoid the child handler being called
$IPSET_CACHE->populate_cache();
$IPSET_ISOL_CACHE->populate_cache();

$SIG{HUP} = \&normal_sighandler;
$SIG{INT} = \&normal_sighandler;
$SIG{TERM} = \&normal_sighandler;
$SIG{CHLD} = \&child_sighandler;
$SIG{ALRM} = \&alarm_sighandler;


sub start_workers {
    my $mask = POSIX::SigSet->new(POSIX::SIGCHLD());
    sigprocmask(SIG_BLOCK,$mask);
    while(@WORKERS) {
        my $worker = shift @WORKERS;
        run_worker($worker);
    }
    sigprocmask(SIG_UNBLOCK,$mask);
}

sub run_worker {
    my ($id) = @_;
    db_disconnect();
    my $pid = fork();
    if($pid) {
        $CHILDREN{$pid} = $id;
    } elsif ($pid == 0) {
        $SIG{CHLD} = "DEFAULT";
        $IS_CHILD = 1;
        eval {
            _run_worker($id);
        };
        if ($@) {
            $logger->error($@);
        }
        $logger->trace(sub { "$$ shutting down" });
        POSIX::_exit(0);
    }
}

my $ns = new Net::DNS::Nameserver(
    LocalAddr       => [@ip_addr],
    LocalPort    => 53,
    ReplyHandler => \&response_handler,
    Verbose      => 0
    ) || die "couldn't create nameserver object\n";


# standard signals and daemonize
daemonize($PROGRAM_NAME) if ($daemonize);
our $PARENT_PID = $$;
$started_successfully = 1;
Systemd::Daemon::notify( READY => 1, STATUS => "Ready", unset => 1 );

sub _run_worker {
    my ($id) = @_;
    $0 = "$0 - $id";
    while($RUNNING && is_parent_alive()) {
        $ns->loop_once(10);
    }
}

END {
    if ( !$args{h} ) {
        if(!$IS_CHILD && $started_successfully) {
            Systemd::Daemon::notify( STOPPING => 1 );
            deletepid("pfdns");
            $logger->info("stopping pfdns");
        }
    }
}

sub response_handler {
    my ($qname, $qclass, $qtype, $peerhost,$query,$conn) = @_;
    pf::CHI::Request::clear_all();
    my $ip = new NetAddr::IP::Lite clean_ip($peerhost);
    my $ip_addr = $ip->addr;
    $logger->trace(sub { "Process $0 handling request for IP : $ip_addr" });

    my $args = {
        qname => $qname,
        qclass => $qclass,
        qtype => $qtype,
        peerhost => $peerhost,
        query => $query,
        conn => $conn,
    };

    foreach my $network (@routed_registration_nets_named) {
        if ($network->contains($ip)) {
            return regzone($qname, $qclass, $qtype, $peerhost, $query, $conn, 'registration', $args);
        }
    }
    foreach my $network (@routed_isolation_nets_named) {
        if ($network->contains($ip)) {
           # Should be different for isolation network.
           my @reply = filtered_results('isolation', $args);
           return @reply if (scalar(@reply) > 1);
           return  isolzone($qname, $qclass, $qtype, $peerhost,$query,$conn);
        }
    }

    foreach my $network (@routed_inline_nets_named) {
        if ($network->contains($ip)) {
            my $mac = pf::ip4log::ip2mac($ip_addr);

            unless($mac){
                $logger->warn("Can't lookup IP $ip_addr to a MAC address. Returning result as if unreg.");
                return regzone($qname, $qclass, $qtype, $peerhost, $query, $conn, 'dnsenforcement', $args);
            }
            require pf::violation;
            my $top_violation = pf::violation::violation_view_top($mac);
            if (defined($top_violation)) {
                return isolzone($qname, $qclass, $qtype, $peerhost, $query, $conn, 'inline', $args);
            } else {
                return regzone($qname, $qclass, $qtype, $peerhost, $query, $conn, 'inline', $args);
            }
        }
    }

    foreach my $network (@routed_dns_enforcement_nets_named) {
        if ($network->contains($ip)) {
            $logger->trace("Performing DNS enforcement on $ip");
            my $mac = pf::ip4log::ip2mac($ip_addr);

            unless($mac){
                $logger->warn("Can't lookup IP $ip_addr to a MAC address. Returning result as if unreg.");
                return regzone($qname, $qclass, $qtype, $peerhost, $query, $conn, 'dnsenforcement', $args);
            }

            my $node = node_attributes($mac);
            if($node->{status} eq $STATUS_REGISTERED){
                $logger->info("Node is registered, returning resolved domain.");
                return resolve($qname, $qclass, $qtype, $peerhost, $query, $conn);
            }
            else {
                $logger->info("Node is unregistered, returning portal domain.");
                return regzone($qname, $qclass, $qtype, $peerhost, $query, $conn, 'dnsenforcement', $args);
            }
        }
    }

    $logger->debug("$ip_addr did not match any known networks. Not responding to DNS request.");
}

=head2 resolve

Resolve a domain using the operating system configured DNS servers and return it as an answer

=cut

sub resolve {
    my ($qname, $qclass, $qtype, $peerhost,$query,$conn) = @_;
    my ($rcode, @ans, @auth, @add);

    my ($ttl, $rdata);
    $logger->debug("Query for public domain ($qtype) : $qname");
    my $reply = resolve_with_cache($qtype, $qname);

    $rcode = "NXDOMAIN";
    if ($qname && $qname eq $Config{'general'}{'hostname'}.".".$Config{'general'}{'domain'}) {
        my ($ttl, $rdata) = ($TTL, $conn->{sockhost});
        my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
        push @ans, $rr;
        $rcode = "NOERROR";
    }
    elsif ($reply) {
        $rcode = "NOERROR";
        push @ans, $reply->answer;
    }
    # mark the answer as authoritive (by setting the 'aa' flag
    my @answer = ($rcode, \@ans, \@auth, \@add, { aa => 1 });
    return @answer;
}

=head2 regzone

Resolve a DNS entry for a client that should see the captive portal

=cut

sub regzone {
    my ($qname, $qclass, $qtype, $peerhost, $query, $conn, $filter_type, $args) = @_;
    my ($rcode, @ans, @auth, @add);

    $logger->trace("Requested Domain: ".$qname);
    my $results = non_filtered($qname, $qclass, $qtype, $peerhost, $query, $conn, "passthroughs");
    if ($results) {
        my @answer = ($results->{rcode}, $results->{ans}, \@auth, \@add, { aa => 1 });
        $logger->trace(sub { use Data::Dumper; "Response : ".Dumper(\@answer) });
        return @answer;
    }

    if ($filter_type) {
        my @reply = filtered_results($filter_type, $args);
        return @reply if @reply > 1;
    }

    if ($qtype eq "A") {
        if ($qname eq $Config{'general'}{'hostname'}.".".$Config{'general'}{'domain'}) {
            my ($ttl, $rdata) = ($TTL, (defined($loadb_ip->{$conn->{sockhost}})) ? $loadb_ip->{$conn->{sockhost}} : $conn->{sockhost});
            my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
            push @ans, $rr;
            $rcode = "NOERROR";
        } else {
            my ($ttl, $rdata) = ($TTL, $Config{'general'}{'hostname'}.".".$Config{'general'}{'domain'}.".");
            my $rr = new Net::DNS::RR("$qname $ttl IN CNAME $rdata");
            my $rdata2 = (defined($loadb_ip->{$conn->{sockhost}})) ? $loadb_ip->{$conn->{sockhost}} : $conn->{sockhost};
            my $rr2 = new Net::DNS::RR("$rdata $ttl $qclass $qtype $rdata2");
            push @ans, $rr;
            push @ans, $rr2;
            $rcode = "NOERROR";
        }
    } elsif ($qtype eq "NS") {
        my $rr = new Net::DNS::RR(
            name    => $Config{'general'}{'domain'},
            type    => 'NS',
            nsdname => $Config{'general'}{'hostname'}.".".$Config{'general'}{'domain'},
        );
        push @ans, $rr;
        $rcode = "NOERROR";
    } elsif ($qtype eq "SRV") {
        #Handle SRV record to be able to contact Active Directory in the reg vlan
        $rcode = "NXDOMAIN";
        my @ip_port_pairs;
        foreach my $key ( keys %domain_dns_servers ) {
            if ($qname =~ /(.*)_msdcs.$key/i) {
                my $resolver = new Net::DNS::Resolver(nameservers => $domain_dns_servers{$key});
                my $reply = $resolver->search($qname, $qtype);
                next if !defined($reply);
                my @answers = $reply->answer;
                foreach my $answer (@answers) {
                    my $target_labels = $answer->{target}->{label};
                    my $target = join('.', @$target_labels);
                    if (!defined $target) {
                        $logger->warn("Invalid target for answer");
                        next;
                    }
                    my $query = $CHI_CACHE->compute("srv-$target", sub { $resolver->search($target, 'A') });
                    if ($query) {
                        my $port = $answer->port;
                        if ($qname =~ /\._udp\./) {
                            $port = "udp:$port";
                        }
                        get_logger->info("Resolved $qname as an Active Directory domain name. Adding passthroughs into ipset.");
                        push @ip_port_pairs,
                          format_query_to_ip_port(
                            $query, $port, 'udp:88',   'udp:123', 'udp:135', '135',
                            'udp:137', 'udp:138',     '139',      'udp:389', 'udp:445', '445',
                            'udp:464', '464',         'tcp:1025', '49155',   '49156',   '49172'
                          );
                    }
                }
                $rcode = "NOERROR";
                push @ans, @answers;
            }
        }
        $IPSET_CACHE->add_pairs(\@ip_port_pairs);
    } else{
        $rcode = "NXDOMAIN";
    }

    # mark the answer as authoritive (by setting the 'aa' flag
    my @answer = ($rcode, \@ans, \@auth, \@add, { aa => 1 });
    $logger->trace(sub { use Data::Dumper; "Response : ".Dumper(\@answer) });
    return @answer;
}

sub format_query_to_ip_port {
    my ($query, @ports) = @_;
    my @pairs;

    foreach my $rr ($query->answer) {
        next unless $rr->type eq "A";
        my $ip = $rr->address;
        foreach my $port (@ports) {
            push @pairs, {ip => $ip, port => $port};
        }
    }
    return @pairs;
}

=head2 non_filtered

Non filtered registration/isolation zone answered

=cut

sub non_filtered {
    my ($qname, $qclass, $qtype, $peerhost, $query, $conn,$zone) = @_;
    my ($matches_passthrough, $ports) = pf::util::dns::matches_passthrough($qname,$zone);
    #Exit early if it does not match
    return unless($qtype eq 'A' && (isenabled($Config{fencing}{passthrough}) || isenabled($Config{fencing}{isolation_passthrough}) ) && $matches_passthrough);
    my @ans;
    my %results = (
        ans   => \@ans,
        rcode => "NXDOMAIN",
    );
    my ($ttl, $rdata);
    my $res = Net::DNS::Resolver->new;
    my $query_non_filtered = resolve_with_cache("A", $qname);
    my @ip_port_pairs;
    if ($query_non_filtered) {
        push @ip_port_pairs, format_query_to_ip_port($query_non_filtered, $HTTP_PORT, $HTTPS_PORT);
        push @ans, $query_non_filtered->answer;
        if (@ans) {
            $results{rcode} = "NOERROR";
        }
        else {
            $logger->warn("Unresolved passthrough domain $qname");
        }
    }
    if ($zone eq "passthroughs") {
        $IPSET_CACHE->add_pairs(\@ip_port_pairs);
    } else {
        $IPSET_ISOL_CACHE->add_pairs(\@ip_port_pairs);
    }
    return \%results;
}

=head2 isolzone

Resolve a DNS name for a client in isolation (no passthroughs, just returns the captive portal records)

=cut

sub isolzone {
    my ($qname, $qclass, $qtype, $peerhost,$query,$conn) = @_;
    my ($rcode, @ans, @auth, @add);
    my $_EXIT_CODE_EXISTS = "1";

    $logger->trace("Requested Domain: ".$qname);
    my $results = non_filtered($qname, $qclass, $qtype, $peerhost, $query, $conn, "isolation_passthroughs");
    if ($results) {
        my @answer = ($results->{rcode}, $results->{ans}, \@auth, \@add, { aa => 1 });
        $logger->trace(sub { use Data::Dumper; "Response : ".Dumper(\@answer) });
        return @answer;
    }
    if ($qtype eq "A") {
        my $ttl = $TTL;
        my $rdata = (defined($loadb_ip->{$conn->{sockhost}})) ? $loadb_ip->{$conn->{sockhost}} : $conn->{sockhost};
        my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
        push @ans, $rr;
        $rcode = "NOERROR";
    } elsif ($qtype eq "NS") {
        my $rr = new Net::DNS::RR(
            name    => $Config{'general'}{'domain'},
            type    => 'NS',
            nsdname => $Config{'general'}{'hostname'}.".".$Config{'general'}{'domain'},
        );
        push @ans, $rr;
        $rcode = "NOERROR";
    } else{
        $rcode = "NXDOMAIN";
    }

    # mark the answer as authoritive (by setting the 'aa' flag
    return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
}

sub normal_sighandler {
    $logger->debug( "pfdns: caught SIG" . $_[0] . " - terminating" );
    $RUNNING = 0;
}

=head2 resolve_with_cache

Resolve a DNS name using the cache
This makes sure the domain name TTL is honored

=cut

sub resolve_with_cache {
    my ($qtype, $qname) = @_;

    my $cache_key = "resolve-$qtype-$qname";

    my $res   = Net::DNS::Resolver->new;
    my $encoded_reply = $CHI_CACHE->get($cache_key);

    my $reply;
    if($encoded_reply) {
        $reply = decode Net::DNS::Packet(\$encoded_reply);
    }

    unless($reply){
        $reply = $res->search($qname, $qtype);
        return unless($reply);
        # We need to clone the reply since accessing the answers modifies the object and makes it invalid after its deserialized from the cache the second time
        my $cloned_reply = dclone($reply);
        my @answers = $cloned_reply->answer;
        if($reply){
            $CHI_CACHE->set($cache_key, $reply->encode, $answers[0]->ttl);
        }
    }
    return $reply;
}

sub is_parent_alive {
    kill (0,$PARENT_PID)
}

=head2 cleanup

cleans after children

=cut

sub cleanup {
    kill_and_wait_for_children('INT',30);
    signal_children('KILL');
}

=head2 kill_and_wait_for_children

signal children and waits for them to exit process

=cut

sub kill_and_wait_for_children {
    my ($signal,$waittime) = @_;
    signal_children($signal);
    $ALARM_RECV = 0;
    alarm $waittime;
    while (((keys %CHILDREN) != 0 ) && !$ALARM_RECV) {
        pause;
    }
}

=head2 signal_children

sends a signal to all active children

=cut

sub signal_children {
    my ($signal) = @_;
    kill ( $signal, keys %CHILDREN);
}

=head2 child_sighandler

reaps the children

=cut

sub child_sighandler {
    local ($!, $?);
    while(1) {
        my $child = waitpid(-1, WNOHANG);
        last unless $child > 0;
        my $worker = delete $CHILDREN{$child};
        if (defined $worker) {
            push @WORKERS, $worker;
        }
    }
}

=head2 alarm_sighandler

the alarm signal handler

=cut

sub alarm_sighandler {
    $ALARM_RECV = 1;
}


while($RUNNING){
    start_workers();
    pause unless @WORKERS;
}

=head2 filtered_results

filtered_results

=cut

sub filtered_results {
    my ($scope, @args) = @_;
    my $filter = pf::access_filter::dns->new;
    my $reply = $filter->filter($scope, @args);
    if (!defined $reply) {
        return undef;
    }
    my $rr = new Net::DNS::RR($reply->{answer});
    my @ans;
    push @ans, $rr;
    return ($reply->{'rcode'},\@ans,[],[], {aa => 1});
}


cleanup();

=head1 COPYRIGHT

Copyright (C) 2005-2017 Inverse inc.

=head1 LICENSE

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.

=cut
