Esempio n. 1
0
        def parsePorts(port_list):
            """
            <method internal="yes">
            Helper function to convert a port or port
            range list to a list of port ranges. Accepted
            input formats are:

            (port1, port2, port3) - list of ports
            (port1, (begin, end), port3) - list of ports mixed with ranges
            </method>
            """
            ports = []
            port_list = makeSequence(port_list)

            for item in port_list:
                if isinstance(item, PortRange):
                    ports.append(item.getTuple())
                else:
                    if isinstance(item, basestring):
                        item = int(item)

                    if not isinstance(item, int):
                        raise ValueError, "Integer port value expected; value='%s'" % (
                            item, )

                    ports.append((item, item))

            return ports
Esempio n. 2
0
File: Rule.py Progetto: Balasys/zorp
        def parsePorts(port_list):
            """
            <method internal="yes">
            Helper function to convert a port or port
            range list to a list of port ranges. Accepted
            input formats are:

            (port1, port2, port3) - list of ports
            (port1, (begin, end), port3) - list of ports mixed with ranges
            </method>
            """
            ports = []
            port_list = makeSequence(port_list)

            for item in port_list:
                if isinstance(item, PortRange):
                    ports.append(item.getTuple())
                else:
                    if isinstance(item, basestring):
                        item = int(item)

                    if not isinstance(item, int):
                        raise ValueError, "Integer port value expected; value='%s'" % (item,)

                    ports.append((item, item))

            return ports
Esempio n. 3
0
        def parseSubnets(subnet_list):
            """
            <method internal="yes">
            Helper function to convert a string-based
            subnet list to two tuples consisting of
            InetSubnet and InetSubnet6 instances.
            </method>
            """
            import socket
            subnets = {socket.AF_INET: [], socket.AF_INET6: []}

            subnet_list = makeSequence(subnet_list)

            for item in subnet_list:
                if isinstance(item, basestring):
                    subnet = Subnet.create(item)
                elif isinstance(item, Subnet):
                    subnet = item
                else:
                    raise ValueError, "Invalid subnet specification: value='%s'" % (
                        item, )

                subnets[subnet.get_family()].append(
                    (subnet.addr_packed(), subnet.netmask_packed()))

            return (tuple(subnets[socket.AF_INET]),
                    tuple(subnets[socket.AF_INET6]))
Esempio n. 4
0
                def resolveZones(name_list):
                        """
                        Helper function to convert a list of zone
                        names to a list of Zone instnaces
                        """
                        name_list = makeSequence(name_list)

                        for name in name_list:
                                if Zone.lookup_by_name(name) == None:
                                        raise ValueError, "No zone was defined with that name; zone='%s'" % (name,)
Esempio n. 5
0
        def resolveZones(name_list):
            """
            <method internal="yes">
            Helper function to convert a list of zone
            names to a list of Zone instnaces
            </method>
            """
            name_list = makeSequence(name_list)

            for name in name_list:
                if Zone.lookupByName(name) == None:
                    raise ValueError, "No zone was defined with that name; zone='%s'" % (name,)
Esempio n. 6
0
        def CreateRealRule(parameters):
            """
            <method internal="yes">
            Helper function to create rules
            </method>
            """

            # store service
            service_name = parameters.pop('service', None)
            self._service = Globals.services.get(service_name, None)
            if not self._service:
                raise ValueError, "No valid service was specified for the rule; service='%s'" % (
                    service_name, )

            # convert and check special dimensions: subnets, ports and zones at the moment

            for ip_keyword in ['src_subnet', 'dst_subnet']:
                ipv6_keyword = ip_keyword + '6'
                # forbid usage of ipv6 related keywords:
                if ipv6_keyword in parameters:
                    raise ValueError, "Invalid dimension specification '%s'" % ipv6_keyword
                (parameters[ip_keyword],
                 parameters[ipv6_keyword]) = parseSubnets(
                     parameters.get(ip_keyword, []))

            parameters['src_ifgroup'] = parseGroups(
                parameters.get('src_ifgroup', []))
            parameters['dst_ifgroup'] = parseGroups(
                parameters.get('dst_ifgroup', []))
            parameters['src_port'] = parsePorts(parameters.get('src_port', []))
            parameters['dst_port'] = parsePorts(parameters.get('dst_port', []))
            resolveZones(parameters.get('src_zone', []))
            resolveZones(parameters.get('dst_zone', []))

            # store values specified
            self._dimensions = {}
            for key, value in parameters.items():
                if key not in self.valid_dim_names:
                    if key in self.dimension_aliases:
                        key = self.dimension_aliases[key]
                    else:
                        raise ValueError, "Unknown dimension '%s'" % (key, )

                self._dimensions.setdefault(key,
                                            []).extend(makeSequence(value))

            Dispatch.RuleDispatcher.createOneInstance()
