Example #1
0
def general_authenhandler(req, req_type, anon_ok=False):
	pw = req.get_basic_auth_pw()
	cookies = Cookie.get_cookies(req)
	if not cookies.has_key('csrftoken'):
		cookie = Cookie.Cookie('csrftoken', hashlib.md5(str(random.randrange(0, 2<<63))).hexdigest())
		cookie.path = '/'
		if config.get('session', 'cookie_host') != '':
			cookie.domain = config.get('session', 'cookie_host')
		Cookie.add_cookie(req, cookie)
	if cookies.has_key('myemsl_session'):
		sql = "select user_name from myemsl.eus_auth where session_id = %(sid)s"
		cnx = myemsldb_connect(myemsl_schema_versions=['1.0'])
		cursor = cnx.cursor()
		cursor.execute(sql, {'sid':cookies['myemsl_session'].value})
		rows = cursor.fetchall()
		found = False
		for row in rows:
			req.user = row[0]
			found = True
		if found:
			logger.debug("Session: %s", str(cookies['myemsl_session'].value))
#FIXME outage_check seems to be in the wrong place for a myemsl database outage.
			return outage_check(req, req_type)
	elif anon_ok:
		req.user = ''
		return outage_check(req, req_type)
	url = urllib.quote(req.unparsed_uri)
	redirect(req, "/myemsl/auth?url=%s" %(url))
	return apache.HTTP_UNAUTHORIZED
Example #2
0
def index(req):
 # check if cookie is set for respondent who already participated
 client_cookie = Cookie.get_cookie(req, 'rm-group-a')
 if client_cookie is None:
  Cookie.add_cookie(req, 'rm-group-a', 'true', expires=time.time()+31*24*3600) # expires after 1 month
 else:
  return 'You already participated.'
 
 # load current respondent conditions
 with open(PATH, 'r') as f:
  respondents = yaml.load(f)
  if respondents is None:
   respondents = []

  no_avatar_count = count_str_in_seq(NO_AVATAR, respondents)
  avatar_count = count_str_in_seq(AVATAR, respondents)

  if no_avatar_count <= MIN_RESPONDENTS and avatar_count >= MIN_RESPONDENTS:
   condition = NO_AVATAR
  elif no_avatar_count >= MIN_RESPONDENTS and avatar_count <= MIN_RESPONDENTS:
   condition = AVATAR
  else:
   condition = random.choice([NO_AVATAR, AVATAR])
 
 # write new condition entry
 with open(PATH, 'w') as f:
  respondents.append(condition)
  yaml.dump(respondents, f)
 util.redirect(req, 'welcome' + '-' + condition + '.html')
Example #3
0
def logout(req):
    cookies = Cookie.get_cookies(req)
    Cookie.add_cookie(req, 'ogtvogh', '', expires=time.time(), path='/')
    req.status=apache.HTTP_MOVED_TEMPORARILY
    req.headers_out["Location"] = SITEURL
    req.send_http_header()
    return "You have successfully logged out"
def general_authenhandler(req, req_type, anon_ok=False):
    pw = req.get_basic_auth_pw()
    cookies = Cookie.get_cookies(req)
    if not cookies.has_key('csrftoken'):
        cookie = Cookie.Cookie(
            'csrftoken',
            hashlib.md5(str(random.randrange(0, 2 << 63))).hexdigest())
        cookie.path = '/'
        if config.get('session', 'cookie_host') != '':
            cookie.domain = config.get('session', 'cookie_host')
        Cookie.add_cookie(req, cookie)
    if cookies.has_key('myemsl_session'):
        sql = "select user_name from myemsl.eus_auth where session_id = %(sid)s"
        cnx = myemsldb_connect(myemsl_schema_versions=['1.0'])
        cursor = cnx.cursor()
        cursor.execute(sql, {'sid': cookies['myemsl_session'].value})
        rows = cursor.fetchall()
        found = False
        for row in rows:
            req.user = row[0]
            found = True
        if found:
            logger.debug("Session: %s", str(cookies['myemsl_session'].value))
            #FIXME outage_check seems to be in the wrong place for a myemsl database outage.
            return outage_check(req, req_type)
    elif anon_ok:
        req.user = ''
        return outage_check(req, req_type)
    url = urllib.quote(req.unparsed_uri)
    redirect(req, "/myemsl/auth?url=%s" % (url))
    return apache.HTTP_UNAUTHORIZED
Example #5
0
    def _set_cookie(self, value, **attrs):
        """(session_id : string)

        Ensure that a session cookie with value 'session_id' will be
        returned to the client via the response object.

        Since Mod_Python has its own Cookie management system, we use it.
        """
        config = get_publisher().config
        name = config.session_cookie_name
        domain = config.session_cookie_domain

        if config.session_cookie_path:
            path = config.session_cookie_path
        else:
            path = get_request().get_environ('SCRIPT_NAME')
            if not path.endswith("/"):
                path += "/"

        expires = -1

        options = {'expires': expires,
                   'path': path }

        if domain is not None:
            options.update({'domain':domain})

        if value:
            Cookie.add_cookie(self.modpython_request, name, value, **options)

        return name
