示例#1
0
        self._ip_range = netaddr.IPNetwork(kwargs['cidr_range'])


class SourceIPRule(IPRangeRule):
    """Filter IP packets based on source address"""

    def __init__(self, **kwargs):
        """Takes single argument, 'cidr_range', passed to super."""
        IPRangeRule.__init__(self, **kwargs)

    def filter_condition(self, pywall_packet):
        """
        Filter packets if their source address falls within the ip_range.
        """
        return pywall_packet.get_src_ip() in self._ip_range


class DestinationIPRule(IPRangeRule):
    """Filter IP packets based on destination address"""

    def __init__(self, **kwargs):
        """Takes single argument, 'cidr_range', passed to super."""
        IPRangeRule.__init__(self, **kwargs)

    def filter_condition(self, pywall_packet):
        """True if destination address falls within the ip_range."""
        return pywall_packet.get_dst_ip() in self._ip_range

register(SourceIPRule)
register(DestinationIPRule)
示例#2
0
            raise ValueError('Invalid source port range')
        elif not self._is_port_range_valid(self._dst_lo, self._dst_hi):
            raise ValueError('Invalid destination port range')

    def _is_port_range_valid(self, port_lo, port_hi):
        """Return true if a port range is valid."""
        valid = (port_hi is None and port_lo is None) or \
                (port_hi is not None and port_lo is not None)
        valid = valid and (port_lo <= port_hi)
        return valid

    def filter_condition(self, packet):
        """Condition to jump to action chain."""
        match = (packet.get_payload() is not None)
        match = match and (packet.get_protocol() == self._protocol)
        match = match and (
            (self._src_range == (None, None)) or
            (self._src_lo <= packet.get_payload().get_src_port() <=
             self._src_hi))
        match = match and (
            (self._dst_range == (None, None)) or
            (self._dst_lo <= packet.get_payload().get_dst_port() <=
             self._dst_hi))
        if match:
            print('PortRangeRule: %s' % str(self._action))
        return match


register(PortRule)
register(PortRangeRule)
示例#3
0
        SimpleRule.__init__(self, **kwargs)
        self._ip_range = netaddr.IPNetwork(kwargs['cidr_range'])


class SourceIPRule(IPRangeRule):
    """Filter IP packets based on source address"""
    def __init__(self, **kwargs):
        """Takes single argument, 'cidr_range', passed to super."""
        IPRangeRule.__init__(self, **kwargs)

    def filter_condition(self, pywall_packet):
        """
        Filter packets if their source address falls within the ip_range.
        """
        return pywall_packet.get_src_ip() in self._ip_range


class DestinationIPRule(IPRangeRule):
    """Filter IP packets based on destination address"""
    def __init__(self, **kwargs):
        """Takes single argument, 'cidr_range', passed to super."""
        IPRangeRule.__init__(self, **kwargs)

    def filter_condition(self, pywall_packet):
        """True if destination address falls within the ip_range."""
        return pywall_packet.get_dst_ip() in self._ip_range


register(SourceIPRule)
register(DestinationIPRule)
示例#4
0
        self.match_if = set(kwargs.get('match_if', []))
        self.match_if_not = set(kwargs.get('match_if_not', []))
        if self.match_if and self.match_if_not:
            raise ValueError('You may only provide one of "match_if" and'
                             ' "match_if_not".')
        if not self.match_if and not self.match_if_not:
            raise ValueError('You must provide one of "match_if" and'
                             ' "match_if_not".')

    def add_connection(self, pywall_packet):
        """
        Add a connection to the Rule. Connections are represented as the TCP
        4-tuple. See the TCPPacket class for more info.
        """
        self._existing_connections.add(pywall_packet.to_tuple())

    def filter_condition(self, pywall_packet):
        if not TCPRule.filter_condition(self, pywall_packet):
            return False
        pipe = get_pipe()
        pipe.send(to_tuple(pywall_packet))
        state = pipe.recv()
        if self.match_if:
            return state in self.match_if
        else:
            return state not in self.match_if_not


register(TCPRule)
register(TCPStateRule)
示例#5
0
        # Create a source IP rule.
        source_args = kwargs.copy()
        source_ip = source_args.pop('src_ip', None)
        if source_ip:
            source_args['cidr_range'] = source_ip
            self.ip_src_rule = SourceIPRule(**source_args)
        else:
            self.ip_src_rule = None

        # Create a dest IP rule.
        dest_args = kwargs.copy()
        dest_ip = dest_args.pop('dst_ip', None)
        if dest_ip:
            dest_args['cidr_range'] = dest_ip
            self.ip_dst_rule = DestinationIPRule(**dest_args)
        else:
            self.ip_dst_rule = None

    def filter_condition(self, packet):
        """Condition to filter on."""
        res = self.port_rule.filter_condition(packet)
        if self.ip_src_rule:
            res = res and self.ip_src_rule.filter_condition(packet)
        if self.ip_dst_rule:
            res = res and self.ip_dst_rule.filter_condition(packet)
        return res