Esempio n. 7
0
File: Rule.py Progetto: Balasys/zorp
        def parseGroups(group_list):
            groups = []
            group_list = makeSequence(group_list)

            for item in group_list:
                if isinstance(item, int):
                    groups.append(item)
                elif isinstance(item, basestring):
                    try:
                        item = int(item)
                    except ValueError:
                        if item not in self.iface_group_aliases:
                            raise ValueError, "Valid group name expected; value='%s' %s" % (item, str(self.iface_group_aliases))
                        item = self.iface_group_aliases[item]

                    groups.append(item)

            return groups
Esempio n. 8
0
        def parseGroups(group_list):
            groups = []
            group_list = makeSequence(group_list)

            for item in group_list:
                if isinstance(item, int):
                    groups.append(item)
                elif isinstance(item, basestring):
                    try:
                        item = int(item)
                    except ValueError:
                        if item not in self.iface_group_aliases:
                            raise ValueError, "Valid group name expected; value='%s' %s" % (item, str(self.iface_group_aliases))
                        item = self.iface_group_aliases[item]

                    groups.append(item)

            return groups
Esempio n. 9
0
    def __init__(self, mapping):
        """
        <method maturity="stable">
          <summary>
            Constructor to initialize a GeneralNAT instance.
          </summary>
          <description>
            <para>
              This constructor initializes a GeneralNAT instance.
            </para>
          </description>
          <metainfo>
            <arguments>
              <argument>
                <name>mapping</name>
                <type>
                  <list>
                    <tuple>
                      <class filter="subnet" instance="yes"/>
                      <class filter="subnet" instance="yes"/>
                      <class filter="subnet" instance="yes"/>
                    </tuple>
                  </list>
                </type>
                <description>
                  List of tuples of InetSubnets in (source domain, destination domain,
                  mapped domain) format.
                </description>
              </argument>
            </arguments>
          </metainfo>
        </method>
        """
        super(GeneralNAT, self).__init__()

        mapping = makeSequence(mapping)
        self.mappings = [[], []]
        for map in mapping:
            if len(map) == 2:
                raise ValueError, "GeneralNAT with old-style mapping parameter is not supported"
            else:
                self.mappings[NAT_SNAT].append(map)
                self.mappings[NAT_DNAT].append(map)
Esempio n. 10
0
    def __init__(self, mapping):
        """
        <method maturity="stable">
          <summary>
            Constructor to initialize a GeneralNAT instance.
          </summary>
          <description>
            <para>
              This constructor initializes a GeneralNAT instance.
            </para>
          </description>
          <metainfo>
            <arguments>
              <argument>
                <name>mapping</name>
                <type>
                  <list>
                    <tuple>
                      <class filter="subnet" instance="yes"/>
                      <class filter="subnet" instance="yes"/>
                      <class filter="subnet" instance="yes"/>
                    </tuple>
                  </list>
                </type>
                <description>
                  List of tuples of InetSubnets in (source domain, destination domain,
                  mapped domain) format.
                </description>
              </argument>
            </arguments>
          </metainfo>
        </method>
        """
        super(GeneralNAT, self).__init__()

        mapping = makeSequence(mapping)
        self.mappings = [[], []]
        for map in mapping:
            if len(map) == 2:
                raise ValueError, "GeneralNAT with old-style mapping parameter is not supported"
            else:
                self.mappings[NAT_SNAT].append(map)
                self.mappings[NAT_DNAT].append(map)