Example #6
0
 def __init__(self, req):
     """get, extract info, and do upkeep on the session cookie. This determines what the sessid and user are 
          for this request."""
     #pass the request in making in so we can edit it later if requested (ACL for example)
     self.ip = req.connection.remote_ip
     c = Cookie.get_cookies(req)
     if not c.has_key('mps'):
         self.sessid = Uid().new_sid(req)
     else:
         c = c['mps']
         self.sessid = c.value
         
     #make new cookie so the cycle continues
     c = Cookie.Cookie('mps', self.sessid)
     c.path = '/'
     Cookie.add_cookie(req, c)
     
     self.session_path = "%s%s"%(path_to_sessions, self.sessid)
     self.full_session_path = "%s%s"%(self.session_path, db_extension)
     
     #use previous authenication until cookie is reevaluated, if they are officially logged in (in Instance)
     if os.path.exists(self.full_session_path):
         session = shelve.open(self.session_path, 'rw')
         self.user  = session['USER_']
         session.close()
     else:
         self.user = self.unauthorized
Example #7
0
    def set_browser_info(self, info):
        """    sets the "state" info for the browser
        """

        #info = base64.encodestring(repr(info))
        info = repr(info)
        Cookie.add_cookie(self.req, Cookie.Cookie('browseinfo', info))
Example #8
0
def index(req):
    # check if cookie is set for respondent who already participated
    client_cookie = Cookie.get_cookie(req, 'rm-group-a')
    if client_cookie is None:
        Cookie.add_cookie(req,
                          'rm-group-a',
                          'true',
                          expires=time.time() +
                          31 * 24 * 3600)  # expires after 1 month
    else:
        return 'You already participated.'

    # load current respondent conditions
    with open(PATH, 'r') as f:
        respondents = yaml.load(f)
        if respondents is None:
            respondents = []

        no_avatar_count = count_str_in_seq(NO_AVATAR, respondents)
        avatar_count = count_str_in_seq(AVATAR, respondents)

        if no_avatar_count <= MIN_RESPONDENTS and avatar_count >= MIN_RESPONDENTS:
            condition = NO_AVATAR
        elif no_avatar_count >= MIN_RESPONDENTS and avatar_count <= MIN_RESPONDENTS:
            condition = AVATAR
        else:
            condition = random.choice([NO_AVATAR, AVATAR])

    # write new condition entry
    with open(PATH, 'w') as f:
        respondents.append(condition)
        yaml.dump(respondents, f)
    util.redirect(req, 'welcome' + '-' + condition + '.html')
Example #9
0
 def set(self,username):
     value = {
         "username": username
     }
     cookie = Cookie.MarshalCookie(self.cookie_key, value, secret=str(self.captureSettings["secretKey"]))
     cookie.path = "/"
     cookie.expires = time.time() + int(self.captureSettings["sessionCookiesTimeout"])
     Cookie.add_cookie(self.req, cookie)
Example #10
0
def _add_csrf_cookie_if_needed(req):
    signed_cookies = Cookie.get_cookies(req, Cookie.SignedCookie, secret=_get_secret())
    cookie = signed_cookies.get(settings.csrf_cookie_name, None)
    if cookie:
        # make sure we aren't altered
        if type(cookie) is Cookie.SignedCookie and cookie.value == _message_contents():
            return
    Cookie.add_cookie(req, _generate_csrf_cookie())
Example #11
0
 def set_cookie(self, coname, codata, expires=None):
     if self.reallympy:
         from mod_python import Cookie
         cookie = Cookie.Cookie(coname, codata)
         #for simplicity
         cookie.path = '/'
         if expires: cookie.expires = expires
         Cookie.add_cookie(self.mpyreq, cookie)
Example #12
0
 def __write_cookies(self):
     self.debug(2, "Output cookies:")
     for key in self.__cookies_out:
         self.debug(
             2, "Outputing cookie: %s ==> %s." %
             (key, self.__cookies_out[key]))
         # This is wierd....
         Cookie.add_cookie(self.__req, self.__cookies_out[key])
Example #13
0
 def send_cookies(self):
     """ sends the http headers for any cookies that need to be set
     """
     if self.req != None:
         for c in self._cookies:
             Cookie.add_cookie(self.req,c)
     else:
         for c in self._cookies:
             print c
Example #14
0
def index(req):
    req.content_type = "text/html"
    html = open("/var/www/html/templates/home.html").read()
    cookie_string = "False, RmFsc2U="
    cookie = Cookie.Cookie("admin", cookie_string)
    timestamp = time.time() + 300
    cookie.expires = timestamp
    Cookie.add_cookie(req, cookie)
    req.write(html)
Example #15
0
 def expire(self):
     value = {}
     cookie = Cookie.MarshalCookie(self.cookie_key,
                                   value,
                                   secret=str(
                                       self.captureSettings["secretKey"]))
     cookie.path = "/"
     cookie.expires = 0
     Cookie.add_cookie(self.req, cookie)
Example #16
0
def index(req):
    secret = 'my_secret'
    marshal_cookies = Cookie.get_cookies(req, Cookie.MarshalCookie, secret=secret)
    returned_marshal = marshal_cookies.get('marshal', None)
    if(returned_marshal):
        returned_marshal.expires= time.time()
        Cookie.add_cookie(req, returned_marshal)
        return '<html><body>return to main place <a href="./">here</a></body></html>'
    else:
        return '<html><title></title><body>there is nothing <a href="./">back</a></body></html>'
Example #17
0
    def set(self, var, val):

        ck = scs.encode(self.s, val, len(val))
        if ck is None:
            raise Exception, 'failed scs.encode()'
       
        c = Cookie.Cookie(var, ck)
        Cookie.add_cookie(self.req, c)
        
        return ck
