def decode(cls, session_cookie_value, secret_key=None):
        """ Decode a Flask cookie  """
        try:
            if(secret_key==None):
                compressed = False
                payload = session_cookie_value

                if payload.startswith('.'):
                    compressed = True
                    payload = payload[1:]

                data = payload.split(".")[0]

                data = base64_decode(data)
                if compressed:
                    data = zlib.decompress(data)

                return data
            else:
                app = MockApp(secret_key)

                si = SecureCookieSessionInterface()
                s = si.get_signing_serializer(app)

                return s.loads(session_cookie_value)
        except Exception as e:
            return "[Decoding error] {}".format(e)
            raise e
Beispiel #2
0
def encode(data):
    from flask.sessions import SecureCookieSessionInterface
    # Dump back to string and encode
    app = FakeApp(SECRET_KEY)
    si = SecureCookieSessionInterface()
    s = si.get_signing_serializer(app)
    return s.dumps(data)
Beispiel #3
0
 def get_expiration_time(self, app, session):
     if "permanent_session" in session and session[
             "permanent_session"] is True:
         return None
     if "permanent_session" in g and g.permanent_session is True:
         return None
     SecureCookieSessionInterface.get_expiration_time(self, app, session)
    def decode(cls, session_cookie_value, secret_key=None):
        """ Decode a Flask cookie  """
        try:
            if (secret_key == None):
                compressed = False
                payload = session_cookie_value

                if payload.startswith('.'):
                    compressed = True
                    payload = payload[1:]

                data = payload.split(".")[0]

                data = base64_decode(data)
                if compressed:
                    data = zlib.decompress(data)

                return data
            else:
                app = MockApp(secret_key)

                si = SecureCookieSessionInterface()
                s = si.get_signing_serializer(app)

                return s.loads(session_cookie_value)
        except Exception as e:
            return "[Decoding error] {}".format(e)
            raise e
Beispiel #5
0
    def flask_encode(self, string):
        """
        flask session编码

        Description:
            通过get_signing_serializer获取签名后的序列化对象
            注意 传入的对象应为JSON字符串
                 签名必须带有secret_key

        Example:
            >>>Codec(key="hello").flask_encode('{"name":"DEADF1SH_CAT","module":"codec"}')
            eyJtb2R1bGUiOnsiIGIiOiJZMjlrWldNPSJ9LCJuYW1lIjp7IiBiIjoiUkVWQlJFWXhVMGhmUTBGVSJ9fQ.X2hcRA.fefBBFWPW96SiC8rhAr6bgLxcHo
        """
        try:
            session_cookie = dict(ast.literal_eval(string))
            if(self.secret_key == None):
                self.secret_key = ""
            sign = SecureCookieSessionInterface()
            serializer = sign.get_signing_serializer(self)
            result = serializer.dumps(session_cookie)

            return result
        except AttributeError:
            raise AttributeError("Secret_key can't be NULL!")
        except ValueError:
            raise ValueError("Data not JSON string!")
Beispiel #6
0
def validate_signed_grant(auth_header):
    """
    Validates a signed grant as found inside an auth header and returns whether it points to a valid
    grant.
    """
    if not auth_header:
        return ValidateResult(AuthKind.signed_grant, missing=True)

    # Try to parse the token from the header.
    normalized = [part.strip() for part in auth_header.split(" ") if part]
    if normalized[0].lower() != "token" or len(normalized) != 2:
        logger.debug("Not a token: %s", auth_header)
        return ValidateResult(AuthKind.signed_grant, missing=True)

    # Check that it starts with the expected prefix.
    if not normalized[1].startswith(SIGNATURE_PREFIX):
        logger.debug("Not a signed grant token: %s", auth_header)
        return ValidateResult(AuthKind.signed_grant, missing=True)

    # Decrypt the grant.
    encrypted = normalized[1][len(SIGNATURE_PREFIX) :]
    ser = SecureCookieSessionInterface().get_signing_serializer(app)

    try:
        token_data = ser.loads(encrypted, max_age=app.config["SIGNED_GRANT_EXPIRATION_SEC"])
    except BadSignature:
        logger.warning("Signed grant could not be validated: %s", encrypted)
        return ValidateResult(
            AuthKind.signed_grant, error_message="Signed grant could not be validated"
        )

    logger.debug("Successfully validated signed grant with data: %s", token_data)
    return ValidateResult(AuthKind.signed_grant, signed_data=token_data)
