Beispiel #1
0
    def wrapper_app(*args, **kwargs):

        # If the function has an auth structure, we will use it and request the user/password
        #   using the http basic authentication
        if function_info.auth is not None:
            user, password = request.auth or (None, None)
            if user is None or not function_info.auth.check(user, password):
                err = HTTPError(401, "Authentication needed")
                err.add_header('WWW-Authenticate', 'Basic realm="Login required"')
                return err            

        # The call to the command will be in array form, so we ensure that the command is included
        parameters = []
        command = function_info.callback.command
        if type(command)==list: 
            parameters = command[:]
        elif type(command)==str:
            parameters.append(command)
        else:
            raise Exception("type of command not supported: %s" % command)

        # Now we add the parameters (in the same order that are requested in the parameter field)
        for pname in function_info.parameters:
            if pname in kwargs:
                pattern = "<%s>" % pname
                parameters = [ p.replace(pattern, kwargs[pname]) for p in parameters ]
            else:
                raise Exception('parameter %s is not defined' % pname)

        # We will pass the post information to the app as the stdin
        inputtext = request.body.readlines()

        # Finally we run the application
        errcode, output, error = runcommand.runcommand_e(parameters, False, timeout = 5, strin = ''.join(inputtext))
        return function_info.errorcodes.build_response(errcode, output, error)
Beispiel #2
0
def abort(code, body):
    if "application/json" in request.headers.get("Accept", ""):
        apireturn(code, body)
    error = HTTPError(code, body)
    for n, v in meta_headers.items():
        error.add_header(n, v)
    raise error
            def wrapper(*a, **ka):

                if required or terrariumUtils.is_true(
                        self.__terrariumEngine.config.get_system()
                    ['always_authenticate']):
                    user, password = request.auth or (None, None)
                    ip = request.remote_addr if request.get_header(
                        'X-Real-Ip') is None else request.get_header(
                            'X-Real-Ip')
                    if user is None or not check(user, password):
                        err = HTTPError(401, text)
                        err.add_header('WWW-Authenticate',
                                       'Basic realm="%s"' % realm)
                        if user is not None or password is not None:
                            self.__terrariumEngine.notification.message(
                                'authentication_warning', {
                                    'ip': ip,
                                    'username': user,
                                    'password': password
                                }, [])
                            logger.warning(
                                'Incorrect login detected using username \'{}\' and password \'{}\' from ip {}'
                                .format(user, password, ip))
                        return err

                return func(*a, **ka)
Beispiel #4
0
def abort(code, body):
    if "application/json" in request.headers.get("Accept", ""):
        apireturn(code, body)
    error = HTTPError(code, body)
    for n,v in meta_headers.items():
        error.add_header(n, v)
    raise error
Beispiel #5
0
 def wrapper(*a, **ka):
     user, password = request.auth or (None, None)
     # no authentification when composer
     if config.MODE=="gui" and (user is None or user!=config.GUI_USER or password!=config.GUI_PASSWORD):
         err = HTTPError(401, text)
         err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
         return err
     return func(*a, **ka)
Beispiel #6
0
def validate_user(app, user, password):
    if not ACCOUNT_REGISTER.has_account_for_app(app, user):
        raise HTTPError(403,
                        'No account for user {} in app {}'.format(user, app))
    if not ACCOUNT_REGISTER.password_matches(user, password):
        err = HTTPError(401, 'Invalid login')
        err.add_header('WWW-Authenticate', '')
        raise err
Beispiel #7
0
		def wrapper(*a, **ka):
			if CONFIG['protect']['status']:
				user, password = request.auth or (None, "")
				password = hashlib.sha256(password).hexdigest()
				if user is None or not (user == CONFIG['protect']['username'] and password == CONFIG['protect']['password']):
					err = HTTPError(401, text)
					err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
					return err
			return func(*a, **ka)
