Esempio n. 1
0
    def page(self):
        config.user.need_permission("general.see_crash_reports")

        filename = "Checkmk_Crash_%s_%s_%s.tar.gz" % \
            (urlencode(self._site_id), urlencode(self._crash_id), time.strftime("%Y-%m-%d_%H-%M-%S"))

        response.headers[
            'Content-Disposition'] = 'Attachment; filename=%s' % filename
        response.headers['Content-Type'] = 'application/x-tar'
        response.set_data(
            _pack_crash_report(self._get_serialized_crash_report()))
Esempio n. 2
0
 def show(self) -> None:
     html.open_ul()
     for group in bi.get_aggregation_group_trees():
         bulletlink(
             group, "view.py?view_name=aggr_group&aggr_group=%s" %
             urlencode(group))
     html.close_ul()
Esempio n. 3
0
 def show(self):
     group_type = self._group_type_ident()
     html.open_ul()
     for name, alias in sites.all_groups(group_type.replace("group", "")):
         url = "view.py?view_name=%s&%s=%s" % (group_type, group_type, urlencode(name))
         bulletlink(alias or name, url)
     html.close_ul()
Esempio n. 4
0
def _handle_not_authenticated() -> Response:
    if fail_silently():
        # While api call don't show the login dialog
        raise MKUnauthenticatedException(_("You are not authenticated."))

    # Redirect to the login-dialog with the current url as original target
    # Never render the login form directly when accessing urls like "index.py"
    # or "dashboard.py". This results in strange problems.
    requested_file = requested_file_name(request)
    if requested_file != "login":
        post_login_url = makeuri(request, [])
        if requested_file != "index":
            # Ensure that users start with a navigation after they have logged in
            post_login_url = makeuri_contextless(
                request, [("start_url", post_login_url)], filename="index.py"
            )
        raise HTTPRedirect(
            "%scheck_mk/login.py?_origtarget=%s" % (url_prefix(), urlencode(post_login_url))
        )

    # This either displays the login page or validates the information submitted
    # to the login form. After successful login a http redirect to the originally
    # requested page is performed.
    login_page = login.LoginPage()
    login_page.set_no_html_output(plain_error())
    login_page.handle_page()

    return response
Esempio n. 5
0
    def _wato_link(self, folder, site, hostname, where):
        if not config.wato_enabled:
            return None

        if display_options.enabled(display_options.X):
            url = "wato.py?folder=%s&host=%s" % (urlencode(folder), urlencode(hostname))
            if where == "inventory":
                url += "&mode=inventory"
                help_txt = _("Edit services")
                icon = "services"
            else:
                url += "&mode=edit_host"
                help_txt = _("Edit this host")
                icon = "wato"
            return icon, help_txt, url

        return None
Esempio n. 6
0
def robotmk_download_page() -> cmk.gui.pages.PageResult:
    user.need_permission("general.see_crash_reports")

    site_id, host_name, service_description = _get_mandatory_request_vars()

    filename = "RobotMK_report_%s_%s_%s_%s.tar.gz" % (
        urlencode(site_id),
        urlencode(host_name),
        urlencode(service_description),
        time.strftime("%Y-%m-%d_%H-%M-%S"),
    )

    response.headers[
        "Content-Disposition"] = "Attachment; filename=%s" % filename
    response.headers["Content-Type"] = "application/x-tar"
    html_content: bytes = _get_html_from_livestatus(site_id, host_name,
                                                    service_description)[0]
    response.set_data(_pack_html_content(html_content))
Esempio n. 7
0
def _redirect_for_two_factor_authentication(user_id: UserId) -> None:
    if requested_file_name(request) in (
            "user_login_two_factor",
            "user_webauthn_login_begin",
            "user_webauthn_login_complete",
    ):
        return

    if userdb.is_two_factor_login_enabled(
            user_id) and not userdb.is_two_factor_completed():
        raise HTTPRedirect("user_login_two_factor.py?_origtarget=%s" %
                           urlencode(makeuri(request, [])))
