Esempio n. 1
0
def new_default_plugin_jail(basename):
    addrs = guess_adresses()
    if not addrs['high_ipv4']:
        raise MiddlewareError(_("Unable to determine IPv4 for plugin"))

    jailname = None
    for i in xrange(1, 1000):
        tmpname = "%s_%d" % (basename, i)
        jails = Jails.objects.filter(jail_host=tmpname)
        if not jails:
            jailname = tmpname
            break

    w = warden.Warden()

    jc = JailsConfiguration.objects.order_by("-id")[0]
    logfile = "%s/warden.log" % jc.jc_path

    try:
        w.create(
            jail=jailname,
            ipv4=addrs['high_ipv4'],
            flags=(warden.WARDEN_CREATE_FLAGS_LOGFILE
                   | warden.WARDEN_CREATE_FLAGS_PLUGINJAIL
                   | warden.WARDEN_CREATE_FLAGS_SYSLOG
                   | warden.WARDEN_CREATE_FLAGS_IPV4),
            logfile=logfile,
        )
    except Exception, e:
        raise MiddlewareError(_("Failed to install plugin: %s") % e)
Esempio n. 2
0
def get_ipv4_exclude_dict():
    ipv4_exclude_dict = {}

    w = warden.Warden()
    jails = w.cached_list()
    if not jails:
        return ipv4_exclude_dict

    for j in jails:
        mask = 24
        if j['ipv4']:
            parts = j['ipv4'].split('/')
            if len(parts) == 2:
                mask = int(parts[1])
            sc = sipcalc_type("%s/%d" % (
                parts[0],
                mask
            ))
            ipv4_exclude_dict[str(sc)] = sc

        if j['bridge_ipv4']:
            parts = j['bridge_ipv4'].split('/')
            if len(parts) == 2:
                try:
                    mask = int(parts[1])
                except ValueError:
                    pass
            sc = sipcalc_type("%s/%d" % (
                parts[0],
                mask
            ))
            ipv4_exclude_dict[str(sc)] = sc

        if j['alias_ipv4']:
            amask = mask
            aliases = j['alias_ipv4'].split(',')
            for a in aliases:
                parts = a.split('/')
                if len(parts) == 2:
                    amask = int(parts[1])
                sc = sipcalc_type("%s/%d" % (
                    parts[0],
                    amask
                ))
                ipv4_exclude_dict[str(sc)] = sc

        if j['alias_bridge_ipv4']:
            amask = mask
            aliases = j['alias_bridge_ipv4'].split(',')
            for a in aliases:
                parts = a.split('/')
                if len(parts) == 2:
                    amask = int(parts[1])
                sc = sipcalc_type("%s/%d" % (
                    parts[0],
                    amask
                ))
                ipv4_exclude_dict[str(sc)] = sc

    return ipv4_exclude_dict
Esempio n. 3
0
def get_ipv6_exclude_dict():
    ipv6_exclude_dict = {}

    w = warden.Warden()
    jails = w.cached_list()
    if not jails:
        return ipv6_exclude_dict

    for j in jails:
        prefix = 24
        if j['ipv6']:
            parts = j['ipv6'].split('/')
            if len(parts) == 2:
                prefix = int(parts[1])
            sc = sipcalc_type("%s/%d" % (
                parts[0],
                prefix
            ))
            ipv6_exclude_dict[str(sc)] = sc

        if j['bridge_ipv6']:
            parts = j['ipv6'].split('/')
            if len(parts) == 2:
                prefix = int(parts[1])
            sc = sipcalc_type("%s/%d" % (
                parts[0],
                prefix
            ))
            ipv6_exclude_dict[str(sc)] = sc

        if j['alias_ipv6']:
            aprefix = prefix
            aliases = j['alias_ipv6'].split(',')
            for a in aliases:
                parts = a.split('/')
                if len(parts) == 2:
                    aprefix = int(parts[1])
                sc = sipcalc_type("%s/%d" % (
                    parts[0],
                    aprefix
                ))
                ipv6_exclude_dict[str(sc)] = sc

        if j['alias_bridge_ipv6']:
            aprefix = prefix
            aliases = j['alias_bridge_ipv6'].split(',')
            for a in aliases:
                parts = a.split('/')
                if len(parts) == 2:
                    aprefix = int(parts[1])
                sc = sipcalc_type("%s/%d" % (
                    parts[0],
                    aprefix
                ))
                ipv6_exclude_dict[str(sc)] = sc

    return ipv6_exclude_dict