Example #18
0
 def set(self, username):
     value = {"username": username}
     cookie = Cookie.MarshalCookie(self.cookie_key,
                                   value,
                                   secret=str(
                                       self.captureSettings["secretKey"]))
     cookie.path = "/"
     cookie.expires = time.time() + int(
         self.captureSettings["sessionCookiesTimeout"])
     Cookie.add_cookie(self.req, cookie)
Example #19
0
    def set(self, var, val):

        ck = scs.encode(self.s, val, len(val))
        if ck is None:
            raise Exception, 'failed scs.encode()'

        c = Cookie.Cookie(var, ck)
        Cookie.add_cookie(self.req, c)

        return ck
Example #20
0
def index(req):

    # get the network address of the client
    address = req.get_remote_host(apache.REMOTE_NOLOOKUP, None)

    # use the path from the request filename to locate the correct template
    name = req.filename[:req.filename.rindex('/')] + "/exitpage.html"
    file = open(name, "r")
    page = file.read()
    file.close()

    # load the app settings
    captureSettings = load_capture_settings(req)

    # setup the uvm and app objects so we can make the RPC call
    captureList = load_rpc_manager_list()

    # track the number of successful calls to userLogout
    exitCount = 0

    # call the logout function for each app instance
    cookie_key = "__ngfwcp"
    for app in captureList:
        exitResult = app.userLogout(address)
        cookies = Cookie.get_cookie(req, cookie_key)
        if cookies != None:
            value = {}
            cookie = Cookie.MarshalCookie(cookie_key,
                                          value,
                                          secret=str(
                                              captureSettings["secretKey"]))
            cookie.path = "/"
            cookie.expires = 0
            Cookie.add_cookie(req, cookie)

        if (exitResult == 0):
            exitCount = exitCount + 1

    if (exitCount == 0):
        page = replace_marker(page, '$.ExitMessage.$',
                              _('You were already logged out'))
        page = replace_marker(page, '$.ExitStyle.$', 'styleProblem')
    else:
        page = replace_marker(page, '$.ExitMessage.$',
                              _('You have successfully logged out'))
        page = replace_marker(page, '$.ExitStyle.$', 'styleNormal')

    page = replace_marker(page, '$.CompanyName.$',
                          captureSettings['companyName'])
    page = replace_marker(page, '$.PageTitle.$',
                          captureSettings['basicLoginPageTitle'])

    # return the logout page we just created
    return (page)
Example #21
0
def _add_csrf_cookie_if_needed(req):
    signed_cookies = Cookie.get_cookies(req,
                                        Cookie.SignedCookie,
                                        secret=_get_secret())
    cookie = signed_cookies.get(settings.csrf_cookie_name, None)
    if cookie:
        # make sure we aren't altered
        if type(cookie
                ) is Cookie.SignedCookie and cookie.value == _message_contents(
                ):
            return
    Cookie.add_cookie(req, _generate_csrf_cookie())
Example #22
0
def Cookie_Cookie(req):

    from mod_python import Cookie

    cookies = Cookie.get_cookies(req)

    for k in cookies:
        Cookie.add_cookie(req, cookies[k])

    req.write("test ok")

    return apache.OK
Example #23
0
def Cookie_Cookie(req):

    from mod_python import Cookie

    cookies = Cookie.get_cookies(req)

    for k in cookies:
        Cookie.add_cookie(req, cookies[k])

    req.write("test ok")
    
    return apache.OK
Example #24
0
def Cookie_MarshalCookie(req):

    from mod_python import Cookie

    cookies = Cookie.get_cookies(req, Cookie.MarshalCookie, secret="secret")

    for k in cookies:
        Cookie.add_cookie(req, cookies[k])

    req.write("test ok")

    return apache.OK
Example #25
0
def Cookie_MarshalCookie(req):

    from mod_python import Cookie

    cookies = Cookie.get_cookies(req, Cookie.MarshalCookie,
                                secret="secret")

    for k in cookies:
        Cookie.add_cookie(req, cookies[k])

    req.write("test ok")
    
    return apache.OK
Example #26
0
    def logout(self, REQUEST):
        """    logs out and redirects to main page
        """

        Cookie.add_cookie(self.req, Cookie.Cookie("sessionkey", "", expires=0))
        Cookie.add_cookie(self.req, Cookie.Cookie("browseinfo", "", expires=0))
        self.info = {}

        links = {"banner": "menu", "leftcontent": "advertising"}

        page = self.tmpl("logout")
        page.staticlink(links)

        return page
Example #27
0
	def setCookie(self,key,value,secret=None,expires=None,path=None):
		cookieType = Cookie.Cookie
		options = {}

		if expires != None: options['expires'] = expires
		if path != None: options['path'] = path
		if secret != None:
			cookieType = Cookie.MarshalCookie
			options['secret'] = secret

		Cookie.add_cookie(self.req, cookieType(key, value, **options))
		if expires==0 and not secret:
			self.cookieCache[key] = None
		elif not secret:
			self.cookieCache[key] = value
Example #28
0
def save(req):
    # Get a list with all the values of the selected_shows[]
    selected_shows = req.form.getlist('selected_shows[]')
    # Escape the user input to avoid script injection attacks
    selected_shows = map(lambda show: cgi.escape(show), selected_shows)
    
    # Value of the cookie is the list of selected shows seperated by ','
    cookie_str = ','.join(selected_shows)
    c = Cookie.Cookie('selected_shows', cookie_str, path='/')
    c.expires = time.time() + 30 * 24 * 60 * 60
    
    # Add the cookie to the HTTP header
    Cookie.add_cookie(req, c)
    
    util.redirect(req, 'http://localhost/wwia')
