Пример #1
0
def make_extra_dev(newroot_norm, extra_devices, owner):
    """Create all the configured "extra" passthrough devices.

    :param ``str`` newroot_norm:
        Path to the container root directory.
    :param ``list`` extra_devices:
        List of extra device specification.
    :param ``str`` owner:
        Username of the owner of the new devices.
    """
    (uid, gid) = utils.get_uid_gid(owner)
    for extra_dev in extra_devices:
        if not extra_dev.startswith('/dev'):
            _LOGGER.warning('Bad passthrough device %r.', extra_dev)
            continue

        try:
            dev_stat = os.stat(extra_dev)
        except OSError as err:
            _LOGGER.warning('Failed to stat() %r: Skipping.', extra_dev)
            continue

        if stat.S_ISDIR(dev_stat.st_mode):
            _LOGGER.warning('Cannot Passthrough directory %r', extra_dev)
            continue

        passthrough_dev = os.path.join(newroot_norm, extra_dev[1:])

        if os.path.dirname(extra_dev) != '/dev':
            # We have to create more directories under '/dev'
            fs.mkdir_safe(os.path.dirname(passthrough_dev))

        os.mknod(passthrough_dev,
                 stat.S_IFMT(dev_stat.st_mode) | 0o600, dev_stat.st_rdev)
        os.chown(passthrough_dev, uid, gid)
Пример #2
0
 def __init__(self, princ, ticket):
     self.princ = princ
     self.ticket = ticket
     self.user = princ[:princ.find('@') if '@' in princ else len(princ)]
     try:
         self.uid = utils.get_uid_gid(self.user)[0]
     except KeyError:
         _LOGGER.warning('princ/user does not exist: %s', self.user)
         self.uid = None
Пример #3
0
def _create_overlay_group(root_dir, proid):
    """create a overlay /etc/group in oder to mount into container
    """
    path = os.path.join(root_dir, _CONTAINER_DOCKER_ETC_DIR, 'group')
    (_uid, gid) = utils.get_uid_gid(proid)
    with io.open(path, 'w') as f:
        root = _GROUP_PATTERN.format(NAME='root', GID=0)
        f.write('{}\n'.format(root))
        group = _GROUP_PATTERN.format(NAME=grp.getgrgid(gid).gr_name, GID=gid)
        f.write('{}\n'.format(group))
Пример #4
0
def make_keytab(kt_target, kt_components, owner=None):
    """Construct target keytab from individial components."""
    _LOGGER.info('Creating keytab: %s %r, owner=%s', kt_target, kt_components,
                 owner)
    cmd_line = ['kt_add', kt_target] + kt_components
    subproc.check_call(cmd_line)

    if owner:
        (uid, _gid) = utils.get_uid_gid(owner)
        os.chown(kt_target, uid, -1)
Пример #5
0
def _prepare_hosts(container_dir, app):
    """Create a hosts file for the container.

    overlay/
        /etc/
            hosts           # hosts file to be bind mounted in container.
        /run/
            /host-aliases/  # Directory to be bind mounted in container.
    """
    etc_dir = os.path.join(container_dir, 'overlay', 'etc')
    ha_dir = os.path.join(container_dir, 'overlay', 'run', 'host-aliases')
    fs.mkdir_safe(etc_dir)
    fs.mkdir_safe(ha_dir)

    shutil.copyfile('/etc/hosts', os.path.join(etc_dir, 'hosts'))

    (uid, gid) = utils.get_uid_gid(app.proid)
    os.chown(ha_dir, uid, gid)
Пример #6
0
def _create_overlay_passwd(root_dir, proid):
    """create a overlay /etc/passwd in order to mount into container
    """
    path = os.path.join(root_dir, _CONTAINER_DOCKER_ETC_DIR, 'passwd')
    (uid, gid) = utils.get_uid_gid(proid)
    with io.open(path, 'w') as f:
        root = _PASSWD_PATTERN.format(NAME='root',
                                      UID=0,
                                      GID=0,
                                      INFO='root',
                                      HOME='/root',
                                      SHELL='/bin/sh')
        f.write('{}\n'.format(root))
        user = _PASSWD_PATTERN.format(NAME=proid,
                                      UID=uid,
                                      GID=gid,
                                      INFO='',
                                      HOME='/',
                                      SHELL='/sbin/nologin')
        f.write('{}\n'.format(user))
Пример #7
0
def _ensure_table_exists(database, owner=None):
    """Creates table if table does not exist.

    :param database: Path to SQLite3 db file.
    """
    conn = sqlite3.connect(database)
    cur = conn.cursor()

    # store virtual => proid map
    # keytab: keytab file name e.g. host#vip1.domain.com@realm
    # table columns definitions:
    # proid: matched proid for the VIP keytab
    # vip: vip1.domain.com
    cur.execute('''
        CREATE TABLE IF NOT EXISTS %s
        (proid text, vip text)
        ''' % keytabs2.TABLE)
    conn.commit()
    conn.close()

    if owner is not None:
        (uid, gid) = utils.get_uid_gid(owner)
        os.chown(database, uid, gid)
