Beispiel #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
Beispiel #2
0
def make_cookie(name, load, seed, expire=0, domain="",  path="",
                timestamp=""):
    """
    Create and return a cookie

    :param name: Cookie name
    :param load: Cookie load
    :param seed: A seed for the HMAC function
    :param expire: Number of minutes before this cookie goes stale
    :param domain: The domain of the cookie
    :param path: The path specification for the cookie
    :return: A tuple to be added to headers
    """
    cookie = SimpleCookie()
    if not timestamp:
        timestamp = str(int(time.mktime(time.gmtime())))
    signature = cookie_signature(seed, load, timestamp)
    cookie[name] = "|".join([load, timestamp, signature])
    if path:
        cookie[name]["path"] = path
    if domain:
        cookie[name]["domain"] = domain
    if expire:
        cookie[name]["expires"] = _expiration(expire,
                                              "%a, %d-%b-%Y %H:%M:%S GMT")

    return tuple(cookie.output().split(": ", 1))
Beispiel #3
0
def cookie_parts(name, kaka):
    cookie_obj = SimpleCookie(kaka)
    morsel = cookie_obj.get(name)
    if morsel:
        return morsel.value.split("|")
    else:
        return None
Beispiel #4
0
    def getSession(self):
        """Return the existing session or a new session"""
        if self.session is not None:
            return self.session

        # Get value of cookie header that was sent
        cookie_str = self.headers.get('Cookie')
        if cookie_str:
            cookie_obj = SimpleCookie(cookie_str)
            sid_morsel = cookie_obj.get(self.SESSION_COOKIE_NAME, None)
            if sid_morsel is not None:
                sid = sid_morsel.value
            else:
                sid = None
        else:
            sid = None

        # If a session id was not set, create a new one
        if sid is None:
            sid = randomString(16, '0123456789abcdef')
            session = None
        else:
            session = self.server.sessions.get(sid)

        # If no session exists for this session ID, create one
        if session is None:
            session = self.server.sessions[sid] = {}

        session['id'] = sid
        self.session = session
        return session
Beispiel #5
0
def get_cookie_dict(environ):
    """Return a *plain* dictionary of cookies as found in the request.

    Unlike ``get_cookies`` this returns a dictionary, not a
    ``SimpleCookie`` object.  For incoming cookies a dictionary fully
    represents the information.  Like ``get_cookies`` this caches and
    checks the cache.
    """
    header = environ.get('HTTP_COOKIE')
    if not header:
        return {}
    if 'paste.cookies.dict' in environ:
        cookies, check_header = environ['paste.cookies.dict']
        if check_header == header:
            return cookies
    cookies = SimpleCookie()
    try:
        cookies.load(header)
    except CookieError:
        pass
    result = {}
    for name in cookies:
        result[name] = cookies[name].value
    environ['paste.cookies.dict'] = (result, header)
    return result
Beispiel #6
0
    def parse_cookies(self):
        from http.cookies import SimpleCookie, CookieError

        if not self._headers_history:
            self._parse_headers_raw()

        # Get cookies from endpoint
        cookies = []
        for header in chain(*self._headers_history):
            if len(header) > 2:
                continue

            key, value = header[0], header[1]

            if key.lower().startswith("set-cookie"):

                try:
                    cookie = SimpleCookie()
                    cookie.load(value)
                    cookies.extend(list(cookie.values()))

                    # update cookie jar
                    for morsel in list(cookie.values()):
                        if isinstance(self._cookies_jar, CookieJar):
                            self._cookies_jar.set_cookie(morsel_to_cookie(morsel))
                except CookieError as e:
                    logger.warn(e)
        self._cookies = dict([(cookie.key, cookie.value) for cookie in cookies])
        return self._cookies
Beispiel #7
0
def set_cookie(name, _, *args):
    cookie = SimpleCookie()
    cookie[name] = base64.b64encode(":".join(args))
    cookie[name]['path'] = "/"
    cookie[name]["expires"] = _expiration(5)  # 5 minutes from now
    logger.debug("Cookie expires: %s" % cookie[name]["expires"])
    return tuple(cookie.output().split(": ", 1))
Beispiel #8
0
 def raw_cookies(self):
     """Raw access to cookies"""
     cookie_data = self.environ.get("HTTP_COOKIE", "")
     cookies = SimpleCookie()
     if not cookie_data:
         return cookies
     cookies.load(cookie_data)
     return cookies
Beispiel #9
0
 def cookies(self) -> HTTPCookies:
     if not hasattr(self, "_cookies"):
         cookies = HTTPCookies()
         if "set-cookie" in self.headers:
             for cookie_header in self.headers.get_list("set-cookie"):
                 cookies.load(cookie_header)
         self._cookies = cookies
     return self._cookies
Beispiel #10
0
 def cookies(self):
     """A dictionary of Cookie.Morsel objects."""
     cookies = SimpleCookie()
     try:
         cookies.load(self.headers["Cookie"])
     except Exception:
         pass
     return cookies
