Exemplo n.º 1
0
        def pw_form_cb(data):
            from beaker.crypto import pbkdf2
            if self.change:
                # if changing password, check the old pw is right first
                uci_data = client.get(filter=filters.foris_config)
                password_hash = uci_data.find_child("uci.foris.auth.password")
                # allow changing the password if password_hash is empty
                if password_hash:
                    password_hash = password_hash.value
                    # crypt automatically extracts salt and iterations from formatted pw hash
                    if password_hash != pbkdf2.crypt(data['old_password'], salt=password_hash):
                        return "save_result", {'wrong_old_password': True}

            uci = Uci()
            foris = Config("foris")
            uci.add(foris)
            auth = Section("auth", "config")
            foris.add(auth)
            # use 48bit pseudo-random salt internally generated by pbkdf2
            new_password_hash = pbkdf2.crypt(data['password'], iterations=1000)
            auth.add(Option("password", new_password_hash))

            if data['set_system_pw'] is True:
                client.set_password("root", data['password'])

            return "edit_config", uci
Exemplo n.º 2
0
        def pw_form_cb(data):
            from beaker.crypto import pbkdf2
            if self.change:
                # if changing password, check the old pw is right first
                uci_data = client.get(filter=filters.foris_config)
                password_hash = uci_data.find_child("uci.foris.auth.password")
                # allow changing the password if password_hash is empty
                if password_hash:
                    password_hash = password_hash.value
                    # crypt automatically extracts salt and iterations from formatted pw hash
                    if password_hash != pbkdf2.crypt(data['old_password'],
                                                     salt=password_hash):
                        return "save_result", {'wrong_old_password': True}

            uci = Uci()
            foris = Config("foris")
            uci.add(foris)
            auth = Section("auth", "config")
            foris.add(auth)
            # use 48bit pseudo-random salt internally generated by pbkdf2
            new_password_hash = pbkdf2.crypt(data['password'], iterations=1000)
            auth.add(Option("password", new_password_hash))

            if data['set_system_pw'] is True:
                client.set_password("root", data['password'])

            return "edit_config", uci
Exemplo n.º 3
0
Arquivo: lan.py Projeto: chlordk/foris
        def lan_form_cb(data):
            uci = Uci()
            config = Config("dhcp")
            uci.add(config)

            dhcp = Section("lan", "dhcp")
            config.add(dhcp)
            # FIXME: this would overwrite any unrelated DHCP options the user might have set.
            # Maybe we should get the current values, scan them and remove selectively the ones
            # with 6 in front of them? Or have some support for higher level of stuff in nuci.
            options = List("dhcp_option")
            options.add(Value(0, "6," + data['lan_ipaddr']))
            dhcp.add_replace(options)
            network = Config("network")
            uci.add(network)
            interface = Section("lan", "interface")
            network.add(interface)
            interface.add(Option("ipaddr", data['lan_ipaddr']))
            if data['dhcp_enabled']:
                dhcp.add(Option("ignore", "0"))
                dhcp.add(Option("start", data['dhcp_min']))
                dhcp.add(Option("limit", data['dhcp_max']))
            else:
                dhcp.add(Option("ignore", "1"))

            # qos data
            qos = {'enabled': False}
            if 'guest_network_shapping' in data and data['guest_network_shapping']:
                qos['enabled'] = True
                qos['download'] = data['guest_network_download']
                qos['upload'] = data['guest_network_upload']

            # update guest network configs
            guest_enabled = data.get("guest_network_enabled")
            guest_network_subnet = data.get("guest_network_subnet")
            if guest_network_subnet:
                network, prefix = data.get("guest_network_subnet").split("/")
            else:
                network, prefix = DEFAULT_GUEST_NETWORK, DEFAULT_GUEST_PREFIX

            # disable guest wifi when guest network is not enabled
            data = client.get(filter=wifi_filter())
            card_count = 0
            while data.find_child("uci.wireless.@wifi-device[%d]" % card_count):
                card_count += 1
            if not guest_enabled and card_count > 0:
                wireless = uci.add(Config("wireless"))
                for i in range(card_count):
                    guest_iface = wireless.add(Section("guest_iface_%d" % i, "wifi-iface"))
                    guest_iface.add(Option("disabled", "1"))

            guest_interfaces = ["guest_turris_%d" % e for e in range(card_count)]

            LanHandler.prepare_guest_configs(
                uci, guest_enabled, network, prefix, guest_interfaces, qos)

            return "edit_config", uci