Esempio n. 4
0
def jail_auto_configure():
    import platform
    """
    Auto configure the jail settings

    The first ZFS volume found will be selected.
    A dataset called jails will be created, if it already exists then
    append "_N" where N 2..100 until a dataset is not found.
    """

    vol_fstype = 'ZFS'
    volume = Volume.objects.filter(vol_fstype='ZFS')
    if not volume.exists():
        raise MiddlewareError(_("You need to create a ZFS volume to proceed!"))

    volume = volume[0]
    basename = "%s/jails" % volume.vol_name

    name = basename
    for i in xrange(2, 100):
        datasets = list_datasets(
            path="/mnt/%s" % name,
            recursive=False,
        )
        if not datasets:
            break
        else:
            name = "%s_%d" % (basename, i)
    rv, err = notifier().create_zfs_dataset(name)
    if rv != 0:
        raise MiddlewareError(
            _("Failed to create dataset %(name)s: %(error)s") % {
                'name': name,
                'error': err,
            })

    try:
        jail = JailsConfiguration.objects.latest('id')
    except JailsConfiguration.DoesNotExist:
        jail = JailsConfiguration()
    jail.jc_path = "/mnt/%s" % name
    jail.save()

    w = warden.Warden()
    w.wtmp = jail.jc_path
    w.jdir = jail.jc_path
    w.release = platform.release().strip()
    w.save()