Beispiel #11
0
 def cookies(self):
     """Container of request cookies
     """
     cookies = SimpleCookie()
     cookie = self.environ.get('HTTP_COOKIE')
     if cookie:
         cookies.load(cookie)
     return cookies
 def test_default_timeout(self):
     # Default timeout should be 30 mins
     self.login()
     response = self.client.get('/next-after-login', follow_redirects=False)
     cookies = SimpleCookie()
     [cookies.load(item[1]) for item in response.headers
         if item[0] == 'Set-Cookie']
     assert int(cookies['SS_INACTIVITY_TIMEOUT'].value) == 30 * 60
Beispiel #13
0
def pull_cookies(environ):
    """
    Pulls and formats cookies stored by user for domain.
    <http://pwp.stevecassidy.net/wsgi/cookies.html>
    """

    cookie = SimpleCookie(environ.get('HTTP_COOKIE', ''))
    return {key: morsel.value for key, morsel in cookie.items()}
def cookie_dict_from_cookie_str(cookie_str):
    """cookie_dict_from_str Cookie字符串返回成dict

    :param cookie_str: cookies string
    """
    cookie = SimpleCookie()
    cookie.load(cookie_str)
    return {key: morsel.value for key, morsel in cookie.items()}
def logout(_request):
    body = base_body % ('<p>Logged out </p>')
    res = Response()
    c = SimpleCookie()
    c['authhash'] = ''
    res.set_header(*c.output().split(': '))
    res.set_body(body)
    return res
Beispiel #16
0
 def user2kaka(self, user):
     uid = rndbytes(32)
     self.uid2user[uid] = user
     cookie = SimpleCookie()
     cookie[self.cookie_name] = uid
     cookie[self.cookie_name]['path'] = "/"
     cookie[self.cookie_name]["expires"] = _expiration(480)
     logger.debug("Cookie expires: %s" % cookie[self.cookie_name]["expires"])
     return tuple(cookie.output().split(": ", 1))
Beispiel #17
0
    def cookies(self):
        """Return request cookies.

        A read-only dictionary-like object.
        """
        raw = self.headers.get(hdrs.COOKIE, '')
        parsed = SimpleCookie(raw)
        return MappingProxyType(
            {key: val.value for key, val in parsed.items()})
Beispiel #18
0
    def get_cookie(self, key):
        cookie_string = self.req_env.get('HTTP_COOKIE', None)
        if cookie_string is None:
            return

        cookie = SimpleCookie()
        cookie.load(cookie_string)

        return cookie.get(key, None).value
Beispiel #19
0
def application1(environ,start_response):
    try:
        request_body_size = remainbytes = int(environ.get('CONTENT_LENGTH',0))
    except ValueError:
        request_body_size = remainbytes = 0
    if remainbytes > 0:
        CONTENT_TYPE = environ.get('CONTENT_TYPE','')
        boundary = re.findall('multipart/form-data.*boundary=(.*)',CONTENT_TYPE)[0].encode('ascii')
        wsgi_input = environ['wsgi.input']
        line = wsgi_input.readline()
        remainbytes -= len(line)
        if not boundary in line:
            return (False,"Content NOT begin with boundary")
        line = wsgi_input.readline()
        remainbytes -= len(line)
        line = line.decode('ascii')
        fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line)[0]
        line = wsgi_input.readline()
        remainbytes -= len(line)
        line = wsgi_input.readline()
        remainbytes -= len(line)
        blocksize = 8192
        out = open(fn,'wb')
        preline = wsgi_input.readline()
        remainbytes -= len(line)
        while remainbytes > 0:
            line = wsgi_input.readline()
            remainbytes -= len(line)
            if boundary in line:
                preline = preline[0:-1]
                if preline.endswith(b'\r'):
                    preline = preline[0:-1]
                out.write(preline)
                out.close()
                break
            else:
                out.write(preline)
                preline = line
    cookie = SimpleCookie(environ.get('HTTP_COOKIE',''))
    if 'sid' in cookie:
        sid = cookie['sid'].value
        message = 'already session'
    else:
        sid = hashlib.sha224(repr(time.time()).encode('ascii')).hexdigest()
        cookie['sid'] = sid
        message = 'new session'
    cookie['sid']['expires'] = 60
    response_body = html % ("OK" if request_body_size else "Empty",message,sid)
    status = '200 OK'
    response_headers = [('Set-Cookie',cookie.output(header="")),
                ('Content-Type','text/html'),
                ('Content-Length',str(len(response_body)))
                ]
    start_response(status,response_headers)
    #response_body = response_body.encode('ascii')
    return [response_body.encode('ascii')]
Beispiel #20
0
def cookie_parts(name, kaka):
    if not isinstance(kaka, SimpleCookie):
        cookie_obj = SimpleCookie(str(kaka))
    else:
        cookie_obj = kaka
    morsel = cookie_obj.get(name)
    if morsel:
        return morsel.value.split("|")
    else:
        return None