Beispiel #7
0
def get_socket_session():
    """ Returns basic user info """
    user = request.oauth.user
    session_serializer = SecureCookieSessionInterface().get_signing_serializer(
        current_app)

    return jsonify(token=session_serializer.dumps({'uid': user.uid}))
Beispiel #8
0
def session_cookie_encoder(secret_key, session_cookie_structure):
    """ Encode a Flask session cookie

    Example:
        cookie_structure = dict(
        	gplus_id     = 1285135705050360459231,
            email        = [email protected],
            user_info    = dict(
                            full_name = john doe,
                        )
        )
        session_cookie_encoder(b'development key', cookie_structure)

    Args:
        secret_key (string): Flask App secret key
        session_cookie_structure (dict): Flask session cookie structure

    Return:
        value (string): Flask session cookie
    """
    try:
        app = MockApp(secret_key)

        session_cookie_structure = dict()
        si = SecureCookieSessionInterface()
        s = si.get_signing_serializer(app)

        return s.dumps(session_cookie_structure)
    except Exception as e:
        return "[Encoding error]{}".format(e)
Beispiel #9
0
class SessionHook(object):
    def __init__(self):
        self.session_interface = SecureCookieSessionInterface()

    def on_response(self, app: DummyFlaskApp, resp: http.Response,
                    session: Session):
        if session is not None:
            self.session_interface.save_session(app, session, resp)
Beispiel #10
0
 def __init__(self, secret_key=None):
     self.compressed = False
     if secret_key is None:
         self.session_serializer = None
     else:
         app = Flask(__name__)
         app.secret_key = secret_key
         self.session_serializer = SecureCookieSessionInterface(
         ).get_signing_serializer(app)
Beispiel #11
0
def get_session_cookie(data, secret_key):
    """Get session with data stored in it"""
    app = Flask("sploit")
    app.secret_key = secret_key

    session_serializer = SecureCookieSessionInterface().get_signing_serializer(
        app)

    return session_serializer.dumps(data)
Beispiel #12
0
def index():
    scsi = SecureCookieSessionInterface()
    ser = scsi.get_signing_serializer(app)
    session['_fresh'] = True
    session[
        '_id'] = u'ff2303a3a71ab7616f64b0b690214c5e1898a538674218bca25427a021cbc0bdd00f9c38e2d9fa4e6745aa27628c23442d2f48364cb533df5729ace743ba07e1'
    session['user_id'] = u'1'
    session['remember'] = u'set'
    return ser.dumps(u'admin')
Beispiel #13
0
    def test_user_info(self):
        with self.client as c:
            account_data = self.real_user.id
            url = url_for('userinfoview', account_data=account_data)
            # Unauthenticated should return 401
            r = c.get(url)
            self.assertStatus(r, 401)

            client = self._create_client('priviledged_client_id', self.real_user.id, scopes='adsws:internal')
            token = self._create_token('priviledged_client_id', self.real_user.id, scopes='adsws:internal')

            user_id = self.real_user.id
            client_id = client.client_id
            expected_hashed_user_id = binascii.hexlify(hashlib.pbkdf2_hmac('sha256', str(user_id), current_app.secret_key, 10, dklen=32)) if user_id else None
            expected_hashed_client_id = binascii.hexlify(hashlib.pbkdf2_hmac('sha256', str(client_id), current_app.secret_key, 10, dklen=32)) if client_id else None

            # Authenticated requests (using a client that has the required scope)
            # and using an 1) user id
            headers={'Authorization': 'Bearer:{}'.format(token.access_token)}
            r = c.get(url, headers=headers)
            self.assertStatus(r, 200)
            self.assertEqual(r.json['hashed_user_id'], expected_hashed_user_id)
            self.assertEqual(r.json['hashed_client_id'], expected_hashed_client_id)
            self.assertFalse(r.json['anonymous'])
            self.assertEqual(r.json['source'], 'user_id')
            expected_json = r.json

            # 2) access token
            account_data = token.access_token
            url = url_for('userinfoview', account_data=account_data)
            r = c.get(url, headers=headers)
            self.assertStatus(r, 200)
            expected_json['source'] = u'access_token'
            self.assertEqual(r.json, expected_json)

            # 3) client id
            account_data = client.client_id
            url = url_for('userinfoview', account_data=account_data)
            r = c.get(url, headers=headers)
            self.assertStatus(r, 200)
            expected_json['source'] = u'client_id'
            self.assertEqual(r.json, expected_json)

            # 4) session
            #
            # Encode first a session cookie using the current app secret:
            sscsi = SecureCookieSessionInterface()
            signingSerializer = sscsi.get_signing_serializer(current_app)
            session = signingSerializer.dumps({'_id': 'session_id', 'oauth_client': client.client_id})

            account_data = session
            url = url_for('userinfoview', account_data=account_data)
            r = c.get(url, headers=headers)
            self.assertStatus(r, 200)
            expected_json['source'] = u'session:client_id'
            self.assertEqual(r.json, expected_json)
