Example #1
0
    def is_correct_two_factor_code(self, code: str) -> bool:
        """Verify that a TOTP/backup code is correct."""
        if not self.two_factor_secret:
            raise ValueError("User does not have 2FA enabled")

        totp = TOTP(self.two_factor_secret)

        code = code.strip().replace(" ", "").lower()

        # some possible user input (such as unicode) can cause an error in the totp
        # library, catch that and treat it the same as an invalid code
        try:
            is_valid_code = totp.verify(code)
        except TypeError:
            is_valid_code = False

        if is_valid_code:
            return True
        elif self.two_factor_backup_codes and code in self.two_factor_backup_codes:
            # Need to set the attribute so SQLAlchemy knows it changed
            self.two_factor_backup_codes = [
                backup_code
                for backup_code in self.two_factor_backup_codes
                if backup_code != code
            ]
            return True

        return False
Example #2
0
def auth():
    if not current_user.can_admin:
        abort(404)
    form = TOTPForm()
    try:
        user_secret = UserMetadata.get((UserMetadata.uid == current_user.uid)
                                       & (UserMetadata.key == 'totp_secret'))
    except UserMetadata.DoesNotExist:
        return engine.get_template('admin/totp.html').render({
            'authform':
            form,
            'error':
            _('No TOTP secret found.')
        })
    if form.validate_on_submit():
        totp = TOTP(user_secret.value)
        if totp.verify(form.totp.data):
            session['apriv'] = time.time()
            return redirect(url_for('admin.index'))
        else:
            return engine.get_template('admin/totp.html').render({
                'authform':
                form,
                'error':
                _('Invalid or expired token.')
            })
    return engine.get_template('admin/totp.html').render({
        'authform': form,
        'error': None
    })
Example #3
0
def index():
    if request.method == "POST":
        totp = TOTP(app.config["TOTP_SECRET"])
        if "authcode" not in request.form:
            flash("Missing OTP", 'error')
            return redirect(request.url)

        if not totp.verify(request.form["authcode"]):
            flash("Incorrect OTP", "error")
            return redirect(request.url)

        if not request.files:
            flash("No files field", "error")
            return redirect(request.url)

        files = (f for f in request.files.getlist("files") if f.filename != "")

        if not files:
            flash("No files specified", "error")
            return redirect(request.url)

        for file in files:
            file.save(os.path.join(app.config["UPLOAD_DIR"], file.filename))

        flash("Files uploaded correctly!", "success")
        return redirect("/drop")

    return render_template("drop.html")
Example #4
0
File: main.py Project: gonicus/gosa
    def verify(self, user_name, object_dn, key):

        # Do we have read permissions for the requested attribute
        self.__check_acl(user_name, object_dn, "r")

        # Get the object for the given dn
        uuid = self.__dn_to_uuid(object_dn)
        factor_method = self.get_method_from_user(uuid)
        user_settings = self.__settings[uuid] if uuid in self.__settings else {}
        if factor_method == "otp":
            totp = TOTP(user_settings.get('otp_secret'))
            return totp.verify(key)

        elif factor_method == "u2f":

            challenge = user_settings.pop('_u2f_challenge_')
            data = loads(key)
            device, c, t = complete_authentication(challenge, data, [self.facet])
            return {
                'keyHandle': device['keyHandle'],
                'touch': t,
                'counter': c
            }

        elif factor_method is None:
            return True

        return False
Example #5
0
    def verify(self, user_name, object_dn, key):

        # Do we have read permissions for the requested attribute
        self.__check_acl(user_name, object_dn, "r")

        # Get the object for the given dn
        uuid = self.__dn_to_uuid(object_dn)
        factor_method = self.get_method_from_user(uuid)
        user_settings = self.__settings[
            uuid] if uuid in self.__settings else {}
        if factor_method == "otp":
            totp = TOTP(user_settings.get('otp_secret'))
            return totp.verify(key)

        elif factor_method == "u2f":

            challenge = user_settings.pop('_u2f_challenge_')
            data = loads(key)
            device, c, t = complete_authentication(challenge, data,
                                                   [self.facet])
            return {'keyHandle': device['keyHandle'], 'touch': t, 'counter': c}

        elif factor_method is None:
            return True

        return False
