Beispiel #1
0
def GetCookie():
    if os.environ.has_key('HTTP_COOKIE'):
        c = Cookie.Cookie(os.environ['HTTP_COOKIE'])
    else:
        c = Cookie.Cookie()
    if c.has_key('login'):
        v = c['login'].value
    else:
        v = ""
    return v
Beispiel #2
0
def CookieUid():
    if os.environ.has_key('HTTP_COOKIE'):
        c = Cookie.Cookie(os.environ['HTTP_COOKIE'])
    else:
        c = Cookie.Cookie()
    if c.has_key('Uid'):
        Uid = c['Uid'].value
        if c.has_key('Name_First'):
            Name_First = c['Name_First'].value
    else:
        Uid = ''
        Name_First = ''
    return Uid, Name_First
Beispiel #3
0
def RemoveCookie():
    """
   Retrieves cookie and uses form to update.
   """
    expires = datetime.datetime.now() - datetime.timedelta(days=100)
    if os.environ.has_key('HTTP_COOKIE'):
        c = Cookie.Cookie(os.environ['HTTP_COOKIE'])
    else:
        c = Cookie.Cookie()
    if c.has_key('login'):
        c['login']['expires'] = expires.strftime("%a, %d %b %Y 23:59:59 GMT")
    if c.has_key('passw'):
        c['passw']['expires'] = expires.strftime("%a, %d %b %Y 23:59:59 GMT")
    return c
Beispiel #4
0
def GetCookie():
    if os.environ.has_key('HTTP_COOKIE'):
        c = Cookie.Cookie(os.environ['HTTP_COOKIE'])
    else:
        c = Cookie.Cookie()
    if c.has_key('login'):
        v = c['login'].value
    else:
        v = ''
    if c.has_key('passw'):
        w = c['passw'].value
    else:
        w = ''
    return v, w
Beispiel #5
0
def RemoveUid():
    """
   Retrieves cookie and uses form to update.
   """
    update = 0
    expires = datetime.datetime.now() - datetime.timedelta(days=1)
    if os.environ.has_key('HTTP_COOKIE'):
        c = Cookie.Cookie(os.environ['HTTP_COOKIE'])
    else:
        c = Cookie.Cookie()
    if c.has_key('Uid'):
        c['Uid'] = ''
    if c.has_key('Name_First'):
        c['Name_First'] = ''
    print c
Beispiel #6
0
def main():
    #build base consumer object with oauth keys and sign using HMAC-SHA1
    base_consumer = oauth.OAuthConsumer(common.consumer_key,
                                        common.consumer_secret)
    signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()

    #create and sign request token fetch request object
    request_rt = oauth.OAuthRequest.from_consumer_and_token(
        base_consumer,
        callback=common.callback_url,
        http_url=common.request_token_endpoint)
    request_rt.sign_request(signature_method_hmac_sha1, base_consumer, None)

    #obtain request token
    token_read = urllib.urlopen(request_rt.to_url())
    token_string = token_read.read()

    #parse request token into individual parameters
    token_params = cgi.parse_qs(token_string)
    oauth_token = token_params['oauth_token'][0]
    oauth_token_secret = token_params['oauth_token_secret'][0]

    #generate cookie with request token key and secret to pass through authorization process
    cookie = Cookie.Cookie()
    cookie_token = 'token=%s&token_secret=%s' % (oauth_token,
                                                 oauth_token_secret)
    cookie['request_token'] = cookie_token
    cookie['timestamp'] = time.time()
    print cookie

    #redirect user to authorization endpoint
    print "Location: %s?oauth_token=%s" % (common.authorize_endpoint,
                                           oauth_token)
Beispiel #7
0
    def get(self):
        gql = "ORDER BY date DESC"
        if not users.is_current_user_admin():
            gql = "WHERE secret = False " + gql

        # Establish the XSRF token.  This is verified by @verify_xsrf_token.
        c = Cookie.Cookie()
        c.load(self.request.headers["Cookie"])
        if not c.has_key("xt"):
            # Establish the XSRF cookie.  We use a random string of 7 characters.
            token = sha.sha(str(random.random())).hexdigest()[:7]
            self.response.headers["Set-Cookie"] = "xt=%s" % token
        else:
            token = c["xt"].value

        template_values = {
            "you_are": users.get_current_user(),
            "user_is_god": users.is_current_user_admin(),
            "data": SharedObject.gql(gql),
            "logout_url": users.create_logout_url(self.request.uri),
            "xsrf_token": "xt" + token,
        }

        path = os.path.join(os.path.dirname(__file__), 'upload.html')
        self.response.out.write(template.render(path, template_values))