Esempio n. 8
0
    def render(self, what, row, tags, custom_vars):
        # service_check_command looks like:
        # u"check_mk_active-bi_aggr!... '-b' 'http://localhost/$HOSTNAME$' ... '-a' 'Host foobar' ..."
        if what == "service" and row.get(
                "service_check_command",
                "").startswith("check_mk_active-bi_aggr!"):
            args = row['service_check_command']
            start = args.find('-b\' \'') + 5
            end = args.find('\' ', start)
            base_url = args[start:end].rstrip('/')
            base_url = base_url.replace('$HOSTADDRESS$', row['host_address'])
            base_url = base_url.replace('$HOSTNAME$', row['host_name'])

            start = args.find('-a\' \'') + 5
            end = args.find('\' ', start)
            aggr_name = args[start:end]

            url = "%s/check_mk/view.py?view_name=aggr_single&aggr_name=%s" % \
                  (base_url, urlencode(aggr_name))

            return 'aggr', _('Open this Aggregation'), url
Esempio n. 9
0
def _check_auth_cookie(cookie_name: str) -> Optional[UserId]:
    username, session_id, cookie_hash = user_from_cookie(
        _fetch_cookie(cookie_name))
    check_parsed_auth_cookie(username, session_id, cookie_hash)

    try:
        userdb.on_access(username, session_id)
    except MKAuthException:
        del_auth_cookie()
        raise

    # Once reached this the cookie is a good one. Renew it!
    _renew_cookie(cookie_name, username, session_id)

    if requested_file_name(request) != "user_change_pw":
        result = userdb.need_to_change_pw(username)
        if result:
            raise HTTPRedirect("user_change_pw.py?_origtarget=%s&reason=%s" %
                               (urlencode(makeuri(request, [])), result))

    # Return the authenticated username
    return username
Esempio n. 10
0
    def render(self, what, row, tags, custom_vars):
        # service_check_command looks like:
        # u"check_mk_active-bi_aggr!... '-b' 'http://localhost/$HOSTNAME$' ... '-a' 'Host foobar' ..."
        if what == "service" and row.get(
                "service_check_command",
                "").startswith("check_mk_active-bi_aggr!"):
            args = row["service_check_command"]
            start = args.find("-b' '") + 5
            end = args.find("' ", start)
            base_url = args[start:end].rstrip("/")
            base_url = base_url.replace("$HOSTADDRESS$", row["host_address"])
            base_url = base_url.replace("$HOSTNAME$", row["host_name"])

            start = args.find("-a' '") + 5
            end = args.find("' ", start)
            aggr_name = args[start:end]

            url = "%s/check_mk/view.py?view_name=aggr_single&aggr_name=%s" % (
                base_url,
                urlencode(aggr_name),
            )

            return "aggr", _("Open this Aggregation"), url
Esempio n. 11
0
 def add_url(cls):
     return 'create_view_dashlet.py?name=%s&mode=create&back=%s' % \
         (urlencode(html.request.var('name')),
          urlencode(makeuri(request, [('edit', '1')])))
Esempio n. 12
0
 def add_url(cls):
     return "create_link_view_dashlet.py?name=%s&mode=create&back=%s" % (
         urlencode(request.var("name")),
         urlencode(makeuri(request, [("edit", "1")])),
     )