Esempio n. 5
0
def new_default_plugin_jail(basename):
    from freenasUI.jails.forms import generate_randomMAC, is_jail_mac_duplicate
    jc = JailsConfiguration.objects.order_by("-id")[0]
    logfile = "%s/warden.log" % jc.jc_path

    if not jc.jc_ipv4_dhcp or not jc.jc_ipv6_autoconf:
        addrs = guess_addresses()

    if not jc.jc_ipv4_dhcp:
        if not addrs['high_ipv4']:
            raise MiddlewareError(_("Unable to determine IPv4 for plugin"))

    if (jc.jc_ipv6_autoconf or jc.jc_ipv6_network):
        if not jc.jc_ipv6_autoconf:
            if not addrs['high_ipv6']:
                raise MiddlewareError(_("Unable to determine IPv6 for plugin"))

    jailname = None
    for i in range(1, 1000):
        tmpname = "%s_%d" % (basename, i)
        jails = Jails.objects.filter(jail_host=tmpname)
        if not jails:
            jailname = tmpname
            break

    w = warden.Warden()
    template_create_args = {}

    template = JailTemplate.objects.get(jt_name='pluginjail')
    template_create_args['nick'] = template.jt_name
    template_create_args['tar'] = template.jt_url
    template_create_args['flags'] = warden.WARDEN_TEMPLATE_FLAGS_CREATE | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_NICK | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_TAR
    if template.jt_mtree:
        template_create_args['mtree'] = template.jt_mtree
        template_create_args['flags'] = template_create_args['flags'] | \
            warden.WARDEN_TEMPLATE_CREATE_FLAGS_MTREE

    template = None
    template_list_flags = {}
    template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
    templates = w.template(**template_list_flags)
    for t in templates:
        if t['nick'] == template_create_args['nick']:
            template = t
            break

    os.environ[
        'EXTRACT_TARBALL_STATUSFILE'] = warden.WARDEN_EXTRACT_STATUS_FILE
    createfile = "/var/tmp/.templatecreate"
    if not template:

        # If for some reason warden does not list the template but the path
        # exists, we shall try to nuke it
        template_path = '{}/.warden-template-pluginjail'.format(jc.jc_path)
        if os.path.exists(template_path):
            try:
                notifier().destroy_zfs_dataset(
                    template_path.replace('/mnt/', ''))
            except:
                pass
            try:
                shutil.rmtree(template_path)
            except OSError:
                pass

        try:
            cf = open(createfile, "a+")
            cf.close()
            w.template(**template_create_args)

        except Exception as e:
            if os.path.exists(createfile):
                os.unlink(createfile)
            raise MiddlewareError(e)

        template_list_flags = {}
        template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
        templates = w.template(**template_list_flags)
        for t in templates:
            if t['nick'] == template_create_args['nick']:
                template = t
                break

    if not template:
        raise MiddlewareError(_('Unable to find template!'))

    try:
        high_ipv4 = "DHCP"
        if not jc.jc_ipv4_dhcp:
            high_ipv4 = addrs['high_ipv4']

        high_ipv6 = "AUTOCONF"
        if not jc.jc_ipv6_autoconf:
            high_ipv6 = addrs['high_ipv6']

        create_args = {
            'jail':
            jailname,
            'ipv4':
            high_ipv4,
            'ipv6':
            high_ipv6,
            'flags': (warden.WARDEN_CREATE_FLAGS_LOGFILE
                      | warden.WARDEN_CREATE_FLAGS_TEMPLATE
                      | warden.WARDEN_CREATE_FLAGS_VANILLA
                      | warden.WARDEN_CREATE_FLAGS_SYSLOG
                      | warden.WARDEN_CREATE_FLAGS_IPV4
                      | warden.WARDEN_CREATE_FLAGS_IPV6),
            'template':
            'pluginjail',
            'logfile':
            logfile
        }

        w.create(**create_args)

    except Exception as e:
        raise MiddlewareError(_("Failed to install plugin: %s") % e)

    jaildir = "%s/%s" % (jc.jc_path, jailname)
    with open('%s/.plugins/PLUGIN' % jaildir, 'w') as f:
        f.close()

    w.auto(jail=jailname)

    # Make sure we generate an unique mac address for the plugin jail
    while True:
        mac = generate_randomMAC()
        if not is_jail_mac_duplicate(mac):
            break
    w.set(
        jail=jailname,
        mac=mac,
        flags=warden.WARDEN_SET_FLAGS_MAC,
    )
    # Setting vnet and mac at the same time seems to confuse Warden wrapper
    w.set(
        jail=jailname,
        flags=warden.WARDEN_SET_FLAGS_VNET_ENABLE,
    )
    w.start(jail=jailname)

    obj = Jails.objects.get(jail_host=jailname)
    add_media_user_and_group(obj.jail_path)
    return obj
