class SessionSerializer(object): def __init__(self): self.__real_serializer = TaggedJSONSerializer() def dumps(self, value): serialized_str = self.__real_serializer.dumps(value) return aes_crypt(serialized_str, SERVER_SECRET_KEY) def loads(self, value): value = aes_decrypt(value, SERVER_SECRET_KEY).decode("utf-8") return self.__real_serializer.loads(value)
def serializerCompressed(key): return URLSafeTimedSerializer(secret_key=key, salt='cookie-session', serializer=TaggedJSONSerializer(), signer_kwargs={ 'key_derivation': 'hmac', 'digest_method': hashlib.sha1 })
def decode_flask_cookie(secret_key, cookie_str): salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = {'key_derivation': 'hmac', 'digest_method': hashlib.sha1} s = URLSafeTimedSerializer(secret_key, salt=salt, serializer=serializer, signer_kwargs=signer_kwargs) return s.loads(cookie_str)
def decode_flask_cookie(secret_key, cookie): salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = { 'key_derivation': 'hmac', 'digest_method': hashlib.sha1 # could also be another form of encryption (sha256, sha512) } s = URLSafeTimedSerializer(secret_key, serializer=serializer, salt=salt, signer_kwargs = signer_kwargs) return s.loads(cookie) # s.dumps({<cookie-data>}) for signing new cookie
def read_session(string: str) -> Any: serializer = TaggedJSONSerializer() signer_kwargs = dict(key_derivation='hmac', digest_method=hashlib.sha1) safeTimeSerializer = URLSafeTimedSerializer(SECRET_KEY, salt='cookie-session', serializer=serializer, signer_kwargs=signer_kwargs) max_age = 2678400 # 31 days data = safeTimeSerializer.loads(string, max_age=max_age) return data
def data(): salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = {'key_derivation': 'hmac', 'digest_method': hashlib.sha1} s = URLSafeTimedSerializer('Bsd405GradebookCas', salt=salt, serializer=serializer, signer_kwargs=signer_kwargs) newdict = s.loads(request.form['session']) student = user(newdict['username'], newdict['password']) student.login() return student.studentName
def encode_flask_cookie(secret_key, values): import hashlib from itsdangerous import URLSafeTimedSerializer from flask.sessions import TaggedJSONSerializer salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = { 'key_derivation': 'hmac', 'digest_method': hashlib.sha1 } s = URLSafeTimedSerializer(secret_key, salt=salt, serializer=serializer, signer_kwargs=signer_kwargs) return s.dumps(values)
def decode_flask_cookie(secret_key, cookie_str): import hashlib from itsdangerous import URLSafeTimedSerializer from flask.sessions import TaggedJSONSerializer salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = {'key_derivation': 'hmac', 'digest_method': hashlib.sha1} s = URLSafeTimedSerializer(secret_key, salt=salt, serializer=serializer, signer_kwargs=signer_kwargs) # return s.loads(cookie_str) print(s.loads(cookie_str))
def flask_cookie(secret_key, cookie_str, operation): # This function is a simplified version of the SecureCookieSessionInterface: https://github.com/pallets/flask/blob/020331522be03389004e012e008ad7db81ef8116/src/flask/sessions.py#L304. salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = {'key_derivation': 'hmac', 'digest_method': hashlib.sha1} s = URLSafeTimedSerializer(secret_key, salt=salt, serializer=serializer, signer_kwargs=signer_kwargs) if operation == "decode": return s.loads(cookie_str) else: return s.dumps(cookie_str)
def get_weight(): salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = {'key_derivation': 'hmac', 'digest_method': hashlib.sha1} s = URLSafeTimedSerializer('Bsd405GradebookCas', salt=salt, serializer=serializer, signer_kwargs=signer_kwargs) newdict = s.loads(request.form['session']) student = user(newdict['username'], newdict['password']) student.login() id = request.form['id'] return (json.dumps(student.getClassWeighting(id)))
class SessionInterface(FlaskSessionInterface): serializer = TaggedJSONSerializer() @staticmethod def _generate_sid(): return str(uuid4()) @staticmethod def _get_signer(app): if not app.secret_key: return None return Signer(app.secret_key, salt='flask-sessions', key_derivation='hmac')
def decode_flask_cookie( secret_key, cookie_str): # pass the SECRET_KEY, and COOKIE STRING VALUE ON BROWSER import hashlib from itsdangerous import URLSafeTimedSerializer from flask.sessions import TaggedJSONSerializer salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = {'key_derivation': 'hmac', 'digest_method': hashlib.sha1} s = URLSafeTimedSerializer(secret_key, salt=salt, serializer=serializer, signer_kwargs=signer_kwargs) return s.loads(cookie_str)
def crack_secret(secret): for id, signer in enumerate(signers): try: serializer = URLSafeTimedSerializer( secret_key=secret, salt='cookie-session', serializer=TaggedJSONSerializer(), signer=TimestampSigner, signer_kwargs={ 'key_derivation': 'hmac', 'digest_method': hashlib.sha1 }).loads(COOKIE) print(f"Secret key found: {secret}") except BadSignature: print(f"Bad secret - {id+1}")
def decode_session_cookie(cookie_str): ''' Decode a session object from an encoded session cookie. ''' # Credit: https://gist.github.com/babldev/502364a3f7c9bafaa6db salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = { 'key_derivation': 'hmac', 'digest_method': hashlib.sha1, } key = current_app.config.get("SECRET_KEY") s = URLSafeTimedSerializer(key, salt=salt, serializer=serializer, signer_kwargs=signer_kwargs) return s.loads(cookie_str)
# -*- coding: utf-8 -*- import hashlib from itsdangerous import URLSafeTimedSerializer from flask.sessions import TaggedJSONSerializer session_json_serializer = TaggedJSONSerializer() signer_kwargs = dict(key_derivation='hmac', digest_method=hashlib.sha1) key = '\xab\x80\xd2\x01\xf1F\xbc\x9e\xf4*o\x8e]\x81]NZt}N)\xb8A]' salt = 'cookie-session' serializer = URLSafeTimedSerializer(key, salt=salt, serializer=session_json_serializer, signer_kwargs=signer_kwargs) session_content = { 'user_id': 'admin', '_id': 'a2b16c036b629cb5a22c8f3d6779f2fd9dd3b0b7dc29f0555a0' } cookie_content = serializer.dumps(session_content) print cookie_content print serializer.loads(cookie_content)
def __init__(self): self.__real_serializer = TaggedJSONSerializer()
class BOFSSessionInterface(SessionInterface): serializer = TaggedJSONSerializer() def create_db_object(self, app, sessionID): storedSession = app.db.SessionStore() storedSession.sessionID = sessionID storedSession.expiry = datetime.utcnow() + timedelta(days=21) app.db.session.add(storedSession) app.db.session.commit() return storedSession def open_session(self, app, request): sessionID = request.cookies.get("session") # No sessionID cookie is set; create a new session. if not sessionID: sessionID = str(uuid4()) self.create_db_object(app, sessionID) return BOFSSession(None, sessionID=sessionID, new=True) storedSession = app.db.session.query( app.db.SessionStore).get(sessionID) # The database has no session info! The cookie exists, but the session is empty. if not storedSession: self.create_db_object(app, sessionID) return BOFSSession(None, sessionID=sessionID, new=True) # The session has been expired, so let's clear out the DB and give a blank session if storedSession.expired: print("Session expired; deleting it.") app.db.session.delete(storedSession) app.db.session.commit() return BOFSSession(None, sessionID=sessionID, new=True) # Try to load the data from the DB into the session dict try: val = storedSession.data data = self.serializer.loads(val) return BOFSSession(data, sessionID=sessionID) # All is well. except: # Nope. Something bad happened; send them a blank session return BOFSSession(None, sessionID=sessionID, new=True) def save_session(self, app, session, response): domain = self.get_cookie_domain(app) #path = self.get_cookie_path(app) path = "/" # We'll only ever want one cookie per project. # Looks like the session was deleted... delete the cookie. # We can't delete stuff from the DB as we don't know the ID. if not session: response.delete_cookie("session", domain=domain, path=path) return httpOnly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) storedSession = app.db.session.query(app.db.SessionStore).get( session.sessionID) # This must be a new session. if not storedSession: storedSession = self.create_db_object(app, session.sessionID) if session.modified: storedSession.data = self.serializer.dumps(dict(session)) if 'participantID' in session: storedSession.participantID = session['participantID'] if 'mTurkID' in session: storedSession.mTurkID = session['mTurkID'] # Only save if there's a reason to do so. if session.new or session.modified: app.db.session.commit() if session.new: response.set_cookie("session", session.sessionID, expires=storedSession.expiry, httponly=httpOnly, domain=domain, path=path, secure=secure)
from itsdangerous import URLSafeTimedSerializer # from itsdangerous import URLSafeSerializer from flask.sessions import TaggedJSONSerializer import hashlib val = 'xxxxxxx' secret_key = '30cbf7006ff9489c4e7b89075ece3913' salt = 'cookie-session' serializer = TaggedJSONSerializer() signer_kwargs = dict( key_derivation='hmac', digest_method=hashlib.sha1 ) s = URLSafeTimedSerializer(secret_key,salt=salt,serializer=serializer,signer_kwargs=signer_kwargs) print s.loads(val) new = s.loads(val) new['user_id']=54 print s.dumps(new)
class SuperSecureSessionInterface(SessionInterface): """ Skip all that unnecessary signing and hashing. Just set a plaintext cookie. """ session_class = SuperSecureSession serializer = TaggedJSONSerializer() def open_session(self, app, request): """ This method has to be implemented and must either return ``None`` in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes on :class:`SessionMixin`. """ data_str = request.cookies.get(app.session_cookie_name) if not data_str: return self.session_class() # HACK: encodes raw, unsigned cookie # attacker can simply change credentials in cookie to log in as any user try: data = self.serializer.loads(data_str) except ValueError: return None return self.session_class(data) def save_session(self, app, session, response): """ This is called for actual sessions returned by open_session at the end of the request. """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) # Delete case. If there is no session we bail early. # If the session was modified to be empty we remove the # whole cookie. if not session: if session.modified: response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return None # modification case if not self.should_set_cookie(app, session): return None httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) data_str = self.serializer.dumps(dict(session)) response.set_cookie(app.session_cookie_name, data_str, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def __init__(self, app, serializer=None, timestamp_key=None): self.key = crypto_generichash(app.secret_key, outlen=crypto_secretbox_KEYBYTES) self.serializer = serializer or TaggedJSONSerializer() self.timestamp_key = timestamp_key or '__session_timestamp__'