File size: 62,447 Bytes
5980447
1
2
{"repo": "privacyidea/privacyidea", "pull_number": 1492, "instance_id": "privacyidea__privacyidea-1492", "issue_numbers": "", "base_commit": "d6ea312fe6d5a33b32fe53e69620e69aacb01f2f", "patch": "diff --git a/privacyidea/api/lib/postpolicy.py b/privacyidea/api/lib/postpolicy.py\n--- a/privacyidea/api/lib/postpolicy.py\n+++ b/privacyidea/api/lib/postpolicy.py\n@@ -41,11 +41,10 @@\n \"\"\"\n import datetime\n import logging\n-log = logging.getLogger(__name__)\n+import traceback\n from privacyidea.lib.error import PolicyError\n from flask import g, current_app, make_response\n from privacyidea.lib.policy import SCOPE, ACTION, AUTOASSIGNVALUE\n-from privacyidea.lib.user import get_user_from_param\n from privacyidea.lib.token import get_tokens, assign_token, get_realms_of_token, get_one_token\n from privacyidea.lib.machine import get_hostname, get_auth_items\n from .prepolicy import check_max_token_user, check_max_token_realm\n@@ -60,6 +59,7 @@\n from privacyidea.lib.realm import get_default_realm\n from privacyidea.lib.subscriptions import subscription_status\n \n+log = logging.getLogger(__name__)\n \n optional = True\n required = False\n@@ -148,9 +148,17 @@ def after_request(response):\n     if current_app.config.get(\"PI_NO_RESPONSE_SIGN\"):\n         return response\n \n-    priv_file = current_app.config.get(\"PI_AUDIT_KEY_PRIVATE\")\n-    pub_file = current_app.config.get(\"PI_AUDIT_KEY_PUBLIC\")\n-    sign_object = Sign(priv_file, pub_file)\n+    priv_file_name = current_app.config.get(\"PI_AUDIT_KEY_PRIVATE\")\n+    try:\n+        with open(priv_file_name, 'rb') as priv_file:\n+            priv_key = priv_file.read()\n+        sign_object = Sign(priv_key, public_key=None)\n+    except (IOError, ValueError, TypeError) as e:\n+        log.info('Could not load private key from '\n+                 'file {0!s}: {1!r}!'.format(priv_file_name, e))\n+        log.debug(traceback.format_exc())\n+        return response\n+\n     request.all_data = get_all_params(request.values, request.data)\n     # response can be either a Response object or a Tuple (Response, ErrorID)\n     response_value = 200\ndiff --git a/privacyidea/lib/auditmodules/sqlaudit.py b/privacyidea/lib/auditmodules/sqlaudit.py\n--- a/privacyidea/lib/auditmodules/sqlaudit.py\n+++ b/privacyidea/lib/auditmodules/sqlaudit.py\n@@ -45,23 +45,21 @@\n from privacyidea.lib.utils import censor_connect_string\n from privacyidea.lib.lifecycle import register_finalizer\n from privacyidea.lib.utils import truncate_comma_list\n+from privacyidea.lib.framework import get_app_config_value\n from sqlalchemy import MetaData, cast, String\n from sqlalchemy import asc, desc, and_, or_\n import datetime\n import traceback\n from six import string_types\n-\n-\n-log = logging.getLogger(__name__)\n-\n-metadata = MetaData()\n-\n from privacyidea.models import audit_column_length as column_length\n-from privacyidea.models import AUDIT_TABLE_NAME as TABLE_NAME\n from privacyidea.models import Audit as LogEntry\n from sqlalchemy import create_engine\n from sqlalchemy.orm import sessionmaker, scoped_session\n \n+log = logging.getLogger(__name__)\n+\n+metadata = MetaData()\n+\n \n class Audit(AuditBase):\n     \"\"\"\n@@ -271,7 +269,16 @@ def read_keys(self, pub, priv):\n         :type priv: string with filename\n         :return: None\n         \"\"\"\n-        self.sign_object = Sign(priv, pub)\n+        try:\n+            with open(priv, \"rb\") as privkey_file:\n+                private_key = privkey_file.read()\n+            with open(pub, 'rb') as pubkey_file:\n+                public_key = pubkey_file.read()\n+            self.sign_object = Sign(private_key, public_key)\n+        except Exception as e:\n+            log.error(\"Error reading key file: {0!r})\".format(e))\n+            log.debug(traceback.format_exc())\n+            raise e\n \n     def _check_missing(self, audit_id):\n         \"\"\"\n@@ -481,9 +488,10 @@ def clear(self):\n     \n     def audit_entry_to_dict(self, audit_entry):\n         sig = None\n+        verify_old_sig = get_app_config_value('PI_CHECK_OLD_SIGNATURES', False)\n         if self.sign_data:\n             sig = self.sign_object.verify(self._log_to_string(audit_entry),\n-                                          audit_entry.signature)\n+                                          audit_entry.signature, verify_old_sig)\n \n         is_not_missing = self._check_missing(int(audit_entry.id))\n         # is_not_missing = True\ndiff --git a/privacyidea/lib/crypto.py b/privacyidea/lib/crypto.py\n--- a/privacyidea/lib/crypto.py\n+++ b/privacyidea/lib/crypto.py\n@@ -53,28 +53,25 @@\n import binascii\n import six\n import ctypes\n-from Crypto.Hash import SHA256 as HashFunc\n-from Crypto.Cipher import AES\n-from Crypto.PublicKey import RSA\n+\n import base64\n-try:\n-    from Crypto.Signature import pkcs1_15\n-    SIGN_WITH_RSA = False\n-except ImportError:\n-    # Bummer the version of PyCrypto has no PKCS1_15\n-    SIGN_WITH_RSA = True\n import traceback\n-from six import PY2, text_type\n+from six import PY2\n \n from privacyidea.lib.log import log_with\n from privacyidea.lib.error import HSMException\n from privacyidea.lib.framework import (get_app_local_store, get_app_config_value,\n                                        get_app_config)\n-from privacyidea.lib.utils import to_unicode, to_bytes, hexlify_and_unicode, b64encode_and_unicode\n+from privacyidea.lib.utils import (to_unicode, to_bytes, hexlify_and_unicode,\n+                                   b64encode_and_unicode)\n \n from cryptography.hazmat.backends import default_backend\n from cryptography.hazmat.primitives.asymmetric import rsa\n from cryptography.hazmat.primitives import serialization\n+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n+from cryptography.hazmat.primitives import padding\n+from cryptography.hazmat.primitives import hashes\n+from cryptography.hazmat.primitives.asymmetric import padding as asym_padding\n \n import passlib.hash\n if hasattr(passlib.hash.pbkdf2_sha512, \"encrypt\"):\n@@ -118,16 +115,18 @@ def hmac_digest(self, data_input, hash_algo):\n         self._clearKey_(preserve=self.preserve)\n         return h\n \n-    def aes_decrypt(self, data_input):\n+    def aes_ecb_decrypt(self, enc_data):\n         '''\n-        support inplace aes decryption for the yubikey\n+        support inplace aes decryption for the yubikey (mode ECB)\n \n-        :param data_input: data, that should be decrypted\n+        :param enc_data: data, that should be decrypted\n         :return: the decrypted data\n         '''\n         self._setupKey_()\n-        aes = AES.new(self.bkey, AES.MODE_ECB)\n-        msg_bin = aes.decrypt(data_input)\n+        backend = default_backend()\n+        cipher = Cipher(algorithms.AES(self.bkey), modes.ECB(), backend=backend)\n+        decryptor = cipher.decryptor()\n+        msg_bin = decryptor.update(enc_data) + decryptor.finalize()\n         self._clearKey_(preserve=self.preserve)\n         return msg_bin\n \n@@ -318,70 +317,75 @@ def decryptPin(cryptPin):\n \n \n @log_with(log, log_entry=False)\n-def encrypt(data, iv, id=0):\n-    '''\n+def encrypt(data, iv, key_id=0):\n+    \"\"\"\n     encrypt a variable from the given input with an initialisation vector\n \n-    :param data: buffer, which contains the value\n-    :type  data: bytes or str\n-    :param iv:   initialisation vector\n-    :type  iv:   bytes or str\n-    :param id:   contains the key id of the keyset which should be used\n-    :type  id:   int\n-    :return:     encrypted and hexlified data\n+    :param data:   buffer, which contains the value\n+    :type  data:   bytes or str\n+    :param iv:     initialisation vector\n+    :type  iv:     bytes or str\n+    :param key_id: contains the key id of the keyset which should be used\n+    :type  key_id: int\n+    :return: encrypted and hexlified data\n     :rtype: str\n-\n-    '''\n+    \"\"\"\n     hsm = get_hsm()\n-    ret = hsm.encrypt(to_bytes(data), to_bytes(iv), id)\n+    ret = hsm.encrypt(to_bytes(data), to_bytes(iv), key_id=key_id)\n     return hexlify_and_unicode(ret)\n \n \n @log_with(log, log_exit=False)\n-def decrypt(input, iv, id=0):\n-    '''\n-    decrypt a variable from the given input with an initialiation vector\n-\n-    :param input: buffer, which contains the crypted value\n-    :type  input: bytes or str\n-    :param iv:    initialisation vector\n-    :type  iv:    bytes or str\n-    :param id:    contains the key id of the keyset which should be used\n-    :type  id:    int\n-    :return:      decrypted buffer\n+def decrypt(enc_data, iv, key_id=0):\n+    \"\"\"\n+    decrypt a variable from the given input with an initialisation vector\n+\n+    :param enc_data: buffer, which contains the crypted value\n+    :type  enc_data: bytes or str\n+    :param iv:       initialisation vector\n+    :type  iv:       bytes or str\n+    :param key_id:   contains the key id of the keyset which should be used\n+    :type  key_id:   int\n+    :return: decrypted buffer\n     :rtype: bytes\n-    '''\n+    \"\"\"\n     hsm = get_hsm()\n-    res = hsm.decrypt(to_bytes(input), to_bytes(iv), id)\n+    res = hsm.decrypt(to_bytes(enc_data), to_bytes(iv), key_id=key_id)\n     return res\n \n \n @log_with(log, log_exit=False)\n-def aes_decrypt(key, iv, cipherdata, mode=AES.MODE_CBC):\n+def aes_cbc_decrypt(key, iv, enc_data):\n     \"\"\"\n-    Decrypts the given cipherdata with the key/iv.\n+    Decrypts the given cipherdata with AES (CBC Mode) using the key/iv.\n+\n+    Attention: This function returns the decrypted data as is, without removing\n+    any padding. The calling function must take care of this!\n \n     :param key: The encryption key\n     :type key: bytes\n     :param iv: The initialization vector\n     :type iv: bytes\n-    :param cipherdata: The cipher text\n-    :type cipherdata: binary string\n+    :param enc_data: The cipher text\n+    :type enc_data: binary string\n     :param mode: The AES MODE\n     :return: plain text in binary data\n     :rtype: bytes\n     \"\"\"\n-    aes = AES.new(key, mode, iv)\n-    output = aes.decrypt(cipherdata)\n-    padding = six.indexbytes(output, len(output) - 1)\n-    # remove padding\n-    output = output[0:-padding]\n+    backend = default_backend()\n+    mode = modes.CBC(iv)\n+    cipher = Cipher(algorithms.AES(key), mode=mode, backend=backend)\n+    decryptor = cipher.decryptor()\n+    output = decryptor.update(enc_data) + decryptor.finalize()\n     return output\n \n \n-def aes_encrypt(key, iv, data, mode=AES.MODE_CBC):\n+def aes_cbc_encrypt(key, iv, data):\n     \"\"\"\n-    encrypts the given data with key/iv\n+    encrypts the given data with AES (CBC Mode) using key/iv.\n+\n+    Attention: This function expects correctly padded input data (multiple of\n+    AES block size). The calling function must take care of this!\n \n     :param key: The encryption key\n     :type key: binary string\n@@ -393,11 +397,13 @@ def aes_encrypt(key, iv, data, mode=AES.MODE_CBC):\n     :return: plain text in binary data\n     :rtype: bytes\n     \"\"\"\n-    aes = AES.new(key, mode, iv)\n-    # pad data\n-    num_pad = aes.block_size - (len(data) % aes.block_size)\n-    data = data + six.int2byte(num_pad) * num_pad\n-    output = aes.encrypt(data)\n+    assert len(data) % (algorithms.AES.block_size // 8) == 0\n+    # do the encryption\n+    backend = default_backend()\n+    mode = modes.CBC(iv)\n+    cipher = Cipher(algorithms.AES(key), mode=mode, backend=backend)\n+    encryptor = cipher.encryptor()\n+    output = encryptor.update(data) + encryptor.finalize()\n     return output\n \n \n@@ -414,25 +420,33 @@ def aes_encrypt_b64(key, data):\n     :return: base64 encrypted output, containing IV and encrypted data\n     :rtype: str\n     \"\"\"\n+    # pad data\n+    padder = padding.PKCS7(algorithms.AES.block_size).padder()\n+    padded_data = padder.update(data) + padder.finalize()\n     iv = geturandom(16)\n-    encdata = aes_encrypt(key, iv, data)\n+    encdata = aes_cbc_encrypt(key, iv, padded_data)\n     return b64encode_and_unicode(iv + encdata)\n \n \n-def aes_decrypt_b64(key, data_b64):\n+def aes_decrypt_b64(key, enc_data_b64):\n     \"\"\"\n     This function decrypts base64 encoded data (containing the IV)\n     using AES-128-CBC. Used for PSKC\n \n     :param key: binary key\n-    :param data_b64: base64 encoded data (IV + encdata)\n-    :type data_b64: str\n+    :param enc_data_b64: base64 encoded data (IV + encdata)\n+    :type enc_data_b64: str\n     :return: encrypted data\n     \"\"\"\n-    data_bin = base64.b64decode(data_b64)\n+    data_bin = base64.b64decode(enc_data_b64)\n     iv = data_bin[:16]\n     encdata = data_bin[16:]\n-    output = aes_decrypt(key, iv, encdata)\n+    padded_data = aes_cbc_decrypt(key, iv, encdata)\n+\n+    # remove padding\n+    unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()\n+    output = unpadder.update(padded_data) + unpadder.finalize()\n+\n     return output\n \n \n@@ -624,35 +638,55 @@ def zerome(bufferObject):\n     return\n \n \n+def _slow_rsa_verify_raw(key, sig, msg):\n+    assert isinstance(sig, six.integer_types)\n+    assert isinstance(msg, six.integer_types)\n+    if hasattr(key, 'public_numbers'):\n+        pn = key.public_numbers()\n+    elif hasattr(key, 'private_numbers'):  # pragma: no cover\n+        pn = key.private_numbers().public_numbers\n+    else:  # pragma: no cover\n+        raise TypeError('No public key')\n+\n+    # compute m**d (mod n)\n+    return msg == pow(sig, pn.e, pn.n)\n+\n+\n class Sign(object):\n     \"\"\"\n     Signing class that is used to sign Audit Entries and to sign API responses.\n     \"\"\"\n-    def __init__(self, private_file, public_file):\n+    sig_ver = 'rsa_sha256_pss'\n+\n+    def __init__(self, private_key=None, public_key=None):\n         \"\"\"\n-        :param private_file: The privacy Key file\n-        :type private_file: filename\n-        :param public_file:  The public key file\n-        :type public_file: filename\n+        :param private_key: The private Key data in PEM format\n+        :type private_key: bytes or None\n+        :param public_key:  The public key data in PEM format\n+        :type public_key: bytes or None\n         :return: Sign Object\n         \"\"\"\n-        self.private = \"\"\n-        self.public = \"\"\n-        try:\n-            f = open(private_file, \"r\")\n-            self.private = f.read()\n-            f.close()\n-        except Exception as e:\n-            log.error(\"Error reading private key {0!s}: ({1!r})\".format(private_file, e))\n-            raise e\n-\n-        try:\n-            f = open(public_file, \"r\")\n-            self.public = f.read()\n-            f.close()\n-        except Exception as e:\n-            log.error(\"Error reading public key {0!s}: ({1!r})\".format(public_file, e))\n-            raise e\n+        self.private = None\n+        self.public = None\n+        backend = default_backend()\n+        if private_key:\n+            try:\n+                self.private = serialization.load_pem_private_key(private_key,\n+                                                                  password=None,\n+                                                                  backend=backend)\n+            except Exception as e:\n+                log.error(\"Error loading private key: ({0!r})\".format(e))\n+                log.debug(traceback.format_exc())\n+                raise e\n+\n+        if public_key:\n+            try:\n+                self.public = serialization.load_pem_public_key(public_key,\n+                                                                backend=backend)\n+            except Exception as e:\n+                log.error(\"Error loading public key: ({0!r})\".format(e))\n+                log.debug(traceback.format_exc())\n+                raise e\n \n     def sign(self, s):\n         \"\"\"\n@@ -660,45 +694,70 @@ def sign(self, s):\n \n         :param s: String to sign\n         :type s: str\n-        :return: The signature of the string\n-        :rtype: long\n+        :return: The hexlified and versioned signature of the string\n+        :rtype: str\n         \"\"\"\n-        if isinstance(s, text_type):\n-            s = s.encode('utf8')\n-        RSAkey = RSA.importKey(self.private)\n-        if SIGN_WITH_RSA:\n-            hashvalue = HashFunc.new(s).digest()\n-            signature = RSAkey.sign(hashvalue, 1)\n-        else:\n-            hashvalue = HashFunc.new(s)\n-            signature = pkcs1_15.new(RSAkey).sign(hashvalue)\n-        s_signature = str(signature[0])\n-        return s_signature\n-\n-    def verify(self, s, signature):\n+        if not self.private:\n+            log.info('Could not sign message {0!s}, no private key!'.format(s))\n+            # TODO: should we throw an exception in this case?\n+            return ''\n+\n+        signature = self.private.sign(\n+            to_bytes(s),\n+            asym_padding.PSS(\n+                mgf=asym_padding.MGF1(hashes.SHA256()),\n+                salt_length=asym_padding.PSS.MAX_LENGTH),\n+            hashes.SHA256())\n+        res = ':'.join([self.sig_ver, hexlify_and_unicode(signature)])\n+        return res\n+\n+    def verify(self, s, signature, verify_old_sigs=False):\n         \"\"\"\n         Check the signature of the string s\n \n         :param s: String to check\n-        :type s: str\n+        :type s: str or bytes\n         :param signature: the signature to compare\n-        :type signature: str\n+        :type signature: str or int\n+        :param verify_old_sigs: whether to check for old style signatures as well\n+        :type verify_old_sigs: bool\n+        :return: True if the signature is valid, false otherwise.\n+        :rtype: bool\n         \"\"\"\n-        if isinstance(s, text_type):\n-            s = s.encode('utf8')\n         r = False\n+        if not self.public:\n+            log.info('Could not verify signature for message {0!s}, '\n+                     'no public key!'.format(s))\n+            return r\n+\n+        sver = ''\n+        try:\n+            sver, signature = six.text_type(signature).split(':')\n+        except ValueError:\n+            # if the signature does not contain a colon we assume an old style signature.\n+            pass\n+\n         try:\n-            RSAkey = RSA.importKey(self.public)\n-            signature = long(signature)\n-            if SIGN_WITH_RSA:\n-                hashvalue = HashFunc.new(s).digest()\n-                r = RSAkey.verify(hashvalue, (signature,))\n+            if sver == self.sig_ver:\n+                self.public.verify(\n+                    binascii.unhexlify(signature),\n+                    to_bytes(s),\n+                    asym_padding.PSS(\n+                        mgf=asym_padding.MGF1(hashes.SHA256()),\n+                        salt_length=asym_padding.PSS.MAX_LENGTH),\n+                    hashes.SHA256())\n+                r = True\n             else:\n-                hashvalue = HashFunc.new(s)\n-                pkcs1_15.new(RSAkey).verify(hashvalue, signature)\n-        except Exception as _e:  # pragma: no cover\n+                if verify_old_sigs:\n+                    int_s = int(binascii.hexlify(sha256(to_bytes(s)).digest()), 16)\n+                    r = _slow_rsa_verify_raw(self.public, int(signature), int_s)\n+                else:\n+                    log.debug('Could not verify old style signature {0!s} '\n+                              'for data {1:s}'.format(signature, s))\n+        except Exception:\n             log.error(\"Failed to verify signature: {0!r}\".format(s))\n             log.debug(\"{0!s}\".format(traceback.format_exc()))\n+\n         return r\n \n \n@@ -720,7 +779,6 @@ def create_hsm_object(config):\n     package_name, class_name = hsm_module_name.rsplit(\".\", 1)\n     hsm_class = get_module_class(package_name, class_name, \"setup_module\")\n     log.info(\"initializing HSM class: {0!s}\".format(hsm_class))\n-    hsm_parameters = {}\n     if class_name == \"DefaultSecurityModule\":\n         hsm_parameters = {\"file\": config.get(\"PI_ENCFILE\")}\n     else:\ndiff --git a/privacyidea/lib/importotp.py b/privacyidea/lib/importotp.py\n--- a/privacyidea/lib/importotp.py\n+++ b/privacyidea/lib/importotp.py\n@@ -51,15 +51,17 @@\n import binascii\n import base64\n import cgi\n+from cryptography.hazmat.backends import default_backend\n+from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n+\n from privacyidea.lib.utils import (modhex_decode, modhex_encode,\n                                    hexlify_and_unicode, to_unicode, to_utf8)\n from privacyidea.lib.config import get_token_class\n from privacyidea.lib.log import log_with\n from privacyidea.lib.crypto import (aes_decrypt_b64, aes_encrypt_b64, geturandom)\n-from Crypto.Cipher import AES\n from bs4 import BeautifulSoup\n import traceback\n-from passlib.utils.pbkdf2 import pbkdf2\n+from passlib.crypto.digest import pbkdf2_hmac\n import gnupg\n \n import logging\n@@ -75,8 +77,10 @@ def _create_static_password(key_hex):\n     '''\n     msg_hex = \"000000000000ffffffffffffffff0f2e\"\n     msg_bin = binascii.unhexlify(msg_hex)\n-    aes = AES.new(binascii.unhexlify(key_hex), AES.MODE_ECB)\n-    password_bin = aes.encrypt(msg_bin)\n+    cipher = Cipher(algorithms.AES(binascii.unhexlify(key_hex)),\n+                    modes.ECB(), default_backend())\n+    encryptor = cipher.encryptor()\n+    password_bin = encryptor.update(msg_bin) + encryptor.finalize()\n     password = modhex_encode(password_bin)\n \n     return password\n@@ -130,7 +134,7 @@ def parseOATHcsv(csv):\n \n     csv_array = csv.split('\\n')\n \n-    m = re.match(\"^#\\s*version:\\s*(\\d+)\", csv_array[0])\n+    m = re.match(r\"^#\\s*version:\\s*(\\d+)\", csv_array[0])\n     if m:\n         version = m.group(1)\n         log.debug(\"the file is version {0}.\".format(version))\n@@ -426,8 +430,8 @@ def derive_key(xml, password):\n     salt = keymeth.find(\"salt\").text.strip()\n     keylength = keymeth.find(\"keylength\").text.strip()\n     rounds = keymeth.find(\"iterationcount\").text.strip()\n-    r = pbkdf2(to_utf8(password), base64.b64decode(salt), int(rounds),\n-               int(keylength))\n+    r = pbkdf2_hmac('sha1', to_utf8(password), base64.b64decode(salt),\n+                    rounds=int(rounds), keylen=int(keylength))\n     return binascii.hexlify(r)\n \n \ndiff --git a/privacyidea/lib/resolvers/SQLIdResolver.py b/privacyidea/lib/resolvers/SQLIdResolver.py\n--- a/privacyidea/lib/resolvers/SQLIdResolver.py\n+++ b/privacyidea/lib/resolvers/SQLIdResolver.py\n@@ -49,7 +49,8 @@\n from privacyidea.lib.utils import (is_true, censor_connect_string, to_utf8)\n from passlib.context import CryptContext\n from base64 import b64decode, b64encode\n-from passlib.utils.binary import h64\n+from passlib.utils import h64\n+\n from passlib.utils.compat import uascii_to_str, u\n from passlib.utils.compat import unicode as pl_unicode\n from passlib.utils import to_unicode\ndiff --git a/privacyidea/lib/security/aeshsm.py b/privacyidea/lib/security/aeshsm.py\n--- a/privacyidea/lib/security/aeshsm.py\n+++ b/privacyidea/lib/security/aeshsm.py\n@@ -207,20 +207,20 @@ def encrypt(self, data, iv, key_id=SecurityModule.TOKEN_KEY):\n \n         return int_list_to_bytestring(r)\n \n-    def decrypt(self, data, iv, key_id=SecurityModule.TOKEN_KEY):\n+    def decrypt(self, enc_data, iv, key_id=SecurityModule.TOKEN_KEY):\n         \"\"\"\n \n         :rtype bytes\n         \"\"\"\n-        if len(data) == 0:\n+        if len(enc_data) == 0:\n             return bytes(\"\")\n-        log.debug(\"Decrypting {} bytes with key {}\".format(len(data), key_id))\n+        log.debug(\"Decrypting {} bytes with key {}\".format(len(enc_data), key_id))\n         m = PyKCS11.Mechanism(PyKCS11.CKM_AES_CBC_PAD, iv)\n         retries = 0\n         while True:\n             try:\n                 k = self.key_handles[key_id]\n-                r = self.session.decrypt(k, bytes(data), m)\n+                r = self.session.decrypt(k, bytes(enc_data), m)\n                 break\n             except PyKCS11.PyKCS11Error as exx:\n                 log.warning(u\"Decryption failed: {0!s}\".format(exx))\n@@ -309,13 +309,13 @@ def create_keys(self):\n     p.setup_module({\"password\": \"12345678\"})\n \n     # random\n-    iv = p.random(16)\n+    tmp_iv = p.random(16)\n     plain = p.random(128)\n     log.info(\"random test successful\")\n \n     # generic encrypt / decrypt\n-    cipher = p.encrypt(plain, iv)\n+    cipher = p.encrypt(plain, tmp_iv)\n     assert (plain != cipher)\n-    text = p.decrypt(cipher, iv)\n+    text = p.decrypt(cipher, tmp_iv)\n     assert (text == plain)\n     log.info(\"generic encrypt/decrypt test successful\")\ndiff --git a/privacyidea/lib/security/default.py b/privacyidea/lib/security/default.py\n--- a/privacyidea/lib/security/default.py\n+++ b/privacyidea/lib/security/default.py\n@@ -41,11 +41,11 @@\n import logging\n import binascii\n import os\n-import six\n \n-from Crypto.Cipher import AES\n from hashlib import sha256\n-from privacyidea.lib.crypto import geturandom, zerome\n+\n+from privacyidea.lib.crypto import (geturandom, zerome, aes_cbc_encrypt,\n+                                    aes_cbc_decrypt)\n from privacyidea.lib.error import HSMException\n from privacyidea.lib.utils import (is_true, to_unicode, to_bytes,\n                                    hexlify_and_unicode)\n@@ -61,11 +61,11 @@ def create_key_from_password(password):\n     This is used to encrypt and decrypt the enckey file.\n \n     :param password:\n-    :type password: bytes\n+    :type password: str or bytes\n     :return: the generated key\n     :rtype: bytes\n     \"\"\"\n-    key = sha256(password).digest()[0:32]\n+    key = sha256(to_bytes(password)).digest()[0:32]\n     return key\n \n \n@@ -101,13 +101,13 @@ def random(self, length):\n                   \"the method : %s \" % (fname,))\n         raise NotImplementedError(\"Should have been implemented {0!s}\".format(fname))\n \n-    def encrypt(self, value, iv=None):\n+    def encrypt(self, data, iv, key_id=TOKEN_KEY):\n         fname = 'encrypt'\n         log.error(\"This is the base class. You should implement \"\n                   \"the method : %s \" % (fname,))\n         raise NotImplementedError(\"Should have been implemented {0!s}\".format(fname))\n \n-    def decrypt(self, value, iv=None):\n+    def decrypt(self, enc_data, iv, key_id=TOKEN_KEY):\n         fname = 'decrypt'\n         log.error(\"This is the base class. You should implement \"\n                   \"the method : %s \" % (fname,))\n@@ -376,7 +376,7 @@ def random(length=32):\n         \"\"\"\n         return os.urandom(length)\n \n-    def encrypt(self, data, iv, slot_id=SecurityModule.TOKEN_KEY):\n+    def encrypt(self, data, iv, key_id=SecurityModule.TOKEN_KEY):\n         \"\"\"\n         security module methods: encrypt\n \n@@ -386,9 +386,9 @@ def encrypt(self, data, iv, slot_id=SecurityModule.TOKEN_KEY):\n         :param iv: initialisation vector\n         :type iv: bytes\n \n-        :param slot_id: slot of the key array. The key file contains 96\n+        :param key_id: slot of the key array. The key file contains 96\n             bytes, which are made up of 3 32byte keys.\n-        :type slot_id: int\n+        :type key_id: int\n \n         :return: encrypted data\n         :rtype:  bytes\n@@ -396,15 +396,15 @@ def encrypt(self, data, iv, slot_id=SecurityModule.TOKEN_KEY):\n         if self.is_ready is False:\n             raise HSMException('setup of security module incomplete')\n \n-        key = self._get_secret(slot_id)\n-        # convert input to ascii, so we can securely append bin data\n+        key = self._get_secret(key_id)\n+\n+        # convert input to ascii, so we can securely append bin data for padding\n         input_data = binascii.b2a_hex(data)\n         input_data += b\"\\x01\\x02\"\n         padding = (16 - len(input_data) % 16) % 16\n         input_data += padding * b\"\\0\"\n-        aes = AES.new(key, AES.MODE_CBC, iv)\n \n-        res = aes.encrypt(input_data)\n+        res = aes_cbc_encrypt(key, iv, input_data)\n \n         if self.crypted is False:\n             zerome(key)\n@@ -412,81 +412,71 @@ def encrypt(self, data, iv, slot_id=SecurityModule.TOKEN_KEY):\n         return res\n \n     @staticmethod\n-    def password_encrypt(text, password):\n+    def password_encrypt(data, password):\n         \"\"\"\n         Encrypt the given text with the password.\n         A key is derived from the password and used to encrypt the text in\n         AES MODE_CBC. The IV is returned together with the cipher text.\n         <IV:Cipher>\n \n-        :param text: The text to encrypt\n-        :type text: str or bytes\n+        :param data: The text to encrypt\n+        :type data: str or bytes\n         :param password: The password to derive a key from\n         :type password: str or bytes\n         :return: IV and cipher text\n         :rtype: str\n         \"\"\"\n-        # TODO rewrite this when updating the crypto library (maybe externalise the AES)\n-        # TODO replace with to_bytes() when available in utils.py\n-        if isinstance(password, six.text_type):\n-            password = password.encode('utf8')\n-        if isinstance(text, six.text_type):\n-            text = text.encode('utf8')\n         bkey = create_key_from_password(password)\n-        # convert input to ascii, so we can securely append bin data\n-        input_data = binascii.hexlify(text)\n+        # convert input to ascii, so we can securely append bin data for padding\n+        input_data = binascii.hexlify(to_bytes(data))\n         input_data += b\"\\x01\\x02\"\n         padding = (16 - len(input_data) % 16) % 16\n         input_data += padding * b\"\\0\"\n         iv = geturandom(16)\n-        aes = AES.new(bkey, AES.MODE_CBC, iv)\n-        cipher = aes.encrypt(input_data)\n+        cipher = aes_cbc_encrypt(bkey, iv, input_data)\n         iv_hex = hexlify_and_unicode(iv)\n         cipher_hex = hexlify_and_unicode(cipher)\n         return \"{0!s}:{1!s}\".format(iv_hex, cipher_hex)\n \n     @staticmethod\n-    def password_decrypt(data, password):\n+    def password_decrypt(enc_data, password):\n         \"\"\"\n         Decrypt the given data with the password.\n         A key is derived from the password. The data is hexlified data, the IV\n         is the first part, separated with a \":\".\n \n-        :param data: The hexlified data\n-        :type data: str\n+        :param enc_data: The hexlified data\n+        :type enc_data: str\n         :param password: The password, that is used to decrypt the data\n-        :type password: str\n+        :type password: str or bytes\n         :return: The clear test\n         :rtype: bytes\n         \"\"\"\n-        # TODO replace with to_bytes() when available in utils.py\n-        if isinstance(password, six.text_type):\n-            password = password.encode('utf8')\n         bkey = create_key_from_password(password)\n         # split the input data\n-        iv_hex, cipher_hex = data.strip().split(\":\")\n+        iv_hex, cipher_hex = enc_data.strip().split(\":\")\n         iv_bin = binascii.unhexlify(iv_hex)\n         cipher_bin = binascii.unhexlify(cipher_hex)\n-        aes = AES.new(bkey, AES.MODE_CBC, iv_bin)\n-        output = aes.decrypt(cipher_bin)\n+        output = aes_cbc_decrypt(bkey, iv_bin, cipher_bin)\n+        # remove padding\n         eof = output.rfind(b\"\\x01\\x02\")\n         if eof >= 0:\n             output = output[:eof]\n         cleartext = binascii.unhexlify(output)\n         return cleartext\n \n-    def decrypt(self, input_data, iv, slot_id=SecurityModule.TOKEN_KEY):\n+    def decrypt(self, enc_data, iv, key_id=SecurityModule.TOKEN_KEY):\n         \"\"\"\n         Decrypt the given data with the key from the key slot\n \n-        :param input_data: the to be decrypted data\n-        :type input_data: bytes\n+        :param enc_data: the to be decrypted data\n+        :type enc_data: bytes\n \n         :param iv: initialisation vector (salt)\n         :type iv: bytes\n \n-        :param slot_id: slot of the key array\n-        :type slot_id: int\n+        :param key_id: slot of the key array\n+        :type key_id: int\n \n         :return: decrypted data\n         :rtype: bytes\n@@ -494,9 +484,9 @@ def decrypt(self, input_data, iv, slot_id=SecurityModule.TOKEN_KEY):\n         if self.is_ready is False:\n             raise HSMException('setup of security module incomplete')\n \n-        key = self._get_secret(slot_id)\n-        aes = AES.new(key, AES.MODE_CBC, iv)\n-        output = aes.decrypt(input_data)\n+        key = self._get_secret(key_id)\n+        output = aes_cbc_decrypt(key, iv, enc_data)\n+        # remove padding\n         eof = output.rfind(b\"\\x01\\x02\")\n         if eof >= 0:\n             output = output[:eof]\ndiff --git a/privacyidea/lib/security/pkcs11.py b/privacyidea/lib/security/pkcs11.py\ndeleted file mode 100644\n--- a/privacyidea/lib/security/pkcs11.py\n+++ /dev/null\n@@ -1,188 +0,0 @@\n-# -*- coding: utf-8 -*-\n-#\n-#  2016-04-15 Cornelius K\u00f6lbel <cornelius@privacyidea.org>\n-#             PKCS11 Security Module\n-#\n-# This code is free software; you can redistribute it and/or\n-# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE\n-# License as published by the Free Software Foundation; either\n-# version 3 of the License, or any later version.\n-#\n-# This code is distributed in the hope that it will be useful,\n-# but WITHOUT ANY WARRANTY; without even the implied warranty of\n-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n-# GNU AFFERO GENERAL PUBLIC LICENSE for more details.\n-#\n-# You should have received a copy of the GNU Affero General Public\n-# License along with this program.  If not, see <http://www.gnu.org/licenses/>.\n-#\n-#\n-__doc__ = \"\"\"\n-This is a PKCS11 Security module that encrypts and decrypts the data on a Smartcard/HSM that is connected via PKCS11.\n-\"\"\"\n-import logging\n-from privacyidea.lib.security.default import SecurityModule\n-from privacyidea.lib.security.password import PASSWORD\n-from privacyidea.lib.error import HSMException\n-from Crypto.PublicKey import RSA\n-from Crypto.Cipher import PKCS1_v1_5\n-\n-log = logging.getLogger(__name__)\n-\n-try:\n-    import PyKCS11\n-except ImportError:\n-    log.info(\"The python module PyKCS11 is not available. So we can not use the PKCS11 security module.\")\n-\n-\n-# FIXME: At the moment this only works with one (1) wsgi process!\n-\n-\n-def int_list_to_bytestring(int_list):  # pragma: no cover\n-    r = \"\"\n-    for i in int_list:\n-        r += chr(i)\n-    return r\n-\n-\n-class PKCS11SecurityModule(SecurityModule):  # pragma: no cover\n-\n-    def __init__(self, config=None):\n-        \"\"\"\n-        Initialize the PKCS11 Security Module.\n-        The configuration needs to contain the pkcs11 module and the ID of the key.\n-\n-          {\"module\": \"/usr/lib/x86_64-linux-gnu/opensc-pkcs11.so\",\n-           \"key_id\": 10}\n-\n-        The HSM is not directly ready, since the HSM is protected by a password.\n-        The function setup_module({\"password\": \"HSM User password\"}) needs to be called.\n-\n-        :param config: contains the HSM configuration\n-        :type config: dict\n-\n-        :return: The Security Module object\n-        \"\"\"\n-        config = config or {}\n-        self.name = \"PKCS11\"\n-        self.config = config\n-        self.is_ready = False\n-\n-        if \"module\" not in config:\n-            log.error(\"No PKCS11 module defined!\")\n-            raise HSMException(\"No PKCS11 module defined.\")\n-        self.key_id = config.get(\"key_id\", 16)\n-        self.pkcs11 = PyKCS11.PyKCS11Lib()\n-        self.pkcs11.load(config.get(\"module\"))\n-        self.session = None\n-        self.key_handle = None\n-\n-    def setup_module(self, params):\n-        \"\"\"\n-        callback, which is called during the runtime to initialze the\n-        security module.\n-\n-        Here the password for the PKCS11 HSM can be provided\n-\n-           {\"password\": \"top secreT\"}\n-\n-        :param params: The password for the HSM\n-        :type  params: dict\n-\n-        :return: -\n-        \"\"\"\n-        if \"password\" in params:\n-            PASSWORD = str(params.get(\"password\"))\n-        else:\n-            raise HSMException(\"missing password\")\n-\n-        slotlist = self.pkcs11.getSlotList()\n-        if not len(slotlist):\n-            raise HSMException(\"No HSM connected\")\n-        slot_id = slotlist[0]\n-        # If the HSM is not connected at this point, it will fail\n-        self.session = self.pkcs11.openSession(slot=slot_id)\n-\n-        slotinfo = self.pkcs11.getSlotInfo(1)\n-        log.info(\"Setting up {}\".format(slotinfo.fields.get(\"slotDescription\")))\n-        # get the public key\n-        objs = self.session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY),\n-                                         (PyKCS11.CKA_ID, (self.key_id,))])\n-        self.key_handle = objs[0]\n-        pubkey_list = self.session.getAttributeValue(self.key_handle,  [PyKCS11.CKA_VALUE], allAsBinary=True)\n-        pubkey_bin = int_list_to_bytestring(pubkey_list[0])\n-        self.rsa_pubkey = RSA.importKey(pubkey_bin)\n-\n-        # We do a login and logout to see if\n-        self.session.login(PASSWORD)\n-        self.session.logout()\n-        self.is_ready = True\n-        log.info(\"Successfully setup the security module.\")\n-\n-        return self.is_ready\n-\n-    def random(self, length):\n-        \"\"\"\n-        Return a random bytestring\n-        :param length: length of the random bytestring\n-        :return:\n-        \"\"\"\n-        r = ''\n-        r_integers = self.session.generateRandom(length)\n-        # convert the array of the random integers to a string\n-        return int_list_to_bytestring(r_integers)\n-\n-    def encrypt(self, value, iv=None):\n-        cipher = PKCS1_v1_5.new(self.rsa_pubkey)\n-        encrypted = cipher.encrypt(value)\n-        return encrypted\n-\n-    def decrypt(self, value, iv=None):\n-        if not PASSWORD:\n-            log.error(\"empty PASSWORD. Your security module is probably not \"\n-                      \"initialized.\")\n-        self.session.login(PASSWORD)\n-        objs = self.session.findObjects([(PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY),\n-                                         (PyKCS11.CKA_ID, (self.key_id,))])\n-\n-        key_handle_private = objs[0]\n-        text = self.session.decrypt(key_handle_private, value)\n-        text = int_list_to_bytestring(text)\n-        self.session.logout()\n-        return text\n-\n-\n-if __name__ == \"__main__\":  # pragma: no cover\n-\n-    module = \"/usr/local/lib/opensc-pkcs11.so\"\n-    #module = \"/usr/lib/x86_64-linux-gnu/opensc-pkcs11.so\"\n-\n-    p = PKCS11SecurityModule({\"module\": module,\n-                              \"key_id\": 17})\n-    p.setup_module({\"password\": \"123456\"})\n-\n-    cleartext = \"Hello there!\"\n-    cipher = p.encrypt(cleartext)\n-    text = p.decrypt(cipher)\n-    print(text)\n-    assert(text == cleartext)\n-\n-    cleartext = \"Hello, this is a really long text and so and and so on...\"\n-    cipher = p.encrypt(cleartext)\n-    text = p.decrypt(cipher)\n-    print(text)\n-    assert (text == cleartext)\n-\n-    # password\n-    password = \"topSekr3t\"\n-    crypted = p.encrypt_password(password)\n-    text = p.decrypt_password(crypted)\n-    print(text)\n-    assert(text == password)\n-\n-    # pin\n-    password = \"topSekr3t\"\n-    crypted = p.encrypt_pin(password)\n-    text = p.decrypt_pin(crypted)\n-    print(text)\n-    assert (text == password)\ndiff --git a/privacyidea/lib/subscriptions.py b/privacyidea/lib/subscriptions.py\n--- a/privacyidea/lib/subscriptions.py\n+++ b/privacyidea/lib/subscriptions.py\n@@ -32,11 +32,10 @@\n from ..models import Subscription\n from privacyidea.lib.error import SubscriptionError\n from privacyidea.lib.token import get_tokens\n+from privacyidea.lib.crypto import Sign\n import functools\n from privacyidea.lib.framework import get_app_config_value\n import os\n-from Crypto.Hash import SHA256\n-from Crypto.PublicKey import RSA\n import traceback\n from sqlalchemy import func\n from six import PY2, string_types\n@@ -280,26 +279,24 @@ def check_signature(subscription):\n     dirname = os.path.dirname(enckey)\n     # In dirname we are searching for <vendor>.pem\n     filename = u\"{0!s}/{1!s}.pem\".format(dirname, vendor)\n-    with open(filename, \"r\") as file_handle:\n-        public = file_handle.read()\n \n-    r = False\n     try:\n         # remove the minutes 00:00:00\n         subscription[\"date_from\"] = subscription.get(\"date_from\").strftime(SUBSCRIPTION_DATE_FORMAT)\n         subscription[\"date_till\"] = subscription.get(\"date_till\").strftime(SUBSCRIPTION_DATE_FORMAT)\n         sign_string = SIGN_FORMAT.format(**subscription)\n-        RSAkey = RSA.importKey(public)\n-        hashvalue = SHA256.new(sign_string.encode(\"utf-8\")).digest()\n-        signature = long(subscription.get(\"signature\") or \"100\")\n-        r = RSAkey.verify(hashvalue, (signature,))\n+        with open(filename, 'rb') as key_file:\n+            sign_obj = Sign(private_key=None, public_key=key_file.read())\n+\n+        signature = subscription.get('signature', '100')\n+        r = sign_obj.verify(sign_string, signature, verify_old_sigs=True)\n         subscription[\"date_from\"] = datetime.datetime.strptime(\n             subscription.get(\"date_from\"),\n             SUBSCRIPTION_DATE_FORMAT)\n         subscription[\"date_till\"] = datetime.datetime.strptime(\n             subscription.get(\"date_till\"),\n             SUBSCRIPTION_DATE_FORMAT)\n-    except Exception as exx:\n+    except Exception as _e:\n         log.debug(traceback.format_exc())\n         raise SubscriptionError(\"Verifying the signature of your subscription \"\n                                 \"failed.\",\ndiff --git a/privacyidea/lib/tokens/yubikeytoken.py b/privacyidea/lib/tokens/yubikeytoken.py\n--- a/privacyidea/lib/tokens/yubikeytoken.py\n+++ b/privacyidea/lib/tokens/yubikeytoken.py\n@@ -262,7 +262,7 @@ def check_otp(self, anOtpVal, counter=None, window=None, options=None):\n             # The OTP value is no yubikey aes otp value and can not be decoded\n             return -4\n \n-        msg_bin = secret.aes_decrypt(otp_bin)\n+        msg_bin = secret.aes_ecb_decrypt(otp_bin)\n         msg_hex = hexlify_and_unicode(msg_bin)\n \n         # The checksum is a CRC-16 (16-bit ISO 13239 1st complement) that\n", "test_patch": "diff --git a/tests/base.py b/tests/base.py\n--- a/tests/base.py\n+++ b/tests/base.py\n@@ -1,3 +1,5 @@\n+# -*- coding: utf-8 -*-\n+\n import unittest\n import json\n import mock\ndiff --git a/tests/test_api_lib_policy.py b/tests/test_api_lib_policy.py\n--- a/tests/test_api_lib_policy.py\n+++ b/tests/test_api_lib_policy.py\n@@ -1887,13 +1887,31 @@ def test_07_sign_response(self):\n                \"id\": 1}\n         resp = jsonify(res)\n         from privacyidea.lib.crypto import Sign\n-        g.sign_object = Sign(\"tests/testdata/private.pem\",\n-                             \"tests/testdata/public.pem\")\n+        sign_object = Sign(private_key=None,\n+                           public_key=open(\"tests/testdata/public.pem\", 'rb').read())\n \n+        # check that we don't sign if 'PI_NO_RESPONSE_SIGN' is set\n+        current_app.config['PI_NO_RESPONSE_SIGN'] = True\n+        new_response = sign_response(req, resp)\n+        self.assertEqual(new_response, resp, new_response)\n+        current_app.config['PI_NO_RESPONSE_SIGN'] = False\n+\n+        # set a broken signing key path. The function should return without\n+        # changing the response\n+        orig_key_path = current_app.config['PI_AUDIT_KEY_PRIVATE']\n+        current_app.config['PI_AUDIT_KEY_PRIVATE'] = '/path/does/not/exist'\n+        new_response = sign_response(req, resp)\n+        self.assertEqual(new_response, resp, new_response)\n+        current_app.config['PI_AUDIT_KEY_PRIVATE'] = orig_key_path\n+\n+        # signing of API responses is the default\n         new_response = sign_response(req, resp)\n         jresult = json.loads(new_response.data)\n         self.assertEqual(jresult.get(\"nonce\"), \"12345678\")\n-        self.assertEqual(jresult.get(\"signature\"), \"11355158914966210201410734667484298031497086510917116878993822963793177737963323849914979806826759273431791474575057946263651613906587629736481370983420295626001055840803201448376203681672140726404056349423937599480275853513810616624349811159346536182220806878464577429106150903913526744093300868582898892977164229848617413618851794501457802670374543399415905458325601994002527427083792164898293507308423780001137468154518279116138010266341425663850327379848131113626641510715557748879427991785684858504631545256553961505159377600982900016536629720752767147086708626971940835730555782551222922985302674756190839458609\")\n+        # After switching to the PSS signature scheme, each signature will be\n+        # different. So we have to verify the signature through the sign object\n+        sig = jresult.pop('signature')\n+        self.assertTrue(sign_object.verify(json.dumps(jresult, sort_keys=True), sig))\n \n     def test_08_get_webui_settings(self):\n         # Test that a machine definition will return offline hashes\ndiff --git a/tests/test_lib_audit.py b/tests/test_lib_audit.py\n--- a/tests/test_lib_audit.py\n+++ b/tests/test_lib_audit.py\n@@ -11,12 +11,11 @@\n from privacyidea.lib.auditmodules.sqlaudit import column_length\n import datetime\n import time\n-from privacyidea.models import db\n-from privacyidea.app import create_app\n \n \n PUBLIC = \"tests/testdata/public.pem\"\n PRIVATE = \"tests/testdata/private.pem\"\n+AUDIT_DB = 'sqlite:///tests/testdata//audit.sqlite'\n \n \n class AuditTestCase(MyTestCase):\n@@ -210,7 +209,13 @@ def test_06_truncate_data(self):\n                          u\"Mannheim,Augsburg,Wiesbaden,Gelsenki+,M\u00f6ncheng+,Braunsch+,Kiel,Chemnitz,Aachen,Magdeburg\",\n                          self.Audit.audit_data.get(\"policies\"))\n \n-    def test_07_sign_non_ascii_entry(self):\n+    def test_07_sign_and_verify(self):\n+        # Test with broken key file paths\n+        self.app.config[\"PI_AUDIT_KEY_PUBLIC\"] = PUBLIC\n+        self.app.config[\"PI_AUDIT_KEY_PRIVATE\"] = '/path/not/valid'\n+        with self.assertRaises(Exception):\n+            getAudit(self.app.config)\n+        self.app.config[\"PI_AUDIT_KEY_PRIVATE\"] = PRIVATE\n         # Log a username as unicode with a non-ascii character\n         self.Audit.log({\"serial\": \"1234\",\n                         \"action\": \"token/assign\",\n@@ -221,6 +226,18 @@ def test_07_sign_non_ascii_entry(self):\n         self.assertEqual(audit_log.total, 1)\n         self.assertEqual(audit_log.auditdata[0].get(\"user\"), u\"k\u00f6lbel\")\n         self.assertEqual(audit_log.auditdata[0].get(\"sig_check\"), \"OK\")\n+        # check the raw data from DB\n+        db_entries = self.Audit.search_query({'user': u'k\u00f6lbel'})\n+        db_entry = next(db_entries)\n+        self.assertTrue(db_entry.signature.startswith('rsa_sha256_pss'), db_entry)\n+        # modify the table data\n+        db_entry.realm = 'realm1'\n+        self.Audit.session.merge(db_entry)\n+        self.Audit.session.commit()\n+        # and check if we get a failed signature check\n+        audit_log = self.Audit.search({\"user\": u\"k\u00f6lbel\"})\n+        self.assertEquals(audit_log.total, 1)\n+        self.assertEquals(audit_log.auditdata[0].get(\"sig_check\"), \"FAIL\")\n \n     def test_08_policies(self):\n         self.Audit.log({\"action\": \"validate/check\"})\n@@ -235,4 +252,28 @@ def test_08_policies(self):\n         self.Audit.finalize_log()\n         audit_log = self.Audit.search({\"policies\": \"*rule4*\"})\n         self.assertEqual(audit_log.total, 1)\n-        self.assertEqual(audit_log.auditdata[0].get(\"policies\"), \"rule4,rule5\")\n\\ No newline at end of file\n+        self.assertEqual(audit_log.auditdata[0].get(\"policies\"), \"rule4,rule5\")\n+\n+    def test_09_check_external_audit_db(self):\n+        self.app.config[\"PI_AUDIT_SQL_URI\"] = AUDIT_DB\n+        audit = getAudit(self.app.config)\n+        total = audit.get_count({})\n+        self.assertEquals(total, 5)\n+        # check that we have old style signatures in the DB\n+        db_entries = audit.search_query({\"user\": \"testuser\"})\n+        db_entry = next(db_entries)\n+        self.assertTrue(db_entry.signature.startswith('213842441384'), db_entry)\n+        # by default, PI_CHECK_OLD_SIGNATURES is false and thus the signature check fails\n+        audit_log = audit.search({\"user\": \"testuser\"})\n+        self.assertEquals(audit_log.total, 1)\n+        self.assertEquals(audit_log.auditdata[0].get(\"sig_check\"), \"FAIL\")\n+        # but they validate correctly when PI_CHECK_OLD_SIGNATURES is true\n+        self.app.config['PI_CHECK_OLD_SIGNATURES'] = True\n+        audit_log = audit.search({\"user\": \"testuser\"})\n+        self.assertEquals(audit_log.total, 1)\n+        self.assertEquals(audit_log.auditdata[0].get(\"sig_check\"), \"OK\")\n+        # except for entry number 4 where the 'realm' was added afterwards\n+        audit_log = audit.search({\"realm\": \"realm1\"})\n+        self.assertEquals(audit_log.total, 1)\n+        self.assertEquals(audit_log.auditdata[0].get(\"sig_check\"), \"FAIL\")\n+        # TODO: add new audit entry and check for new style signature\ndiff --git a/tests/test_lib_crypto.py b/tests/test_lib_crypto.py\n--- a/tests/test_lib_crypto.py\n+++ b/tests/test_lib_crypto.py\n@@ -14,7 +14,7 @@\n                                     geturandom, get_alphanum_str, hash_with_pepper,\n                                     verify_with_pepper, aes_encrypt_b64, aes_decrypt_b64,\n                                     get_hsm, init_hsm, set_hsm_password, hash,\n-                                    encrypt, decrypt, generate_keypair)\n+                                    encrypt, decrypt, Sign, generate_keypair)\n from privacyidea.lib.utils import to_bytes, to_unicode\n from privacyidea.lib.security.default import (SecurityModule,\n                                               DefaultSecurityModule)\n@@ -36,8 +36,8 @@ def test_00_security_module_base_class(self):\n \n         self.assertRaises(NotImplementedError, hsm.setup_module, {})\n         self.assertRaises(NotImplementedError, hsm.random, 20)\n-        self.assertRaises(NotImplementedError, hsm.encrypt, \"20\")\n-        self.assertRaises(NotImplementedError, hsm.decrypt, \"20\")\n+        self.assertRaises(NotImplementedError, hsm.encrypt, \"20\", 'abcd')\n+        self.assertRaises(NotImplementedError, hsm.decrypt, \"20\", 'abcd')\n \n     def test_01_default_security_module(self):\n         config = current_app.config\n@@ -45,6 +45,7 @@ def test_01_default_security_module(self):\n         hsm.setup_module({\"file\": config.get(\"PI_ENCFILE\")})\n         self.assertTrue(hsm is not None, hsm)\n         self.assertTrue(hsm.secFile is not None, hsm.secFile)\n+        self.assertTrue(hsm.is_ready)\n \n     def test_01_no_file_in_config(self):\n         self.assertRaises(Exception, DefaultSecurityModule, {})\n@@ -55,6 +56,7 @@ def test_04_random(self):\n                                      \"crypted\": True})\n         r = hsm.random(20)\n         self.assertTrue(len(r) == 20, r)\n+        self.assertFalse(hsm.is_ready)\n \n     def test_05_encrypt_decrypt(self):\n         config = current_app.config\n@@ -143,6 +145,14 @@ def test_00_encrypt_decrypt_pin(self):\n         pin = decryptPin(r)\n         self.assertTrue(pin == \"test\", (r, pin))\n \n+        # decrypt some pins generated with 2.23\n+        pin1 = 'd2c920ad10513c8ea322b522751185a3:54f068cffb43ada1edd024087da614ec'\n+        self.assertEqual(decryptPin(pin1), 'test')\n+        pin2 = '223f414872122ad112eb9f17b05da0b8:123079d997cd18601414830ab7c97678'\n+        self.assertEqual(decryptPin(pin2), 'test')\n+        pin3 = '4af7590600286becde70b99b10493104:09e4133652c609f9697e1923cde72904'\n+        self.assertEqual(decryptPin(pin3), '1234')\n+\n     def test_01_encrypt_decrypt_pass(self):\n         r = encryptPassword(u\"passw\u00f6rd\".encode('utf8'))\n         # encryptPassword returns unicode\n@@ -155,6 +165,16 @@ def test_01_encrypt_decrypt_pass(self):\n         pin = decryptPassword(r)\n         self.assertEqual(pin, u\"passw\u00f6rd\")\n \n+        # decrypt some passwords generated with 2.23\n+        pw1 = '3d1bf9db4c75469b4bb0bc7c70133181:2c27ac3839ed2213b8399d0471b17136'\n+        self.assertEqual(decryptPassword(pw1), 'test123')\n+        pw2 = '3a1be65a234f723fe5c6969b818582e1:08e51d1c65aa74c4988d094c40cb972c'\n+        self.assertEqual(decryptPassword(pw2), 'test123')\n+        pw3 = '7a4d5e2f26978394e33715bc3e8188a3:90b2782112ad7bbc5b48bd10e5c7c096cfe4ef7d9d11272595dc5b6c7f21d98a'\n+        self.assertEqual(decryptPassword(pw3, ), u'passw\u00f6rd')\n+\n+        # TODO: add checks for broken paddings/encrypted values and malformed enc_data\n+\n         not_valid_password = b\"\\x01\\x02\\x03\\x04\\xff\"\n         r = encryptPassword(not_valid_password)\n         # A non valid password will raise an exception during decryption\n@@ -181,6 +201,18 @@ def test_02_encrypt_decrypt_eas_base64(self):\n         d = aes_decrypt_b64(key, s)\n         self.assertEqual(otp_seed, d)\n \n+        # check some data generated with 2.23\n+        hex_key = 'f84c2ddb09dee2a88194d5ac2156a8e4'\n+        data = b'secret data'\n+        enc_data = 'WNfUSNBNZF5kaPfujW8ueUi5Afas47pQ/3FHc3VymWM='\n+        d = aes_decrypt_b64(binascii.unhexlify(hex_key), enc_data)\n+        self.assertEqual(data, d)\n+        enc_data = 'RDDvdAJhCnw/tlYscTxv+6idHAQnQFY5VpUK8SFflYQ='\n+        d = aes_decrypt_b64(binascii.unhexlify(hex_key), enc_data)\n+        self.assertEqual(data, d)\n+\n+        # TODO: add checks for broken paddings/encrypted values and malformed enc_data\n+\n     def test_03_hash(self):\n         import os\n         val = os.urandom(16)\n@@ -204,6 +236,23 @@ def test_04_encrypt_decrypt_data(self):\n         d = decrypt(binascii.unhexlify(c), iv)\n         self.assertEqual(s, d.decode('utf8'))\n \n+        # TODO: add checks for broken paddings/encrypted values and malformed enc_data\n+\n+        # check some data generated with 2.23\n+        s = u'passw\u00f6rd'.encode('utf8')\n+        iv_hex = 'cd5245a2875007d30cc049c2e7eca0c5'\n+        enc_data_hex = '7ea55168952b33131077f4249cf9e52b5f2b572214ace13194c436451fe3788c'\n+        self.assertEqual(s, decrypt(binascii.unhexlify(enc_data_hex),\n+                                     binascii.unhexlify(iv_hex)))\n+        enc_data_hex = 'fb79a04d69e832aec8ffb4bbfe031b3bd28a2840150212d8c819e' \\\n+                       '362b1711cc389aed70eaf27af53131ea446095da80e88c4caf791' \\\n+                       'c709e9581ff0a5f1e19228dc4c3c278d148951acaab9a164c1770' \\\n+                       '7166134f4ba6111055c65d72771c6f59c2dc150a53753f2cf4c47' \\\n+                       'ec02901022f02a054d1fc7678fd4f66b47967a5d222a'\n+        self.assertEqual(b'\\x01\\x02' * 30,\n+                          decrypt(binascii.unhexlify(enc_data_hex),\n+                                  binascii.unhexlify(iv_hex)))\n+\n     def test_05_encode_decode(self):\n         b_str = b'Hello World'\n         self.assertEqual(to_unicode(b_str), b_str.decode('utf8'))\n@@ -516,3 +565,76 @@ def test_01_set_password(self):\n             self.assertTrue(ready)\n             self.assertIs(hsm, init_hsm())\n             self.assertIs(get_hsm(), hsm)\n+\n+\n+class SignObjectTestCase(MyTestCase):\n+    \"\"\" tests for the SignObject which signs/verifies using RSA \"\"\"\n+\n+    def test_00_create_sign_object(self):\n+        # test with invalid key data\n+        with self.assertRaises(Exception):\n+            Sign(b'This is not a private key', b'This is not a public key')\n+        with self.assertRaises(Exception):\n+            priv_key = open(current_app.config.get(\"PI_AUDIT_KEY_PRIVATE\"), 'rb').read()\n+            Sign(private_key=priv_key,\n+                 public_key=b'Still not a public key')\n+        # this should work\n+        priv_key = open(current_app.config.get(\"PI_AUDIT_KEY_PRIVATE\"), 'rb').read()\n+        pub_key = open(current_app.config.get(\"PI_AUDIT_KEY_PUBLIC\"), 'rb').read()\n+        so = Sign(priv_key, pub_key)\n+        self.assertEqual(so.sig_ver, 'rsa_sha256_pss')\n+\n+        # test missing keys\n+        so = Sign(public_key=pub_key)\n+        res = so.sign('testdata')\n+        self.assertEqual(res, '')\n+        so = Sign(private_key=priv_key)\n+        res = so.verify('testdata', 'testsig')\n+        self.assertFalse(res)\n+\n+    def test_01_sign_and_verify_data(self):\n+        priv_key = open(current_app.config.get(\"PI_AUDIT_KEY_PRIVATE\"), 'rb').read()\n+        pub_key = open(current_app.config.get(\"PI_AUDIT_KEY_PUBLIC\"), 'rb').read()\n+        so = Sign(priv_key, pub_key)\n+        data = 'short text'\n+        sig = so.sign(data)\n+        self.assertTrue(sig.startswith(so.sig_ver), sig)\n+        self.assertTrue(so.verify(data, sig))\n+\n+        data = b'A slightly longer text, this time in binary format.'\n+        sig = so.sign(data)\n+        self.assertTrue(so.verify(data, sig))\n+\n+        # test with text larger than RSA key size\n+        data = b'\\x01\\x02' * 5000\n+        sig = so.sign(data)\n+        self.assertTrue(so.verify(data, sig))\n+\n+        # now test a broken signature\n+        data = 'short text'\n+        sig = so.sign(data)\n+        sig_broken = sig[:-1] + '{:x}'.format((int(sig[-1], 16) + 1) % 16)\n+        self.assertFalse(so.verify(data, sig_broken))\n+\n+        # test with non hex string\n+        sig_broken = sig[:-1] + 'x'\n+        self.assertFalse(so.verify(data, sig_broken))\n+\n+        # now try to verify old signatures\n+        # first without enabling old signatures in config\n+        short_text_sig = 15197717811878792093921885389298262311612396877333963031070812155820116863657342817645537537961773450510020137791036591085713379948816070430789598146539509027948592633362217308056639775153575635684961642110792013775709164803544619582232081442445758263838942315386909453927493644845757192298617925455779136340217255670113943560463286896994555184188496806420559078552626485909484729552861477888246423469461421103010299470836507229490718177625822972845024556897040292571751452383573549412451282884349017186147757238775308192484937929135306435242403555592741059466194258607967889051881221759976135386624406095324595765010\n+        data = 'short text'\n+        self.assertFalse(so.verify(data, short_text_sig))\n+\n+        # now we enable the checking of old signatures\n+        short_text_sig = 15197717811878792093921885389298262311612396877333963031070812155820116863657342817645537537961773450510020137791036591085713379948816070430789598146539509027948592633362217308056639775153575635684961642110792013775709164803544619582232081442445758263838942315386909453927493644845757192298617925455779136340217255670113943560463286896994555184188496806420559078552626485909484729552861477888246423469461421103010299470836507229490718177625822972845024556897040292571751452383573549412451282884349017186147757238775308192484937929135306435242403555592741059466194258607967889051881221759976135386624406095324595765010\n+        data = 'short text'\n+        self.assertTrue(so.verify(data, short_text_sig, verify_old_sigs=True))\n+\n+        # verify a broken old signature\n+        broken_short_text_sig = short_text_sig + 1\n+        self.assertFalse(so.verify(data, broken_short_text_sig, verify_old_sigs=True))\n+\n+        long_data_sig = 991763198885165486007338893972384496025563436289154190056285376683148093829644985815692167116166669178171916463844829424162591848106824431299796818231239278958776853940831433819576852350691126984617641483209392489383319296267416823194661791079316704545017249491961092046751201670544843607206698682190381208022128216306635574292359600514603728560982584561531193227312370683851459162828981766836503134221347324867936277484738573153562229478151744446530191383660477390958159856842222437156763388859923477183453362567547792824054461704970820770533637185477922709297916275611571003099205429044820469679520819043851809079\n+        long_data = b'\\x01\\x02' * 5000\n+        self.assertTrue(so.verify(long_data, long_data_sig, verify_old_sigs=True))\ndiff --git a/tests/test_lib_subscriptions.py b/tests/test_lib_subscriptions.py\n--- a/tests/test_lib_subscriptions.py\n+++ b/tests/test_lib_subscriptions.py\n@@ -105,4 +105,22 @@ def test_03_check_subscription(self):\n         init_token({\"type\": \"spass\"}, user=User(\"nopw\", self.realm1))\n         # Now we have three users with tokens, subscription will fail\n         self.assertRaises(SubscriptionError, check_subscription,\n-                          \"demo_application\")\n\\ No newline at end of file\n+                          \"demo_application\")\n+\n+        # try to save some broken sunbscriptions\n+        sub1 = SUBSCRIPTION1.copy()\n+        sub1['date_from'] = '1234'\n+        with self.assertRaises(ValueError):\n+            save_subscription(sub1)\n+\n+        sub1 = SUBSCRIPTION1.copy()\n+        sub1['by_name'] = 'unknown vendor'\n+        with self.assertRaisesRegexp(SubscriptionError, 'Verifying the signature '\n+                                                        'of your subscription'):\n+            save_subscription(sub1)\n+\n+        sub1 = SUBSCRIPTION1.copy()\n+        sub1['signature'] = str(int(sub1['signature']) + 1)\n+        with self.assertRaisesRegexp(SubscriptionError, 'Signature of your '\n+                                                        'subscription does not'):\n+            save_subscription(sub1)\ndiff --git a/tests/testdata/audit.sqlite b/tests/testdata/audit.sqlite\nnew file mode 100644\nBinary files /dev/null and b/tests/testdata/audit.sqlite differ\n", "problem_statement": "", "hints_text": "", "created_at": "2019-03-07T13:35:50Z"}