Esempio n. 6
0
def jail_auto_configure():
    import platform

    """
    Auto configure the jail settings

    The first ZFS volume found will be selected.
    A dataset called jails will be created, if it already exists then
    append "_N" where N 2..100 until a dataset is not found.
    """

    vol_fstype = 'ZFS'
    volume = Volume.objects.filter(vol_fstype='ZFS')
    if not volume.exists():
        log.warn("ZFS is recommended for plugins!")
        volume = Volume.objects.filter(vol_fstype='UFS')
        if not volume.exists():
            raise MiddlewareError(_("You need to create a volume to proceed!"))
        vol_fstype = 'UFS'  

    volume = volume[0]
    basename = "%s/jails" % volume.vol_name

    if vol_fstype == 'ZFS':
        name = basename
        for i in xrange(2, 100):
            datasets = list_datasets(
                path="/mnt/%s" % name,
                recursive=False,
            )
            if not datasets:
                break
            else:
                name = "%s_%d" % (basename, i)
        rv, err = notifier().create_zfs_dataset(name)
        if rv != 0:
            raise MiddlewareError(_("Failed to create dataset %(name)s: %(error)s") % {
                'name': name,
                'error': err,
            })

    elif vol_fstype == 'UFS':
        name = "/mnt/%s" % basename
        if os.path.exists(name):
            max = 1
            dirs = glob.glob("%s_*" % name)
            if dirs:
                for d in dirs:
                    parts = d.split('_')
                    if len(parts) > 1 and re.match('^[0-9]+$', parts[1]):
                        num = int(parts[1])
                        if num > max:
                            max = num

            name = "%s_%d" % (name, max + 1)

        name = name.replace('/mnt/', '')
        try:
            os.makedirs("/mnt/%s" % name)

        except Exception as e:
            raise MiddlewareError(_("Failed to create directory %(name)s: %(error)s") % {
                'name': name,
                'error': e
            })

    try:
        jail = JailsConfiguration.objects.latest('id')
    except JailsConfiguration.DoesNotExist:
        jail = JailsConfiguration()
    jail.jc_path = "/mnt/%s" % name
    jail.save()

    w = warden.Warden()
    w.wtmp = jail.jc_path
    w.jdir = jail.jc_path
    w.release = platform.release().strip()
    w.save()
Esempio n. 7
0
def new_default_plugin_jail(basename):
    addrs = guess_addresses()
    if not addrs['high_ipv4']:
        raise MiddlewareError(_("Unable to determine IPv4 for plugin"))

    jailname = None
    for i in xrange(1, 1000):
        tmpname = "%s_%d" % (basename, i)
        jails = Jails.objects.filter(jail_host=tmpname)
        if not jails:
            jailname = tmpname
            break

    w = warden.Warden()

    jc = JailsConfiguration.objects.order_by("-id")[0]
    logfile = "%s/warden.log" % jc.jc_path

    template_create_args = {}

    template = JailTemplate.objects.get(jt_name='pluginjail')
    template_create_args['nick'] = template.jt_name
    template_create_args['tar'] = template.jt_url
    template_create_args['flags'] = warden.WARDEN_TEMPLATE_FLAGS_CREATE | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_NICK | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_TAR

    template = None
    template_list_flags = {}
    template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
    templates = w.template(**template_list_flags)
    for t in templates:
        if t['nick'] == template_create_args['nick']:
            template = t
            break

    os.environ['EXTRACT_TARBALL_STATUSFILE'] = warden.WARDEN_EXTRACT_STATUS_FILE
    createfile = "/var/tmp/.templatecreate"
    if not template:
        try:
            cf = open(createfile, "a+")
            cf.close()
            w.template(**template_create_args)

        except Exception as e:
            if os.path.exists(createfile):
                os.unlink(createfile)
            raise MiddlewareError(e.message)

        template_list_flags = {}
        template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
        templates = w.template(**template_list_flags)
        for t in templates:
            if t['nick'] == template_create_args['nick']:
                template = t
                break

    if not template:
        raise MiddlewareError(_('Unable to find template!'))

    try:
        w.create(
            jail=jailname,
            ipv4=addrs['high_ipv4'],
            flags=(
                warden.WARDEN_CREATE_FLAGS_LOGFILE |
                warden.WARDEN_CREATE_FLAGS_TEMPLATE |
                warden.WARDEN_CREATE_FLAGS_VANILLA |
                warden.WARDEN_CREATE_FLAGS_SYSLOG |
                warden.WARDEN_CREATE_FLAGS_IPV4
            ),
            template='pluginjail',
            logfile=logfile,
        )
    except Exception, e:
        raise MiddlewareError(_("Failed to install plugin: %s") % e)
