Example #1
0
def parse_cookie(name, seed, kaka):
    """Parses and verifies a cookie value

    :param seed: A seed used for the HMAC signature
    :param kaka: The cookie
    :return: A tuple consisting of (payload, timestamp)
    """
    if not kaka:
        return None

    cookie_obj = SimpleCookie(kaka)
    morsel = cookie_obj.get(name)

    if morsel:
        parts = morsel.value.split("|")
        if len(parts) != 3:
            return None
            # verify the cookie signature
        sig = cookie_signature(seed, parts[0], parts[1])
        if sig != parts[2]:
            raise SAMLError("Invalid cookie signature")

        try:
            return parts[0].strip(), parts[1]
        except KeyError:
            return None
    else:
        return None
Example #2
0
def parse_cookie(name, seed, kaka):
    """Parses and verifies a cookie value

    :param seed: A seed used for the HMAC signature
    :param kaka: The cookie
    :return: A tuple consisting of (payload, timestamp)
    """
    if not kaka:
        return None

    cookie_obj = SimpleCookie(kaka)
    morsel = cookie_obj.get(name)

    if morsel:
        parts = morsel.value.split("|")
        if len(parts) != 3:
            return None
            # verify the cookie signature
        sig = cookie_signature(seed, parts[0], parts[1])
        if sig != parts[2]:
            raise SAMLError("Invalid cookie signature")

        try:
            return parts[0].strip(), parts[1]
        except KeyError:
            return None
    else:
        return None
Example #3
0
    def _load_session(self, environ):
        session = None

        try:
            # Attempt to load existing cookie from environ
            C = SimpleCookie(environ.get('HTTP_COOKIE'))
            morsel = C.get(self._cookie_key)
        except CookieError:
            morsel = None

        if morsel is not None:
            try:
                # Attempt to decrypt and decode
                session_data = self._crypto.decrypt(morsel.value.encode('ascii'), ttl=self._session_ttl)
                session = self._session_cls(self._serializer.decode(self._compressor[1](session_data)))
            except (InvalidToken, SessionSerializerException, zlib.error):
                # Start anew
                session = self._session_cls()
                # And ensure invalid cookie is overwritten
                session.save()

        if session is None:
            session = self._session_cls()

        return session
Example #4
0
def cookie_parts(name, kaka):
    cookie_obj = SimpleCookie(kaka)
    morsel = cookie_obj.get(name)
    if morsel:
        return morsel.value.split("|")
    else:
        return None
Example #5
0
def cookie_parts(name, kaka):
    cookie_obj = SimpleCookie(kaka)
    morsel = cookie_obj.get(name)
    if morsel:
        return morsel.value.split("|")
    else:
        return None
Example #6
0
def delete_cookie(environ, name):
    kaka = environ.get("HTTP_COOKIE", "")
    logger.debug("delete KAKA: %s", kaka)
    if kaka:
        cookie_obj = SimpleCookie(kaka)
        morsel = cookie_obj.get(name, None)
        cookie = SimpleCookie()
        cookie[name] = ""
        cookie[name]["path"] = "/"
        logger.debug("Expire: %s", morsel)
        cookie[name]["expires"] = _expiration("dawn")
        return tuple(cookie.output().split(": ", 1))
    return None
Example #7
0
def delete_cookie(environ, name):
    kaka = environ.get("HTTP_COOKIE", '')
    logger.debug("delete KAKA: %s", kaka)
    if kaka:
        cookie_obj = SimpleCookie(kaka)
        morsel = cookie_obj.get(name, None)
        cookie = SimpleCookie()
        cookie[name] = ""
        cookie[name]['path'] = "/"
        logger.debug("Expire: %s", morsel)
        cookie[name]["expires"] = _expiration("dawn")
        return tuple(cookie.output().split(": ", 1))
    return None