Beispiel #21
0
 def start_response(status, headers):
     ret["status"] = status
     ret["headers"] = headers
     ret["cookies"] = {}
     cookies = SimpleCookie()
     for k, v in headers:
         if k == 'Set-Cookie':
             cookies.load(v)
     for key in cookies.keys():
         ret["cookies"][key] = cookies[key]
Beispiel #22
0
 def wsgi_filter(environ, start_response):
     # set REMOTE_USER from cookie
     cookies = SimpleCookie()
     cookies.load(environ.get('HTTP_COOKIE', ''))
     if 'REMOTE_USER' in cookies:
         user = cookies['REMOTE_USER'].value
     else:
         user = '******'
     environ['REMOTE_USER'] = user
     return app(environ, start_response)
Beispiel #23
0
 def _loadSessionFromCookie(self, environ):
     """
     Attempt to load the associated session using the identifier from
     the cookie.
     """
     C = SimpleCookie(environ.get('HTTP_COOKIE'))
     morsel = C.get(self._cookieName, None)
     if morsel is not None:
         self._session = self._store.checkOutSession(morsel.value)
         self._expired = self._session is None
Beispiel #24
0
    def _set_common_domain_cookie(self, internal_response, http_args, context):
        """
        """
        # Find any existing common domain cookie and deconsruct it to
        # obtain the list of IdPs.
        cookie = SimpleCookie(context.cookie)
        if '_saml_idp' in cookie:
            common_domain_cookie = cookie['_saml_idp']
            satosa_logging(logger, logging.DEBUG, "Found existing common domain cookie {}".format(common_domain_cookie), context.state)
            space_separated_b64_idp_string = unquote(common_domain_cookie.value)
            b64_idp_list = space_separated_b64_idp_string.split()
            idp_list = [urlsafe_b64decode(b64_idp).decode('utf-8') for b64_idp in b64_idp_list]
        else:
            satosa_logging(logger, logging.DEBUG, "No existing common domain cookie found", context.state)
            idp_list = []

        satosa_logging(logger, logging.DEBUG, "Common domain cookie list of IdPs is {}".format(idp_list), context.state)

        # Identity the current IdP just used for authentication in this flow.
        this_flow_idp = internal_response.auth_info.issuer

        # Remove all occurrences of the current IdP from the list of IdPs.
        idp_list = [idp for idp in idp_list if idp != this_flow_idp]

        # Append the current IdP.
        idp_list.append(this_flow_idp)
        satosa_logging(logger, logging.DEBUG, "Added IdP {} to common domain cookie list of IdPs".format(this_flow_idp), context.state)
        satosa_logging(logger, logging.DEBUG, "Common domain cookie list of IdPs is now {}".format(idp_list), context.state)

        # Construct the cookie.
        b64_idp_list = [urlsafe_b64encode(idp.encode()).decode("utf-8") for idp in idp_list]
        space_separated_b64_idp_string = " ".join(b64_idp_list)
        url_encoded_space_separated_b64_idp_string = quote(space_separated_b64_idp_string)

        cookie = SimpleCookie()
        cookie['_saml_idp'] = url_encoded_space_separated_b64_idp_string
        cookie['_saml_idp']['path'] = '/'

        # Use the domain from configuration if present else use the domain
        # from the base URL for the front end.
        domain = urlparse(self.base_url).netloc
        if isinstance(self.config['common_domain_cookie'], dict):
            if 'domain' in self.config['common_domain_cookie']:
                domain = self.config['common_domain_cookie']['domain']

        # Ensure that the domain begins with a '.'
        if domain[0] != '.':
            domain = '.' + domain

        cookie['_saml_idp']['domain'] = domain
        cookie['_saml_idp']['secure'] = True

        # Set the cookie.
        satosa_logging(logger, logging.DEBUG, "Setting common domain cookie with {}".format(cookie.output()), context.state)
        http_args['headers'].append(tuple(cookie.output().split(": ", 1)))
Beispiel #25
0
 def _set_cookies(self, appid, headers):
     if appid not in self.cookies:
         self._init_cookies(appid)
     for sc in headers.get_list("Set-Cookie"):
         c = SimpleCookie(sc)
         for morsel in c.values():
             if morsel.key not in ['data_bizuin', 'slave_user', 'bizuin']:
                 if morsel.value and morsel.value != 'EXPIRED':
                     self.cookies[appid][morsel.key] = morsel.value
                 else:
                     self.cookies[appid].pop(morsel.key, None)
Beispiel #26
0
 def parse_cookies( self, headers ):
     """:meth:`pluggdapps.web.interfaces.IHTTPCookie.parse_cookies` 
     interface method."""
     cookies = SimpleCookie()
     cookie = headers.get( 'cookie', '' )
     try    : 
         cookies.load( cookie )
         return cookies
     except CookieError :
         self.pa.logwarn( "Unable to parse cookie: %s" % cookie )
         return None
Beispiel #27
0
 def cookies(self) -> HTTPCookies:
     """
     Parse cookies and return cookies in a `HTTPCookies` instance.
     """
     if not hasattr(self, "_cookies"):
         cookies = HTTPCookies()
         if "set-cookie" in self.headers:
             for cookie_header in self.headers.get_list("set-cookie"):
                 cookies.load(cookie_header)
         self._cookies = cookies
     return self._cookies
