Example #1
0
def gdbgui():
    """Render the main gdbgui interface"""
    interpreter = "lldb" if app.config["LLDB"] else "gdb"
    gdbpid = request.args.get("gdbpid", 0)

    add_csrf_token_to_session()

    THEMES = ["monokai", "light"]
    initial_data = {
        "gdbgui_version": __version__,
        "interpreter": interpreter,
        "initial_binary_and_args": app.config["initial_binary_and_args"],
        "show_gdbgui_upgrades": app.config["show_gdbgui_upgrades"],
        "themes": THEMES,
        "signals": SIGNAL_NAME_TO_OBJ,
        "gdbpid": gdbpid,
        "p": pbkdf2_hex(str(app.config.get("l")), "Feo8CJol") if app.config.get(
            "l"
        ) else "",
        "project_home": app.config["project_home"],
        "csrf_token": session["csrf_token"],
        "using_windows": USING_WINDOWS,
    }

    return render_template(
        "gdbgui.html",
        version=__version__,
        debug=app.debug,
        interpreter=interpreter,
        initial_data=initial_data,
        themes=THEMES,
    )
Example #2
0
def gdbgui():
    """Render the main gdbgui interface"""
    interpreter = 'lldb' if app.config['LLDB'] else 'gdb'
    gdbpid = request.args.get('gdbpid', 0)

    THEMES = ['monokai', 'light']
    initial_data = {
        'gdbgui_version':
        __version__,
        'interpreter':
        interpreter,
        'initial_binary_and_args':
        app.config['initial_binary_and_args'],
        'show_gdbgui_upgrades':
        app.config['show_gdbgui_upgrades'],
        'themes':
        THEMES,
        'signals':
        SIGNAL_NAME_TO_OBJ,
        'gdbpid':
        gdbpid,
        'p':
        pbkdf2_hex(str(app.config.get('l')), 'Feo8CJol')
        if app.config.get('l') else '',
        'project_home':
        app.config['project_home']
    }

    return render_template('gdbgui.html',
                           version=__version__,
                           debug=app.debug,
                           interpreter=interpreter,
                           initial_data=initial_data,
                           themes=THEMES)
Example #3
0
def _fix_legacy_auth(auth_info):
    """When 'auth_info' contains no 'provider' field,
    a proper 'auth_info' data will
    be constructed if either 'jwt' or 'username' and 'password' field exist.
    """
    # Auto-detect the intended authentication method and "fix" the request.
    if "jwt" in auth_info:
        auth_info['provider'] = "jwt"
        auth_info['provider_details'] = {'jwt': auth_info['jwt']}
    elif "username" in auth_info:
        username = auth_info["username"]
        if username.startswith("gamecenter:"):
            auth_info["automatic_account_creation"] = False
            username = "******" + pbkdf2_hex(username, "staticsalt",
                                                  iterations=25000)
            log.info("Hashed gamecenter username: %s", username)
            auth_info['provider'] = "device_id"
            auth_info['username'] = username
        elif username.startswith("uuid:"):
            auth_info['provider'] = "device_id"
        else:
            auth_info['provider'] = "user+pass"
    else:
        abort_unauthorized("Bad Request. No provider specified")

    log.warning("Legacy authentication detected. Fixed for provider '%s'",
                auth_info['provider'])

    return auth_info
Example #4
0
def insert():
    data = request.json
    email = data.get('email')
    document = data.get('document')
    password = data.get('password')
    re_password = data.get('re_password')

    if password and re_password and password != re_password:
        return res_error(200, 'Password and verification required.')

    try:
        User.objects.get(Q(email=email) | Q(document=document))
        return res_error(200, 'Email or document already in use.')
    except User.DoesNotExist:
        pass

    try:
        data.update(friends=[],
                    groups=[],
                    events=[],
                    invites=[],
                    password=security.pbkdf2_hex(password, SALT, 69),
                    created_at=datetime.datetime.utcnow)
        user = User(**dissoc(data, 're_password'))
        user.validate()
        created = user.save().to_mongo().to_dict()
        return res_success(200, {'id': created['_id']})
    except Exception as e:
        print(e)
        return res_error(400, e)