Beispiel #8
0
            def wrapper(*a, **ka):
                if int(self.engine.settings['always_authenticate']) != -1 and (
                        required or terrariumUtils.is_true(
                            self.engine.settings['always_authenticate'])):
                    user, password = request.auth or (None, None)
                    ip = request.remote_addr if request.get_header(
                        'X-Real-Ip') is None else request.get_header(
                            'X-Real-Ip')
                    if user is None or not check(user, password):
                        err = HTTPError(401, text)
                        err.add_header('WWW-Authenticate',
                                       f'Basic realm="{realm}"')
                        if user is not None or password is not None:
                            self.engine.notification.message(
                                'authentication_error', {
                                    'ip': ip,
                                    'username': user,
                                    'password': password
                                }, [])
                            logger.warning(
                                f'Incorrect login detected using username \'{user}\' and password \'{password}\' from ip {ip}'
                            )
                        return err

                if request.method.lower() in ['get', 'head']:
                    self.__add_caching_headers(response, request.fullpath)

                    if request.url.lower().endswith(
                            '.html') or '/' == request.fullpath:
                        user, password = request.get_cookie(
                            'auth', secret=self.cookie_secret) or (None, None)
                        if check(user, password):
                            # Update the cookie timeout so that we are staying logged in as long as we are working on the interface
                            response.set_cookie('auth',
                                                request.get_cookie(
                                                    'auth',
                                                    secret=self.cookie_secret),
                                                secret=self.cookie_secret,
                                                **{
                                                    'max_age': 3600,
                                                    'path': '/'
                                                })

                elif request.method.lower() in ['post', 'put', 'delete']:
                    response.set_cookie('no-cache',
                                        '1',
                                        secret=None,
                                        **{
                                            'max_age': 90,
                                            'path': '/'
                                        })
                    response.set_header('Cache-Control', 'no-cache')

                return func(*a, **ka)
Beispiel #9
0
 def wrapper(*a, **ka):
     user, password = request.auth or (None, None)
     if 'hooked.basicauth' in conf:
         if user is None or not check(user, password):
             err = HTTPError(401, text)
             err.add_header('WWW-Authenticate',
                            'Basic realm="%s"' % realm)
             return err
         return func(*a, **ka)
     else:
         print("No basic auth required.")
         return func(*a, **ka)
            def wrapper(*a, **ka):
                user, password = request.auth or (None, None)
                if required or terrariumUtils.is_true(
                        self.__terrariumEngine.config.get_system()
                    ['always_authenticate']):

                    if user is None or not check(user, password):
                        err = HTTPError(401, text)
                        err.add_header('WWW-Authenticate',
                                       'Basic realm="%s"' % realm)
                        return err

                return func(*a, **ka)
Beispiel #11
0
        def wrapper(*a, **ka):
            auth = config.get('DEFAULT', 'auth', fallback=None)

            if auth == 'none': return func(*a, **ka)

            user, password = request.auth or (None, None)

            if user is None or not check(user, password):
                err = HTTPError(401, text)
                err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                return err

            return func(*a, **ka)
Beispiel #12
0
def root():
    """
    Display a web-UI

    :return:
    """
    login, password = request.auth or (None, None)
    if addon.pass_protect and (login is None or (login, password) != addon.credentials):
        error = HTTPError(401, 'Access denied')
        error.add_header('WWW-Authenticate', 'Basic realm="private"')
        return error
    else:
        return template('torrents')
Beispiel #13
0
 def require_user(self, user):
     #log.debug("headers %r", request.headers.items())
     try:
         authuser, authpassword = request.auth
     except TypeError:
         log.warn("could not read auth header")
         err = HTTPError(401, "authentication required")
         err.add_header('WWW-Authenticate', 'Basic realm="devpi"')
         raise err
     log.debug("detected auth for user %r", authuser)
     try:
         val = self.signer.unsign(authpassword, self.LOGIN_EXPIRATION)
     except itsdangerous.BadData:
         abort(401, "invalid authentication for user %r" % authuser)
     if not val.startswith(authuser + "-"):
         abort(401, "mismatch credential for user %r" % authuser)
     if authuser == "root" or authuser == user:
         return
     abort(401, "user %r not authorized, requiring %r" % (authuser, user))
Beispiel #14
0
 def err():
     err = HTTPError(401, "Access denied")
     err.add_header("WWW-Authenticate", 'Basic realm="%s"' % "admin area")
     return err
Beispiel #15
0
def abort_authenticate(msg="authentication required"):
    err = HTTPError(401, msg)
    err.add_header(str('WWW-Authenticate'), 'Basic realm="pypi"')
    err.add_header(str('location'), "/+login")
    raise err
Beispiel #16
0
 def wrapper(*a, **ka):
     if not current_is_admin():
         err = HTTPError(401, "Admin permission required")
         err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
         return err
     return func(*a, **ka)