Beispiel #28
0
 def cookies(self):
     if self._cookies is None:
         cookie = self.headers.get('Cookie') or self.headers.get('cookie')
         if cookie is not None:
             cookies = SimpleCookie()
             cookies.load(cookie)
             self._cookies = {name: cookie.value
                              for name, cookie in cookies.items()}
         else:
             self._cookies = {}
     return self._cookies
Beispiel #29
0
 def COOKIES(self):
     if self._cookies is None:
         try:
             c = SimpleCookie(self.ENV.get('HTTP_COOKIE', ''))
         except CookieError:  # pragma: no cover
             self._cookies = {}
         else:
             res = {}
             for name, value in c.items():
                 res[name] = value.value
             self._cookies = res
     return self._cookies
Beispiel #30
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
Beispiel #31
0
def set_cookie_header(header: str) -> None:
    """Like set_cookie, but you can set the header directly."""
    c = SimpleCookie()
    c.load(header)
    session.cookies.update(c)
Beispiel #32
0
#!/usr/local/bin/python3

from cgitb import enable
enable()

from cgi import FieldStorage
from os import environ
from hashlib import sha256
from time import time
from shelve import open
from http.cookies import SimpleCookie

result = ''
redirect = ''
try:
    cookie = SimpleCookie()
    http_cookie_header = environ.get('HTTP_COOKIE')
    if not http_cookie_header:
        sid = sha256(repr(time()).encode()).hexdigest()
        cookie['sid'] = sid
    else:
        cookie.load(http_cookie_header)
        sid = cookie['sid'].value

    session_store = open('sess_' + sid, writeback=True)

    # Get the id of the item being added to the cart
    form_data = FieldStorage()
    book_id = form_data.getfirst('book_id')
    qty = session_store.get(book_id)
    if not qty:
Beispiel #33
0
 def make_redirect_cookie(self, scope):
     """cookie to tell browser where to redirect post authentication"""
     redirect_cookie = SimpleCookie()
     redirect_cookie[self.redirect_cookie_name] = scope["path"]
     redirect_cookie[self.redirect_cookie_name]["path"] = "/"
     return redirect_cookie
Beispiel #34
0
    def _set_common_domain_cookie(self, internal_response, http_args, context):
        """
        """
        # Find any existing common domain cookie and deconsruct it to
        # obtain the list of IdPs.
        cookie = SimpleCookie(context.cookie)
        if '_saml_idp' in cookie:
            common_domain_cookie = cookie['_saml_idp']
            satosa_logging(
                logger, logging.DEBUG,
                "Found existing common domain cookie {}".format(
                    common_domain_cookie), context.state)
            space_separated_b64_idp_string = unquote(
                common_domain_cookie.value)
            b64_idp_list = space_separated_b64_idp_string.split()
            idp_list = [
                urlsafe_b64decode(b64_idp).decode('utf-8')
                for b64_idp in b64_idp_list
            ]
        else:
            satosa_logging(logger, logging.DEBUG,
                           "No existing common domain cookie found",
                           context.state)
            idp_list = []

        satosa_logging(
            logger, logging.DEBUG,
            "Common domain cookie list of IdPs is {}".format(idp_list),
            context.state)

        # Identity the current IdP just used for authentication in this flow.
        this_flow_idp = internal_response.auth_info.issuer

        # Remove all occurrences of the current IdP from the list of IdPs.
        idp_list = [idp for idp in idp_list if idp != this_flow_idp]

        # Append the current IdP.
        idp_list.append(this_flow_idp)
        satosa_logging(
            logger, logging.DEBUG,
            "Added IdP {} to common domain cookie list of IdPs".format(
                this_flow_idp), context.state)
        satosa_logging(
            logger, logging.DEBUG,
            "Common domain cookie list of IdPs is now {}".format(idp_list),
            context.state)

        # Construct the cookie.
        b64_idp_list = [
            urlsafe_b64encode(idp.encode()).decode("utf-8") for idp in idp_list
        ]
        space_separated_b64_idp_string = " ".join(b64_idp_list)
        url_encoded_space_separated_b64_idp_string = quote(
            space_separated_b64_idp_string)

        cookie = SimpleCookie()
        cookie['_saml_idp'] = url_encoded_space_separated_b64_idp_string
        cookie['_saml_idp']['path'] = '/'

        # Use the domain from configuration if present else use the domain
        # from the base URL for the front end.
        domain = urlparse(self.base_url).netloc
        if isinstance(self.config['common_domain_cookie'], dict):
            if 'domain' in self.config['common_domain_cookie']:
                domain = self.config['common_domain_cookie']['domain']

        # Ensure that the domain begins with a '.'
        if domain[0] != '.':
            domain = '.' + domain

        cookie['_saml_idp']['domain'] = domain
        cookie['_saml_idp']['secure'] = True

        # Set the cookie.
        satosa_logging(
            logger, logging.DEBUG,
            "Setting common domain cookie with {}".format(cookie.output()),
            context.state)
        http_args['headers'].append(tuple(cookie.output().split(": ", 1)))