Example #8
0
def info_from_cookie(kaka):
    logger.debug("KAKA: %s", kaka)
    if kaka:
        cookie_obj = SimpleCookie(kaka)
        morsel = cookie_obj.get("idpauthn", None)
        if morsel:
            try:
                key, ref = base64.b64decode(morsel.value).split(":")
                return IDP.cache.uid2user[key], ref
            except (KeyError, TypeError):
                return None, None
        else:
            logger.debug("No idpauthn cookie")
    return None, None
Example #9
0
def info_from_cookie(kaka):
    logger.debug("KAKA: %s", kaka)
    if kaka:
        cookie_obj = SimpleCookie(kaka)
        morsel = cookie_obj.get("idpauthn", None)
        if morsel:
            try:
                key, ref = base64.b64decode(morsel.value).split(":")
                return IDP.cache.uid2user[key], ref
            except (KeyError, TypeError):
                return None, None
        else:
            logger.debug("No idpauthn cookie")
    return None, None
Example #10
0
 def delete_cookie(self, environ):
     cookie = environ.get("HTTP_COOKIE", '')
     logger.debug("delete cookie: %s", cookie)
     if cookie:
         _name = self.cookie_name
         cookie_obj = SimpleCookie(cookie)
         morsel = cookie_obj.get(_name, None)
         cookie = SimpleCookie()
         cookie[_name] = ""
         cookie[_name]['path'] = "/"
         logger.debug("Expire: %s", morsel)
         cookie[_name]["expires"] = _expiration("now")
         return cookie.output().split(": ", 1)
     return None
Example #11
0
 def delete_cookie(self, environ):
     cookie = environ.get("HTTP_COOKIE", "")
     logger.debug("delete cookie: %s", cookie)
     if cookie:
         _name = self.cookie_name
         cookie_obj = SimpleCookie(cookie)
         morsel = cookie_obj.get(_name, None)
         cookie = SimpleCookie()
         cookie[_name] = ""
         cookie[_name]["path"] = "/"
         logger.debug("Expire: %s", morsel)
         cookie[_name]["expires"] = _expiration("now")
         return cookie.output().split(": ", 1)
     return None
Example #12
0
    def get_user(self, environ):
        cookie = environ.get("HTTP_COOKIE", '')
        logger.debug("Cookie: %s", cookie)
        if cookie:
            cookie_obj = SimpleCookie(cookie)
            morsel = cookie_obj.get(self.cookie_name, None)
            if morsel:
                try:
                    return self.uid2user[morsel.value]
                except KeyError:
                    return None
            else:
                logger.debug("No %s cookie", self.cookie_name)

        return None
Example #13
0
    def get_user(self, environ):
        cookie = environ.get("HTTP_COOKIE", "")
        logger.debug("Cookie: %s", cookie)
        if cookie:
            cookie_obj = SimpleCookie(cookie)
            morsel = cookie_obj.get(self.cookie_name, None)
            if morsel:
                try:
                    return self.uid2user[morsel.value]
                except KeyError:
                    return None
            else:
                logger.debug("No %s cookie", self.cookie_name)

        return None
Example #14
0
 def _websocket_auth(self, queue_events_data: Dict[str, Dict[str, str]],
                     cookies: SimpleCookie) -> Generator[str, str, None]:
     message = {
         "req_id": self._get_request_id(),
         "type": "auth",
         "request": {
             "csrf_token": cookies.get(settings.CSRF_COOKIE_NAME),
             "queue_id": queue_events_data['queue_id'],
             "status_inquiries": []
         }
     }
     auth_frame_str = ujson.dumps(message)
     self.ws.write_message(ujson.dumps([auth_frame_str]))
     response_ack = yield self.ws.read_message()
     response_message = yield self.ws.read_message()
     raise gen.Return([response_ack, response_message])