Beispiel #14
0
def generate_signed_token(grants, user_context):
    """ Generates a signed session token with the given grants and user context. """
    ser = SecureCookieSessionInterface().get_signing_serializer(app)
    data_to_sign = {
        'grants': grants,
        'user_context': user_context,
    }

    encrypted = ser.dumps(data_to_sign)
    return '{0}{1}'.format(SIGNATURE_PREFIX, encrypted)
Beispiel #15
0
    def connectionMade(self):
        s = SecureCookieSessionInterface()
        signing_serializer = s.get_signing_serializer(app)
        sessionid = self.transport.transport.request.getCookie('session')
        session = signing_serializer.loads(sessionid,
                                           max_age=total_seconds(
                                               app.permanent_session_lifetime))
        user_pk = session.get('user_pk')
        self.user = User(pk=user_pk) if user_pk else None

        self.play()
Beispiel #16
0
    def connectionMade(self):
        s = SecureCookieSessionInterface()
        signing_serializer = s.get_signing_serializer(app)
        sessionid = self.transport.transport.request.getCookie('session')
        session = signing_serializer.loads(
            sessionid,
            max_age=total_seconds(app.permanent_session_lifetime)
        )
        user_pk = session.get('user_pk')
        self.user = User(pk=user_pk) if user_pk else None

        self.play()
Beispiel #17
0
def init():
    adminsession = dict()
    adminsession['password'] = os.environ.get('ADMIN_PASS')
    session_serializer = SecureCookieSessionInterface().get_signing_serializer(
        app)
    cookie = session_serializer.dumps(adminsession)
    os.environ['ADMIN_COOKIE'] = str(cookie)
    flag_cids = json.dumps([os.environ.get('FLAG_CID')])
    os.environ['ADMIN_CIDS'] = flag_cids
    with app.app_context():
        add_comment(os.environ.get('FLAG'), os.environ.get('ADMIN_PASS'),
                    os.environ.get('FLAG_CID'))
def session_cookie_encoder(secret_key, session_cookie_structure):
    """ Encode a Flask session cookie """
    try:
        app = MockApp(secret_key)

        session_cookie_structure = dict(ast.literal_eval(session_cookie_structure))
        si = SecureCookieSessionInterface()
        s = si.get_signing_serializer(app)

        return s.dumps(session_cookie_structure)
    except Exception as e:
        return "[Encoding error]{}".format(e)
Beispiel #19
0
def session_cookie_encoder(url):
    try:
        app = Flask(__name__)
        app.secret_key = 'v3ry_v3ry_s3cr37_k3y'

        session_cookie_structure = {"url": url}
        si = SecureCookieSessionInterface()
        s = si.get_signing_serializer(app)

        return s.dumps(session_cookie_structure)
    except Exception as e:
        return "[Encoding error]{}".format(e)
    def encode(cls, secret_key, session_cookie_structure):
        """ Encode a Flask session cookie """
        try:
            app = MockApp(secret_key)

            session_cookie_structure = dict(ast.literal_eval(session_cookie_structure))
            si = SecureCookieSessionInterface()
            s = si.get_signing_serializer(app)

            return s.dumps(session_cookie_structure)
        except Exception as e:
            return "[Encoding error] {}".format(e)
            raise e
Beispiel #21
0
 def __init__(self, old_interface=None, new_interface=None):
     if old_interface is None:
         old_interface = OldSecureCookieSessionInterface()
     if new_interface is None:
         new_interface = SecureCookieSessionInterface()
     self.old_interface = old_interface
     self.new_interface = new_interface
Beispiel #22
0
class SessionComponent(Component):
    def __init__(self):
        self.dummy_request = namedtuple("Request", "cookies")
        self.session_interface = SecureCookieSessionInterface()

    def resolve(self, app: DummyFlaskApp,
                cookies: typing.Dict[str, Cookie]) -> Session:
        request = self.dummy_request(cookies=cookies)
        return self.session_interface.open_session(app, request)