Beispiel #17
0
def abort_authenticate(msg="authentication required"):
    err = HTTPError(401, msg)
    err.add_header(str('WWW-Authenticate'), 'Basic realm="pypi"')
    err.add_header(str('location'), "/+login")
    raise err
    def _call(self):
        if request.auth not in self._credentials:
            error = HTTPError(401, "Access denied")
            error.add_header("WWW-Authenticate", 'Basic realm="private"')
            return error

        method = request.headers.get("SOAPAction")
        xml_body = etree.fromstring(request.body.read())[0]
        response.content_type = 'text/xml; charset="UTF-8"'

        valide_session_response = self._validate_session_id(method, xml_body)
        if valide_session_response is not None:
            return valide_session_response

        if method == "newSession":
            result = etree.Element("newSessionResult")
            session_id = len(self._subscribe_list)
            result.set("session-id", str(session_id))
            result.set("ifmap-publisher-id", "111")
            result.set("max-poll-result-size", str(self._ITEM_MAX_MSG_SIZE))
            self._subscribe_list.append(None)
            msg = "New session %d established." % session_id
            self._log(msg, SandeshLevel.SYS_DEBUG)
            return self._RSP_ENVELOPE % {"result": etree.tostring(result)}
        elif method == "subscribe":
            session_id = int(xml_body[0].get("session-id"))
            self._subscribe_list[session_id] = PriorityQueue()
            buffer = StringIO()
            try:
                VncIfmapServer._export_root_graph(buffer)
                self._subscribe_list[session_id].put((1, time(), "searchResult", buffer.getvalue()))
            finally:
                buffer.close()
            result = etree.Element("subscribeReceived")
            msg = "Session %d has subscribed to the root graph" % session_id
            self._log(msg, SandeshLevel.SYS_DEBUG)
            return self._RSP_ENVELOPE % {"result": etree.tostring(result)}
        elif method == "poll":
            session_id = int(xml_body[0].get("session-id"))
            queue = self._subscribe_list[session_id]
            if queue is None:
                msg = (
                    "Session ID %d did not subscribed to the graph's root. "
                    "Please subscribe before polling." % session_id
                )
                self._log(msg, SandeshLevel.SYS_WARN)
                result = etree.Element("errorResult", errorCode="AccessDenied")
                err_str = etree.SubElement(result, "errorString")
                err_str.text = msg
                return self._RSP_ENVELOPE % {"result": etree.tostring(result)}

            _, _, action, items = queue.get()
            while True:
                try:
                    _, _, new_action, new_item = queue.peek(timeout=1)
                except Empty:
                    break
                if new_action != action:
                    break
                if (len(items) + len(new_item)) > self._ITEM_MAX_MSG_SIZE:
                    break
                try:
                    items += queue.get_nowait()[3]
                except Empty:
                    break

            poll_str = '<pollResult><%s name="root">%s</%s></pollResult>' % (action, items, action)
            msg = "Session %d polled and get %s" % (session_id, action)
            self._log(msg, SandeshLevel.SYS_DEBUG)
            return self._RSP_ENVELOPE % {"result": poll_str}
        elif method == "search":
            # grab ident string; lookup graph with match meta and return
            start_name = xml_body[0][0].get("name")
            match_links = xml_body[0].get("match-links", "all")
            if match_links != "all":
                match_links = set(match_links.split(" or "))
            result_filter = xml_body[0].get("result-filter", "all")
            if result_filter != "all":
                result_filter = set(result_filter.split(" or "))

            visited_nodes = set([])
            result_items = []

            def visit_node(ident_name):
                if ident_name in visited_nodes:
                    return
                visited_nodes.add(ident_name)
                # add all metas on current to result, visit further nodes
                to_visit_nodes = set([])
                ident_str = VncIfmapServer._graph[ident_name]["ident"]
                links = VncIfmapServer._graph[ident_name]["links"]
                property_items = ""
                for link_key, link_info in links.iteritems():
                    meta_name = link_key.split()[0]
                    if "other" in link_info:
                        to_visit_nodes.add(link_key.split()[1])
                        if result_filter != "all" and meta_name in result_filter:
                            result_items.append(
                                "<resultItem>%s%s%s</resultItem>" % (ident_str, link_info["other"], link_info["meta"])
                            )
                    elif result_filter != "all" and meta_name in result_filter:
                        property_items += link_info["meta"][10:-11]
                if property_items:
                    result_items.append(
                        "<resultItem>%s<metadata>%s" "</metadata></resultItem>" % (ident_str, property_items)
                    )

                # all metas on ident walked
                for new_node in to_visit_nodes:
                    visit_node(new_node)

            # end visit_node

            visit_node(start_name)

            search_str = "<searchResult>%s</searchResult>" % "".join(result_items)
            return VncIfmapServer._RSP_ENVELOPE % {"result": search_str}
        else:
            msg = "IF-MAP method '%s' is not implemented." % method
            self._log(msg, level=SandeshLevel.SYS_DEBUG)
            result = etree.Element("errorResult", errorCode="InvalidMethod")
            err_str = etree.SubElement(result, "errorString")
            err_str.text = msg
            return self._RSP_ENVELOPE % {"result": etree.tostring(result)}