Пример #8
0
def _install(package, src_dir, dst_dir, params, prefix_len=None, rec=None):
    """Interpolate source directory into target directory with params.
    """
    package_name = package.__name__
    _LOGGER.info(
        'Installing package: %s %s %s', package_name, src_dir, dst_dir
    )

    contents = pkg_resources.resource_listdir(package_name, src_dir)

    if prefix_len is None:
        prefix_len = len(src_dir) + 1

    for item in contents:
        resource_path = os.path.join(src_dir, item)
        dst_path = os.path.join(dst_dir, resource_path[prefix_len:])
        if pkg_resources.resource_isdir(package_name,
                                        os.path.join(src_dir, item)):
            fs.mkdir_safe(dst_path)

            # Check directory ownership.
            owner_rsrc = os.path.join(resource_path, '.owner')
            if pkg_resources.resource_exists(package_name, owner_rsrc):
                owner = bootstrap.interpolate(
                    pkg_resources.resource_string(
                        package_name, owner_rsrc
                    ).decode(),
                    params
                ).strip()

                try:
                    _LOGGER.info('Setting owner: %r - %r', dst_path, owner)
                    (uid, gid) = utils.get_uid_gid(owner)
                    os.chown(dst_path, uid, gid)
                except (IOError, OSError) as err:
                    if err.errno != errno.ENOENT:
                        raise

            if rec:
                rec.write('%s\n' % os.path.join(dst_path, ''))

            install_fn = _install

            # Test if is a scan dir first
            if _is_scan_dir(package, os.path.join(src_dir, item), dst_path):
                _LOGGER.info('Scan dir found: %s => %s', resource_path,
                             dst_path)
                install_fn = _install_scan_dir

            install_fn(
                package,
                os.path.join(src_dir, item),
                dst_dir,
                params,
                prefix_len=prefix_len,
                rec=rec
            )
        else:
            if resource_path.endswith('.swp'):
                continue
            if resource_path.endswith('.owner'):
                continue

            resource_str = pkg_resources.resource_string(
                package_name,
                resource_path
            )

            if rec:
                rec.write('%s\n' % dst_path)
            _update(dst_path,
                    bootstrap.render(resource_str.decode('utf8'), params))
Пример #9
0
    def __init__(self, **kwargs):
        users = kwargs.get('users', [])
        self._users = [utils.get_uid_gid(user) for user in users]
        _LOGGER.debug('Allowed uid, gid: %r', self._users)

        # TODO: add schema validation
        def authzreq(data):
            """implement AuthZPlugin.AuthZReq
            """
            if 'RequestBody' in data:
                request_body = base64.b64decode(data['RequestBody'])
                _LOGGER.debug('request body: %s', request_body)
                request_obj = json.loads(request_body.decode())
            else:
                request_obj = {}

            for plugin in self._plugins:
                (allow, msg) = plugin.run_req(data['RequestMethod'],
                                              data['RequestUri'],
                                              request_obj,
                                              users=self._users)

                if not allow:
                    break
            else:
                allow = True

            _LOGGER.info(
                'Request: %s %s %s (%s)',
                data['RequestMethod'],
                data['RequestUri'],
                ('Authorized' if allow else 'Not authorized'),
                msg,
            )

            return (allow, msg)

        # TODO: add schema validation
        def authzres(data):
            """implement AuthZPlugin.AuthZReq
            """
            if 'RequestBody' in data:
                request_body = base64.b64decode(data['RequestBody'])
                _LOGGER.debug('request body: %s', request_body)
                request_obj = json.loads(request_body.decode())
            else:
                request_obj = {}

            if 'ResponseBody' in data:
                response_body = base64.b64decode(data['ResponseBody'])
                _LOGGER.debug('response body: %s', response_body)
                response_obj = json.loads(response_body.decode())
            else:
                response_obj = {}

            for plugin in self._plugins:
                (allow, msg) = plugin.run_res(
                    data['RequestMethod'],
                    data['RequestUri'],
                    request_obj,
                    response_obj,
                    users=self._users,
                )

                if not allow:
                    break
            else:
                allow = True

            _LOGGER.info(
                'Response: %s %s %s %s',
                data['RequestMethod'],
                data['RequestUri'],
                data.get('ResponseStatusCode', None),
                ('Authorized' if allow else 'Not authorized'),
            )

            return (allow, msg)

        # TODO: add schema validation
        def activate():
            """Implement Plugin.Activate
            """
            return {'Implements': [_PLUGIN_NAME]}

        self.authzreq = authzreq
        self.authzres = authzres
        self.activate = activate