Example #15
0
 def _websocket_auth(self, queue_events_data: Dict[str, Dict[str, str]],
                     cookies: SimpleCookie) -> Generator[str, str, None]:
     message = {
         "req_id": self._get_request_id(),
         "type": "auth",
         "request": {
             "csrf_token": cookies.get(settings.CSRF_COOKIE_NAME),
             "queue_id": queue_events_data['queue_id'],
             "status_inquiries": []
         }
     }
     auth_frame_str = ujson.dumps(message)
     self.ws.write_message(ujson.dumps([auth_frame_str]))
     response_ack = yield self.ws.read_message()
     response_message = yield self.ws.read_message()
     raise gen.Return([response_ack, response_message])
Example #16
0
def info_from_cookie(kaka):
    logger.debug("KAKA: %s", kaka)
    if kaka:
        cookie_obj = SimpleCookie(kaka)
        morsel = cookie_obj.get("idpauthn", None)
        if morsel:
            try:
                data = base64.b64decode(morsel.value)
                if not isinstance(data, six.string_types):
                    data = data.decode("ascii")
                key, ref = data.split(":", 1)
                return IDP.cache.uid2user[key], ref
            except (KeyError, TypeError):
                return None, None
        else:
            logger.debug("No idpauthn cookie")
    return None, None