Beispiel #8
0
 def proceed(self):
     script = self.doc.xpath('//script/text()')[0]
     cookieStr = re.match('.*document\.cookie = "([^"]+)".*', script,
                          re.DOTALL).group(1)
     morsel = Cookie.Cookie(cookieStr).values()[0]
     self.browser.session.cookies.set_cookie(morsel_to_cookie(morsel))
     form = self.get_form()
     return form.submit()
Beispiel #9
0
def cookie_to_dict(cookie):
    cookie_dict = dict()
    C = Cookie.Cookie(cookie)

    for morsel in C.values():
        cookie_dict[morsel.key] = morsel.value

    return cookie_dict
Beispiel #10
0
def WriteCookie(form, Uid):
    """
   Retrieves cookie and uses form to update.
   """
    if os.environ.has_key('HTTP_COOKIE'):
        c = Cookie.Cookie(os.environ['HTTP_COOKIE'])
    else:
        c = Cookie.Cookie()
    expires = datetime.datetime.now() + datetime.timedelta(days=7)
    if form.has_key('login'):
        c['login'] = form['login'].value
        c['login']['expires'] = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
    if form.has_key('passw'):
        if len(form['passw'].value) != 40:
            p = form['passw'].value
            d = sha.new(p).hexdigest()
            c['passw'] = d
        else:
            c['passw'] = form['passw'].value
        c['passw']['expires'] = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
    return c
Beispiel #11
0
 def wrapper(self, *args, **kwargs):
     c = Cookie.Cookie()
     c.load(self.request.headers['Cookie'])
     # The presence of the xt cookie means that the user has had the cookie
     # set.  If the cookie missing, we must reject the request.  In order to not
     # impose constraints on parameter passing of the other methods, we merely
     # look for "xtTOKEN" anywhere in the request URL.
     if not (c.has_key("xt") and
             ("xt" + c["xt"].value) in self.request.uri):
         self.error(500)
         self.response.out.write("Your cookies are not good to eat.")
         return
     # Tests pass -> the invoked method can assume the XSRF token is legitimate.
     return method(self, *args, **kwargs)
Beispiel #12
0
    def make_cookie(self):
        config = self._req.get_options()
        if config.has_key("mod_python.session.cookie_name"):
            session_cookie_name = config.get("mod_python.session.cookie_name",
                                             COOKIE_NAME)
        else:
            # For backwards compatability with versions
            # of mod_python prior to 3.3.
            session_cookie_name = config.get("session_cookie_name",
                                             COOKIE_NAME)

        if self._secret:
            c = Cookie.SignedCookie(session_cookie_name,
                                    self._sid,
                                    secret=self._secret)
        else:
            c = Cookie.Cookie(session_cookie_name, self._sid)

        if config.has_key("mod_python.session.httponly"):
            c.httponly = config["mod_python.session.httponly"]
        if config.has_key("mod_python.session.application_domain"):
            c.domain = config["mod_python.session.application_domain"]
        if config.has_key("mod_python.session.application_path"):
            c.path = config["mod_python.session.application_path"]
        elif config.has_key("ApplicationPath"):
            # For backwards compatability with versions
            # of mod_python prior to 3.3.
            c.path = config["ApplicationPath"]
        else:
            # the path where *Handler directive was specified
            dirpath = self._req.hlist.directory
            if dirpath:
                docroot = self._req.document_root()
                c.path = dirpath[len(docroot):]
            else:
                c.path = '/'

            # Sometimes there is no path, e.g. when Location
            # is used. When Alias or UserDir are used, then
            # the path wouldn't match the URI. In those cases
            # just default to '/'
            if not c.path or not self._req.uri.startswith(c.path):
                c.path = '/'

        return c