Beispiel #19
0
    def _call(self):
        if request.auth not in self._credentials:
            error = HTTPError(401, "Access denied")
            error.add_header('WWW-Authenticate', 'Basic realm="private"')
            return error

        method = request.headers.get('SOAPAction')
        xml_body = etree.fromstring(request.body.read())[0]
        response.content_type = 'text/xml; charset="UTF-8"'

        valide_session_response = self._validate_session_id(method, xml_body)
        if valide_session_response is not None:
            return valide_session_response

        if method == 'newSession':
            result = etree.Element('newSessionResult')
            session_id = len(self._subscribe_list)
            result.set("session-id", str(session_id))
            result.set("ifmap-publisher-id", "111")
            result.set("max-poll-result-size", str(self._ITEM_MAX_MSG_SIZE))
            self._subscribe_list.append(None)
            msg = "New session %d established." % session_id
            self._log(msg, SandeshLevel.SYS_DEBUG)
            return self._RSP_ENVELOPE % {'result': etree.tostring(result)}
        elif method == 'subscribe':
            session_id = int(xml_body[0].get('session-id'))
            self._subscribe_list[session_id] = PriorityQueue()
            buffer = StringIO()
            try:
                VncIfmapServer._export_root_graph(buffer)
                self._subscribe_list[session_id].put(
                    (1, time(), 'searchResult', buffer.getvalue()))
            finally:
                buffer.close()
            result = etree.Element('subscribeReceived')
            msg = "Session %d has subscribed to the root graph" % session_id
            self._log(msg, SandeshLevel.SYS_DEBUG)
            return self._RSP_ENVELOPE % {'result': etree.tostring(result)}
        elif method == 'poll':
            session_id = int(xml_body[0].get('session-id'))
            queue = self._subscribe_list[session_id]
            if queue is None:
                msg = "Session ID %d did not subscribed to the graph's root. "\
                      "Please subscribe before polling." % session_id
                self._log(msg, SandeshLevel.SYS_WARN)
                result = etree.Element('errorResult', errorCode='AccessDenied')
                err_str = etree.SubElement(result, 'errorString')
                err_str.text = msg
                return self._RSP_ENVELOPE % {'result': etree.tostring(result)}

            _, _, action, items = queue.get()
            while True:
                try:
                    _, _, new_action, new_item = queue.peek(timeout=1)
                except Empty:
                    break
                if new_action != action:
                    break
                if (len(items) + len(new_item)) > self._ITEM_MAX_MSG_SIZE:
                    break
                try:
                    items += queue.get_nowait()[3]
                except Empty:
                    break

            poll_str = ('<pollResult><%s name="root">%s</%s></pollResult>' %
                        (action, items, action))
            msg = "Session %d polled and get %s" % (session_id, action)
            self._log(msg, SandeshLevel.SYS_DEBUG)
            return self._RSP_ENVELOPE % {'result': poll_str}
        elif method == 'search':
            # grab ident string; lookup graph with match meta and return
            start_name = xml_body[0][0].get('name')
            match_links = xml_body[0].get('match-links', 'all')
            if match_links != 'all':
                match_links = set(match_links.split(' or '))
            result_filter = xml_body[0].get('result-filter', 'all')
            if result_filter != 'all':
                result_filter = set(result_filter.split(' or '))

            visited_nodes = set([])
            result_items = []
            def visit_node(ident_name):
                if ident_name in visited_nodes:
                    return
                visited_nodes.add(ident_name)
                # add all metas on current to result, visit further nodes
                to_visit_nodes = set([])
                ident_str = VncIfmapServer._graph[ident_name]['ident']
                links = VncIfmapServer._graph[ident_name]['links']
                property_items = ''
                for link_key, link_info in links.iteritems():
                    meta_name = link_key.split()[0]
                    if 'other' in link_info:
                        to_visit_nodes.add(link_key.split()[1])
                        if (result_filter != 'all' and
                                meta_name in result_filter):
                            result_items.append(
                                '<resultItem>%s%s%s</resultItem>' % (ident_str,
                                link_info['other'], link_info['meta']))
                    elif (result_filter != 'all' and
                            meta_name in result_filter):
                        property_items += link_info['meta'][10:-11]
                if property_items:
                    result_items.append('<resultItem>%s<metadata>%s'
                                        '</metadata></resultItem>' %
                                        (ident_str, property_items))

                # all metas on ident walked
                for new_node in to_visit_nodes:
                    visit_node(new_node)
            # end visit_node

            visit_node(start_name)

            search_str = ('<searchResult>%s</searchResult>' %
                          ''.join(result_items))
            return VncIfmapServer._RSP_ENVELOPE % {'result': search_str}
        else:
            msg = "IF-MAP method '%s' is not implemented." % method
            self._log(msg, level=SandeshLevel.SYS_DEBUG)
            result = etree.Element('errorResult', errorCode='InvalidMethod')
            err_str = etree.SubElement(result, 'errorString')
            err_str.text = msg
            return self._RSP_ENVELOPE % {'result': etree.tostring(result)}