Example #17
0
class HTTP(object):
    HTTPError = HTTPError

    def __init__(self, script):
        self.script = script
        if script:  # For testing purposes
            self.logger = PrefixLoggerAdapter(script.logger, "http")
        self.headers = {}
        self.cookies = None
        self.session_started = False
        self.request_id = 1
        self.session_id = None
        self.request_middleware = None
        if self.script:  # For testing purposes
            self.setup_middleware()

    def get_url(self, path):
        address = self.script.credentials["address"]
        port = self.script.credentials.get("http_port")
        if port:
            address += ":%s" % port
        proto = self.script.credentials.get("http_protocol", "http")
        return "%s://%s%s" % (proto, address, path)

    def get(self,
            path,
            headers=None,
            cached=False,
            json=False,
            eof_mark=None,
            use_basic=False):
        """
        Perform HTTP GET request
        :param path: URI
        :param headers: Dict of additional headers
        :param cached: Cache result
        :param json: Decode json if set to True
        :param eof_mark: Waiting eof_mark in stream for end session (perhaps device return length 0)
        :param use_basic: Use basic authentication
        """
        self.ensure_session()
        self.request_id += 1
        self.logger.debug("GET %s", path)
        if cached:
            cache_key = "get_%s" % path
            r = self.script.root.http_cache.get(cache_key)
            if r is not None:
                self.logger.debug("Use cached result")
                return r
        user, password = None, None
        if use_basic:
            user = self.script.credentials.get("user")
            password = self.script.credentials.get("password")
        # Apply GET middleware
        url = self.get_url(path)
        hdr = self._get_effective_headers(headers)
        if self.request_middleware:
            for mw in self.request_middleware:
                url, _, hdr = mw.process_get(url, "", hdr)
        code, headers, result = fetch_sync(
            url,
            headers=hdr,
            request_timeout=60,
            follow_redirects=True,
            allow_proxy=False,
            validate_cert=False,
            eof_mark=eof_mark,
            user=user,
            password=password,
        )
        if not 200 <= code <= 299:
            raise HTTPError(msg="HTTP Error (%s)" % result[:256], code=code)
        self._process_cookies(headers)
        if json:
            try:
                result = ujson.loads(result)
            except ValueError as e:
                raise HTTPError("Failed to decode JSON: %s", e)
        self.logger.debug("Result: %r", result)
        if cached:
            self.script.root.http_cache[cache_key] = result
        return result

    def post(self,
             path,
             data,
             headers=None,
             cached=False,
             json=False,
             eof_mark=None,
             use_basic=False):
        """
        Perform HTTP GET request
        :param path: URI
        :param headers: Dict of additional headers
        :param cached: Cache result
        :param json: Decode json if set to True
        :param eof_mark: Waiting eof_mark in stream for end session (perhaps device return length 0)
        :param use_basic: Use basic authentication
        """
        self.ensure_session()
        self.request_id += 1
        self.logger.debug("POST %s %s", path, data)
        if cached:
            cache_key = "post_%s" % path
            r = self.script.root.http_cache.get(cache_key)
            if r is not None:
                self.logger.debug("Use cached result")
                return r
        user, password = None, None
        if use_basic:
            user = self.script.credentials.get("user")
            password = self.script.credentials.get("password")
        # Apply POST middleware
        url = self.get_url(path)
        hdr = self._get_effective_headers(headers)
        if self.request_middleware:
            for mw in self.request_middleware:
                url, data, hdr = mw.process_post(url, data, hdr)
        code, headers, result = fetch_sync(
            url,
            method="POST",
            body=data,
            headers=hdr,
            request_timeout=60,
            follow_redirects=True,
            allow_proxy=False,
            validate_cert=False,
            eof_mark=eof_mark,
            user=user,
            password=password,
        )
        if not 200 <= code <= 299:
            raise HTTPError(msg="HTTP Error (%s)" % result[:256], code=code)
        self._process_cookies(headers)
        if json:
            try:
                return ujson.loads(result)
            except ValueError as e:
                raise HTTPError(msg="Failed to decode JSON: %s" % e)
        self.logger.debug("Result: %r", result)
        if cached:
            self.script.root.http_cache[cache_key] = result
        return result

    def close(self):
        if self.session_started:
            self.shutdown_session()

    def _process_cookies(self, headers):
        """
        Process and store cookies from response headers
        :param headers:
        :return:
        """
        cdata = headers.get("Set-Cookie")
        if not cdata:
            return
        if not self.cookies:
            self.cookies = SimpleCookie()
        self.cookies.load(cdata)

    def get_cookie(self, name):
        """
        Get cookie name by value
        :param name:
        :return: Morsel object or None
        """
        if not self.cookies:
            return None
        return self.cookies.get(name)

    def _get_effective_headers(self, headers):
        """
        Append session headers when necessary. Apply effective cookies
        :param headers:
        :return:
        """
        if self.headers:
            if headers:
                headers = headers.copy()
            else:
                headers = {}
            headers.update(self.headers)
        elif not headers and self.cookies:
            headers = {}
        if self.cookies:
            headers["Cookie"] = self.cookies.output(header="").lstrip()
        return headers

    def set_header(self, name, value):
        """
        Set HTTP header to be set with all following requests
        :param name:
        :param value:
        :return:
        """
        self.logger.debug("Set header: %s = %s", name, value)
        self.headers[name] = str(value)

    def set_session_id(self, session_id):
        """
        Set session_id to be reused by middleware
        :param session_id:
        :return: None
        """
        if session_id is not None:
            self.session_id = session_id
        else:
            self.session_id = None

    def ensure_session(self):
        if not self.session_started:
            self.session_started = True
            self.setup_session()

    def setup_session(self):
        if self.script.profile.setup_http_session:
            self.logger.debug("Setup http session")
            self.script.profile.setup_http_session(self.script)

    def shutdown_session(self):
        if self.script.profile.shutdown_http_session:
            self.logger.debug("Shutdown http session")
            self.script.profile.shutdown_http_session(self.script)

    def setup_middleware(self):
        mw_list = self.script.profile.get_http_request_middleware(self.script)
        if not mw_list:
            return
        self.request_middleware = []
        for mw_cfg in mw_list:
            if isinstance(mw_cfg, tuple):
                name, cfg = mw_cfg
            else:
                name, cfg = mw_cfg, {}
            if "." in name:
                # Handler
                mw_cls = get_handler(name)
                assert mw_cls
                assert issubclass(mw_cls, BaseMiddleware)
            else:
                # Middleware name
                mw_cls = loader.get_class(name)
            self.request_middleware += [mw_cls(self, **cfg)]