Beispiel #35
0
async def test_filter_cookie_with_unicode_domain(loop) -> None:
    jar = CookieJar()
    jar.update_cookies(
        SimpleCookie("idna-domain-first=first; Domain=xn--9caa.com; Path=/; "))
    assert len(jar.filter_cookies(URL("http://éé.com"))) == 1
    assert len(jar.filter_cookies(URL("http://xn--9caa.com"))) == 1
Beispiel #36
0
class ClientResponse(HeadersMixin):

    # from the Status-Line of the response
    version = None  # HTTP-Version
    status = None   # Status-Code
    reason = None   # Reason-Phrase

    content = None  # Payload stream
    headers = None  # Response headers, CIMultiDictProxy
    raw_headers = None  # Response raw headers, a sequence of pairs

    _connection = None  # current connection
    flow_control_class = StreamReader  # reader flow control
    _reader = None     # input stream
    _source_traceback = None
    # setted up by ClientRequest after ClientResponse object creation
    # post-init stage allows to not change ctor signature
    _loop = None
    _closed = True  # to allow __del__ for non-initialized properly response
    _session = None

    def __init__(self, method, url, *,
                 writer=None, continue100=None, timer=None,
                 request_info=None, auto_decompress=True):
        assert isinstance(url, URL)

        self.method = method
        self.headers = None
        self.cookies = SimpleCookie()

        self._url = url
        self._content = None
        self._writer = writer
        self._continue = continue100
        self._closed = True
        self._history = ()
        self._request_info = request_info
        self._timer = timer if timer is not None else TimerNoop()
        self._auto_decompress = auto_decompress
        self._cache = {}  # reqired for @reify method decorator

    @property
    def url(self):
        return self._url

    @property
    def url_obj(self):
        warnings.warn(
            "Deprecated, use .url #1654", DeprecationWarning, stacklevel=2)
        return self._url

    @property
    def host(self):
        return self._url.host

    @property
    def _headers(self):
        return self.headers

    @property
    def request_info(self):
        return self._request_info

    @reify
    def content_disposition(self):
        raw = self._headers.get(hdrs.CONTENT_DISPOSITION)
        if raw is None:
            return None
        disposition_type, params = multipart.parse_content_disposition(raw)
        params = MappingProxyType(params)
        filename = multipart.content_disposition_filename(params)
        return ContentDisposition(disposition_type, params, filename)

    def _post_init(self, loop, session):
        self._loop = loop
        self._session = session  # store a reference to session #1985
        if loop.get_debug():
            self._source_traceback = traceback.extract_stack(sys._getframe(1))

    def __del__(self, _warnings=warnings):
        if self._loop is None:
            return  # not started
        if self._closed:
            return

        if self._connection is not None:
            self._connection.release()
            self._cleanup_writer()

            if self._loop.get_debug():
                if PY_36:
                    kwargs = {'source': self}
                else:
                    kwargs = {}
                _warnings.warn("Unclosed response {!r}".format(self),
                               ResourceWarning,
                               **kwargs)
                context = {'client_response': self,
                           'message': 'Unclosed response'}
                if self._source_traceback:
                    context['source_traceback'] = self._source_traceback
                self._loop.call_exception_handler(context)

    def __repr__(self):
        out = io.StringIO()
        ascii_encodable_url = str(self.url)
        if self.reason:
            ascii_encodable_reason = self.reason.encode('ascii',
                                                        'backslashreplace') \
                .decode('ascii')
        else:
            ascii_encodable_reason = self.reason
        print('<ClientResponse({}) [{} {}]>'.format(
            ascii_encodable_url, self.status, ascii_encodable_reason),
            file=out)
        print(self.headers, file=out)
        return out.getvalue()

    @property
    def connection(self):
        return self._connection

    @property
    def history(self):
        """A sequence of of responses, if redirects occurred."""
        return self._history

    async def start(self, connection, read_until_eof=False):
        """Start response processing."""
        self._closed = False
        self._protocol = connection.protocol
        self._connection = connection

        connection.protocol.set_response_params(
            timer=self._timer,
            skip_payload=self.method.lower() == 'head',
            read_until_eof=read_until_eof,
            auto_decompress=self._auto_decompress)

        with self._timer:
            while True:
                # read response
                try:
                    (message, payload) = await self._protocol.read()
                except http.HttpProcessingError as exc:
                    raise ClientResponseError(
                        self.request_info, self.history,
                        code=exc.code,
                        message=exc.message, headers=exc.headers) from exc

                if (message.code < 100 or
                        message.code > 199 or message.code == 101):
                    break

                if self._continue is not None:
                    set_result(self._continue, True)
                    self._continue = None

        # payload eof handler
        payload.on_eof(self._response_eof)

        # response status
        self.version = message.version
        self.status = message.code
        self.reason = message.reason

        # headers
        self.headers = CIMultiDictProxy(message.headers)
        self.raw_headers = tuple(message.raw_headers)

        # payload
        self.content = payload

        # cookies
        for hdr in self.headers.getall(hdrs.SET_COOKIE, ()):
            try:
                self.cookies.load(hdr)
            except CookieError as exc:
                client_logger.warning(
                    'Can not load response cookies: %s', exc)
        return self

    def _response_eof(self):
        if self._closed:
            return

        if self._connection is not None:
            # websocket, protocol could be None because
            # connection could be detached
            if (self._connection.protocol is not None and
                    self._connection.protocol.upgraded):
                return

            self._connection.release()
            self._connection = None

        self._closed = True
        self._cleanup_writer()

    @property
    def closed(self):
        return self._closed

    def close(self):
        if self._closed:
            return

        self._closed = True
        if self._loop is None or self._loop.is_closed():
            return

        if self._connection is not None:
            self._connection.close()
            self._connection = None
        self._cleanup_writer()
        self._notify_content()

    def release(self):
        if self._closed:
            return noop()

        self._closed = True
        if self._connection is not None:
            self._connection.release()
            self._connection = None

        self._cleanup_writer()
        self._notify_content()
        return noop()

    def raise_for_status(self):
        if 400 <= self.status:
            raise ClientResponseError(
                self.request_info,
                self.history,
                code=self.status,
                message=self.reason,
                headers=self.headers)

    def _cleanup_writer(self):
        if self._writer is not None:
            self._writer.cancel()
        self._writer = None
        self._session = None

    def _notify_content(self):
        content = self.content
        if content and content.exception() is None and not content.is_eof():
            content.set_exception(
                ClientConnectionError('Connection closed'))

    async def wait_for_close(self):
        if self._writer is not None:
            try:
                await self._writer
            finally:
                self._writer = None
        self.release()

    async def read(self):
        """Read response payload."""
        if self._content is None:
            try:
                self._content = await self.content.read()
            except BaseException:
                self.close()
                raise

        return self._content

    def get_encoding(self):
        ctype = self.headers.get(hdrs.CONTENT_TYPE, '').lower()
        mimetype = helpers.parse_mimetype(ctype)

        encoding = mimetype.parameters.get('charset')
        if encoding:
            try:
                codecs.lookup(encoding)
            except LookupError:
                encoding = None
        if not encoding:
            if mimetype.type == 'application' and mimetype.subtype == 'json':
                # RFC 7159 states that the default encoding is UTF-8.
                encoding = 'utf-8'
            else:
                encoding = chardet.detect(self._content)['encoding']
        if not encoding:
            encoding = 'utf-8'

        return encoding

    async def text(self, encoding=None, errors='strict'):
        """Read response payload and decode."""
        if self._content is None:
            await self.read()

        if encoding is None:
            encoding = self.get_encoding()

        return self._content.decode(encoding, errors=errors)

    async def json(self, *, encoding=None, loads=json.loads,
                   content_type='application/json'):
        """Read and decodes JSON response."""
        if self._content is None:
            await self.read()

        if content_type:
            ctype = self.headers.get(hdrs.CONTENT_TYPE, '').lower()
            if content_type not in ctype:
                raise ContentTypeError(
                    self.request_info,
                    self.history,
                    message=('Attempt to decode JSON with '
                             'unexpected mimetype: %s' % ctype),
                    headers=self.headers)

        stripped = self._content.strip()
        if not stripped:
            return None

        if encoding is None:
            encoding = self.get_encoding()

        return loads(stripped.decode(encoding))

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        # similar to _RequestContextManager, we do not need to check
        # for exceptions, response object can closes connection
        # is state is broken
        self.release()
