File squilt-20230719.dde2b0b.obscpio of Package squilt-python

07070100000000000081A400000000000000000000000164B7B6E600000430000000000000000000000000000000000000002000000000squilt-20230719.dde2b0b/LICENSEMIT License

Copyright (c) 2018 Johannes Segitz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
07070100000001000081A400000000000000000000000164B7B6E60000096C000000000000000000000000000000000000002200000000squilt-20230719.dde2b0b/README.md# squilt
Wrapper to confine quilt with [nsjail](https://github.com/google/nsjail)

# Why?
Using quilt on untrusted spec files is not secure. For more see
[this posting by Matthias](https://www.openwall.com/lists/oss-security/2018/09/27/2).

Matthias developed the original exploit, but as described in the posting, any
command in %prep is run as the user calling quilt without any limitations. This
was (at least to us) unexpected.

# Usage
If you add an alias quilt=squilt or copy this script as 'quilt' to a directory
that is earlier in $PATH you should be able to use it like you use quilt without
noticying a difference.

# Protection Level

squilt uses namespace isolation techniques to mark most of the hosts file
systems as read-only and to make possibly sensitive data inacessible (like the
user's home directory or most system configuration files). Write access is
still necessary in the current working directory where squilt is invoked. This
means a malicous RPM spec file could still manipulate the RPM package's
directory contents. When working with untrusted spec files this should be
obvious, however.

# Runtime Configuration

Squilt does not support command line parameters, because it acts as a frontend
to the actual `quilt` program and thus passes on any command line parameters
to it.

To still allow some degree of configuration the following environment
variables are recognized by squilt:

- `SQUILT_VERBOSE`: if set then the verbosity of squilt and nsjail is
  increased to give a better picture of what happens.
- `SQUILT_DEBUG`: if set then even more internals of the squilt operation
  are shown. This currently means the temporary nsjail configuration file is
  dumped onto stdout before executing quilt.
- `SQUILT_ENTER_SHELL`: if set then instead of actually running quilt, an
  interactive shell in the jail environment is invoked. This allows
  interactive debugging of the shell environment. Note that some things are
  different in this mode: For example the /proc directory is mounted which
  is normally not the case.
- `SQUILT_EXTRA_MOUNTS`: to allow extra mount operations in the jail
  environment without having to modify the squilt main script you can
  specify a semicolon separted list of extra `MountSpec` entries that will
  be added. For example: `SQUILT_EXTRA_MOUNTS="MountSpec(src='/opt')"`. This
  would be mounting /opt from the host into the jail environment.
07070100000002000081ED00000000000000000000000164B7B6E600001769000000000000000000000000000000000000001F00000000squilt-20230719.dde2b0b/squilt#!/usr/bin/python3

import os
import shutil
import socket
import subprocess
import sys
import tempfile

if sys.version_info.major != 3 or sys.version_info.minor < 6:
    print("this script needs at least Python 3.7 to work", file=sys.stderr)
    sys.exit(1)


from collections import namedtuple
from pathlib import Path


def eprint(*args, **kwargs):
    kwargs['file'] = sys.stderr
    ex = kwargs.pop('exit', None)
    print(*args, **kwargs)

    if ex is not None:
        sys.exit(ex)


MountSpec = namedtuple(
    'MountSpec',
    'src dst rw fstype, mandatory'
)

# Python >= 3.7 support a 'defaults' kwargs in the Factory above, but I still
# want to support 3.6 which is the default on openSUSE :(
MountSpec.__new__.__defaults__ = (None, None, False, None, True)

QUILT_CONFIGS = (
    # per-user config
    os.path.expanduser("~/.quiltrc"),
    # system-wide config
    "/etc/quilt.quiltrc"
)

nsjail = shutil.which("nsjail")

if not nsjail:
    eprint("you need 'nsjail' (security/nsjail in OBS) for this wrapper to work", exit=1)

pkgroot = Path(os.getcwd())

# are we inside the already unpacked dir? If so mount the parent dir so we
# have access to the patches
if (pkgroot / "patches").is_symlink():
    pkgroot = pkgroot.parent

mounts = [
    MountSpec(src="/bin"),
    MountSpec(src="/lib"),
    MountSpec(src="/lib64"),
    MountSpec(src="/usr"),
    MountSpec(src="/sbin"),
    MountSpec(src="/etc/alternatives", mandatory=False),
    MountSpec(src="/etc/resolv.conf"),
    MountSpec(src="/etc/ld.so.cache"),
    MountSpec(src="/etc/rpm", mandatory=False),
    MountSpec(dst="/tmp", fstype="tmpfs", rw=True),
    MountSpec(dst="/var/tmp", fstype="tmpfs", rw=True),
    MountSpec(dst="/var/tmp", fstype="tmpfs", rw=True),
    MountSpec(src="/var/lib/rpm"),
    MountSpec(src=pkgroot, rw=True),
    MountSpec(dst=os.path.expanduser("~/rpmbuild"), fstype="tmpfs", rw=True),
]

# Autodetect nsswitch.conf
if os.path.isfile("/etc/nsswitch.conf"):
    mounts.append(MountSpec(src="/etc/nsswitch.conf"))
elif os.path.isfile("/usr/etc/nsswitch.conf"):
    mounts.append(MountSpec(src="/usr/etc/nsswitch.conf"))
else:
    eprint(f"nsswitch.conf not found (tried /etc and /usr/etc)", exit=2)

for config in QUILT_CONFIGS:
    if not Path(config).exists():
        continue

    spec = MountSpec(src=config)
    mounts.append(spec)

VERBOSE = "SQUILT_VERBOSE" in os.environ
ENTER_SHELL = "SQUILT_ENTER_SHELL" in os.environ
DEBUG = "SQUILT_DEBUG" in os.environ

if ENTER_SHELL:
    mounts.append(
        MountSpec(src="/dev", rw=True)
    )
else:
    mounts.extend([
        MountSpec(src="/dev/null", rw=True),
        MountSpec(src="/dev/urandom", rw=True),
    ])

extra_mounts = os.environ.get("SQUILT_EXTRA_MOUNTS", "")

for extra in extra_mounts.split(";"):
    extra = extra.strip()
    if not extra:
        continue
    spec = eval(extra)
    if type(spec) != MountSpec:
        eprint(f"expression {extra} in SQUILT_EXTRA_MOUNTS is not a MountSpec instance!", exit=2)

    mounts.append(spec)

config_settings = [
    ("name", '"quilt secure sandbox"'),
    ("hostname", f'"{socket.gethostname()}"'),
    ("description", '"This policy allows to run quilt in a secure way"'),
    ("cwd", f'"{os.getcwd()}"'),
    ("envar", f'"HOME={os.environ["HOME"]}"'),
    ("envar", f'"PATH={os.environ["PATH"]}"'),
]

for rlimit_class in ("as", "core", "cpu", "fsize", "nofile", "nproc", "stack"):
    config_settings.append((f"rlimit_{rlimit_class}_type", "HARD"))

if ENTER_SHELL:
    config_settings.extend([
        ("mount_proc", "true"),
        # this option is security relevant, because programs in the jail can put
        # back characters into our host environment's terminal
        ("skip_setsid", "true")
    ])
else:
    config_settings.append(
        ("time_limit", "120")
    )

# we need to create a temporary config file since mounts with
# : (like found in OBS package names) don't work on the command line
with tempfile.NamedTemporaryFile(mode='w') as tmpfile:

    for key, val in config_settings:
        tmpfile.write(f"{key}: {val}\n")

    for mnt in mounts:
        if mnt.src is None and mnt.fstype is None:
            eprint("Error in MountSpec ({str(mnt)}): neither src nor fstype", exit=1)
        elif mnt.fstype is not None and not mnt.rw:
            eprint("Error in MountSpec ({str(mnt)}): tmpfs w/o RW?", exit=1)
        elif mnt.src and not mnt.mandatory and not Path(mnt.src).exists():
            # check ourselves whether non-mandatory mounts exist to avoid ugly
            # warnings being output by nsjail
            continue

        tmpfile.write("mount {\n")
        if mnt.src is not None:
            tmpfile.write(f'\tsrc: "{mnt.src}"\n')

        dst = mnt.dst if mnt.dst is not None else mnt.src
        tmpfile.write(f'\tdst: "{dst}"\n')
        rw = "true" if mnt.rw else "false"
        tmpfile.write(f'\trw: {rw}\n')
        is_bind = "true"
        if mnt.src is None and mnt.fstype is not None:
            is_bind = "false"
        tmpfile.write(f'\tis_bind: {is_bind}\n')

        if mnt.fstype:
            tmpfile.write(f'\tfstype: "{mnt.fstype}"\n')

        if not mnt.mandatory:
            tmpfile.write('\tmandatory: false\n')
        tmpfile.write('}\n')

    tmpfile.flush()

    nsjail_opts = ["-Mo"]
    nsjail_target = []

    if not VERBOSE:
        nsjail_opts.append("-q")

    if ENTER_SHELL:
        print("Entering debug shell in target environment")
        nsjail_target = ["/bin/bash", "-i"]
    else:
        nsjail_target = ["/usr/bin/quilt"] + sys.argv[1:]

    nsjail_opts.extend(["--config", tmpfile.name, "--"])
    nsjail_cmdline = [nsjail] + nsjail_opts + nsjail_target

    if VERBOSE:
        print(' '.join(nsjail_cmdline))
    if DEBUG:
        with open(tmpfile.name, 'r') as cfgfd:
            print('configuration file content:')
            print('-' * 80)
            print(cfgfd.read())
            print('-' * 80)
    res = subprocess.call(nsjail_cmdline, shell=False)

sys.exit(res)
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!20 blocks
openSUSE Build Service is sponsored by