Example #29
0
    def set_cookie(self, varname, value, expires = None):
        # httponly tells the browser not to make this cookie available to Javascript.
        # But it is only available from Python 2.6+. Be compatible.
        try:
            c = Cookie.Cookie(varname, make_utf8(value), path='/', httponly=True)
        except AttributeError:
            c = Cookie.Cookie(varname, make_utf8(value), path='/')

        if self.is_ssl_request():
            c.secure = True

        if expires is not None:
            c.expires = expires

        self.set_http_header("Set-Cookie", str(c))
Example #30
0
    def init(self):

        # Parse the HTTP headers for variables and files.
        for field in self.__field_storage.list:

            # This is a normal variable.
            if str(type(field.file)) == "<type 'cStringIO.StringI'>" or \
                str(type(field.file)) == "<type 'cStringIO.StringO'>":
                self.set_var(field.name, field.value)

            # This is a file.
            else:
                # Some browsers give a full path instead of a file name. Some
                # browsers give an encoded file name. Plan for those cases.
                # FIXME: is the explanation above and the code below correct?
                filename = field.filename
                filename = urllib.unquote_plus(
                    filename
                )  # unquote filename (it should be encoded like an url)
                filename = re.sub(
                    r'\\+', '/', filename
                )  # some OS use "\" for paths... replace '\' in '/'
                filename = os.path.basename(
                    filename
                )  # some browsers (IE) send full path.. rip path part and just get file name
                self.__files[field.name] = KWebFile(filename, field.file)

        # Store the HTTP headers.
        for key in self.__req.headers_in:
            self.__headers_in[key] = self.__req.headers_in[key]

        # Initialize the cookies.
        self.__cookies_in = Cookie.get_cookies(self.__req)
Example #31
0
    def __init__(self, req=None, mod_python_session=None, FieldStorage_formdata=None):

        for item in self.attrs:
            setattr(self, item, None)

        try:
            self.remote_ip = req.connection.remote_ip
        except:
            self.remote_ip = "1.2.3.4"

        if req and req.headers_in.has_key("referer"):
            self.refURL = req.headers_in["referer"]
        else:
            self.refURL = None

        self.cookies = cookieData.cookieData(
            Cookie.get_cookies(req)
        )  # XZ: dictionary type. To hold values transfered from mod_python Cookie.

        # XZ: dictionary type. To hold values transfered from mod_python Session object. We assume that it is always picklable.
        self.input_session_data = sessionData.sessionData(mod_python_session)

        # XZ: FieldStorage_formdata may contain item that can't be pickled. Must convert to picklable data.
        self.formdata = cgiData(FieldStorage_formdata)

        # get Form ID
        self.formID = self.formdata.getfirst("FormID")

        # get rest of the attributes
        if self.formID:
            for item in self.attrs:
                value = self.formdata.getfirst(item)
                if value != None:
                    setattr(self, item, string.strip(value))

        self.ppolar = ""
        self.mpolar = ""
        if self.RISet:
            try:
                # NL, 07/27/2010. ParInfo has been moved from webqtlForm.py to webqtlUtil.py;
                f1, f12, self.mpolar, self.ppolar = webqtlUtil.ParInfo[self.RISet]
            except:
                f1 = f12 = self.mpolar = self.ppolar = None

        try:
            self.nperm = int(self.nperm)
            self.nboot = int(self.nboot)
        except:
            self.nperm = 2000  # XZ: Rob asked to change the default value to 2000
            self.nboot = 2000  # XZ: Rob asked to change the default value to 2000

        if self.allstrainlist:
            self.allstrainlist = map(string.strip, string.split(self.allstrainlist))
            # self.readGenotype()
            # self.readData()

        if self.RISet == "BXD300":
            self.RISet = "BXD"
        else:
            pass
Example #32
0
def accesshandler(request):

    cookies = Cookie.get_cookies(request)

    # if login ticket cookie does not exist, then deny
    if not cookies.has_key('login_ticket'):
        # just refuse access
        return apache.HTTP_FORBIDDEN

    ticket = cookies['login_ticket'].value
    if not ticket:
        return apache.HTTP_FORBIDDEN

    server = TacticServerStub.get(protocol='local')
    expr = "@SOBJECT(sthpw/ticket['ticket','%s'])" % ticket
    sobject = server.eval(expr, single=True)
    now = SPTDate.now()
    expiry = sobject.get("expiry")
    if expiry and expiry < str(now):
        return apache.HTTP_FORBIDDEN

    request.add_common_vars()
    path = str(request.subprocess_env['REQUEST_URI'])
    if path == None:
        return apache.HTTP_FORBIDDEN

    # FIXME: find some mechanism which is more acceptable ... like /icons
    #if path.find("_icon_") != -1:
    #    return apache.OK

    return apache.OK