Beispiel #37
0
def get_cookies(raw_cookie):
    """extract cookies from raw cookie data"""
    cookie = SimpleCookie(raw_cookie)
    result = dict([(k, cookie[k].value) for k in cookie])
    return result
Beispiel #38
0
  def _serve_websocket (self):
    self.close_connection = 1

    # I think you technically need HTTP/1.1 to be able to upgrade or
    # something like that.  Firefox and Chrome don't seem to mind if
    # we reply with HTTP/1.0, but at least one (Epiphany) will fail.
    self.protocol_version = "HTTP/1.1"

    log.debug("Upgrading to websocket")
    self.send_response(101, "Switching Protocols")
    k = self.headers.get("Sec-WebSocket-Key", "")
    k += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    k = base64.b64encode(hashlib.sha1(k.encode()).digest()).decode()
    self.send_header("Sec-WebSocket-Accept", k)
    self.send_header("Upgrade", "websocket")
    self.send_header("Connection", "Upgrade")

    do_cg = getattr(self, "ws_pox_cookieguard", None)
    if do_cg is None: do_cg = getattr(self.parent, "pox_cookieguard", True)
    if not do_cg:
      cg_ok = True
    else:
      cookies = SimpleCookie(self.headers.get('Cookie'))
      cgc = cookies.get(self.parent._pox_cookieguard_cookie_name)
      if cgc and cgc.value == self.parent._get_cookieguard_cookie():
        cg_ok = True
      else:
        # Cookieguard failed.
        cookie = ("%s=%s; SameSite=Strict; HttpOnly; path=/"
                  % (self.parent._pox_cookieguard_cookie_name,
                     self.parent._get_cookieguard_cookie()))
        self.send_header("Set-Cookie", cookie)
        self.send_header("POX", "request-reconnect")

        cg_ok = False

    self.end_headers()

    # Now stop using wfile and use raw socket
    self.wfile.flush()
    self.connection.settimeout(0)

    if not cg_ok:
      log.info("Bad POX CookieGuard cookie  -- closing connection")
      return

    self._websocket_open = True
    self._queue_call(self._on_start)

    def feeder ():
      data = b''
      old_op = None
      hdr = b''
      while self._websocket_open:
        while len(hdr) < 2:
          newdata = yield True
          if newdata: hdr += newdata

        flags_op,len1 = struct.unpack_from("!BB", hdr, 0)
        op = flags_op & 0x0f
        flags = flags_op >> 4
        fin = flags & 0x8
        if (len1 & 0x80) == 0: raise RuntimeError("No mask set")
        len1 &= 0x7f
        hdr = hdr[2:]

        while True:
          if len1 <= 0x7d:
            length = len1
            break
          elif len1 == 0x7e and len(hdr) >= 2:
            length = struct.unpack_from("!H", hdr, 0)
            hdr = hdr[2:]
            break
          elif len1 == 0x7f and len(hdr) >= 8:
            length = struct.unpack_from("!Q", hdr, 0)
            hdr = hdr[8:]
            break
          else:
            raise RuntimeError("Bad length")
          hdr += yield True

        while len(hdr) < 4:
          hdr += yield True

        mask = [x for x in hdr[:4]]
        hdr = hdr[4:]

        while len(hdr) < length:
          hdr += yield True

        d = hdr[:length]
        hdr = hdr[length:]

        d = bytes((c ^ mask[i % 4]) for i,c in enumerate(d))

        if not fin:
          if op == self.WS_CONTINUE:
            if old_op is None: raise RuntimeError("Continuing unknown opcode")
          else:
            if old_op is not None: raise RuntimeError("Discarded partial message")
            old_op = op
          data += d
        else: # fin
          if op == self.WS_CONTINUE:
            if old_op is None: raise RuntimeError("Can't continue unknown frame")
            op = old_op
          d = data + d
          old_op = None
          data = b''
          if op == self.WS_TEXT: d = d.decode('utf8')

          if op in (self.WS_TEXT, self.WS_BINARY):
            self._ws_message(op, d)
          elif op == self.WS_PING:
            msg = self._frame(self.WS_PONG, d)
            self._send_real(msg)
          elif op == self.WS_CLOSE:
            if self.disconnect():
              #TODO: Send close frame?
              pass
          elif op == self.WS_PONG:
            pass
          else:
            pass # Do nothing for unknown type

    deframer = feeder()
    try:
      deframer.send(None)
    except StopIteration:
      pass # PEP 479?

    # This is nutso, but it just might work.
    # *Try* to read individual bytes from rfile in case it has some
    # buffered.  When it fails, switch to reading from connection.
    while True:
      try:
        d = self.rfile.read(1)
        if not d: break
        deframer.send(d)
      except Exception:
        break

    import select
    while self._websocket_open and core.running:
      try:
        (rx, tx, xx) = select.select([self.connection], [], [self.connection],
                                     self.READ_TIMEOUT)
      except Exception:
        # sock died
        log.warn("Websocket died")
        break
      if len(xx):
        #TODO: reopen?
        log.warn("Websocket exceptional")
        break
      if len(rx):
        try:
          r = self.connection.recv(4096)
          if not r: break
          deframer.send(r)
        except Exception as e:
          #TODO: reopen
          break

    log.debug("Done reading websocket")

    #NOTE: We should probably send a close frame, but don't.
    self.disconnect()
