Exemple #1
0
 def __init__(self, expiry, data, dough, mac):
     self._expiry = expiry
     self._data = data
     self._mac = mac
     self._cookie = Cookie.SmartCookie()
     self._cookie[_TOKEN] = '%s%s' % (dough, mac)
     self._name = '%s%s' % (dough, mac)  # XXX WebKit only.
Exemple #2
0
 def test_cookie_str_changed_data(self):
     c = self.jar.makeCookie(self.exp, self.data)
     cout = c.output()
     str = cout[:36] + chr(ord(cout[36]) ^ 1) + cout[37:]
     s = Cookie.SmartCookie()
     s.load(str)
     self.assertFalse(self.jar.isGoodCookieString(s.output()))
Exemple #3
0
 def test_cookie_str_arbitrary_change(self):
     c = self.jar.makeCookie(self.exp, self.data)
     cout = c.output()
     str = cout[:32] + 'this is bad' + cout[32:]
     s = Cookie.SmartCookie()
     s.load(str)
     self.failIf(self.jar.isGoodCookieString(s.output()))
 def test_cookie_str_changed_data(self):
     c = self.jar.makeCookie(self.exp, self.data)
     cout = c.output()
     str = cout[:36] + 'X' + cout[37:]
     s = Cookie.SmartCookie()
     s.load(str)
     self.failIf(self.jar.isGoodCookieString(s.output()))
Exemple #5
0
    def __init__(self, sessionpath=None, sessionlifetime=None, config=None):
        """
      Initialisieren der Session

      Pruefen ob Sessionverzeichnis vorhanden, wenn nicht anlegen.
      """
        if sessionlifetime is not None:
            self.sessionlifetime = sessionlifetime

        if sessionpath is None:
            self.sessionpath = Config.sessionpath
        else:
            self.sessionpath = sessionpath

        # legt Sessionverzeichnis an, wenn nicht vorhanden
        if not os.path.exists(self.sessionpath):
            os.makedirs(self.sessionpath)

        self.cookie = Cookie.SmartCookie()
        self.loadCookie()
        self.newSession()

        # Attribute Laden wenn Cookie 'sid' gesetzt
        if self.cookie is not None:
            self.loadAttributes()
Exemple #6
0
 def test_cookie_str_changed_mac(self):
     c = self.jar.makeCookie(self.exp, self.data)
     cout = c.output()
     str = cout[:76] + chr(ord(cout[76]) ^ 1) + cout[77:]
     s = Cookie.SmartCookie()
     s.load(str)
     self.failIf(self.jar.isGoodCookieString(s.output()))
Exemple #7
0
 def get_cookie(self, headers_in, key):
     if headers_in.has_key('Cookie'):
         cookie = Cookie.SmartCookie(headers_in['Cookie'])
         cookie.load(headers_in['Cookie'])
         if cookie.has_key(key):
             return cookie[key].value
     return None
 def test_mix_unmix3(self):
     c = self.jar.makeCookie(self.exp, self.data)
     s = Cookie.SmartCookie()
     s.load(c.output())
     exp, data, digest = unmix3(s[self._token].value)
     self.failUnlessEqual(data, self.data)
     self.failUnlessEqual(float(exp), self.exp)
     key = self.jar._key     # Peeking...
     mac = binascii.b2a_base64(EVP.hmac(key, mix(self.exp, self.data), 'sha1'))[:-1]
     self.failUnlessEqual(digest, mac)
Exemple #9
0
 def add_cookie(self, server, header):
     header = string.strip(header)
     new_cookies = Cookie.SmartCookie()
     new_cookies.load(header)
     for cookie in new_cookies.values():
         if not cookie.get('domain', None):
             cookie['domain'] = string.lower(server)
         bigtest.Assert(len(cookie['domain']) > 0)
     self.cookies.update(new_cookies)
     self._debug("added cookie: server=%s, header=%s" % (server, header))
Exemple #10
0
 def isGoodCookieString(self, cookie_str):
     c = Cookie.SmartCookie()
     c.load(cookie_str)
     if _TOKEN not in c:
         return 0
     undough = unmix3(c[_TOKEN].value)
     if undough is None:
         return 0
     exp, data, mac = undough
     c2 = self.makeCookie(exp, data)
     return (not c2.isExpired()) and (c2._mac == mac)
