Ejemplo n.º 1
0
 def ipfw_enabled(self) -> bool:
     """Return True if ipfw is enabled on the host system."""
     try:
         firewall_enabled = freebsd_sysctl.Sysctl("net.inet.ip.fw.enable")
         return (firewall_enabled.value == 1) is True
     except Exception:
         return False
Ejemplo n.º 2
0
def test_security_jail_param_list(benchmark):
    test_node_name = "security.jail.param"
    stdout = subprocess.check_output([
        "/sbin/sysctl",
        "-N",
        test_node_name
    ]).strip().decode()
    child_names = stdout.split("\n")
    assert len(child_names) > 0, "test pre-condition"

    def get_children(test_node_sysctl):
        return list(test_node_sysctl.children)

    test_node_children = benchmark(
        get_children,
        freebsd_sysctl.Sysctl(test_node_name)
    )

    assert len(test_node_children) == len(child_names), (
        "different number of children reported"
    )

    test_node_child_names = [c.name for c in test_node_children]
    assert all([a == b for a, b in zip(test_node_child_names, child_names)]), (
        "the order of children or their names differed"
    )
Ejemplo n.º 3
0
    def ensure_firewall_enabled(self) -> None:
        """Raise an FirewallDisabled exception if the firewall is disabled."""
        requirements = self._required_sysctl_properties

        if len(requirements) == 0:
            return

        try:
            current = "not found"
            for key in requirements:
                expected = requirements[key]
                current = freebsd_sysctl.Sysctl(key).value
                if int(current) != int(expected):
                    raise ValueError(
                        f"Invalid Sysctl {key}: "
                        f"{current} found, but expected: {expected}"
                    )
            return
        except Exception:
            # an IocageException is raised in the next step at the right level
            pass

        hint = f"sysctl {key} is expected to be {expected}, but was {current}"
        raise libioc.errors.FirewallDisabled(
            hint=hint,
            logger=self.logger
        )
Ejemplo n.º 4
0
def test_sysctl_descriptions(sysctl_types):
    for sysctl_name, sysctl_type in sysctl_types.items():
        current_sysctl = freebsd_sysctl.Sysctl(sysctl_name)

        stdout = subprocess.check_output(
            ["/sbin/sysctl", "-d", "-n", sysctl_name]).strip().decode()

        current_description = str(current_sysctl.description).strip()
        assert stdout == current_description, sysctl_name
Ejemplo n.º 5
0
def test_explicit_list_of_sysctl_value(item):

    sysctl_name = item[1]

    sysctl = freebsd_sysctl.Sysctl(sysctl_name)

    stdout = subprocess.check_output([
        "/sbin/sysctl",
        "-n",
        sysctl_name
    ]).strip().decode()

    assert str(sysctl.value) == stdout
Ejemplo n.º 6
0
def test_sysctl_values(sysctl_types):
    for sysctl_name, sysctl_type in sysctl_types.items():
        current_sysctl = freebsd_sysctl.Sysctl(sysctl_name)

        stdout = subprocess.check_output(["/sbin/sysctl", "-n",
                                          sysctl_name]).strip().decode()

        if isinstance(current_sysctl.raw_value, freebsd_sysctl.OPAQUE):
            continue
        elif isinstance(current_sysctl.raw_value, freebsd_sysctl.NODE):
            continue
        else:
            current_value = str(current_sysctl.value).strip()
            assert current_value == stdout, sysctl_name
Ejemplo n.º 7
0
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Unit tests for Jail Resource Limits."""
import typing
import pytest
import subprocess

import freebsd_sysctl

try:
    rctl_supported = (freebsd_sysctl.Sysctl("kern.features.rctl").value == 1)
    rctl_enabled = (freebsd_sysctl.Sysctl("kern.racct.enable").value == 1)
    rctl_supported = (rctl_supported and rctl_enabled) is True
except Exception:
    rctl_supported = False


@pytest.mark.skipif((rctl_supported is False),
                    reason="Resource Limits disabled (kern.features.rctl=0).")
class TestResourceLimits(object):
    """Run Resource Limit tests."""
    @staticmethod
    def __mib_to_bytes(value: int) -> int:
        return value * 1024 * 1024

    def test_limits_are_applied_to_jails_on_start(
Ejemplo n.º 8
0
 def uuid(self) -> UUID:
     """Return the hostuuid and memoize on first lookup."""
     return uuid.UUID(freebsd_sysctl.Sysctl("kern.hostuuid").value)
Ejemplo n.º 9
0
 def lookup_values(sysctl_types):
     for sysctl_name, sysctl_type in sysctl_types.items():
         yield sysctl_name, freebsd_sysctl.Sysctl(sysctl_name).raw_value
Ejemplo n.º 10
0
def test_sysctl_types(sysctl_types):
    for sysctl_name, sysctl_type in sysctl_types.items():
        current_sysctl = freebsd_sysctl.Sysctl(sysctl_name)
        current_mapped_type = map_sysctl_type(current_sysctl.ctl_type)
        assert sysctl_type == current_mapped_type, sysctl_name
Ejemplo n.º 11
0
def test_sysctl_names(sysctl_types):
    for sysctl_name, sysctl_type in sysctl_types.items():
        current_sysctl = freebsd_sysctl.Sysctl(sysctl_name)
        resolved_sysctl = freebsd_sysctl.Sysctl(oid=current_sysctl.oid)
        assert sysctl_name == resolved_sysctl.name
Ejemplo n.º 12
0
 def lookup_descriptions(sysctl_types):
     for sysctl_name, sysctl_type in sysctl_types.items():
         yield sysctl_name, freebsd_sysctl.Sysctl(sysctl_name).description
Ejemplo n.º 13
0
def test_sysctl_opaque_fmt(sysctl_name, expected):
    sysctl = freebsd_sysctl.Sysctl(sysctl_name)
    assert sysctl.fmt == expected
Ejemplo n.º 14
0
def test_sysctl_names(sysctl_types):
    for sysctl_name, sysctl_type in sysctl_types.items():
        current_sysctl = freebsd_sysctl.Sysctl(sysctl_name)
        assert sysctl_name == current_sysctl.name
Ejemplo n.º 15
0
 def __get_sysctl(self, key: str) -> freebsd_sysctl.Sysctl:
     _key = self.__getkey(key).decode("UTF-8")
     if _key not in self.cached_sysctls.keys():
         self.cached_sysctls[_key] = freebsd_sysctl.Sysctl(_key)
     return self.cached_sysctls[_key]
Ejemplo n.º 16
0
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""FreeBSD jail sysctl bindings."""
import typing
import ctypes
import itertools
import ipaddress

import freebsd_sysctl
import freebsd_sysctl.types

from jail.libc import dll
import jail.types

NULL_BYTES = b"\x00"
JAIL_MAX_AF_IPS = freebsd_sysctl.Sysctl("security.jail.jail_max_af_ips").value


class Iovec(ctypes.Structure):
    _fields_ = [
        ("iov_base", ctypes.c_void_p),
        ("iov_size", ctypes.c_size_t)
    ]


class IovecKey:

    def __init__(self, value: typing.Union[str, bytes]) -> None:
        if isinstance(value, bytes) is True:
            self.value = value
        elif isinstance(value, str) is True: