Python cryptography.fernet.InvalidToken() Examples

The following are 25 code examples of cryptography.fernet.InvalidToken(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.fernet , or try the search function .
Example #1
Source File: cookie_storage.py    From aiohttp-session with Apache License 2.0 7 votes vote down vote up
def load_session(self, request):
        cookie = self.load_cookie(request)
        if cookie is None:
            return Session(None, data=None, new=True, max_age=self.max_age)
        else:
            try:
                data = self._decoder(
                    self._fernet.decrypt(
                        cookie.encode('utf-8'),
                        ttl=self.max_age
                    ).decode('utf-8')
                )
                return Session(None, data=data,
                               new=False, max_age=self.max_age)
            except InvalidToken:
                log.warning("Cannot decrypt cookie value, "
                            "create a new fresh session")
                return Session(None, data=None, new=True, max_age=self.max_age) 
Example #2
Source File: variable.py    From airflow with Apache License 2.0 7 votes vote down vote up
def get_val(self):
        """
        Get Airflow Variable from Metadata DB and decode it using the Fernet Key
        """
        if self._val is not None and self.is_encrypted:
            try:
                fernet = get_fernet()
                return fernet.decrypt(bytes(self._val, 'utf-8')).decode()
            except InvalidFernetToken:
                self.log.error("Can't decrypt _val for key=%s, invalid token or value", self.key)
                return None
            except Exception:  # pylint: disable=broad-except
                self.log.error("Can't decrypt _val for key=%s, FERNET_KEY configuration missing", self.key)
                return None
        else:
            return self._val 
Example #3
Source File: test_security.py    From maas with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_assures_data_integrity(self):
        self.write_secret()
        testdata = factory.make_bytes(size=10)
        token = fernet_encrypt_psk(testdata)
        bad_token = bytearray(token)
        # Flip a bit in the token, so we can ensure it won't decrypt if it
        # has been corrupted. Subtract 4 to avoid the end of the token; that
        # portion is just padding, and isn't covered by the HMAC.
        byte_to_flip = randint(0, len(bad_token) - 4)
        bit_to_flip = 1 << randint(0, 7)
        bad_token[byte_to_flip] ^= bit_to_flip
        bad_token = bytes(bad_token)
        test_description = "token=%s; token[%d] ^= 0x%02x" % (
            token.decode("utf-8"),
            byte_to_flip,
            bit_to_flip,
        )
        with ExpectedException(InvalidToken, msg=test_description):
            fernet_decrypt_psk(bad_token) 
Example #4
Source File: test_secret_encryption.py    From shhh with MIT License 6 votes vote down vote up
def test_wrong_passphrase(self):
        with self.assertRaises(InvalidToken):
            Secret(self.encrypted_text, "wrongPassphrase").decrypt() 
Example #5
Source File: crypt.py    From zun with Apache License 2.0 6 votes vote down vote up
def decrypt(data, encryption_key=None):
    if data is None:
        return None

    encryption_key = get_valid_encryption_key(encryption_key)
    encoded_key = base64.b64encode(encryption_key.encode('utf-8'))
    sym = fernet.Fernet(encoded_key)
    try:
        value = sym.decrypt(encodeutils.safe_encode(data))
        if value is not None:
            return encodeutils.safe_decode(value, 'utf-8')
    except fernet.InvalidToken:
        raise exception.InvalidEncryptionKey() 
Example #6
Source File: crypto.py    From quay with Apache License 2.0 6 votes vote down vote up
def decrypt_string(string, key, ttl=None):
    """
    Decrypts an encrypted string with the specified key.

    The key must be 32 raw bytes.
    """
    f = Fernet(key)

    # Fernet() works only on byte objects. Convert the string to bytes before decrypting.
    encrypted_bytes = string.encode()  # str -> bytes

    try:
        decrypted_bytes = f.decrypt(encrypted_bytes, ttl=ttl)
    except InvalidToken:
        """
        From the the Cryptography's library documentation:

        If the token is in any way invalid, this exception is raised.
        A token may be invalid for a number of reasons: it is older than the
        ttl, it is malformed, or it does not have a valid signature.
        """
        return None  # TODO(kmullins): Shall we log this case? Is it expected?

    decrypted_string = decrypted_bytes.decode()  # bytes -> str
    return decrypted_string 
Example #7
Source File: utils.py    From shhh with MIT License 5 votes vote down vote up
def read_secret(slug: str, passphrase: str) -> Tuple[Dict, int]:
    """Read a secret.

    Args:
        slug (str): Unique slug link to access the secret.
        passphrase (str): Passphrase needed to decrypt the secret.

    """
    secret = Entries.query.filter_by(slug_link=slug).first()
    if not secret:
        app.logger.warning(
            f"{slug} tried to read but do not exists in database")
        return dict(status=Status.EXPIRED.value,
                    msg=("Sorry, we can't find a secret, it has expired, "
                         "been deleted or has already been read.")), 404

    try:
        msg = Secret(secret.encrypted_text, passphrase).decrypt()
    except InvalidToken:
        remaining = secret.tries - 1
        if remaining == 0:
            # Number of tries exceeded
            app.logger.warning(f"{slug} tries to open secret exceeded")
            secret.delete()
            return dict(
                status=Status.INVALID.value,
                msg=("The passphrase is not valid. You've exceeded the "
                     "number of tries and the secret has been deleted.")), 401

        secret.update(tries=remaining)
        app.logger.warning(f"{slug} wrong passphrase used. "
                           f"Number of tries remaining: {remaining}")
        return dict(status=Status.INVALID.value,
                    msg=("Sorry the passphrase is not valid. "
                         f"Number of tries remaining: {remaining}")), 401

    secret.delete()  # Delete message after it's read
    app.logger.info(f"{slug} was decrypted and deleted")
    return dict(status=Status.SUCCESS.value, msg=html.escape(msg)), 200 
Example #8
Source File: test_security.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_messages_from_future_exceeding_clock_skew_limit_rejected(self):
        self.write_secret()
        testdata = factory.make_bytes()
        now = time.time()
        self.patch(time, "time").side_effect = [now + 61, now]
        token = fernet_encrypt_psk(testdata)
        with ExpectedException(InvalidToken):
            fernet_decrypt_psk(token, ttl=1) 
Example #9
Source File: test_security.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_messages_from_the_past_exceeding_ttl_rejected(self):
        self.write_secret()
        testdata = factory.make_bytes()
        now = time.time()
        self.patch(time, "time").side_effect = [now - 2, now]
        token = fernet_encrypt_psk(testdata)
        with ExpectedException(InvalidToken):
            fernet_decrypt_psk(token, ttl=1) 
Example #10
Source File: payment_methods.py    From silver with Apache License 2.0 5 votes vote down vote up
def decrypt_data(self, crypted_data):
        key = settings.PAYMENT_METHOD_SECRET

        try:
            return str(Fernet(key).decrypt(bytes(crypted_data)))
        except InvalidToken:
            return None 
Example #11
Source File: token_manager.py    From Flask-User with MIT License 5 votes vote down vote up
def verify_token(self, token, expiration_in_seconds=None):
        """ Verify token signature, verify token expiration, and decrypt token.

        | Returns None if token is expired or invalid.
        | Returns a list of strings and integers on success.

        Implemented as::

            concatenated_str = self.decrypt_string(token, expiration_in_seconds)
            data_items = self.decode_data_items(concatenated_str)
            return data_items

        Example:

        ::

            # Verify that a User with ``user_id`` has a password that ends in ``password_ends_with``.
            token_is_valid = False
            data_items = token_manager.verify(token, expiration_in_seconds)
            if data_items:
                user_id = data_items[0]
                password_ends_with = data_items[1]
                user = user_manager.db_manager.get_user_by_id(user_id)
                token_is_valid = user and user.password[-8:]==password_ends_with
        """

        from cryptography.fernet import InvalidToken

        try:
            concatenated_str = self.decrypt_string(token, expiration_in_seconds)
            data_items = self.decode_data_items(concatenated_str)
        except InvalidToken:
            data_items = None

        return data_items 
Example #12
Source File: spec.py    From badwolf with MIT License 5 votes vote down vote up
def _decrypt(self, token):
        from cryptography.fernet import InvalidToken

        try:
            return SecureToken.decrypt(token)
        except InvalidToken:
            logger.warning('Invalid secure token: %s', token)
            return '' 
Example #13
Source File: AuthContainer.py    From katprep with GNU General Public License v3.0 5 votes vote down vote up
def get_credential(self, hostname):
        """
        This function returns credentials for a particular hostname.
        
        :param hostname: hostname
        :type hostname: str
        """
        hostname = self.cut_hostname(hostname)
        try:
            if self.is_encrypted():
                self.LOGGER.debug("Decrypting crendentials")
                crypto = Fernet(self.KEY)
                return (
                    self.CREDENTIALS[hostname]["username"],
                    crypto.decrypt(self.CREDENTIALS[hostname]["password"][2:].encode())
                    )
            else:
                #return plain information
                self.LOGGER.debug("Plain login data")
                return (
                    self.CREDENTIALS[hostname]["username"],
                    self.CREDENTIALS[hostname]["password"]
                    )
        except InvalidToken:
            raise ContainerException("Invalid password specified!")
        except KeyError:
            pass 
Example #14
Source File: ghost.py    From ghost with Apache License 2.0 5 votes vote down vote up
def _assert_valid_stash(self):
        if not self._storage.is_initialized:
            raise GhostError(
                'Stash not initialized. Please initialize it and try again')
        else:
            try:
                key = self._storage.get('stored_passphrase')
                if key:
                    self._decrypt(key['value'])
            except InvalidToken:
                raise GhostError(
                    'The passphrase provided is invalid for this stash. '
                    'Please provide the correct passphrase') 
Example #15
Source File: encrypt.py    From maple-blog with GNU General Public License v3.0 5 votes vote down vote up
def post(self):
        request_data = request.data
        password = request_data.pop('password', '')
        content = request_data.pop('content', '')
        if not password or not content:
            return HTTP.BAD_REQUEST(message="params required.")
        ec = Encrypt(password, current_app.config['SECRET_KEY_SALT'])
        try:
            return HTTP.OK(data=ec.decrypt(content))
        except InvalidToken:
            return HTTP.BAD_REQUEST(message="password is not correct") 
Example #16
Source File: diagnostic_cli.py    From autopush with Mozilla Public License 2.0 5 votes vote down vote up
def run(self):
        match = PUSH_RE.search(self._endpoint)
        if not match:
            return "Not a valid endpoint"

        md = match.groupdict()
        api_ver, token = md.get("api_ver", "v1"), md["token"]

        try:
            parsed = self._conf.parse_endpoint(
                self.db.metrics,
                token=token,
                version=api_ver,
            )
            uaid, chid = parsed["uaid"], parsed["chid"]
        except (InvalidTokenException, InvalidToken) as ex:
            print(("Token could not be deciphered: {}. "
                   "Are you using the correct configuration or platform?")
                  .format(ex))
            return "Invalid Token"

        print("UAID: {}\nCHID: {}\n".format(uaid, chid))

        try:
            rec = self.db.router.get_uaid(uaid)
            print("Router record:")
            self._pp.pprint(rec)
            if "current_month" in rec:
                chans = Message(rec["current_month"],
                                boto_resource=self.db.resource).all_channels(
                    uaid)
                print("Channels in message table:")
                self._pp.pprint(chans)
        except ItemNotFound as ex:
            print("Item Missing from database: {}".format(ex))
            return "Not Found"
        print("\n") 
Example #17
Source File: test_diagnostic_cli.py    From autopush with Mozilla Public License 2.0 5 votes vote down vote up
def test_invalid_endpoint(self):
        def err(*args, **kwargs):
            raise InvalidToken("You are unworthy")

        cli = self._makeFUT([
            "--router_tablename=fred",
            "http://something/wpush/v1/indecipherable_token"])
        cli._conf = Mock()
        cli._conf.parse_endpoint.side_effect = err
        returncode = cli.run()
        assert returncode == "Invalid Token" 
Example #18
Source File: test_endpoint.py    From autopush with Mozilla Public License 2.0 5 votes vote down vote up
def test_delete_token_invalid(self):
        self.fernet_mock.configure_mock(**{
            "decrypt.side_effect": InvalidToken})
        resp = yield self.client.delete(self.url(message_id='%20'))
        assert resp.get_status() == 400 
Example #19
Source File: webpush.py    From autopush with Mozilla Public License 2.0 5 votes vote down vote up
def extract_subscription(self, d):
        try:
            result = self.context["conf"].parse_endpoint(
                self.context["metrics"],
                token=d["token"],
                version=d["api_ver"],
                ckey_header=d["ckey_header"],
                auth_header=d["auth_header"],
            )
        except (VapidAuthException):
            raise InvalidRequest("missing authorization header",
                                 status_code=401, errno=109)
        except (InvalidTokenException, InvalidToken):
            raise InvalidRequest("invalid token", status_code=404, errno=102)
        return result 
Example #20
Source File: message.py    From autopush with Mozilla Public License 2.0 5 votes vote down vote up
def extract_data(self, req):
        message_id = req['path_kwargs'].get('message_id')
        try:
            notif = WebPushNotification.from_message_id(
                bytes(message_id),
                fernet=self.context['conf'].fernet,
            )
        except (InvalidToken, InvalidTokenException):
            raise InvalidRequest("Invalid message ID",
                                 status_code=400)
        return dict(notification=notif) 
Example #21
Source File: crypto.py    From desec-stack with MIT License 5 votes vote down vote up
def decrypt(token, *, context, ttl=None):
    key = retrieve_key(label=b'crypt', context=context)
    try:
        value = Fernet(key=key).decrypt(token, ttl=ttl)
        metrics.get('desecapi_key_decryption_success').labels(context).inc()
        return value
    except InvalidToken:
        raise ValueError 
Example #22
Source File: crypt.py    From pgrepup with GNU General Public License v3.0 5 votes vote down vote up
def decrypt(password):
    encrypted_passwords = config().get('Security', 'encrypted_credentials') == 'y'
    if not encrypted_passwords:
        return password

    try:
        f = Fernet(_get_key())
        return f.decrypt(password)
    except InvalidToken:
        print("Invalid master password")
        sys.exit(-1) 
Example #23
Source File: AuthContainer.py    From katprep with GNU General Public License v3.0 4 votes vote down vote up
def __manage_credentials(self, hostname, username, password,
        remove_entry=False):
        """
        This functions adds or removes credentials to/from the authentication
        container.
        Adding credentials requires a hostname, username and corresponding
        password. Removing credentials only requires a hostname.

        There are two alias functions for credentials management:
        add_credentials() and remove_credentials()

        :param hostname: hostname
        :type hostname: str
        :param username: username
        :type username: str
        :param password: corresponding password
        :type password: str
        :param remove_entry: setting True will remove an entry
        :type remove_entry: bool
        """
        global CREDENTIALS
        hostname = self.cut_hostname(hostname)

        try:
            if remove_entry:
                #remove entry
                del self.CREDENTIALS[hostname]
            else:
                #add entry
                self.CREDENTIALS[hostname] = {}
                self.CREDENTIALS[hostname]["username"] = username
                #add encrypted or plain password
                if self.KEY:
                    crypto = Fernet(self.KEY)
                    self.CREDENTIALS[hostname]["password"] = "s/{0}".format(
                        crypto.encrypt(password.encode()))
                else:
                    self.CREDENTIALS[hostname]["password"] = password
        except InvalidToken:
            raise ContainerException("Invalid password specified!")
        except KeyError:
            pass

    #aliases 
Example #24
Source File: beaconing.py    From maas with GNU Affero General Public License v3.0 4 votes vote down vote up
def read_beacon_payload(beacon_bytes):
    """Returns a BeaconPayload namedtuple representing the given beacon bytes.

    Decrypts the inner beacon data if necessary.

    :param beacon_bytes: beacon payload (bytes).
    :return: BeaconPayload namedtuple
    """
    if len(beacon_bytes) < BEACON_HEADER_LENGTH_V1:
        raise InvalidBeaconingPacket(
            "Beaconing packet must be at least %d bytes."
            % BEACON_HEADER_LENGTH_V1
        )
    header = beacon_bytes[:BEACON_HEADER_LENGTH_V1]
    version, beacon_type_code, expected_payload_length = struct.unpack(
        BEACON_HEADER_FORMAT_V1, header
    )
    actual_payload_length = len(beacon_bytes) - BEACON_HEADER_LENGTH_V1
    if len(beacon_bytes) - BEACON_HEADER_LENGTH_V1 < expected_payload_length:
        raise InvalidBeaconingPacket(
            "Invalid payload length: expected %d bytes, got %d bytes."
            % (expected_payload_length, actual_payload_length)
        )
    payload_start = BEACON_HEADER_LENGTH_V1
    payload_end = BEACON_HEADER_LENGTH_V1 + expected_payload_length
    payload_bytes = beacon_bytes[payload_start:payload_end]
    payload = None
    if version == 1:
        if len(payload_bytes) == 0:
            # No encrypted inner payload; nothing to do.
            pass
        else:
            try:
                decrypted_data = fernet_decrypt_psk(
                    payload_bytes, ttl=60, raw=True
                )
            except InvalidToken:
                raise InvalidBeaconingPacket(
                    "Failed to decrypt inner payload: check MAAS secret key."
                )
            try:
                decompressed_data = decompress(decrypted_data)
            except OSError:
                raise InvalidBeaconingPacket(
                    "Failed to decompress inner payload: %r" % decrypted_data
                )
            try:
                # Replace the data in the dictionary with its decrypted form.
                payload = BSON.decode(decompressed_data)
            except BSONError:
                raise InvalidBeaconingPacket(
                    "Inner beacon payload is not BSON: %r" % decompressed_data
                )
    else:
        raise InvalidBeaconingPacket("Unknown beacon version: %d" % version)
    beacon_type_code = payload["type"] if payload else beacon_type_code
    return BeaconPayload(
        beacon_bytes, version, BEACON_TYPE_VALUES[beacon_type_code], payload
    ) 
Example #25
Source File: nginx-ldap-auth-daemon.py    From docker-ldap-auth with GNU General Public License v3.0 4 votes vote down vote up
def do_GET(self):

        ctx = self.ctx

        ctx['action'] = 'input parameters check'
        for k, v in self.get_params().items():
            ctx[k] = self.headers.get(v[0], v[1])
            if ctx[k] == None:
                self.auth_failed(ctx, 'required "%s" header was not passed' % k)
                return True

        ctx['action'] = 'performing authorization'
        auth_header = self.headers.get('Authorization')
        auth_cookie = self.get_cookie(ctx['cookiename'])

        if auth_cookie != None and auth_cookie != '':
            auth_header = "Basic " + auth_cookie
            self.log_message("using username/password from cookie %s" %
                             ctx['cookiename'])
        else:
            self.log_message("using username/password from authorization header")

        if auth_header is None or not auth_header.lower().startswith('basic '):

            self.send_response(401)
            self.send_header('WWW-Authenticate', 'Basic realm="' + ctx['realm'] + '"')
            self.send_header('Cache-Control', 'no-cache')
            self.end_headers()

            return True

        ctx['action'] = 'decoding credentials'

        try:
            cipher_suite = Fernet(REPLACEWITHFERNETKEY)
            self.log_message('Trying to dechipher credentials...')
            auth_decoded = auth_header[6:].encode()
            auth_decoded = cipher_suite.decrypt(auth_decoded)
            auth_decoded = auth_decoded.decode("utf-8")
            user, passwd = auth_decoded.split(':', 1)
        except InvalidToken:
            self.log_message('Incorrect token. Trying to decode credentials from BASE64...')
            auth_decoded = base64.b64decode(auth_header[6:])
            auth_decoded = auth_decoded.decode("utf-8")
            user, passwd = auth_decoded.split(':', 1)
        except Exception as e:
            self.auth_failed(ctx)
            self.log_error(e)
            return True

        ctx['user'] = user
        ctx['pass'] = passwd

        # Continue request processing
        return False