Exemple #11
0
def set_client_Cookie():
    # Create a Cookie object.
    a_cookie = Cookie.SmartCookie()

    # Assign the cookie a value.
    a_cookie["user"] = "******"

    # Required header that tells the browser how to render the HTML.
    print "Content-Type: text/html"

    # Send the cookie back to the client.
    print a_cookie, "\n\n"

    # Print the cookie value.
    print "<HTML><BODY>"
    print a_cookie["user"].value, "user cookie set.\n"
    print "<FORM METHOD = post ACTION = \"example_7.4.cgi\">\n"
    print "<INPUT TYPE = \"hidden\" NAME = \
    \"set\" VALUE =\"yes\">\n"

    print "<INPUT TYPE = \"submit\" VALUE = \"Go\"></FORM>\n"
    print "</BODY></HTML>\n"

    # Define function to read a cookie.
    def read_client_Cookie():
        # Create a Cookie object.
        a_cookie = Cookie.SmartCookie(os.environ.get("HTTP_COOKIE", ""))

    # Assign the variable a cookie value.
    cookie_val = a_cookie["user"].value

    # Required header that tells the browser how to render the HTML.
    print "Content-Type: text/html\n\n"

    # Print the cookie value.
    print "<HTML><BODY>"
    print cookie_val, "user cookie read from client.\n"
    print "</BODY></HTML>\n"

    # Define main function.
    def main():
        form = cgi.FieldStorage()

    if (form.has_key("set")):
        if (form["set"].value == "yes"):
            read_client_Cookie()
    else:
        set_client_Cookie()

    # Call main function.
    main()
def parse_request(request):
    access_token = request.META.get('HTTP_AUTHORIZATION', None)

    if not access_token:
        cookie = Cookie.SmartCookie()
        if 'HTTP_COOKIE' in request.META:
            cookie.load(request.META['HTTP_COOKIE'])

            if TOKEN_KEY_NAME in cookie:
                access_token = cookie[TOKEN_KEY_NAME].value

    if not access_token:
        raise JWTError('No token found',
                       'Access token is missing in the request header')

    return access_token
Exemple #13
0
def _getHTML(url, params=None):
    global _opener
    if not _opener:
        _opener = urllib.FancyURLopener()
        _opener.addheaders = [
            ('User-agent',
             'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)')
        ]
    if params:
        data = urllib.urlencode(params)
        usock = _opener.open(url, data)
    else:
        usock = _opener.open(url)
    cookies = Cookie.SmartCookie()
    for c in usock.headers.getallmatchingheaders("set-cookie"):
        cookies.load(c)
    html = usock.read()
    usock.close()
    _opener.addheaders.extend([
        ('Cookie', c)
        for c in cookies.output().replace("\n", "").split("Set-Cookie: ")[1:]
    ])
    return html
Exemple #14
0
 def test_cookie_str2(self):
     c = self.jar.makeCookie(self.exp, self.data)
     s = Cookie.SmartCookie()
     s.load(c.output())
     self.failUnless(self.jar.isGoodCookieString(s.output()))
Exemple #15
0
users = udb.get_users()

# Force email to lower case for comparison to users list, which we
# lower-cased when loading.
if email:
    email = email.lower()

if email not in users:

    # print ("openid_session %s" % openid_session)
    if email:
        common.print_http_header()
        print("Access Denied ... '%s' not in users<br>" % (email))
        sys.exit(0)
    elif auth_type == 'OpenID':
        out_cookies = Cookie.SmartCookie()
        out_cookies[common.OPENID_SESSION_COOKIE_NAME] = ''
        out_cookies[common.OPENID_SESSION_COOKIE_NAME][
            'path'] = '/cloudsim/inside/cgi-bin/'
        print(out_cookies)
        common.print_http_header()
        print("""
        Your open session ID is not associated with a user. Please login again<br>
        <a href="/cloudsim/index.html">login</a>
        """)
        sys.exit(0)

# Save session ID and email to our own database
if auth_type == 'OpenID':
    sdb.db[openid_session] = email
    sdb.save()