register(IPPortRule)
示例#6
0
        self.port_rule = PortRangeRule(**kwargs)

        # Create a source IP rule.
        source_args = kwargs.copy()
        source_ip = source_args.pop('src_ip', None)
        if source_ip:
            source_args['cidr_range'] = source_ip
            self.ip_src_rule = SourceIPRule(**source_args)
        else:
            self.ip_src_rule = None

        # Create a dest IP rule.
        dest_args = kwargs.copy()
        dest_ip = dest_args.pop('dst_ip', None)
        if dest_ip:
            dest_args['cidr_range'] = dest_ip
            self.ip_dst_rule = DestinationIPRule(**dest_args)
        else:
            self.ip_dst_rule = None

    def filter_condition(self, packet):
        """Condition to filter on."""
        res = self.port_rule.filter_condition(packet)
        if self.ip_src_rule:
            res = res and self.ip_src_rule.filter_condition(packet)
        if self.ip_dst_rule:
            res = res and self.ip_dst_rule.filter_condition(packet)
        return res

register(IPPortRule)
示例#7
0
        # clear if we have timed out
        if last_activity + timedelta(seconds=self._timeout) < datetime.now():
            print('PortKnocking: timeout -- fall through: %s' % (src_ip))
            del self._activity[src_ip]
            i, last_activity = act_def

        if i >= len(self._doors):
            if (self._protocol == pywall_packet.get_protocol() and
                    self._port == payload.get_dst_port()):
                print('PortKnocking: accepting from %s' % (src_ip))
                return 'ACCEPT'
            else:
                print('PortKnocking: fall through from recognized ip: %s' %
                      (src_ip))
                return False
        else:
            cur_proto, cur_port = self._doors[i]
            if (cur_proto == pywall_packet.get_protocol() and
                    cur_port == payload.get_dst_port() and
                    self._src_port == payload.get_src_port()):
                i += 1
                self._activity[src_ip] = (i, datetime.now())
                print('PortKnocking: advance to %d' % i)
                return 'DROP'
            else:
                print('PortKnocking: unrecognized -- fall-through')
                return False


register(PortKnocking)
示例#8
0
        self.match_if = set(kwargs.get('match_if', []))
        self.match_if_not = set(kwargs.get('match_if_not', []))
        if self.match_if and self.match_if_not:
            raise ValueError('You may only provide one of "match_if" and'
                             ' "match_if_not".')
        if not self.match_if and not self.match_if_not:
            raise ValueError('You must provide one of "match_if" and'
                             ' "match_if_not".')

    def add_connection(self, pywall_packet):
        """
        Add a connection to the Rule. Connections are represented as the TCP
        4-tuple. See the TCPPacket class for more info.
        """
        self._existing_connections.add(pywall_packet.to_tuple())

    def filter_condition(self, pywall_packet):
        if not TCPRule.filter_condition(self, pywall_packet):
            return False
        pipe = get_pipe()
        pipe.send(to_tuple(pywall_packet))
        state = pipe.recv()
        if self.match_if:
            return state in self.match_if
        else:
            return state not in self.match_if_not


register(TCPRule)
register(TCPStateRule)
示例#9
0
"""Printout rule for PyWall."""

from __future__ import print_function
from rules import register, SimpleRule


class PrintRule(SimpleRule):
    """Rule that just prints the socket and its payload.

    This is mostly irrelevent now that logging is enabled.

    """

    def filter_condition(self, pywall_packet):
        """Prints out packet information at the IP level."""
        print(unicode(pywall_packet))
        print(unicode(pywall_packet.get_payload()))
        # Action should not be applied. Ever.
        return False


register(PrintRule)
示例#10
0
        # clear if we have timed out
        if last_activity + timedelta(seconds=self._timeout) < datetime.now():
            print('PortKnocking: timeout -- fall through: %s' % (src_ip))
            del self._activity[src_ip]
            i, last_activity = act_def

        if i >= len(self._doors):
            if (self._protocol == pywall_packet.get_protocol()
                    and self._port == payload.get_dst_port()):
                print('PortKnocking: accepting from %s' % (src_ip))
                return 'ACCEPT'
            else:
                print('PortKnocking: fall through from recognized ip: %s' %
                      (src_ip))
                return False
        else:
            cur_proto, cur_port = self._doors[i]
            if (cur_proto == pywall_packet.get_protocol()
                    and cur_port == payload.get_dst_port()
                    and self._src_port == payload.get_src_port()):
                i += 1
                self._activity[src_ip] = (i, datetime.now())
                print('PortKnocking: advance to %d' % i)
                return 'DROP'
            else:
                print('PortKnocking: unrecognized -- fall-through')
                return False


register(PortKnocking)
示例#11
0
"""Rule that is always true."""
from rules import register, SimpleRule


class TrueRule(SimpleRule):
    """Rule that is always true."""

    def filter_condition(self, pckt):
        return True

register(TrueRule)
示例#12
0
"""Rule that is always true."""
from rules import register, SimpleRule


class TrueRule(SimpleRule):
    """Rule that is always true."""
    def filter_condition(self, pckt):
        return True


register(TrueRule)