Example #5
0
def check_password(user_password, client_password, salt):
    user_password = pbkdf2_hex(user_password,
                               salt,
                               iterations=50000,
                               keylen=None,
                               hashfunc=None)  # Default hashfunc SHA-256
    if user_password == client_password: return True
    else: return False
Example #6
0
def test_pbkdf2_non_native():
    import werkzeug.security as sec
    prev_value = sec._has_native_pbkdf2
    sec._has_native_pbkdf2 = None

    assert pbkdf2_hex('password', 'salt', 1, 20, 'sha1') \
        == '0c60c80f961f0e71f3a9b524af6012062fe037a6'
    sec._has_native_pbkdf2 = prev_value
Example #7
0
def generate_token(string="token", salt="token", it=1000, length=6):
    from time import time

    salt = salt + str(time())

    hex = pbkdf2_hex(string, salt, iterations=300).upper()
    token = str(hex[:length])
    return token
Example #8
0
def test_pbkdf2_non_native():
    import werkzeug.security as sec
    prev_value = sec._has_native_pbkdf2
    sec._has_native_pbkdf2 = None

    assert pbkdf2_hex('password', 'salt', 1, 20, 'sha1') \
        == '0c60c80f961f0e71f3a9b524af6012062fe037a6'
    sec._has_native_pbkdf2 = prev_value
Example #9
0
def create_password(user_password):
    salt = os.urandom(10)
    client_password = pbkdf2_hex(user_password,
                                 salt,
                                 iterations=50000,
                                 keylen=None,
                                 hashfunc=None)
    return [client_password, salt]
Example #10
0
def GetPassword(user_name,password):
    conn = db_connect.connect()
    query = conn.execute("select * from Accounts WHERE username=?", (user_name,))
    result = {'data': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]}
    if not result['data']:
        password = '******'
    else:
        password = pbkdf2_hex(password, result['data'][0]['salt'], iterations=50000, keylen=None, hashfunc="sha256")
    return str(password)
Example #11
0
def create_password(user_password):
    # Oppdatering: hvis ikke oppdatert i databasen
    #salt = os.urandom(10)
    salt = os.urandom(10).hex()
    client_password = w.pbkdf2_hex(user_password,
                                   salt,
                                   iterations=50000,
                                   keylen=None,
                                   hashfunc=None)
    return [client_password, salt]
Example #12
0
def generate(seed, name, entry_type, secret):
    if entry_type == 'hex':
        res = pbkdf2_hex(seed + secret, name, iterations=8192)
        res = res[:8]
    elif entry_type == 'hexlong':
        res = pbkdf2_hex(seed + secret, name, iterations=8192)
        res = res[:16]
    elif entry_type == 'alnum':
        int_data = gen_large_int(seed, name, secret)
        res = grab_alnum(int_data, 8)
    elif entry_type == 'alnumlong':
        int_data = gen_large_int(seed, name, secret)
        res = grab_alnum(int_data, 12)
    elif entry_type == 'xkcd':
        int_data = gen_large_int(seed, name, secret)
        res = grab_xkcd(int_data, 4)
    elif entry_type == 'xkcdlong':
        int_data = gen_large_int(seed, name, secret)
        res = grab_xkcd(int_data, 8)
    elif entry_type == 'ssh':
        res = grab_ssh(seed, name, secret)
    else:
        res = 'unknown type'
    return res