Esempio n. 11
0
File: Rule.py Progetto: Balasys/zorp
        def CreateRealRule(parameters):
            """
            <method internal="yes">
            Helper function to create rules
            </method>
            """

            # store service
            service_name = parameters.pop('service', None)
            self._service = Globals.services.get(service_name, None)
            if not self._service:
                raise ValueError, "No valid service was specified for the rule; service='%s'" % (service_name,)

            # convert and check special dimensions: subnets, ports and zones at the moment

            for ip_keyword in ['src_subnet', 'dst_subnet']:
                ipv6_keyword = ip_keyword + '6'
                # forbid usage of ipv6 related keywords:
                if ipv6_keyword in parameters:
                    raise ValueError, "Invalid dimension specification '%s'" % ipv6_keyword
                (parameters[ip_keyword], parameters[ipv6_keyword]) = parseSubnets(parameters.get(ip_keyword, []))

            parameters['src_ifgroup'] = parseGroups(parameters.get('src_ifgroup', []))
            parameters['dst_ifgroup'] = parseGroups(parameters.get('dst_ifgroup', []))
            parameters['src_port'] = parsePorts(parameters.get('src_port', []))
            parameters['dst_port'] = parsePorts(parameters.get('dst_port', []))
            resolveZones(parameters.get('src_zone', []))
            resolveZones(parameters.get('dst_zone', []))

            # store values specified
            self._dimensions = {}
            for key, value in parameters.items():
                if key not in self.valid_dim_names:
                    if key in self.dimension_aliases:
                        key = self.dimension_aliases[key]
                    else:
                        raise ValueError, "Unknown dimension '%s'" % (key,)

                self._dimensions.setdefault(key, []).extend(makeSequence(value))

            Dispatch.RuleDispatcher.createOneInstance()
Esempio n. 12
0
                def parseSubnets(subnet_list):
                        """
                        Helper function to convert a string-based
                        subnet list to two tuples consisting of
                        InetSubnet and InetSubnet6 instances.
                        """
                        import socket
                        subnets = { socket.AF_INET: [], socket.AF_INET6: [] }

                        subnet_list = makeSequence(subnet_list)

                        for item in subnet_list:
                                if isinstance(item, basestring):
                                        subnet = Subnet.create(item)
                                elif isinstance(item, Subnet):
                                        subnet = item
                                else:
                                        raise ValueError, "Invalid subnet specification: value='%s'" % (item,)

                                subnets[subnet.get_family()].append((subnet.addr_packed(), subnet.netmask_packed()))

                        return (tuple(subnets[socket.AF_INET]), tuple(subnets[socket.AF_INET6]))