Example #33
0
 def __init__(self,req=None, form=None):
     self.req = req
     if self.req != None:
         # mod_python
         self.form = util.FieldStorage(self.req)
         self._cookies_in = Cookie.get_cookies(self.req)
     else:
         # if we have a form, don't get a new one
         if form:
            self.form=form
         # if we don't have a form, then get one
         else:
            self.form = cgi.FieldStorage()
         self._cookies_in = SimpleCookie()
         try:
             self._cookies_in.load(os.environ["HTTP_COOKIE"])
         except KeyError:
             pass
     self._dispatch      = {}
     self._header_sent   = 0
     self._header_props  = {"Content-Type" : "text/html;charset=UTF-8"}
     self._header_props  = {}
     self._header_type   = "header"
     self._cookies       = []
     self._url           = ""
     self._environ       = os.environ
     self.template_dir   = 'templates'
     self.run_mode_param = 'rm'
     self.start_mode     = ''
     self.__globals__    = {}
     self.setup()
Example #34
0
def check_authen(req, vserver_name):
    """ If authenticated, return userid """

    try:
        cookies = Cookie.get_cookies(req,
                                     Class=RSASignedCookie.RSASignedCookie,
                                     secret=_get_pub_key())
    except RSASignedCookie.RSASignError:
        cookies = None

    if not cookies or not cookies.has_key('openvps-user'):
        login(req, vserver_name, message='please log in')
    else:
        try:
            login_time, userid = cookies['openvps-user'].value.split(':', 1)
            if (time.time() - int(login_time)) > TIMEOUT:
                login(req,
                      vserver_name,
                      message='session time-out, please log in again')
                return None
        except:
            login(req, vserver_name, message='please log in')
            return None

        return userid
Example #35
0
 def __init__(self,req,appid=None):
     self.req = req
     if appid == None:
         args = split_args(self.req.args);
         appid = args['APPID']
     self.captureSettings = load_capture_settings(self.req,appid)
     self.cookie = Cookie.get_cookies(self.req, Cookie.MarshalCookie, secret=str(self.captureSettings["secretKey"]))
 def get_cookie(cls, req, name):
     """Retreive cookie by name from request object."""
     #cookies = mod_python.Cookie.get_cookies(req)
     cookies = Cookie.get_cookies(req)
     this_cookie = cookies.get(name)
     value = cut(str(this_cookie), "{0}=".format(name))
     return value
Example #37
0
def create_user():
    import mod_python.Cookie as Cookie

    try:
        c = Cookie.get_cookies(global_variables.g_req,
                               Cookie.MarshalCookie,
                               secret='popcorn')
        if not 'session_id' in c:
            return None

        session_id = c["session_id"].value
    except (Cookie.CookieError, KeyError, Exception):
        return None

    import classes.class_user_factory as user_factory
    import exceptions.e_notregistered as e_notregistered
    import scripts.classes.class_dosql as sql

    dosql = sql.doSql()

    try:
        ((username, ), ) = dosql.execqry(
            "SELECT * FROM getUser('" + str(session_id) + "')", False)
        return user_factory.UserFactory().createUserFromID(username)
    except (e_notregistered.ENotRegistered, Exception):
        return None
Example #38
0
def accesshandler(request):

    cookies = Cookie.get_cookies(request)

    # if login ticket cookie does not exist, then deny
    if not cookies.has_key('login_ticket'):
        # just refuse access
        return apache.HTTP_FORBIDDEN

    ticket = cookies['login_ticket'].value
    if not ticket:
        return apache.HTTP_FORBIDDEN

    server = TacticServerStub.get(protocol='local')
    expr = "@SOBJECT(sthpw/ticket['ticket','%s'])" % ticket
    sobject = server.eval(expr, single=True)
    now = SPTDate.now()
    expiry = sobject.get("expiry")
    if expiry and expiry < str(now):
        return apache.HTTP_FORBIDDEN

    request.add_common_vars()
    path = str(request.subprocess_env['REQUEST_URI'])
    if path == None:
        return apache.HTTP_FORBIDDEN


    # FIXME: find some mechanism which is more acceptable ... like /icons
    #if path.find("_icon_") != -1:
    #    return apache.OK

    return apache.OK
Example #39
0
    def init(self):
        
        # Parse the HTTP headers for variables and files.
        for field in self.__field_storage.list:
            
            # This is a normal variable.
            if str(type(field.file)) == "<type 'cStringIO.StringI'>" or \
                str(type(field.file)) == "<type 'cStringIO.StringO'>":
                    self.set_var(field.name, field.value)
                
            # This is a file.
            else:
                # Some browsers give a full path instead of a file name. Some
                # browsers give an encoded file name. Plan for those cases.
                # FIXME: is the explanation above and the code below correct?
                filename = field.filename
                filename = urllib.unquote_plus(filename) # unquote filename (it should be encoded like an url)
                filename = re.sub(r'\\+', '/', filename) # some OS use "\" for paths... replace '\' in '/'
                filename = os.path.basename(filename) # some browsers (IE) send full path.. rip path part and just get file name
                self.__files[field.name] = KWebFile(filename, field.file)
        
        # Store the HTTP headers.
        for key in self.__req.headers_in:
            self.__headers_in[key] = self.__req.headers_in[key]

        # Initialize the cookies.
        self.__cookies_in = Cookie.get_cookies(self.__req)