Example #13
0
def generate(seed, name, entry_type, secret):
    if entry_type == 'hex':
        res = pbkdf2_hex(seed + secret,
                         name,
                         iterations=42000,
                         hashfunc='sha1',
                         keylen=40)
        res = res[:8]
    elif entry_type == 'hexlong':
        res = pbkdf2_hex(seed + secret,
                         name,
                         iterations=42000,
                         hashfunc='sha1',
                         keylen=40)
        res = res[:16]
    elif entry_type == 'alnum':
        int_data = gen_large_int(seed, name, secret)
        res = grab_alnum(int_data, 8)
    elif entry_type == 'alnumlong':
        int_data = gen_large_int(seed, name, secret)
        res = grab_alnum(int_data, 12)
    elif entry_type == 'base58':
        int_data = gen_large_int(seed, name, secret)
        res = get_base58(int_data)[:8]
    elif entry_type == 'base58long':
        int_data = gen_large_int(seed, name, secret)
        res = get_base58(int_data)[:12]
    elif entry_type == 'xkcd':
        int_data = gen_large_int(seed, name, secret)
        res = grab_xkcd(int_data, 4)
    elif entry_type == 'xkcdlong':
        int_data = gen_large_int(seed, name, secret)
        res = grab_xkcd(int_data, 6)
    else:
        res = 'unknown type'
    return res
Example #14
0
File: util.py Project: jpan17/spot
def save_file(filestorage, hash=True):
    """
    Saves a file to upload folder and returns the absolute URL to the saved image.

    Pararmeters
    -----------
    filestorage : FileStorage
        The FileStorage object that Flask provides from a form file input (e.g. request.files['file'])
    hash : bool
        Whether to hash the name of the file or not

    Returns
    -------
    str or None
        The absolute URL where the saved image is stored, or None if saved image was not stored.

    Examples
    --------
    >>> save_file(file)
    'http://localhost:5000/static/img/uploads/2651ab247cffe084048759f87b2c9d15f6bc437c7ed3a8e8eab1b9e4f04a3d13.jpg'
    >>> save_file(invalid_file)
    None
    """

    if allowed_file(filestorage.filename):
        filename = filestorage.filename
        # Hash with appended timestamp, if appropriate
        if hash:
            parts_of_filename = secure_filename(filename).rsplit('.', 1)
            filename = '.'.join([
                pbkdf2_hex(parts_of_filename[0] + str(time.time()),
                           app.config['SECURITY_PASSWORD_SALT']),
                parts_of_filename[1]
            ])

        # Save and get url
        filestorage.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        url = url_for('static',
                      filename=os.path.join(
                          app.config['UPLOAD_FOLDER'].split('/', 1)[1],
                          filename),
                      _external=True)
        return url

    return None
Example #15
0
def login():
    data = request.json
    email = data.get('email')
    password = data.get('password')

    if not email or not password:
        return res_error(400, 'Required field: email and password')

    user = db.find_one('user', 'email', email)
    if not user:
        return res_error(401, 'Incorrect credentials.')

    hash_password = security.pbkdf2_hex(password, SALT, 69)
    if user.get('password') == hash_password:
        payload = {
            'exp': datetime.utcnow() + timedelta(minutes=30),
            'id': str(user.get('_id'))
        }
        encoded_jwt = encode(payload, SECRET, algorithm='HS256')
        return res_success(200, {'jwt': encoded_jwt.decode('utf-8')})

    return res_error(401, 'Incorrect credentials.')
Example #16
0
def sign_s3():
    S3_BUCKET = os.environ.get('S3_BUCKET')

    file_name = request.args.get('file_name')
    file_type = request.args.get('file_type')

    if allowed_file(file_name):
        parts_of_filename = secure_filename(file_name).rsplit('.', 1)
        file_name = '.'.join([
            pbkdf2_hex(parts_of_filename[0] + str(time.time()),
                       app.config['SECURITY_PASSWORD_SALT']),
            parts_of_filename[1]
        ])
    else:
        return json.dumps({'data': 'Bad file type'})

    s3 = boto3.client('s3')

    presigned_post = s3.generate_presigned_post(Bucket=S3_BUCKET,
                                                Key=file_name,
                                                Fields={
                                                    "acl": "public-read",
                                                    "Content-Type": file_type
                                                },
                                                Conditions=[{
                                                    "acl":
                                                    "public-read"
                                                }, {
                                                    "Content-Type":
                                                    file_type
                                                }],
                                                ExpiresIn=3600)

    return json.dumps({
        'data':
        presigned_post,
        'url':
        'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name)
    })