Esempio n. 13
0
File: Rule.py Progetto: VPetyaa/zorp
    def __init__(self, **kw):
        """
        <method>
            <summary>Initializes a rule</summary>
            <description>Initializes a rule</description>
            <metainfo>
                <arguments>
                    <argument>
                        <name>dst_iface</name>
                        <type><interface/></type>
                        <description>Permit traffic only for connections that target a configured IP address of the listed interfaces. This parameter can be used to provide nontransparent service on an interface that received its IP address dynamically. For example, <parameter>dst_iface='eth0',</parameter> or <parameter>dst_iface=('eth0', 'tun1'),</parameter>.</description>
                    </argument>
                    <argument>
                        <name>dst_ifgroup</name>
                        <type><integer/></type>
                        <description>Permit traffic only for connections that target a configured IP address of the listed interface group. This parameter can be used to provide nontransparent service on an interface that received its IP address dynamically. For example, <parameter>dst_ifgroup=1</parameter>.</description>
                    </argument>
                    <argument>
                        <name>dst_port</name>
                        <type><integer/></type>
                        <description>Permit traffic only if the client targets the listed port. For example, <parameter>dst_port=80</parameter>, or <parameter>dst_port=(80, 443)</parameter>. To specify port ranges, use the <link linkend="python.Rule.PortRange">PortRange</link> class, for example, <parameter>dst_port=PortRange(2000, 2100)</parameter>.</description>
                    </argument>
                    <argument>
                        <name>dst_subnet</name>
                        <type><subnet/></type>
                        <description>Permit traffic only for connections targeting a listed IP address, or an address belonging to the listed subnet. The subnet can be IPv4 or IPv6 subnet. When listing multiple subnets, you can list both IPv4 and IPv6 subnets. IP addresses are treated as subnets with a /32 (IPv4) or /128 (IPv6) netmask. If no netmask is set for a subnet, it is treated as a specific IP address. For example, <parameter>dst_subnet='192.168.10.16'</parameter> or <parameter>dst_subnet=('192.168.0.0/16', '2001:db8:c001:ba80::/58')</parameter>.</description>
                    </argument>
                    <argument>
                        <name>dst_zone</name>
                        <type><zone/></type>
                        <description>Permit traffic only for connections targeting an address belonging to the listed zones. For example, <parameter>dst_zone='office'</parameter> or <parameter>dst_zone=('office', 'finance')</parameter>. Note that this applies to destination address of the client-side connection request: the actual address of the server-side connection can be different (for example, if a DirectedRouter is used in the service).</description>
                    </argument>
                    <argument>
                        <name>proto</name>
                        <type><integer/></type>
                        <description>Permit only connections using the specified transport protocol. This is the transport layer (Layer 4) protocol of the OSI model, for example, TCP, UDP, ICMP, and so on. The protocol must be specified using a number: the decimal value of the "protocol" field of the IP header. This value is 6 for the TCP and 17 for the UDP protocol. For a list of protocol numbers, see the <ulink url="http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml">Assigned Internet Protocol Numbers page of IANA</ulink>. For example: <parameter>proto=(6,17)</parameter>.
                        <para>To permit any protocol, do not add the <parameter>proto</parameter> parameter to the rule.</para></description>
                    </argument>
                    <argument>
                        <name>rule_id</name>
                        <type><integer/></type>
                        <description>A unique ID number for the rule. This parameter is optional, Zorp automatically generates an ID number for the rule during startup.</description>
                    </argument>
                    <argument>
                        <name>service</name>
                        <type><service/></type>
                        <description>The name of the service to start for matching connections. This is the only required parameter for the rule, everything else is optional. For example, <parameter>service='MyService'</parameter></description>
                    </argument>
                    <argument>
                        <name>src_iface</name>
                        <type><interface/></type>
                        <description>Permit traffic only for connections received on the listed interface. For example, <parameter>src_iface='eth0',</parameter> or <parameter>src_iface=('eth0', 'tun1'),</parameter>.</description>
                    </argument>
                    <argument>
                        <name>src_ifgroup</name>
                        <type><integer/></type>
                        <description>Permit traffic only for connections received on the listed interfacegroup. For example, <parameter>src_iface=1</parameter>. Interface groups can be defined in the <filename>/etc/network/interfaces</filename> file, for example:
                        <synopsis>iface eth0 inet dhcp
            group 1
        iface eth1 inet dhcp
            group 1</synopsis></description>
                    </argument>
                    <argument>
                        <name>src_port</name>
                        <type><integer/></type>
                        <description>Permit traffic only if the client sends the connection request from the listed port. For example, <parameter>src_port=4455</parameter>. To specify port ranges, use the <link linkend="python.Rule.PortRange">PortRange</link> class, for example, <parameter>src_port=PortRange(2000, 2100)</parameter>.</description>
                    </argument>
                    <argument>
                        <name>src_subnet</name>
                        <type><subnet/></type>
                        <description>Permit traffic only for the clients of the listed subnet or IP addresses. The subnet can be IPv4 or IPv6 subnet. When listing multiple subnets, you can list both IPv4 and IPv6 subnets. IP addresses are treated as subnets with a /32 (IPv4) or /128 (IPv6) netmask. If no netmask is set for a subnet, it is treated as a specific IP address. For example, <parameter>src_subnet='192.168.10.16'</parameter> or <parameter>src_subnet=('192.168.0.0/16', '2001:db8:c001:ba80::/58')</parameter>.</description>
                    </argument>
                    <argument>
                        <name>src_zone</name>
                        <type><zone/></type>
                        <description>Permit traffic only for the clients of the listed zones. For example, <parameter>src_zone='office'</parameter> or <parameter>src_zone=('office', 'finance')</parameter>.</description>
                    </argument>
                </arguments>
            </metainfo>
        </method>
        """
        def parseSubnets(subnet_list):
            """
            <method internal="yes">
            Helper function to convert a string-based
            subnet list to two tuples consisting of
            InetSubnet and InetSubnet6 instances.
            </method>
            """
            import socket
            subnets = {socket.AF_INET: [], socket.AF_INET6: []}

            subnet_list = makeSequence(subnet_list)

            for item in subnet_list:
                if isinstance(item, basestring):
                    subnet = Subnet.create(item)
                elif isinstance(item, Subnet):
                    subnet = item
                else:
                    raise ValueError, "Invalid subnet specification: value='%s'" % (
                        item, )

                subnets[subnet.get_family()].append(
                    (subnet.addr_packed(), subnet.netmask_packed()))

            return (tuple(subnets[socket.AF_INET]),
                    tuple(subnets[socket.AF_INET6]))

        def resolveZones(name_list):
            """
            <method internal="yes">
            Helper function to convert a list of zone
            names to a list of Zone instnaces
            </method>
            """
            name_list = makeSequence(name_list)

            for name in name_list:
                if Zone.lookup_by_name(name) == None:
                    raise ValueError, "No zone was defined with that name; zone='%s'" % (
                        name, )

        def parsePorts(port_list):
            """
            <method internal="yes">
            Helper function to convert a port or port
            range list to a list of port ranges. Accepted
            input formats are:

            (port1, port2, port3) - list of ports
            (port1, (begin, end), port3) - list of ports mixed with ranges
            </method>
            """
            ports = []
            port_list = makeSequence(port_list)

            for item in port_list:
                if isinstance(item, PortRange):
                    ports.append(item.getTuple())
                else:
                    if isinstance(item, basestring):
                        item = int(item)

                    if not isinstance(item, int):
                        raise ValueError, "Integer port value expected; value='%s'" % (
                            item, )

                    ports.append((item, item))

            return ports

        def parseGroups(group_list):
            groups = []
            group_list = makeSequence(group_list)

            for item in group_list:
                if isinstance(item, int):
                    groups.append(item)
                elif isinstance(item, basestring):
                    try:
                        item = int(item)
                    except ValueError:
                        if item not in self.iface_group_aliases:
                            raise ValueError, "Valid group name expected; value='%s' %s" % (
                                item, str(self.iface_group_aliases))
                        item = self.iface_group_aliases[item]

                    groups.append(item)

            return groups

        # store id
        self._id = kw.pop('rule_id', None)

        # store service
        service_name = kw.pop('service', None)
        self._service = Globals.services.get(service_name, None)
        if not self._service:
            raise ValueError, "No valid service was specified for the rule; service='%s'" % (
                service_name, )

        # convert and check special dimensions: subnets, ports and zones at the moment

        for ip_keyword in ['src_subnet', 'dst_subnet']:
            ipv6_keyword = ip_keyword + '6'
            # forbid usage of ipv6 related keywords:
            if ipv6_keyword in kw:
                raise ValueError, "Invalid dimension specification '%s'" % ipv6_keyword
            (kw[ip_keyword],
             kw[ipv6_keyword]) = parseSubnets(kw.get(ip_keyword, []))

        kw['src_ifgroup'] = parseGroups(kw.get('src_ifgroup', []))
        kw['dst_ifgroup'] = parseGroups(kw.get('dst_ifgroup', []))
        kw['src_port'] = parsePorts(kw.get('src_port', []))
        kw['dst_port'] = parsePorts(kw.get('dst_port', []))
        resolveZones(kw.get('src_zone', []))
        resolveZones(kw.get('dst_zone', []))

        # store values specified
        self._dimensions = {}
        for key, value in kw.items():
            if key not in self.valid_dimensions:
                if key in self.dimension_aliases:
                    key = self.dimension_aliases[key]
                else:
                    raise ValueError, "Unknown dimension '%s'" % (key, )

            self._dimensions.setdefault(key, []).extend(makeSequence(value))

        Globals.rules.add(self)
        Dispatch.RuleDispatcher.createOneInstance()