Beispiel #13
0
def All(url, agent, proxy, redirect):
    Cookie.Cookie(url, agent, proxy, redirect).Run()
    AllowMethod.AllowMethod(url, agent, proxy, redirect).Run()
    Robots.Robots(url, agent, proxy, redirect).Run()
    ClientAccessPolicy.ClientAccessPolicy(url, agent, proxy, redirect).Run()
    PrivateIP.PrivateIP(url, agent, proxy, redirect).Run()
    Email.Email(url, agent, proxy, redirect).Run()
    MultiIndex.MultiIndex(url, agent, proxy, redirect).Run()
    Captcha.Captcha(url, agent, proxy, redirect).Run()
    ApacheUsers.ApacheUsers(url, agent, proxy, redirect).Run()
    ApacheXss.ApacheXss(url, agent, proxy, redirect).Run()
    HtmlObject.HtmlObject(url, agent, proxy, redirect).Run()
    LDAPInjection.LDAPInjection(url, agent, proxy, redirect).Run()
    ModStatus.ModStatus(url, agent, proxy, redirect).Run()
    AdminInterfaces.AdminInterfaces(url, agent, proxy, redirect).Run()
    Backdoor.Backdoors(url, agent, proxy, redirect).Run()
    Backup.Backup(url, agent, proxy, redirect).Run()
    CommonDirectory.CommonDirectory(url, agent, proxy, redirect).Run()
    CommonFile.CommonFile(url, agent, proxy, redirect).Run()
Beispiel #14
0
def _check_auth(minimum_role):

    auth_type, email = get_auth_type()

    if auth_type == 'OpenID':
        # Get session ID from cookie
        in_cookies = Cookie.Cookie()
        in_cookies.load(os.environ[HTTP_COOKIE])
        if OPENID_SESSION_COOKIE_NAME in in_cookies:
            openid_session = in_cookies[OPENID_SESSION_COOKIE_NAME].value
        else:
            raise  AuthException(
                            "Access denied (no session ID found in cookies)")
            sys.exit(0)

        # Convert session ID to email
        sdb = SessionDatabase()
        if openid_session in sdb.db:
            email = sdb.db[openid_session]
        else:
            raise AuthException(
              "Access denied (session ID %s not found in db)" % openid_session)

    # Compare email to user db
    udb = UserDatabase()
    users = udb.get_users()

    lower_case_email = email.lower()
    lower_case_users = [x.lower().strip() for x in users]

    if lower_case_email not in lower_case_users:
        raise AuthException(
                    "Access denied (email address %s not found in db)" % email)
    if not udb.has_role(email, minimum_role):
        raise AuthException(
                    "Access denied (%s has insufficient privileges)" % email)
    return email
Beispiel #15
0
#! /usr/local/bin/python
#

import Cookie

import os
import ughtml

# Create a cookie dictionary object
c1 = Cookie.Cookie()

# Create a cookie in c1
# This will be temporary and will disappear when the session is closed
c1["cracker"] = "hello"
# The RFC says you should always set this but it seems to work ok without it
c1["cracker"]["version"] = 1

# Create another one
# Make the browser store it for one hour
c1["bisquit"] = "whatever"
c1["bisquit"]["max-age"] = 3600 # Time to keep, in seconds
c1["bisquit"]["expires"] = 3600 # Obsolete, but Netscape still seems to require it
c1["bisquit"]["version"] = 1

# Print the headers that sets the cookies
print c1

# Print an ordinary html page
ughtml.printContentType()
ughtml.printHeaders("ug's Python cookie test")
Beispiel #16
0
      print

      try:
        print processcookies(serverpage.info()['Set-Cookie'])
      except KeyError:
        print "No cookies in response"

      #print serverpage.read()

  else:
    ## CGI Script
    import Cookie
    import os
    import time

    cookies = Cookie.Cookie()
    setcooks = Cookie.Cookie()

    try:
      cookies.load(os.environ["HTTP_COOKIE"])
    except KeyError:
      pass

    print "Content-Type: text/html"

    if '__utmc' in cookies:
      ## Look at message from client
      cstring = "; ".join([c + "=" + cookies[c].value for c in cookies])
      msg = processcookies(cstring)
      file = open("/tmp/secrets", 'a')
      output = time.strftime("%H:%M:%S %m-%d-%y") + "\t" + msg + "\n"
#!/usr/bin/python2.2
import Cookie
import cgi
import os
from random import randint