Example #17
0
def mailnotusedwithinayear(
    mailausformular, updatego
):  # check if this service has already been used with a mailadress within a year
    checkmail = pbkdf2_hex(mailausformular,
                           saltx,
                           iterations=50000,
                           keylen=None,
                           hashfunc=None)
    checkentry = mailliste.query.filter_by(dbemail=checkmail).first()
    yearcheck = timedelta(days=365)
    if checkentry is None or checkentry.dbdatum < (datetime.utcnow() -
                                                   yearcheck):
        if updatego:
            if checkentry is None:
                neueintrag = mailliste(dbemail=checkmail)
                db.session.add(neueintrag)
            else:
                checkentry.dbdatum = datetime.utcnow()
            db.session.commit()
            db.session.close()
        return True
    else:
        db.session.close()
        return False
Example #18
0
def generate_password(tag, salt, n=32):
    tag_hash = pbkdf2_hex("{}-password".format(tag), salt)
    return base64.b85encode(bytes(tag_hash, "ascii"))[:n].decode("ascii")
Example #19
0
 def check(data, salt, iterations, keylen, expected):
     rv = pbkdf2_hex(data, salt, iterations, keylen)
     self.assert_equal(rv, expected)
Example #20
0
def mk_pwd_hash(data, salt, iterations, keylen, algo):
    """
    Returns a pbkdf2_hex hash of the passed data with specified parameters
    """
    hashed = pbkdf2_hex(data, salt, iterations, keylen, algo)
    return algo + "$" + salt + ":" + str(iterations) + "$" + hashed
Example #21
0
def mk_pwd_hash(data, salt, iterations, keylen, algo):
    """
    Returns a pbkdf2_hex hash of the passed data with specified parameters
    """
    hashed = pbkdf2_hex(data, salt, iterations, keylen, algo)
    return algo + "$" + salt + ":" + str(iterations) + "$" + hashed
Example #22
0
 def check(data, salt, iterations, keylen, hashfunc, expected):
     rv = pbkdf2_hex(data, salt, iterations, keylen, hashfunc)
     assert rv == expected
Example #23
0
 def generate_token(source):
     return pbkdf2_hex(source,
                       'email-confirmation',
                       iterations=1000,
                       keylen=20)
Example #24
0
 def check(data, salt, iterations, keylen, hashfunc, expected):
     rv = pbkdf2_hex(data, salt, iterations, keylen, hashfunc)
     assert rv == expected
Example #25
0
 def pbkdf2(cls, text, salt, iterations, dklen):
     # werkzeug.security.pbkdf2_hex returns always the native string type
     return pbkdf2_hex(text.encode("utf-8"), salt, iterations, dklen)