Example #40
0
    def getCookies(self, cookieClass=None, secret=None):
        """Return a reference to the request cookies dictionary.
        Wrap in this method because the access is method is different
        depending on whether this is a CGI or PSP call.
        """
        cookieDict = None
        if self.req is not None:
            # PSP call
            import mod_python.Cookie
            if cookieClass == "signed" and secret is not None:
                #Signed Cookie
                cookieDict = mod_python.Cookie.get_cookies(
                    self.req, mod_python.Cookie.SignedCookie, secret=secret)
            else:
                #Non-signed, regular, less secure, user modifiable cookies
                cookieDict = mod_python.Cookie.get_cookies(self.req)
        else:
            # Assume is a CGI call
            import Cookie
            cookieDict = Cookie.SimpleCookie()
            if "HTTP_COOKIE" in os.environ:
                cookieDict.load(os.environ["HTTP_COOKIE"])

                #Set all default attributes, because they were all lost
                #Actually this does not have the desired affect, all cookies should be set to root path, but they are not.
                #Leaving it in here, perhaps some servers/clients support this
                for cookieName in cookieDict:
                    cookie = cookieDict[cookieName]
                    cookie.path = '/'
        return cookieDict
Example #41
0
def outputfilter_watermark(filter):

    s_in = None
    s_out = None
    try:
        s_in = StringIO(filter.read())
        im_in = Image.open(s_in)
        if im_in.size[0] <= 240 and im_in.size[1] <= 120:
            filter.write(s_in.getvalue())
            return

        # if this is a sub request, then don't process again
        req = filter.req
        if req.main:
            filter.write(s_in.getvalue())
            return

        cookies = Cookie.get_cookies(req)
        ticket = cookies['login_ticket'].value
        query = req.parsed_uri[apache.URI_QUERY]

        if query == "watermark=false":
            filter.write(s_in.getvalue())
            ticket_sobj = Ticket.get_by_valid_key(ticket)

            # if this is not a valid ticket, then just exit with no image
            if not ticket_sobj:
                return

            # TODO: need fancier algorithm here
            if ticket_sobj.get_value("login") == 'admin':
                filter.write(s_in.getvalue())
                return

        sizex = im_in.size[0]
        sizey = im_in.size[1]
        max_res = 240
        max_width = 640
        im_in = im_in.resize((max_res, int(sizey / (sizex / float(max_res)))))
        im_in = im_in.resize(
            (max_width, int(sizey / (sizex / float(max_width)))))

        # add the watermark
        watermark = Watermark()
        now = datetime.today().strftime("%Y/%m/%d, %H:%M")
        texts = ['Do Not Copy', ticket, now]
        sizes = [20, 10, 10, 20, 20]

        mark = watermark.generate(texts, sizes)
        im_out = watermark.execute(im_in, mark, 'tile', 0.5)

        s_out = StringIO()
        im_out.save(s_out, format='jpeg')
        filter.write(s_out.getvalue())

    finally:
        if s_in:
            s_in.close()
        if s_out:
            s_out.close()
Example #42
0
def index(req):

    # get the network address of the client
    address = req.get_remote_host(apache.REMOTE_NOLOOKUP,None)

    # use the path from the request filename to locate the correct template
    name = req.filename[:req.filename.rindex('/')] + "/exitpage.html"
    file = open(name, "r")
    page = file.read();
    file.close()

    # load the app settings
    captureSettings = load_capture_settings(req)

    # setup the uvm and app objects so we can make the RPC call
    captureList = load_rpc_manager_list()

    # track the number of successful calls to userLogout
    exitCount = 0

    # call the logout function for each app instance
    cookie_key = "__ngfwcp"
    for app in captureList:
        exitResult = app.userLogout(address)
        cookies = Cookie.get_cookie(req, cookie_key)
        if cookies != None:
            value = {}
            cookie = Cookie.MarshalCookie(cookie_key, value, secret=str(captureSettings["secretKey"]))
            cookie.path = "/"
            cookie.expires = 0
            Cookie.add_cookie(req, cookie)

        if (exitResult == 0):
            exitCount = exitCount + 1

    if (exitCount == 0):
        page = replace_marker(page,'$.ExitMessage.$', _('You were already logged out') )
        page = replace_marker(page,'$.ExitStyle.$', 'styleProblem')
    else:
        page = replace_marker(page,'$.ExitMessage.$', _('You have successfully logged out') )
        page = replace_marker(page,'$.ExitStyle.$', 'styleNormal')

    page = replace_marker(page,'$.CompanyName.$', captureSettings['companyName'])
    page = replace_marker(page,'$.PageTitle.$', captureSettings['basicLoginPageTitle'])

    # return the logout page we just created
    return(page)
def isValidSession(req):
    """
    check the Django's session table to decided this is a valid session or not.
    """

    # check for PythonOptions
    _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes')

    options = req.get_options()
    permission_name = options.get('DjangoPermissionName', None)
    staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on"))
    superuser_only = _str_to_bool(
        options.get('DjangoRequireSuperuserStatus', "off"))
    settings_module = options.get('DJANGO_SETTINGS_MODULE', None)
    if settings_module:
        os.environ['DJANGO_SETTINGS_MODULE'] = settings_module

    from django.conf import settings
    cookieName = settings.SESSION_COOKIE_NAME

    cookies = Cookie.get_cookies(req)
    if not cookies.has_key(cookieName):
        return False

    #import pdb; pdb.set_trace()
    sessionId = cookies[cookieName].value

    # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes
    # that so that the following import works
    os.environ.update(req.subprocess_env)

    from django.contrib.sessions.models import Session
    from django import db
    db.reset_queries()

    try:
        try:
            session = Session.objects.get(pk=sessionId)
        except Session.DoesNotExist:
            return False

        sessionData = session.get_decoded()
        if not sessionData.has_key('_auth_user_id'):
            # this is not a valid session!
            return False

        if session.expire_date > datetime.now():
            if isResourcesRequest(req):
                # just pass
                return True
            # this is a valid session, update the expre date!
            expiry = settings.SESSION_COOKIE_AGE
            session.expire_date = datetime.now() + timedelta(seconds=expiry)
            session.save()
            return True
        else:
            return False
    finally:
        db.connection.close()