Beispiel #39
0
    async def auth_callback(self, scope, receive, send):
        # Look for ?code=
        qs = dict(parse_qsl(scope["query_string"].decode("utf8")))
        if not qs.get("code"):
            await send_html(send, "Authentication failed, no code")
            return
        # Exchange that code for a token
        github_response = (await self.http_request(
            "https://github.com/login/oauth/access_token",
            body=urlencode({
                "client_id": self.client_id,
                "client_secret": self.client_secret,
                "code": qs["code"],
            }).encode("utf-8"),
        )).text
        parsed = dict(parse_qsl(github_response))
        # b'error=bad_verification_code&error_description=The+code+passed...'
        if parsed.get("error"):
            await send_html(
                send,
                "{}<h1>GitHub authentication error</h1><p>{}</p><p>{}</p>".
                format(LOGIN_CSS, parsed["error"],
                       parsed.get("error_description") or ""),
            )
            return
        access_token = parsed.get("access_token")
        if not access_token:
            await send_html(send, "No valid access token")
            return
        # Use access_token to verify user
        profile_url = "https://api.github.com/user?access_token={}".format(
            access_token)
        try:
            profile = (await self.http_request(profile_url)).json()
        except ValueError:
            await send_html(send, "Could not load GitHub profile")
            return
        auth = {
            "id": str(profile["id"]),
            "name": profile["name"],
            "username": profile["login"],
            "email": profile["email"],
        }
        # Are they allowed?
        if not (await self.user_is_allowed(auth, access_token)):
            await send_html(
                send,
                """{}<h1>Access forbidden</h1>""".format(LOGIN_CSS),
                status=403)
            return

        # Set a signed cookie and redirect to homepage
        signer = Signer(self.cookie_secret)
        signed_cookie = signer.sign(
            json.dumps(dict(auth, ts=int(time.time())), separators=(",", ":")))

        redirect_to = cookies_from_scope(scope).get(
            self.redirect_cookie_name) or "/"

        headers = [["location", redirect_to]]
        login_cookie = SimpleCookie()
        login_cookie[self.cookie_name] = signed_cookie
        login_cookie[self.cookie_name]["path"] = "/"
        headers.append(["set-cookie", login_cookie.output(header="").lstrip()])
        asgi_logout_cookie = SimpleCookie()
        asgi_logout_cookie[self.logout_cookie_name] = ""
        asgi_logout_cookie[self.logout_cookie_name]["path"] = "/"
        asgi_logout_cookie[self.logout_cookie_name]["max-age"] = 0
        asgi_logout_cookie[self.logout_cookie_name]["expires"] = 0
        headers.append(
            ["set-cookie",
             asgi_logout_cookie.output(header="").lstrip()])
        await send_html(send, "", 302, headers)