Esempio n. 8
0
def guess_adresses():
    high_ipv4 = None
    high_ipv6 = None

    st_ipv4_network = None
    st_ipv6_network = None

    jc = None
    try:
        jc = JailsConfiguration.objects.order_by("-id")[0]
        st_ipv4_network = sipcalc_type(jc.jc_ipv4_network)
        st_ipv6_network = sipcalc_type(jc.jc_ipv6_network)
    except Exception as e:
        log.debug("Exception caught: %s", e)

    #
    # If a jails configuration exists (as it should),
    # create sipcalc objects
    #
    if st_ipv4_network:
        high_ipv4 = sipcalc_type(
            "%s/%d" %
            (jc.jc_ipv4_network_start, st_ipv4_network.network_mask_bits))
    if st_ipv6_network:
        high_ipv6 = sipcalc_type(
            "%s/%d" %
            (jc.jc_ipv6_network_start, st_ipv6_network.prefix_length))

    #
    # Attempt to determine the primary interface network.
    # This is done so that we don't set a bridge address
    # (we leave it blank, in which case the Warden will
    # figure out the default gateway and set that up inside
    # the jail if on the same network as the host).
    #
    st_host_ipv4_network = None
    try:
        iface = notifier().guess_default_interface()
        st_ha = sipcalc_type(iface=iface)
        if not st_ha.is_ipv4():
            st_host_ipv4_network = None
        else:
            st_host_ipv4_network = sipcalc_type(
                "%s/%d" % (st_ha.network_address, st_ha.network_mask_bits))
    except Exception as e:
        log.debug("Exception caught: %s", e)

    #
    # Be extra careful, if no start and end addresses
    # are configured, take the first network address
    # and add 25 to it.
    #
    if not high_ipv4 and st_ipv4_network:
        high_ipv4 = sipcalc_type("%s/%d" % (
            st_ipv4_network.usable_range[0],
            st_ipv4_network.network_mask_bits,
        ))
        high_ipv4 += 25

    if not high_ipv6 and st_ipv6_network:
        high_ipv6 = sipcalc_type("%s/%d" % (
            st_ipv6_network.network_range[0],
            st_ipv6_network.prefix_length,
        ))
        high_ipv6 += 25

    try:
        wlist = warden.Warden().list()
    except:
        wlist = []

    for wj in wlist:
        wo = warden.WardenJail(**wj)

        st_ipv4 = None
        st_ipv6 = None

        #
        # This figures out the highest IP address currently in use
        #

        if wo.ipv4:
            st_ipv4 = sipcalc_type(wo.ipv4)
        if wo.ipv6:
            st_ipv6 = sipcalc_type(wo.ipv6)

        if st_ipv4 and st_ipv4_network is not None:
            if st_ipv4_network.in_network(st_ipv4):
                if st_ipv4 > high_ipv4:
                    high_ipv4 = st_ipv4

        if st_ipv6 and st_ipv6_network is not None:
            if st_ipv6_network.in_network(st_ipv6):
                if st_ipv6 > high_ipv6:
                    high_ipv6 = st_ipv6

    if high_ipv4 is None and st_ipv4_network is not None:
        high_ipv4 = sipcalc_type("%s/%d" % (
            st_ipv4_network.usable_range[0],
            st_ipv4_network.network_mask_bits,
        ))

    elif high_ipv4 is not None and st_ipv4_network is not None:
        high_ipv4 += 1
        if not st_ipv4_network.in_network(high_ipv4):
            high_ipv4 = None

    if high_ipv6 is None and st_ipv6_network is not None:
        high_ipv6 = sipcalc_type("%s/%d" % (
            st_ipv6_network.network_range[0],
            st_ipv6_network.prefix_length,
        ))

    elif high_ipv6 is not None and st_ipv6_network is not None:
        high_ipv6 += 1
        if not st_ipv6_network.in_network(high_ipv6):
            high_ipv6 = None

    #
    # If a network is configured for jails, and it is NOT on
    # the same network as the host, setup a bridge address.
    # (This will be the default gateway of the jail).
    #
    bridge_ipv4 = None
    if st_ipv4_network is not None and not st_host_ipv4_network:
        bridge_ipv4 = sipcalc_type("%s/%d" % (
            st_ipv4_network.usable_range[0],
            st_ipv4_network.network_mask_bits,
        ))

    bridge_ipv6 = None
    if st_ipv6_network is not None:
        bridge_ipv6 = sipcalc_type("%s/%d" % (
            st_ipv6_network.network_range[0],
            st_ipv6_network.prefix_length,
        ))

    return {
        'high_ipv4': high_ipv4,
        'high_ipv6': high_ipv6,
        'bridge_ipv4': bridge_ipv4,
        'bridge_ipv6': bridge_ipv6,
    }