Esempio n. 13
0
    def show(self, width, context):
        hosts = self._get_livestatus(context)
        num_hosts = len(hosts)

        if num_hosts > 900:
            html.write_text(_("Sorry, I will not display more than 900 hosts."))
            return

        # Choose smallest square number large enough
        # to show all hosts
        n = 1
        while n * n < num_hosts:
            n += 1

        rows = int(num_hosts / n)
        lastcols = num_hosts % n
        if lastcols > 0:
            rows += 1

        # Calculate cell size (Automatic sizing with 100% does not work here)
        # This is not a 100% solution but way better than having no links
        cell_spacing = 3
        cell_size = (width - cell_spacing * n) / n
        cell_height = 2 * cell_size / 3

        # Add one cell_spacing so that the cells fill the whole snapin width.
        # The spacing of the last cell overflows on the right.
        html.open_table(class_=["hostmatrix"], style=["width:%spx" % (width + cell_spacing)])
        col, row = 1, 1
        for site, host, state, has_been_checked, worstsvc, downtimedepth in sorted(hosts):
            if col == 1:
                html.open_tr()

            if downtimedepth > 0:
                s = "d"
            elif not has_been_checked:
                s = "p"
            elif worstsvc == 2 or state == 1:
                s = "2"
            elif worstsvc == 3 or state == 2:
                s = "3"
            elif worstsvc == 1:
                s = "1"
            else:
                s = "0"
            url = "view.py?view_name=host&site=%s&host=%s" % (urlencode(site), urlencode(host))
            html.open_td(
                style=[
                    "width:%.2fpx" % (cell_size + cell_spacing),
                    "height:%.2fpx" % (cell_height + cell_spacing),
                ]
            )
            html.a(
                "",
                href=url,
                title=host,
                target="main",
                class_=["state", "state%s" % s],
                style=["width:%.2fpx;" % cell_size, "height:%.2fpx;" % cell_height],
            )
            html.close_td()

            if col == n or (row == rows and n == lastcols):
                html.open_tr()
                col = 1
                row += 1
            else:
                col += 1
        html.close_table()
Esempio n. 14
0
    def _do_login(self) -> None:
        """handle the sent login form"""
        if not request.var("_login"):
            return

        try:
            if not config.user_login:
                raise MKUserError(None,
                                  _("Login is not allowed on this site."))

            username_var = request.get_unicode_input("_username", "")
            assert username_var is not None
            username = UserId(username_var.rstrip())
            if not username:
                raise MKUserError("_username", _("Missing username"))

            password = request.var("_password", "")
            if not password:
                raise MKUserError("_password", _("Missing password"))

            default_origtarget = url_prefix() + "check_mk/"
            origtarget = request.get_url_input("_origtarget",
                                               default_origtarget)

            # Disallow redirections to:
            #  - logout.py: Happens after login
            #  - side.py: Happens when invalid login is detected during sidebar refresh
            if "logout.py" in origtarget or "side.py" in origtarget:
                origtarget = default_origtarget

            result = userdb.check_credentials(username, password)
            if result:
                # use the username provided by the successful login function, this function
                # might have transformed the username provided by the user. e.g. switched
                # from mixed case to lower case.
                username = result

                session_id = userdb.on_succeeded_login(username)

                # The login succeeded! Now:
                # a) Set the auth cookie
                # b) Unset the login vars in further processing
                # c) Redirect to really requested page
                _create_auth_session(username, session_id)

                # Never use inplace redirect handling anymore as used in the past. This results
                # in some unexpected situations. We simpy use 302 redirects now. So we have a
                # clear situation.
                # userdb.need_to_change_pw returns either False or the reason description why the
                # password needs to be changed
                change_pw_result = userdb.need_to_change_pw(username)
                if change_pw_result:
                    raise HTTPRedirect(
                        "user_change_pw.py?_origtarget=%s&reason=%s" %
                        (urlencode(origtarget), change_pw_result))
                raise HTTPRedirect(origtarget)

            userdb.on_failed_login(username)
            raise MKUserError(None, _("Invalid login"))
        except MKUserError as e:
            user_errors.add(e)
Esempio n. 15
0
def test_urlencode(inp, out):
    assert urlencode(inp) == out
Esempio n. 16
0
def _redirect_for_password_change(user_id: UserId) -> None:
    if requested_file_name(request) != "user_change_pw":
        result = userdb.need_to_change_pw(user_id)
        if result:
            raise HTTPRedirect("user_change_pw.py?_origtarget=%s&reason=%s" %
                               (urlencode(makeuri(request, [])), result))