Example #6
0
File: main.py Project: peuter/gosa
    def verify(self, user_name, object_dn, key):

        # Do we have read permissions for the requested attribute
        self.__check_acl(user_name, object_dn, "r")

        # Get the object for the given dn
        user = ObjectProxy(object_dn)
        factor_method = self.get_method_from_user(user)
        user_settings = self.__settings[
            user.uuid] if user.uuid in self.__settings else {}
        if factor_method == "otp":
            totp = TOTP(user_settings.get('otp_secret'))
            return totp.verify(key)

        elif factor_method == "u2f":
            devices = [
                DeviceRegistration.wrap(device)
                for device in user_settings.get('_u2f_devices_', [])
            ]

            challenge = user_settings.pop('_u2f_challenge_')
            data = loads(key)
            c, t = verify_authenticate(devices, challenge, data, [self.facet])
            return {'touch': t, 'counter': c}

        elif factor_method is None:
            return True

        return False
Example #7
0
File: main.py Project: peuter/gosa
    def verify(self, user_name, object_dn, key):

        # Do we have read permissions for the requested attribute
        self.__check_acl(user_name, object_dn, "r")

        # Get the object for the given dn
        user = ObjectProxy(object_dn)
        factor_method = self.get_method_from_user(user)
        user_settings = self.__settings[user.uuid] if user.uuid in self.__settings else {}
        if factor_method == "otp":
            totp = TOTP(user_settings.get('otp_secret'))
            return totp.verify(key)

        elif factor_method == "u2f":
            devices = [DeviceRegistration.wrap(device)
                       for device in user_settings.get('_u2f_devices_', [])]

            challenge = user_settings.pop('_u2f_challenge_')
            data = loads(key)
            c, t = verify_authenticate(devices, challenge, data, [self.facet])
            return {
                'touch': t,
                'counter': c
            }

        elif factor_method is None:
            return True

        return False
Example #8
0
def OTP(request):
     getd = unquote(request.GET.get('key'))
     signerverify = signer.unsign(getd, max_age=int(settings.PYADSELFSERVICE_STOUT))
     if request.method == 'POST':
        form = renderotp(request.POST)
        if form.is_valid():
           base32 = calc_base32(signerverify)
           totp = TOTP(base32)
           otp = totp.verify(form.cleaned_data['otp'], valid_window=5)
           data = signer.sign(signerverify)
           if otp == True:
             return HttpResponseRedirect('/resetpass?key=' + quote(data))
     return render(request, 'index.html', {'form': renderotp()})
    def validate_code(self, code):
        from pyotp import TOTP

        if not self.request.session.get('secret_key_activated', False):
            raise serializers.ValidationError(
                'You did not activated google authenticator',
                code=constants.GOOGLE_OTP_NOT_ACTIVATED_CODE)

        totp = TOTP(self.request.session['temp_otp_secret_key'])
        if not totp.verify(code, valid_window=1):
            raise serializers.ValidationError(
                'Code is incorrect', code=constants.GOOGLE_OTP_INVALID_CODE)
        return code
Example #10
0
    def verifyOTP(self, otp, transaction_key):
        # emsg=pbkdf2_sha256.encrypt(self.publicKey, rounds=12000, salt_size=32)

        baseForOtp = self.baseForOtp
        print(baseForOtp)
        print("base", type(baseForOtp))
        print(self.otp_value)
        print(otp)
        pot = TOTP(baseForOtp, interval=120)
        value = pot.verify(otp)
        print('value', value)

        if not value:
            return value

        try:
            key = self.user.keylist_set.all().filter(key=transaction_key)
        except Exception as e:
            print(e)
            return False

        if len(key) != 0:
            return False

        key = keyList(key=transaction_key, user=self.user)
        print(key)
        key.save()

        print(self.publicKey)
        try:

            flag = pbkdf2_sha256.verify(self.publicKey, transaction_key)
            print(flag)
            print(self.publicKey)
        except:
            print("Exception in key")
            return False
        return pot.verify(otp) and flag