Esempio n. 9
0
def new_default_plugin_jail(basename):
    jc = JailsConfiguration.objects.order_by("-id")[0]
    logfile = "%s/warden.log" % jc.jc_path

    if not jc.jc_ipv4_dhcp or not jc.jc_ipv6_autoconf:
        addrs = guess_addresses()

    if not jc.jc_ipv4_dhcp:
        if not addrs['high_ipv4']:
            raise MiddlewareError(_("Unable to determine IPv4 for plugin"))

    if (jc.jc_ipv6_autoconf or jc.jc_ipv6_network):
        if not jc.jc_ipv6_autoconf:
            if not addrs['high_ipv6']:
                raise MiddlewareError(_("Unable to determine IPv6 for plugin"))

    jailname = None
    for i in xrange(1, 1000):
        tmpname = "%s_%d" % (basename, i)
        jails = Jails.objects.filter(jail_host=tmpname)
        if not jails:
            jailname = tmpname
            break

    w = warden.Warden()
    template_create_args = {}

    template = JailTemplate.objects.get(jt_name='pluginjail')
    template_create_args['nick'] = template.jt_name
    template_create_args['tar'] = template.jt_url
    template_create_args['flags'] = warden.WARDEN_TEMPLATE_FLAGS_CREATE | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_NICK | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_TAR
    if template.jt_mtree:
        template_create_args['mtree'] = template.jt_mtree
        template_create_args['flags'] = template_create_args['flags'] | \
            warden.WARDEN_TEMPLATE_CREATE_FLAGS_MTREE

    template = None
    template_list_flags = {}
    template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
    templates = w.template(**template_list_flags)
    for t in templates:
        if t['nick'] == template_create_args['nick']:
            template = t
            break

    os.environ['EXTRACT_TARBALL_STATUSFILE'] = warden.WARDEN_EXTRACT_STATUS_FILE
    createfile = "/var/tmp/.templatecreate"
    if not template:
        try:
            cf = open(createfile, "a+")
            cf.close()
            w.template(**template_create_args)

        except Exception as e:
            if os.path.exists(createfile):
                os.unlink(createfile)
            raise MiddlewareError(e.message)

        template_list_flags = {}
        template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
        templates = w.template(**template_list_flags)
        for t in templates:
            if t['nick'] == template_create_args['nick']:
                template = t
                break

    if not template:
        raise MiddlewareError(_('Unable to find template!'))

    try:
        high_ipv4 = "DHCP"
        if not jc.jc_ipv4_dhcp:
            high_ipv4 = addrs['high_ipv4']

        high_ipv6 = "AUTOCONF"
        if not jc.jc_ipv6_autoconf:
            high_ipv6 = addrs['high_ipv6']

        create_args = {
            'jail': jailname,
            'ipv4': high_ipv4,
            'ipv6': high_ipv6,
            'flags': (
                warden.WARDEN_CREATE_FLAGS_LOGFILE |
                warden.WARDEN_CREATE_FLAGS_TEMPLATE |
                warden.WARDEN_CREATE_FLAGS_VANILLA |
                warden.WARDEN_CREATE_FLAGS_SYSLOG |
                warden.WARDEN_CREATE_FLAGS_IPV4 |
                warden.WARDEN_CREATE_FLAGS_IPV6
            ),
            'template': 'pluginjail',
            'logfile': logfile
        }

        w.create(**create_args)

    except Exception, e:
        raise MiddlewareError(_("Failed to install plugin: %s") % e)