def log_user_in(p_username):
	from mod_python import Cookie
	import time
	import uuid

	session_id = None

	while True:
		session_id = uuid.uuid4()

		((is_unique_session,),) = global_variables.g_sql.execqry("SELECT * FROM saveSessionID('" + str(session_id) + "', '" + p_username + "')", True)
		if is_unique_session:
			break

	c = Cookie.Cookie('session_id', session_id)
	c.expires = time.time() + 432000.0
	Cookie.add_cookie(global_variables.g_req, c)
Example #45
0
 def get_cookie(my, name):
     cookies = Cookie.get_cookies(my.request)
     cookie = cookies[name]
     if cookie == None:
         return ""
     else:
         my.error("cookie: "+cookie.value)
         return cookie.value
Example #46
0
def set_info(req):
        server_info=[]
        from cgi import escape
        name = escape(req.form['word'])
        host = escape(req.form['host_name'])
        password = escape(req.form['pas'])
        base_dn = escape(req.form['base_dn'])
        language = req.form['language']
        send_marshal = Cookie.MarshalCookie('marshal', {'key1':name, 'key2':password,'key3':host,'key4':base_dn,'key5':language}, secret)
        send_marshal.expires = time.time() +  4 * 60 * 60
        Cookie.add_cookie(req, send_marshal)
        server_info.append(name)
        server_info.append(password)
        server_info.append(host)
        server_info.append(base_dn)
        server_info.append(language)
        return server_info
Example #47
0
 def get_cookie(self, coname):
     if self.reallympy:
         from mod_python import Cookie
         cookie = Cookie.get_cookies(self.mpyreq)
         if cookie.has_key(coname):
             return cookie[coname].value
         else:
             return ''
Example #48
0
 def get_cookie(my, name):
     cookies = Cookie.get_cookies(my.request)
     cookie = cookies[name]
     if cookie == None:
         return ""
     else:
         my.error("cookie: " + cookie.value)
         return cookie.value
def isValidSession(req):
    """
    check the Django's session table to decided this is a valid session or not.
    """

    # check for PythonOptions
    _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes')

    options = req.get_options()
    permission_name = options.get('DjangoPermissionName', None)
    staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on"))
    superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off"))
    settings_module = options.get('DJANGO_SETTINGS_MODULE', None)
    if settings_module:
        os.environ['DJANGO_SETTINGS_MODULE'] = settings_module

    from django.conf import settings
    cookieName = settings.SESSION_COOKIE_NAME

    cookies = Cookie.get_cookies(req)
    if not cookies.has_key(cookieName):
        return False

    #import pdb; pdb.set_trace()
    sessionId = cookies[cookieName].value

    # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes
    # that so that the following import works
    os.environ.update(req.subprocess_env)

    from django.contrib.sessions.models import Session
    from django import db
    db.reset_queries()

    try:
        try:
            session = Session.objects.get(pk=sessionId)
        except Session.DoesNotExist:
            return False

        sessionData = session.get_decoded()
        if not sessionData.has_key('_auth_user_id'):
            # this is not a valid session!
            return False

        if session.expire_date > datetime.now():
            if isResourcesRequest(req):
                # just pass
                return True
            # this is a valid session, update the expre date!
            expiry = settings.SESSION_COOKIE_AGE
            session.expire_date = datetime.now() + timedelta(seconds=expiry)
            session.save()
            return True
        else:
            return False
    finally:
        db.connection.close()
