Exemple #1
0
    def get_credentials(self, client, login, passwd):
        import argon2
        from argon2 import PasswordHasher

        #         returncode, data = self.get_user_phash(login)
        #         if returncode != 0:
        #             raise ValueError(data)

        #         ph = PasswordHasher()
        # #         print("DATA iS ", data[0])

        #         if ph.verify(data[0], passwd):
        #             self.verified_connections.add((id(client), client.getpeername()))
        #             return [0, "=>Verification successfull."]
        #         else:
        #             raise ValueError("Verification faild")

        response = self.get_user_phash(login)

        if response['returncode'] != 0:
            return self.prepare_response(1, response['data'], "err")

        ph = PasswordHasher()
        try:
            ph.verify(response['data'], passwd)
            self.verified_connections.add((id(client), client.getpeername()))
            answer = "=>Verification successfull."
            return self.prepare_response(0, answer, "answer")

        except argon2.exceptions.VerifyMismatchError as e:
            print("!=> ", traceback.format_exc())
            return self.prepare_response(1, str(e), "err")
Exemple #2
0
 def _verify_password(self, stored, password):
     ph = PasswordHasher()
     try:
         ph.verify(stored, password)
         return True
     except (exceptions.VerifyMismatchError, exceptions.VerificationError):
         return False
Exemple #3
0
def check_argon(uid, user_lst_3, password_1):
    ph = PasswordHasher()
    try:
        ph.verify(user_lst_3[uid], password_1)
        return True
    except argon2.exceptions.VerifyMismatchError:
        return False
Exemple #4
0
def login():
    """Retrieve a token"""
    data = request.get_json()
    user = User.query.filter_by(username=data["username"]).first()

    if not user:
        return jsonify({"message": "Invalid credentials"}), 401

    try:
        hasher = PasswordHasher()
        hasher.verify(user.password, data["password"])
    except (VerifyMismatchError, VerificationError, InvalidHash,
            AttributeError):
        # This must also return 401 or else the user may learn
        # private information
        return jsonify({"message": "Invalid credentials"}), 401

    # Rehash password if the parameters of the PasswordHasher change.
    # https://argon2-cffi.readthedocs.io/en/stable/api.html
    if hasher.check_needs_rehash(user.password):
        user.password = hasher.hash(data["password"])
        db.session.add(user)
        db.session.commit()

    access_token = create_access_token(identity=user.username, fresh=True)
    refresh_token = create_refresh_token(user.username)

    return (jsonify({
        "access_token": access_token,
        "refresh_token": refresh_token
    }), 200)
Exemple #5
0
def login():
    message = ""
    site_login = request.form.get("site_login")
    password = request.form.get("password")
    result = db.execute(
        "SELECT password,visible_name,user_id FROM users WHERE login=:login", {
            "login": site_login
        }).fetchone()
    ### users table schema
    ###  user_id | login | password | visible_name
    if result is None:
        message = "Login or password is incorrect. Please try again."
        return render_template("index.html", message=message)

    password_hash = result[0]
    message = password_hash
    visible_name = result[1]
    user_id = result[2]
    try:
        pwd_hasher = PasswordHasher()
        pwd_hasher.verify(password_hash, password)
    except argon2.exceptions.VerifyMismatchError:
        message = "Login or password is incorrect. Please try again."
        return render_template("index.html", message=message)
    except:
        message = "An error has occured during authentication. Please try again."
        return render_template("index.html", message=message)
    session['site_login'] = site_login
    session['visible_name'] = visible_name
    session['user_id'] = user_id
    return redirect(url_for('homepage'))
Exemple #6
0
 def verify_password(self, password):
     hasher = PasswordHasher()
     try:
         hasher.verify(self.password_hash, password)
         return True
     except Exception:
         return False
Exemple #7
0
 def verificar_senha(self, password):
     ph = PasswordHasher()
     try:
         ph.verify(self.password, password)
         return {'status': True, 'msg': 'senha correta'}
     except Exception:
         return {'status': False, 'msg': 'senha incorreta'}
Exemple #8
0
 def verify_password(self, password):
     hasher = PasswordHasher()
     try:
         hasher.verify(self.password_hash, password)
         return True
     except Exception:
         return False