Example #26
0
    def auth_request_handler():
        if request.method == "GET":
            abort_unauthorized("Bad Request. "
                               "This endpoint only supports the POST method.")

        auth_info = request.get_json()
        if not auth_info:
            abort_unauthorized("Bad Request. Expected json payload.")

        if "provider" not in auth_info:
            auth_info = _fix_legacy_auth(auth_info)

        # HACK: Client bug workaround:
        if auth_info.get("provider") == "gamecenter" and \
                "provider_details" not in auth_info:
            auth_info = _fix_legacy_auth(auth_info)

        identity = None
        provider_details = auth_info.get('provider_details')

        # TODO: Move specific auth logic outside this module.
        # Steam and Game Center. should not be in here.

        if auth_info['provider'] == "jwt":
            # Authenticate using a JWT. We validate the token,
            # and issue a new one based on that.
            token = provider_details['jwt']
            payload = verify_token(token, "JWT")
            # Issue a JWT with same payload as the one we got
            log.debug("Authenticating using a JWT: %s", payload)
            identity = payload
        elif auth_info['provider'] == "jti":
            if provider_details and 'jti' in provider_details:
                identity = get_cached_token(provider_details['jti'])
            if not identity:
                abort_unauthorized("Bad Request. Invalid JTI.")
        elif auth_info['provider'] in ['device_id', 'user+pass', 'uuid']:
            # Authenticate using access key, secret key pair
            # (or username, password pair)
            identity = authenticate(auth_info['username'],
                                    auth_info['password'])
        elif auth_info['provider'] == "gamecenter":
            app_bundles = app.config.get('apple_game_center', {}) \
                                    .get('bundle_ids')
            from drift.auth.gamecenter import validate_gamecenter_token
            identity_id = validate_gamecenter_token(provider_details,
                                                    app_bundles=app_bundles)
            gc_player_id = "gamecenter:" + identity_id
            username = "******" + pbkdf2_hex(gc_player_id, "staticsalt",
                                                  iterations=25000)
            identity = authenticate(username, "")
        elif auth_info['provider'] == "steam":
            from drift.auth.steam import validate_steam_ticket
            identity_id = validate_steam_ticket()
            username = "******" + identity_id
            identity = authenticate(username, "")
        elif auth_info['provider'] == "oculus" and provider_details.get('provisional', False):
            if len(provider_details['username']) < 1:
                abort_unauthorized("Bad Request. 'username' cannot be an empty string.")
            username = "******" + provider_details['username']
            password = provider_details['password']
            identity = authenticate(username, password)
        elif auth_info['provider'] == "oculus":
            from drift.auth.oculus import validate_oculus_ticket
            identity_id = validate_oculus_ticket()
            username = "******" + identity_id
            identity = authenticate(username, "")
        elif auth_info['provider'] == "viveport" and provider_details.get('provisional', False):
            if len(provider_details['username']) < 1:
                abort_unauthorized("Bad Request. 'username' cannot be an empty string.")
            username = "******" + provider_details['username']
            password = provider_details['password']
            identity = authenticate(username, password)
        elif auth_info['provider'] == "hypereal" and provider_details.get('provisional', False):
            if len(provider_details['username']) < 1:
                abort_unauthorized("Bad Request. 'username' cannot be an empty string.")
            username = "******" + provider_details['username']
            password = provider_details['password']
            identity = authenticate(username, password)
        elif auth_info['provider'] == "googleplay" and provider_details.get('provisional', False):
            if len(provider_details['username']) < 1:
                abort_unauthorized("Bad Request. 'username' cannot be an empty string.")
            username = "******" + provider_details['username']
            password = provider_details['password']
            identity = authenticate(username, password)
        elif auth_info['provider'] == "psn":
            from drift.auth.psn import validate_psn_ticket
            identity_id = validate_psn_ticket()
            username = "******" + identity_id
            identity = authenticate(username, "")
        elif auth_info['provider'] == "7663":
            username = "******" + provider_details['username']
            password = provider_details['password']
            identity = authenticate(username, password)
        else:
            abort_unauthorized("Bad Request. Unknown provider '%s'." %
                               auth_info['provider'])

        if not identity or not identity.get("identity_id"):
            raise RuntimeError("authenticate must return a dict with at"
                               " least 'identity_id' field.")

        if 'service' in identity['roles']:
            expire = JWT_EXPIRATION_DELTA_FOR_SERVICES
        else:
            expire = JWT_EXPIRATION_DELTA

        ret = issue_token(identity, expire=expire)
        log.info("Authenticated: %s", identity)
        return jsonify(ret)
 def check(data, salt, iterations, keylen, expected):
     rv = pbkdf2_hex(data, salt, iterations, keylen)
     self.assert_equal(rv, expected)