Beispiel #40
0
async def test_preserving_quoted_cookies(loop) -> None:
    jar = CookieJar(unsafe=True)
    jar.update_cookies(SimpleCookie("ip-cookie=\"second\"; Domain=127.0.0.1;"))
    cookies_sent = jar.filter_cookies(
        URL("http://127.0.0.1/")).output(header='Cookie:')
    assert cookies_sent == 'Cookie: ip-cookie=\"second\"'
 else:
     sha256_password = sha256(password.encode()).hexdigest()
     try:
         connection = db.connect()
         cursor = connection.cursor(db.cursors.DictCursor)
         cursor.execute(
             """SELECT max_points FROM users 
                           WHERE username = %s
                           AND password = %s""",
             (username, sha256_password))
         if cursor.rowcount == 0:
             result = '<p>Error: incorrect user name or password</p>'
         else:
             sql_points = cursor.fetchone()
             current_points = sql_points['max_points']
             cookie = SimpleCookie()
             sid = sha256(repr(time()).encode()).hexdigest()
             cookie['sid'] = sid
             session_store = open('sess_' + sid, writeback=True)
             session_store['authenticated'] = True
             session_store['username'] = username
             session_store['max_points'] = current_points
             session_store.close()
             result = """
                <p>Succesfully logged in!</p>
                <p>Welcome back to Space, Asteroids and Dinosaurs.</p>
                <ul>
                    <li><a href="index.py">Home</a></li> 
                    <li><a href="logout.py">Logout</a></li>
                </ul>"""
             print(cookie)
Beispiel #42
0
 def cookie(self):
     c = SimpleCookie()
     for key in list(self.values.keys()):
         c[key] = self.values[key]
     c["session_id"] = self.session_id
     return c
Beispiel #43
0
def parse_cookies(cookies_str):
    cookies = SimpleCookie()
    cookies.load(cookies_str)
    logging.debug(cookies)
    return {key: morsel.value for key, morsel in cookies.items()}
Beispiel #44
0
 def setUp(self):
     self.application_id = uuid.UUID
     signer = TimestampSigner()
     signed_email = signer.sign('*****@*****.**')
     self.client.cookies = SimpleCookie({'_ofs': signed_email})
Beispiel #45
0
 def get_cookie_header(cookies: SimpleCookie) -> str:
     return ';'.join([
         "{}={}".format(name, value.value)
         for name, value in cookies.items()
     ])
Beispiel #46
0
enable()

from os import environ
from http.cookies import SimpleCookie
from shelve import open
import util
import pymysql as db
print('Content-Type: text/html')
print()
# Updates stats
# Write to d and session store

result = 'fail'
http_cookie = environ.get('HTTP_COOKIE')
if http_cookie:
    cookie = SimpleCookie()
    cookie.load(http_cookie)

    if 'karols_sid' in cookie:
        karols_sid = cookie['karols_sid'].value
        #try:
        session_store = open('sessions/sess_' + str(karols_sid),
                             writeback=True)
        if session_store['authenticated']:

            # Take in current status if sent
            high_score = util.getInt('high_score', 0)
            curr_balance = util.getInt('curr_balance', 0)
            armour = util.getInt('armour', 0, 5)
            health_regen = util.getInt('health_regen', 0, 5)
            boost = util.getInt('boost', 0, 5)
Beispiel #47
0
 def cookies(self) -> dict:
     cookie_jar = SimpleCookie(self.headers.get("cookie") or "")
     return {name: value.value for name, value in cookie_jar.items()}