Exemple #9
0
def main():
    """Testing 'argon2-cffi' package"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbosity",
        dest="verbosity",
        action="count",
        default=0,
        help="set verbosity level",
    )
    args = parser.parse_args()

    if args.verbosity == 1:
        logging.basicConfig(level=logging.INFO)
    elif args.verbosity > 1:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.ERROR)

    logging.debug(f"{argon2.__name__} {argon2.__version__}")

    ph = PasswordHasher()
    dummy_hash = ph.hash("s3kr3tp4ssw0rd")
    ph.verify(dummy_hash, "s3kr3tp4ssw0rd")
    ph.check_needs_rehash(dummy_hash)
Exemple #10
0
def verify_password(password: str, hashed_password: str) -> bool:
    ph = PasswordHasher()
    try:
        ph.verify(hashed_password, password)
        return True
    except VerifyMismatchError:
        return False
Exemple #11
0
    def get_transactions(self, user_hash: str = ''):
        user_transactions = []
        ph = PasswordHasher()
        if user_hash != '':
            for block in self.chain:
                for transaction in block['transactions']:
                    try:
                        if ph.verify(transaction['sender'], user_hash):
                            temp_transaction = deepcopy(transaction)
                            temp_transaction['sender'] = 'self'
                            user_transactions.append(temp_transaction)
                    except Exception:
                        try:
                            if ph.verify(transaction['reciever'], user_hash):
                                temp_transaction = deepcopy(transaction)
                                temp_transaction['recipient'] = 'self'
                                user_transactions.append(temp_transaction)
                        except Exception:
                            continue
            return user_transactions

        for block in self.chain:
            for transaction in block['transactions']:
                user_transactions.append(transaction)
        return user_transactions
    def authenticate(self, email: str, password: str) -> Any:
        """Authenticate password for the given user email"""
        with self.tracer.start_as_current_span(
                "AuthenticateUseCase.authenticate", kind=SERVER) as span:
            ph = PasswordHasher()
            user = self.user.retrieve_user_by_email(email)
            ph.verify(user.password, password)
            span.set_attribute("authenticated?", str(True))
            key = jwk.JWK.from_pem(
                str(
                    settings.RSA_PRIVATE_KEY.encode("utf8").decode(
                        "unicode-escape")).encode("utf8"))
            expiration_time = datetime.utcnow() + timedelta(
                seconds=settings.ID_TOKEN_EXPIRE_SECONDS)
            # Required ID Token claims
            claims = {
                "iss": settings.ISS_ENDPOINT,
                "sub": str(user.email),
                "aud": user.email,
                "exp": int(calendar.timegm(expiration_time.utctimetuple())),
                "iat": int(calendar.timegm(datetime.utcnow().utctimetuple())),
                "auth_time":
                int(calendar.timegm(expiration_time.utctimetuple())),
            }

            jwt_token = jwt.JWT(
                header=json.dumps({"alg": "RS256"}, default=str),
                claims=json.dumps(claims, default=str),
            )
            jwt_token.make_signed_token(key)
            return jwt_token.serialize()
Exemple #13
0
 def signin(user):
     __password = user['password']
     try:
         __id = user['id']
         users = User.objects.filter(id=__id)
     except:
         try:
             __email = user['email']
             users = User.objects.filter(email=__email)
         except:
             pass
     ph = PasswordHasher()
     for u in users:
         if (u.active == 'false'):
             return None
         try:
             ph.verify(u.password, __password)
             __logged_user = {
                 'id': u.id,
                 'name': u.name,
                 'email': u.email,
                 'level': u.level
             }
             return __logged_user
         except:
             return None
    def login(self, username, password):
        success = False
        msg = ''
        userID = 'N/A'
        key = 'N/A'

        self.cursor.execute(
            """select password, id from users
			where username = %s""", (username, ))

        if self.cursor.rowcount == 0:
            success = False
            msg += '\n\tUsername does not exists'

        elif self.cursor.rowcount != 1:
            success = False
            msg += '\n\tUnknown Error'

        else:
            row = self.cursor.fetchone()
            hashed = row[0]
            userID = row[1]

            verifier = PasswordHasher()
            try:
                verifier.verify(hashed, password)
                success = True
            except:
                success = False

            if success:
                msg += 'Authenticated'

                if verifier.check_needs_rehash(hashed):
                    hashed = verifier.hash(password)
                    count = self.cursor.execute(
                        """update users
						set password = %s
						where username = %s""", (hashed, username))

                    if count != 1:
                        msg += 'Failed to rehash password, contact support'
                        logging.error('Failed to rehash password')
                        self.db.rollback()
                    else:
                        self.db.commit()

                self.cursor.execute(
                    """select activationKey from productKey
					where userID = %s""", (userID, ))

                row = self.cursor.fetchone()
                key = row[0]

            else:
                success = False
                msg += 'Incorrect Password'

        return success, msg, userID, key
Exemple #15
0
def auth_failure_lab2(request):
    if request.method == "GET":
        return render(request, "Lab_2021/A7_auth_failure/lab2.html")

    elif request.method == "POST":
        username = request.POST["username"]
        password = request.POST["password"]
        try:
            user = AF_admin.objects.get(username=username)
            print(type(user.lockout_cooldown))
            if user.is_locked == True and user.lockout_cooldown > datetime.datetime.now(
            ):
                return render(request, "Lab_2021/A7_auth_failure/lab2.html",
                              {"is_locked": True})

            try:
                ph = PasswordHasher()
                ph.verify(user.password, password)
                if user.is_locked == True and user.lockout_cooldown < datetime.datetime.now(
                ):
                    user.is_locked = False
                    user.last_login = datetime.datetime.now()
                    user.failattempt = 0
                    user.save()
                return render(request, "Lab_2021/A7_auth_failure/lab2.html", {
                    "user": user,
                    "success": True,
                    "failure": False
                })
            except:
                # fail attempt
                print("wrong password")
                fail_attempt = user.failattempt + 1
                if fail_attempt == 5:
                    user.is_active = False
                    user.failattempt = 0
                    user.is_locked = True
                    user.lockout_cooldown = datetime.datetime.now(
                    ) + datetime.timedelta(minutes=1440)
                    user.save()
                    return render(
                        request, "Lab_2021/A7_auth_failure/lab2.html", {
                            "user": user,
                            "success": False,
                            "failure": True,
                            "is_locked": True
                        })
                user.failattempt = fail_attempt
                user.save()
                return render(request, "Lab_2021/A7_auth_failure/lab2.html", {
                    "success": False,
                    "failure": True
                })
        except Exception as e:
            print(e)
            return render(request, "Lab_2021/A7_auth_failure/lab2.html", {
                "success": False,
                "failure": True
            })
Exemple #16
0
 def auth_user(self, email, senha):
     user = self.select_users(email=email, max_results=1)
     ph = PasswordHasher()
     try:
         ph.verify(user.senha, senha)
         return True
     except Exception:
         return False
Exemple #17
0
def check_password(input_password, hashed_password):
    # パスワードチェック
    ph = PasswordHasher()
    try:
        ph.verify(hashed_password, input_password)
    except Exception as e:
        return False
    return True
Exemple #18
0
def check_tuple(h_tuple: Iterator[str], a_tuple: Iterator[str]) -> bool:
    ph = PasswordHasher()
    for hash, text in zip(h_tuple, a_tuple):
        try:
            ph.verify(hash, text)
        except argon2.exceptions.VerifyMismatchError:
            return False
    return True
Exemple #19
0
    def verify(self, password):
        hasher = PasswordHasher()
        try:

            hasher.verify(self.pwd, password)  #Verify the password

            return True
        except VerifyMismatchError:  #Incorrect password
            return False
Exemple #20
0
class KosekiAuth:
    def __init__(self, storage: Storage):
        self.storage = storage
        self.__ph = PasswordHasher()

    def current_user(self) -> int:
        return session["uid"]

    def member_of(self,
                  group: Union[int, str, Group, None],
                  person: Optional[Person] = None) -> bool:
        if group is None:
            raise ValueError("group cannot be None when checking member_of")
        if person is None:
            person = self.storage.query(Person).filter_by(
                uid=self.current_user()).scalar()

        if isinstance(group, int):
            group = self.storage.query(Group).filter_by(gid=group).scalar()
        elif isinstance(group, str):
            group = self.storage.query(Group).filter_by(name=group).scalar()

        if group is None:
            return False
        group = cast(Group, group)

        return sum(1 for x in person.groups if x.gid == group.gid) > 0

    def require_session(self,
                        func: Callable,
                        groups: list[str] = None) -> Callable:
        def wrap(*args, **kwargs) -> Union[str, Response]:  # type: ignore
            if "uid" not in session:
                return redirect(url_for("login", redir=request.url))
            else:
                if (groups is None or
                        sum(1
                            for group in groups if self.member_of(group)) > 0):
                    return func(*args, **kwargs)
                else:
                    abort(403)

        wrap.__name__ = func.__name__
        return wrap

    def hash_password(self, password: str) -> str:
        return self.__ph.hash(password)

    def verify_password(self, password: Union[str, None],
                        password2: str) -> bool:
        if password is None:
            return False
        try:
            self.__ph.verify(password, password2)
            return True
        except VerifyMismatchError:
            return False
def login():
    """Handle login requests

    On successfull login a session with a length of an hour should be generated.
    On failure an error should be thrown.
    """
    hasher = PasswordHasher()

    payload = request.json
    username = payload['user']
    password = payload['pass']

    DBSessionMaker = sessionmaker(bind=engine)
    db_session = DBSessionMaker()

    try:
        user = db_session.query(Users).get(username)
        hasher.verify(user.password, password)

        # If the hash parameters are out of date or the user update the hash
        # One example of an out of date parameter is a insufficient time cost
        if hasher.check_needs_rehash(user.password):
            user.password = hasher.hash(password)

        # calculate an expiration time one our from now
        expire = datetime.utcnow() + timedelta(hours=1)

        session_id = uuid.uuid4().hex

        user_session = Sessions(
            # This must be a uuid4 or large cryptographically secure random number
            # A other formats of UUID can have several bytes perdicted presenting
            # a potential brute forcing risk
            # This implimentation choice assumes CPython is being used.
            id=session_id,
            username=username,
            session_expire=expire
        )
        db_session.add(user_session)
        db_session.commit()

        auth_resp = Response(status=200)
        auth_resp.set_cookie('session', session_id)
        db_session.commit()
        return auth_resp

    # For security reasons only two responses may be provided
    # Thus errors do not need to be handled individually
    except Exception:
        db_session.rollback()

    # If we get to the end of this funtion something went wrong.
    # Thus make sure the user does not think they are logged in
    err_resp = Response(status=401)
    err_resp.delete_cookie('session')
    return err_resp
Exemple #22
0
def password_verify(id, password, hash):
    """Verify password hash (Argon2), use this function if you want to
       authorize logins"""
    hasher = PasswordHasher()
    cleartext = '%s:%s' % (id, password)
    try:
        hasher.verify(hash, cleartext)
        return True
    except Exception:
        return False
def compare_passwords(password, stored_password):
    """compares a plaintext password with the stored, encrypted password"""
    ph = PasswordHasher()
    try:
        ph.verify(stored_password, password)
        if ph.check_needs_rehash(stored_password):
            return (True, True)
        return (True, False)
    except VerifyMismatchError:
        return (False, False)
Exemple #24
0
 def verify_password(self, password):
     """Verify the provided password against the stored hash."""
     ph = PasswordHasher()
     try:
         # Note: The ph.verify doesn't return a False value, it's either
         #       True or it raises a VerifyMismatchError exception.
         ph.verify(self.password, password)
         return True
     except argon2_exceptions.VerifyMismatchError:
         raise Exception("Unvalid credentials.")
Exemple #25
0
def verify_password(hashed_password, password):
    ph = PasswordHasher()
    peppers = get_peppers_list()

    for pepper in peppers:
        try:
            ph.verify(hashed_password, password + pepper)
            return True
        except VerifyMismatchError as e:
            print(e)

    return False
def tokens_create(user_data: TokenSchema = Body(...)):
    data = user_data.dict()
    user = UserModel.get_or_none(UserModel.username == data.get("username"))
    if not user:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
    pw = PasswordHasher()
    try:
        pw.verify(user.password, data.get("password"))
    except argon_exc.VerifyMismatchError or argon_exc.VerificationError:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    token = jwt.encode(
        {"username": user.username}, key=SECRET, algorithm="HS256"
    )
    return {"access": token}
Exemple #27
0
def check_password(hashed_password, raw_password) -> bool:
    ph = PasswordHasher(
        time_cost=settings.argon2_time_cost,
        memory_cost=settings.argon2_memory_cost,
        parallelism=settings.argon2_parallelism,
        hash_len=settings.argon2_hash_len,
        salt_len=settings.argon2_salt_len,
        encoding="utf-8",
        type=Type.ID,
    )
    try:
        ph.verify(hashed_password, raw_password)
        return True
    except VerifyMismatchError:
        return False
    def test_hash_password(self):
        kdf = PasswordHasher()
        password = '******'

        hash = kdf.hash(password)

        self.assertTrue(kdf.verify(hash, password))
Exemple #29
0
    def mutate(self, info, email=None, name=None, role=None, get_alerts=None, old_password=None, new_password=None):
        if get_jwt_claims()['role'] == 'Admin' and email and email != get_jwt_identity():
            user = User.query.filter_by(email=email).first()
            if name:
                user.name = name
            if role:
                user.role = role
            if get_alerts is not None:
                user.get_alerts = get_alerts
            if new_password:
                ph = PasswordHasher()
                user.password = ph.hash(new_password)

            db.session.commit()
        else:
            user = User.query.filter_by(email=get_jwt_identity()).first()
            ph = PasswordHasher()
            if name:
                user.name = name
            if get_alerts is not None:
                user.get_alerts = get_alerts
            if old_password and new_password and ph.verify(user.password, old_password):
                user.password = ph.hash(new_password)

            db.session.commit()
        return UpdateUserMutation(user=user)
Exemple #30
0
def check_password_hash(hash: str, password: str) -> bool:
    ph = PasswordHasher()
    try:
        if ph.verify(hash, password):
            return True
    except argon2.exceptions.VerifyMismatchError:
        return False
Exemple #31
0
    def passwordChecker(self,user_pass,server_pass,server_hash):
        protected = True
        # print("Password detected")
        if server_pass is not False and server_hash is False:
            if user_pass == server_pass:
                protected = False

        if server_hash is not False and server_pass is False:
            try:
                ph = PasswordHasher()
                ph.verify(server_hash, user_pass)
                protected = False
            except exceptions.VerifyMismatchError:
                protected = True

        return protected
Exemple #32
0
def _console_test(argv):
    pw = argv[1]
    salt_length = int(argv[2])
    hash_length = int(argv[3])

    print('Password:    %s' % pw)
    print('Salt Length: %s' % salt_length)
    print('Hash Length: %s' % hash_length)
    print('------------------------------')
    print('Calculating hash...')

    ph = PasswordHasher(hash_len=hash_length,
                        salt_len=salt_length,
                        encoding='utf-8',
                        time_cost=1000,
                        memory_cost=1024)
    pwhash = ph.hash(pw)

    print('Verifying hash...')

    ph2 = PasswordHasher()

    verified = ph2.verify(pwhash, pw)

    parsed = parse_argon_hash(pwhash)

    print('Results:')
    print('Hash    : %s' % pwhash)
    print('Verified: %s' % verified)
    print('Parsed  : %s' % parsed)
    """
    def test_verify(self, password):
        """
        Verification works with unicode and bytes.
        """
        ph = PasswordHasher(1, 8, 1, 16, 16, "latin1")
        hash = (  # handrolled artisanal test vector
            u"$argon2i$m=8,t=1,p=1$"
            u"bL/lLsegFKTuR+5vVyA8tA$VKz5CHavCtFOL1N5TIXWSA"
        )

        assert ph.verify(hash, password)
Exemple #34
0
def login():
    userid = request.form.get('userid')
    userpw = request.form.get('userpw')
    if userid and userpw:
        user = get_user(userid)
        if user:
            ph = PasswordHasher()
            try:
                ph.verify(user.password, userpw)
            except VerifyMismatchError:
                flash('check account or password')
            else:
                session['username'] = user.account
                flash('welcome back!')
                return redirect(url_for('home'))
        else:
            flash('check account or password')
    else:
        flash('account id or password is blank.')
    return redirect(url_for('login'))
 def verify_password(self, password):
     ph = PasswordHasher()
     return ph.verify(self.password_hash, password)