Esempio n. 14
0
File: Rule.py Progetto: VPetyaa/zorp
    def __init__(self, **kw):
        """
        <method>
            <summary>Initializes a rule</summary>
            <description>Initializes a rule</description>
            <metainfo>
                <arguments>
                    <argument>
                        <name>dst_iface</name>
                        <type><interface/></type>
                        <description>Permit traffic only for connections that target a configured IP address of the listed interfaces. This parameter can be used to provide nontransparent service on an interface that received its IP address dynamically. For example, <parameter>dst_iface='eth0',</parameter> or <parameter>dst_iface=('eth0', 'tun1'),</parameter>.</description>
                    </argument>
                    <argument>
                        <name>dst_ifgroup</name>
                        <type><integer/></type>
                        <description>Permit traffic only for connections that target a configured IP address of the listed interface group. This parameter can be used to provide nontransparent service on an interface that received its IP address dynamically. For example, <parameter>dst_ifgroup=1</parameter>.</description>
                    </argument>
                    <argument>
                        <name>dst_port</name>
                        <type><integer/></type>
                        <description>Permit traffic only if the client targets the listed port. For example, <parameter>dst_port=80</parameter>, or <parameter>dst_port=(80, 443)</parameter>. To specify port ranges, use the <link linkend="python.Rule.PortRange">PortRange</link> class, for example, <parameter>dst_port=PortRange(2000, 2100)</parameter>.</description>
                    </argument>
                    <argument>
                        <name>dst_subnet</name>
                        <type><subnet/></type>
                        <description>Permit traffic only for connections targeting a listed IP address, or an address belonging to the listed subnet. The subnet can be IPv4 or IPv6 subnet. When listing multiple subnets, you can list both IPv4 and IPv6 subnets. IP addresses are treated as subnets with a /32 (IPv4) or /128 (IPv6) netmask. If no netmask is set for a subnet, it is treated as a specific IP address. For example, <parameter>dst_subnet='192.168.10.16'</parameter> or <parameter>dst_subnet=('192.168.0.0/16', '2001:db8:c001:ba80::/58')</parameter>.</description>
                    </argument>
                    <argument>
                        <name>dst_zone</name>
                        <type><zone/></type>
                        <description>Permit traffic only for connections targeting an address belonging to the listed zones. For example, <parameter>dst_zone='office'</parameter> or <parameter>dst_zone=('office', 'finance')</parameter>. Note that this applies to destination address of the client-side connection request: the actual address of the server-side connection can be different (for example, if a DirectedRouter is used in the service).</description>
                    </argument>
                    <argument>
                        <name>proto</name>
                        <type><integer/></type>
                        <description>Permit only connections using the specified transport protocol. This is the transport layer (Layer 4) protocol of the OSI model, for example, TCP, UDP, ICMP, and so on. The protocol must be specified using a number: the decimal value of the "protocol" field of the IP header. This value is 6 for the TCP and 17 for the UDP protocol. For a list of protocol numbers, see the <ulink url="http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml">Assigned Internet Protocol Numbers page of IANA</ulink>. For example: <parameter>proto=(6,17)</parameter>.
                        <para>To permit any protocol, do not add the <parameter>proto</parameter> parameter to the rule.</para></description>
                    </argument>
                    <argument>
                        <name>rule_id</name>
                        <type><integer/></type>
                        <description>A unique ID number for the rule. This parameter is optional, Zorp automatically generates an ID number for the rule during startup.</description>
                    </argument>
                    <argument>
                        <name>service</name>
                        <type><service/></type>
                        <description>The name of the service to start for matching connections. This is the only required parameter for the rule, everything else is optional. For example, <parameter>service='MyService'</parameter></description>
                    </argument>
                    <argument>
                        <name>src_iface</name>
                        <type><interface/></type>
                        <description>Permit traffic only for connections received on the listed interface. For example, <parameter>src_iface='eth0',</parameter> or <parameter>src_iface=('eth0', 'tun1'),</parameter>.</description>
                    </argument>
                    <argument>
                        <name>src_ifgroup</name>
                        <type><integer/></type>
                        <description>Permit traffic only for connections received on the listed interfacegroup. For example, <parameter>src_iface=1</parameter>. Interface groups can be defined in the <filename>/etc/network/interfaces</filename> file, for example:
                        <synopsis>iface eth0 inet dhcp
            group 1
        iface eth1 inet dhcp
            group 1</synopsis></description>
                    </argument>
                    <argument>
                        <name>src_port</name>
                        <type><integer/></type>
                        <description>Permit traffic only if the client sends the connection request from the listed port. For example, <parameter>src_port=4455</parameter>. To specify port ranges, use the <link linkend="python.Rule.PortRange">PortRange</link> class, for example, <parameter>src_port=PortRange(2000, 2100)</parameter>.</description>
                    </argument>
                    <argument>
                        <name>src_subnet</name>
                        <type><subnet/></type>
                        <description>Permit traffic only for the clients of the listed subnet or IP addresses. The subnet can be IPv4 or IPv6 subnet. When listing multiple subnets, you can list both IPv4 and IPv6 subnets. IP addresses are treated as subnets with a /32 (IPv4) or /128 (IPv6) netmask. If no netmask is set for a subnet, it is treated as a specific IP address. For example, <parameter>src_subnet='192.168.10.16'</parameter> or <parameter>src_subnet=('192.168.0.0/16', '2001:db8:c001:ba80::/58')</parameter>.</description>
                    </argument>
                    <argument>
                        <name>src_zone</name>
                        <type><zone/></type>
                        <description>Permit traffic only for the clients of the listed zones. For example, <parameter>src_zone='office'</parameter> or <parameter>src_zone=('office', 'finance')</parameter>.</description>
                    </argument>
                </arguments>
            </metainfo>
        </method>
        """

        def parseSubnets(subnet_list):
            """
            <method internal="yes">
            Helper function to convert a string-based
            subnet list to two tuples consisting of
            InetSubnet and InetSubnet6 instances.
            </method>
            """
            import socket
            subnets = { socket.AF_INET: [], socket.AF_INET6: [] }

            subnet_list = makeSequence(subnet_list)

            for item in subnet_list:
                if isinstance(item, basestring):
                    subnet = Subnet.create(item)
                elif isinstance(item, Subnet):
                    subnet = item
                else:
                    raise ValueError, "Invalid subnet specification: value='%s'" % (item,)

                subnets[subnet.get_family()].append((subnet.addr_packed(), subnet.netmask_packed()))

            return (tuple(subnets[socket.AF_INET]), tuple(subnets[socket.AF_INET6]))

        def resolveZones(name_list):
            """
            <method internal="yes">
            Helper function to convert a list of zone
            names to a list of Zone instnaces
            </method>
            """
            name_list = makeSequence(name_list)

            for name in name_list:
                if Zone.lookup_by_name(name) == None:
                    raise ValueError, "No zone was defined with that name; zone='%s'" % (name,)

        def parsePorts(port_list):
            """
            <method internal="yes">
            Helper function to convert a port or port
            range list to a list of port ranges. Accepted
            input formats are:

            (port1, port2, port3) - list of ports
            (port1, (begin, end), port3) - list of ports mixed with ranges
            </method>
            """
            ports = []
            port_list = makeSequence(port_list)

            for item in port_list:
                if isinstance(item, PortRange):
                    ports.append(item.getTuple())
                else:
                    if isinstance(item, basestring):
                        item = int(item)

                    if not isinstance(item, int):
                        raise ValueError, "Integer port value expected; value='%s'" % (item,)

                    ports.append((item, item))

            return ports

        def parseGroups(group_list):
            groups = []
            group_list = makeSequence(group_list)

            for item in group_list:
                if isinstance(item, int):
                    groups.append(item)
                elif isinstance(item, basestring):
                    try:
                        item = int(item)
                    except ValueError:
                        if item not in self.iface_group_aliases:
                            raise ValueError, "Valid group name expected; value='%s' %s" % (item, str(self.iface_group_aliases))
                        item = self.iface_group_aliases[item]

                    groups.append(item)

            return groups

        # store id
        self._id = kw.pop('rule_id', None)

        # store service
        service_name = kw.pop('service', None)
        self._service = Globals.services.get(service_name, None)
        if not self._service:
            raise ValueError, "No valid service was specified for the rule; service='%s'" % (service_name,)

        # convert and check special dimensions: subnets, ports and zones at the moment

        for ip_keyword in ['src_subnet', 'dst_subnet']:
            ipv6_keyword = ip_keyword + '6'
            # forbid usage of ipv6 related keywords:
            if ipv6_keyword in kw:
                raise ValueError, "Invalid dimension specification '%s'" % ipv6_keyword
            (kw[ip_keyword], kw[ipv6_keyword]) = parseSubnets(kw.get(ip_keyword, []))

        kw['src_ifgroup'] = parseGroups(kw.get('src_ifgroup', []))
        kw['dst_ifgroup'] = parseGroups(kw.get('dst_ifgroup', []))
        kw['src_port'] = parsePorts(kw.get('src_port', []))
        kw['dst_port'] = parsePorts(kw.get('dst_port', []))
        resolveZones(kw.get('src_zone', []))
        resolveZones(kw.get('dst_zone', []))

        # store values specified
        self._dimensions = {}
        for key, value in kw.items():
            if key not in self.valid_dimensions:
                if key in self.dimension_aliases:
                    key = self.dimension_aliases[key]
                else:
                    raise ValueError, "Unknown dimension '%s'" % (key,)

            self._dimensions.setdefault(key, []).extend(makeSequence(value))

        Globals.rules.add(self)
        Dispatch.RuleDispatcher.createOneInstance()