Beispiel #20
0
def authenticate(session: Session,
                 node: Node,
                 header: str,
                 method: str = "GET"):

    # from bottlepy
    def tob(s, enc='utf8'):
        return s.encode(enc) if isinstance(s, str) else bytes(s)

    def touni(s, enc='utf8', err='strict'):
        if isinstance(s, bytes):
            return s.decode(enc, err)
        else:
            return str(s or ("" if s is None else s))

    raise_login = True
    realm = "user@TheOnionBox"
    auth_scheme = "TheOnionBox"

    if header != '':
        try:
            scheme, data = header.split(None, 1)
            if scheme == auth_scheme:

                # Basic Authentication
                if session['auth'] == 'basic':
                    user, pwd = touni(b64decode(tob(data))).split(':', 1)

                    if user == session.id:
                        node.controller.authenticate(password=pwd)
                        raise_login = False

                # Digest Authentication
                elif session['auth'] == 'digest':

                    # the data comes as in as 'key1="xxx...", key2="xxx...", ..., key_x="..."'
                    # therefore we split @ ', '
                    # then remove the final '"' & split @ '="'
                    # to create a nice dict.
                    request_data = dict(item[:-1].split('="')
                                        for item in data.split(", "))

                    ha1_prep = (session.id + ":" + realm + ":" +
                                node.controller.password).encode('utf-8')
                    ha1 = md5(ha1_prep).hexdigest()
                    ha2_prep = (method + ":" +
                                request_data['uri']).encode('utf-8')
                    ha2 = md5(ha2_prep).hexdigest()
                    resp_prep = (ha1 + ":{}:".format(session['nonce']) +
                                 ha2).encode('utf-8')
                    response = md5(resp_prep).hexdigest()

                    # print(response)
                    # print(request_data['response'])

                    if response == request_data['response']:
                        node.controller.authenticate(
                            password=node.controller.password)
                        raise_login = False

        except Exception as e:
            print(e)
            pass

    if raise_login:
        acc_denied = HTTPError(401, 'Access denied!')

        # Request Basic Authentication
        if session['auth'] == 'basic':
            acc_denied.add_header('WWW-Authenticate',
                                  '{} realm={}'.format(auth_scheme, realm))

        # Request Digest Authentication
        else:
            session['nonce'] = uuid1().hex
            session['opaque'] = uuid4().hex
            header = '{} realm={}, nonce={}, opaque={}'
            header = header.format(auth_scheme, realm, session['nonce'],
                                   session['opaque'])
            acc_denied.add_header('WWW-Authenticate', header)

        raise acc_denied

    # at this stage, authentication was passed!
    return node.controller.password