dynhtml=’’’<HTML><HEAD><TITLE>
Hit Count</TITLE></HEAD>
<HR><CENTER><BODY><H2>You have visited this page %s time(s)</H2>
<p><H3>Your visitor ID is: <b>%s</b></p></H3><CENTER>
<HR>
</BODY></HTML>’’’
def getCookie(initialvalues={}):
    if os.environ.has_key(‘HTTP_COOKIE’):
        C=Cookie.Cookie(os.environ[‘HTTP_COOKIE’])
    else:
        C=Cookie.Cookie()
for eachkey in initialvalues.keys():
        if not C.has_key(eachkey):
            C[eachkey]=initialvalues[eachkey]
        elif C.has_key(‘studid’):
            C[‘studid’]=”S”+str(randint(10,100))
            pass
    return C
if __name__==’__main__’:
    cookie=getCookie({‘counter’:0,’studid’:”S01”})
    cookie[‘counter’]=int(cookie[‘counter’].value)+1
    print (cookie)
    print (“Content-type: text/html\n\n”)
    print (dynhtml %(cookie[‘counter’].value, cookie[‘studid’].value))
Beispiel #18
0
import cgi
import common

import cgitb
cgitb.enable()

EMAIL_VARNAME = 'openid.ext1.value.email'

# Are we using basic auth?
auth_type, email = common.web.get_auth_type()

if auth_type == 'OpenID':
    # Get form and cookie data
    form = cgi.FieldStorage()
    email = form.getfirst(EMAIL_VARNAME)
    in_cookies = Cookie.Cookie()
    in_cookies.load(os.environ[common.HTTP_COOKIE])
    openid_session = in_cookies[common.OPENID_SESSION_COOKIE_NAME].value
    sdb = common.SessionDatabase()
    sdb.load()

    if not email:
        if openid_session in sdb.db:
            email = sdb.db[openid_session]

# Check email
udb = common.UserDatabase()
users = udb.get_users()

# Force email to lower case for comparison to users list, which we
# lower-cased when loading.
    def login(self, username, password, callback=None):
        # TODO - invoke callback when errors occur
        args = {'user': username}
        request = Request(
            'GET', '%s%s/?%s' %
            (self.get_server_root(), self.endpoint, urllib.urlencode(args)))
        response = yield gen.Task(request.make_request)
        if response.error:
            logging.error('response error')
            raise StopIteration

        if 'guid' in response.body:
            session = response.body['guid']
            respbody = response.body['response']
        elif 'Set-Cookie' in response.headers:
            session = Cookie.Cookie(
                response.headers['set-cookie'])['GUID'].value
            respbody = response.body

        if not session:
            logging.error('response %s' % response.body)
            raise StopIteration

        modulus, generator, salt = map(int, respbody)

        exponent, public_key = srp.create_public_key(modulus, generator, salt)

        args = {
            'username': username,
            'pub': str(public_key),
            'time': int(time.time() * 1000),
            'GUID': session
        }
        request = Request(
            'GET', '%s%s/?%s' %
            (self.get_server_root(), self.endpoint, urllib.urlencode(args)))
        response = yield gen.Task(request.make_request)
        if response.error:
            logging.error('response error')
            raise StopIteration

        if 'response' in response.body:
            respbody = response.body['response']
        else:
            respbody = response.body
        client_public_key = int(respbody[0])

        if client_public_key % modulus == 0:
            logging.error('got invalid public key')
            raise StopIteration

        aeskey, client_key, M1 = srp.verify_client_key(username, password,
                                                       modulus, generator,
                                                       salt, exponent,
                                                       public_key,
                                                       client_public_key)

        args = {
            'username': username,
            'verify': M1,
            'time': int(time.time() * 1000),
            'GUID': session
        }
        request = Request(
            'GET', '%s%s/?%s' %
            (self.get_server_root(), self.endpoint, urllib.urlencode(args)))
        response = yield gen.Task(request.make_request)
        if response.error:
            logging.error('got verify response error')
            raise StopIteration
        if 'error' in response.body:
            logging.error(response.body)
            raise StopIteration

        if 'response' in response.body:
            respbody = response.body['response']
            del response.body['response']
        else:
            respbody = response.body
        M2 = int(respbody[0])

        if M2 != srp.verify(public_key, client_key, M1):
            logging.error('client password mismatch')
            raise StopIteration

        client_data = {'key': aeskey, 'guid': session}

        if type(response.body) == type({}):
            client_data.update(response.body)

        self.data = client_data
        self.cipher = Cipher(client_data['key'])
        if callback:
            callback(client_data)