Exemplo n.º 4
0
        def wifi_form_cb(data):
            uci = Uci()
            wireless = Config("wireless")
            uci.add(wireless)

            guest_wifi_enabled = False
            for radio in radios:
                if self._prepare_radio_cb(data, wireless, radio):
                    guest_wifi_enabled = True

            guest_interfaces = ["guest_turris_%s" % e for e in sorted(radios)]

            # test whether it is required to pass update guest network
            current_data = client.get(filter=filters.wifi_filter())
            current_enabled = preprocessors.guest_network_enabled(current_data)
            if guest_wifi_enabled and not current_enabled:
                # Guest network handling
                guest_network_subnet = data.get("guest_network_subnet")
                if guest_network_subnet:
                    network, prefix = data.get("guest_network_subnet").split(
                        "/")
                else:
                    network, prefix = DEFAULT_GUEST_NETWORK, DEFAULT_GUEST_PREFIX
                LanHandler.prepare_guest_configs(uci, True, network, prefix,
                                                 guest_interfaces)
            elif guest_wifi_enabled:
                # try to update guest interfaces if the differs
                stored = current_data.find_child(
                    "uci.network.guest_turris.ifname")
                if not stored or set(
                        stored.value.split(" ")) != set(guest_interfaces):
                    network_conf = uci.add(Config("network"))
                    interface_section = network_conf.add(
                        Section("guest_turris", "interface"))
                    interface_section.add(
                        Option("ifname", " ".join(guest_interfaces)))

            return "edit_config", uci
Exemplo n.º 5
0
    def get_form(self):
        stats = client.get(filter=filters.stats).find_child("stats")
        cards = self._get_wireless_cards(stats)

        if not cards:
            return None

        wifi_form = fapi.ForisForm("wifi",
                                   self.data,
                                   filter=filters.wifi_filter())

        # Create mapping of radio_name -> iface_index
        radio_to_iface = self._get_radio_to_iface(wifi_form)

        # Add header section (used for page title)
        wifi_form.add_section(
            name="wifi",
            title=_(self.userfriendly_title),
            description=
            _("If you want to use your router as a Wi-Fi access point, enable Wi-Fi "
              "here and fill in an SSID (the name of the access point) and a "
              "corresponding password. You can then set up your mobile devices, "
              "using the QR code available next to the form."))

        # Add wifi section
        wifi_section = wifi_form.add_section(
            name="wifi_settings",
            title=_("Wi-Fi settings"),
        )

        # Get list of available radios
        radios = self._get_radios(cards, wifi_section, radio_to_iface,
                                  self.data or {}, wifi_form.nuci_config())

        def wifi_form_cb(data):
            uci = Uci()
            wireless = Config("wireless")
            uci.add(wireless)

            guest_wifi_enabled = False
            for radio in radios:
                if self._prepare_radio_cb(data, wireless, radio):
                    guest_wifi_enabled = True

            guest_interfaces = ["guest_turris_%s" % e for e in sorted(radios)]

            # test whether it is required to pass update guest network
            current_data = client.get(filter=filters.wifi_filter())
            current_enabled = preprocessors.guest_network_enabled(current_data)
            if guest_wifi_enabled and not current_enabled:
                # Guest network handling
                guest_network_subnet = data.get("guest_network_subnet")
                if guest_network_subnet:
                    network, prefix = data.get("guest_network_subnet").split(
                        "/")
                else:
                    network, prefix = DEFAULT_GUEST_NETWORK, DEFAULT_GUEST_PREFIX
                LanHandler.prepare_guest_configs(uci, True, network, prefix,
                                                 guest_interfaces)
            elif guest_wifi_enabled:
                # try to update guest interfaces if the differs
                stored = current_data.find_child(
                    "uci.network.guest_turris.ifname")
                if not stored or set(
                        stored.value.split(" ")) != set(guest_interfaces):
                    network_conf = uci.add(Config("network"))
                    interface_section = network_conf.add(
                        Section("guest_turris", "interface"))
                    interface_section.add(
                        Option("ifname", " ".join(guest_interfaces)))

            return "edit_config", uci

        wifi_form.add_callback(wifi_form_cb)

        return wifi_form