Esempio n. 15
0
        def __init__(self, **kw):

                def parseSubnets(subnet_list):
                        """
                        Helper function to convert a string-based
                        subnet list to two tuples consisting of
                        InetSubnet and InetSubnet6 instances.
                        """
                        import socket
                        subnets = { socket.AF_INET: [], socket.AF_INET6: [] }

                        subnet_list = makeSequence(subnet_list)

                        for item in subnet_list:
                                if isinstance(item, basestring):
                                        subnet = Subnet.create(item)
                                elif isinstance(item, Subnet):
                                        subnet = item
                                else:
                                        raise ValueError, "Invalid subnet specification: value='%s'" % (item,)

                                subnets[subnet.get_family()].append((subnet.addr_packed(), subnet.netmask_packed()))

                        return (tuple(subnets[socket.AF_INET]), tuple(subnets[socket.AF_INET6]))

                def resolveZones(name_list):
                        """
                        Helper function to convert a list of zone
                        names to a list of Zone instnaces
                        """
                        name_list = makeSequence(name_list)

                        for name in name_list:
                                if Zone.lookup_by_name(name) == None:
                                        raise ValueError, "No zone was defined with that name; zone='%s'" % (name,)

                def parsePorts(port_list):
                        """
                        Helper function to convert a port or port
                        range list to a list of port ranges. Accepted
                        input formats are:

                        (port1, port2, port3) - list of ports
                        (port1, (begin, end), port3) - list of ports mixed with ranges
                        """
                        ports = []
                        port_list = makeSequence(port_list)

                        for item in port_list:
                                if isinstance(item, PortRange):
                                        ports.append(item.getTuple())
                                else:
                                        if isinstance(item, basestring):
                                                item = int(item)

                                        if not isinstance(item, int):
                                                raise ValueError, "Integer port value expected; value='%s'" % (item,)

                                        ports.append((item, item))

                        return ports

                # store id
                self._id = kw.pop('rule_id', None)

                # store service
                service_name = kw.pop('service', None)
                self._service = Globals.services.get(service_name, None)
                if not self._service:
                        raise ValueError, "No valid service was specified for the rule; service='%s'" % (service_name,)

                # convert and check special dimensions: subnets, ports and zones at the moment
                (kw['src_subnet'], kw['src_subnet6']) = parseSubnets(kw.get('src_subnet', []))
                (kw['dst_subnet'], kw['dst_subnet6']) = parseSubnets(kw.get('dst_subnet', []))
                kw['src_port'] = parsePorts(kw.get('src_port', []))
                kw['dst_port'] = parsePorts(kw.get('dst_port', []))
                resolveZones(kw.get('src_zone', []))
                resolveZones(kw.get('dst_zone', []))

                # store values specified
                self._dimensions = {}
                for key, value in kw.items():
                        if key not in self.valid_dimensions:
                                raise ValueError, "Unknown dimension '%s'" % (key,)

                        self._dimensions[key] = makeSequence(value)

                Globals.rules.add(self)
                Dispatch.RuleDispatcher.createOneInstance()