Example #50
0
def index(req):
	charSet = 'abcdefghijlmnopqtsrvwxz1234567890ABCDEFGHIJLMNOPQTSRVWXZ'
	tstamp = time.time() + 2000
	a_cookie = Cookie.Cookie('mySweetAuth', mmfao2K98Lbkkg(charSet, 12) + '__' + str(tstamp))
	a_cookie.expires = tstamp
	Cookie.add_cookie(req, a_cookie)
	return generateDir(req, 'index')
	"""
		Generates the directory page content (profile boxes) - this is a actual page
		!! might be duplicate for def generateDir()
	"""
	# cookies = mod_python.Cookie.get_cookies(req)

	# cookies = Cookie.SimpleCookie()
	# print cookies['manca'].value
	

	"""
Example #51
0
def login(req,user='',passwd=''):
    cryptedpasswd = ''
    f = open('/etc/apache2/passwords')
    for line in f:
        if user == line.split(':')[0]:
            cryptedpasswd = line.split(':')[1]
            f.close()
            break
    f.close()
    if cryptedpasswd == '':
        return "Unknown user"
    if cryptedpasswd != crypt.crypt(passwd,cryptedpasswd):
        return "Incorrect password"
    Cookie.add_cookie(req, 'ogtvogh', crypt.crypt(passwd,cryptedpasswd), expires=time.time()+36000, path='/')
    req.status=apache.HTTP_MOVED_TEMPORARILY
    req.headers_out["Location"] = SITEURL
    req.send_http_header()
    return "You have successfully logged in"
Example #52
0
def log_user_in(p_username):
    from mod_python import Cookie
    import time
    import uuid

    session_id = None

    while True:
        session_id = uuid.uuid4()

        ((is_unique_session, ), ) = global_variables.g_sql.execqry(
            "SELECT * FROM saveSessionID('" + str(session_id) + "', '" +
            p_username + "')", True)
        if is_unique_session:
            break

    c = Cookie.Cookie('session_id', session_id)
    c.expires = time.time() + 432000.0
    Cookie.add_cookie(global_variables.g_req, c)
Example #53
0
def authorize(req):
    cookies = Cookie.get_cookies(req)
    if cookies.has_key("ogtvogh"):
        user = str(cookies["ogtvogh"]).split('=')[1]
        f = open('/etc/apache2/passwords')
        for line in f:
            if user == line.split(':')[1]:
                f.close()
                return 'auth'
    return ''
Example #54
0
 def __init__(self, req, appid=None):
     self.req = req
     if appid == None:
         args = split_args(self.req.args)
         appid = args['APPID']
     self.captureSettings = load_capture_settings(self.req, appid)
     self.cookie = Cookie.get_cookies(
         self.req,
         Cookie.MarshalCookie,
         secret=str(self.captureSettings["secretKey"]))
Example #55
0
    def addCookie(self,
                  key,
                  value,
                  cookieClass=None,
                  secret=None,
                  cookieAttributes=[]):
        """Simplest case of adding a name-value pair cookie for session persistence.
        """
        if self.req is not None:
            # PSP call
            import mod_python.Cookie
            # Check to see if this should be a signed cookie, or a regular cookie
            cookie = mod_python.Cookie.Cookie(key, value)

            #Go through and assign all cookie attributes, I know this is cool right?  Variable vaiables!
            for attribute in cookieAttributes:
                if isinstance(attribute['value'], int):
                    exec "cookie.%s = %s" % (attribute['name'],
                                             attribute['value'])
                else:
                    exec "cookie.%s = '%s'" % (attribute['name'],
                                               attribute['value'])

            #Add cookie to header
            mod_python.Cookie.add_cookie(self.req, cookie)
        else:
            # Assume is a CGI call
            import Cookie
            if os.environ.has_key("HTTP_COOKIE"):
                cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
            else:
                cookie = Cookie.SimpleCookie()

            #Define cookie name and value
            cookie[key] = value

            #Go through and assign all cookie attributes
            for attribute in cookieAttributes:
                cookie[key][attribute['name']] = attribute['value']

            #This is the actual header output and will eventually happen in printHeaders response method
            os.environ["HTTP_COOKIE"] = cookie.output(header='')
Example #56
0
    def set_cookie(self, varname, value, expires = None):
        c = Cookie.Cookie(varname, value, path = '/')
        if expires is not None:
            c.expires = expires

        if not self.req.headers_out.has_key("Set-Cookie"):
            self.req.headers_out.add("Cache-Control", 'no-cache="set-cookie"')
            self.req.err_headers_out.add("Cache-Control", 'no-cache="set-cookie"')

        self.req.headers_out.add("Set-Cookie", str(c))
        self.req.err_headers_out.add("Set-Cookie", str(c))
Example #57
0
    def set_cookie(self, varname, value, expires = None):
        # httponly tells the browser not to make this cookie available to Javascript
        c = Cookie.Cookie(varname, make_utf8(value), path='/', httponly=True)

        if self.is_ssl_request():
            c.secure = True

        if expires is not None:
            c.expires = expires

        self.set_http_header("Set-Cookie", str(c))
Example #58
0
def index(req):
    req.content_type = "text/html"
    html = open("/var/www/html/templates/admin.html").read()
    t = Template(html)
    cookie = Cookie.get_cookie(req, "admin")
    if cookie:
        if str(cookie.value) == "True, VHJ1ZQ==":
            req.write(t.render(text=open("/opt/flag.txt").read()))
        else:
            req.write(t.render(text="LOL get out you are not the admin!"))
    else:
        req.write(t.render(text="LOL get out you are not the admin!"))
Example #59
0
def index(req):

    req.content_type = 'text/html; charset=utf-8'
    form = req.form or util.FieldStorage(req)
    txt = '{}'

    v = search(r'view\.py\?v=(.*)$', req.unparsed_uri, re.DOTALL)

    a = form.get('a', None)  # action
    n = form.get('n', None)  # number
    f = form.get('f', None)  # file
    c = form.get('c', None)  # command

    if v:
        obj = play_obj(v)
        playURL(v, getOption(req))
        txt = json.dumps(obj.__dict__)

    elif f:
        obj = play_obj(f)
        playURL(f)
        txt = json.dumps(obj.__dict__)

    elif a:
        obj = act_obj(a, n)
        sendACT(a, n)
        txt = json.dumps(obj.__dict__)

    elif c:
        status = handleCmd(c)
        obj = cmd_obj(status)
        txt = json.dumps(obj.__dict__)

    pb_cookie = Cookie.Cookie('playbackMode',
                              xurl.readLocal(conf.playbackMode))
    Cookie.add_cookie(req, pb_cookie)
    req.write(txt)

    return
Example #60
0
def Session_Session(req):

    from mod_python import Session, Cookie
    s = Session.Session(req)
    if s.is_new():
        s.save()

    cookies = Cookie.get_cookies(req)
    if cookies.has_key(Session.COOKIE_NAME) and s.is_new():
        req.write(str(cookies[Session.COOKIE_NAME]))
    else:
        req.write("test ok")

    return apache.OK