Exemplo n.º 6
0
    def get_form(self):
        pkg_list = client.get(filter=filters.updater).find_child("updater").pkg_list

        package_lists_form = fapi.ForisForm("package_lists", self.data,
                                            filter=create_config_filter("updater"))
        package_lists_main = package_lists_form.add_section(
            name="select_package_lists",
            title=_(self.userfriendly_title),
            description=_("Updater is a service that keeps all TurrisOS "
                          "software up to date. Apart from the standard "
                          "installation, you can optionally select lists of "
                          "additional software that'd be installed on the "
                          "router. This software can be selected from the "
                          "following list. "
                          "Please note that only software that is part of "
                          "TurrisOS or that has been installed from a package "
                          "list is maintained by Updater. Software that has "
                          "been installed manually or using opkg is not "
                          "affected.")
        )

        def make_preproc(list_name):
            """Make function for preprocessing value of single pkglist."""
            def preproc(list):
                enabled_names = map(lambda x: x.content, list.children)
                return list_name in enabled_names
            return preproc

        for pkg_list_item in pkg_list:
            package_lists_main.add_field(
                Checkbox,
                name="install_%s" % pkg_list_item.name,
                label=pkg_list_item.title,
                hint=pkg_list_item.description,
                nuci_path="uci.updater.pkglists.lists",
                nuci_preproc=make_preproc(pkg_list_item.name)
            )

        def package_lists_form_cb(data):
            uci = Uci()
            updater = Config("updater")
            uci.add(updater)

            pkglists = Section("pkglists", "pkglists")
            updater.add(pkglists)
            lists = List("lists")

            # create List with selected packages
            i = 0
            for k, v in data.iteritems():
                if v and k.startswith("install_"):
                    lists.add(Value(i, k[8:]))
                    i += 1
            if i == 0:
                pkglists.add_removal(lists)
            else:
                pkglists.add_replace(lists)

            return "edit_config", uci

        def package_lists_run_updater_cb(data):
            logger.info("Checking for updates.")
            client.check_updates()
            return "none", None

        package_lists_form.add_callback(package_lists_form_cb)
        package_lists_form.add_callback(package_lists_run_updater_cb)
        return package_lists_form