Example #11
0
 def get(self, request, totp):
     chatrooms = Chatroom.objects.all()
     for chatroom in chatrooms:
         salt = chatroom.salt
         validator = TOTP(salt)
         if validator.verify(totp):
             data = ChatroomSerializer(chatroom).data
             token = jwt.encode(data, SECRET_KEY)
             body = {"token": token}
             body.update(
                 serializer_to_body(ChatroomSerializer, chatroom,
                                    "chatroom"))
             return Response(body, status=status.HTTP_200_OK)
     return Response(status=status.HTTP_403_FORBIDDEN)
Example #12
0
    def authenticate(self, request=None, **kwargs):
        """Check form validity."""
        django_version = tuple(
            [int(s) for s in django.get_version().split(".")])
        otp_auth = kwargs.pop("otp_auth", None)
        auth_user = partial(
            super(OTPAuthenticationBackend, self).authenticate, **kwargs)

        user = auth_user() if django_version < (1, 11) else auth_user(request)
        if hasattr(user, "otp_secret"):
            auth_provider = TOTP(user.otp_secret.secret)
            if not auth_provider.verify(otp_auth):
                user = None
        return user
Example #13
0
    def clean(self):
        super().clean()

        if self.errors:
            return

        if self.user.has_mfa_enabled():
            raise self.get_mfa_set_up_error()

        totp = TOTP(self.cleaned_data.get('secret', ''))

        if totp.verify(self.cleaned_data.get('code')):
            return

        raise self.get_invalid_mfa_error()
Example #14
0
def verify_otp(shared_key, code):
    try:
        app.logger.info(f'Shared key: {shared_key}, Code: {code}')
        totp = TOTP(shared_key, interval=interval)
        result = totp.verify(code)
        app.logger.info(f'Is otp code {code} valid? {result}')

        if (result):
            return ('Valid', 200)

        return ('Code not valid', 400)

    except Exception as error:
        app.logger.error(f'Exception {error}')
        return ('Error', 500)
Example #15
0
def auth(userID,OTP,path = 'Unknow'):
    from pyotp import TOTP
    from setting import OTPAdminLOG, Log_t_format
    from time import strftime, localtime as now

    User = OTPKeys[int(userID)]
    OTPi = TOTP(User[1])
    f = open(OTPAdminLOG,'a')
    if (OTPi.verify(OTP)):
        f.writelines( strftime(Log_t_format,now())+"\t"+path+"\tAuthencate Successful\n" )
        f.close()
        return True
    else:
        f.writelines( strftime(Log_t_format,now())+"\t"+path+"\tAuthencate Failed!!!!\n" )
        f.close()
        return False
Example #16
0
    def authenticate(self, user_id, key, **kwargs):
        totp = TOTP(user_id)
        if not totp.verify(key):
            raise AuthenticationError("TOTP taped token is not valid.")

        logger.info(
            "TOTP Token for user {} successfully verified.".format(user_id))

        # If the SSOProfile is not yet in MongoDB, set-it
        app_id = kwargs['app']
        app_name = kwargs['app_name']
        backend_id = kwargs['backend']
        login = kwargs['login']

        try:
            aes = AESCipher("{}{}{}{}{}".format(SECRET_KEY, app_id, backend_id,
                                                login, "totp"))
            encrypted_field = aes.key.hex()
            sso_profile = SSOProfile.objects.filter(
                encrypted_name=encrypted_field, login=login).first()
            if sso_profile:
                decrypted_value = sso_profile.get_data(
                    sso_profile.encrypted_value, app_id, backend_id, login,
                    "totp")
                if decrypted_value:
                    logger.debug(
                        "TOTP token for user '{}' retrieven from database.".
                        format(login))
                    return True

            # SSOProfile not found -> Create it
            sso_profile = SSOProfile()
            sso_profile.set_data(
                app_id, app_name, backend_id,
                BaseAbstractRepository.search_repository(
                    ObjectId(backend_id)).repo_name, login, "totp", user_id)
            logger.info(
                "TOTP token for user {} stored in database.".format(login))
            # Save in Mongo
            sso_profile.store()
        except Exception as e:
            logger.exception(e)
            raise e

        return True