Example #28
0
def authenticate(username, password):
    """basic authentication"""
    identity_type = ""
    create_roles = []
    lst = username.split(":")
    # old backwards compatible (non-identity)
    is_old = True
    if len(lst) > 1:
        identity_type = lst[0]
        is_old = False
    else:
        log.info("Old-style authentication for '%s'", username)
    automatic_account_creation = True
    if identity_type.lower() == "gamecenter":
        automatic_account_creation = False
        username = pbkdf2_hex(username, "staticsalt", iterations=25000)
        username = "******" % (identity_type, username)
        log.info("Hashed gamecenter username: %s", username)

    identity_id = 0

    my_identity = g.db.query(UserIdentity) \
                      .filter(UserIdentity.name == username) \
                      .first()

    service_user = current_app.config.get("service_user")
    if not service_user:
        raise RuntimeError("service_user not found in config!")

    # if we do not have an identity, create one along with a user and a player
    if my_identity is None:
        # if this is a service user make sure the password
        # matches before creating the user
        if username == service_user["username"]:
            if password != service_user["password"]:
                log.error("Attempting to log in as service "
                          "user without correct password!")
                abort(httplib.METHOD_NOT_ALLOWED,
                      message="Incorrect password for service user")
            else:
                create_roles.append("service")

        my_identity = UserIdentity(name=username, identity_type=identity_type)
        my_identity.set_password(password)
        if is_old:
            my_user = g.db.query(User) \
                          .filter(User.user_name == username) \
                          .first()
            if my_user:
                my_identity.user_id = my_user.user_id
                log.info("Found an old-style user. Hacking it into identity")

        g.db.add(my_identity)
        g.db.flush()
        log.info("User Identity '%s' has been created with id %s",
                 username, my_identity.identity_id)
    else:
        if not my_identity.check_password(password):
            abort(httplib.METHOD_NOT_ALLOWED, message="Incorrect password")
            return

    if my_identity:
        identity_id = my_identity.identity_id

    my_user = None
    my_player = None
    my_user_name = ""
    user_id = 0
    user_roles = []
    player_id = 0
    player_name = ""
    if my_identity.user_id:
        my_user = g.db.query(User).get(my_identity.user_id)
        if my_user.status != "active":
            log.info("Logon identity is using an inactive user %s, "
                     "creating new one", my_user.user_id)
            my_user = None
        else:
            user_id = my_user.user_id

    if my_user is None:
        if not automatic_account_creation:
            log.info("User Identity %s has no user but "
                     "automatic_account_creation is false so he "
                     "gets no user account",
                     my_identity.identity_id)
        else:
            my_user = User(user_name=username)
            g.db.add(my_user)
            # this is so we can access the auto-increment key value
            g.db.flush()
            user_id = my_user.user_id
            for role_name in create_roles:
                role = UserRole(user_id=user_id, role=role_name)
                g.db.add(role)
            my_identity.user_id = user_id
            log.info("User '%s' has been created with user_id %s",
                     username, user_id)

    if my_user:
        user_roles = [r.role for r in my_user.roles]
        user_id = my_user.user_id
        my_user_name = my_user.user_name

        my_player = g.db.query(CorePlayer) \
                        .filter(CorePlayer.user_id == user_id) \
                        .first()

        if my_player is None:
            my_player = CorePlayer(user_id=user_id, player_name=u"")
            g.db.add(my_player)
            # this is so we can access the auto-increment key value
            g.db.flush()
            log.info("Player for user %s has been created with player_id %s",
                     my_user.user_id, my_player.player_id)

    if my_player:
        player_id = my_player.player_id
        player_name = my_player.player_name

    if my_user and not my_user.default_player_id:
        my_user.default_player_id = my_player.player_id

    g.db.commit()

    # store the user information in the cache for later lookup
    ret = {
        "user_name": my_user_name,
        "user_id": user_id,
        "identity_id": identity_id,
        "player_id": player_id,
        "player_name": player_name,
        "roles": user_roles,
    }
    cache = UserCache()
    cache.set_all(user_id, ret)
    return ret