Exemplo n.º 7
0
    def get_form(self):
        stats = client.get(filter=filters.stats).find_child("stats")
        if len(stats.data['wireless-cards']) < 1:
            return None

        wifi_form = fapi.ForisForm("wifi", self.data,
                                   filter=create_config_filter("wireless"))
        wifi_main = wifi_form.add_section(
            name="set_wifi",
            title=_(self.userfriendly_title),
            description=_("If you want to use your router as a Wi-Fi access point, enable Wi-Fi "
                          "here and fill in an SSID (the name of the access point) and a "
                          "corresponding password. You can then set up your mobile devices, "
                          "using the QR code available next to the form.")
        )
        wifi_main.add_field(Hidden, name="iface_section", nuci_path="uci.wireless.@wifi-iface[0]",
                            nuci_preproc=lambda val: val.name)
        wifi_main.add_field(Checkbox, name="wifi_enabled", label=_("Enable Wi-Fi"), default=True,
                            nuci_path="uci.wireless.@wifi-iface[0].disabled",
                            nuci_preproc=lambda val: not bool(int(val.value)))
        wifi_main.add_field(Textbox, name="ssid", label=_("SSID"),
                            nuci_path="uci.wireless.@wifi-iface[0].ssid",
                            required=True, validators=validators.ByteLenRange(1, 32))\
            .requires("wifi_enabled", True)
        wifi_main.add_field(Checkbox, name="ssid_hidden", label=_("Hide SSID"), default=False,
                            nuci_path="uci.wireless.@wifi-iface[0].hidden",
                            hint=_("If set, network is not visible when scanning for available "
                                   "networks."))\
            .requires("wifi_enabled", True)

        channels_2g4 = [("auto", _("auto"))]
        channels_5g = []
        for channel in stats.data['wireless-cards'][0]['channels']:
            if channel['disabled']:
                continue
            pretty_channel = "%s (%s MHz)" % (channel['number'], channel['frequency'])
            if channel['frequency'] < 2500:
                channels_2g4.append((str(channel['number']), pretty_channel))
            else:
                channels_5g.append((str(channel['number']), pretty_channel))

        is_dual_band = False
        # hwmode choice for dual band devices
        if len(channels_2g4) > 1 and len(channels_5g) > 1:
            is_dual_band = True
            wifi_main.add_field(Radio, name="hwmode", label=_("Wi-Fi mode"), default="11ng",
                                args=(("11g", "2.4 GHz (g)"), ("11a", "5 GHz (a)")),
                                nuci_path="uci.wireless.radio0.hwmode",
                                nuci_preproc=lambda x: x.value.replace("n", ""),  # old configs used
                                                                                  # 11ng/11na
                                hint=_("The 2.4 GHz band is more widely supported by clients, but "
                                       "tends to have more interference. The 5 GHz band is a newer"
                                       " standard and may not be supported by all your devices. It "
                                       "usually has less interference, but the signal does not "
                                       "carry so well indoors."))\
                .requires("wifi_enabled", True)
        wifi_main.add_field(
            Dropdown, name="htmode", label=_("802.11n mode"),
            args=(("NOHT", _("Disabled")),
                  ("HT20", _("Enabled (20 MHz wide channel)")),
                  ("HT40", _("Enabled (40 MHz wide channel)"))),
            nuci_path="uci.wireless.radio0.htmode",
            hint=_("Change this to adjust 802.11n mode of operation. 802.11n with 40 MHz wide "
                   "channels can yield higher throughput but can cause more interference in the "
                   "network. If you don't know what to choose, use the default option with "
                   "20 MHz wide channel.")
        ).requires("wifi_enabled", True)
        # 2.4 GHz channels
        if len(channels_2g4) > 1:
            field_2g4 = wifi_main.add_field(Dropdown, name="channel2g4", label=_("Network channel"),
                                            default=channels_2g4[0][0], args=channels_2g4,
                                            nuci_path="uci.wireless.radio0.channel")\
                .requires("wifi_enabled", True)
            if is_dual_band:
                field_2g4.requires("hwmode", "11g")
        # 5 GHz channels
        if len(channels_5g) > 1:
            field_5g = wifi_main.add_field(Dropdown, name="channel5g", label=_("Network channel"),
                                           default=channels_5g[0][0], args=channels_5g,
                                           nuci_path="uci.wireless.radio0.channel")\
                .requires("wifi_enabled", True)
            if is_dual_band:
                field_5g.requires("hwmode", "11a")
        wifi_main.add_field(Password, name="key", label=_("Network password"),
                            nuci_path="uci.wireless.@wifi-iface[0].key",
                            required=True,
                            validators=validators.ByteLenRange(8, 63),
                            hint=_("WPA2 pre-shared key, that is required to connect to the "
                                   "network. Minimum length is 8 characters."))\
            .requires("wifi_enabled", True)

        def wifi_form_cb(data):
            uci = Uci()
            wireless = Config("wireless")
            uci.add(wireless)

            iface = Section(data['iface_section'], "wifi-iface")
            wireless.add(iface)
            device = Section("radio0", "wifi-device")
            wireless.add(device)
            # we must toggle both wifi-iface and device
            iface.add(Option("disabled", not data['wifi_enabled']))
            device.add(Option("disabled", not data['wifi_enabled']))
            if data['wifi_enabled']:
                iface.add(Option("ssid", data['ssid']))
                iface.add(Option("hidden", data['ssid_hidden']))
                iface.add(Option("encryption", "psk2+tkip+aes"))
                iface.add(Option("key", data['key']))
                if data.get('channel2g4'):
                    channel = data['channel2g4']
                elif data.get('channel5g'):
                    channel = data['channel5g']
                else:
                    logger.critical("Saving form without Wi-Fi channel: %s", data)
                    channel = "auto"
                hwmode = data.get('hwmode')
                if hwmode:
                    # change hwmode only if we had the choice
                    device.add(Option("hwmode", hwmode))
                device.add(Option("htmode", data['htmode']))
                # channel is in wifi-device section
                device.add(Option("channel", channel))
            else:
                pass  # wifi disabled

            return "edit_config", uci

        wifi_form.add_callback(wifi_form_cb)

        return wifi_form
Exemplo n.º 8
0
 def __init__(self, *args, **kwargs):
     super(UpdaterHandler, self).__init__(*args, **kwargs)
     lazy_cache.nuci_updater = lambda: client.get(filter=filters.updater
                                                  ).find_child("updater")
Exemplo n.º 9
0
def get_stats_dict():
    try:
        return get(filter=filters.stats).find_child("stats").data
    except (RPCError, TimeoutExpiredError):
        return {}