Example #17
0
def token_valid(request, secret_key):
    totp = TOTP(secret_key)

    try:
        if (request.method == 'POST' and 'token' in request.POST):
            # Load the payload into a dictionary.
            raw_payload = request.read()
            payload = dict(
                item.split("=")
                for item in raw_payload.decode('utf8').split("&"))

            if (totp.verify(payload['token'])):
                return True

    except Exception as e:
        print(e)
    else:
        return False
    def verify_credentials(self, principal, credentials):
        code = credentials['code']
        from ..models import _tznow
        from ..models import OneTimePasswordCredential
        from pyotp import TOTP

        try:
            otp_credential = self._credential_directory.credentials.get(
                principal=principal,
                valid_from__lte=_tznow(),
                valid_till__gte=_tznow())

            secret_key = otp_credential.salt.decode()
            totp = TOTP(secret_key, interval=200)

            if totp.verify(code, valid_window=1):
                return True
        except OneTimePasswordCredential.DoesNotExist:
            pass
        return False
Example #19
0
def check_totp(totp, key):
    """Retruns true if totp is a valid TOTP

    Key word arguments:
    totp - The six digits provided by a TOTP app or function.
    key - API key.

    Output:
    Bool value based on whether or not the six_digits are the valid
    TOTP for the 30 second window."""
    pwd_file = open(u_file, 'r', encoding='ascii')
    reader = DictReader(pwd_file)
    # Performing input validation.
    if validate_totp(totp) and validate_api_key(key):
        for row in reader:
            # Checking the TOTP value
            if key == row['apikey'] and int(row['fl_count']) <= 9:
                MFA = TOTP(row['totp'])
                if MFA.verify(totp):
                    return True
                else:
                    return False
    else:
        return False
Example #20
0
def is_valid_otp(otp,
                 instance,
                 interval=OTP_INTERVAL.OTP_LIVE_TIME,
                 for_time=None):
    """
  :param otp:
  :param otp_instance:
  :param interval:
  :param for_time:
  :return: boolean
  """
    if not instance.can_check_otp():
        raise LimitedException

    if not instance or not instance.signature:
        return False

    signature = instance.signature
    key = generate_secret_key(signature)
    totp = TOTP(key, interval=interval)
    if for_time is None:
        for_time = datetime.datetime.now().replace(microsecond=0)
    # TODO: Logger for generated OTP code
    return totp.verify(otp, for_time, valid_window=1)
Example #21
0
 def validate_code(form, field):
     totp = TOTP(form.secret.data)
     if not totp.verify(field.data, valid_window=1):
         raise ValidationError(_('The code is wrong, please try again.'))
Example #22
0
 def authenticate(self, user_id, key):
     logger.debug("")
     totp = TOTP(user_id)
     if not totp.verify(key):
         raise AuthenticationError("TOTP taped token is not valid.")
     return True
Example #23
0
class Safe():
    """Stores the encrypted password for a determined period.

    This class stores the enctypted password, provides a passphrase and token
    and returns the encrypted password when provided the valid token"""
    def __init__(self):
        pass

    def encrypt(self, password, minutes):
        """Encrypts the user password.

        Parameters
        ----------
        password : str
            The password to encrypt

        minutes : int
            The validity period, in minutes, of the TOTP token used to
            retreive the encrypted password.

        Returns
        -------
        passphrase : str
            The passhprase used to derive the encryption key.

        token : str
            The TOTP token required to retreive the encrypted password.
        """

        self._window = 60 * int(minutes)

        # Generate TOTP source
        self._totp = TOTP(random_base32(), interval=1)

        # Generate TOTP token
        token = self._totp.now()

        # Generate passphrase and derive key from passphrase
        passphrase = Passphrase().generate(PASSPHRASE_N_WORDS)
        key = _generate_key(passphrase)

        # Encrypt password using key
        f = Fernet(key)
        self._password = f.encrypt(password.encode('utf-8'))

        return passphrase, token

    def get_password(self, token):
        """Returns the encrypted password, provided a valid TOTP token.

        Parameters
        ----------
        token : str
            The TOTP token required to retreive the encrypted password.

        Returns
        -------
        password : str
            The encrypted password.

        Raises
        ------
        InvalidToken
            If the provided TOTP token is invalid or expired.
        """

        token = token.replace(' ', '')

        if self._totp.verify(token, valid_window=self._window):
            return self._password
        else:
            raise InvalidToken('Invalid TOTP token.')