Beispiel #23
0
    def flask_decode(self, string):
        """
        flask session解码

        Description:
            通过字符串头部是否包含“.”验证是否数据经过压缩,若有,则解压缩
            通过签名对象,直接解码出数据
            注意 不设置密钥时只返回解压缩后加密的data

        Example:
            >>>Code(key="hello").flask_decode('eyJtb2R1bGUiOnsiIGIiOiJZMjlrWldNPSJ9LCJuYW1lIjp7IiBiIjoiUkVWQlJFWXhVMGhmUTBGVSJ9fQ.X2hcdg.z_SIMDwrUNk0OEedqvrbEEF_fGI')
            {"name": "DEADF1SH_CAT", "module": "codec"}
            >>>Codec(key="").flask_decode('eyJtb2R1bGUiOnsiIGIiOiJZMjlrWldNPSJ9LCJzYW5nZm9yIjp7IiBiIjoiVTFKSiJ9fQ.Xfc4bg._sHWpX1GPy0q7qHpJIzqzLDM0TM')
            {"module":{" b":"Y29kZWM="},"name":{" b":"REVBREYxU0hfQ0FU"}}
        """
        try:
            session_cookie_value = string
            if(self.secret_key == None or self.secret_key == ""):
                compressed = False
                payload = session_cookie_value

                #判断payload是否经过压缩    
                if payload.startswith('.'):
                    compressed = True
                    payload = payload[1:]

                data = payload.split(".")[0]
                
                #解压payload数据
                data = base64_decode(data)
                if compressed:
                    data = zlib.decompress(data)

                return data
            else:
                #验证签名
                sign = SecureCookieSessionInterface()
                serializer = sign.get_signing_serializer(self)
                result = json.dumps(serializer.loads(session_cookie_value))

                return result
        except AttributeError:
            raise AttributeError("Secret_key can't be NULL!")
Beispiel #24
0
	def __init__(self):
		scsi = SecureCookieSessionInterface()
		signer_kwargs = dict(
			key_derivation=scsi.key_derivation,
			digest_method=scsi.digest_method
		)
		self.serializer = URLSafeTimedSerializer(SECRET_KEY, salt=scsi.salt,
										serializer=scsi.serializer,
										signer_kwargs=signer_kwargs
										)
Beispiel #25
0
def flask_cookie_decode(app, cookie):
    if not app.secret_key:
        compressed = False
        payload = cookie

        if payload.startswith('.'):
            compressed = True
            payload = payload[1:]

        data = payload.split(".")[0]

        data = base64_decode(data)
        if compressed:
            data = zlib.decompress(data)

        return data
    else:
        si = SecureCookieSessionInterface()
        s = si.get_signing_serializer(app)
        return s.loads(cookie)
Beispiel #26
0
    def init_app(self, app):
        """Initalizes the application with the extension."""
        self._session_interface = SecureCookieSessionInterface()
        self._signing_serializer = self._session_interface.get_signing_serializer(app)
        self._timestamp_signer = TimestampSigner(
            app.secret_key, key_derivation="hmac", salt="cookie-session"
        )
        self._max_age = total_seconds(app.permanent_session_lifetime)

        cookie_cli = AppGroup(
            "cookie", help="Tools to inspect the Flask session cookie."
        )
        app.cli.add_command(cookie_cli)

        @cookie_cli.command("decode")
        @click.argument("cookie")
        def decode(cookie):
            """Decode a flask session cookie"""
            decoded_cookie = self.decode_cookie(cookie)
            click.echo(decoded_cookie)

        app.extensions["flask_cookie_decode"] = self
Beispiel #27
0
class FlaskEncoder(object):

    salt = "cookie-session"

    def __init__(self, secret_key=None):
        self.compressed = False
        if secret_key is None:
            self.session_serializer = None
        else:
            app = Flask(__name__)
            app.secret_key = secret_key
            self.session_serializer = SecureCookieSessionInterface(
            ).get_signing_serializer(app)

    def decode(self, cookie):
        if self.session_serializer is None:
            payload = cookie
            if payload.startswith('.'):
                self.compressed = True
                payload = payload[1:]
            data = payload.split(".")[0]
            data = base64_decode(data)
            if self.compressed:
                data = zlib.decompress(data)
            return json.loads(data.decode("utf-8"))
        else:
            return self.session_serializer.loads(cookie)

    def encode(self, cookie, secret_key=None):
        if self.session_serializer is None:
            if self.compressed:
                cookie = "." + base64_encode(zlib.compress(cookie))
            else:
                cookie = base64_encode(cookie)
            return cookie
        else:
            return self.session_serializer.dumps(cookie)