Exemple #16
0
def GetCookieValue(headers_in, key):
    if headers_in.has_key('Cookie'):
        import Cookie
        C = Cookie.SmartCookie(headers_in['Cookie'])
        if C.has_key(key):
            return C[key].value
Exemple #17
0
 def read_client_Cookie():
     # Create a Cookie object.
     a_cookie = Cookie.SmartCookie(os.environ.get("HTTP_COOKIE", ""))
Exemple #18
0
 def test_cookie_str_expired(self):
     t = self.exp - 7200
     c = self.jar.makeCookie(t, self.data)
     s = Cookie.SmartCookie()
     s.load(c.output())
     self.failIf(self.jar.isGoodCookieString(s.output()))
Exemple #19
0
 def __init__(self, use_cookies=1, debug_level=0):
     self.cookies = Cookie.SmartCookie()
     self.use_cookies = use_cookies
     self.debug_level = debug_level
     self.standard_headers = []
     self.authorisation = None
import Cookie
import os, time
cookie = Cookie.SimpleCookie()
cookie["user"] = "******"
cookie["timestamp"] = time.time()
print cookie
# simulate CGI roundtrip
os.environ["HTTP_COOKIE"] = str(cookie)
print
cookie = Cookie.SmartCookie()
cookie.load(os.environ["HTTP_COOKIE"])
for key, item in cookie.items():
    # dictionary items are "Morsel" instances
    # use value attribute to get actual value
    print key, repr(item.value)
Exemple #21
0
 def __call__(self):
     self._cookies = Cookie.SmartCookie()
     self._cookies.load(os.environ.get('HTTP_COOKIE', ''))
     d = read_data()  # TODO: handle partial data
     write_data(self.process(d), self._cookies.output())
def main():
    #create new smart cookie to extract request token
    cookie = Cookie.SmartCookie()

    #if a cookie is available, load it
    if os.environ.has_key('HTTP_COOKIE'):
        cookie.load(os.environ['HTTP_COOKIE'])

        #if the request token cookie is available, load and parse it
        if cookie.has_key('request_token'):
            request_token = cookie.get('request_token').value
            rt_params = cgi.parse_qs(request_token)

            #parse query string parameters into dictionary
            qs_params = {}
            string_split = [
                s for s in os.environ['QUERY_STRING'].split('&') if s
            ]
            for item in string_split:
                key, value = item.split('=')
                qs_params[key] = value

            #create base consumer and signature method objects
            base_consumer = oauth.OAuthConsumer(common.consumer_key,
                                                common.consumer_secret)
            signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()

            #build dictionary of request token and secret to exchange for access token
            req_token = dotdict({
                'key': rt_params['token'][0],
                'secret': rt_params['token_secret'][0]
            })

            #build request token to access token exchange request object and sign it
            oauth_request = oauth.OAuthRequest.from_consumer_and_token(
                base_consumer,
                token=req_token,
                verifier=qs_params['oauth_verifier'],
                http_url=common.oauth_access_token_endpoint)
            oauth_request.sign_request(signature_method_hmac_sha1,
                                       base_consumer, req_token)

            #obtain request token as string and dictionary objects
            token_read = urllib.urlopen(oauth_request.to_url())
            token_string = token_read.read()
            token_params = cgi.parse_qs(token_string)

            #create access token object out of access token string
            access_token = oauth.OAuthToken.from_string(token_string)

            #create url to Yahoo! servers to access user profile
            guid = token_params['xoauth_yahoo_guid'][0]
            url = 'http://%s/v1/user/%s/profile' % ('social.yahooapis.com',
                                                    guid)

            #create new oauth request and sign using HMAC-SHA1 to get profile of authorized user
            oauth_request = oauth.OAuthRequest.from_consumer_and_token(
                base_consumer,
                token=access_token,
                http_method='GET',
                http_url=url)
            oauth_request.sign_request(signature_method_hmac_sha1,
                                       base_consumer, access_token)

            #make request to get profile of user
            profile_read = urllib.urlopen(oauth_request.to_url())
            profile_string = profile_read.read()
            print 'Content-Type: text/plain'
            print ''
            print profile_string
        else:
            #if request token cookie was not available, end
            print 'Request token cookie not found - exiting'
            sys.exit()
    else:
        #if cookies were not available, end
        print 'Request token cookie not found - exiting'
        sys.exit()