Beispiel #28
0
def create_app(package_name, config_filename, **kwargs):
    app = Flask(package_name, **kwargs)

    app.config.from_pyfile(config_filename)

    app.session_interface = SecureCookieSessionInterface()
    app.session_interface.key_derivation = None

    # 添加错误日志处理模块
    add_logger_handler(app)

    # 将后端返回的json数据进行压缩减少传输
    Compress(app)

    return app
def sign(val):
    scsi = SecureCookieSessionInterface()
    ser = scsi.get_signing_serializer(app)
    return ser.dumps(val)
Beispiel #30
0
config = script.config

app = Flask('acoustid.web')
app.config.update(
    DEBUG=config.website.debug,
    SECRET_KEY=config.website.secret,
    MB_OAUTH_CLIENT_ID=config.website.mb_oauth_client_id,
    MB_OAUTH_CLIENT_SECRET=config.website.mb_oauth_client_secret,
    GOOGLE_OAUTH_CLIENT_ID=config.website.google_oauth_client_id,
    GOOGLE_OAUTH_CLIENT_SECRET=config.website.google_oauth_client_secret,
)
app.acoustid_config = config

# can't use json because of python-openid
app.session_interface = SecureCookieSessionInterface()
app.session_interface.serializer = pickle


@app.context_processor
def inject_common_values():
    show_donate_banner = False
    if datetime.date.today().month in (11, 12):
        show_donate_banner = True
    return dict(
        account_id=session.get('id'),
        show_maintenace_banner=config.website.maintenance,
        show_donate_banner=show_donate_banner,
        morris_js_version='0.5.1',
        raphael_js_version='2.1.4',
        bootstrap_version='3.3.6',
Beispiel #31
0
import sys
import mysql.connector
from datetime import datetime
from .config import secret_key, model_file, no_phonemes, no_verses, epi, IPAV, vowels
from .utils import eprint, connectMySQL

nlp = spacy.load('en_core_web_md')

app = Flask(__name__)
application = app
if __name__ == "__main__":
    app.run()
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = secret_key

session_cookie = SecureCookieSessionInterface().get_signing_serializer(app)

print('{timestamp} -- start loading model file'.format(
    timestamp=datetime.utcnow().isoformat()))
model = gensim.models.Word2Vec.load(model_file)

print('{timestamp} -- start loading corpus from MySQL'.format(
    timestamp=datetime.utcnow().isoformat()))
corpus = list()
cnx = connectMySQL()
cursor = cnx.cursor()
query = ('SELECT id, gid, verse, ipa FROM english')
cursor.execute(query)
for (id, gid, verse, ipa) in cursor:
    corpus.append((id, gid, verse, ipa))
cursor.close()
Beispiel #32
0
 def __init__(self):
     self.session_interface = SecureCookieSessionInterface()
Beispiel #33
0
 def _decodeFlaskCookie(self, cookie_value):
     sscsi = SecureCookieSessionInterface()
     signingSerializer = sscsi.get_signing_serializer(current_app)
     return signingSerializer.loads(cookie_value)
Beispiel #34
0
from util import (
    validate_email_address,
    is_prod,
    get_host,
    sanitize,
    js_time,
    get_client_ip,
)
from rate_limit_manager import check_rate_limit

setup_env()

app = Flask(__name__)
app.secret_key = environ.get("secret-key", token_hex(10))

cookie_sess = SecureCookieSessionInterface()
_cookie_serializer = cookie_sess.get_signing_serializer(app)

database_url: str = environ.get("DATABASE_URL")
app.config["SQLALCHEMY_DATABASE_URI"] = database_url
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)


# get current cookies
def get_session(r=None):
    r = r or request
    cookies = r.cookies.get(app.session_cookie_name)
    if cookies:
        c = _cookie_serializer.loads(cookies)
Beispiel #35
0
 def _decodeFlaskCookie(self, cookie_value):
     sscsi = SecureCookieSessionInterface()
     signingSerializer = sscsi.get_signing_serializer(current_app)
     return signingSerializer.loads(cookie_value)